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

@@ -3,9 +3,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
type SeedService = typeof import("./SeedService").default;
const dbMock = {
$queryRaw: vi.fn(async () => [{ marked: true }]),
user: {
findUnique: vi.fn(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}` })),
findUnique: vi.fn(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}`, active: true })),
create: vi.fn(),
update: vi.fn(async ({ where, data }: { where: { id: string }; data: { active: boolean } }) => ({ id: where.id, active: data.active })),
},
adminUser: {
findUnique: vi.fn(async () => ({ userId: "admin-id" })),
@@ -95,12 +97,37 @@ const dbMock = {
app: {
upsert: vi.fn(),
},
automationTemplate: {
findFirst: vi.fn(async () => null),
create: vi.fn(),
update: vi.fn(),
},
bookingPage: {
upsert: vi.fn(async ({ create }: { create: { slug: string; tenantId: string } }) => ({ id: `booking-page-${create.tenantId}-${create.slug}` })),
},
bookingPageProvider: {
upsert: vi.fn(),
},
availabilityRule: {
upsert: vi.fn(),
},
availabilityException: {
upsert: vi.fn(),
},
appointment: {
upsert: vi.fn(),
},
calendarEvent: {
upsert: vi.fn(),
deleteMany: vi.fn(),
},
};
const hashMock = vi.fn(async () => "hashed-password");
const genSaltMock = vi.fn(async () => "generated-salt");
const seedRolesAndPermissionsMock = vi.fn();
const seedStandardEntitlementsMock = vi.fn();
const seedStagingDomainDemoMock = vi.fn();
const originalEnv = { ...process.env };
const loggerInfo = vi.fn();
@@ -123,6 +150,7 @@ vi.mock("@hivegrid/db/seed.server", async () => {
vi.mock("~/utils/services/emailService", () => ({ getAvailableTenantInboundAddress: vi.fn(async () => "seed@example.test") }));
vi.mock("~/utils/services/rolesAndPermissionsService", () => ({ seedRolesAndPermissions: seedRolesAndPermissionsMock }));
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
vi.mock("./stagingDomainDemoSeed.server", () => ({ seedStagingDomainDemo: seedStagingDomainDemoMock }));
async function loadSeedService(): Promise<SeedService> {
vi.resetModules();
@@ -133,11 +161,21 @@ async function loadSeedService(): Promise<SeedService> {
describe("SeedService", () => {
beforeEach(() => {
vi.clearAllMocks();
dbMock.user.findUnique.mockImplementation(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}`, active: true }));
dbMock.user.update.mockImplementation(async ({ where, data }: { where: { id: string }; data: { active: boolean } }) => ({ id: where.id, active: data.active }));
process.env = { ...originalEnv };
delete process.env.SEED_ADMIN_EMAIL;
delete process.env.SEED_ADMIN_PASSWORD;
delete process.env.SEED_DEMO_DATA;
delete process.env.ALLOW_STAGING_DEMO_SEED;
delete process.env.SEED_DEMO_PRO_MANAGED;
delete process.env.LOCAL_DEV_CREDENTIALS;
// These unit cases exercise explicit seed environments. The dedicated
// local-credential contract suite covers the fail-closed CI branch.
delete process.env.CI;
delete process.env.SENTRY_ENVIRONMENT;
delete process.env.RLS_RUNTIME_MODE;
delete process.env.ADMIN_APP_HOST;
process.env.NODE_ENV = "test";
});
@@ -189,6 +227,87 @@ describe("SeedService", () => {
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("safe-production-password");
});
it("keeps the existing seed override path when the canonical local launcher flag is absent", async () => {
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-development-password";
const SeedService = await loadSeedService();
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "owner@example.com" } });
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
expect(hashMock).toHaveBeenCalledWith("safe-development-password", "generated-salt");
expect(dbMock.user.update).not.toHaveBeenCalled();
expect(dbMock.$queryRaw).not.toHaveBeenCalled();
});
it("restores canonical seed credentials only through the verified local launcher contract", async () => {
process.env.NODE_ENV = "development";
process.env.LOCAL_DEV_CREDENTIALS = "1";
process.env.DATABASE_URL = "postgresql://local:local@127.0.0.1:5432/hivegrid";
process.env.ADMIN_APP_HOST = "admin.localhost:3000";
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
dbMock.user.findUnique.mockResolvedValueOnce({ id: "local-admin", active: false } as never);
dbMock.user.update.mockResolvedValueOnce({ id: "local-admin", active: true } as never);
const SeedService = await loadSeedService();
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "owner@example.com" } });
expect(hashMock).toHaveBeenCalledWith("password", "generated-salt");
expect(dbMock.$queryRaw).toHaveBeenCalledOnce();
expect(dbMock.user.update).toHaveBeenCalledWith({
where: { id: "local-admin" },
data: { passwordHash: "hashed-password", active: true },
});
});
it("fails before seed work when the local launcher flag targets a remote database", async () => {
process.env.NODE_ENV = "development";
process.env.LOCAL_DEV_CREDENTIALS = "1";
process.env.DATABASE_URL = "postgresql://app:secret@staging-db:5432/hivegrid";
process.env.ADMIN_APP_HOST = "admin.localhost:3000";
const SeedService = await loadSeedService();
await expect(SeedService.seed()).rejects.toThrow("loopback PostgreSQL");
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
expect(dbMock.user.create).not.toHaveBeenCalled();
expect(hashMock).not.toHaveBeenCalled();
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
expect(dbMock.$queryRaw).not.toHaveBeenCalled();
});
it("fails before seed work when a loopback database lacks the disposable-local marker", async () => {
process.env.NODE_ENV = "development";
process.env.LOCAL_DEV_CREDENTIALS = "1";
process.env.DATABASE_URL = "postgresql://local:local@127.0.0.1:5432/hivegrid";
process.env.ADMIN_APP_HOST = "admin.localhost:3000";
dbMock.$queryRaw.mockResolvedValueOnce([{ marked: false }]);
const SeedService = await loadSeedService();
await expect(SeedService.seed()).rejects.toThrow("database marked as disposable local development data");
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
expect(dbMock.user.create).not.toHaveBeenCalled();
expect(hashMock).not.toHaveBeenCalled();
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
});
it("creates seed-managed users as active", async () => {
dbMock.user.findUnique.mockResolvedValueOnce(null as never);
dbMock.user.create.mockResolvedValueOnce({ id: "new-admin", active: true } as never);
const SeedService = await loadSeedService();
await SeedService.seed();
expect(dbMock.user.create).toHaveBeenCalledWith({
data: expect.objectContaining({ active: true }),
});
});
it("rejects blank admin credential overrides in production before DB writes", async () => {
process.env.NODE_ENV = "production";
process.env.SEED_ADMIN_EMAIL = "";
@@ -220,7 +339,7 @@ describe("SeedService", () => {
it("skips local demo users and tenants unless explicitly enabled", async () => {
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "log").mockImplementation(() => undefined);
await SeedService.seed();
@@ -237,7 +356,7 @@ describe("SeedService", () => {
it("seeds local demo users and tenants only when explicitly enabled outside production", async () => {
process.env.SEED_DEMO_DATA = "true";
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "log").mockImplementation(() => undefined);
await SeedService.seed();
@@ -268,12 +387,87 @@ describe("SeedService", () => {
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(6);
expect(seedStagingDomainDemoMock).toHaveBeenCalledOnce();
expect(seedStagingDomainDemoMock).toHaveBeenCalledWith({
tenantId: "tenant-demo-business-crm",
ownerUserId: "user-john.doe@company.com",
});
// AK-P16a/b: booking + calendar demo data per demo tenant (2 pages, 2
// providers each, Mo-Fr rules x 2 providers, 2 exceptions, 4 appointments,
// 3 internal mirrors + 1 external event; the cancelled appointment clears
// its mirror instead).
expect(dbMock.bookingPage.upsert).toHaveBeenCalledTimes(6);
expect(dbMock.bookingPageProvider.upsert).toHaveBeenCalledTimes(12);
expect(dbMock.availabilityRule.upsert).toHaveBeenCalledTimes(30);
expect(dbMock.availabilityException.upsert).toHaveBeenCalledTimes(6);
expect(dbMock.appointment.upsert).toHaveBeenCalledTimes(12);
expect(dbMock.calendarEvent.upsert).toHaveBeenCalledTimes(12);
expect(dbMock.calendarEvent.deleteMany).toHaveBeenCalledTimes(3);
expect(dbMock.bookingPage.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId_slug: { tenantId: "tenant-demo-starter-crm", slug: "beratungstermin" } },
create: expect.objectContaining({ isDemoData: true, isPublished: true }),
}),
);
expect(dbMock.appointment.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "seed-demo-starter-crm-appt-cancelled-consult" },
create: expect.objectContaining({ status: "cancelled", isDemoData: true, internalCalendarEventId: null }),
}),
);
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "seed.createDemoUsers", count: 2 }),
"Creating CRM SaaS demo users with tenants",
);
});
it("keeps the managed demo-pro tenant outside the legacy boot demo seed", async () => {
process.env.SEED_DEMO_DATA = "true";
process.env.SEED_DEMO_PRO_MANAGED = "true";
const SeedService = await loadSeedService();
vi.spyOn(console, "log").mockImplementation(() => undefined);
await SeedService.seed();
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-business-crm" } });
expect(dbMock.tenant.findUnique).not.toHaveBeenCalledWith(expect.objectContaining({ where: { slug: "demo-pro-crm" } }));
expect(dbMock.tenantUser.create).toHaveBeenCalledTimes(6);
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { billingProviderId: "hivegrid_entitlement_plan_starter" },
select: { id: true },
});
expect(dbMock.subscriptionProduct.findFirst).not.toHaveBeenCalledWith({
where: { billingProviderId: "hivegrid_entitlement_plan_pro" },
select: { id: true },
});
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { billingProviderId: "hivegrid_entitlement_plan_business" },
select: { id: true },
});
expect(dbMock.tenantSubscriptionProduct.create).toHaveBeenCalledTimes(2);
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(2);
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(2);
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(4);
expect(dbMock.bookingPage.upsert).toHaveBeenCalledTimes(4);
expect(dbMock.bookingPageProvider.upsert).toHaveBeenCalledTimes(8);
expect(dbMock.availabilityRule.upsert).toHaveBeenCalledTimes(20);
expect(dbMock.availabilityException.upsert).toHaveBeenCalledTimes(4);
expect(dbMock.appointment.upsert).toHaveBeenCalledTimes(8);
expect(dbMock.calendarEvent.upsert).toHaveBeenCalledTimes(8);
expect(dbMock.calendarEvent.deleteMany).toHaveBeenCalledTimes(2);
expect(seedStagingDomainDemoMock).toHaveBeenCalledOnce();
expect(seedStagingDomainDemoMock).toHaveBeenCalledWith({
tenantId: "tenant-demo-business-crm",
ownerUserId: "user-john.doe@company.com",
});
expect(seedRolesAndPermissionsMock).toHaveBeenCalledWith({
adminEmail: "admin@email.com",
diagnostics: expect.any(Function),
excludedTenantSlugs: ["demo-pro-crm"],
});
});
it("does not reassign a demo tenant plan after self-service checkout", async () => {
process.env.SEED_DEMO_DATA = "true";
dbMock.tenant.findUnique.mockImplementation(async ({ where, include }: { where: { slug: string }; include?: unknown }) => ({
@@ -329,14 +523,28 @@ describe("SeedService", () => {
process.env.ALLOW_STAGING_DEMO_SEED = "true";
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "log").mockImplementation(() => undefined);
const SeedService = await loadSeedService();
dbMock.user.findUnique
.mockResolvedValueOnce({ id: "admin-user", active: true } as never)
.mockResolvedValueOnce({ id: "demo-user-1", active: false } as never)
.mockResolvedValueOnce({ id: "demo-user-2", active: false } as never);
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalled();
expect(dbMock.user.update).toHaveBeenCalledTimes(2);
expect(dbMock.user.update).toHaveBeenCalledWith({
where: { id: "demo-user-1" },
data: { active: true },
});
expect(dbMock.user.update).toHaveBeenCalledWith({
where: { id: "demo-user-2" },
data: { active: true },
});
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "db-seed", phase: "start", nodeEnv: "staging-demo" }),
"DB seed event",
@@ -371,6 +579,8 @@ describe("SeedService", () => {
expect(seedStandardEntitlementsMock).toHaveBeenCalledOnce();
expect(seedStandardEntitlementsMock).toHaveBeenCalledWith({
client: dbMock,
includeCustomerPortalCommercialProducts: true,
includeEmailMarketingCommercialProducts: true,
diagnostics: expect.any(Function),
});
expect(calls).toEqual(["roles", "entitlements"]);
@@ -415,7 +625,7 @@ describe("SeedService", () => {
it("logs redacted roles and permissions seed diagnostics from the helper", async () => {
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "log").mockImplementation(() => undefined);
seedRolesAndPermissionsMock.mockImplementation(async ({ diagnostics }) => {
await diagnostics?.({
phase: "success",
@@ -453,7 +663,7 @@ describe("SeedService", () => {
it("logs redacted entitlements seed diagnostics from the helper", async () => {
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "log").mockImplementation(() => undefined);
seedStandardEntitlementsMock.mockImplementation(async ({ diagnostics }) => {
await diagnostics?.({
phase: "failure",
@@ -12,6 +12,15 @@ import { seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent }
import { db } from "~/utils/db.server";
import { seedShkCustomFieldTemplate } from "~/utils/integrations/crm/customFieldService.server";
import { createScopedLogger } from "~/utils/logger.server";
import {
assertLocalCredentialsDatabaseMarker,
assertLocalCredentialsEnvironment,
} from "./localCredentialsEnvironment.server";
import { seedStagingDomainDemo } from "./stagingDomainDemoSeed.server";
import {
automationTemplateCatalog,
automationTemplateFlowData,
} from "~/services/automation/automation.registry";
const seedLogger = createScopedLogger("seed");
@@ -32,6 +41,7 @@ const localDemoSeedUsers = [
lastName: "Doe",
email: "john.doe@company.com",
password: "password",
reactivateExisting: true,
},
{
userType: "app" as const,
@@ -39,6 +49,7 @@ const localDemoSeedUsers = [
lastName: "Davis",
email: "luna.davis@company.com",
password: "password",
reactivateExisting: true,
},
];
const demoCrmTenants = [
@@ -46,6 +57,7 @@ const demoCrmTenants = [
{ slug: "demo-pro-crm", name: "Demo Pro CRM", planId: entitlementPlanIds.pro },
{ slug: "demo-business-crm", name: "Demo Business CRM", planId: entitlementPlanIds.business },
] as const;
const managedDemoProTenantSlug = "demo-pro-crm";
const demoTenantRoleSeeds = [
{
name: "CRM Manager",
@@ -68,7 +80,94 @@ const demoSupportTicketSubjects = {
const demoSupportTicketPlanGatesMessage =
"Use this ticket to confirm blueprint, plan, tenant override, and tenant-owned role access in the seeded workspace.";
function getAdminSeedUser() {
// AK-P16a/AK-P16b: booking + calendar demo data for the demo tenants so
// /bookings, /bookings/pages, /availability and /calendar are populated out of
// the box. The rich local demo seed (scripts/seed-hivegrid-demo.ts) refuses to
// run with NODE_ENV=production, so the staging demo path lives here.
// Deterministic `seed-<tenant>-*` ids keep every upsert idempotent across
// SEED_ON_BOOT runs; day offsets are re-resolved on each run so "upcoming"
// appointments stay upcoming.
const demoBookingTimezone = "Europe/Berlin";
const demoBookingPageSeeds = [
{
slug: "beratungstermin",
title: "Beratungstermin", // demo seed copy
description: "Kostenloses Erstgespräch für neue Anfragen (Demo).",
durationMinutes: 30,
isPublished: true,
},
{
slug: "vor-ort-termin",
title: "Vor-Ort-Termin", // demo seed copy
description: "Termin beim Endkunden vor Ort (Demo, unveröffentlicht).",
durationMinutes: 60,
isPublished: false,
},
] as const;
const demoAppointmentSeeds = [
{
key: "upcoming-consult",
pageSlug: "beratungstermin",
providerIndex: 0,
dayOffset: 2,
startHour: 10,
status: "scheduled",
intakeAnswers: { vorname: "Sabine", nachname: "Wagner", email: "sabine.wagner@example.test", anliegen: "Bad-Sanierung besprechen." },
},
{
key: "upcoming-onsite",
pageSlug: "vor-ort-termin",
providerIndex: 1,
dayOffset: 5,
startHour: 8,
status: "scheduled",
intakeAnswers: { vorname: "Thomas", nachname: "Schneider", email: "thomas.schneider@example.test", anliegen: "Heizungstausch vor Ort ansehen." },
},
{
key: "past-held",
pageSlug: "beratungstermin",
providerIndex: 0,
dayOffset: -3,
startHour: 14,
status: "held",
intakeAnswers: { vorname: "Birgit", nachname: "Sommer", email: "birgit.sommer@example.test", anliegen: "Jahreswartung planen." },
},
{
key: "cancelled-consult",
pageSlug: "beratungstermin",
providerIndex: 1,
dayOffset: -1,
startHour: 9,
status: "cancelled",
intakeAnswers: { vorname: "Peter", nachname: "Krause", email: "peter.krause@example.test", anliegen: "Terminanfrage (storniert)." },
},
] as const;
const demoAvailabilityWeekdays = ["monday", "tuesday", "wednesday", "thursday", "friday"] as const;
const demoAvailabilityExceptionSeeds = [
{ key: "day-off", providerIndex: 0, dayOffset: 7, kind: "unavailable", startTime: null, endTime: null, reason: "Urlaubstag (Demo)" },
{ key: "short-day", providerIndex: 1, dayOffset: 3, kind: "custom_window", startTime: "10:00", endTime: "14:00", reason: "Verkürzter Tag (Demo)" },
] as const;
async function useCanonicalLocalCredentials() {
if (process.env.LOCAL_DEV_CREDENTIALS !== "1") {
return false;
}
assertLocalCredentialsEnvironment(process.env);
await assertLocalCredentialsDatabaseMarker(db);
return true;
}
function getAdminSeedUser(canonicalLocalCredentials: boolean) {
if (canonicalLocalCredentials) {
return {
email: DEFAULT_ADMIN_EMAIL,
password: DEFAULT_ADMIN_PASSWORD,
firstName: "Admin",
lastName: "User",
};
}
return {
email: process.env.SEED_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL,
password: process.env.SEED_ADMIN_PASSWORD ?? DEFAULT_ADMIN_PASSWORD,
@@ -78,8 +177,10 @@ function getAdminSeedUser() {
}
async function seed() {
const adminUser = getAdminSeedUser();
const canonicalLocalCredentials = await useCanonicalLocalCredentials();
const adminUser = getAdminSeedUser(canonicalLocalCredentials);
const shouldSeedDemoData = shouldSeedCrmDemoData();
const bootSeedDemoCrmTenants = getBootSeedDemoCrmTenants();
const seedCredentials = shouldSeedDemoData
? [
{ label: "admin", email: adminUser.email, password: adminUser.password },
@@ -94,16 +195,16 @@ async function seed() {
seedCredentials,
diagnostics: logDbSeedDiagnostic,
seed: async () => {
const admin = await createUser({ userType: "admin", ...adminUser });
const admin = await createUser({ userType: "admin", canonicalLocalCredentials, ...adminUser });
let demoUsers: Awaited<ReturnType<typeof createUser>>[] = [];
if (shouldSeedDemoData) {
seedLogger.info({ op: "seed.createDemoUsers", count: localDemoSeedUsers.length }, "Creating CRM SaaS demo users with tenants");
demoUsers = await Promise.all(localDemoSeedUsers.map((user) => createUser(user)));
demoUsers = await Promise.all(localDemoSeedUsers.map((user) => createUser({ ...user, canonicalLocalCredentials })));
const [user1, user2] = demoUsers;
await Promise.all(
demoCrmTenants.map((tenant, index) =>
bootSeedDemoCrmTenants.map((tenant, index) =>
createTenant(tenant.slug, tenant.name, [
{ ...admin, type: TenantUserType.ADMIN },
{ ...user1, type: index === 0 ? TenantUserType.ADMIN : TenantUserType.OWNER },
@@ -117,25 +218,40 @@ async function seed() {
await seedRolesAndPermissions({
adminEmail: adminUser.email,
diagnostics: logRolesAndPermissionsSeedDiagnostic,
...(process.env.SEED_DEMO_PRO_MANAGED === "true" ? { excludedTenantSlugs: [managedDemoProTenantSlug] } : {}),
});
await seedStandardEntitlements({
client: db,
includeCustomerPortalCommercialProducts: true,
includeEmailMarketingCommercialProducts: true,
diagnostics: logEntitlementsSeedDiagnostic,
});
// R-P5: global App definition table from the code catalog (idempotent by
// unique key; the tenant runtime keeps reading INTEGRATION_CATALOG).
await seedIntegrationCatalog();
await seedAutomationTemplateCatalog();
if (shouldSeedDemoData) {
await Promise.all(demoCrmTenants.map((tenant) => assignTenantPlan(tenant.slug, tenant.planId)));
await Promise.all(demoCrmTenants.map((tenant) => seedDemoProductCoreTenant(tenant.slug, tenant.planId, demoUsers)));
await Promise.all(bootSeedDemoCrmTenants.map((tenant) => assignTenantPlan(tenant.slug, tenant.planId)));
await Promise.all(bootSeedDemoCrmTenants.map((tenant) => seedDemoProductCoreTenant(tenant.slug, tenant.planId, demoUsers)));
}
},
});
}
function getBootSeedDemoCrmTenants() {
if (process.env.SEED_DEMO_PRO_MANAGED !== "true") {
return demoCrmTenants;
}
// The comprehensive staging seed owns every tenant-scoped row in demo-pro-crm.
// Excluding it here keeps later web boots from reintroducing legacy members,
// plans, bookings, projects, or other product-core fixtures.
return demoCrmTenants.filter((tenant) => tenant.slug !== managedDemoProTenantSlug);
}
/** Upsert the code catalog into the global `App` table (R-P5, no RLS/tenant). */
async function seedIntegrationCatalog() {
const plan = buildCatalogSeedPlan();
@@ -148,6 +264,38 @@ async function seedIntegrationCatalog() {
seedLogger.info({ op: "seed.integrationCatalog", count: plan.length }, "Upserted integration catalog into App table");
}
/** Seed global templates through the privileged deployment seed, never a tenant request. */
async function seedAutomationTemplateCatalog() {
for (const template of automationTemplateCatalog) {
const flowData = JSON.parse(JSON.stringify(automationTemplateFlowData(template))) as object;
// Matching the old key-shaped name too heals rows that were seeded before
// display text replaced the translation key.
const existing = await db.automationTemplate.findFirst({
where: { tenantId: null, name: { in: [template.defaultName, template.nameKey] }, archivedAt: null },
select: { id: true },
});
const data = {
name: template.defaultName,
description: template.defaultDescription,
category: template.category,
flowData,
isPublished: true,
isDemoData: true,
};
if (existing) {
await db.automationTemplate.update({ where: { id: existing.id }, data });
} else {
await db.automationTemplate.create({
data: { tenantId: null, ...data },
});
}
}
seedLogger.info(
{ op: "seed.automationTemplateCatalog", count: automationTemplateCatalog.length },
"Upserted global automation template catalog",
);
}
function shouldSeedCrmDemoData() {
if (process.env.SEED_DEMO_DATA !== "true") {
return false;
@@ -229,12 +377,16 @@ async function createUser({
email,
password,
userType,
reactivateExisting = false,
canonicalLocalCredentials = false,
}: {
firstName: string;
lastName: string;
email: string;
password: string;
userType: "admin" | "app";
reactivateExisting?: boolean;
canonicalLocalCredentials?: boolean;
}) {
// Never log raw `email` (PII) and never log `password` (secret).
// Use email fingerprint hash so operators can still correlate seed events.
@@ -248,7 +400,24 @@ async function createUser({
where: { email },
});
if (user) {
const isAdmin = await db.adminUser.findUnique({ where: { userId: user.id } });
if (canonicalLocalCredentials) {
user = await db.user.update({
where: { id: user.id },
data: {
passwordHash,
...(userType === "admin" || reactivateExisting ? { active: true } : {}),
},
});
}
// Only explicitly managed demo identities opt into reactivation. Existing
// admin or customer accounts may have been disabled intentionally.
if (!canonicalLocalCredentials && reactivateExisting && user.active === false) {
user = await db.user.update({
where: { id: user.id },
data: { active: true },
});
}
const isAdmin = await db.adminUser.findUnique({ where: { id: user.id } });
if (!isAdmin && userType === "admin") {
if (process.env.NODE_ENV === "production") {
throw new Error("Production seed refused to promote an existing non-admin user. Choose a new SEED_ADMIN_EMAIL or bootstrap the admin user explicitly.");
@@ -257,7 +426,15 @@ async function createUser({
{ op: "seed.promoteUserToAdmin", emailFingerprint: emailFingerprint(email) },
"User already exists; promoting to admin",
);
await db.adminUser.create({ data: { userId: user.id } });
await db.adminUser.create({
data: {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
status: "active",
},
});
} else {
seedLogger.info(
{ op: "seed.userExists", userType, emailFingerprint: emailFingerprint(email) },
@@ -274,11 +451,18 @@ async function createUser({
firstName,
lastName,
phone: "",
active: true,
},
});
if (userType === "admin") {
await db.adminUser.create({
data: { userId: user.id },
data: {
id: user.id,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
status: "active",
},
});
}
return user;
@@ -426,10 +610,162 @@ async function seedDemoProductCoreTenant(tenantSlug: string, planId: Entitlement
// data (`isDemoData = true`) instead of the legacy entity-builder CRM
// entities. The template is intentionally empty until the Geerkens
// workshop (E3), so this is currently an idempotent no-op.
seedShkCustomFieldTemplate({ tenantId: tenant.id }),
seedShkCustomFieldTemplate({ tenantId: tenant.id, isDemoData: true }),
planId === entitlementPlanIds.business && demoUsers[0]
? seedStagingDomainDemo({ tenantId: tenant.id, ownerUserId: demoUsers[0].id })
: Promise.resolve(),
seedDemoTenantBookingData(tenant.id, tenant.slug, demoUsers),
]);
}
/** Local wall-clock date `dayOffset` days from now (mirrors the local demo seed). */
function demoBookingDate(dayOffset: number, hour: number, minute = 0): Date {
const value = new Date();
value.setDate(value.getDate() + dayOffset);
value.setHours(hour, minute, 0, 0);
return value;
}
/** Calendar-date-only value at UTC midnight (AvailabilityException stores `@db.Date`). */
function demoBookingDateOnlyUtc(dayOffset: number): Date {
const value = new Date();
value.setDate(value.getDate() + dayOffset);
return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
}
async function seedDemoTenantBookingData(tenantId: string, tenantSlug: string, demoUsers: { id: string }[]) {
const providers = demoUsers.slice(0, 2);
if (providers.length === 0) {
return;
}
// Booking pages + provider assignments (unique per tenantId+slug).
const pageBySlug = new Map<string, { id: string; durationMinutes: number }>();
for (const page of demoBookingPageSeeds) {
const data = {
title: page.title,
description: page.description,
durationMinutes: page.durationMinutes,
confirmationEmailSubject: `Terminbestätigung: ${page.title}`,
confirmationEmailBody: "Vielen Dank für deine Buchung. Die Termindetails findest du im Kalenderanhang (.ics).",
isPublished: page.isPublished,
isDemoData: true,
createdByUserId: providers[0].id,
};
const row = await db.bookingPage.upsert({
where: { tenantId_slug: { tenantId, slug: page.slug } },
create: { tenantId, slug: page.slug, ...data },
update: data,
select: { id: true },
});
pageBySlug.set(page.slug, { id: row.id, durationMinutes: page.durationMinutes });
for (const [index, provider] of providers.entries()) {
await db.bookingPageProvider.upsert({
where: { bookingPageId_providerUserId: { bookingPageId: row.id, providerUserId: provider.id } },
create: { tenantId, bookingPageId: row.id, providerUserId: provider.id, displayOrder: index, isActive: true },
update: { displayOrder: index, isActive: true },
});
}
}
// Weekly Mo–Fr availability per provider so the public slot engine and the
// /availability editor have data. AvailabilityRule has no natural unique key,
// so deterministic ids keep the upserts idempotent.
for (const [providerIndex, provider] of providers.entries()) {
for (const day of demoAvailabilityWeekdays) {
const id = `seed-${tenantSlug}-avail-${providerIndex}-${day}`;
const data = { tenantId, providerUserId: provider.id, dayOfWeek: day, startTime: "09:00", endTime: "17:00", timezone: demoBookingTimezone };
await db.availabilityRule.upsert({ where: { id }, create: { id, ...data }, update: data });
}
}
for (const exception of demoAvailabilityExceptionSeeds) {
const provider = providers[exception.providerIndex % providers.length];
const id = `seed-${tenantSlug}-exception-${exception.key}`;
const data = {
tenantId,
providerUserId: provider.id,
date: demoBookingDateOnlyUtc(exception.dayOffset),
kind: exception.kind,
startTime: exception.startTime,
endTime: exception.endTime,
reason: exception.reason,
timezone: demoBookingTimezone,
};
await db.availabilityException.upsert({ where: { id }, create: { id, ...data }, update: data });
}
// Appointments across the list tabs (upcoming/past/cancelled) + a local
// CalendarEvent mirror per active appointment so /calendar shows sources
// (mirrors what BookingSubmitService does on a real booking).
for (const appointment of demoAppointmentSeeds) {
const page = pageBySlug.get(appointment.pageSlug);
const provider = providers[appointment.providerIndex % providers.length];
if (!page) {
continue;
}
const appointmentId = `seed-${tenantSlug}-appt-${appointment.key}`;
const calendarEventId = `seed-${tenantSlug}-cal-${appointment.key}`;
const startAt = demoBookingDate(appointment.dayOffset, appointment.startHour);
const endAt = new Date(startAt.getTime() + page.durationMinutes * 60_000);
const cancelled = appointment.status === "cancelled";
if (cancelled) {
// Real cancels remove the availability-blocking mirror — keep parity.
await db.calendarEvent.deleteMany({ where: { id: calendarEventId } });
} else {
const eventData = {
tenantId,
userId: provider.id,
source: "hivegrid_internal" as const,
title: `${demoBookingPageSeeds.find((p) => p.slug === appointment.pageSlug)?.title ?? "Buchung"} (Demo)`,
startsAt: startAt,
endsAt: endAt,
timeZone: demoBookingTimezone,
isBusyForAvailability: true,
internalEntityLink: { type: "appointment", id: appointmentId },
isDemoData: true,
};
await db.calendarEvent.upsert({ where: { id: calendarEventId }, create: { id: calendarEventId, ...eventData }, update: eventData });
}
const data = {
tenantId,
bookingPageId: page.id,
providerUserId: provider.id,
startAt,
endAt,
timezone: demoBookingTimezone,
status: appointment.status,
intakeAnswers: { ...appointment.intakeAnswers },
internalCalendarEventId: cancelled ? null : calendarEventId,
cancelledAt: cancelled ? demoBookingDate(appointment.dayOffset - 1, 12) : null,
cancelledByKind: cancelled ? ("customer" as const) : null,
cancellationReason: cancelled ? "Vom Endkunden storniert (Demo)." : null,
isDemoData: true,
};
await db.appointment.upsert({ where: { id: appointmentId }, create: { id: appointmentId, ...data }, update: data });
}
// One external busy block per tenant so the calendar grid shows both source
// markers (internal + external) without a live Google connection.
const externalEventId = `seed-${tenantSlug}-cal-external`;
const externalStartsAt = demoBookingDate(1, 12);
const externalData = {
tenantId,
userId: providers[0].id,
source: "external_synced" as const,
title: "Externer Termin (Demo)",
startsAt: externalStartsAt,
endsAt: new Date(externalStartsAt.getTime() + 90 * 60_000),
timeZone: demoBookingTimezone,
isBusyForAvailability: true,
isDemoData: true,
};
await db.calendarEvent.upsert({ where: { id: externalEventId }, create: { id: externalEventId, ...externalData }, update: externalData });
}
async function seedDemoTenantProductConfiguration(tenantId: string, planId: EntitlementPlanId) {
await db.tenantProductConfiguration.upsert({
where: { tenantId },
@@ -0,0 +1,221 @@
import { describe, expect, it, vi } from "vitest";
import { LOCAL_ADMIN_EMAIL, LOCAL_ADMIN_PASSWORD, ensureLocalCredentials, type LocalCredentialsClient } from "./localCredentials.server";
import { assertLocalCredentialsEnvironment } from "./localCredentialsEnvironment.server";
const localEnv = {
LOCAL_DEV_CREDENTIALS: "1",
NODE_ENV: "development",
DATABASE_URL: "postgresql://local:local@127.0.0.1:55432/hivegrid_local",
ADMIN_APP_HOST: "admin.localhost:3000",
};
describe("assertLocalCredentialsEnvironment", () => {
it("accepts only the canonical local launcher with a loopback PostgreSQL database", () => {
expect(assertLocalCredentialsEnvironment(localEnv).hostname).toBe("127.0.0.1");
expect(assertLocalCredentialsEnvironment({ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid" }).hostname).toBe("localhost");
});
it.each([
[{ ...localEnv, LOCAL_DEV_CREDENTIALS: undefined }, "canonical local launcher"],
[{ ...localEnv, NODE_ENV: "production" }, "NODE_ENV=development"],
[{ ...localEnv, CI: "true" }, "disabled in CI"],
[{ ...localEnv, SENTRY_ENVIRONMENT: "staging" }, "deployed Sentry environments"],
[{ ...localEnv, SENTRY_ENVIRONMENT: "canary" }, "deployed Sentry environments"],
[{ ...localEnv, SENTRY_ENVIRONMENT: "preview" }, "deployed Sentry environments"],
[{ ...localEnv, SENTRY_ENVIRONMENT: "prod" }, "deployed Sentry environments"],
[{ ...localEnv, RLS_RUNTIME_MODE: "required" }, "RLS runtime mode"],
[{ ...localEnv, ADMIN_APP_HOST: undefined }, "admin.localhost"],
[{ ...localEnv, ADMIN_APP_HOST: "admin.hivegrid.de" }, "admin.localhost"],
[{ ...localEnv, ADMIN_APP_HOST: "admin.localhost.evil" }, "admin.localhost"],
[{ ...localEnv, DATABASE_URL: "postgresql://app:secret@staging-db:5432/hivegrid" }, "loopback PostgreSQL"],
[{ ...localEnv, DATABASE_URL: "not-a-url" }, "valid DATABASE_URL"],
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?host=remote-db" }, "connection query parameters"],
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?HOSTADDR=203.0.113.10" }, "connection query parameters"],
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?host=%2Fvar%2Frun%2Fpostgresql" }, "connection query parameters"],
[{ ...localEnv, DATABASE_URL: "postgresql://local:local@localhost:5432/hivegrid?SeRvIcE=production" }, "connection query parameters"],
])("rejects unsafe environment %#", (env, message) => {
expect(() => assertLocalCredentialsEnvironment(env)).toThrow(message);
});
});
describe("ensureLocalCredentials", () => {
it("upserts the canonical platform admin and normalizes every password-backed local identity", async () => {
const transaction = {
user: {
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
updateMany: vi.fn().mockResolvedValue({ count: 51 }),
},
portalUser: {
updateMany: vi.fn().mockResolvedValue({ count: 3 }),
},
adminUser: {
updateMany: vi.fn().mockResolvedValue({ count: 2 }),
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
},
adminRole: {
findUnique: vi.fn().mockResolvedValue({ id: "super-admin-role" }),
},
adminUserRole: {
deleteMany: vi.fn().mockResolvedValue({ count: 2 }),
create: vi.fn().mockResolvedValue({ id: "admin-user-role" }),
},
};
const client = {
$queryRaw: vi.fn().mockResolvedValue([{ marked: true }]),
$transaction: vi.fn(async (callback) => callback(transaction as never)),
} as unknown as LocalCredentialsClient;
const hashPassword = vi.fn().mockResolvedValue("argon2-hash");
const syncPermissions = vi.fn().mockResolvedValue(undefined);
const syncAdminPermissions = vi.fn().mockResolvedValue(undefined);
await expect(ensureLocalCredentials({ client, env: localEnv, hashPassword, syncPermissions, syncAdminPermissions })).resolves.toEqual({
adminUserId: "admin-user",
normalizedPasswordIdentityCount: 54,
});
expect(client.$queryRaw).toHaveBeenCalledOnce();
expect(hashPassword).toHaveBeenCalledWith(LOCAL_ADMIN_PASSWORD);
expect(syncPermissions).toHaveBeenCalledOnce();
expect(syncAdminPermissions).toHaveBeenCalledOnce();
expect(transaction.user.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { email: LOCAL_ADMIN_EMAIL },
create: expect.objectContaining({ email: LOCAL_ADMIN_EMAIL, passwordHash: "argon2-hash", active: true }),
update: expect.objectContaining({ passwordHash: "argon2-hash", active: true, totpEnabledAt: null }),
})
);
expect(transaction.adminUser.updateMany).toHaveBeenCalledWith({
where: { email: { not: LOCAL_ADMIN_EMAIL }, status: "active" },
data: expect.objectContaining({ status: "disabled" }),
});
expect(transaction.adminUser.upsert).toHaveBeenCalledWith({
where: { email: LOCAL_ADMIN_EMAIL },
create: expect.objectContaining({ id: "admin-user", email: LOCAL_ADMIN_EMAIL, status: "active" }),
update: expect.objectContaining({ status: "active", disabledAt: null, disabledReason: null }),
select: { id: true },
});
expect(transaction.adminRole.findUnique).toHaveBeenCalledWith({
where: { systemKey: "super_admin" },
select: { id: true },
});
expect(transaction.adminUserRole.deleteMany).toHaveBeenCalledWith({
where: { adminUserId: "admin-user" },
});
expect(transaction.adminUserRole.create).toHaveBeenCalledWith({
data: { adminUserId: "admin-user", adminRoleId: "super-admin-role", grantedByAdminUserId: "admin-user" },
});
expect(transaction.user.updateMany).toHaveBeenCalledWith({
where: { passwordHash: { not: null } },
data: { passwordHash: "argon2-hash" },
});
expect(transaction.portalUser.updateMany).toHaveBeenCalledWith({
where: { passwordHash: { not: null } },
data: { passwordHash: "argon2-hash" },
});
});
it("fails before hashing or opening a transaction outside the local contract", async () => {
const client = { $queryRaw: vi.fn(), $transaction: vi.fn() } as unknown as LocalCredentialsClient;
const hashPassword = vi.fn();
const syncPermissions = vi.fn();
await expect(
ensureLocalCredentials({
client,
env: { ...localEnv, DATABASE_URL: "postgresql://app:secret@staging-db:5432/hivegrid" },
hashPassword,
syncPermissions,
})
).rejects.toThrow("loopback PostgreSQL");
expect(hashPassword).not.toHaveBeenCalled();
expect(syncPermissions).not.toHaveBeenCalled();
expect(client.$queryRaw).not.toHaveBeenCalled();
expect(client.$transaction).not.toHaveBeenCalled();
});
it("fails before hashing, permission sync, or writes when the database lacks the disposable-local marker", async () => {
const client = {
$queryRaw: vi.fn().mockResolvedValue([{ marked: false }]),
$transaction: vi.fn(),
} as unknown as LocalCredentialsClient;
const hashPassword = vi.fn();
const syncPermissions = vi.fn();
await expect(ensureLocalCredentials({ client, env: localEnv, hashPassword, syncPermissions })).rejects.toThrow(
"database marked as disposable local development data"
);
expect(hashPassword).not.toHaveBeenCalled();
expect(syncPermissions).not.toHaveBeenCalled();
expect(client.$transaction).not.toHaveBeenCalled();
});
it("fails closed when the canonical admin role is unavailable after permission sync", async () => {
const transaction = {
user: {
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
updateMany: vi.fn(),
},
portalUser: { updateMany: vi.fn() },
adminUser: { updateMany: vi.fn(), upsert: vi.fn().mockResolvedValue({ id: "admin-user" }) },
adminRole: { findUnique: vi.fn().mockResolvedValue(null) },
adminUserRole: { deleteMany: vi.fn(), create: vi.fn() },
};
const client = {
$queryRaw: vi.fn().mockResolvedValue([{ marked: true }]),
$transaction: vi.fn(async (callback) => callback(transaction as never)),
} as unknown as LocalCredentialsClient;
await expect(
ensureLocalCredentials({
client,
env: localEnv,
hashPassword: vi.fn().mockResolvedValue("argon2-hash"),
syncPermissions: vi.fn().mockResolvedValue(undefined),
syncAdminPermissions: vi.fn().mockResolvedValue(undefined),
})
).rejects.toThrow("canonical SuperAdmin role");
expect(transaction.adminUserRole.deleteMany).not.toHaveBeenCalled();
expect(transaction.adminUserRole.create).not.toHaveBeenCalled();
expect(transaction.user.updateMany).not.toHaveBeenCalled();
expect(transaction.portalUser.updateMany).not.toHaveBeenCalled();
});
it("keeps exactly one canonical SuperAdmin assignment across repeated local starts", async () => {
const transaction = {
user: {
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
},
portalUser: { updateMany: vi.fn().mockResolvedValue({ count: 0 }) },
adminUser: {
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
upsert: vi.fn().mockResolvedValue({ id: "admin-user" }),
},
adminRole: { findUnique: vi.fn().mockResolvedValue({ id: "super-admin-role" }) },
adminUserRole: {
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
create: vi.fn().mockResolvedValue({ id: "admin-user-role" }),
},
};
const client = {
$queryRaw: vi.fn().mockResolvedValue([{ marked: true }]),
$transaction: vi.fn(async (callback) => callback(transaction as never)),
} as unknown as LocalCredentialsClient;
const options = {
client,
env: localEnv,
hashPassword: vi.fn().mockResolvedValue("argon2-hash"),
syncPermissions: vi.fn().mockResolvedValue(undefined),
syncAdminPermissions: vi.fn().mockResolvedValue(undefined),
};
await ensureLocalCredentials(options);
await ensureLocalCredentials(options);
expect(transaction.adminUserRole.deleteMany).toHaveBeenCalledTimes(2);
expect(transaction.adminUserRole.create).toHaveBeenCalledTimes(2);
expect(transaction.adminUserRole.create).toHaveBeenLastCalledWith({
data: { adminUserId: "admin-user", adminRoleId: "super-admin-role", grantedByAdminUserId: "admin-user" },
});
});
});
@@ -0,0 +1,141 @@
import type { DbClient } from "@hivegrid/db/client.server";
import { syncDefaultRolesAndPermissions } from "@hivegrid/db/permissions-seed.server";
import { syncAdminRoleCatalog } from "@hivegrid/db/admin-rbac.server";
import argon2 from "argon2";
import {
assertLocalCredentialsDatabaseMarker,
assertLocalCredentialsEnvironment,
type LocalCredentialsEnvironment,
} from "./localCredentialsEnvironment.server";
export const LOCAL_ADMIN_EMAIL = "admin@email.com";
export const LOCAL_ADMIN_PASSWORD = "password";
export type LocalCredentialsClient = Pick<DbClient, "$queryRaw" | "$transaction">;
export type LocalCredentialsResult = {
adminUserId: string;
normalizedPasswordIdentityCount: number;
};
export async function ensureLocalCredentials({
client,
env = process.env,
hashPassword = hashLocalPassword,
syncPermissions = async () => {
await syncDefaultRolesAndPermissions({ client: client as DbClient });
},
syncAdminPermissions = async () => {
await syncAdminRoleCatalog(client as DbClient);
},
}: {
client: LocalCredentialsClient;
env?: LocalCredentialsEnvironment;
hashPassword?: (password: string) => Promise<string>;
syncPermissions?: () => Promise<void>;
syncAdminPermissions?: () => Promise<void>;
}): Promise<LocalCredentialsResult> {
assertLocalCredentialsEnvironment(env);
await assertLocalCredentialsDatabaseMarker(client);
const passwordHash = await hashPassword(LOCAL_ADMIN_PASSWORD);
await syncPermissions();
await syncAdminPermissions();
return client.$transaction(async (transaction) => {
const admin = await transaction.user.upsert({
where: { email: LOCAL_ADMIN_EMAIL },
create: {
email: LOCAL_ADMIN_EMAIL,
passwordHash,
firstName: "Admin",
lastName: "User",
avatar: "",
phone: "",
active: true,
},
update: {
passwordHash,
active: true,
pendingDeletion: false,
scheduledDeletionAt: null,
deletionRequestedAt: null,
pseudonymized: false,
pseudonymizedAt: null,
deletionRequestId: null,
totpSecretEncrypted: null,
totpPendingSecretEncrypted: null,
totpEnabledAt: null,
totpPendingCreatedAt: null,
},
select: { id: true },
});
await transaction.adminUser.updateMany({
where: { email: { not: LOCAL_ADMIN_EMAIL }, status: "active" },
data: {
status: "disabled",
disabledAt: new Date(),
disabledReason: "Local canonical admin normalization",
},
});
const adminIdentity = await transaction.adminUser.upsert({
where: { email: LOCAL_ADMIN_EMAIL },
create: {
id: admin.id,
email: LOCAL_ADMIN_EMAIL,
firstName: "Admin",
lastName: "User",
status: "active",
authentikGroups: [],
},
update: {
firstName: "Admin",
lastName: "User",
status: "active",
disabledAt: null,
disabledReason: null,
},
select: { id: true },
});
const adminRole = await transaction.adminRole.findUnique({
where: { systemKey: "super_admin" },
select: { id: true },
});
if (!adminRole) {
throw new Error("Local credential setup could not resolve the canonical SuperAdmin role.");
}
// Delete and recreate so this remains idempotent even after `prisma db push`,
// where migration-only partial unique indexes may not exist yet.
await transaction.adminUserRole.deleteMany({
where: { adminUserId: adminIdentity.id },
});
await transaction.adminUserRole.create({
data: { adminUserId: adminIdentity.id, adminRoleId: adminRole.id, grantedByAdminUserId: adminIdentity.id },
});
const normalizedUsers = await transaction.user.updateMany({
where: { passwordHash: { not: null } },
data: { passwordHash },
});
const normalizedPortalUsers = await transaction.portalUser.updateMany({
where: { passwordHash: { not: null } },
data: { passwordHash },
});
return {
adminUserId: adminIdentity.id,
normalizedPasswordIdentityCount: normalizedUsers.count + normalizedPortalUsers.count,
};
});
}
async function hashLocalPassword(password: string): Promise<string> {
return argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 19_456,
timeCost: 2,
parallelism: 1,
});
}
@@ -0,0 +1,77 @@
import type { DbClient } from "@hivegrid/db/client.server";
export type LocalCredentialsEnvironment = {
ADMIN_APP_HOST?: string;
CI?: string;
DATABASE_URL?: string;
LOCAL_DEV_CREDENTIALS?: string;
NODE_ENV?: string;
RLS_RUNTIME_MODE?: string;
SENTRY_ENVIRONMENT?: string;
};
const LOCAL_DATABASE_HOSTS = new Set(["127.0.0.1", "[::1]", "localhost"]);
const LOCAL_ADMIN_HOST_PATTERN = /^admin\.localhost(?::\d+)?$/i;
const LOCAL_DATABASE_MARKER = "app.local_dev_credentials";
const LOCAL_DATABASE_MARKER_VALUE = "enabled";
/**
* Local credential normalization requires independent process, URL, and
* database-side proof. A loopback SSH tunnel must never be sufficient.
*/
export function assertLocalCredentialsEnvironment(env: LocalCredentialsEnvironment = process.env): URL {
if (env.LOCAL_DEV_CREDENTIALS !== "1") {
throw new Error("Local credential normalization requires the canonical local launcher.");
}
if (env.NODE_ENV !== "development") {
throw new Error("Local credential normalization requires NODE_ENV=development.");
}
if (env.CI?.trim()) {
throw new Error("Local credential normalization is disabled in CI.");
}
if (env.SENTRY_ENVIRONMENT?.trim()) {
throw new Error("Local credential normalization is disabled for deployed Sentry environments.");
}
if (env.RLS_RUNTIME_MODE?.trim().toLowerCase() === "required") {
throw new Error("Local credential normalization is disabled when RLS runtime mode is required.");
}
if (!LOCAL_ADMIN_HOST_PATTERN.test(env.ADMIN_APP_HOST?.trim() ?? "")) {
throw new Error("Local credential normalization requires the admin.localhost host.");
}
let databaseUrl: URL;
try {
databaseUrl = new URL(env.DATABASE_URL ?? "");
} catch {
throw new Error("Local credential normalization requires a valid DATABASE_URL.");
}
// node-postgres accepts query parameters that can override the URI host.
if (databaseUrl.search !== "") {
throw new Error("Local credential normalization does not allow PostgreSQL connection query parameters.");
}
if (!new Set(["postgres:", "postgresql:"]).has(databaseUrl.protocol) || !LOCAL_DATABASE_HOSTS.has(databaseUrl.hostname)) {
throw new Error("Local credential normalization requires a loopback PostgreSQL database.");
}
return databaseUrl;
}
export async function assertLocalCredentialsDatabaseMarker(client: Pick<DbClient, "$queryRaw">): Promise<void> {
const markerRows = await client.$queryRaw<Array<{ marked: boolean }>>`
SELECT EXISTS (
SELECT 1
FROM pg_catalog.pg_db_role_setting AS setting
JOIN pg_catalog.pg_database AS database
ON database.oid = setting.setdatabase
WHERE database.datname = current_database()
AND setting.setrole = 0
AND ${`${LOCAL_DATABASE_MARKER}=${LOCAL_DATABASE_MARKER_VALUE}`} = ANY(setting.setconfig)
) AS marked
`;
if (markerRows[0]?.marked !== true) {
throw new Error(
"Local credential normalization requires a database marked as disposable local development data. Run pnpm dev:services:mark-local only for the repository's local Postgres container."
);
}
}
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const dbMock = vi.hoisted(() => ({
pipeline: { upsert: vi.fn() },
pipelineStage: { upsert: vi.fn() },
pipelineAccess: { upsert: vi.fn() },
pipelineFieldConfig: { upsert: vi.fn() },
pipelineFieldVisibility: { upsert: vi.fn() },
lostReason: { upsert: vi.fn() },
projekt: { upsert: vi.fn() },
automationRule: { upsert: vi.fn() },
automationRuleStep: { upsert: vi.fn(), deleteMany: vi.fn() },
task: { upsert: vi.fn() },
automationExecution: { upsert: vi.fn() },
automationStepExecution: { upsert: vi.fn() },
automationTemplate: { upsert: vi.fn() },
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
import { seedStagingDomainDemo } from "./stagingDomainDemoSeed.server";
describe("seedStagingDomainDemo", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("upserts a reviewable P8 and P12 staging showcase", async () => {
await seedStagingDomainDemo({ tenantId: "tenant-business", ownerUserId: "user-owner" });
expect(dbMock.pipeline.upsert).toHaveBeenCalledTimes(2);
expect(dbMock.pipelineStage.upsert).toHaveBeenCalledTimes(10);
expect(dbMock.lostReason.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.projekt.upsert).toHaveBeenCalledTimes(7);
expect(dbMock.automationRule.upsert).toHaveBeenCalledOnce();
expect(dbMock.automationRuleStep.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.automationTemplate.upsert).toHaveBeenCalledOnce();
expect(dbMock.projekt.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({ tenantId: "tenant-business", projektname: "Heizungstausch Schneider", isDemoData: true }),
}),
);
expect(dbMock.automationRule.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({ tenantId: "tenant-business", enabled: true, isDemoData: true }),
}),
);
});
it("seeds an executable 24h reverse example with a real demo task output", async () => {
await seedStagingDomainDemo({ tenantId: "tenant-business", ownerUserId: "user-owner" });
expect(dbMock.task.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({ id: "staging-demo-automation-task", source: "automation" }),
update: expect.objectContaining({ archivedAt: null }),
}),
);
expect(dbMock.automationExecution.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
id: "staging-demo-automation-execution-success",
status: "success",
reverseWindowExpiresAt: expect.any(Date),
isDemoData: true,
}),
}),
);
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
stepKey: "create-task",
output: expect.objectContaining({ taskId: "staging-demo-automation-task" }),
}),
}),
);
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({
stepKey: "notify-office",
output: expect.objectContaining({
recipients: [
expect.objectContaining({ email: "buero@demo-pro.example" }),
expect.objectContaining({ email: "einsatzleitung@demo-pro.example" }),
],
}),
}),
}),
);
});
it("removes UI-rewritten rule steps before upserting so the (ruleId, stepKey) unique cannot collide", async () => {
await seedStagingDomainDemo({ tenantId: "tenant-business", ownerUserId: "user-owner" });
expect(dbMock.automationRuleStep.deleteMany).toHaveBeenCalledExactlyOnceWith({
where: {
ruleId: "staging-demo-automation-lead-follow-up",
id: {
notIn: [
"staging-demo-automation-step-trigger",
"staging-demo-automation-step-create-task",
"staging-demo-automation-step-notify-office",
],
},
},
});
const deleteOrder = dbMock.automationRuleStep.deleteMany.mock.invocationCallOrder[0];
const firstUpsertOrder = dbMock.automationRuleStep.upsert.mock.invocationCallOrder[0];
expect(deleteOrder).toBeLessThan(firstUpsertOrder);
expect(dbMock.automationStepExecution.upsert).toHaveBeenCalledWith(
expect.objectContaining({
update: expect.objectContaining({ ruleStepId: "staging-demo-automation-step-create-task" }),
}),
);
});
});
@@ -0,0 +1,377 @@
import { db } from "~/utils/db.server";
type StagingDomainDemoSeedInput = {
tenantId: string;
ownerUserId: string;
};
const salesPipelineId = "staging-demo-pipeline-sales";
const orderPipelineId = "staging-demo-pipeline-orders";
const lostReasonBudgetId = "staging-demo-lost-reason-budget";
const automationRuleId = "staging-demo-automation-lead-follow-up";
const automationTaskId = "staging-demo-automation-task";
const automationExecutionId = "staging-demo-automation-execution-success";
const automationRuleDescription = "Erstellt eine Rückruf-Aufgabe und informiert das Büro über neue Website-Anfragen.";
const automationTaskTitle = "Rückruf Familie Klein zur Wärmepumpe";
const automationTemplateDescription = "Informiert die Projektleitung vor einer nahenden Deadline.";
const salesStages = [
{ key: "new", name: "Neu", stageKind: "offen", winProbability: 10, color: "#64748b" },
{ key: "qualified", name: "Qualifiziert", stageKind: "offen", winProbability: 35, color: "#0ea5e9" },
{ key: "proposal", name: "Angebot", stageKind: "offen", winProbability: 70, color: "#8b5cf6" },
{ key: "won", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
{ key: "lost", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#ef4444" },
] as const;
const orderStages = [
{ key: "planning", name: "Planung", stageKind: "offen", winProbability: 100, color: "#64748b" },
{ key: "installation", name: "Montage", stageKind: "offen", winProbability: 100, color: "#0ea5e9" },
{ key: "acceptance", name: "Abnahme", stageKind: "offen", winProbability: 100, color: "#f59e0b" },
{ key: "done", name: "Abgeschlossen", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
{ key: "cancelled", name: "Storniert", stageKind: "verloren", winProbability: 0, color: "#ef4444" },
] as const;
function stageId(pipeline: "sales" | "orders", key: string): string {
return `staging-demo-stage-${pipeline}-${key}`;
}
function daysFromNow(days: number, hour = 12): Date {
const date = new Date();
date.setHours(hour, 0, 0, 0);
date.setDate(date.getDate() + days);
return date;
}
async function seedPipelinesAndProjects(input: StagingDomainDemoSeedInput): Promise<void> {
const pipelines = [
{ id: salesPipelineId, name: "Sales-Pipeline", typHint: "sales", position: 0, isDefault: true, stages: salesStages, key: "sales" },
{ id: orderPipelineId, name: "Auftragsabwicklung", typHint: "auftrag", position: 10, isDefault: false, stages: orderStages, key: "orders" },
] as const;
for (const pipeline of pipelines) {
await db.pipeline.upsert({
where: { id: pipeline.id },
create: {
id: pipeline.id,
tenantId: input.tenantId,
createdByUserId: input.ownerUserId,
name: pipeline.name,
typHint: pipeline.typHint,
position: pipeline.position,
isDefault: pipeline.isDefault,
isDemoData: true,
},
update: {
name: pipeline.name,
typHint: pipeline.typHint,
position: pipeline.position,
isDefault: pipeline.isDefault,
isDemoData: true,
archivedAt: null,
},
});
for (const [position, stage] of pipeline.stages.entries()) {
const id = stageId(pipeline.key, stage.key);
await db.pipelineStage.upsert({
where: { id },
create: {
id,
tenantId: input.tenantId,
pipelineId: pipeline.id,
name: stage.name,
stageKind: stage.stageKind,
winProbability: stage.winProbability,
color: stage.color,
position,
isDemoData: true,
},
update: {
pipelineId: pipeline.id,
name: stage.name,
stageKind: stage.stageKind,
winProbability: stage.winProbability,
color: stage.color,
position,
isDemoData: true,
archivedAt: null,
},
});
}
}
await db.pipelineAccess.upsert({
where: { id: "staging-demo-pipeline-access-owner" },
create: {
id: "staging-demo-pipeline-access-owner",
tenantId: input.tenantId,
pipelineId: salesPipelineId,
principalType: "user",
principalId: input.ownerUserId,
kannSehen: true,
kannBearbeiten: true,
},
update: { principalId: input.ownerUserId, kannSehen: true, kannBearbeiten: true },
});
const valueFieldConfigId = "staging-demo-pipeline-field-potential-value";
await db.pipelineFieldConfig.upsert({
where: { id: valueFieldConfigId },
create: {
id: valueFieldConfigId,
tenantId: input.tenantId,
pipelineId: salesPipelineId,
fieldKey: "potenziellerAuftragswert",
sichtbar: true,
pflicht: false,
reihenfolge: 10,
},
update: { sichtbar: true, pflicht: false, reihenfolge: 10 },
});
await db.pipelineFieldVisibility.upsert({
where: { id: "staging-demo-pipeline-field-visibility-owner" },
create: {
id: "staging-demo-pipeline-field-visibility-owner",
tenantId: input.tenantId,
fieldConfigId: valueFieldConfigId,
principalType: "user",
principalId: input.ownerUserId,
kannSehen: true,
kannBearbeiten: true,
},
update: { principalId: input.ownerUserId, kannSehen: true, kannBearbeiten: true },
});
const lostReasons = [
{ id: lostReasonBudgetId, name: "Budget nicht freigegeben", position: 0 },
{ id: "staging-demo-lost-reason-timing", name: "Zeitpunkt passt nicht", position: 10 },
{ id: "staging-demo-lost-reason-competitor", name: "Wettbewerber gewählt", position: 20 },
];
for (const reason of lostReasons) {
await db.lostReason.upsert({
where: { id: reason.id },
create: { ...reason, tenantId: input.tenantId, isDemoData: true },
update: { name: reason.name, position: reason.position, isDemoData: true, archivedAt: null },
});
}
const projects = [
{ id: "staging-demo-project-heat-pump", number: "HG-2026-0042", name: "Wärmepumpe Familie Klein", stage: stageId("sales", "new"), value: 28500, priority: "hoch", deadline: daysFromNow(14), won: false, lost: false, order: false },
{ id: "staging-demo-project-bathroom", number: "HG-2026-0043", name: "Badsanierung Wagner", stage: stageId("sales", "qualified"), value: 42000, priority: "normal", deadline: daysFromNow(30), won: false, lost: false, order: false },
{ id: "staging-demo-project-heating", number: "HG-2026-0044", name: "Heizungstausch Schneider", stage: stageId("sales", "proposal"), value: 19750, priority: "dringend", deadline: daysFromNow(-3), won: false, lost: false, order: false },
{ id: "staging-demo-project-housing", number: "HG-2026-0045", name: "Sanierung Wohnanlage Müller", stage: stageId("sales", "won"), value: 138000, priority: "hoch", deadline: daysFromNow(60), won: true, lost: false, order: false },
{ id: "staging-demo-project-maintenance", number: "HG-2026-0046", name: "Wartungsvertrag Bäckerei Sonnenschein", stage: stageId("sales", "lost"), value: 7800, priority: "niedrig", deadline: daysFromNow(7), won: false, lost: true, order: false },
{ id: "staging-demo-project-installation", number: "HG-2026-0047", name: "Montage Wärmepumpe Klein", stage: stageId("orders", "installation"), value: 28500, priority: "hoch", deadline: daysFromNow(10), won: false, lost: false, order: true },
{ id: "staging-demo-project-acceptance", number: "HG-2026-0048", name: "Abnahme Badsanierung Wagner", stage: stageId("orders", "acceptance"), value: 42000, priority: "normal", deadline: daysFromNow(2), won: false, lost: false, order: true },
] as const;
for (const project of projects) {
const pipelineId = project.order ? orderPipelineId : salesPipelineId;
const data = {
tenantId: input.tenantId,
createdByUserId: input.ownerUserId,
projektNummer: project.number,
projektname: project.name,
beschreibung: "Staging-Demodatensatz für die visuelle Prüfung der Projekt- und Pipeline-Oberflächen.",
projekttyp: project.order ? "Auftrag" : "Verkaufschance",
prioritaet: project.priority,
pipelineId,
stageId: project.stage,
potenziellerAuftragswert: project.order ? null : project.value,
auftragsvolumen: project.order ? project.value : null,
startDatum: daysFromNow(-14),
deadline: project.deadline,
zustaendigePersonId: input.ownerUserId,
wonAt: project.won ? daysFromNow(-5) : null,
lostAt: project.lost ? daysFromNow(-2) : null,
lostReasonId: project.lost ? lostReasonBudgetId : null,
isDemoData: true,
archivedAt: null,
};
await db.projekt.upsert({ where: { id: project.id }, create: { id: project.id, ...data }, update: data });
}
}
async function seedAutomation(input: StagingDomainDemoSeedInput): Promise<void> {
const steps = [
{ key: "trigger", kind: "trigger", nodeType: "forms.submitted", parents: [], position: { x: 120, y: 160 }, summary: "automation.steps.triggerFormSubmitted" },
{ key: "create-task", kind: "action", nodeType: "task.create", parents: ["trigger"], position: { x: 440, y: 160 }, summary: "automation.steps.createBackofficeTask" },
{ key: "notify-office", kind: "action", nodeType: "notification.send", parents: ["create-task"], position: { x: 760, y: 160 }, summary: "automation.steps.notifyOffice" },
] as const;
const flowData = {
triggerKey: "forms.submitted",
steps: steps.map((step, sortOrder) => ({
stepKey: step.key,
kind: step.kind,
nodeType: step.nodeType,
parentStepIds: step.parents,
config: {},
position: step.position,
sortOrder,
summaryKey: step.summary,
})),
history: { past: [], future: [] },
};
await db.automationRule.upsert({
where: { id: automationRuleId },
create: {
id: automationRuleId,
tenantId: input.tenantId,
name: "Angebotsanfragen automatisch nachfassen",
description: automationRuleDescription,
status: "active",
enabled: true,
createdVia: "staging-demo-seed",
triggerKey: "forms.submitted",
flowData,
createdByUserId: input.ownerUserId,
isDemoData: true,
},
update: { description: automationRuleDescription, status: "active", enabled: true, flowData, isDemoData: true, archivedAt: null },
});
// Saving the rule in the UI rewrites its steps with generated cuid ids. Those
// rows collide with the fixed-id upserts below on the (ruleId, stepKey) unique,
// crashing the seed on boot. Remove them first; executions keep working via
// the SetNull relation and are re-linked below.
await db.automationRuleStep.deleteMany({
where: {
ruleId: automationRuleId,
id: { notIn: steps.map((step) => `staging-demo-automation-step-${step.key}`) },
},
});
for (const [sortOrder, step] of steps.entries()) {
const id = `staging-demo-automation-step-${step.key}`;
await db.automationRuleStep.upsert({
where: { id },
create: {
id,
tenantId: input.tenantId,
ruleId: automationRuleId,
stepKey: step.key,
stepKind: step.kind,
nodeType: step.nodeType,
config: {},
parentStepIds: [...step.parents],
position: step.position,
sortOrder,
summaryText: step.summary,
isDemoData: true,
},
update: { stepKind: step.kind, nodeType: step.nodeType, config: {}, parentStepIds: [...step.parents], position: step.position, sortOrder, summaryText: step.summary, isDemoData: true },
});
}
await db.task.upsert({
where: { id: automationTaskId },
create: {
id: automationTaskId,
tenantId: input.tenantId,
createdByUserId: input.ownerUserId,
title: automationTaskTitle,
description: "Von der Staging-Demo-Automation angelegte Aufgabe.",
status: "open",
priority: "high",
deadline: daysFromNow(2),
assignedToUserId: input.ownerUserId,
source: "automation",
sourceRef: automationExecutionId,
isDemoData: true,
},
update: { status: "open", priority: "high", deadline: daysFromNow(2), assignedToUserId: input.ownerUserId, assignedToGroupId: null, archivedAt: null, isDemoData: true },
});
const startedAt = new Date(Date.now() - 45 * 60_000);
const endedAt = new Date(startedAt.getTime() + 38_000);
await db.automationExecution.upsert({
where: { id: automationExecutionId },
create: {
id: automationExecutionId,
tenantId: input.tenantId,
ruleId: automationRuleId,
triggerKey: "forms.submitted",
triggerPayload: { form: "Angebotsanfrage", contact: "Familie Klein", source: "staging-demo" },
status: "success",
dryRun: false,
idempotencyKey: "staging-demo:lead-follow-up:success",
reverseWindowExpiresAt: daysFromNow(1),
summaryText: "Angebotsanfrage Familie Klein erfolgreich verarbeitet",
queuedAt: startedAt,
startedAt,
endedAt,
durationMs: 38_000,
createdByUserId: input.ownerUserId,
isDemoData: true,
createdAt: startedAt,
},
update: { status: "success", reverseWindowExpiresAt: daysFromNow(1), summaryText: "Angebotsanfrage Familie Klein erfolgreich verarbeitet", errorText: null, queuedAt: startedAt, startedAt, endedAt, durationMs: 38_000, isDemoData: true, createdAt: startedAt },
});
const executionOutputs = {
trigger: { form: "Angebotsanfrage", contact: "Familie Klein", topic: "Wärmepumpe" },
"create-task": { taskId: automationTaskId, createdTaskId: automationTaskId, title: automationTaskTitle },
"notify-office": {
recipient: "Büro",
deliveryStatus: "delivered",
// Reverse-window recipients contract: send-type steps persist who was
// reached so the 24h reverse plan can show the (non-retractable) list.
recipients: [
{ name: "Sandra Vogel", email: "buero@demo-pro.example" },
{ name: "Peter Klein", email: "einsatzleitung@demo-pro.example" },
],
},
} as const;
for (const [sortOrder, step] of steps.entries()) {
const id = `staging-demo-automation-step-execution-${step.key}`;
await db.automationStepExecution.upsert({
where: { id },
create: {
id,
tenantId: input.tenantId,
executionId: automationExecutionId,
ruleStepId: `staging-demo-automation-step-${step.key}`,
stepKey: step.key,
stepKind: step.kind,
nodeType: step.nodeType,
status: "success",
input: sortOrder === 0 ? { source: "Website-Formular" } : { previousStep: step.parents[0] ?? null },
output: executionOutputs[step.key],
summaryText: step.summary,
startedAt: new Date(startedAt.getTime() + sortOrder * 10_000),
endedAt: new Date(startedAt.getTime() + (sortOrder + 1) * 10_000),
durationMs: 10_000,
sortOrder,
},
update: { status: "success", output: executionOutputs[step.key], summaryText: step.summary, errorText: null, sortOrder, ruleStepId: `staging-demo-automation-step-${step.key}` },
});
}
await db.automationTemplate.upsert({
where: { id: "staging-demo-automation-template-project-deadline" },
create: {
id: "staging-demo-automation-template-project-deadline",
tenantId: input.tenantId,
name: "Projekt-Deadline erinnern",
description: automationTemplateDescription,
category: "projects",
flowData: {
triggerKey: "projects.deadline_soon",
steps: [
{ stepKey: "trigger", kind: "trigger", nodeType: "projects.deadline_soon", parentStepIds: [], summaryKey: "automation.steps.triggerProjectDeadline" },
{ stepKey: "notify", kind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], summaryKey: "automation.steps.notifyProjectLead" },
],
},
isPublished: true,
createdByUserId: input.ownerUserId,
isDemoData: true,
},
update: { description: automationTemplateDescription, isPublished: true, isDemoData: true, archivedAt: null },
});
}
export async function seedStagingDomainDemo(input: StagingDomainDemoSeedInput): Promise<void> {
await seedPipelinesAndProjects(input);
await seedAutomation(input);
}