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

@@ -0,0 +1,345 @@
import type { EmployeeRole, ProjectType, SeedAddress } from "./types";
export const REFERENCE_DATE = "2026-07-13T08:00:00.000Z";
export const LOCATIONS: readonly Omit<SeedAddress, "strasse" | "hausnummer" | "land">[] = [
{ plz: "60311", ort: "Frankfurt am Main" },
{ plz: "60314", ort: "Frankfurt am Main" },
{ plz: "60433", ort: "Frankfurt am Main" },
{ plz: "60528", ort: "Frankfurt am Main" },
{ plz: "63065", ort: "Offenbach am Main" },
{ plz: "63071", ort: "Offenbach am Main" },
{ plz: "61118", ort: "Bad Vilbel" },
{ plz: "63477", ort: "Maintal" },
{ plz: "63263", ort: "Neu-Isenburg" },
{ plz: "65760", ort: "Eschborn" },
{ plz: "65719", ort: "Hofheim am Taunus" },
{ plz: "63450", ort: "Hanau" },
{ plz: "65428", ort: "Rüsselsheim am Main" },
{ plz: "61348", ort: "Bad Homburg vor der Höhe" },
{ plz: "64283", ort: "Darmstadt" },
{ plz: "65185", ort: "Wiesbaden" },
] as const;
export const STREET_PREFIXES = [
"Mainblick",
"Taunusblick",
"Mühlenrain",
"Apfelgarten",
"Kastanienhain",
"Quellenfeld",
"Rosenhöhe",
"Mainsonnenhang",
"Mainerlenbruch",
"Wiesenbogen",
"Falkengrund",
"Kupferwiese",
"Lindenrain",
"Auenblick",
"Taunusschieferhang",
"Mainkirschgarten",
"Buchenfeld",
"Morgenhöhe",
"Weidenbogen",
"Kranichgrund",
] as const;
export const STREET_SUFFIXES = ["straße", "weg", "ring", "allee", "pfad", "bogen"] as const;
export const FEMALE_FIRST_NAMES = [
"Anna",
"Sabine",
"Julia",
"Katharina",
"Laura",
"Nadine",
"Petra",
"Claudia",
"Miriam",
"Tanja",
"Leonie",
"Melanie",
"Stefanie",
"Jasmin",
"Saskia",
"Carolin",
"Bianca",
"Vanessa",
"Heike",
"Nicole",
] as const;
export const MALE_FIRST_NAMES = [
"Thomas",
"Michael",
"Andreas",
"Stefan",
"Markus",
"Daniel",
"Christian",
"Sebastian",
"Martin",
"Alexander",
"Tobias",
"Matthias",
"Jan",
"Florian",
"Patrick",
"Mehmet",
"Murat",
"Dennis",
"Sven",
"Oliver",
] as const;
export const LAST_NAMES = [
"Schneider",
"Fischer",
"Weber",
"Meyer",
"Wagner",
"Becker",
"Hoffmann",
"Schäfer",
"Koch",
"Bauer",
"Richter",
"Klein",
"Wolf",
"Schröder",
"Neumann",
"Schwarz",
"Zimmermann",
"Braun",
"Krüger",
"Hartmann",
"Lange",
"Werner",
"Schmitz",
"Krause",
"Meier",
"Lehmann",
"Schmid",
"Schulz",
"Maier",
"Köhler",
] as const;
// These names belong to the globally persisted rheinmain-shk-v1 employee IDs.
// Keep this mapping immutable when roles, seats, departments, or crews change.
export const EMPLOYEE_IDENTITIES_V1 = [
{ firstName: "Anna", lastName: "Schneider" },
{ firstName: "Michael", lastName: "Schäfer" },
{ firstName: "Julia", lastName: "Neumann" },
{ firstName: "Stefan", lastName: "Werner" },
{ firstName: "Laura", lastName: "Maier" },
{ firstName: "Daniel", lastName: "Becker" },
{ firstName: "Petra", lastName: "Wolf" },
{ firstName: "Sebastian", lastName: "Hartmann" },
{ firstName: "Miriam", lastName: "Schmid" },
{ firstName: "Alexander", lastName: "Meyer" },
{ firstName: "Leonie", lastName: "Richter" },
{ firstName: "Matthias", lastName: "Braun" },
{ firstName: "Stefanie", lastName: "Meier" },
{ firstName: "Florian", lastName: "Fischer" },
{ firstName: "Saskia", lastName: "Koch" },
{ firstName: "Mehmet", lastName: "Schwarz" },
{ firstName: "Bianca", lastName: "Schmitz" },
{ firstName: "Dennis", lastName: "Köhler" },
{ firstName: "Heike", lastName: "Hoffmann" },
{ firstName: "Oliver", lastName: "Schröder" },
{ firstName: "Miriam", lastName: "Wagner" },
{ firstName: "Markus", lastName: "Schwarz" },
{ firstName: "Daniel", lastName: "Schmid" },
{ firstName: "Christian", lastName: "Schäfer" },
{ firstName: "Sebastian", lastName: "Krüger" },
{ firstName: "Jasmin", lastName: "Köhler" },
{ firstName: "Alexander", lastName: "Richter" },
{ firstName: "Tobias", lastName: "Werner" },
{ firstName: "Matthias", lastName: "Weber" },
{ firstName: "Jan", lastName: "Schröder" },
{ firstName: "Heike", lastName: "Meier" },
{ firstName: "Patrick", lastName: "Becker" },
{ firstName: "Mehmet", lastName: "Zimmermann" },
{ firstName: "Murat", lastName: "Schulz" },
{ firstName: "Dennis", lastName: "Koch" },
{ firstName: "Katharina", lastName: "Hartmann" },
{ firstName: "Oliver", lastName: "Schneider" },
{ firstName: "Thomas", lastName: "Klein" },
{ firstName: "Michael", lastName: "Schmitz" },
{ firstName: "Andreas", lastName: "Meyer" },
{ firstName: "Miriam", lastName: "Neumann" },
{ firstName: "Markus", lastName: "Lehmann" },
{ firstName: "Daniel", lastName: "Hoffmann" },
{ firstName: "Christian", lastName: "Braun" },
{ firstName: "Sebastian", lastName: "Maier" },
{ firstName: "Jasmin", lastName: "Bauer" },
{ firstName: "Alexander", lastName: "Lange" },
{ firstName: "Tobias", lastName: "Fischer" },
{ firstName: "Matthias", lastName: "Wolf" },
{ firstName: "Jan", lastName: "Krause" },
] as const;
export const OFFICE_ROLE_COUNTS: ReadonlyArray<{ role: EmployeeRole; count: number; jobTitle: string }> = [
{ role: "Geschäftsführer", count: 1, jobTitle: "Geschäftsführer" },
{ role: "Vertriebsleiter", count: 1, jobTitle: "Leiter Vertrieb" },
{ role: "Vertriebler", count: 3, jobTitle: "Fachberater SHK" },
{ role: "Büro/Backoffice", count: 4, jobTitle: "Kaufmännische Sachbearbeitung" },
{ role: "Marketing", count: 1, jobTitle: "Marketing und Kommunikation" },
{ role: "Projektleiter/Bauleiter", count: 7, jobTitle: "Projektleiter SHK" },
] as const;
export const ORGANIZATION_SECTORS = [
"Hausverwaltung",
"Wohnungswirtschaft",
"Gastronomie",
"Hotellerie",
"Einzelhandel",
"Büro und Beratung",
"Bauunternehmen",
"Architekturbüro",
"Partnerhandwerk",
"Pflegeeinrichtung",
"Bildungsträger",
"Kommunale Einrichtung",
"Industrie",
"Logistik",
"Großhandel",
] as const;
export const ORGANIZATION_ROOTS = [
"Mainbogen",
"Taunusblick",
"Rheinwarte",
"Stadtgarten",
"Quellenhof",
"Uferwerk",
"Auenland",
"Hofgarten",
"Brückenfeld",
"Sonnenhof",
"Mainquartier",
"Wiesenwerk",
"Römerblick",
"Kronenhof",
"Mühlenwerk",
"Bergquell",
"Westhafen",
] as const;
export const PROJECT_TYPE_COUNTS: Readonly<Record<ProjectType, number>> = {
reparatur_notdienst: 150,
wartung_pruefung: 118,
heizungstausch: 86,
heizungsoptimierung: 43,
badsanierung: 64,
sanitaer_rohrarbeiten: 38,
objekt_neubau: 22,
lueftung_klima: 16,
};
export const PROJECT_TYPE_DETAILS: Readonly<
Record<
ProjectType,
{
label: string;
descriptions: readonly string[];
minValue: number;
maxValue: number;
durationDays: [number, number];
}
>
> = {
reparatur_notdienst: {
label: "Reparatur und Störungsdienst",
descriptions: [
"Heizungsstörung diagnostizieren und beheben",
"Rohrleck lokalisieren und instand setzen",
"Warmwasserversorgung kurzfristig wiederherstellen",
],
minValue: 250,
maxValue: 4500,
durationDays: [1, 4],
},
wartung_pruefung: {
label: "Wartung und Prüfung",
descriptions: [
"Jahreswartung mit Messprotokoll durchführen",
"Anlage reinigen, prüfen und hydraulisch nachstellen",
"Wartungstermin inklusive Verschleißteilprüfung ausführen",
],
minValue: 250,
maxValue: 2500,
durationDays: [1, 3],
},
heizungstausch: {
label: "Heizungstausch",
descriptions: [
"Bestandsanlage demontieren und Wärmepumpe installieren",
"Wärmeerzeuger samt Speicher und Regelung erneuern",
"Heizzentrale modernisieren und Anlage einregulieren",
],
minValue: 12000,
maxValue: 45000,
durationDays: [4, 14],
},
heizungsoptimierung: {
label: "Heizungsoptimierung",
descriptions: [
"Hydraulischen Abgleich und Pumpentausch durchführen",
"Regelung optimieren und Heizkreise einregulieren",
"Verbrauchsanalyse mit Optimierungsmaßnahmen umsetzen",
],
minValue: 1500,
maxValue: 8000,
durationDays: [2, 6],
},
badsanierung: {
label: "Badsanierung",
descriptions: [
"Bad vollständig entkernen und barrierearm neu ausbauen",
"Sanitärobjekte und Leitungsführung modernisieren",
"Teilbad mit Dusche, Armaturen und Vorwand erneuern",
],
minValue: 4000,
maxValue: 45850,
durationDays: [5, 24],
},
sanitaer_rohrarbeiten: {
label: "Sanitär- und Rohrarbeiten",
descriptions: [
"Trinkwasserleitungen abschnittsweise erneuern",
"Fallstrang sanieren und Anschlussleitungen anpassen",
"Sanitärinstallation für Nutzungseinheit herstellen",
],
minValue: 1200,
maxValue: 28000,
durationDays: [2, 18],
},
objekt_neubau: {
label: "Objekt- und Neubauinstallation",
descriptions: [
"SHK-Gewerke für Mehrfamilienhaus koordinieren und ausführen",
"Heizungs- und Sanitärinstallation im Gewerbeobjekt herstellen",
"Technikzentrale und Steigstränge für Neubau errichten",
],
minValue: 50000,
maxValue: 250000,
durationDays: [30, 150],
},
lueftung_klima: {
label: "Lüftung und Klima",
descriptions: [
"Kontrollierte Wohnraumlüftung planen und montieren",
"Klimageräte für Gewerbefläche installieren",
"Lüftungsanlage reinigen und Volumenströme einregulieren",
],
minValue: 3500,
maxValue: 55000,
durationDays: [3, 30],
},
};
export const SALES_STAGE_COUNTS = { neu: 47, qualifiziert: 59, angebot: 73, gewonnen: 112, verloren: 28 } as const;
export const ORDER_STAGE_COUNTS = { planung: 31, montage: 67, abnahme: 39, abgeschlossen: 69, storniert: 12 } as const;
export const LEAD_OUTCOME_COUNTS = { spam: 15, disqualified: 33, offer_lost: 29, converted: 116 } as const;
@@ -0,0 +1,226 @@
import { describe, expect, test, vi } from "vitest";
import { DEMO_PRO_TENANT_SLUG, parseSeedCommand } from "./cli";
const stagingEnv = {
SEED_DEMO_PRO_ALLOWED: "true",
SEED_DEMO_PRO_EXPECTED_DATABASE: "hivegrid_staging",
SEED_DEMO_PRO_EXPECTED_DATABASE_HOST: "postgres-staging:5432",
SEED_DEMO_PRO_EXPECTED_STORAGE_BUCKET: "hivegrid-staging-media",
SEED_DEMO_PRO_EXPECTED_STORAGE_ENDPOINT: "https://staging-storage.example.test",
SEED_DEMO_PRO_EXPECTED_TENANT_ID: "tenant_staging_demo_pro",
SEED_DEMO_PRO_OUTBOUND_SANDBOX: "true",
SEED_DEMO_PRO_WORKERS_DRAINED: "true",
SEED_DEMO_USER_PASSWORD: "R7!qL2#vN9@xP4$kT8&m",
SENTRY_ENVIRONMENT: "staging",
};
describe("demo-pro seed CLI", () => {
test("defaults to an environment-free dry run", () => {
expect(parseSeedCommand([], {})).toEqual({
mode: "dry-run",
tenantSlug: DEMO_PRO_TENANT_SLUG,
});
expect(parseSeedCommand(["--dry-run"], {})).toEqual({
mode: "dry-run",
tenantSlug: DEMO_PRO_TENANT_SLUG,
});
});
test("accepts only the demo-pro-crm tenant", () => {
expect(parseSeedCommand(["--tenant=demo-pro-crm"], {})).toEqual({
mode: "dry-run",
tenantSlug: DEMO_PRO_TENANT_SLUG,
});
expect(() => parseSeedCommand(["--tenant=another-tenant"], {})).toThrow("target tenant must be demo-pro-crm");
});
test("rejects unknown, duplicate and conflicting arguments", () => {
expect(() => parseSeedCommand(["apply"], {})).toThrow("unknown argument");
expect(() => parseSeedCommand(["--apply", "--cleanup"], stagingEnv)).toThrow("exactly one mode");
expect(() => parseSeedCommand(["--tenant=demo-pro-crm", "--tenant=demo-pro-crm"], {})).toThrow("--tenant may only be provided once");
expect(() => parseSeedCommand(["--apply", "--confirm=demo-pro-crm", "--confirm=demo-pro-crm"], stagingEnv)).toThrow("--confirm may only be provided once");
});
test("requires an exact tenant confirmation for apply", () => {
expect(() => parseSeedCommand(["--apply"], stagingEnv)).toThrow("--confirm=demo-pro-crm");
expect(() => parseSeedCommand(["--apply", "--confirm=another-tenant"], stagingEnv)).toThrow("--confirm=demo-pro-crm");
});
test("requires explicit authorization for apply and cleanup", () => {
expect(() =>
parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
SENTRY_ENVIRONMENT: "staging",
})
).toThrow("explicit staging seed authorization");
expect(() =>
parseSeedCommand(["--cleanup", "--confirm=demo-pro-crm"], {
SENTRY_ENVIRONMENT: "staging",
})
).toThrow("explicit staging seed authorization");
});
test("requires drained workers and a staging-only outbound sink", () => {
expect(() =>
parseSeedCommand(["--cleanup", "--confirm=demo-pro-crm"], {
...stagingEnv,
SEED_DEMO_PRO_WORKERS_DRAINED: "false",
})
).toThrow("drained workers");
expect(() =>
parseSeedCommand(["--cleanup", "--confirm=demo-pro-crm"], {
...stagingEnv,
SEED_DEMO_PRO_OUTBOUND_SANDBOX: "false",
})
).toThrow("outbound staging sandbox");
});
test("allows apply only on staging and resolves the configured staging password", () => {
expect(parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], stagingEnv)).toEqual({
mode: "apply",
tenantSlug: DEMO_PRO_TENANT_SLUG,
userPassword: "R7!qL2#vN9@xP4$kT8&m",
expectedTenantId: "tenant_staging_demo_pro",
expectedDatabaseName: "hivegrid_staging",
expectedDatabaseHost: "postgres-staging:5432",
expectedStorageBucket: "hivegrid-staging-media",
expectedStorageEndpoint: "https://staging-storage.example.test",
});
});
test("requires the password to be supplied as a staging secret", () => {
expect(() =>
parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
SEED_DEMO_PRO_ALLOWED: "true",
SEED_DEMO_PRO_EXPECTED_DATABASE: "hivegrid_staging",
SEED_DEMO_PRO_EXPECTED_DATABASE_HOST: "postgres-staging:5432",
SEED_DEMO_PRO_EXPECTED_STORAGE_BUCKET: "hivegrid-staging-media",
SEED_DEMO_PRO_EXPECTED_STORAGE_ENDPOINT: "https://staging-storage.example.test",
SEED_DEMO_PRO_EXPECTED_TENANT_ID: "tenant_staging_demo_pro",
SEED_DEMO_PRO_OUTBOUND_SANDBOX: "true",
SEED_DEMO_PRO_WORKERS_DRAINED: "true",
SENTRY_ENVIRONMENT: "staging",
})
).toThrow("demo-user password secret");
});
test("requires mutation to be bound to the exact staging tenant and database", () => {
expect(() =>
parseSeedCommand(["--cleanup", "--confirm=demo-pro-crm"], {
SEED_DEMO_PRO_ALLOWED: "true",
SEED_DEMO_PRO_OUTBOUND_SANDBOX: "true",
SEED_DEMO_PRO_WORKERS_DRAINED: "true",
SENTRY_ENVIRONMENT: "staging",
})
).toThrow("tenant, database, and storage binding");
});
test.each(["passwort", "password", "HiveGrid-Demo-Password", "short-but-varied!9A"])("rejects a weak shared staging password (%s)", (password) => {
expect(() =>
parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
...stagingEnv,
SEED_DEMO_USER_PASSWORD: password,
})
).toThrow("strong random secret");
});
test("allows the explicitly requested shared password only behind the dedicated staging guard", () => {
expect(
parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
...stagingEnv,
SEED_DEMO_PRO_ALLOW_SHARED_STAGING_PASSWORD: "true",
SEED_DEMO_USER_PASSWORD: "password",
}),
).toMatchObject({ mode: "apply", userPassword: "password" });
expect(() =>
parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
...stagingEnv,
SEED_DEMO_PRO_ALLOW_SHARED_STAGING_PASSWORD: "true",
SEED_DEMO_USER_PASSWORD: "passwort",
}),
).toThrow("strong random secret");
});
test("keeps a configured password opaque and does not log it", () => {
const consoleSpies = [
vi.spyOn(console, "log").mockImplementation(() => undefined),
vi.spyOn(console, "info").mockImplementation(() => undefined),
vi.spyOn(console, "warn").mockImplementation(() => undefined),
vi.spyOn(console, "error").mockImplementation(() => undefined),
];
const password = " R7!qL2#vN9@xP4$kT8&m ";
const command = parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
...stagingEnv,
SEED_DEMO_USER_PASSWORD: password,
});
expect(command).toEqual({
mode: "apply",
tenantSlug: DEMO_PRO_TENANT_SLUG,
userPassword: password,
expectedTenantId: "tenant_staging_demo_pro",
expectedDatabaseName: "hivegrid_staging",
expectedDatabaseHost: "postgres-staging:5432",
expectedStorageBucket: "hivegrid-staging-media",
expectedStorageEndpoint: "https://staging-storage.example.test",
});
for (const spy of consoleSpies) expect(spy).not.toHaveBeenCalled();
vi.restoreAllMocks();
});
test("does not echo values from rejected arguments", () => {
const accidentalSecret = "Never expose this value";
expect(() => parseSeedCommand([`--password=${accidentalSecret}`], {})).toThrowError(
expect.not.objectContaining({ message: expect.stringContaining(accidentalSecret) })
);
});
test.each([undefined, "", "production", "development", "test", "STAGING", "staging-preview"])(
"rejects verify outside the exact staging environment (%s)",
(environment) => {
expect(() =>
parseSeedCommand(["--verify"], {
SENTRY_ENVIRONMENT: environment,
})
).toThrow("restricted to the staging environment");
}
);
test("allows read-only verification on staging without mutation authorization", () => {
expect(parseSeedCommand(["--verify"], { SENTRY_ENVIRONMENT: "staging" })).toEqual({
mode: "verify",
tenantSlug: DEMO_PRO_TENANT_SLUG,
});
});
test("allows cleanup only with every destructive-operation guard", () => {
expect(parseSeedCommand(["--cleanup", "--confirm=demo-pro-crm"], stagingEnv)).toEqual({
mode: "cleanup",
tenantSlug: DEMO_PRO_TENANT_SLUG,
expectedTenantId: "tenant_staging_demo_pro",
expectedDatabaseName: "hivegrid_staging",
expectedDatabaseHost: "postgres-staging:5432",
expectedStorageBucket: "hivegrid-staging-media",
expectedStorageEndpoint: "https://staging-storage.example.test",
});
});
test("does not treat NODE_ENV=production as production when the deployment is explicitly staging", () => {
expect(
parseSeedCommand(["--apply", "--confirm=demo-pro-crm"], {
...stagingEnv,
NODE_ENV: "production",
})
).toMatchObject({ mode: "apply", tenantSlug: DEMO_PRO_TENANT_SLUG });
});
test("does not accept confirmation for non-mutating modes", () => {
expect(() => parseSeedCommand(["--confirm=demo-pro-crm"], {})).toThrow("--confirm is only valid for apply and cleanup");
expect(() => parseSeedCommand(["--verify", "--confirm=demo-pro-crm"], { SENTRY_ENVIRONMENT: "staging" })).toThrow(
"--confirm is only valid for apply and cleanup"
);
});
});
@@ -0,0 +1,173 @@
export const DEMO_PRO_TENANT_SLUG = "demo-pro-crm" as const;
export type SeedMode = "dry-run" | "apply" | "verify" | "cleanup";
type NonApplySeedCommand = {
mode: "dry-run" | "verify";
tenantSlug: typeof DEMO_PRO_TENANT_SLUG;
};
type CleanupSeedCommand = {
mode: "cleanup";
tenantSlug: typeof DEMO_PRO_TENANT_SLUG;
expectedTenantId: string;
expectedDatabaseName: string;
expectedDatabaseHost: string;
expectedStorageBucket: string;
expectedStorageEndpoint: string;
};
type ApplySeedCommand = {
mode: "apply";
tenantSlug: typeof DEMO_PRO_TENANT_SLUG;
userPassword: string;
expectedTenantId: string;
expectedDatabaseName: string;
expectedDatabaseHost: string;
expectedStorageBucket: string;
expectedStorageEndpoint: string;
};
export type SeedCommand = NonApplySeedCommand | CleanupSeedCommand | ApplySeedCommand;
type SeedEnvironment = Readonly<Record<string, string | undefined>>;
const modeArguments = new Map<string, SeedMode>([
["--dry-run", "dry-run"],
["--apply", "apply"],
["--verify", "verify"],
["--cleanup", "cleanup"],
]);
function parseSingleValueArgument(argv: readonly string[], name: string): string | undefined {
const prefix = `${name}=`;
const values = argv.filter((argument) => argument.startsWith(prefix)).map((argument) => argument.slice(prefix.length));
if (values.length > 1) {
throw new Error(`demo-pro seed: ${name} may only be provided once`);
}
return values[0];
}
function parseMode(argv: readonly string[]): SeedMode {
const modes = argv.flatMap((argument) => {
const mode = modeArguments.get(argument);
return mode ? [mode] : [];
});
if (modes.length > 1) {
throw new Error("demo-pro seed: provide exactly one mode");
}
return modes[0] ?? "dry-run";
}
function assertKnownArguments(argv: readonly string[]): void {
for (const argument of argv) {
if (modeArguments.has(argument) || argument.startsWith("--confirm=") || argument.startsWith("--tenant=")) {
continue;
}
throw new Error("demo-pro seed: unknown argument");
}
}
function assertTargetTenant(argv: readonly string[]): void {
const tenantSlug = parseSingleValueArgument(argv, "--tenant");
if (tenantSlug !== undefined && tenantSlug !== DEMO_PRO_TENANT_SLUG) {
throw new Error(`demo-pro seed: target tenant must be ${DEMO_PRO_TENANT_SLUG}`);
}
}
function assertStagingEnvironment(env: SeedEnvironment): void {
if (env.SENTRY_ENVIRONMENT?.trim() !== "staging") {
throw new Error("demo-pro seed: this mode is restricted to the staging environment");
}
}
function assertMutationAllowed(argv: readonly string[], env: SeedEnvironment): void {
const confirmation = parseSingleValueArgument(argv, "--confirm");
if (confirmation !== DEMO_PRO_TENANT_SLUG) {
throw new Error(`demo-pro seed: this mode requires --confirm=${DEMO_PRO_TENANT_SLUG}`);
}
if (env.SEED_DEMO_PRO_ALLOWED?.trim() !== "true") {
throw new Error("demo-pro seed: this mode requires explicit staging seed authorization");
}
if (env.SEED_DEMO_PRO_WORKERS_DRAINED?.trim() !== "true" || env.SEED_DEMO_PRO_OUTBOUND_SANDBOX?.trim() !== "true") {
throw new Error("demo-pro seed: mutation requires drained workers and an outbound staging sandbox");
}
}
/**
* Parses process arguments passed after the script path and enforces the staging-only seed boundary.
* The function has no side effects and never includes environment values in errors or output.
*/
export function parseSeedCommand(argv: readonly string[], env: SeedEnvironment): SeedCommand {
assertKnownArguments(argv);
const mode = parseMode(argv);
assertTargetTenant(argv);
const confirmation = parseSingleValueArgument(argv, "--confirm");
if ((mode === "dry-run" || mode === "verify") && confirmation !== undefined) {
throw new Error("demo-pro seed: --confirm is only valid for apply and cleanup");
}
if (mode === "dry-run") {
return { mode, tenantSlug: DEMO_PRO_TENANT_SLUG };
}
assertStagingEnvironment(env);
if (mode === "verify") {
return { mode, tenantSlug: DEMO_PRO_TENANT_SLUG };
}
assertMutationAllowed(argv, env);
const expectedTenantId = env.SEED_DEMO_PRO_EXPECTED_TENANT_ID?.trim();
const expectedDatabaseName = env.SEED_DEMO_PRO_EXPECTED_DATABASE?.trim();
const expectedDatabaseHost = env.SEED_DEMO_PRO_EXPECTED_DATABASE_HOST?.trim();
const expectedStorageBucket = env.SEED_DEMO_PRO_EXPECTED_STORAGE_BUCKET?.trim();
const expectedStorageEndpoint = env.SEED_DEMO_PRO_EXPECTED_STORAGE_ENDPOINT?.trim();
if (!expectedTenantId || !expectedDatabaseName || !expectedDatabaseHost || !expectedStorageBucket || !expectedStorageEndpoint) {
throw new Error("demo-pro seed: mutation requires the staging tenant, database, and storage binding secrets");
}
if (mode === "cleanup") {
return {
mode,
tenantSlug: DEMO_PRO_TENANT_SLUG,
expectedTenantId,
expectedDatabaseName,
expectedDatabaseHost,
expectedStorageBucket,
expectedStorageEndpoint,
};
}
const userPassword = env.SEED_DEMO_USER_PASSWORD;
if (!userPassword || userPassword.trim().length === 0) {
throw new Error("demo-pro seed: apply requires the staging demo-user password secret");
}
const explicitlyAllowedSharedStagingPassword =
userPassword === "password" && env.SEED_DEMO_PRO_ALLOW_SHARED_STAGING_PASSWORD?.trim() === "true";
if (
!explicitlyAllowedSharedStagingPassword &&
(userPassword.length < 20 || new Set(userPassword).size < 10 || /^(?:passw(?:or)?t|password|demo|hivegrid)/iu.test(userPassword))
) {
throw new Error("demo-pro seed: the staging demo-user password must be a strong random secret of at least 20 characters");
}
return {
mode,
tenantSlug: DEMO_PRO_TENANT_SLUG,
userPassword,
expectedTenantId,
expectedDatabaseName,
expectedDatabaseHost,
expectedStorageBucket,
expectedStorageEndpoint,
};
}
@@ -0,0 +1,195 @@
import { createHash } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import {
buildSeedFileObjectMetadata,
buildSeedPdfBytes,
deleteDemoProSeedFileObjects,
deleteDemoProTenantFileObjects,
seedFileStorageKey,
seedFileStoragePrefix,
uploadDemoProSeedFileObjects,
verifyDemoProSeedFileObjects,
} from "./file-objects";
const descriptor = {
id: "rheinmain-shk-v1-file-0001",
displayName: "Aufmaß_HG-2026-0042.pdf",
notes: "Projektunterlage zur Wärmepumpenmodernisierung; dem Projekt HG-2026-0042 zugeordnet.",
};
describe("demo-pro seed file objects", () => {
it("builds a deterministic PDF with valid xref offsets and exact metadata", () => {
const bytes = buildSeedPdfBytes(descriptor);
const second = buildSeedPdfBytes(descriptor);
const pdf = new TextDecoder().decode(bytes);
expect(second).toEqual(bytes);
expect(pdf.startsWith("%PDF-1.4\n")).toBe(true);
expect(pdf.endsWith("%%EOF\n")).toBe(true);
const startXref = Number(pdf.match(/startxref\n(\d+)\n%%EOF/u)?.[1]);
expect(pdf.slice(startXref).startsWith("xref\n")).toBe(true);
const xrefEntries = [...pdf.matchAll(/^(\d{10}) 00000 n $/gmu)].map((match) => Number(match[1]));
expect(xrefEntries).toHaveLength(5);
for (const [index, offset] of xrefEntries.entries()) {
expect(pdf.slice(offset).startsWith(`${index + 1} 0 obj\n`)).toBe(true);
}
const metadata = buildSeedFileObjectMetadata(descriptor);
expect(metadata.mimeType).toBe("application/pdf");
expect(metadata.sizeBytes).toBe(bytes.byteLength);
expect(metadata.checksumSha256).toBe(createHash("sha256").update(bytes).digest("hex"));
});
it("uses the mandatory tenant-prefixed Files storage path", () => {
expect(seedFileStorageKey("tenant-staging", descriptor.id)).toBe(`tenants/tenant-staging/files/${descriptor.id}/original`);
expect(seedFileStoragePrefix("tenant-staging")).toBe("tenants/tenant-staging/files/");
expect(() => seedFileStorageKey("tenant/foreign", descriptor.id)).toThrow(/Invalid storage path segment/u);
});
it("uploads all PDFs with bounded concurrency and fails on metadata drift", async () => {
const files = Array.from({ length: 9 }, (_, index) =>
buildSeedFileObjectMetadata({ ...descriptor, id: `${descriptor.id}-${index}`, displayName: `Dokument-${index}.pdf` })
);
let active = 0;
let maxActive = 0;
const putObject = vi.fn(async ({ body }: { body: Uint8Array }) => {
active += 1;
maxActive = Math.max(maxActive, active);
expect(new TextDecoder().decode(body)).toMatch(/^%PDF-1\.4/u);
await Promise.resolve();
active -= 1;
});
await expect(uploadDemoProSeedFileObjects({ tenantId: "tenant-staging", files, concurrency: 3, bucket: "staging-files", putObject })).resolves.toEqual({
bucket: "staging-files",
uploaded: files.length,
});
expect(putObject).toHaveBeenCalledTimes(files.length);
expect(maxActive).toBeLessThanOrEqual(3);
expect(putObject.mock.calls[0]![0]).toMatchObject({
bucket: "staging-files",
key: `tenants/tenant-staging/files/${descriptor.id}-0/original`,
contentType: "application/pdf",
});
await expect(
uploadDemoProSeedFileObjects({
tenantId: "tenant-staging",
files: [{ ...files[0]!, sizeBytes: files[0]!.sizeBytes + 1 }],
bucket: "staging-files",
putObject,
})
).rejects.toThrow(/metadata drifted/u);
});
it("deletes every deterministic object and refuses cleanup without storage", async () => {
const files = [{ id: "file-1" }, { id: "file-2" }];
const deleteObject = vi.fn(async () => undefined);
await expect(
deleteDemoProSeedFileObjects({
tenantId: "tenant-staging",
files,
concurrency: 2,
bucket: "staging-files",
deleteObject,
storageConfigured: () => true,
})
).resolves.toEqual({ bucket: "staging-files", deleted: 2 });
expect(deleteObject).toHaveBeenCalledTimes(2);
await expect(
deleteDemoProSeedFileObjects({
tenantId: "tenant-staging",
files,
bucket: "staging-files",
deleteObject,
storageConfigured: () => false,
})
).rejects.toThrow(/storage provider is not configured/u);
});
it("downloads and verifies every uploaded object against its exact checksum", async () => {
const file = buildSeedFileObjectMetadata(descriptor);
const bytes = buildSeedPdfBytes(file);
let storedBytes = bytes;
const send = vi.fn(async (command: unknown) => {
if ((command as { constructor: { name: string } }).constructor.name === "ListObjectsV2Command") {
return { Contents: [{ Key: seedFileStorageKey("tenant-staging", file.id) }], IsTruncated: false };
}
return {
ContentLength: storedBytes.byteLength,
Body: { transformToByteArray: async () => storedBytes },
};
});
await expect(
verifyDemoProSeedFileObjects({
tenantId: "tenant-staging",
files: [file],
bucket: "staging-files",
client: { send },
})
).resolves.toEqual({ bucket: "staging-files", verified: 1 });
expect(send.mock.calls.map(([command]) => command.constructor.name)).toEqual(["ListObjectsV2Command", "GetObjectCommand"]);
const corrupted = new Uint8Array(bytes);
corrupted[20] = corrupted[20]! ^ 1;
storedBytes = corrupted;
await expect(
verifyDemoProSeedFileObjects({
tenantId: "tenant-staging",
files: [file],
bucket: "staging-files",
client: { send },
})
).rejects.toThrow(/metadata drifted/u);
});
it("fails verification when the managed prefix contains an extra object", async () => {
const file = buildSeedFileObjectMetadata(descriptor);
const send = vi.fn(async () => ({
Contents: [{ Key: seedFileStorageKey("tenant-staging", file.id) }, { Key: "tenants/tenant-staging/files/orphan/original" }],
IsTruncated: false,
}));
await expect(
verifyDemoProSeedFileObjects({
tenantId: "tenant-staging",
files: [file],
bucket: "staging-files",
client: { send },
})
).rejects.toThrow(/unexpected storage object/u);
});
it("removes every object below the managed tenant file prefix", async () => {
const send = vi
.fn()
.mockResolvedValueOnce({
Contents: [{ Key: "tenants/tenant-staging/files/file-1/original" }, { Key: "tenants/tenant-staging/files/orphan/thumb.webp" }],
IsTruncated: true,
})
.mockResolvedValueOnce({ Errors: [] })
.mockResolvedValueOnce({
Contents: [{ Key: "tenants/tenant-staging/files/file-3/original" }],
IsTruncated: false,
})
.mockResolvedValueOnce({ Errors: [] })
.mockResolvedValueOnce({ Contents: [], IsTruncated: false });
await expect(deleteDemoProTenantFileObjects({ tenantId: "tenant-staging", bucket: "staging-files", client: { send } })).resolves.toEqual({
bucket: "staging-files",
deleted: 3,
});
expect(send.mock.calls.map(([command]) => command.constructor.name)).toEqual([
"ListObjectsV2Command",
"DeleteObjectsCommand",
"ListObjectsV2Command",
"DeleteObjectsCommand",
"ListObjectsV2Command",
]);
});
});
@@ -0,0 +1,357 @@
import { createHash } from "node:crypto";
import { DeleteObjectsCommand, GetObjectCommand, ListObjectsV2Command, S3Client } from "@aws-sdk/client-s3";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { buildFileStorageKeys } from "@hivegrid/storage";
import {
deleteFile,
hasStorageCredentials,
putBufferAsFile,
resolveStorageBinding,
resolveStorageBucket,
} from "../../apps/web/app/utils/integrations/storageService";
const DEFAULT_STORAGE_CONCURRENCY = 12;
const PDF_CONTENT_TYPE = "application/pdf";
const encoder = new TextEncoder();
export type SeedFileObjectDescriptor = {
id: string;
displayName: string;
notes: string;
};
export type SeedFileObjectMetadata = SeedFileObjectDescriptor & {
mimeType: string;
sizeBytes: number;
checksumSha256: string;
};
type PersistedSeedFileObject = SeedFileObjectDescriptor & {
mimeType: string;
sizeBytes: number;
checksumSha256: string;
};
type PutObject = (input: { bucket: string; key: string; body: Uint8Array; contentType?: string }) => Promise<unknown>;
type DeleteObject = (input: { bucket: string; key: string }) => Promise<unknown>;
type SeedS3Client = {
send(command: unknown): Promise<unknown>;
};
function printableAscii(value: string): string {
return value
.normalize("NFKD")
.replace(/[\u0300-\u036f]/gu, "")
.replace(/[^\x20-\x7E]/gu, "?")
.replace(/\s+/gu, " ")
.trim();
}
function escapePdfLiteral(value: string): string {
return printableAscii(value).replace(/([\\()])/gu, "\\$1");
}
function wrapText(value: string, maxLength = 72): string[] {
const words = printableAscii(value).split(" ").filter(Boolean);
const lines: string[] = [];
let line = "";
for (const word of words) {
if (line.length === 0) {
line = word;
continue;
}
if (line.length + word.length + 1 <= maxLength) {
line += ` ${word}`;
continue;
}
lines.push(line);
line = word;
}
if (line.length > 0) lines.push(line);
return lines.length > 0 ? lines : ["Projektunterlage"];
}
function byteLength(value: string): number {
return encoder.encode(value).byteLength;
}
/** Builds a deterministic, single-page PDF whose xref offsets match its exact bytes. */
export function buildSeedPdfBytes(file: SeedFileObjectDescriptor): Uint8Array {
const title = escapePdfLiteral(file.displayName);
const detailLines = wrapText(file.notes).slice(0, 6).map(escapePdfLiteral);
const content = [
"BT",
"/F1 18 Tf",
"72 770 Td",
`(${title}) Tj`,
"/F1 11 Tf",
...detailLines.flatMap((line) => ["0 -24 Td", `(${line}) Tj`]),
"0 -36 Td",
`(Dokument-ID: ${escapePdfLiteral(file.id)}) Tj`,
"ET",
"",
].join("\n");
const objects = [
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
`<< /Length ${byteLength(content)} >>\nstream\n${content}endstream`,
];
let pdf = "%PDF-1.4\n% HiveGrid generated staging document\n";
const offsets = [0];
for (const [index, object] of objects.entries()) {
offsets.push(byteLength(pdf));
pdf += `${index + 1} 0 obj\n${object}\nendobj\n`;
}
const xrefOffset = byteLength(pdf);
pdf += `xref\n0 ${objects.length + 1}\n`;
pdf += "0000000000 65535 f \n";
pdf += offsets
.slice(1)
.map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)
.join("");
pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
return encoder.encode(pdf);
}
export function buildSeedFileObjectMetadata(file: SeedFileObjectDescriptor): SeedFileObjectMetadata {
const bytes = buildSeedPdfBytes(file);
return {
...file,
mimeType: PDF_CONTENT_TYPE,
sizeBytes: bytes.byteLength,
checksumSha256: createHash("sha256").update(bytes).digest("hex"),
};
}
export function seedFileStorageKey(tenantId: string, fileId: string): string {
return buildFileStorageKeys(tenantId, fileId).original;
}
export function seedFileStoragePrefix(tenantId: string): string {
const probe = seedFileStorageKey(tenantId, "seed-prefix-probe");
return probe.slice(0, -"seed-prefix-probe/original".length);
}
function createSeedS3Client(): SeedS3Client {
const binding = resolveStorageBinding();
const { storage } = loadRequiredWebConfig();
if (binding.provider !== "s3" || !storage.endpoint || !storage.region || !storage.accessKeyId || !storage.secretAccessKey) {
throw new Error("demo-pro seed files: complete S3 staging storage configuration is required");
}
return new S3Client({
endpoint: storage.endpoint,
region: storage.region,
credentials: {
accessKeyId: storage.accessKeyId,
secretAccessKey: storage.secretAccessKey,
sessionToken: storage.sessionToken,
},
forcePathStyle: storage.forcePathStyle?.toLowerCase() === "true",
}) as unknown as SeedS3Client;
}
async function storageBodyBytes(body: unknown): Promise<Uint8Array> {
if (!body || typeof (body as { transformToByteArray?: unknown }).transformToByteArray !== "function") {
throw new Error("demo-pro seed files: storage object body is unreadable");
}
return (body as { transformToByteArray(): Promise<Uint8Array> }).transformToByteArray();
}
function assertConcurrency(concurrency: number): void {
if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 64) {
throw new Error("demo-pro seed files: concurrency must be an integer between 1 and 64");
}
}
async function forEachConcurrent<T>(items: readonly T[], concurrency: number, worker: (item: T) => Promise<void>): Promise<void> {
assertConcurrency(concurrency);
let nextIndex = 0;
let failed = false;
let failure: unknown;
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (!failed && nextIndex < items.length) {
const index = nextIndex;
nextIndex += 1;
try {
await worker(items[index]!);
} catch (error) {
if (!failed) failure = error;
failed = true;
}
}
});
await Promise.all(workers);
if (failed) throw failure;
}
function assertMetadataMatches(file: PersistedSeedFileObject, bytes: Uint8Array): void {
const checksumSha256 = createHash("sha256").update(bytes).digest("hex");
if (file.mimeType !== PDF_CONTENT_TYPE || file.sizeBytes !== bytes.byteLength || file.checksumSha256 !== checksumSha256) {
throw new Error(`demo-pro seed files: generated PDF metadata drifted for ${file.id}`);
}
}
export async function uploadDemoProSeedFileObjects({
tenantId,
files,
concurrency = DEFAULT_STORAGE_CONCURRENCY,
bucket = resolveStorageBucket(),
putObject = putBufferAsFile,
}: {
tenantId: string;
files: readonly PersistedSeedFileObject[];
concurrency?: number;
bucket?: string;
putObject?: PutObject;
}): Promise<{ bucket: string; uploaded: number }> {
await forEachConcurrent(files, concurrency, async (file) => {
const bytes = buildSeedPdfBytes(file);
assertMetadataMatches(file, bytes);
await putObject({
bucket,
key: seedFileStorageKey(tenantId, file.id),
body: bytes,
contentType: PDF_CONTENT_TYPE,
});
});
return { bucket, uploaded: files.length };
}
export async function verifyDemoProSeedFileObjects({
tenantId,
files,
concurrency = DEFAULT_STORAGE_CONCURRENCY,
bucket = resolveStorageBucket(),
client = createSeedS3Client(),
}: {
tenantId: string;
files: readonly PersistedSeedFileObject[];
concurrency?: number;
bucket?: string;
client?: SeedS3Client;
}): Promise<{ bucket: string; verified: number }> {
const prefix = seedFileStoragePrefix(tenantId);
const expectedKeys = new Set(files.map((file) => seedFileStorageKey(tenantId, file.id)));
if (expectedKeys.size !== files.length) {
throw new Error("demo-pro seed files: expected storage keys are not unique");
}
const observedKeys = new Set<string>();
let continuationToken: string | undefined;
do {
const page = (await client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken: continuationToken, MaxKeys: 1_000 }))) as {
Contents?: Array<{ Key?: string }>;
IsTruncated?: boolean;
NextContinuationToken?: string;
};
for (const object of page.Contents ?? []) {
if (!object.Key) throw new Error("demo-pro seed files: storage listing returned an object without a key");
if (!object.Key.startsWith(prefix)) {
throw new Error("demo-pro seed files: storage listing returned a key outside the tenant file prefix");
}
if (!expectedKeys.has(object.Key)) {
throw new Error(`demo-pro seed files: unexpected storage object ${object.Key}`);
}
if (observedKeys.has(object.Key)) {
throw new Error(`demo-pro seed files: storage listing returned duplicate object ${object.Key}`);
}
observedKeys.add(object.Key);
}
if (page.IsTruncated && !page.NextContinuationToken) {
throw new Error("demo-pro seed files: truncated storage listing has no continuation token");
}
continuationToken = page.IsTruncated ? page.NextContinuationToken : undefined;
} while (continuationToken);
for (const expectedKey of expectedKeys) {
if (!observedKeys.has(expectedKey)) throw new Error(`demo-pro seed files: missing storage object ${expectedKey}`);
}
await forEachConcurrent(files, concurrency, async (file) => {
const result = (await client.send(new GetObjectCommand({ Bucket: bucket, Key: seedFileStorageKey(tenantId, file.id) }))) as {
Body?: unknown;
ContentLength?: number;
};
const bytes = await storageBodyBytes(result.Body);
assertMetadataMatches(file, bytes);
if (result.ContentLength !== undefined && result.ContentLength !== bytes.byteLength) {
throw new Error(`demo-pro seed files: storage size drifted for ${file.id}`);
}
});
return { bucket, verified: files.length };
}
export async function deleteDemoProTenantFileObjects({
tenantId,
bucket = resolveStorageBucket(),
client = createSeedS3Client(),
}: {
tenantId: string;
bucket?: string;
client?: SeedS3Client;
}): Promise<{ bucket: string; deleted: number }> {
const prefix = seedFileStoragePrefix(tenantId);
let deleted = 0;
let previousFirstKey: string | undefined;
while (true) {
const page = (await client.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, MaxKeys: 1_000 }))) as {
Contents?: Array<{ Key?: string }>;
IsTruncated?: boolean;
NextContinuationToken?: string;
};
const pageKeys = (page.Contents ?? []).map(({ Key }) => {
if (!Key) throw new Error("demo-pro seed files: storage listing returned an object without a key");
return Key;
});
if (pageKeys.some((key) => !key.startsWith(prefix))) {
throw new Error("demo-pro seed files: storage listing returned a key outside the tenant file prefix");
}
if (pageKeys.length > 1_000 || new Set(pageKeys).size !== pageKeys.length) {
throw new Error("demo-pro seed files: storage listing returned an invalid cleanup page");
}
if (pageKeys.length === 0) {
if (page.IsTruncated) throw new Error("demo-pro seed files: truncated storage listing returned no objects");
break;
}
if (pageKeys[0] === previousFirstKey) {
throw new Error("demo-pro seed files: storage prefix cleanup made no progress");
}
previousFirstKey = pageKeys[0];
const result = (await client.send(
new DeleteObjectsCommand({
Bucket: bucket,
Delete: { Objects: pageKeys.map((Key) => ({ Key })), Quiet: true },
})
)) as { Errors?: unknown[] };
if ((result.Errors?.length ?? 0) > 0) throw new Error("demo-pro seed files: storage prefix cleanup failed");
deleted += pageKeys.length;
}
return { bucket, deleted };
}
export async function deleteDemoProSeedFileObjects({
tenantId,
files,
concurrency = DEFAULT_STORAGE_CONCURRENCY,
bucket = resolveStorageBucket(),
deleteObject = deleteFile,
storageConfigured = hasStorageCredentials,
}: {
tenantId: string;
files: readonly Pick<PersistedSeedFileObject, "id">[];
concurrency?: number;
bucket?: string;
deleteObject?: DeleteObject;
storageConfigured?: () => boolean;
}): Promise<{ bucket: string; deleted: number }> {
if (!storageConfigured()) throw new Error("demo-pro seed files: storage provider is not configured");
await forEachConcurrent(files, concurrency, async (file) => {
await deleteObject({ bucket, key: seedFileStorageKey(tenantId, file.id) });
});
return { bucket, deleted: files.length };
}
@@ -0,0 +1,170 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { LEAD_OUTCOME_COUNTS, OFFICE_ROLE_COUNTS, PROJECT_TYPE_COUNTS } from "./catalog";
import { generateDemoProSeed, validateDemoProSeedGraph } from "./generator";
import { DEMO_PRO_SEED_NAMESPACE } from "./types";
function frequencies(values: readonly string[]): Record<string, number> {
return values.reduce<Record<string, number>>((result, value) => {
result[value] = (result[value] ?? 0) + 1;
return result;
}, {});
}
describe("demo-pro Rhein-Main seed generator", () => {
it("generates the exact employee structure with realistic odd staffing and crews", () => {
const graph = generateDemoProSeed();
const officeEmployees = graph.employees.filter((employee) => employee.seatCategory === "office");
const fieldEmployees = graph.employees.filter((employee) => employee.seatCategory === "field");
expect(graph.employees).toHaveLength(50);
expect(officeEmployees).toHaveLength(17);
expect(fieldEmployees).toHaveLength(33);
expect(frequencies(officeEmployees.map((employee) => employee.role))).toEqual(
Object.fromEntries(OFFICE_ROLE_COUNTS.map(({ role, count }) => [role, count]))
);
expect(graph.crews).toHaveLength(16);
expect(frequencies(graph.crews.map((crew) => String(crew.memberEmployeeIds.length)))).toEqual({ "2": 15, "3": 1 });
expect(new Set(graph.crews.flatMap((crew) => crew.memberEmployeeIds)).size).toBe(33);
expect(fieldEmployees.every((employee) => graph.crews.some((crew) => crew.id === employee.crewId && crew.memberEmployeeIds.includes(employee.id)))).toBe(
true
);
});
it("keeps every globally persisted v1 employee identity stable across staffing changes", () => {
const employees = generateDemoProSeed().employees;
const serializedIdentities = employees.map(({ id, firstName, lastName, email }) => [id, firstName, lastName, email].join("|")).join("\n");
expect(createHash("sha256").update(serializedIdentities).digest("hex")).toBe("507aaa29467a9b830d447552af41071aa0e1bd109257c9c41dead3e7eccb5877");
expect(employees.slice(16, 21).map(({ id, firstName, lastName, email, seatCategory }) => ({ id, firstName, lastName, email, seatCategory }))).toEqual([
{
id: "rheinmain-shk-v1-employee-0017",
firstName: "Bianca",
lastName: "Schmitz",
email: "bianca.schmitz.17@mitarbeiter.example.test",
seatCategory: "office",
},
{
id: "rheinmain-shk-v1-employee-0018",
firstName: "Dennis",
lastName: "Köhler",
email: "dennis.kohler.18@mitarbeiter.example.test",
seatCategory: "field",
},
{
id: "rheinmain-shk-v1-employee-0019",
firstName: "Heike",
lastName: "Hoffmann",
email: "heike.hoffmann.19@mitarbeiter.example.test",
seatCategory: "field",
},
{
id: "rheinmain-shk-v1-employee-0020",
firstName: "Oliver",
lastName: "Schröder",
email: "oliver.schroder.20@mitarbeiter.example.test",
seatCategory: "field",
},
{
id: "rheinmain-shk-v1-employee-0021",
firstName: "Miriam",
lastName: "Wagner",
email: "miriam.wagner.21@mitarbeiter.example.test",
seatCategory: "field",
},
]);
});
it("builds the full realistic contact and project volume", () => {
const graph = generateDemoProSeed();
expect(graph.organizations).toHaveLength(247);
expect(graph.persons).toHaveLength(536);
expect(graph.contactRelations).toHaveLength(421);
expect(graph.projects).toHaveLength(537);
expect(frequencies(graph.projects.map((project) => project.projectType))).toEqual(PROJECT_TYPE_COUNTS);
expect(new Set(graph.organizations.map((organization) => organization.branche)).size).toBeGreaterThanOrEqual(12);
expect(new Set(graph.persons.map((person) => `${person.firstName} ${person.lastName}`)).size).toBeGreaterThan(100);
expect(graph.projects.every((project) => project.description.length > 100 && project.contacts.length >= 3)).toBe(true);
expect(
graph.organizations.every((organization) => {
const locationToken = organization.address.ort.replace(" am Main", "").replace(" vor der Höhe", "");
return organization.orgName.includes(locationToken);
})
).toBe(true);
});
it("uses the requested exact lead outcomes and complete conversion links", () => {
const graph = generateDemoProSeed();
const converted = graph.leads.filter((lead) => lead.outcome === "converted");
expect(graph.leads).toHaveLength(193);
expect(frequencies(graph.leads.map((lead) => lead.outcome))).toEqual(LEAD_OUTCOME_COUNTS);
expect(converted).toHaveLength(116);
expect(converted.every((lead) => lead.linkedContactId && lead.convertedProjectId && lead.convertedAt)).toBe(true);
expect(graph.projects.filter((project) => project.convertedFromLeadId)).toHaveLength(116);
expect(
converted.every((lead) => {
const project = graph.projects.find(({ id }) => id === lead.convertedProjectId)!;
return new Date(lead.createdAt) < new Date(lead.convertedAt!) && new Date(lead.convertedAt!) <= new Date(project.createdAt);
})
).toBe(true);
expect(graph.leads.every((lead) => !lead.lostAt || new Date(lead.lostAt) <= new Date(graph.referenceDate))).toBe(true);
});
it("keeps every project lifecycle chronologically plausible", () => {
const graph = generateDemoProSeed();
const referenceDate = new Date(graph.referenceDate);
expect(graph.projects.every((project) => !project.startDate || new Date(project.createdAt) < new Date(project.startDate))).toBe(true);
expect(graph.projects.every((project) => new Date(project.createdAt) < new Date(project.deadline))).toBe(true);
expect(graph.projects.every((project) => !project.startDate || new Date(project.startDate) < new Date(project.deadline))).toBe(true);
expect(
graph.projects.every((project) => !project.wonAt || (new Date(project.createdAt) < new Date(project.wonAt) && new Date(project.wonAt) <= referenceDate))
).toBe(true);
expect(
graph.projects.every(
(project) => !project.lostAt || (new Date(project.createdAt) < new Date(project.lostAt) && new Date(project.lostAt) <= referenceDate)
)
).toBe(true);
});
it("keeps every external contact channel non-routable and every ID namespaced", () => {
const graph = generateDemoProSeed();
const ids = [
...graph.employees.map(({ id }) => id),
...graph.crews.map(({ id }) => id),
...graph.organizations.map(({ id }) => id),
...graph.persons.map(({ id }) => id),
...graph.contactRelations.map(({ id }) => id),
...graph.projects.map(({ id }) => id),
...graph.leads.map(({ id }) => id),
];
const emails = [
...graph.employees.map(({ email }) => email),
...graph.organizations.flatMap((organization) => [organization.email, ...organization.additionalEmails.map(({ value }) => value)]),
...graph.persons.flatMap((person) => [person.email, ...person.additionalEmails.map(({ value }) => value)]),
...graph.leads.map(({ email }) => email),
];
const phones = [
...graph.employees.map(({ phone }) => phone),
...graph.organizations.flatMap((organization) => [organization.phone, ...organization.additionalPhones.map(({ value }) => value)]),
...graph.persons.flatMap((person) => [person.phone, ...person.additionalPhones.map(({ value }) => value)]),
...graph.leads.map(({ phone }) => phone),
];
expect(ids.every((id) => id.startsWith(`${DEMO_PRO_SEED_NAMESPACE}-`))).toBe(true);
expect(new Set(ids).size).toBe(ids.length);
expect(emails.every((email) => email.endsWith(".example.test"))).toBe(true);
expect(phones.every((phone) => /^\+496990009\d{3}$/.test(phone))).toBe(true);
});
it("is byte-for-byte deterministic and passes its integrity validator", () => {
const first = generateDemoProSeed();
const second = generateDemoProSeed();
expect(second).toEqual(first);
expect(validateDemoProSeedGraph(first)).toEqual({ valid: true, errors: [] });
});
});
@@ -0,0 +1,628 @@
import {
EMPLOYEE_IDENTITIES_V1,
FEMALE_FIRST_NAMES,
LAST_NAMES,
LEAD_OUTCOME_COUNTS,
LOCATIONS,
MALE_FIRST_NAMES,
OFFICE_ROLE_COUNTS,
ORDER_STAGE_COUNTS,
ORGANIZATION_ROOTS,
ORGANIZATION_SECTORS,
PROJECT_TYPE_COUNTS,
PROJECT_TYPE_DETAILS,
REFERENCE_DATE,
SALES_STAGE_COUNTS,
STREET_PREFIXES,
STREET_SUFFIXES,
} from "./catalog";
import {
DEMO_PRO_SEED_NAMESPACE,
type DemoProSeedGraph,
type EmployeeRole,
type LeadOutcome,
type SeedAddress,
type SeedContactRelation,
type SeedCrew,
type SeedEmployee,
type SeedLead,
type SeedOrganization,
type SeedPerson,
type SeedProject,
type SeedValidationResult,
} from "./types";
const ID_PREFIX = `${DEMO_PRO_SEED_NAMESPACE}-`;
const OFFICE_EMPLOYEE_COUNT = 17;
const FIELD_EMPLOYEE_COUNT = 33;
const TWO_PERSON_CREW_COUNT = 15;
const CREW_COUNT = 16;
const ORGANIZATION_COUNT = 247;
const PERSON_COUNT = 536;
const BUSINESS_PERSON_COUNT = 421;
const PROJECT_COUNT = 537;
const LEAD_COUNT = 193;
function deterministicShuffle<T>(values: readonly T[], seed: number): T[] {
const result = [...values];
let state = seed >>> 0;
for (let index = result.length - 1; index > 0; index -= 1) {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
const swapIndex = state % (index + 1);
[result[index], result[swapIndex]] = [result[swapIndex]!, result[index]!];
}
return result;
}
function seedId(kind: string, index: number): string {
return `${ID_PREFIX}${kind}-${String(index + 1).padStart(4, "0")}`;
}
function dramaPhone(index: number): string {
if (index < 0 || index > 999) {
throw new Error(`Drama-number index ${index} is outside the reserved 000-999 range.`);
}
return `+496990009${String(index).padStart(3, "0")}`;
}
function emailPart(value: string): string {
return value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/ß/g, "ss")
.toLowerCase()
.replace(/[^a-z0-9]+/g, ".")
.replace(/^\.|\.$/g, "");
}
function addDays(isoDate: string, days: number): string {
const date = new Date(isoDate);
date.setUTCDate(date.getUTCDate() + days);
return date.toISOString();
}
function earlierDate(first: string, second: string): string {
return new Date(first) <= new Date(second) ? first : second;
}
function laterDate(first: string, second: string): string {
return new Date(first) >= new Date(second) ? first : second;
}
function money(value: number): string {
return value.toFixed(2);
}
function makeAddress(index: number): SeedAddress {
const location = LOCATIONS[(index * 7) % LOCATIONS.length]!;
const prefix = STREET_PREFIXES[(index * 11) % STREET_PREFIXES.length]!;
const suffix = STREET_SUFFIXES[(index * 5) % STREET_SUFFIXES.length]!;
const baseNumber = 1 + ((index * 17) % 184);
const numberSuffix = index % 19 === 0 ? "a" : index % 31 === 0 ? "b" : "";
return {
strasse: `${prefix}${suffix}`,
hausnummer: `${baseNumber}${numberSuffix}`,
plz: location.plz,
ort: location.ort,
land: "DE",
};
}
function employeeGroups(role: EmployeeRole, crewName?: string): string[] {
const groupByRole: Record<EmployeeRole, string> = {
Geschäftsführer: "Geschäftsführung",
Vertriebsleiter: "Vertrieb",
Vertriebler: "Vertrieb",
"Büro/Backoffice": "Backoffice",
Marketing: "Marketing",
"Projektleiter/Bauleiter": "Projektleitung",
Monteur: "Montage",
};
return crewName ? [groupByRole[role], crewName] : [groupByRole[role]];
}
function generateEmployees(): { employees: SeedEmployee[]; crews: SeedCrew[] } {
const employees: SeedEmployee[] = [];
const officeRoles = OFFICE_ROLE_COUNTS.flatMap(({ role, count, jobTitle }) => Array.from({ length: count }, () => ({ role, jobTitle })));
officeRoles.forEach(({ role, jobTitle }, index) => {
const { firstName, lastName } = EMPLOYEE_IDENTITIES_V1[index]!;
employees.push({
id: seedId("employee", index),
firstName,
lastName,
email: `${emailPart(firstName)}.${emailPart(lastName)}.${String(index + 1).padStart(2, "0")}@mitarbeiter.example.test`,
phone: dramaPhone(index),
role,
jobTitle,
seatCategory: "office",
groupNames: employeeGroups(role),
crewId: null,
active: true,
locale: "de",
});
});
for (let fieldIndex = 0; fieldIndex < FIELD_EMPLOYEE_COUNT; fieldIndex += 1) {
const index = OFFICE_EMPLOYEE_COUNT + fieldIndex;
const { firstName, lastName } = EMPLOYEE_IDENTITIES_V1[index]!;
const crewIndex = Math.min(Math.floor(fieldIndex / 2), CREW_COUNT - 1);
const crewId = seedId("crew", crewIndex);
const crewName = `Montageteam ${String(crewIndex + 1).padStart(2, "0")}`;
employees.push({
id: seedId("employee", index),
firstName,
lastName,
email: `${emailPart(firstName)}.${emailPart(lastName)}.${String(index + 1).padStart(2, "0")}@mitarbeiter.example.test`,
phone: dramaPhone(index),
role: "Monteur",
jobTitle: fieldIndex % 6 === 0 ? "Kundendiensttechniker SHK" : fieldIndex % 4 === 0 ? "Anlagenmechaniker SHK, Obermonteur" : "Anlagenmechaniker SHK",
seatCategory: "field",
groupNames: employeeGroups("Monteur", crewName),
crewId,
active: true,
locale: "de",
});
}
const projectManagers = employees.filter((employee) => employee.role === "Projektleiter/Bauleiter");
const crews: SeedCrew[] = Array.from({ length: CREW_COUNT }, (_, index) => {
const crewId = seedId("crew", index);
return {
id: crewId,
name: `Montageteam ${String(index + 1).padStart(2, "0")}`,
memberEmployeeIds: employees.filter((employee) => employee.crewId === crewId).map(({ id }) => id),
projectManagerEmployeeId: projectManagers[index % projectManagers.length]!.id,
};
});
return { employees, crews };
}
function organizationLegalForm(index: number, sector: string): Pick<SeedOrganization, "orgMerkmal"> & { suffix: string } {
if (sector === "Kommunale Einrichtung") {
return { orgMerkmal: "oeffentliche_einrichtung", suffix: "Eigenbetrieb" };
}
if (index % 11 === 0) {
return { orgMerkmal: "kg", suffix: "GmbH & Co. KG" };
}
if (index % 7 === 0) {
return { orgMerkmal: "sonstige", suffix: "eG" };
}
return { orgMerkmal: "gmbh", suffix: "GmbH" };
}
function generateOrganizations(employees: readonly SeedEmployee[]): SeedOrganization[] {
const owners = employees.filter((employee) => employee.role === "Vertriebler" || employee.role === "Büro/Backoffice");
return Array.from({ length: ORGANIZATION_COUNT }, (_, index) => {
const sector = ORGANIZATION_SECTORS[(index * 7) % ORGANIZATION_SECTORS.length]!;
const root = ORGANIZATION_ROOTS[(index * 11) % ORGANIZATION_ROOTS.length]!;
const address = makeAddress(index);
const legalForm = organizationLegalForm(index, sector);
const locationToken = address.ort.replace(" am Main", "").replace(" vor der Höhe", "");
const orgName =
sector === "Kommunale Einrichtung" ? `${root} ${locationToken} ${legalForm.suffix}` : `${root} ${sector} ${locationToken} ${legalForm.suffix}`;
const emailToken = `betrieb-${String(index + 1).padStart(3, "0")}`;
return {
id: seedId("organization", index),
kontaktTyp: "organisation",
orgName,
orgMerkmal: legalForm.orgMerkmal,
branche: sector,
kontaktStatus: index % 5 === 0 ? "kontakt" : index % 3 === 0 ? "kunde" : "bestandskunde",
email: `kontakt@${emailToken}.example.test`,
phone: dramaPhone(50 + index),
additionalEmails: index % 4 === 0 ? [{ value: `rechnung@${emailToken}.example.test`, primaer: false, label: "rechnung" }] : [],
additionalPhones: index % 7 === 0 ? [{ value: dramaPhone(910 + Math.floor(index / 7)), primaer: false, label: "zentrale" }] : [],
address,
language: "de",
ownerEmployeeId: owners[index % owners.length]!.id,
tags: sector === "Hausverwaltung" || sector === "Wohnungswirtschaft" ? ["B2B", "Rahmenkunde"] : index % 4 === 0 ? ["B2B", "Wartungsvertrag"] : ["B2B"],
};
});
}
function generatePersons(employees: readonly SeedEmployee[], organizations: readonly SeedOrganization[]): SeedPerson[] {
const owners = employees.filter((employee) => employee.role === "Vertriebler" || employee.role === "Büro/Backoffice");
return Array.from({ length: PERSON_COUNT }, (_, index) => {
const female = index % 2 === 0;
const firstNames = female ? FEMALE_FIRST_NAMES : MALE_FIRST_NAMES;
const firstName = firstNames[(Math.floor(index / 2) * 7 + 3) % firstNames.length]!;
const lastName = LAST_NAMES[(index * 11 + 2) % LAST_NAMES.length]!;
const businessContact = index < BUSINESS_PERSON_COUNT;
const address = businessContact ? organizations[index % organizations.length]!.address : makeAddress(400 + index);
const emailToken = `${emailPart(firstName)}.${emailPart(lastName)}.${String(index + 1).padStart(3, "0")}`;
return {
id: seedId("person", index),
kontaktTyp: "privatperson",
firstName,
lastName,
salutation: female ? "Frau" : "Herr",
kontaktStatus: businessContact ? (index % 4 === 0 ? "kunde" : "kontakt") : index % 3 === 0 ? "bestandskunde" : "kunde",
email: `${emailToken}@kunden.example.test`,
phone: dramaPhone(297 + index),
additionalEmails: index % 11 === 0 ? [{ value: `${emailToken}@privat.example.test`, primaer: false, label: "privat" }] : [],
additionalPhones: [],
address,
language: "de",
ownerEmployeeId: owners[(index * 5) % owners.length]!.id,
tags: businessContact ? ["Ansprechpartner"] : index % 5 === 0 ? ["Privatkunde", "Wartung"] : ["Privatkunde"],
};
});
}
function generateContactRelations(): SeedContactRelation[] {
const jobContexts = ["Technische Leitung", "Kaufmännische Leitung", "Objektbetreuung", "Geschäftsführung", "Haustechnik", "Einkauf"] as const;
return Array.from({ length: BUSINESS_PERSON_COUNT }, (_, index) => ({
id: seedId("contact-relation", index),
organizationId: seedId("organization", index % ORGANIZATION_COUNT),
personId: seedId("person", index),
role: index < ORGANIZATION_COUNT ? "hauptkontakt" : index % 4 === 0 ? "sekundaerkontakt" : "mitarbeiter",
context: jobContexts[(index * 5) % jobContexts.length]!,
}));
}
function expandCounts<T extends string>(counts: Readonly<Record<T, number>>): T[] {
return Object.entries(counts).flatMap(([value, count]) => Array.from({ length: count as number }, () => value as T));
}
function projectContactName(projectContacts: SeedProject["contacts"], organizations: readonly SeedOrganization[], persons: readonly SeedPerson[]): string {
const primaryId = projectContacts.find((contact) => contact.primary)?.contactId ?? projectContacts[0]!.contactId;
const organization = organizations.find((contact) => contact.id === primaryId);
if (organization) return organization.orgName.replace(/ (GmbH|GmbH & Co\. KG|eG|Eigenbetrieb)$/, "");
const person = persons.find((contact) => contact.id === primaryId)!;
return `${person.lastName}`;
}
function generateProjects(
employees: readonly SeedEmployee[],
crews: readonly SeedCrew[],
organizations: readonly SeedOrganization[],
persons: readonly SeedPerson[]
): SeedProject[] {
const projectManagers = employees.filter((employee) => employee.role === "Projektleiter/Bauleiter");
const backoffice = employees.filter((employee) => employee.role === "Büro/Backoffice");
const projectTypes = deterministicShuffle(expandCounts(PROJECT_TYPE_COUNTS), 0x524d2026);
const salesStages = deterministicShuffle(expandCounts(SALES_STAGE_COUNTS), 0x53414c45);
const orderStages = deterministicShuffle(expandCounts(ORDER_STAGE_COUNTS), 0x4f524445);
const sources = ["Bestandskunde", "Empfehlung", "Website", "Telefon", "Partner", "Ausschreibung"] as const;
const lostReasons = ["Preisentscheidung", "Zeitfenster nicht passend", "Bestandsanlage wird weiterbetrieben", "Wettbewerber beauftragt"] as const;
return Array.from({ length: PROJECT_COUNT }, (_, index) => {
const projectType = projectTypes[index]!;
const details = PROJECT_TYPE_DETAILS[projectType];
const pipeline = index < salesStages.length ? "sales" : "auftrag";
const stage = pipeline === "sales" ? salesStages[index]! : orderStages[index - salesStages.length]!;
const privateCustomer = (index * 73) % PROJECT_COUNT < 322;
const organization = privateCustomer ? null : organizations[(index * 31) % organizations.length]!;
const person = privateCustomer
? persons[BUSINESS_PERSON_COUNT + ((index * 37) % (PERSON_COUNT - BUSINESS_PERSON_COUNT))]!
: persons[(index * 31) % ORGANIZATION_COUNT]!;
const contacts: SeedProject["contacts"] = organization
? [
{ contactId: organization.id, role: "auftraggeber", primary: true },
{ contactId: organization.id, role: "rechnungsempfaenger", primary: false },
{ contactId: person.id, role: "ansprechpartner", primary: false },
]
: [
{ contactId: person.id, role: "auftraggeber", primary: true },
{ contactId: person.id, role: "bauherr", primary: false },
{ contactId: person.id, role: "rechnungsempfaenger", primary: false },
];
const customerAddress = organization?.address ?? person.address;
const projectAddress = organization && index % 3 !== 0 ? makeAddress(1100 + index) : customerAddress;
const valueSpan = details.maxValue - details.minValue;
const rawValue = details.minValue + ((index * 7919) % (valueSpan + 1));
const roundedValue = rawValue < 5000 ? Math.round(rawValue / 10) * 10 : Math.round(rawValue / 100) * 100;
const duration = details.durationDays[0] + ((index * 11) % (details.durationDays[1] - details.durationDays[0] + 1));
const won = stage === "gewonnen" || stage === "abgeschlossen";
const lost = stage === "verloren" || stage === "storniert";
const desiredStartDate =
pipeline === "sales" && !won
? null
: stage === "abgeschlossen"
? addDays(REFERENCE_DATE, -(duration + 1 + ((index * 17) % 180)))
: stage === "montage"
? addDays(REFERENCE_DATE, -((index * 7) % Math.max(1, duration)))
: stage === "abnahme"
? addDays(REFERENCE_DATE, -Math.max(1, duration - 1))
: stage === "storniert"
? addDays(REFERENCE_DATE, -(2 + (index % 45)))
: addDays(REFERENCE_DATE, 5 + ((index * 13) % 120));
const rawCreatedAt = addDays(REFERENCE_DATE, -((index * 37) % 822));
const createdAt = desiredStartDate ? earlierDate(rawCreatedAt, addDays(desiredStartDate, -(3 + (index % 27)))) : rawCreatedAt;
const startDate = desiredStartDate ? laterDate(desiredStartDate, addDays(createdAt, 1)) : null;
const deadline = startDate ? addDays(startDate, duration) : laterDate(addDays(REFERENCE_DATE, 7 + ((index * 19) % 90)), addDays(createdAt, 7));
const wonAt = won && startDate ? earlierDate(REFERENCE_DATE, laterDate(addDays(createdAt, 1), addDays(startDate, -(2 + (index % 14))))) : null;
const lostAt = lost ? earlierDate(REFERENCE_DATE, addDays(createdAt, 3 + (index % 28))) : null;
const manager = projectManagers[index % projectManagers.length]!;
const primaryCrew = crews[index % crews.length]!;
const crewIds = projectType === "objekt_neubau" && index % 2 === 0 ? [primaryCrew.id, crews[(index + 4) % crews.length]!.id] : [primaryCrew.id];
const contactName = projectContactName(contacts, organizations, persons);
return {
id: seedId("project", index),
projectNumber: `RM-${new Date(createdAt).getUTCFullYear()}-${String(700001 + index)}`,
projectName: `${details.label} ${contactName}`,
description: `${details.descriptions[index % details.descriptions.length]}. Ausführung im Raum ${projectAddress.ort}; Abstimmung, Dokumentation und Einweisung sind im Leistungsumfang berücksichtigt.`,
projectType,
source: sources[(index * 5) % sources.length]!,
priority:
projectType === "reparatur_notdienst" && index % 3 === 0
? "dringend"
: projectType === "objekt_neubau" || index % 11 === 0
? "hoch"
: index % 17 === 0
? "niedrig"
: "normal",
pipeline,
stage,
potentialOrderValue: pipeline === "sales" ? money(roundedValue) : null,
orderVolume: pipeline === "auftrag" || won ? money(roundedValue) : null,
createdAt,
startDate,
deadline,
responsibleEmployeeId: backoffice[index % backoffice.length]!.id,
projectManagerEmployeeId: manager.id,
crewIds,
projectAddress,
invoiceAddress: customerAddress,
clientAddress: customerAddress,
convertedFromLeadId: null,
lostReason: lost ? lostReasons[index % lostReasons.length]! : null,
wonAt,
lostAt,
contacts,
tags:
projectType === "reparatur_notdienst"
? ["Kundendienst", "Zeitkritisch"]
: projectType === "wartung_pruefung"
? ["Wartung"]
: organization
? ["B2B", "Projektgeschäft"]
: ["Privatkunde", "Projektgeschäft"],
};
});
}
function leadMessage(outcome: LeadOutcome, project?: SeedProject): string {
if (outcome === "spam") return "Angebot für Suchmaschinenoptimierung und günstige Firmenkredite. Bitte sofort zurückrufen.";
if (outcome === "converted" && project)
return `Bitte um Beratung und Terminabstimmung für ${PROJECT_TYPE_DETAILS[project.projectType].label.toLowerCase()} am Objekt in ${project.projectAddress.ort}.`;
if (outcome === "offer_lost") return "Vielen Dank für das Angebot. Nach interner Abstimmung haben wir uns für eine andere Ausführung entschieden.";
return "Wir möchten die technische Machbarkeit und einen passenden Vor-Ort-Termin klären. Bitte um Rückmeldung.";
}
function generateLeads(employees: readonly SeedEmployee[], persons: readonly SeedPerson[], projects: SeedProject[]): SeedLead[] {
const salesOwners = employees.filter((employee) => employee.role === "Vertriebler" || employee.role === "Vertriebsleiter");
const outcomes = deterministicShuffle(expandCounts(LEAD_OUTCOME_COUNTS), 0x4c454144);
const sources = ["form", "email", "aircall", "manual", "custom"] as const;
const sourceOrigins = ["Website Kontaktformular", "E-Mail Eingang", "Telefonzentrale", "Manuelle Erfassung", "Partnerportal"] as const;
const disqualifiedReasons = ["Objekt außerhalb des Einsatzgebiets", "Leistungsumfang nicht passend", "Terminwunsch nicht realisierbar"] as const;
let convertedProjectIndex = 0;
let externalPhoneIndex = 833;
return outcomes.map((outcome, index) => {
const convertedProject = outcome === "converted" ? projects[convertedProjectIndex++]! : null;
const linkedPersonId = convertedProject?.contacts.find((contact) => contact.contactId.includes("-person-"))?.contactId ?? null;
const linkedPerson = linkedPersonId ? persons.find((person) => person.id === linkedPersonId)! : null;
const female = index % 2 === 0;
const firstName =
linkedPerson?.firstName ??
(female ? FEMALE_FIRST_NAMES[(index * 3) % FEMALE_FIRST_NAMES.length]! : MALE_FIRST_NAMES[(index * 3) % MALE_FIRST_NAMES.length]!);
const lastName = linkedPerson?.lastName ?? LAST_NAMES[(index * 13) % LAST_NAMES.length]!;
const createdAt = convertedProject ? addDays(convertedProject.createdAt, -3 - (index % 18)) : addDays(REFERENCE_DATE, -((index * 23) % 540));
const contactEmail = linkedPerson?.email ?? `${emailPart(firstName)}.${emailPart(lastName)}.lead-${String(index + 1).padStart(3, "0")}@leads.example.test`;
const contactPhone = linkedPerson?.phone ?? dramaPhone(externalPhoneIndex++);
const id = seedId("lead", index);
if (convertedProject) convertedProject.convertedFromLeadId = id;
return {
id,
outcome,
status: outcome === "spam" ? "spam" : outcome === "converted" ? "converted" : "lost",
source: sources[(index * 7) % sources.length]!,
sourceOrigin: sourceOrigins[(index * 7) % sourceOrigins.length]!,
createdAt,
ownerEmployeeId: salesOwners[index % salesOwners.length]!.id,
firstName,
lastName,
email: contactEmail,
phone: contactPhone,
message: leadMessage(outcome, convertedProject ?? undefined),
furtherProcessingConsent: outcome === "spam" ? "nein" : outcome === "converted" || outcome === "offer_lost" ? "ja" : "unklar",
spamScore: outcome === "spam" ? 85 + (index % 14) : index % 9,
spamReason: outcome === "spam" ? "Honeypot und kommerzielles Spam-Muster erkannt" : null,
isQuarantined: outcome === "spam",
linkedContactId: linkedPerson?.id ?? null,
convertedProjectId: convertedProject?.id ?? null,
convertedAt: convertedProject?.createdAt ?? null,
lostAt: outcome === "disqualified" || outcome === "offer_lost" ? earlierDate(REFERENCE_DATE, addDays(createdAt, 2 + (index % 21))) : null,
disqualifiedReason:
outcome === "disqualified"
? disqualifiedReasons[index % disqualifiedReasons.length]!
: outcome === "offer_lost"
? "Angebot an Wettbewerber vergeben"
: null,
};
});
}
export function generateDemoProSeed(): DemoProSeedGraph {
const { employees, crews } = generateEmployees();
const organizations = generateOrganizations(employees);
const persons = generatePersons(employees, organizations);
const contactRelations = generateContactRelations();
const projects = generateProjects(employees, crews, organizations, persons);
const leads = generateLeads(employees, persons, projects);
const graph: DemoProSeedGraph = {
namespace: DEMO_PRO_SEED_NAMESPACE,
generatedForTenantSlug: "demo-pro-crm",
referenceDate: REFERENCE_DATE,
employees,
crews,
organizations,
persons,
contactRelations,
projects,
leads,
};
const validation = validateDemoProSeedGraph(graph);
if (!validation.valid) {
throw new Error(`Generated demo-pro seed is invalid:\n${validation.errors.join("\n")}`);
}
return graph;
}
function countBy<T extends string>(values: readonly T[]): Record<string, number> {
return values.reduce<Record<string, number>>((counts, value) => {
counts[value] = (counts[value] ?? 0) + 1;
return counts;
}, {});
}
function compareCounts(label: string, actual: Record<string, number>, expected: Readonly<Record<string, number>>, errors: string[]): void {
for (const [key, expectedCount] of Object.entries(expected)) {
if ((actual[key] ?? 0) !== expectedCount) errors.push(`${label} ${key}: expected ${expectedCount}, received ${actual[key] ?? 0}.`);
}
}
export function validateDemoProSeedGraph(graph: DemoProSeedGraph): SeedValidationResult {
const errors: string[] = [];
const expectLength = (label: string, actual: number, expected: number) => {
if (actual !== expected) errors.push(`${label}: expected ${expected}, received ${actual}.`);
};
expectLength("employees", graph.employees.length, 50);
expectLength("office employees", graph.employees.filter((employee) => employee.seatCategory === "office").length, OFFICE_EMPLOYEE_COUNT);
expectLength("field employees", graph.employees.filter((employee) => employee.seatCategory === "field").length, FIELD_EMPLOYEE_COUNT);
expectLength("crews", graph.crews.length, CREW_COUNT);
expectLength("organizations", graph.organizations.length, ORGANIZATION_COUNT);
expectLength("persons", graph.persons.length, PERSON_COUNT);
expectLength("contact relations", graph.contactRelations.length, BUSINESS_PERSON_COUNT);
expectLength("projects", graph.projects.length, PROJECT_COUNT);
expectLength("leads", graph.leads.length, LEAD_COUNT);
compareCounts(
"office role",
countBy(graph.employees.filter((employee) => employee.seatCategory === "office").map((employee) => employee.role)),
Object.fromEntries(OFFICE_ROLE_COUNTS.map(({ role, count }) => [role, count])),
errors
);
compareCounts("project type", countBy(graph.projects.map((project) => project.projectType)), PROJECT_TYPE_COUNTS, errors);
compareCounts("lead outcome", countBy(graph.leads.map((lead) => lead.outcome)), LEAD_OUTCOME_COUNTS, errors);
const allIds = [
...graph.employees.map(({ id }) => id),
...graph.crews.map(({ id }) => id),
...graph.organizations.map(({ id }) => id),
...graph.persons.map(({ id }) => id),
...graph.contactRelations.map(({ id }) => id),
...graph.projects.map(({ id }) => id),
...graph.leads.map(({ id }) => id),
];
if (allIds.some((id) => !id.startsWith(ID_PREFIX))) errors.push(`Every generated ID must start with ${ID_PREFIX}.`);
if (new Set(allIds).size !== allIds.length) errors.push("Generated IDs must be globally unique.");
const projectNumbers = graph.projects.map((project) => project.projectNumber);
if (new Set(projectNumbers).size !== projectNumbers.length) errors.push("Project numbers must be unique.");
if (projectNumbers.some((number) => !/^RM-20\d{2}-7\d{5}$/.test(number))) errors.push("Project numbers must use the RM-YYYY-7xxxxx format.");
const primaryEntities = [...graph.employees, ...graph.organizations, ...graph.persons];
const primaryEmails = primaryEntities.map((entity) => entity.email);
const primaryPhones = primaryEntities.map((entity) => entity.phone);
if (new Set(primaryEmails).size !== primaryEmails.length) errors.push("Primary employee and contact e-mail addresses must be unique.");
if (new Set(primaryPhones).size !== primaryPhones.length) errors.push("Primary employee and contact phone numbers must be unique.");
const allEmails = [
...primaryEmails,
...graph.organizations.flatMap((organization) => organization.additionalEmails.map(({ value }) => value)),
...graph.persons.flatMap((person) => person.additionalEmails.map(({ value }) => value)),
...graph.leads.map((lead) => lead.email),
];
if (allEmails.some((email) => !email.endsWith(".example.test"))) errors.push("Every e-mail address must use an .example.test domain.");
const allPhones = [
...primaryPhones,
...graph.organizations.flatMap((organization) => organization.additionalPhones.map(({ value }) => value)),
...graph.persons.flatMap((person) => person.additionalPhones.map(({ value }) => value)),
...graph.leads.map((lead) => lead.phone),
];
if (allPhones.some((phone) => !/^\+496990009\d{3}$/.test(phone)))
errors.push("Every phone number must use the BNetzA +49 69 90009 000-999 drama-number range.");
const employeeIds = new Set(graph.employees.map(({ id }) => id));
const contactIds = new Set([...graph.organizations.map(({ id }) => id), ...graph.persons.map(({ id }) => id)]);
const crewIds = new Set(graph.crews.map(({ id }) => id));
const projectIds = new Set(graph.projects.map(({ id }) => id));
const personIds = new Set(graph.persons.map(({ id }) => id));
const organizationIds = new Set(graph.organizations.map(({ id }) => id));
const crewMembershipIds = graph.crews.flatMap(({ memberEmployeeIds }) => memberEmployeeIds);
const fieldEmployeeIds = new Set(graph.employees.filter(({ seatCategory }) => seatCategory === "field").map(({ id }) => id));
if (
crewMembershipIds.length !== FIELD_EMPLOYEE_COUNT ||
new Set(crewMembershipIds).size !== FIELD_EMPLOYEE_COUNT ||
crewMembershipIds.some((employeeId) => !fieldEmployeeIds.has(employeeId))
) {
errors.push("Every field employee must belong to exactly one crew.");
}
for (const [index, crew] of graph.crews.entries()) {
const expectedCrewSize = index < TWO_PERSON_CREW_COUNT ? 2 : 3;
if (crew.memberEmployeeIds.length !== expectedCrewSize || new Set(crew.memberEmployeeIds).size !== expectedCrewSize) {
errors.push(`${crew.id} must have exactly ${expectedCrewSize} distinct members.`);
}
if (crew.memberEmployeeIds.some((id) => !employeeIds.has(id))) errors.push(`${crew.id} references an unknown employee.`);
if (!employeeIds.has(crew.projectManagerEmployeeId)) errors.push(`${crew.id} references an unknown project manager.`);
}
for (const employee of graph.employees) {
if (employee.seatCategory === "field" && (!employee.crewId || !crewIds.has(employee.crewId))) {
errors.push(`${employee.id} does not reference a valid crew.`);
}
if (employee.seatCategory === "office" && employee.crewId !== null) errors.push(`${employee.id} must not reference a crew.`);
}
for (const relation of graph.contactRelations) {
if (!organizationIds.has(relation.organizationId) || !personIds.has(relation.personId)) errors.push(`${relation.id} references an unknown contact.`);
}
for (const project of graph.projects) {
if (!employeeIds.has(project.responsibleEmployeeId) || !employeeIds.has(project.projectManagerEmployeeId))
errors.push(`${project.id} references an unknown employee.`);
if (project.crewIds.some((id) => !crewIds.has(id))) errors.push(`${project.id} references an unknown crew.`);
if (project.contacts.some(({ contactId }) => !contactIds.has(contactId))) errors.push(`${project.id} references an unknown contact.`);
if (project.contacts.filter(({ primary }) => primary).length !== 1) errors.push(`${project.id} must have exactly one primary contact.`);
}
for (const lead of graph.leads) {
if (!employeeIds.has(lead.ownerEmployeeId)) errors.push(`${lead.id} references an unknown owner.`);
if (lead.linkedContactId && !personIds.has(lead.linkedContactId)) errors.push(`${lead.id} references an unknown linked contact.`);
if (lead.convertedProjectId && !projectIds.has(lead.convertedProjectId)) errors.push(`${lead.id} references an unknown converted project.`);
if (lead.outcome === "converted" && (!lead.convertedProjectId || !lead.linkedContactId || !lead.convertedAt))
errors.push(`${lead.id} is converted but has an incomplete conversion link.`);
}
const validLocations = new Set(LOCATIONS.map(({ plz, ort }) => `${plz}|${ort}`));
const allAddresses = [
...graph.organizations.map(({ address }) => address),
...graph.persons.map(({ address }) => address),
...graph.projects.flatMap(({ projectAddress, invoiceAddress, clientAddress }) => [projectAddress, invoiceAddress, clientAddress]),
];
if (allAddresses.some(({ plz, ort }) => !validLocations.has(`${plz}|${ort}`)))
errors.push("Every address must use a supported real Rhein-Main place/PLZ pair.");
if (allAddresses.some(({ strasse }) => !STREET_PREFIXES.some((prefix) => strasse.startsWith(prefix))))
errors.push("Every address must use the synthetic street catalog.");
return { valid: errors.length === 0, errors };
}
@@ -0,0 +1,34 @@
import { describe, expect, it, vi } from "vitest";
import { generatedStreetNames, validateGeneratedStreets } from "./geodata";
describe("demo-pro geodata validation", () => {
it("builds the exact deterministic street catalog used by the generator", () => {
const names = generatedStreetNames();
expect(names).toHaveLength(60);
expect(new Set(names).size).toBe(names.length);
});
it("detects collisions against paginated official street responses", async () => {
const collision = generatedStreetNames()[3]!;
const fetchMock = vi.fn(async (url: string | URL | Request) => {
const offset = Number(new URL(String(url)).searchParams.get("offset"));
const features =
offset === 0
? Array.from({ length: 500 }, (_, index) => ({ properties: { text: `Unrelated Street ${index}` } }))
: [{ properties: { text: collision } }];
return new Response(JSON.stringify({ numberMatched: 501, features }), { status: 200 });
});
const report = await validateGeneratedStreets(fetchMock as typeof fetch);
expect(report.collisions).toEqual([collision]);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("fails closed on an incomplete successful pagination response", async () => {
const fetchMock = vi.fn(
async () => new Response(JSON.stringify({ numberMatched: 501, features: [{ properties: { text: "Only one" } }] }), { status: 200 })
);
await expect(validateGeneratedStreets(fetchMock as typeof fetch)).rejects.toThrow("incomplete");
});
});
@@ -0,0 +1,95 @@
import { createHash } from "node:crypto";
import { STREET_PREFIXES, STREET_SUFFIXES } from "./catalog";
export const HESSEN_STREET_SOURCE_URL = "https://www.geoportal.hessen.de/spatial-objects/706/collections/ad%3AThoroughfareName/items?f=json&limit=500";
type GeoJsonPage = {
numberMatched?: number;
features?: Array<{ properties?: { text?: unknown } }>;
};
export type GeodataValidationReport = {
sourceUrl: string;
sourceHashSha256: string;
officialStreetCount: number;
generatedStreetCount: number;
collisions: string[];
};
function normalizeStreet(value: string): string {
return value
.normalize("NFD")
.replace(/[\u0300-\u036f]/gu, "")
.replace(/ß/gu, "ss")
.replace(/�/gu, "ss")
.toLowerCase()
.replace(/[^a-z0-9]/gu, "");
}
export function generatedStreetNames(): string[] {
const result = new Set<string>();
for (let index = 0; index < 60; index += 1) {
result.add(`${STREET_PREFIXES[(index * 11) % STREET_PREFIXES.length]!}${STREET_SUFFIXES[(index * 5) % STREET_SUFFIXES.length]!}`);
}
return [...result].sort((left, right) => left.localeCompare(right, "de"));
}
async function fetchPage(fetchImpl: typeof fetch, offset: number): Promise<{ raw: string; page: GeoJsonPage }> {
let lastError: unknown;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
const response = await fetchImpl(`${HESSEN_STREET_SOURCE_URL}&offset=${offset}`, {
headers: { accept: "application/geo+json" },
signal: AbortSignal.timeout(20_000),
});
if (!response.ok) throw new Error(`Hessen geodata request failed with HTTP ${response.status}.`);
const raw = await response.text();
const page = JSON.parse(raw) as GeoJsonPage;
if (!Array.isArray(page.features)) throw new Error(`Hessen geodata page at offset ${offset} has no feature array.`);
return { raw, page };
} catch (error) {
lastError = error;
}
}
throw lastError instanceof Error ? lastError : new Error(`Hessen geodata page at offset ${offset} failed.`);
}
/**
* Checks the synthetic street catalog against the official Hessen street-name
* snapshot. This is an explicit development-time gate and never runs during a
* staging seed, keeping the production seed independent from remote services.
*/
export async function validateGeneratedStreets(fetchImpl: typeof fetch = fetch): Promise<GeodataValidationReport> {
const first = await fetchPage(fetchImpl, 0);
const numberMatched = first.page.numberMatched ?? first.page.features!.length;
if (!Number.isSafeInteger(numberMatched) || numberMatched <= 0) throw new Error("Hessen geodata response has an invalid numberMatched value.");
const offsets = Array.from({ length: Math.max(0, Math.ceil(numberMatched / 500) - 1) }, (_, index) => (index + 1) * 500);
const pages = [first];
for (const batchStart of Array.from({ length: Math.ceil(offsets.length / 8) }, (_, index) => index * 8)) {
pages.push(...(await Promise.all(offsets.slice(batchStart, batchStart + 8).map((offset) => fetchPage(fetchImpl, offset)))));
}
for (const [pageIndex, { page }] of pages.entries()) {
if (page.numberMatched !== undefined && page.numberMatched !== numberMatched)
throw new Error("Hessen geodata pagination returned inconsistent numberMatched values.");
const expectedFeatures = Math.min(500, numberMatched - pageIndex * 500);
if (page.features!.length !== expectedFeatures) {
throw new Error(`Hessen geodata page at offset ${pageIndex * 500} is incomplete.`);
}
}
const officialNames = pages
.flatMap(({ page }) => page.features!)
.flatMap(({ properties }) => (typeof properties?.text === "string" ? [properties.text] : []));
if (officialNames.length !== numberMatched) throw new Error("Hessen geodata snapshot contains incomplete street-name properties.");
const officialNormalized = new Set(officialNames.map(normalizeStreet));
const generated = generatedStreetNames();
const hash = createHash("sha256");
for (const { raw } of pages) hash.update(raw);
return {
sourceUrl: HESSEN_STREET_SOURCE_URL,
sourceHashSha256: hash.digest("hex"),
officialStreetCount: officialNames.length,
generatedStreetCount: generated.length,
collisions: generated.filter((name) => officialNormalized.has(normalizeStreet(name))),
};
}
@@ -0,0 +1,66 @@
import { readFileSync, readdirSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const repoFile = (path: string): string => readFileSync(resolve(process.cwd(), path), "utf8");
const persistenceSource = repoFile("scripts/demo-pro-seed/persistence.ts");
const projectServiceSource = repoFile("apps/web/app/utils/integrations/projects/projectService.server.ts");
const orderServiceSource = repoFile("apps/web/app/utils/integrations/projects/auftragService.server.ts");
const formTemplateSource = repoFile("apps/web/app/modules/forms/services/shkFormTemplates.server.ts");
const customFieldSource = repoFile("apps/web/app/utils/integrations/crm/customFieldService.server.ts");
const automationSource = repoFile("apps/web/app/services/automation/automation.server.ts");
const crmLegacySeedSource = repoFile("scripts/ops/seed-crm-leads-demo.mts");
const hrLegacySeedSource = repoFile("scripts/ops/seed-hr-demo.mts");
describe("managed staging business data", () => {
it("never persists comprehensive seed rows behind product demo filters", () => {
const creationSource = persistenceSource.split("export async function verifyDemoProTenant")[0]!;
expect(creationSource).toContain("const STAGING_BUSINESS_DATA_IS_DEMO = false;");
expect(creationSource).not.toContain("isDemoData: true");
expect(creationSource).toContain("isDemoData: STAGING_BUSINESS_DATA_IS_DEMO");
expect(creationSource).not.toContain('tags: ["Demo"');
expect(creationSource).not.toContain("Seed-Gruppe");
expect(creationSource).not.toContain("Demo-Signatur");
});
it("creates lazy project defaults as normal tenant data", () => {
expect(projectServiceSource).not.toContain("isDemoData: true");
expect(orderServiceSource).not.toContain("isDemoData: true");
});
it("keeps reachable template writers on the normal-data invariant", () => {
expect(formTemplateSource).toContain("const isDemoData = input.isDemoData ?? false");
expect(customFieldSource).toContain("const isDemoData = input.isDemoData ?? false");
const userTemplateCreation = automationSource.split("export async function createAutomationRuleFromTemplate")[1]!.split("export async function createAutomationRuleFromTemplateForRoute")[0]!;
expect(userTemplateCreation).not.toContain("isDemoData: true");
expect(userTemplateCreation).toContain("isDemoData: false");
});
it("verifies every tenant model that currently carries an isDemoData flag", () => {
const declaredList = persistenceSource.match(/const TENANT_MODELS_WITH_DEMO_FLAG = \[([\s\S]*?)\] as const;/u)?.[1];
expect(declaredList).toBeDefined();
const verifiedModels = [...(declaredList?.matchAll(/"([A-Za-z0-9]+)"/gu) ?? [])].map((match) => match[1]).sort();
const schemaDir = resolve(process.cwd(), "prisma/schema");
const schemaModels = readdirSync(schemaDir)
.filter((name) => name.endsWith(".prisma"))
.flatMap((name) => {
const source = readFileSync(resolve(schemaDir, name), "utf8");
return [...source.matchAll(/model\s+(\w+)\s*\{([\s\S]*?)\n\}/gu)]
.filter(([, , body]) => /\btenantId\s+String\??\b/u.test(body!) && /\bisDemoData\s+Boolean\b/u.test(body!))
.map(([, model]) => model!);
})
.sort();
expect(verifiedModels).toEqual(schemaModels);
});
it("keeps legacy demo scripts away from the managed staging tenant", () => {
for (const source of [crmLegacySeedSource, hrLegacySeedSource]) {
const targetList = source.match(/const DEMO_SLUGS = \[(.*?)\];/u)?.[1];
expect(targetList).toBeDefined();
expect(targetList).not.toContain('"demo-pro-crm"');
expect(source).toContain('const MANAGED_STAGING_TENANT_SLUG = "demo-pro-crm";');
expect(source).toContain("if (t.slug === MANAGED_STAGING_TENANT_SLUG)");
}
});
});
@@ -0,0 +1,145 @@
import { describe, expect, it } from "vitest";
import { generateDemoProSeed } from "./generator";
import { buildSeedFileObjectMetadata, seedFileStorageKey } from "./file-objects";
import { generateOperationalGraph, OPERATIONAL_COUNTS } from "./operations";
describe("demo-pro operational graph", () => {
it("generates all agreed connected entity volumes", () => {
const operational = generateOperationalGraph(generateDemoProSeed());
for (const [key, expected] of Object.entries(OPERATIONAL_COUNTS)) {
expect(operational[key as keyof typeof operational]).toHaveLength(expected);
}
});
it("keeps task assignment and schedule data internally consistent", () => {
const graph = generateDemoProSeed();
const operational = generateOperationalGraph(graph);
expect(operational.tasks.every((task) => Number(Boolean(task.assignedToUserId)) + Number(Boolean(task.assignedToGroupId)) === 1)).toBe(true);
expect(
operational.tasks.every(
(task) =>
new Date(task.createdAt) <= new Date(task.updatedAt) &&
new Date(task.updatedAt) <= new Date(graph.referenceDate) &&
(task.completedAt === null || (new Date(task.createdAt) <= new Date(task.completedAt) && new Date(task.completedAt) <= new Date(graph.referenceDate)))
)
).toBe(true);
expect(operational.scheduleEntries.every((entry) => new Date(entry.startAt) < new Date(entry.endAt))).toBe(true);
const projects = new Map(graph.projects.map((project) => [project.id, project]));
expect(
operational.scheduleEntries.every((entry) => {
const project = projects.get(entry.projectId)!;
return Boolean(project.startDate) && new Date(entry.startAt) >= new Date(project.startDate!) && new Date(entry.endAt) <= new Date(project.deadline);
})
).toBe(true);
expect(
operational.scheduleConflicts.every((conflict) => {
const entry = operational.scheduleEntries.find(({ id }) => id === conflict.entryId)!;
const source = operational.scheduleEntries.find(({ id }) => id === conflict.sourceEntryId)!;
return (
entry.assignedUserId === source.assignedUserId && new Date(entry.startAt) < new Date(source.endAt) && new Date(source.startAt) < new Date(entry.endAt)
);
})
).toBe(true);
expect(
operational.scheduleEntries.every((entry) => {
if (entry.calendarEventId === null) return entry.syncStatus === "pending";
const event = operational.calendarEvents.find(({ id }) => id === entry.calendarEventId);
return (
entry.syncStatus === "synced" &&
event?.projectId === entry.projectId &&
event.userId === entry.assignedUserId &&
event.startsAt === entry.startAt &&
event.endsAt === entry.endAt
);
})
).toBe(true);
expect(new Set(operational.files.map((file) => seedFileStorageKey("tenant-staging", file.id))).size).toBe(operational.files.length);
expect(
operational.files.every(
(file) =>
seedFileStorageKey("tenant-staging", file.id).startsWith("tenants/tenant-staging/files/") &&
file.mimeType === "application/pdf" &&
file.sizeBytes === buildSeedFileObjectMetadata(file).sizeBytes &&
file.checksumSha256 === buildSeedFileObjectMetadata(file).checksumSha256 &&
file.tags.every((tag) => !/demo|synthet/u.test(tag.toLowerCase())) &&
!/demo|synthet|seed/u.test(file.notes.toLowerCase())
)
).toBe(true);
expect(operational.acceptanceSignatures.every((signature) => signature.signerRole === "kunde" || signature.signerRole === "monteur")).toBe(true);
expect(operational.activities.every((activity) => new Date(activity.createdAt) <= new Date(graph.referenceDate))).toBe(true);
expect(operational.acceptances.every((acceptance) => new Set(acceptance.attendees).size === acceptance.attendees.length)).toBe(true);
expect(
operational.acceptances.every(
(acceptance) =>
new Date(acceptance.date) <= new Date(acceptance.createdAt) &&
new Date(acceptance.createdAt) <= new Date(acceptance.updatedAt) &&
new Date(acceptance.updatedAt) <= new Date(graph.referenceDate)
)
).toBe(true);
expect(
operational.acceptances
.filter(({ kind }) => kind === "with_defects")
.every((acceptance) => operational.checklists.find(({ id }) => id === acceptance.checklistId)?.type === "maengel")
).toBe(true);
expect(
operational.signatureDocuments.every((document) => operational.files.find(({ id }) => id === document.sourceFileId)?.displayName.startsWith("Angebot_"))
).toBe(true);
expect(
operational.signatureDocuments.every(
(document) =>
document.createdAt === document.sentAt &&
new Date(document.createdAt) <= new Date(document.updatedAt) &&
new Date(document.updatedAt) <= new Date(graph.referenceDate)
)
).toBe(true);
expect(
operational.invoices.every((invoice) => {
const project = projects.get(invoice.projectId)!;
return project.pipeline === "auftrag" || project.stage === "gewonnen";
})
).toBe(true);
expect(operational.invoices.every((invoice) => new Date(invoice.date) <= new Date(graph.referenceDate))).toBe(true);
const invoiceFileIds = operational.invoices.flatMap(({ fileId }) => (fileId ? [fileId] : []));
expect(invoiceFileIds.length).toBeGreaterThan(0);
expect(new Set(invoiceFileIds).size).toBe(invoiceFileIds.length);
expect(
operational.invoices.every((invoice) => {
if (!invoice.fileId) return true;
const file = operational.files.find(({ id }) => id === invoice.fileId);
return file?.projectId === invoice.projectId && file.displayName.startsWith("Rechnung_");
})
).toBe(true);
expect(operational.checklistItems.every(({ photoFileId }) => photoFileId === null)).toBe(true);
expect(operational.acceptances.some(({ documentFileId }) => documentFileId !== null)).toBe(true);
expect(
operational.acceptances.every((acceptance) => {
if (!acceptance.documentFileId) return true;
const file = operational.files.find(({ id }) => id === acceptance.documentFileId);
return file?.projectId === acceptance.projectId && file.displayName.startsWith("Abnahmeprotokoll_");
})
).toBe(true);
expect(
operational.bookingAppointments.every((appointment) =>
operational.bookingProviders.some(
(provider) => provider.bookingPageId === appointment.bookingPageId && provider.providerUserId === appointment.providerUserId
)
)
).toBe(true);
expect(new Set(operational.bookingAppointments.map(({ internalCalendarEventId }) => internalCalendarEventId)).size).toBe(
operational.bookingAppointments.length
);
expect(
operational.bookingAppointments.every((appointment) => {
const page = operational.bookingPages.find(({ id }) => id === appointment.bookingPageId)!;
return new Date(appointment.endsAt).getTime() - new Date(appointment.startsAt).getTime() === page.durationMinutes * 60_000;
})
).toBe(true);
});
it("is deterministic across complete operational generations", () => {
expect(generateOperationalGraph(generateDemoProSeed())).toEqual(generateOperationalGraph(generateDemoProSeed()));
});
});
@@ -0,0 +1,963 @@
import type { DemoProSeedGraph, ProjectType, SeedProject } from "./types";
import { buildSeedFileObjectMetadata } from "./file-objects";
export const OPERATIONAL_COUNTS = {
projectContacts: 1_611,
projectMembers: 1_876,
tasks: 1_684,
taskWatchers: 421,
activities: 2_731,
scheduleEntries: 1_147,
scheduleConflicts: 23,
calendarEvents: 613,
projectAppointments: 613,
bookingPages: 3,
bookingProviders: 21,
availabilityRules: 35,
availabilityExceptions: 7,
bookingAppointments: 79,
invoices: 347,
checklists: 329,
checklistItems: 1_693,
files: 917,
acceptances: 73,
acceptanceSignatures: 146,
signatureDocuments: 47,
signatureSigners: 47,
} as const;
type ProjectContact = {
id: string;
projectId: string;
contactId: string;
role: "auftraggeber" | "bauherr" | "rechnungsempfaenger" | "ansprechpartner";
primary: boolean;
};
type ProjectMember = {
id: string;
projectId: string;
userId: string | null;
groupId: string | null;
role: "monteur" | "projektleiter" | "zustaendig";
};
type SeedTask = {
id: string;
projectId: string;
title: string;
description: string;
status: "open" | "in_progress" | "blocked" | "done" | "cancelled";
priority: "low" | "normal" | "high" | "urgent";
deadline: string;
assignedToUserId: string | null;
assignedToGroupId: string | null;
completedAt: string | null;
createdAt: string;
updatedAt: string;
};
type SeedActivity = {
id: string;
projectId: string;
actorUserId: string;
activityType: string;
createdAt: string;
summaryText: string;
metadata: Record<string, unknown>;
};
type SeedScheduleEntry = {
id: string;
projectId: string;
assignedUserId: string;
title: string;
startAt: string;
endAt: string;
status: "planned" | "confirmed" | "in_progress" | "done" | "cancelled";
calendarEventId: string | null;
syncStatus: "pending" | "synced";
};
type SeedCalendarEvent = {
id: string;
projectId: string;
userId: string;
title: string;
description: string;
location: string;
startsAt: string;
endsAt: string;
};
type SeedBookingPage = {
id: string;
slug: string;
title: string;
description: string;
durationMinutes: number;
};
type SeedBookingAppointment = {
id: string;
bookingPageId: string;
providerUserId: string;
contactId: string;
projectId: string;
internalCalendarEventId: string;
startsAt: string;
endsAt: string;
status: "scheduled" | "held" | "cancelled";
customerName: string;
customerEmail: string;
customerPhone: string;
request: string;
};
type SeedInvoice = {
id: string;
projectId: string;
invoiceNumber: string;
amount: string;
status: "entwurf" | "gestellt" | "bezahlt" | "storniert";
date: string;
dueAt: string;
fileId: string | null;
createdAt: string;
updatedAt: string;
};
type SeedChecklist = {
id: string;
projectId: string;
title: string;
type: "generisch" | "maengel" | "abnahme_doku";
};
type SeedChecklistItem = {
id: string;
checklistId: string;
title: string;
status: "offen" | "erledigt" | "entfaellt";
defectClass: string | null;
assignedToUserId: string;
dueAt: string;
position: number;
photoFileId: null;
};
type SeedFile = {
id: string;
projectId: string;
displayName: string;
mimeType: string;
sizeBytes: number;
checksumSha256: string;
assignedToUserId: string;
tags: string[];
notes: string;
linkRole: string;
createdAt: string;
updatedAt: string;
};
type SeedAcceptance = {
id: string;
projectId: string;
checklistId: string | null;
creatorUserId: string;
date: string;
kind: "full" | "with_defects";
attendees: string[];
remarks: string;
customerEmail: string;
documentFileId: string | null;
createdAt: string;
updatedAt: string;
};
type SeedSignatureDocument = {
id: string;
projectId: string;
sourceFileId: string;
creatorUserId: string;
status: "sent" | "viewed" | "signed";
title: string;
sentAt: string;
completedAt: string | null;
signerContactId: string;
signerEmail: string;
signerName: string;
createdAt: string;
updatedAt: string;
};
export type DemoProOperationalGraph = {
projectContacts: ProjectContact[];
projectMembers: ProjectMember[];
tasks: SeedTask[];
taskWatchers: Array<{ id: string; taskId: string; userId: string }>;
activities: SeedActivity[];
scheduleEntries: SeedScheduleEntry[];
scheduleConflicts: Array<{ id: string; entryId: string; sourceEntryId: string; resolvedAt: string | null }>;
calendarEvents: SeedCalendarEvent[];
projectAppointments: Array<SeedCalendarEvent & { status: "geplant" | "bestaetigt" | "erledigt" | "abgesagt" }>;
bookingPages: SeedBookingPage[];
bookingProviders: Array<{ id: string; bookingPageId: string; providerUserId: string; displayOrder: number }>;
availabilityRules: Array<{
id: string;
providerUserId: string;
dayOfWeek: "monday" | "tuesday" | "wednesday" | "thursday" | "friday";
startTime: string;
endTime: string;
}>;
availabilityExceptions: Array<{
id: string;
providerUserId: string;
date: string;
kind: "unavailable" | "custom_window";
startTime: string | null;
endTime: string | null;
reason: string;
}>;
bookingAppointments: SeedBookingAppointment[];
invoices: SeedInvoice[];
checklists: SeedChecklist[];
checklistItems: SeedChecklistItem[];
files: SeedFile[];
acceptances: SeedAcceptance[];
acceptanceSignatures: Array<{ id: string; acceptanceId: string; signerName: string; signerRole: "kunde" | "monteur"; signedAt: string }>;
signatureDocuments: SeedSignatureDocument[];
signatureSigners: Array<{
id: string;
documentId: string;
contactId: string;
email: string;
name: string;
status: "sent" | "viewed" | "signed";
signedAt: string | null;
}>;
};
const taskTemplates: Readonly<Record<ProjectType, readonly string[]>> = {
reparatur_notdienst: [
"Störungsbild telefonisch aufnehmen",
"Ersatzteile und Werkzeug disponieren",
"Einsatzbericht mit Messwerten abschließen",
"Kunden über Folgemaßnahmen informieren",
],
wartung_pruefung: [
"Anlagendaten und Wartungshistorie prüfen",
"Wartungsmaterial zusammenstellen",
"Mess- und Wartungsprotokoll erfassen",
"Nächsten Wartungszyklus vormerken",
],
heizungstausch: [
"Heizlast und Bestandssituation prüfen",
"Wärmeerzeuger und Speicher disponieren",
"Montageablauf mit Kunde abstimmen",
"Inbetriebnahme und Einweisung dokumentieren",
],
heizungsoptimierung: [
"Bestandswerte und Heizkreise aufnehmen",
"Einstellwerte berechnen",
"Optimierungsmaßnahmen ausführen",
"Verbrauchsempfehlungen dokumentieren",
],
badsanierung: [
"Aufmaß und Ausstattungsdetails bestätigen",
"Sanitärobjekte und Armaturen disponieren",
"Gewerkeablauf koordinieren",
"Abnahme und Pflegehinweise vorbereiten",
],
sanitaer_rohrarbeiten: [
"Leitungsverlauf und Absperrungen prüfen",
"Rohrmaterial disponieren",
"Druckprobe dokumentieren",
"Bestandsunterlagen aktualisieren",
],
objekt_neubau: [
"Ausführungsplanung mit Fachplanung abstimmen",
"Bauzeitenplan und Materialabrufe aktualisieren",
"Montagefortschritt dokumentieren",
"Teilabnahme vorbereiten",
],
lueftung_klima: [
"Luftmengen und Aufstellorte prüfen",
"Geräte und Kanalmaterial disponieren",
"Anlage montieren und einregulieren",
"Messprotokoll und Einweisung abschließen",
],
};
const activityTemplates = [
["project.created", "Projekt wurde vollständig angelegt"],
["project.contact_linked", "Kunden- und Ansprechpartner wurden verknüpft"],
["project.assignment_changed", "Projektteam und Zuständigkeiten wurden geplant"],
["project.schedule_planned", "Ausführungstermin wurde in der Plantafel reserviert"],
["project.note_added", "Technische Projektnotiz wurde ergänzt"],
["project.stage_changed", "Pipeline-Status wurde aktualisiert"],
] as const;
function id(kind: string, index: number): string {
return `rheinmain-shk-v1-${kind}-${String(index + 1).padStart(5, "0")}`;
}
function addDays(value: string, days: number, hour?: number): string {
const date = new Date(value);
date.setUTCDate(date.getUTCDate() + days);
if (hour !== undefined) date.setUTCHours(hour, 0, 0, 0);
return date.toISOString();
}
function earlierDate(first: string, second: string): string {
return new Date(first) <= new Date(second) ? first : second;
}
function laterDate(first: string, second: string): string {
return new Date(first) >= new Date(second) ? first : second;
}
function euro(value: string | null, factor: number): string {
const amount = Number(value ?? 0);
return Math.max(90, Math.round((amount * factor) / 10) * 10).toFixed(2);
}
function contactDisplayName(graph: DemoProSeedGraph, contactId: string): string {
const organization = graph.organizations.find((contact) => contact.id === contactId);
if (organization) return organization.orgName;
const person = graph.persons.find((contact) => contact.id === contactId);
return person ? `${person.firstName} ${person.lastName}` : "Kunde";
}
function contactEmail(graph: DemoProSeedGraph, contactId: string): string {
return (
graph.organizations.find((contact) => contact.id === contactId)?.email ??
graph.persons.find((contact) => contact.id === contactId)?.email ??
"kunde@unbekannt.example.test"
);
}
function contactPhone(graph: DemoProSeedGraph, contactId: string): string {
return (
graph.organizations.find((contact) => contact.id === contactId)?.phone ??
graph.persons.find((contact) => contact.id === contactId)?.phone ??
"+496990009000"
);
}
function employeeDisplayName(graph: DemoProSeedGraph, employeeId: string): string {
const employee = graph.employees.find(({ id: currentId }) => currentId === employeeId);
return employee ? `${employee.firstName} ${employee.lastName}` : "Mitarbeiter";
}
export function generateOperationalGraph(graph: DemoProSeedGraph): DemoProOperationalGraph {
const crewById = new Map(graph.crews.map((crew) => [crew.id, crew]));
const projectContacts: ProjectContact[] = [];
const projectMembers: ProjectMember[] = [];
const tasks: SeedTask[] = [];
const activities: SeedActivity[] = [];
const scheduleEntries: SeedScheduleEntry[] = [];
const calendarEvents: SeedCalendarEvent[] = [];
const projectAppointments: DemoProOperationalGraph["projectAppointments"] = [];
for (const [projectIndex, project] of graph.projects.entries()) {
for (const contact of project.contacts) {
projectContacts.push({
id: id("project-contact", projectContacts.length),
projectId: project.id,
contactId: contact.contactId,
role: contact.role,
primary: contact.primary,
});
}
const crew = crewById.get(project.crewIds[0]!)!;
projectMembers.push({
id: id("project-member", projectMembers.length),
projectId: project.id,
userId: project.projectManagerEmployeeId,
groupId: null,
role: "projektleiter",
});
for (const userId of crew.memberEmployeeIds) {
projectMembers.push({ id: id("project-member", projectMembers.length), projectId: project.id, userId, groupId: null, role: "monteur" });
}
for (const additionalCrewId of project.crewIds.slice(1)) {
const additionalCrew = crewById.get(additionalCrewId)!;
for (const userId of additionalCrew.memberEmployeeIds) {
projectMembers.push({ id: id("project-member", projectMembers.length), projectId: project.id, userId, groupId: null, role: "monteur" });
}
}
if (projectIndex < 216) {
projectMembers.push({
id: id("project-member", projectMembers.length),
projectId: project.id,
userId: project.responsibleEmployeeId,
groupId: null,
role: "zustaendig",
});
}
const projectTaskCount = projectIndex < 73 ? 4 : 3;
for (let slot = 0; slot < projectTaskCount; slot += 1) {
const deadline = addDays(project.startDate ?? project.createdAt, 1 + slot * 2);
const done = new Date(deadline) < new Date(graph.referenceDate) && (projectIndex + slot) % 4 !== 0;
const assignedToCrew = slot === 1 || (slot === 2 && projectIndex % 3 === 0);
const createdAt = earlierDate(earlierDate(addDays(project.createdAt, slot), deadline), graph.referenceDate);
const completedAt = done ? addDays(deadline, 0, 16) : null;
const statusUpdatedAt =
done || (projectIndex + slot) % 3 !== 0
? (completedAt ?? createdAt)
: earlierDate(addDays(createdAt, 1 + ((projectIndex + slot) % 5)), graph.referenceDate);
tasks.push({
id: id("task", tasks.length),
projectId: project.id,
title: taskTemplates[project.projectType][slot]!,
description: `${project.projectNumber}: ${project.projectName}. Zuständigkeit und Ergebnis nachvollziehbar im Projekt dokumentieren.`,
status: done ? "done" : slot === 2 && projectIndex % 17 === 0 ? "blocked" : slot === 0 && projectIndex % 5 === 0 ? "in_progress" : "open",
priority: project.priority === "dringend" ? "urgent" : project.priority === "hoch" ? "high" : project.priority === "niedrig" ? "low" : "normal",
deadline,
assignedToUserId: assignedToCrew ? null : slot === 0 ? project.responsibleEmployeeId : crew.memberEmployeeIds[slot % crew.memberEmployeeIds.length]!,
assignedToGroupId: assignedToCrew ? crew.id : null,
completedAt,
createdAt,
updatedAt: laterDate(createdAt, statusUpdatedAt),
});
}
const activityCount = projectIndex < 46 ? 6 : 5;
for (let slot = 0; slot < activityCount; slot += 1) {
const [activityType, summaryText] = activityTemplates[slot]!;
const candidateCreatedAt = addDays(project.createdAt, slot * 2);
activities.push({
id: id("activity", activities.length),
projectId: project.id,
actorUserId: slot % 2 === 0 ? project.responsibleEmployeeId : project.projectManagerEmployeeId,
activityType,
createdAt: new Date(candidateCreatedAt) > new Date(graph.referenceDate) ? graph.referenceDate : candidateCreatedAt,
summaryText: `${summaryText}: ${project.projectNumber}`,
metadata: { projectNumber: project.projectNumber, projectType: project.projectType, seedNamespace: graph.namespace },
});
}
const calendarCount = projectIndex < 76 ? 2 : 1;
for (let slot = 0; slot < calendarCount; slot += 1) {
const userId = slot === 0 ? project.projectManagerEmployeeId : project.responsibleEmployeeId;
const calendarWindowStart = project.startDate ?? project.createdAt;
const calendarWindowDays = Math.max(
1,
Math.floor((new Date(project.deadline ?? graph.referenceDate).getTime() - new Date(calendarWindowStart).getTime()) / 86_400_000)
);
const dayOffset = Math.min(calendarWindowDays - 1, (projectIndex * 3 + slot) % calendarWindowDays);
const startsAt = addDays(calendarWindowStart, dayOffset, 9 + slot * 4);
const endsAt = new Date(new Date(startsAt).getTime() + (slot === 0 ? 90 : 45) * 60 * 1_000).toISOString();
const event = {
id: id("calendar", calendarEvents.length),
projectId: project.id,
userId,
title: slot === 0 ? `Baubesprechung · ${project.projectNumber}` : `Kundenabstimmung · ${project.projectNumber}`,
description: `${project.projectName}: Termin, nächste Schritte und offene Punkte abstimmen.`,
location: `${project.projectAddress.strasse} ${project.projectAddress.hausnummer}, ${project.projectAddress.plz} ${project.projectAddress.ort}`,
startsAt,
endsAt,
};
calendarEvents.push(event);
projectAppointments.push({
...event,
id: id("project-appointment", projectAppointments.length),
status: new Date(endsAt) < new Date(graph.referenceDate) ? "erledigt" : slot === 0 ? "bestaetigt" : "geplant",
});
}
}
const scheduleConflictPairs: Array<{ entryId: string; sourceEntryId: string }> = [];
const scheduledProjects = graph.projects.filter((project): project is SeedProject & { startDate: string } => Boolean(project.startDate));
for (const [scheduledProjectIndex, project] of scheduledProjects.entries()) {
const projectStartDate = project.startDate!;
const crew = crewById.get(project.crewIds[0]!)!;
const scheduleCount = scheduledProjectIndex < 157 ? 4 : 3;
const windowDays = Math.max(
1,
Math.floor((new Date(project.deadline ?? graph.referenceDate).getTime() - new Date(projectStartDate).getTime()) / 86_400_000)
);
const projectEntries: SeedScheduleEntry[] = [];
for (let slot = 0; slot < scheduleCount; slot += 1) {
const conflictSlot = scheduledProjectIndex < OPERATIONAL_COUNTS.scheduleConflicts && slot === 2;
const assignedUserId = conflictSlot ? crew.memberEmployeeIds[0] : crew.memberEmployeeIds[slot % crew.memberEmployeeIds.length]!;
const startAt = conflictSlot
? projectEntries[0]!.startAt
: addDays(projectStartDate, Math.min(windowDays - 1, Math.floor(slot / 2)), 9 + Math.floor(slot / 2) * 4);
const endAt = conflictSlot ? projectEntries[0]!.endAt : new Date(new Date(startAt).getTime() + 3 * 60 * 60 * 1_000).toISOString();
const past = new Date(endAt) < new Date(graph.referenceDate);
const entry: SeedScheduleEntry = {
id: id("schedule", scheduleEntries.length),
projectId: project.id,
assignedUserId,
title: `${project.projectNumber} · ${project.projectName}`,
startAt,
endAt,
status: past ? "done" : scheduledProjectIndex % 5 === 0 ? "confirmed" : "planned",
calendarEventId: null,
syncStatus: "pending",
};
projectEntries.push(entry);
scheduleEntries.push(entry);
if (conflictSlot) scheduleConflictPairs.push({ entryId: entry.id, sourceEntryId: projectEntries[0]!.id });
}
}
const bookingPages: SeedBookingPage[] = [
{
id: id("booking-page", 0),
slug: "heizung-bad-beratung",
title: "Heizungs- und Badberatung",
description: "Persönliche Erstberatung für Heizungstausch, Wärmepumpe und Badsanierung im Rhein-Main-Gebiet.",
durationMinutes: 45,
},
{
id: id("booking-page", 1),
slug: "wartung-bestandskunden",
title: "Wartung für Bestandskunden",
description: "Terminabstimmung für die regelmäßige Wartung bestehender Heizungs- und Sanitäranlagen.",
durationMinutes: 60,
},
{
id: id("booking-page", 2),
slug: "notdienst-rueckruf",
title: "Notdienst-Rückruf",
description: "Kurzer technischer Rückruf zur Einschätzung einer akuten Störung und zur Einsatzplanung.",
durationMinutes: 30,
},
];
const providers = graph.employees.filter(({ role }) => role === "Projektleiter/Bauleiter");
const bookingProviders = bookingPages.flatMap((page) =>
providers.map((employee, displayOrder) => ({
id: `${page.id}-provider-${String(displayOrder + 1).padStart(2, "0")}`,
bookingPageId: page.id,
providerUserId: employee.id,
displayOrder,
}))
);
const weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday"] as const;
const availabilityRules = providers.flatMap((provider, providerIndex) =>
weekdays.map((dayOfWeek, weekdayIndex) => ({
id: id("availability-rule", providerIndex * weekdays.length + weekdayIndex),
providerUserId: provider.id,
dayOfWeek,
startTime: weekdayIndex === 4 ? "08:00" : providerIndex % 2 === 0 ? "08:30" : "09:00",
endTime: weekdayIndex === 4 ? "14:00" : providerIndex % 3 === 0 ? "16:30" : "17:00",
}))
);
const availabilityExceptions = providers.map((provider, index) => {
const customWindow = index % 3 === 1;
return {
id: id("availability-exception", index),
providerUserId: provider.id,
date: addDays(graph.referenceDate, 11 + index),
kind: customWindow ? ("custom_window" as const) : ("unavailable" as const),
startTime: customWindow ? "10:00" : null,
endTime: customWindow ? "14:00" : null,
reason: customWindow ? "Fortbildung am Vormittag" : index % 2 === 0 ? "Urlaub" : "Baustellenbegehung außer Haus",
};
});
const projectById = new Map(graph.projects.map((project) => [project.id, project]));
const providerIds = new Set(providers.map(({ id: providerId }) => providerId));
const bookingAppointments = calendarEvents
.filter(({ userId }) => providerIds.has(userId))
.filter(({ startsAt }) => {
const day = new Date(startsAt).getUTCDay();
return day >= 1 && day <= 5;
})
.slice(0, OPERATIONAL_COUNTS.bookingAppointments)
.map((event, index): SeedBookingAppointment => {
const project = projectById.get(event.projectId)!;
const primaryContact = project.contacts.find(({ primary }) => primary)?.contactId ?? project.contacts[0]!.contactId;
const page =
project.projectType === "reparatur_notdienst" ? bookingPages[2]! : project.projectType === "wartung_pruefung" ? bookingPages[1]! : bookingPages[0]!;
const cancelled = index % 17 === 0;
const endsAt = new Date(new Date(event.startsAt).getTime() + page.durationMinutes * 60_000).toISOString();
event.endsAt = endsAt;
const projectAppointment = projectAppointments.find(
(appointment) => appointment.projectId === event.projectId && appointment.userId === event.userId && appointment.startsAt === event.startsAt
);
if (projectAppointment) projectAppointment.endsAt = endsAt;
if (projectAppointment && cancelled) projectAppointment.status = "abgesagt";
return {
id: id("booking-appointment", index),
bookingPageId: page.id,
providerUserId: event.userId,
contactId: primaryContact,
projectId: project.id,
internalCalendarEventId: event.id,
startsAt: event.startsAt,
endsAt,
status: cancelled ? "cancelled" : new Date(endsAt) < new Date(graph.referenceDate) ? "held" : "scheduled",
customerName: contactDisplayName(graph, primaryContact),
customerEmail: contactEmail(graph, primaryContact),
customerPhone: contactPhone(graph, primaryContact),
request: `${project.projectName}: Terminwunsch zu ${project.description}`,
};
});
const calendarEventsByScheduleWindow = new Map<string, SeedCalendarEvent[]>();
for (const event of calendarEvents) {
const key = [event.projectId, event.userId, event.startsAt, event.endsAt].join("\u0000");
const matches = calendarEventsByScheduleWindow.get(key) ?? [];
matches.push(event);
calendarEventsByScheduleWindow.set(key, matches);
}
for (const entry of scheduleEntries) {
const key = [entry.projectId, entry.assignedUserId, entry.startAt, entry.endAt].join("\u0000");
const matches = calendarEventsByScheduleWindow.get(key) ?? [];
// A schedule row may only claim sync when one exact calendar counterpart
// exists. Similar-looking meetings are intentionally not guessed as links.
if (matches.length === 1) {
entry.calendarEventId = matches[0]!.id;
entry.syncStatus = "synced";
}
}
const taskWatchers = tasks.slice(0, OPERATIONAL_COUNTS.taskWatchers).map((task, index) => ({
id: id("task-watcher", index),
taskId: task.id,
userId: graph.employees[(index * 7) % graph.employees.length]!.id,
}));
const scheduleConflicts = scheduleConflictPairs.map((pair, index) => ({
id: id("schedule-conflict", index),
entryId: pair.entryId,
sourceEntryId: pair.sourceEntryId,
resolvedAt: index % 3 === 0 ? null : addDays(scheduleEntries.find(({ id: entryId }) => entryId === pair.entryId)!.startAt, -2),
}));
const billableProjects = graph.projects.filter((project) => project.pipeline === "auftrag" || project.stage === "gewonnen");
const invoiceProjects = Array.from({ length: OPERATIONAL_COUNTS.invoices }, (_, index) => billableProjects[index % billableProjects.length]!);
const invoices = invoiceProjects.map((project, index): SeedInvoice => {
const status: SeedInvoice["status"] =
project.stage === "storniert"
? "storniert"
: project.stage === "abgeschlossen"
? index % 7 === 0
? "gestellt"
: "bezahlt"
: project.stage === "abnahme" && index % 3 === 0
? "gestellt"
: "entwurf";
const date = earlierDate(addDays(project.createdAt, 3 + (index % 21)), graph.referenceDate);
const createdAt = earlierDate(addDays(project.createdAt, index % 3), date);
const lifecycleOffsetDays = status === "bezahlt" ? 7 + (index % 7) : status === "storniert" ? 2 + (index % 4) : status === "gestellt" ? 1 : 0;
return {
id: id("invoice", index),
projectId: project.id,
invoiceNumber: `RE-${new Date(date).getUTCFullYear()}-${String(70419 + index)}`,
amount: euro(project.orderVolume ?? project.potentialOrderValue, index % 4 === 0 ? 0.35 : 1),
status,
date,
dueAt: addDays(date, 14),
fileId: null,
createdAt,
updatedAt: laterDate(createdAt, earlierDate(addDays(date, lifecycleOffsetDays), graph.referenceDate)),
};
});
const checklistProjects = graph.projects
.filter((project) => project.pipeline === "auftrag" || project.stage === "gewonnen")
.slice(0, OPERATIONAL_COUNTS.checklists);
const checklists = checklistProjects.map(
(project, index): SeedChecklist => ({
id: id("checklist", index),
projectId: project.id,
title:
project.stage === "abnahme" || project.stage === "abgeschlossen"
? `Abnahmedokumentation ${project.projectNumber}`
: `Ausführungscheckliste ${project.projectNumber}`,
type: project.stage === "abnahme" ? "abnahme_doku" : index % 9 === 0 ? "maengel" : "generisch",
})
);
const checklistItemTitles = [
"Arbeitsbereich und Absperrungen vorbereitet",
"Material und Bauteile vollständig geprüft",
"Montage nach Herstellervorgaben ausgeführt",
"Messwerte und Druckprobe dokumentiert",
"Arbeitsbereich gereinigt und Kunde eingewiesen",
"Restpunkt mit Verantwortlichem und Termin erfasst",
] as const;
const checklistItems: SeedChecklistItem[] = [];
for (const [checklistIndex, checklist] of checklists.entries()) {
const project = graph.projects.find(({ id: projectId }) => projectId === checklist.projectId)!;
const projectCrew = crewById.get(project.crewIds[0]!)!;
const itemCount = checklistIndex < 48 ? 6 : 5;
for (let position = 0; position < itemCount; position += 1) {
checklistItems.push({
id: id("checklist-item", checklistItems.length),
checklistId: checklist.id,
title: checklistItemTitles[position]!,
status: checklistIndex % 4 === 0 && position > 2 ? "offen" : position === 5 && checklistIndex % 13 === 0 ? "entfaellt" : "erledigt",
defectClass: checklist.type === "maengel" && position === 3 ? "B" : null,
assignedToUserId: projectCrew.memberEmployeeIds[position % projectCrew.memberEmployeeIds.length]!,
dueAt: addDays(project.deadline ?? graph.referenceDate, position - 3),
position,
photoFileId: null,
});
}
}
const files: SeedFile[] = [];
const fileNames = ["Angebot", "Aufmaß", "Montageprotokoll", "Anlagenschema", "Messprotokoll", "Rechnung", "Abnahmeprotokoll"] as const;
for (const [projectIndex, project] of graph.projects.entries()) {
const fileCount = projectIndex < 380 ? 2 : 1;
for (let slot = 0; slot < fileCount; slot += 1) {
const ordinal = files.length;
const baseName = fileNames[(projectIndex + slot) % fileNames.length]!;
const descriptor = {
id: id("file", ordinal),
displayName: `${baseName}_${project.projectNumber}.pdf`,
notes: `Projektunterlage zu ${project.projectName}; dem Projekt ${project.projectNumber} zugeordnet.`,
};
files.push({
...buildSeedFileObjectMetadata(descriptor),
projectId: project.id,
assignedToUserId: project.projectManagerEmployeeId,
tags: [baseName],
linkRole: baseName.toLowerCase(),
createdAt: earlierDate(addDays(project.createdAt, 2 + slot), graph.referenceDate),
updatedAt: earlierDate(addDays(project.createdAt, 2 + slot), graph.referenceDate),
});
}
}
const invoiceFilesByProject = new Map<string, SeedFile[]>();
for (const file of files.filter(({ displayName }) => displayName.startsWith("Rechnung_"))) {
const projectFiles = invoiceFilesByProject.get(file.projectId) ?? [];
projectFiles.push(file);
invoiceFilesByProject.set(file.projectId, projectFiles);
}
for (const invoice of invoices) {
const projectFiles = invoiceFilesByProject.get(invoice.projectId);
invoice.fileId = projectFiles?.shift()?.id ?? null;
}
const acceptanceEligible = graph.projects.filter((project) => project.pipeline === "auftrag" && ["abnahme", "abgeschlossen"].includes(project.stage));
const defectAcceptanceProjects = acceptanceEligible
.filter((project) => checklists.find(({ projectId }) => projectId === project.id)?.type === "maengel")
.slice(0, 10);
const defectProjectIds = new Set(defectAcceptanceProjects.map(({ id: projectId }) => projectId));
const acceptanceProjects = [
...defectAcceptanceProjects,
...acceptanceEligible.filter((project) => !defectProjectIds.has(project.id)).slice(0, OPERATIONAL_COUNTS.acceptances - defectAcceptanceProjects.length),
];
const acceptances = acceptanceProjects.map((project, index): SeedAcceptance => {
const primaryContact = project.contacts.find(({ primary }) => primary)!.contactId;
const checklist = checklists.find(({ projectId }) => projectId === project.id);
const kind: SeedAcceptance["kind"] = index < defectAcceptanceProjects.length ? "with_defects" : "full";
const date = earlierDate(addDays(project.deadline ?? graph.referenceDate, index % 3), addDays(graph.referenceDate, -1));
const documentFileId = files.find((file) => file.projectId === project.id && file.displayName.startsWith("Abnahmeprotokoll_"))?.id ?? null;
const attendees = [...new Set([contactDisplayName(graph, primaryContact), contactDisplayName(graph, project.contacts.at(-1)!.contactId)])];
if (attendees.length < 2) attendees.push(employeeDisplayName(graph, project.projectManagerEmployeeId));
return {
id: id("acceptance", index),
projectId: project.id,
checklistId: checklist?.id ?? null,
creatorUserId: project.projectManagerEmployeeId,
date,
kind,
attendees: attendees.slice(0, 2),
remarks:
kind === "with_defects"
? "Abnahme mit dokumentierten Restpunkten und verbindlichem Nachtermin."
: "Leistung gemeinsam geprüft, Anlage erläutert und ohne Vorbehalt abgenommen.",
customerEmail: contactEmail(graph, primaryContact),
documentFileId,
createdAt: date,
updatedAt: addDays(date, 0, 15),
};
});
const acceptanceSignatures = acceptances.flatMap((acceptance, index) => {
const project = graph.projects.find(({ id: projectId }) => projectId === acceptance.projectId)!;
const crew = crewById.get(project.crewIds[0]!)!;
return [
{
id: id("acceptance-signature", index * 2),
acceptanceId: acceptance.id,
signerName: acceptance.attendees[0]!,
signerRole: "kunde" as const,
signedAt: addDays(acceptance.date, 0, 15),
},
{
id: id("acceptance-signature", index * 2 + 1),
acceptanceId: acceptance.id,
signerName: employeeDisplayName(graph, crew.memberEmployeeIds[0]!),
signerRole: "monteur" as const,
signedAt: addDays(acceptance.date, 0, 15),
},
];
});
const signatureProjects = graph.projects
.filter(
(project) =>
project.pipeline === "sales" &&
["angebot", "gewonnen"].includes(project.stage) &&
files.some((file) => file.projectId === project.id && file.displayName.startsWith("Angebot_"))
)
.slice(0, OPERATIONAL_COUNTS.signatureDocuments);
const signatureDocuments = signatureProjects.map((project, index): SeedSignatureDocument => {
const primaryContact = project.contacts.find(({ primary }) => primary)!.contactId;
const status: SeedSignatureDocument["status"] = index % 4 === 0 ? "sent" : index % 4 === 1 ? "viewed" : "signed";
const sentAt = addDays(project.createdAt, 4 + (index % 8));
const completedAt = status === "signed" ? addDays(sentAt, 2 + (index % 5)) : null;
return {
id: id("signature-document", index),
projectId: project.id,
sourceFileId: files.find((file) => file.projectId === project.id && file.displayName.startsWith("Angebot_"))!.id,
creatorUserId: project.responsibleEmployeeId,
status,
title: `Angebot ${project.projectNumber} zur elektronischen Freigabe`,
sentAt,
completedAt,
signerContactId: primaryContact,
signerEmail: contactEmail(graph, primaryContact),
signerName: contactDisplayName(graph, primaryContact),
createdAt: sentAt,
updatedAt: completedAt ?? (status === "viewed" ? new Date(new Date(sentAt).getTime() + 3_600_000).toISOString() : sentAt),
};
});
const signatureSigners = signatureDocuments.map((document, index) => ({
id: id("signature-signer", index),
documentId: document.id,
contactId: document.signerContactId,
email: document.signerEmail,
name: document.signerName,
status: document.status,
signedAt: document.completedAt,
}));
const operational: DemoProOperationalGraph = {
projectContacts,
projectMembers,
tasks,
taskWatchers,
activities,
scheduleEntries,
scheduleConflicts,
calendarEvents,
projectAppointments,
bookingPages,
bookingProviders,
availabilityRules,
availabilityExceptions,
bookingAppointments,
invoices,
checklists,
checklistItems,
files,
acceptances,
acceptanceSignatures,
signatureDocuments,
signatureSigners,
};
validateOperationalGraph(operational, graph.referenceDate);
return operational;
}
export function validateOperationalGraph(graph: DemoProOperationalGraph, referenceDate: string): void {
for (const [key, expected] of Object.entries(OPERATIONAL_COUNTS)) {
const actual = graph[key as keyof DemoProOperationalGraph].length;
if (actual !== expected) throw new Error(`Operational seed ${key}: expected ${expected}, received ${actual}.`);
}
if (graph.tasks.some((task) => Number(Boolean(task.assignedToUserId)) + Number(Boolean(task.assignedToGroupId)) !== 1)) {
throw new Error("Every operational task must have exactly one assignee.");
}
if (new Set(graph.scheduleEntries.map(({ id: entryId }) => entryId)).size !== graph.scheduleEntries.length) {
throw new Error("Operational schedule IDs must be unique.");
}
const reference = new Date(referenceDate);
const invalidTask = graph.tasks.find(
(task) =>
new Date(task.createdAt) > new Date(task.updatedAt) ||
new Date(task.updatedAt) > reference ||
(task.completedAt !== null && (new Date(task.completedAt) < new Date(task.createdAt) || new Date(task.completedAt) > reference)) ||
(task.status === "done") !== (task.completedAt !== null)
);
if (invalidTask) throw new Error(`Operational task ${invalidTask.id} timestamps violate the task lifecycle.`);
if (
graph.invoices.some(
(invoice) =>
new Date(invoice.createdAt) > new Date(invoice.date) ||
new Date(invoice.date) > new Date(invoice.updatedAt) ||
new Date(invoice.updatedAt) > reference ||
new Date(invoice.date) > new Date(invoice.dueAt)
)
) {
throw new Error("Operational invoice timestamps violate the invoice lifecycle.");
}
if (graph.files.some((file) => new Date(file.createdAt) > new Date(file.updatedAt) || new Date(file.updatedAt) > reference)) {
throw new Error("Operational file timestamps violate the file lifecycle.");
}
if (
graph.acceptances.some(
(acceptance) =>
new Date(acceptance.date) > new Date(acceptance.createdAt) ||
new Date(acceptance.createdAt) > new Date(acceptance.updatedAt) ||
new Date(acceptance.updatedAt) > reference
)
) {
throw new Error("Operational acceptance timestamps violate the acceptance lifecycle.");
}
if (
graph.signatureDocuments.some(
(document) =>
document.createdAt !== document.sentAt ||
new Date(document.createdAt) > new Date(document.updatedAt) ||
new Date(document.updatedAt) > reference ||
(document.status === "signed") !== (document.completedAt !== null) ||
(document.completedAt !== null && document.updatedAt !== document.completedAt)
)
) {
throw new Error("Operational signature timestamps violate the signature lifecycle.");
}
const calendarEventsById = new Map(graph.calendarEvents.map((event) => [event.id, event]));
if (
graph.scheduleEntries.some((entry) => {
if (entry.calendarEventId === null) return entry.syncStatus !== "pending";
const event = calendarEventsById.get(entry.calendarEventId);
return (
entry.syncStatus !== "synced" ||
!event ||
event.projectId !== entry.projectId ||
event.userId !== entry.assignedUserId ||
event.startsAt !== entry.startAt ||
event.endsAt !== entry.endAt
);
})
) {
throw new Error("Operational schedule entries claim calendar sync without an exact matching event.");
}
const filesById = new Map(graph.files.map((file) => [file.id, file]));
const linkedInvoiceFileIds = graph.invoices.flatMap(({ fileId }) => (fileId ? [fileId] : []));
if (
new Set(linkedInvoiceFileIds).size !== linkedInvoiceFileIds.length ||
graph.invoices.some((invoice) => {
if (invoice.fileId === null) return false;
const file = filesById.get(invoice.fileId);
return !file || file.projectId !== invoice.projectId || !file.displayName.startsWith("Rechnung_");
})
) {
throw new Error("Operational invoices contain ambiguous or semantically invalid file links.");
}
if (graph.checklistItems.some(({ photoFileId }) => photoFileId !== null)) {
throw new Error("Operational checklist items cannot use generated PDF files as photos.");
}
if (
graph.acceptances.some((acceptance) => {
if (acceptance.documentFileId === null) return false;
const file = filesById.get(acceptance.documentFileId);
return !file || file.projectId !== acceptance.projectId || !file.displayName.startsWith("Abnahmeprotokoll_");
})
) {
throw new Error("Operational acceptances contain semantically invalid document links.");
}
}
@@ -0,0 +1,176 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { type DbClient } from "@hivegrid/db/client.server";
import { verifySupportedPassword } from "../../apps/api/src/auth/password";
import { hashDemoProUserPassword, renewDemoProSeedLease, resetDemoProTenant, startDemoProSeedLeaseHeartbeat, type DemoProSeedLease } from "./persistence";
const lease: DemoProSeedLease = {
tenantId: "tenant_staging_demo_pro",
tenantSlug: "demo-pro-crm",
lockId: "demo-pro-seed-lock-tenant_staging_demo_pro",
token: "lease-token",
};
function leaseDb(updateMany: ReturnType<typeof vi.fn>): DbClient {
return { outboxEvent: { updateMany } } as unknown as DbClient;
}
afterEach(() => {
vi.useRealTimers();
});
describe("demo-pro seed lease heartbeat", () => {
it("renews only the lock owned by the current run", async () => {
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
await renewDemoProSeedLease(leaseDb(updateMany), lease);
expect(updateMany).toHaveBeenCalledWith({
where: {
id: lease.lockId,
tenantId: lease.tenantId,
lastError: lease.token,
status: "PROCESSING",
},
data: { lockedUntil: expect.any(Date) },
});
});
it("keeps renewing until stopped", async () => {
vi.useFakeTimers();
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
const heartbeat = startDemoProSeedLeaseHeartbeat(leaseDb(updateMany), lease, 1_000);
await heartbeat.assertHealthy();
await vi.advanceTimersByTimeAsync(3_000);
await heartbeat.assertHealthy();
expect(updateMany).toHaveBeenCalledTimes(4);
await heartbeat.stop();
await vi.advanceTimersByTimeAsync(3_000);
expect(updateMany).toHaveBeenCalledTimes(4);
});
it("fails closed when lease ownership is lost", async () => {
vi.useFakeTimers();
const updateMany = vi.fn().mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
const heartbeat = startDemoProSeedLeaseHeartbeat(leaseDb(updateMany), lease, 1_000);
await heartbeat.assertHealthy();
await vi.advanceTimersByTimeAsync(1_000);
await expect(heartbeat.assertHealthy()).rejects.toThrow("tenant lease was lost during execution");
await expect(heartbeat.stop()).rejects.toThrow("tenant lease was lost during execution");
});
});
describe("demo-pro seed password hashing", () => {
it("uses the app-standard Argon2id hash format", async () => {
const password = "R7!qL2#vN9@xP4$kT8&m";
const hash = await hashDemoProUserPassword(password);
expect(hash).toMatch(/^\$argon2id\$/u);
await expect(verifySupportedPassword(password, hash)).resolves.toBe(true);
});
});
describe("demo-pro tenant identity reset", () => {
it("revokes John, Luna and admin sessions while preserving other memberships and global account state", async () => {
const targetTenantId = "tenant_staging_demo_pro";
const previousMemberIds = ["old-john", "old-luna", "old-admin", "seed-existing"];
const seedEmployeeIds = ["seed-existing", "seed-new"];
const order: string[] = [];
const tenantUserDeleteMany = vi.fn(async () => {
order.push("purge-target-members");
return { count: previousMemberIds.length };
});
const userSessionDeleteMany = vi.fn().mockResolvedValue({ count: 5 });
const trustedDeviceDeleteMany = vi.fn().mockResolvedValue({ count: 5 });
const magicLinkTokenDeleteMany = vi.fn().mockResolvedValue({ count: 5 });
const deviceTokenDeleteMany = vi.fn().mockResolvedValue({ count: 5 });
const roleDeleteMany = vi.fn().mockResolvedValue({ count: 7 });
const userUpdateMany = vi.fn().mockResolvedValue({ count: 1 });
const fallbackDelegates = new Map<string, { deleteMany: ReturnType<typeof vi.fn> }>();
const txTarget = {
$executeRaw: vi.fn().mockResolvedValue(undefined),
tenantUser: {
findMany: vi.fn(async () => {
order.push("capture-members");
return previousMemberIds.map((userId) => ({ userId }));
}),
deleteMany: tenantUserDeleteMany,
},
knowledgeBase: {
findMany: vi.fn().mockResolvedValue([]),
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
knowledgeBaseArticle: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }) },
knowledgeBaseCategory: { deleteMany: vi.fn().mockResolvedValue({ count: 0 }) },
outboxEvent: {
createMany: vi.fn(async ({ data }: { data: unknown[] }) => ({ count: data.length })),
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
userSession: { deleteMany: userSessionDeleteMany },
trustedDevice: { deleteMany: trustedDeviceDeleteMany },
magicLinkToken: { deleteMany: magicLinkTokenDeleteMany },
deviceToken: { deleteMany: deviceTokenDeleteMany },
role: { deleteMany: roleDeleteMany },
user: { updateMany: userUpdateMany },
};
const tx = new Proxy(txTarget as Record<string, unknown>, {
get(target, property, receiver) {
if (Reflect.has(target, property)) return Reflect.get(target, property, receiver);
const key = String(property);
const delegate = fallbackDelegates.get(key) ?? { deleteMany: vi.fn().mockResolvedValue({ count: 0 }) };
fallbackDelegates.set(key, delegate);
return delegate;
},
});
const db = {
tenant: {
findUnique: vi.fn().mockResolvedValue({ id: targetTenantId, slug: "demo-pro-crm", name: "Demo Pro CRM" }),
},
outboxEvent: {
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
count: vi.fn().mockResolvedValue(0),
},
$transaction: vi.fn(async (callback: (transaction: unknown) => Promise<unknown>) => callback(tx)),
} as unknown as DbClient;
await resetDemoProTenant(db, "demo-pro-crm", seedEmployeeIds);
expect(order).toEqual(["capture-members", "purge-target-members"]);
expect(tenantUserDeleteMany).toHaveBeenCalledTimes(1);
expect(tenantUserDeleteMany).toHaveBeenCalledWith({ where: { tenantId: targetTenantId } });
expect(roleDeleteMany).toHaveBeenCalledWith({
where: {
tenantId: targetTenantId,
OR: [{ isTemplateOrigin: true }, { name: { in: expect.arrayContaining(["Geschäftsführer", "Monteur"]) } }],
},
});
for (const deleteMany of [userSessionDeleteMany, trustedDeviceDeleteMany, magicLinkTokenDeleteMany]) {
expect(deleteMany).toHaveBeenCalledWith({ where: { userId: { in: seedEmployeeIds } } });
}
expect(deviceTokenDeleteMany).toHaveBeenCalledWith({ where: { tenantId: targetTenantId } });
expect(deviceTokenDeleteMany).toHaveBeenCalledWith({ where: { userId: { in: seedEmployeeIds } } });
expect(userUpdateMany).toHaveBeenNthCalledWith(1, {
where: { id: { in: previousMemberIds }, defaultTenantId: targetTenantId },
data: { defaultTenantId: null },
});
expect(userUpdateMany).toHaveBeenNthCalledWith(2, {
where: { id: { in: seedEmployeeIds } },
data: expect.objectContaining({
active: false,
defaultTenantId: null,
passwordHash: null,
totpSecretEncrypted: null,
mfaRecoveryCodeHashes: expect.anything(),
}),
});
const seedResetIds = userUpdateMany.mock.calls[1]![0].where.id.in as string[];
expect(seedResetIds).not.toContain("old-john");
expect(seedResetIds).not.toContain("old-luna");
expect(seedResetIds).not.toContain("old-admin");
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,35 @@
import { OUTBOX_MAX_PAYLOAD_BYTES } from "@hivegrid/db/outbox";
import { describe, expect, it } from "vitest";
import { generateDemoProSeed } from "./generator";
import { generateOperationalGraph } from "./operations";
import { splitSearchPayload } from "./search-batches";
describe("demo-pro search outbox batches", () => {
it("keeps the largest generated task payloads below the outbox hard limit", () => {
const graph = generateDemoProSeed();
const operational = generateOperationalGraph(graph);
const tenantId = "tenant-demo-pro";
const documents = operational.tasks.map((task) => ({
id: task.id,
tenantId,
title: task.title,
description: task.description,
status: task.status,
priority: task.priority,
linkedEntityId: task.projectId,
deadline: task.deadline,
}));
const payloadFor = (batch: readonly (typeof documents)[number][]) => ({
action: "upsert-batch",
indexName: "tasks",
tenantId,
documents: batch,
});
const batches = splitSearchPayload(documents, payloadFor);
expect(batches.flat()).toEqual(documents);
expect(batches.length).toBeLessThan(20);
expect(batches.every((batch) => Buffer.byteLength(JSON.stringify(payloadFor(batch)), "utf8") < OUTBOX_MAX_PAYLOAD_BYTES)).toBe(true);
});
});
@@ -0,0 +1,29 @@
import { OUTBOX_MAX_PAYLOAD_BYTES } from "@hivegrid/db/outbox";
const SEARCH_OUTBOX_SAFETY_MARGIN_BYTES = 8 * 1024;
export const SEARCH_OUTBOX_TARGET_BYTES = OUTBOX_MAX_PAYLOAD_BYTES - SEARCH_OUTBOX_SAFETY_MARGIN_BYTES;
function payloadBytes(value: unknown): number {
return Buffer.byteLength(JSON.stringify(value), "utf8");
}
export function splitSearchPayload<T>(values: readonly T[], payloadFor: (batch: readonly T[]) => unknown, maxItems = 250): T[][] {
const batches: T[][] = [];
let current: T[] = [];
for (const value of values) {
const candidate = [...current, value];
if (candidate.length <= maxItems && payloadBytes(payloadFor(candidate)) <= SEARCH_OUTBOX_TARGET_BYTES) {
current = candidate;
continue;
}
if (current.length === 0) throw new Error("demo-pro seed: one search document exceeds the safe outbox payload size");
batches.push(current);
current = [value];
if (payloadBytes(payloadFor(current)) > SEARCH_OUTBOX_TARGET_BYTES) {
throw new Error("demo-pro seed: one search document exceeds the safe outbox payload size");
}
}
if (current.length > 0) batches.push(current);
return batches;
}
@@ -0,0 +1,118 @@
import { ALL_SEARCH_INDEXES, createSearchClient, crmContactsIndex, type SearchClient } from "../../packages/search/src/index";
import { createInMemoryMeili } from "../../packages/search/src/testing";
import { describe, expect, it } from "vitest";
import { generateDemoProSeed } from "./generator";
import { generateOperationalGraph } from "./operations";
import { expectedDemoProSearchCounts, expectedDemoProSearchIds, type DemoProSearchIds, waitForDemoProSearch } from "./search-verification";
describe("demo-pro final search verification", () => {
it("requires every registered index to be empty after cleanup", () => {
expect(Object.values(expectedDemoProSearchCounts("cleanup")).every((count) => count === 0)).toBe(true);
});
it("derives the exact expected document IDs from the complete seed graphs", () => {
const graph = generateDemoProSeed();
const operational = generateOperationalGraph(graph);
const ids = expectedDemoProSearchIds(graph, operational);
const counts = expectedDemoProSearchCounts("apply");
for (const schema of ALL_SEARCH_INDEXES) {
expect(ids[schema.name]).toHaveLength(counts[schema.name]);
expect(new Set(ids[schema.name]).size).toBe(counts[schema.name]);
}
});
it("reads tenant-isolated counts from Meilisearch", async () => {
const meili = createInMemoryMeili();
const client = createSearchClient({ url: "http://memory", meiliFactory: meili.factory });
await client.index(crmContactsIndex.name).upsert([{ id: "tenant-a:contact-1", tenantId: "tenant-a", entityType: "contact" }]);
await expect(waitForDemoProSearch({ tenantId: "tenant-b", mode: "cleanup", timeoutMs: 0, client })).resolves.toMatchObject({
[crmContactsIndex.name]: 0,
});
});
it("uses exact tenant facets when estimated hits are capped", async () => {
const meili = createInMemoryMeili({ maxTotalHits: 1_000 });
const client = createSearchClient({ url: "http://memory", meiliFactory: meili.factory });
const expected = expectedDemoProSearchCounts("apply");
const expectedIds: DemoProSearchIds = {};
for (const schema of ALL_SEARCH_INDEXES) {
const count = expected[schema.name] ?? 0;
expectedIds[schema.name] = Array.from({ length: count }, (_, index) => `${schema.name}-${index}`);
await client.index(schema.name).upsert(
expectedIds[schema.name]!.map((id) => ({
id,
tenantId: "tenant-a",
}))
);
}
await expect(waitForDemoProSearch({ tenantId: "tenant-a", mode: "apply", timeoutMs: 0, client, expectedIdsByIndex: expectedIds })).resolves.toMatchObject({
tasks: 1_684,
});
});
it("fails when an index below the pagination cap has the right count but the wrong IDs", async () => {
const meili = createInMemoryMeili({ maxTotalHits: 1_000 });
const client = createSearchClient({ url: "http://memory", meiliFactory: meili.factory });
const expected = expectedDemoProSearchCounts("apply");
const expectedIds: DemoProSearchIds = {};
for (const schema of ALL_SEARCH_INDEXES) {
const count = expected[schema.name] ?? 0;
expectedIds[schema.name] = Array.from({ length: count }, (_, index) => `${schema.name}-${index}`);
await client.index(schema.name).upsert(
expectedIds[schema.name]!.map((id, index) => ({
id: schema.name === crmContactsIndex.name && index === 0 ? "unexpected-contact" : id,
tenantId: "tenant-a",
}))
);
}
await expect(waitForDemoProSearch({ tenantId: "tenant-a", mode: "apply", timeoutMs: 0, client, expectedIdsByIndex: expectedIds })).rejects.toThrow(
/document IDs differ/u
);
});
it("fails closed when Meilisearch omits tenant facets", async () => {
const client = createFacetClient(undefined);
await expect(waitForDemoProSearch({ tenantId: "tenant-a", mode: "cleanup", timeoutMs: 0, client })).rejects.toThrow(
/did not return an exact facet distribution/u
);
});
it("fails closed when a facet is empty despite matching documents", async () => {
const client = createFacetClient({}, 1);
await expect(waitForDemoProSearch({ tenantId: "tenant-a", mode: "cleanup", timeoutMs: 0, client })).rejects.toThrow(/omitted the tenant facet count/u);
});
it.each([-1, 1.5, Number.NaN])("rejects invalid exact tenant facet count %s", async (count) => {
const client = createFacetClient({ "tenant-a": count });
await expect(waitForDemoProSearch({ tenantId: "tenant-a", mode: "cleanup", timeoutMs: 0, client })).rejects.toThrow(/invalid tenant facet count/u);
});
});
function createFacetClient(tenantFacet: Record<string, number> | undefined, estimatedTotalHits = 0): SearchClient {
return {
index() {
return {
async ensure() {},
async search() {
return {
hits: [],
estimatedTotalHits,
...(tenantFacet === undefined ? {} : { facetDistribution: { tenantId: tenantFacet } }),
processingTimeMs: 0,
};
},
async upsert() {},
async delete() {},
async deleteByFilter() {},
};
},
async health() {
return { status: "available" };
},
};
}
@@ -0,0 +1,167 @@
import {
ALL_SEARCH_INDEXES,
createSearchClient,
crmContactsIndex,
filesIndex,
projectsIndex,
searchInIndex,
tasksIndex,
usersIndex,
type SearchClient,
} from "../../packages/search/src/index";
import type { DemoProOperationalGraph } from "./operations";
import type { DemoProSeedGraph } from "./types";
export type DemoProSearchCounts = Record<string, number>;
export type DemoProSearchIds = Record<string, readonly (string | number)[]>;
// Meilisearch caps search pagination at 1,000 documents by default. Counts
// remain exact through tenant facets; exact ID-set verification is performed
// for every index whose complete tenant slice fits inside that API boundary.
const MAX_EXACT_SEARCH_IDS = 1_000;
export function expectedDemoProSearchCounts(mode: "apply" | "cleanup"): DemoProSearchCounts {
const counts = Object.fromEntries(ALL_SEARCH_INDEXES.map(({ name }) => [name, 0]));
if (mode === "apply") {
counts[crmContactsIndex.name] = 976;
counts[projectsIndex.name] = 537;
counts[tasksIndex.name] = 1_684;
counts[filesIndex.name] = 917;
counts[usersIndex.name] = 50;
}
return counts;
}
export function expectedDemoProSearchIds(graph: DemoProSeedGraph, operational: DemoProOperationalGraph): DemoProSearchIds {
const ids: DemoProSearchIds = Object.fromEntries(ALL_SEARCH_INDEXES.map(({ name }) => [name, []]));
ids[crmContactsIndex.name] = [...graph.organizations, ...graph.persons, ...graph.leads].map(({ id }) => id);
ids[projectsIndex.name] = graph.projects.map(({ id }) => id);
ids[tasksIndex.name] = operational.tasks.map(({ id }) => id);
ids[filesIndex.name] = operational.files.map(({ id }) => id);
ids[usersIndex.name] = graph.employees.map(({ id }) => id);
return ids;
}
function searchId(value: string | number): string {
return `${typeof value === "number" ? "n" : "s"}:${String(value)}`;
}
function assertExpectedIds(ids: DemoProSearchIds, expectedCounts: DemoProSearchCounts): void {
for (const schema of ALL_SEARCH_INDEXES) {
const expectedIds = ids[schema.name];
if (!expectedIds) throw new Error(`demo-pro seed: expected Meilisearch IDs are missing for ${schema.name}`);
if (expectedIds.length !== expectedCounts[schema.name]) {
throw new Error(`demo-pro seed: expected Meilisearch ID count does not match ${schema.name}`);
}
if (new Set(expectedIds.map(searchId)).size !== expectedIds.length) {
throw new Error(`demo-pro seed: expected Meilisearch IDs are not unique for ${schema.name}`);
}
}
}
async function readSearchState(
client: SearchClient,
tenantId: string,
expectedIdsByIndex: DemoProSearchIds
): Promise<{ counts: DemoProSearchCounts; idMismatches: string[] }> {
const entries = await Promise.all(
ALL_SEARCH_INDEXES.map(async (schema) => {
const result = await searchInIndex({
client,
schema,
tenantId,
query: "",
options: { limit: 0, facets: ["tenantId"], attributesToRetrieve: [schema.primaryKey] },
});
if (!result.facetDistribution) {
throw new Error(`demo-pro seed: Meilisearch did not return an exact facet distribution for ${schema.name}`);
}
// Meilisearch returns an empty distribution (without the requested
// facet key) when the tenant filter has no matches. The response object
// itself is still mandatory so an unsupported/ignored facets request
// cannot be mistaken for an exact zero.
const count = result.facetDistribution.tenantId?.[tenantId] ?? 0;
if (count === 0 && result.estimatedTotalHits > 0) {
throw new Error(`demo-pro seed: Meilisearch omitted the tenant facet count for ${schema.name} despite matching documents`);
}
if (!Number.isSafeInteger(count) || count < 0) {
throw new Error(`demo-pro seed: Meilisearch returned an invalid tenant facet count for ${schema.name}`);
}
const expectedIds = expectedIdsByIndex[schema.name]!;
if (count !== expectedIds.length || expectedIds.length === 0 || expectedIds.length > MAX_EXACT_SEARCH_IDS) {
return { indexName: schema.name, count, idMismatch: null };
}
const documents = await searchInIndex({
client,
schema,
tenantId,
query: "",
options: {
limit: expectedIds.length,
offset: 0,
attributesToRetrieve: [schema.primaryKey],
},
});
const actualIds = documents.hits
.map(({ document }) => document[schema.primaryKey])
.map((value) => {
if (typeof value !== "string" && typeof value !== "number") {
throw new Error(`demo-pro seed: Meilisearch returned an invalid document ID for ${schema.name}`);
}
return searchId(value);
});
const actualIdSet = new Set(actualIds);
const expectedIdSet = new Set(expectedIds.map(searchId));
const exact =
actualIds.length === expectedIds.length &&
actualIdSet.size === actualIds.length &&
[...expectedIdSet].every((documentId) => actualIdSet.has(documentId));
return {
indexName: schema.name,
count,
idMismatch: exact ? null : `${schema.name}: tenant document IDs differ from the expected set`,
};
})
);
return {
counts: Object.fromEntries(entries.map(({ indexName, count }) => [indexName, count])),
idMismatches: entries.flatMap(({ idMismatch }) => (idMismatch ? [idMismatch] : [])),
};
}
export async function waitForDemoProSearch(input: {
tenantId: string;
mode: "apply" | "cleanup";
timeoutMs: number;
client?: SearchClient;
expectedIdsByIndex?: DemoProSearchIds;
}): Promise<DemoProSearchCounts> {
if (!input.client && !process.env.MEILI_URL) throw new Error("demo-pro seed: MEILI_URL is required for final search verification");
const client =
input.client ??
createSearchClient({
url: process.env.MEILI_URL!,
apiKey: process.env.MEILI_API_KEY,
timeout: 10_000,
});
const expected = expectedDemoProSearchCounts(input.mode);
const expectedIdsByIndex = input.mode === "cleanup" ? Object.fromEntries(ALL_SEARCH_INDEXES.map(({ name }) => [name, []])) : input.expectedIdsByIndex;
if (!expectedIdsByIndex) throw new Error("demo-pro seed: exact Meilisearch IDs are required for apply verification");
assertExpectedIds(expectedIdsByIndex, expected);
const deadline = Date.now() + input.timeoutMs;
let counts: DemoProSearchCounts = {};
let idMismatches: string[] = [];
do {
({ counts, idMismatches } = await readSearchState(client, input.tenantId, expectedIdsByIndex));
if (idMismatches.length === 0 && Object.entries(expected).every(([indexName, expectedCount]) => counts[indexName] === expectedCount)) {
return counts;
}
if (input.timeoutMs <= 0) break;
await new Promise((resolve) => setTimeout(resolve, 1_000));
} while (Date.now() < deadline);
throw new Error(
`demo-pro seed: Meilisearch did not reach the expected tenant state (${JSON.stringify(counts)}${
idMismatches.length > 0 ? `; ${idMismatches.join("; ")}` : ""
})`
);
}
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"include": ["./*.ts", "../seed-demo-pro-crm.ts", "../validate-demo-pro-geodata.ts"],
"exclude": ["./*.test.ts"],
"compilerOptions": {
"types": ["@react-router/node", "vite/client"],
"noEmit": true
}
}
@@ -0,0 +1,172 @@
export const DEMO_PRO_SEED_NAMESPACE = "rheinmain-shk-v1" as const;
export type SeedAddress = {
strasse: string;
hausnummer: string;
plz: string;
ort: string;
land: "DE";
};
export type SeedChannel = {
value: string;
primaer: boolean;
label: "geschäftlich" | "privat" | "mobil" | "zentrale" | "rechnung";
};
export type EmployeeRole = "Geschäftsführer" | "Vertriebsleiter" | "Vertriebler" | "Büro/Backoffice" | "Marketing" | "Projektleiter/Bauleiter" | "Monteur";
export type SeedEmployee = {
id: string;
firstName: string;
lastName: string;
email: string;
phone: string;
role: EmployeeRole;
jobTitle: string;
seatCategory: "office" | "field";
groupNames: string[];
crewId: string | null;
active: true;
locale: "de";
};
export type SeedCrew = {
id: string;
name: string;
memberEmployeeIds: [string, string];
projectManagerEmployeeId: string;
};
export type ContactStatus = "kontakt" | "kunde" | "bestandskunde";
export type SeedOrganization = {
id: string;
kontaktTyp: "organisation";
orgName: string;
orgMerkmal: "gmbh" | "kg" | "oeffentliche_einrichtung" | "sonstige";
branche: string;
kontaktStatus: ContactStatus;
email: string;
phone: string;
additionalEmails: SeedChannel[];
additionalPhones: SeedChannel[];
address: SeedAddress;
language: "de";
ownerEmployeeId: string;
tags: string[];
};
export type SeedPerson = {
id: string;
kontaktTyp: "privatperson";
firstName: string;
lastName: string;
salutation: "Frau" | "Herr" | "Divers";
kontaktStatus: ContactStatus;
email: string;
phone: string;
additionalEmails: SeedChannel[];
additionalPhones: SeedChannel[];
address: SeedAddress;
language: "de";
ownerEmployeeId: string;
tags: string[];
};
export type SeedContactRelation = {
id: string;
organizationId: string;
personId: string;
role: "hauptkontakt" | "sekundaerkontakt" | "mitarbeiter";
context: string;
};
export type ProjectType =
| "reparatur_notdienst"
| "wartung_pruefung"
| "heizungstausch"
| "heizungsoptimierung"
| "badsanierung"
| "sanitaer_rohrarbeiten"
| "objekt_neubau"
| "lueftung_klima";
export type SeedProjectContact = {
contactId: string;
role: "auftraggeber" | "bauherr" | "rechnungsempfaenger" | "ansprechpartner";
primary: boolean;
};
export type SeedProject = {
id: string;
projectNumber: string;
projectName: string;
description: string;
projectType: ProjectType;
source: "Bestandskunde" | "Empfehlung" | "Website" | "Telefon" | "Partner" | "Ausschreibung";
priority: "niedrig" | "normal" | "hoch" | "dringend";
pipeline: "sales" | "auftrag";
stage: string;
potentialOrderValue: string | null;
orderVolume: string | null;
createdAt: string;
startDate: string | null;
deadline: string | null;
responsibleEmployeeId: string;
projectManagerEmployeeId: string;
crewIds: string[];
projectAddress: SeedAddress;
invoiceAddress: SeedAddress;
clientAddress: SeedAddress;
convertedFromLeadId: string | null;
lostReason: string | null;
wonAt: string | null;
lostAt: string | null;
contacts: SeedProjectContact[];
tags: string[];
};
export type LeadOutcome = "spam" | "disqualified" | "offer_lost" | "converted";
export type SeedLead = {
id: string;
outcome: LeadOutcome;
status: "spam" | "lost" | "converted";
source: "form" | "email" | "aircall" | "manual" | "custom";
sourceOrigin: string;
createdAt: string;
ownerEmployeeId: string;
firstName: string;
lastName: string;
email: string;
phone: string;
message: string;
furtherProcessingConsent: "ja" | "nein" | "unklar";
spamScore: number;
spamReason: string | null;
isQuarantined: boolean;
linkedContactId: string | null;
convertedProjectId: string | null;
convertedAt: string | null;
lostAt: string | null;
disqualifiedReason: string | null;
};
export type DemoProSeedGraph = {
namespace: typeof DEMO_PRO_SEED_NAMESPACE;
generatedForTenantSlug: "demo-pro-crm";
referenceDate: string;
employees: SeedEmployee[];
crews: SeedCrew[];
organizations: SeedOrganization[];
persons: SeedPerson[];
contactRelations: SeedContactRelation[];
projects: SeedProject[];
leads: SeedLead[];
};
export type SeedValidationResult = {
valid: boolean;
errors: string[];
};