Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/scripts/demo-pro-seed/generator.ts
T

629 lines
30 KiB
TypeScript

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 };
}