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

2645 lines
114 KiB
TypeScript

#!/usr/bin/env tsx
// Rich, realistic SHK/Handwerk demo tenant for local exploration.
//
// Modelled after `scripts/seed-e2e-readiness.ts` (env guard, DB client import,
// idempotent Prisma calls, clean exit). Unlike the E2E fixture this seed fills a
// full craft-business workspace (contacts, pipelines, projects, leads, forms,
// bookings, calendar events, automations, tasks, invoices, activities,
// notifications, an API key and an incoming webhook) so the app is explorable
// end-to-end instead of empty.
//
// Guards: refuses to run in production and requires HIVEGRID_DEMO_SEED=1. The
// `seed:demo` package script sets the flag itself.
//
// Idempotency: every row uses a deterministic key (natural @@unique upsert where
// one exists, otherwise a `demo-*` primary key) so re-running the seed updates in
// place instead of duplicating. Demo-capable domain rows carry `isDemoData = true`.
import "dotenv/config";
import bcrypt from "bcryptjs";
import { deriveLegacyApiKeyHashMetadata } from "@hivegrid/db/api-keys.server";
import { getDbClient, type DbClient } from "@hivegrid/db/client.server";
import { Prisma } from "@hivegrid/db/prisma-browser";
import { syncDefaultRolesAndPermissions } from "@hivegrid/db/permissions-seed.server";
import { seedShkTemplateRolesForTenant } from "@hivegrid/db/shk-template-roles-seed.server";
import { entitlementPlanIds, featureKeys, productBlueprintIds } from "@hivegrid/entitlements";
type EnvRecord = Record<string, string | undefined>;
// TenantUser type/status/joined are Ints resolved via
// apps/web/app/application/enums/tenants/*. Mirrored here as local constants
// because scripts at repo root cannot import the web-app `~/` alias.
const TENANT_USER_TYPE = { OWNER: 0, ADMIN: 1, MEMBER: 2 } as const;
const TENANT_USER_STATUS_ACTIVE = 2; // TenantUserStatus.ACTIVE
const TENANT_USER_JOINED_CREATOR = 0; // TenantUserJoined.CREATOR
export const HIVEGRID_DEMO_TENANT_SLUG = "hivegrid-demo";
export const HIVEGRID_DEMO_TENANT_NAME = "HiveGrid Demo SHK";
export const HIVEGRID_DEMO_PASSWORD = "password";
export const HIVEGRID_DEMO_OWNER_EMAIL = "demo@hivegrid.de";
export const HIVEGRID_DEMO_API_KEY_ALIAS = "Website Lead Intake";
export const HIVEGRID_DEMO_WEBHOOK_SLUG = "website-kontaktformular";
const HIVEGRID_DEMO_SUBSCRIPTION_PRODUCT_BILLING_ID = "hivegrid_demo_business_plan";
const HIVEGRID_DEMO_SUBSCRIPTION_PRICE_BILLING_ID = "hivegrid_demo_business_price_monthly";
// Feature keys switched ON for the demo tenant so no surface is plan-gated.
const HIVEGRID_DEMO_ENABLED_FEATURE_KEYS = [
featureKeys.crmBasic,
featureKeys.leads,
featureKeys.projects,
featureKeys.billing,
featureKeys.api,
featureKeys.tasks,
featureKeys.files,
featureKeys.hr,
featureKeys.integrations,
featureKeys.booking,
featureKeys.forms,
featureKeys.automation,
featureKeys.emailInbox,
featureKeys.dashboard,
featureKeys.search,
] as const;
type DemoUserSeed = {
key: string;
email: string;
firstName: string;
lastName: string;
tenantUserType: (typeof TENANT_USER_TYPE)[keyof typeof TENANT_USER_TYPE];
appRoleNames: string[];
// Tenant-owned SHK template role (Fundament B) assigned in addition to the
// global app roles above, so the demo tenant shows the 7 SHK roles in use.
shkRoleName?: string;
};
// demo@ is guaranteed the global SuperUser role (all app permissions) → the
// fully-privileged login the DoD requires. On top, each demo user carries the
// matching SHK template role so the role editor shows them assigned.
const HIVEGRID_DEMO_USERS: DemoUserSeed[] = [
{ key: "owner", email: HIVEGRID_DEMO_OWNER_EMAIL, firstName: "Daniel", lastName: "Geschäftsführer", tenantUserType: TENANT_USER_TYPE.OWNER, appRoleNames: ["SuperUser"], shkRoleName: "Geschäftsführer" },
{ key: "buero", email: "buero@hivegrid.de", firstName: "Birgit", lastName: "Büro", tenantUserType: TENANT_USER_TYPE.ADMIN, appRoleNames: ["Admin", "Billing Admin"], shkRoleName: "Büro/Backoffice" },
{ key: "monteur", email: "monteur@hivegrid.de", firstName: "Murat", lastName: "Monteur", tenantUserType: TENANT_USER_TYPE.MEMBER, appRoleNames: ["User"], shkRoleName: "Monteur" },
{ key: "vertrieb", email: "vertrieb@hivegrid.de", firstName: "Vera", lastName: "Vertrieb", tenantUserType: TENANT_USER_TYPE.MEMBER, appRoleNames: ["User"], shkRoleName: "Vertriebler" },
];
type DemoContactSeed = {
key: string;
typ: "organisation" | "privatperson";
orgName?: string;
orgMerkmal?: "gmbh" | "kg" | "oeffentliche_einrichtung" | "sonstige";
vorname?: string;
nachname?: string;
status: "kontakt" | "kunde" | "bestandskunde";
email: string;
telefon: string;
adresse: { strasse: string; hausnummer: string; plz: string; ort: string };
// WF-P8 S02 Stufe B: the master data the contact cards on the project detail
// render read-only. Organisations use the upper block, persons the lower two,
// so a card is only filled with fields its own type can show.
stammdaten?: {
website?: string;
ustIdNr?: string;
handelsregister?: string;
kundennummer?: string;
kundeSeitIso?: string;
branche?: string;
mitarbeiterzahl?: number;
position?: string;
erreichbarkeit?: string;
notizen?: string;
};
// Additional phone numbers with their type, so the Durchwahl/Mobil/Fax rows
// have something to show next to the primary number.
weitereTelefone?: { key: string; telefon: string; typ: "durchwahl" | "mobil" | "fax" }[];
};
const HIVEGRID_DEMO_COMPANIES: DemoContactSeed[] = [
{
key: "hausverwaltung-mueller",
typ: "organisation",
orgName: "Hausverwaltung Müller & Partner GmbH",
orgMerkmal: "gmbh",
status: "bestandskunde",
email: "kontakt@hv-mueller.de",
telefon: "+49 761 5510101",
adresse: { strasse: "Kaiser-Joseph-Straße", hausnummer: "112", plz: "79098", ort: "Freiburg" },
stammdaten: {
website: "https://hv-mueller.de",
ustIdNr: "DE 812 345 678",
handelsregister: "HRB 24571, AG Freiburg",
kundennummer: "K-2021-0148",
kundeSeitIso: "2021-03-01",
branche: "Immobilienverwaltung",
mitarbeiterzahl: 24,
notizen:
"Rechnungen ausschließlich per E-Mail, Papierrechnungen werden nicht bearbeitet.\nZugang zu Objekten immer über die Hausverwaltung anmelden, Schlüsselübergabe nur werktags.",
},
weitereTelefone: [
{ key: "durchwahl", telefon: "+49 761 5510117", typ: "durchwahl" },
{ key: "fax", telefon: "+49 761 5510199", typ: "fax" },
],
},
{ key: "wohnbau-rheintal", typ: "organisation", orgName: "Wohnbaugenossenschaft Rheintal eG", orgMerkmal: "sonstige", status: "kunde", email: "info@wohnbau-rheintal.de", telefon: "+49 7531 220340", adresse: { strasse: "Seestraße", hausnummer: "8", plz: "78462", ort: "Konstanz" }, stammdaten: { website: "https://wohnbau-rheintal.de", kundennummer: "K-2019-0032", kundeSeitIso: "2019-09-15", branche: "Wohnungsbau", mitarbeiterzahl: 61 } },
{ key: "baeckerei-sonnenschein", typ: "organisation", orgName: "Bäckerei Sonnenschein GmbH", orgMerkmal: "gmbh", status: "bestandskunde", email: "buero@baeckerei-sonnenschein.de", telefon: "+49 761 4488220", adresse: { strasse: "Habsburgerstraße", hausnummer: "45", plz: "79104", ort: "Freiburg" } },
{ key: "restaurant-davinci", typ: "organisation", orgName: "Restaurant Da Vinci", orgMerkmal: "sonstige", status: "kunde", email: "reservierung@davinci-offenburg.de", telefon: "+49 781 9203040", adresse: { strasse: "Hauptstraße", hausnummer: "27", plz: "77652", ort: "Offenburg" } },
{ key: "autohaus-berg", typ: "organisation", orgName: "Autohaus Berg KG", orgMerkmal: "kg", status: "kontakt", email: "service@autohaus-berg.de", telefon: "+49 7721 660550", adresse: { strasse: "Schwenninger Straße", hausnummer: "3", plz: "78048", ort: "Villingen-Schwenningen" } },
{ key: "stadtwerke-musterstadt", typ: "organisation", orgName: "Stadtwerke Musterstadt", orgMerkmal: "oeffentliche_einrichtung", status: "kunde", email: "technik@stadtwerke-musterstadt.de", telefon: "+49 7641 880900", adresse: { strasse: "Rathausplatz", hausnummer: "1", plz: "79312", ort: "Emmendingen" } },
];
const HIVEGRID_DEMO_PERSONS: DemoContactSeed[] = [
{
key: "thomas-schneider",
typ: "privatperson",
vorname: "Thomas",
nachname: "Schneider",
status: "kunde",
email: "thomas.schneider@example.de",
telefon: "+49 761 1234501",
adresse: { strasse: "Lindenweg", hausnummer: "14", plz: "79110", ort: "Freiburg" },
stammdaten: {
position: "Eigentümer",
erreichbarkeit: "Werktags ab 16 Uhr, davor nur mobil",
notizen: "Entscheider für Budget und Vergabe. Möchte Angebote mit Einzelpositionen, keine Pauschalen.",
},
weitereTelefone: [{ key: "mobil", telefon: "+49 170 2345678", typ: "mobil" }],
},
{
key: "sabine-wagner",
typ: "privatperson",
vorname: "Sabine",
nachname: "Wagner",
status: "kunde",
email: "sabine.wagner@example.de",
telefon: "+49 7531 998877",
adresse: { strasse: "Am Seerhein", hausnummer: "5", plz: "78467", ort: "Konstanz" },
stammdaten: { position: "Objektbetreuung", erreichbarkeit: "Montag bis Donnerstag, 8 bis 15 Uhr" },
weitereTelefone: [{ key: "mobil", telefon: "+49 171 8765432", typ: "mobil" }],
},
{ key: "michael-becker", typ: "privatperson", vorname: "Michael", nachname: "Becker", status: "kontakt", email: "michael.becker@example.de", telefon: "+49 781 445566", adresse: { strasse: "Gartenstraße", hausnummer: "22", plz: "77654", ort: "Offenburg" } },
{ key: "andrea-hoffmann", typ: "privatperson", vorname: "Andrea", nachname: "Hoffmann", status: "kontakt", email: "andrea.hoffmann@example.de", telefon: "+49 7721 334455", adresse: { strasse: "Bergstraße", hausnummer: "9", plz: "78050", ort: "Villingen-Schwenningen" } },
{ key: "stefan-koch", typ: "privatperson", vorname: "Stefan", nachname: "Koch", status: "kunde", email: "stefan.koch@example.de", telefon: "+49 761 7788990", adresse: { strasse: "Merzhauser Straße", hausnummer: "77", plz: "79100", ort: "Freiburg" } },
{ key: "julia-braun", typ: "privatperson", vorname: "Julia", nachname: "Braun", status: "bestandskunde", email: "julia.braun@example.de", telefon: "+49 7641 221100", adresse: { strasse: "Bahnhofstraße", hausnummer: "31", plz: "79312", ort: "Emmendingen" } },
{ key: "markus-weber", typ: "privatperson", vorname: "Markus", nachname: "Weber", status: "kontakt", email: "markus.weber@example.de", telefon: "+49 761 6655440", adresse: { strasse: "Schwarzwaldstraße", hausnummer: "150", plz: "79117", ort: "Freiburg" } },
{ key: "petra-schulz", typ: "privatperson", vorname: "Petra", nachname: "Schulz", status: "kunde", email: "petra.schulz@example.de", telefon: "+49 7531 445500", adresse: { strasse: "Mainaustraße", hausnummer: "62", plz: "78464", ort: "Konstanz" } },
];
const ALL_DEMO_CONTACTS = [...HIVEGRID_DEMO_COMPANIES, ...HIVEGRID_DEMO_PERSONS];
type DemoStageSeed = { key: string; name: string; stageKind: "offen" | "gewonnen" | "verloren"; winProbability: number; color: string };
type DemoPipelineSeed = { key: string; name: string; typHint: "sales" | "auftrag" | "custom"; position: number; isDefault: boolean; stages: DemoStageSeed[] };
const HIVEGRID_DEMO_PIPELINES: DemoPipelineSeed[] = [
{
key: "sales",
name: "Vertriebs-Pipeline",
typHint: "sales",
position: 0,
isDefault: true,
stages: [
{ key: "neu", name: "Neu", stageKind: "offen", winProbability: 10, color: "#3b82f6" },
{ key: "qualifiziert", name: "Qualifiziert", stageKind: "offen", winProbability: 30, color: "#6366f1" },
{ key: "angebot", name: "Angebot", stageKind: "offen", winProbability: 60, color: "#f59e0b" },
{ key: "gewonnen", name: "Gewonnen", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
{ key: "verloren", name: "Verloren", stageKind: "verloren", winProbability: 0, color: "#ef4444" },
],
},
{
key: "auftrag",
name: "Auftrags-Pipeline",
typHint: "auftrag",
position: 1,
isDefault: false,
stages: [
{ key: "geplant", name: "Geplant", stageKind: "offen", winProbability: 100, color: "#3b82f6" },
{ key: "ausfuehrung", name: "In Ausführung", stageKind: "offen", winProbability: 100, color: "#f59e0b" },
{ key: "abnahme", name: "Abnahme", stageKind: "offen", winProbability: 100, color: "#8b5cf6" },
{ key: "abgeschlossen", name: "Abgeschlossen", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
],
},
];
type DemoAddressSeed = {
strasse: string;
hausnummer: string;
plz: string;
ort: string;
// Slot extras from ProjektAdressDetail. Each slot only carries its own: a
// Zahlungsziel belongs to the invoice address, a Zufahrt to the site.
bauabschnitt?: string;
zufahrt?: string;
koordinaten?: string;
empfaenger?: string;
zahlungsziel?: string;
rechnungsEmail?: string;
postErwuenscht?: boolean;
telefon?: string;
ansprechpartnerVorOrt?: string;
notizen?: string;
};
type DemoProjectSeed = {
key: string;
nummer: string;
name: string;
pipeline: "sales" | "auftrag";
stage: string;
prioritaet: "niedrig" | "normal" | "hoch" | "dringend";
contactKey: string;
potenziellerAuftragswert?: string;
auftragsvolumen?: string;
won?: boolean;
lost?: boolean;
// WF-P8 S02: the detail screen's Grunddaten and Planung sections. Without
// these the flagship project renders as a page of empty fields.
quelle?: string;
promotion?: string;
beschreibung?: string;
startOffsetDays?: number;
deadlineOffsetDays?: number;
kontaktdaten?: { email?: string; telefon?: string; fax?: string };
projektleiterKey?: string;
zustaendigeKeys?: string[];
monteurKeys?: string[];
adressen?: { projekt?: DemoAddressSeed; rechnung?: DemoAddressSeed; bauherr?: DemoAddressSeed };
};
const HIVEGRID_DEMO_PROJECTS: DemoProjectSeed[] = [
// The flagship project: every S02 section has to have something to render, so
// this one carries source, promotion, dates, project contact data, a project
// lead, members and all three address slots including their extras.
{
key: "heizungstausch-schneider",
nummer: "P-00001",
name: "Heizungstausch EFH Schneider",
pipeline: "sales",
stage: "angebot",
prioritaet: "hoch",
contactKey: "thomas-schneider",
potenziellerAuftragswert: "18500.00",
quelle: "Empfehlung",
promotion: "Wärmepumpen-Bonus",
beschreibung: "Austausch des Gaskessels von 1998 gegen eine Luft-Wasser-Wärmepumpe, inklusive Heizlastberechnung und hydraulischem Abgleich.",
startOffsetDays: 12,
deadlineOffsetDays: 47,
kontaktdaten: { email: "bauleitung@schneider-efh.de", telefon: "+49 761 1234599", fax: "+49 761 1234598" },
projektleiterKey: "buero",
zustaendigeKeys: ["vertrieb", "buero"],
monteurKeys: ["monteur"],
adressen: {
projekt: {
strasse: "Lindenallee",
hausnummer: "14",
plz: "79110",
ort: "Freiburg",
bauabschnitt: "BA 2 (Hinterhaus)",
zufahrt: "Hofeinfahrt Ottostraße 7, Durchfahrtshöhe 3,20 m",
koordinaten: "47.9990, 7.8421",
notizen: "Zufahrt für LKW nur über die Ottostraße. Baustrom liegt im Kellerraum links, Schlüssel hängt im Hausmeisterbüro.\nAnlieferung nur zwischen 7 und 16 Uhr.",
},
rechnung: {
strasse: "Postfach 10 24 45",
hausnummer: "",
plz: "79024",
ort: "Freiburg",
empfaenger: "Thomas Schneider, z. Hd. Buchhaltung",
zahlungsziel: "30 Tage netto",
rechnungsEmail: "rechnungen@schneider-efh.de",
notizen: "Rechnungen bitte immer mit Projektnummer im Betreff. Papierrechnungen werden nicht bearbeitet.",
},
bauherr: {
strasse: "Merzhauser Straße",
hausnummer: "77",
plz: "79100",
ort: "Freiburg",
postErwuenscht: true,
telefon: "+49 761 7788990",
ansprechpartnerVorOrt: "Frau Schneider",
notizen: "Privatadresse der Eigentümer. Bauprotokolle wöchentlich per Post.",
},
},
},
{ key: "bad-sanierung-wagner", nummer: "P-00002", name: "Bad-Sanierung 3.OG Wagner", pipeline: "sales", stage: "qualifiziert", prioritaet: "normal", contactKey: "sabine-wagner", potenziellerAuftragswert: "12400.00", quelle: "Website", startOffsetDays: 20, deadlineOffsetDays: 34, projektleiterKey: "buero", monteurKeys: ["monteur"] },
{ key: "waermepumpe-mueller", nummer: "P-00003", name: "Wärmepumpe Neubau Müller", pipeline: "sales", stage: "neu", prioritaet: "normal", contactKey: "hausverwaltung-mueller", potenziellerAuftragswert: "27800.00", quelle: "Bestandskunde", promotion: "Sommeraktion 2026", startOffsetDays: 30, deadlineOffsetDays: 75, zustaendigeKeys: ["vertrieb"] },
{ key: "sanitaer-rheintal", nummer: "P-00004", name: "Sanitärinstallation Wohnanlage Rheintal", pipeline: "sales", stage: "gewonnen", prioritaet: "hoch", contactKey: "wohnbau-rheintal", potenziellerAuftragswert: "64000.00", auftragsvolumen: "64000.00", won: true },
{ key: "notdienst-hoffmann", nummer: "P-00005", name: "Notdienst Wasserschaden Hoffmann", pipeline: "sales", stage: "verloren", prioritaet: "dringend", contactKey: "andrea-hoffmann", potenziellerAuftragswert: "3200.00", lost: true },
{ key: "wartung-baeckerei", nummer: "P-00006", name: "Wartungsvertrag Bäckerei Sonnenschein", pipeline: "auftrag", stage: "ausfuehrung", prioritaet: "normal", contactKey: "baeckerei-sonnenschein", auftragsvolumen: "1450.00" },
{ key: "rohrbruch-davinci", nummer: "P-00007", name: "Rohrbruch-Notdienst Restaurant Da Vinci", pipeline: "auftrag", stage: "abgeschlossen", prioritaet: "dringend", contactKey: "restaurant-davinci", auftragsvolumen: "890.00", won: true },
{ key: "heizungswartung-berg", nummer: "P-00008", name: "Heizungswartung Autohaus Berg", pipeline: "auftrag", stage: "geplant", prioritaet: "normal", contactKey: "autohaus-berg", auftragsvolumen: "620.00" },
// Extra "Neu" column volume so the board demonstrates the S01b two-column
// wrap (KanbanColumn twoColumn/wrapAfter kicks in above 6 cards per column).
{ key: "pv-anlage-koch", nummer: "P-00009", name: "PV-Anlage Doppelhaus Koch", pipeline: "sales", stage: "neu", prioritaet: "normal", contactKey: "stefan-koch", potenziellerAuftragswert: "21400.00" },
{ key: "fussbodenheizung-braun", nummer: "P-00010", name: "Fußbodenheizung Altbau Braun", pipeline: "sales", stage: "neu", prioritaet: "niedrig", contactKey: "julia-braun", potenziellerAuftragswert: "9800.00" },
{ key: "waermepumpe-weber", nummer: "P-00011", name: "Wärmepumpe Bestandsbau Weber", pipeline: "sales", stage: "neu", prioritaet: "hoch", contactKey: "markus-weber", potenziellerAuftragswert: "31200.00" },
{ key: "badumbau-schulz", nummer: "P-00012", name: "Barrierefreier Badumbau Schulz", pipeline: "sales", stage: "neu", prioritaet: "normal", contactKey: "petra-schulz", potenziellerAuftragswert: "14600.00" },
{ key: "heizlast-becker", nummer: "P-00013", name: "Heizlastberechnung MFH Becker", pipeline: "sales", stage: "neu", prioritaet: "niedrig", contactKey: "michael-becker", potenziellerAuftragswert: "2400.00" },
{ key: "fernwaerme-stadtwerke", nummer: "P-00014", name: "Fernwärme-Übergabestation Stadtwerke", pipeline: "sales", stage: "neu", prioritaet: "hoch", contactKey: "stadtwerke-musterstadt", potenziellerAuftragswert: "48200.00" },
];
type DemoLeadSourceSeed = { key: string; type: "system" | "custom"; name: string; displayLabel: string };
const HIVEGRID_DEMO_LEAD_SOURCES: DemoLeadSourceSeed[] = [
{ key: "website-form", type: "custom", name: "Website Kontaktformular", displayLabel: "Website Kontaktformular" },
{ key: "email-inbound", type: "system", name: "E-Mail Eingang", displayLabel: "E-Mail" },
{ key: "manual-entry", type: "system", name: "Manuelle Erfassung", displayLabel: "Manuell" },
];
type DemoLeadSeed = {
key: string;
quelle: "form" | "email" | "aircall" | "manual" | "custom";
sourceKey?: string;
status: "new" | "qualified" | "converted" | "lost" | "spam";
vorname: string;
nachname: string;
email: string;
telefon: string;
message: string;
spamScore?: number;
isQuarantined?: boolean;
};
const HIVEGRID_DEMO_LEADS: DemoLeadSeed[] = [
{ key: "klein-waermepumpe", quelle: "form", sourceKey: "website-form", status: "new", vorname: "Familie", nachname: "Klein", email: "familie.klein@example.de", telefon: "+49 761 3020100", message: "Wir interessieren uns für eine Wärmepumpe für unser Einfamilienhaus. Bitte um Rückruf." },
{ key: "buerogebaeude-heizung", quelle: "email", sourceKey: "email-inbound", status: "qualified", vorname: "Robert", nachname: "Fischer", email: "r.fischer@buero-fischer.de", telefon: "+49 7531 606070", message: "Heizungsanlage im Bürogebäude muss erneuert werden, ca. 400qm." },
{ key: "anruf-heizung-defekt", quelle: "manual", sourceKey: "manual-entry", status: "new", vorname: "Karin", nachname: "Lehmann", email: "karin.lehmann@example.de", telefon: "+49 781 112233", message: "Heizung fällt immer wieder aus, bittet um Termin diese Woche." },
{ key: "aircall-notdienst", quelle: "aircall", status: "converted", vorname: "Jens", nachname: "Krüger", email: "jens.krueger@example.de", telefon: "+49 7721 445566", message: "Notdienstanfrage über Telefon, Wasserrohrbruch im Keller." },
{ key: "custom-integration", quelle: "custom", status: "lost", vorname: "Sandra", nachname: "Vogel", email: "sandra.vogel@example.de", telefon: "+49 761 908070", message: "Anfrage über Partnerportal, hat sich anderweitig entschieden." },
{ key: "spam-form", quelle: "form", sourceKey: "website-form", status: "spam", vorname: "Best", nachname: "Deals", email: "promo@spam-offers.example", telefon: "+49 000 0000000", message: "Cheap loans and SEO services, click here now!", spamScore: 92, isQuarantined: true },
];
type DemoTaskSeed = {
key: string;
title: string;
description?: string;
status: "open" | "in_progress" | "blocked" | "done" | "cancelled";
priority: "low" | "normal" | "high" | "urgent";
assigneeKey: string;
linkedEntityType?: "contact" | "company" | "lead" | "deal" | "project" | "user" | "order" | "appointment";
linkedProjectKey?: string;
linkedContactKey?: string;
completed?: boolean;
};
const HIVEGRID_DEMO_TASKS: DemoTaskSeed[] = [
{ key: "angebot-schneider", title: "Angebot Heizungstausch Schneider erstellen", description: "Wärmeerzeuger + Speicher kalkulieren, Fördermittel prüfen.", status: "in_progress", priority: "high", assigneeKey: "vertrieb", linkedEntityType: "project", linkedProjectKey: "heizungstausch-schneider" },
{ key: "material-bad-wagner", title: "Material bestellen Bad-Sanierung Wagner", description: "Fliesen, Armaturen und Sanitärobjekte beim Großhandel ordern.", status: "open", priority: "normal", assigneeKey: "monteur", linkedEntityType: "project", linkedProjectKey: "bad-sanierung-wagner" },
{ key: "wartungstermin-baeckerei", title: "Wartungstermin Bäckerei bestätigen", description: "Termin für Jahreswartung mit dem Büro abstimmen.", status: "open", priority: "normal", assigneeKey: "monteur", linkedEntityType: "project", linkedProjectKey: "wartung-baeckerei" },
{ key: "rechnung-davinci", title: "Rechnung Da Vinci prüfen und versenden", description: "Notdienst-Rechnung final prüfen und an den Kunden senden.", status: "done", priority: "normal", assigneeKey: "buero", linkedEntityType: "project", linkedProjectKey: "rohrbruch-davinci", completed: true },
{ key: "nachfassen-berg", title: "Kontakt Autohaus Berg nachfassen", description: "Wegen Wartungsvertrag Werkstattheizung telefonisch nachhaken.", status: "open", priority: "low", assigneeKey: "vertrieb", linkedEntityType: "company", linkedContactKey: "autohaus-berg" },
{ key: "rueckruf-klein", title: "Rückruf Familie Klein (Wärmepumpe)", description: "Erstberatung telefonisch, Vor-Ort-Termin anbieten.", status: "open", priority: "high", assigneeKey: "vertrieb", linkedEntityType: "contact", linkedContactKey: "thomas-schneider" },
];
type DemoFormFieldSeed = {
key: string;
type: "text" | "email" | "phone" | "textarea" | "select" | "boolean" | "photo" | "honeypot";
label: string;
required?: boolean;
helpText?: string;
placeholder?: string;
options?: { value: string; label: string }[];
};
type DemoFormSeed = {
key: string;
slug: string;
name: string;
subtype: "standard" | "acceptance_form" | "lead" | "survey" | "internal";
/** Defaults to "published"; drafts stay private and show the editor flow. */
status?: "draft" | "published";
targetType: string;
/** create_lead mapping formFieldKey -> vorname|nachname|email|telefon|message. */
actionFieldMapping?: Record<string, string>;
fields: DemoFormFieldSeed[];
submissions: {
key: string;
status: string;
values: Record<string, string | boolean>;
sourceOrigin: string;
linkedEntityType?: string;
linkedLeadKey?: string;
/** Surfaces a failed action in the S05 submission drawer. */
actionErrorMessage?: string;
}[];
};
// Matches the create_lead worker contract (WF-P16 S02L): only
// vorname/nachname/email/telefon/message are valid mapping targets.
const DEMO_LEAD_FIELD_MAPPING: Record<string, string> = {
full_name: "nachname",
email: "email",
phone: "telefon",
message: "message",
};
const HIVEGRID_DEMO_FORMS: DemoFormSeed[] = [
{
key: "angebotsanfrage",
slug: "shk-angebotsanfrage",
name: "SHK Angebotsanfrage",
subtype: "standard",
targetType: "create-lead",
fields: [
{ key: "full_name", type: "text", label: "Name", required: true, placeholder: "Max Mustermann" },
{ key: "email", type: "email", label: "E-Mail", required: true },
{ key: "phone", type: "phone", label: "Telefon", required: false },
{
key: "service_type",
type: "select",
label: "Leistungsbereich",
required: true,
options: [
{ value: "heizung", label: "Heizung" },
{ value: "sanitaer", label: "Sanitär" },
{ value: "bad", label: "Bad" },
],
},
{ key: "message", type: "textarea", label: "Projektbeschreibung", required: true },
{ key: "hp_extra_data", type: "honeypot", label: "Bitte leer lassen" },
],
submissions: [
{
key: "klein",
status: "routed-to-crm",
sourceOrigin: "https://www.hivegrid-demo.local",
linkedEntityType: "lead",
linkedLeadKey: "klein-waermepumpe",
values: {
full_name: "Familie Klein",
email: "familie.klein@example.de",
phone: "+49 761 3020100",
service_type: "heizung",
message: "Wir interessieren uns für eine Wärmepumpe für unser Einfamilienhaus.",
},
},
{
key: "fischer",
status: "processed",
sourceOrigin: "https://www.hivegrid-demo.local",
values: {
full_name: "Robert Fischer",
email: "r.fischer@buero-fischer.de",
phone: "+49 7531 606070",
service_type: "heizung",
message: "Heizungsanlage im Bürogebäude muss erneuert werden, ca. 400qm.",
},
},
],
},
{
key: "abnahme",
slug: "shk-abnahmeprotokoll",
name: "SHK Abnahmeprotokoll",
subtype: "acceptance_form",
targetType: "generic",
fields: [
{ key: "project_number", type: "text", label: "Projektnummer", required: true },
{ key: "customer_name", type: "text", label: "Kunde", required: true },
{ key: "accepted", type: "boolean", label: "Abnahme erteilt", required: true },
{ key: "defects", type: "textarea", label: "Mängel / Hinweise" },
{ key: "photo", type: "photo", label: "Foto-Dokumentation" },
{ key: "hp_extra_data", type: "honeypot", label: "Bitte leer lassen" },
],
submissions: [
{
key: "davinci",
status: "processed",
sourceOrigin: "https://www.hivegrid-demo.local",
values: {
project_number: "P-00007",
customer_name: "Restaurant Da Vinci",
accepted: true,
defects: "Keine offenen Punkte, Kunde hat digital bestätigt.",
photo: "demo-abnahme-davinci.jpg",
},
},
],
},
{
key: "waermepumpen-anfrage",
slug: "waermepumpen-anfrage",
name: "Wärmepumpen-Anfrage Website",
subtype: "lead",
targetType: "create-lead",
actionFieldMapping: { vorname: "vorname", nachname: "nachname", email: "email", phone: "telefon", message: "message" },
fields: [
{ key: "vorname", type: "text", label: "Vorname", required: false, placeholder: "Max" },
{ key: "nachname", type: "text", label: "Nachname", required: true, placeholder: "Mustermann" },
{ key: "email", type: "email", label: "E-Mail", required: true },
{ key: "phone", type: "phone", label: "Telefon", required: false },
{
key: "gebaeude",
type: "select",
label: "Gebäudetyp",
required: true,
options: [
{ value: "einfamilienhaus", label: "Einfamilienhaus" },
{ value: "mehrfamilienhaus", label: "Mehrfamilienhaus" },
{ value: "gewerbe", label: "Gewerbe" },
],
},
{ key: "message", type: "textarea", label: "Ihr Anliegen", required: true },
{ key: "hp_extra_data", type: "honeypot", label: "Bitte leer lassen" },
],
submissions: [
{
key: "sommer",
status: "processed",
sourceOrigin: "https://www.hivegrid-demo.local",
values: {
vorname: "Otto",
nachname: "Sommer",
email: "otto.sommer@example.de",
phone: "+49 761 5566770",
gebaeude: "einfamilienhaus",
message: "Altbau von 1985, Ölheizung soll durch Wärmepumpe ersetzt werden.",
},
},
{
key: "brandt",
status: "route-failed",
sourceOrigin: "https://www.hivegrid-demo.local",
actionErrorMessage: "Lead konnte nicht angelegt werden: Lead-Inbox hat die Anfrage abgelehnt (Demo-Fehlerfall).",
values: {
vorname: "Heike",
nachname: "Brandt",
email: "heike.brandt@example.de",
phone: "+49 7531 889900",
gebaeude: "mehrfamilienhaus",
message: "Anfrage für 6-Parteien-Haus, bitte um Beratung zu Förderung.",
},
},
{
key: "spam-promo",
status: "spam",
sourceOrigin: "https://spam-offers.example",
values: {
vorname: "Best",
nachname: "Deals",
email: "promo@spam-offers.example",
phone: "+49 000 0000000",
gebaeude: "gewerbe",
message: "Cheap heat pumps wholesale, click here now!",
},
},
],
},
{
key: "kundenzufriedenheit",
slug: "kundenzufriedenheit-2026",
name: "Kundenzufriedenheit 2026",
subtype: "survey",
targetType: "generic",
fields: [
{
key: "bewertung",
type: "select",
label: "Wie zufrieden waren Sie mit unserer Arbeit?",
required: true,
options: [
{ value: "5", label: "Sehr zufrieden" },
{ value: "4", label: "Zufrieden" },
{ value: "3", label: "Neutral" },
{ value: "2", label: "Unzufrieden" },
{ value: "1", label: "Sehr unzufrieden" },
],
},
{ key: "weiterempfehlung", type: "boolean", label: "Würden Sie uns weiterempfehlen?", required: true },
{ key: "feedback", type: "textarea", label: "Was können wir besser machen?" },
{ key: "hp_extra_data", type: "honeypot", label: "Bitte leer lassen" },
],
submissions: [
{
key: "schneider",
status: "processed",
sourceOrigin: "https://www.hivegrid-demo.local",
values: {
bewertung: "5",
weiterempfehlung: true,
feedback: "Monteure waren pünktlich und haben sauber gearbeitet, gerne wieder.",
},
},
{
key: "wagner",
status: "processed",
sourceOrigin: "https://www.hivegrid-demo.local",
values: {
bewertung: "4",
weiterempfehlung: true,
feedback: "Alles gut, nur die Terminfindung hat etwas gedauert.",
},
},
{
key: "anonym",
status: "received",
sourceOrigin: "https://www.hivegrid-demo.local",
values: {
bewertung: "3",
weiterempfehlung: false,
feedback: "Rückfragen wurden erst nach mehrmaligem Nachhaken beantwortet.",
},
},
],
},
{
key: "stoerungsmeldung",
slug: "interne-stoerungsmeldung",
name: "Interne Störungsmeldung",
subtype: "internal",
status: "draft",
targetType: "generic",
fields: [
{ key: "anlage", type: "text", label: "Anlage / Standort", required: true },
{
key: "prioritaet",
type: "select",
label: "Priorität",
required: true,
options: [
{ value: "hoch", label: "Hoch" },
{ value: "normal", label: "Normal" },
{ value: "niedrig", label: "Niedrig" },
],
},
{ key: "beschreibung", type: "textarea", label: "Störungsbeschreibung", required: true },
],
submissions: [],
},
];
type DemoAutomationStepSeed = {
key: string;
kind: "trigger" | "condition" | "action" | "flow_control";
nodeType: string;
parentStepIds: string[];
summaryText: string;
/** Realistic key/value snapshots for the S03 run-detail EINGABE/AUSGABE blocks. */
input?: Record<string, string>;
output?: Record<string, string>;
};
type DemoAutomationSeed = {
key: string;
name: string;
description: string;
status: "draft" | "active" | "paused";
enabled: boolean;
triggerKey: string;
steps: DemoAutomationStepSeed[];
executions: {
key: string;
status: "success" | "failed" | "running" | "skipped" | "paused";
dryRun: boolean;
summaryText: string;
errorText?: string;
}[];
/** Seeds an active AutomationTriggerMeter anomaly (WF-P12 S01 banner + M02 dialog). */
anomaly?: { anomalyText: string };
};
const HIVEGRID_DEMO_AUTOMATIONS: DemoAutomationSeed[] = [
{
key: "form-lead-follow-up",
name: "Formular-Leads nachfassen",
description: "Erstellt aus einer Angebotsanfrage eine Rückruf-Aufgabe und informiert das Büro.",
status: "active",
enabled: true,
triggerKey: "forms.submitted",
steps: [
{
key: "trigger",
kind: "trigger",
nodeType: "forms.submitted",
parentStepIds: [],
summaryText: "Formular-Eingang erkannt",
input: { Quelle: "Website-Formular", Formular: "SHK Angebotsanfrage" },
output: { Name: "Familie Klein", "E-Mail": "familie.klein@example.de", Anliegen: "Wärmepumpe Einfamilienhaus" },
},
{
key: "create-task",
kind: "action",
nodeType: "task.create",
parentStepIds: ["trigger"],
summaryText: "Rückruf-Aufgabe für Vertrieb erstellt",
input: { Lead: "Familie Klein", Bereich: "Heizung" },
output: { Aufgabe: "Rückruf Familie Klein (Wärmepumpe)", Zuweisung: "Vera Vertrieb", Fälligkeit: "in 2 Tagen" },
},
{
key: "notify-office",
kind: "action",
nodeType: "notification.send",
parentStepIds: ["create-task"],
summaryText: "Büro per In-App-Hinweis informiert",
input: { Empfänger: "Birgit Büro", Kanal: "In-App" },
output: { Status: "Zugestellt" },
},
],
executions: [
{ key: "klein-success", status: "success", dryRun: false, summaryText: "Lead Familie Klein verarbeitet" },
{ key: "dry-run", status: "success", dryRun: true, summaryText: "Trockenlauf mit Muster-Anfrage erfolgreich" },
{ key: "spam-skip", status: "skipped", dryRun: false, summaryText: "Als Spam markierte Anfrage übersprungen" },
],
},
{
key: "booking-reminder",
name: "Termin-Erinnerung vorbereiten",
description: "Markiert neue Beratungstermine für die Vorbereitung im Monteur-Team.",
status: "active",
enabled: true,
triggerKey: "booking.appointment_booked",
steps: [
{
key: "trigger",
kind: "trigger",
nodeType: "booking.appointment_booked",
parentStepIds: [],
summaryText: "Neuer Booking-Termin erkannt",
input: { Buchungsseite: "Beratung vor Ort" },
output: { Kunde: "Sabine Wagner", Termin: "Beratung Bad-Sanierung" },
},
{
key: "create-task",
kind: "action",
nodeType: "task.create",
parentStepIds: ["trigger"],
summaryText: "Vorbereitungs-Aufgabe erstellt",
input: { Termin: "Beratung Bad-Sanierung", Team: "Monteure" },
output: { Aufgabe: "Material und Unterlagen vorbereiten", Zuweisung: "Murat Monteur" },
},
],
executions: [
{ key: "wagner-success", status: "success", dryRun: false, summaryText: "Bad-Sanierung Wagner für Monteur vorbereitet" },
{ key: "failed-calendar", status: "failed", dryRun: false, summaryText: "Kalender-Rückmeldung konnte nicht zugestellt werden", errorText: "Demo: Provider-Verbindung pausiert" },
],
},
{
key: "kundendaten-sync",
name: "Kundendaten aktualisieren",
description: "Gleicht geänderte Kontaktdaten automatisch mit verknüpften Datensätzen ab.",
status: "paused",
enabled: false,
triggerKey: "crm.kontakt_updated",
anomaly: { anomalyText: "2.000 Läufe in 5 Minuten, typisch sind 5 bis 10 pro Tag. Automatisch pausiert." },
steps: [
{
key: "trigger",
kind: "trigger",
nodeType: "crm.kontakt_updated",
parentStepIds: [],
summaryText: "Kontakt-Änderung erkannt",
input: { Kontakt: "Hausverwaltung Müller & Partner GmbH" },
output: { "Geändertes Feld": "Telefonnummer" },
},
{
key: "update-record",
kind: "action",
nodeType: "crm.update_kontakt",
parentStepIds: ["trigger"],
summaryText: "Verknüpfte Datensätze aktualisiert",
input: { Kontakt: "Hausverwaltung Müller & Partner GmbH" },
output: { "Aktualisierte Datensätze": "3" },
},
],
executions: [
{ key: "sync-success", status: "success", dryRun: false, summaryText: "Kontaktdaten Hausverwaltung Müller synchronisiert" },
{ key: "guard-paused", status: "paused", dryRun: false, summaryText: "Automatisch pausiert: ungewöhnlich hohe Auslöse-Rate erkannt", errorText: "2.000 Läufe in 5 Minuten, typisch sind 5 bis 10 pro Tag." },
],
},
];
type DemoBookingPageSeed = {
key: string;
slug: string;
title: string;
description: string;
durationMinutes: number;
/** Demo form key linked as intake form (AK-P16b/AK-P16c editor selection). */
intakeFormKey?: string;
providerKeys: string[];
appointments: {
key: string;
providerKey: string;
contactKey: string;
dayOffset: number;
startHour: number;
startMinute: number;
status: "scheduled" | "held" | "cancelled";
intakeAnswers: Record<string, string>;
notesInternal?: string;
}[];
};
const HIVEGRID_DEMO_BOOKING_PAGES: DemoBookingPageSeed[] = [
{
key: "beratung",
slug: "beratung-vor-ort",
title: "Beratung vor Ort",
description: "Kostenlose Erstberatung für Heizung, Bad und Sanitär.",
durationMinutes: 45,
intakeFormKey: "angebotsanfrage",
providerKeys: ["vertrieb", "monteur"],
appointments: [
{
key: "wagner-bad",
providerKey: "vertrieb",
contactKey: "sabine-wagner",
dayOffset: 2,
startHour: 10,
startMinute: 0,
status: "scheduled",
intakeAnswers: {
vorname: "Sabine",
nachname: "Wagner",
email: "sabine.wagner@example.de",
telefon: "+49 7531 998877",
anliegen: "Bad-Sanierung im 3. OG besprechen.",
},
},
{
key: "schneider-heizung",
providerKey: "monteur",
contactKey: "thomas-schneider",
dayOffset: -2,
startHour: 14,
startMinute: 30,
status: "held",
intakeAnswers: {
vorname: "Thomas",
nachname: "Schneider",
email: "thomas.schneider@example.de",
telefon: "+49 761 1234501",
anliegen: "Heizungstausch und Fördermöglichkeiten.",
},
notesInternal: "Bestandsanlage fotografiert, Angebot folgt.",
},
],
},
{
key: "wartung",
slug: "wartungstermin",
title: "Wartungstermin buchen",
description: "Jährliche Wartung für bestehende Kunden.",
durationMinutes: 60,
providerKeys: ["monteur"],
appointments: [
{
key: "baeckerei-wartung",
providerKey: "monteur",
contactKey: "baeckerei-sonnenschein",
dayOffset: 5,
startHour: 8,
startMinute: 30,
status: "scheduled",
intakeAnswers: {
vorname: "Birgit",
nachname: "Sonnenschein",
email: "buero@baeckerei-sonnenschein.de",
telefon: "+49 761 4488220",
anliegen: "Jahreswartung vor Produktionsbeginn.",
},
},
],
},
];
export function assertCanRunDemoSeed(env: EnvRecord = process.env): void {
if (env.NODE_ENV === "production") {
throw new Error("Refusing to run the HiveGrid demo seed in production. This seed is for local exploration only.");
}
if (env.HIVEGRID_DEMO_SEED !== "1") {
throw new Error("Set HIVEGRID_DEMO_SEED=1 to seed the local HiveGrid demo tenant (the `pnpm seed:demo` script sets it for you).");
}
if (!env.DATABASE_URL?.trim()) {
throw new Error("DATABASE_URL is required for the HiveGrid demo seed.");
}
}
async function upsertUser(db: DbClient, input: { email: string; firstName: string; lastName: string; passwordHash: string }) {
return db.user.upsert({
where: { email: input.email },
create: {
email: input.email,
passwordHash: input.passwordHash,
firstName: input.firstName,
lastName: input.lastName,
active: true,
locale: "de",
},
update: {
passwordHash: input.passwordHash,
firstName: input.firstName,
lastName: input.lastName,
active: true,
},
});
}
async function ensureMembership(db: DbClient, tenantId: string, userId: string, type: number) {
await db.user.update({ where: { id: userId }, data: { defaultTenantId: tenantId } });
await db.tenantUser.upsert({
where: { tenantId_userId: { tenantId, userId } },
create: { tenantId, userId, type, joined: TENANT_USER_JOINED_CREATOR, status: TENANT_USER_STATUS_ACTIVE },
update: { type, status: TENANT_USER_STATUS_ACTIVE },
});
}
async function ensureAppRole(db: DbClient, userId: string, tenantId: string, roleName: string) {
// UserRole has no composite @@unique (tenantId is nullable), so guard via
// findFirst before create to stay idempotent.
const role = await db.role.findFirst({ where: { tenantId: null, name: roleName, type: "app" }, select: { id: true } });
if (!role) {
throw new Error(`Default app role "${roleName}" not found — syncDefaultRolesAndPermissions must run first.`);
}
const existing = await db.userRole.findFirst({ where: { userId, tenantId, roleId: role.id }, select: { id: true } });
if (!existing) {
await db.userRole.create({ data: { userId, tenantId, roleId: role.id } });
}
}
async function ensureTenantAppRole(db: DbClient, userId: string, tenantId: string, roleName: string) {
// Same idempotent guard as ensureAppRole but for a TENANT-OWNED role (the SHK
// template roles seeded by seedShkTemplateRolesForTenant).
const role = await db.role.findFirst({ where: { tenantId, name: roleName, type: "app" }, select: { id: true } });
if (!role) {
throw new Error(`SHK template role "${roleName}" not found for tenant — seedShkTemplateRolesForTenant must run first.`);
}
const existing = await db.userRole.findFirst({ where: { userId, tenantId, roleId: role.id }, select: { id: true } });
if (!existing) {
await db.userRole.create({ data: { userId, tenantId, roleId: role.id } });
}
}
async function seedTenantAndUsers(db: DbClient) {
const tenant = await db.tenant.upsert({
where: { slug: HIVEGRID_DEMO_TENANT_SLUG },
create: { slug: HIVEGRID_DEMO_TENANT_SLUG, name: HIVEGRID_DEMO_TENANT_NAME, active: true },
update: { name: HIVEGRID_DEMO_TENANT_NAME, active: true, deactivatedReason: null },
});
// Roles/permissions must exist before role assignment (idempotent).
await syncDefaultRolesAndPermissions({ client: db });
// Fundament B: seed the 7 SHK standard roles as tenant-owned template roles
// (idempotent). Depends on the permissions synced above so grant keys resolve.
await seedShkTemplateRolesForTenant(db, tenant.id);
const passwordHash = await bcrypt.hash(HIVEGRID_DEMO_PASSWORD, 10);
const userIdByKey = new Map<string, string>();
for (const seed of HIVEGRID_DEMO_USERS) {
const user = await upsertUser(db, { email: seed.email, firstName: seed.firstName, lastName: seed.lastName, passwordHash });
userIdByKey.set(seed.key, user.id);
await ensureMembership(db, tenant.id, user.id, seed.tenantUserType);
for (const roleName of seed.appRoleNames) {
await ensureAppRole(db, user.id, tenant.id, roleName);
}
if (seed.shkRoleName) {
await ensureTenantAppRole(db, user.id, tenant.id, seed.shkRoleName);
}
}
return { tenant, userIdByKey };
}
async function seedFeaturesAndSubscription(db: DbClient, tenantId: string) {
await db.tenantProductConfiguration.upsert({
where: { tenantId },
create: { tenantId, blueprintId: productBlueprintIds.crmSaas, notes: "HiveGrid SHK demo tenant — CRM SaaS blueprint with all v1 modules enabled." },
update: { blueprintId: productBlueprintIds.crmSaas, notes: "HiveGrid SHK demo tenant — CRM SaaS blueprint with all v1 modules enabled." },
});
for (const featureKey of HIVEGRID_DEMO_ENABLED_FEATURE_KEYS) {
await db.tenantFeatureOverride.upsert({
where: { tenantId_featureKey: { tenantId, featureKey } },
create: { tenantId, featureKey, override: "enabled", reason: "Demo tenant: keep the module explorable regardless of plan." },
update: { override: "enabled", reason: "Demo tenant: keep the module explorable regardless of plan." },
});
}
// Self-contained business subscription (mirrors the E2E readiness seed): a
// dedicated product/price + TenantSubscription + one TenantSubscriptionProduct
// → hasSubscription = true, business entitlement plan resolves feature gates.
const now = new Date();
const periodEnd = new Date(now);
periodEnd.setUTCMonth(periodEnd.getUTCMonth() + 1);
const product =
(await db.subscriptionProduct.findFirst({ where: { billingProviderId: HIVEGRID_DEMO_SUBSCRIPTION_PRODUCT_BILLING_ID } })) ??
(await db.subscriptionProduct.create({
data: {
billingProviderId: HIVEGRID_DEMO_SUBSCRIPTION_PRODUCT_BILLING_ID,
order: 1,
title: "HiveGrid Demo Business",
active: true,
model: 0,
public: true,
description: "Local HiveGrid demo business subscription.",
billingAddressCollection: "auto",
hasQuantity: false,
canBuyAgain: false,
},
}));
const price =
(await db.subscriptionPrice.findFirst({ where: { subscriptionProductId: product.id, billingProviderId: HIVEGRID_DEMO_SUBSCRIPTION_PRICE_BILLING_ID } })) ??
(await db.subscriptionPrice.create({
data: {
subscriptionProductId: product.id,
billingProviderId: HIVEGRID_DEMO_SUBSCRIPTION_PRICE_BILLING_ID,
type: 0,
billingPeriod: 3,
price: "49",
currency: "eur",
trialDays: 0,
active: true,
},
}));
const tenantSubscription = await db.tenantSubscription.upsert({
where: { tenantId },
create: { tenantId, status: "active" },
update: { status: "active" },
});
const tenantProduct =
(await db.tenantSubscriptionProduct.findFirst({ where: { tenantSubscriptionId: tenantSubscription.id, subscriptionProductId: product.id } })) ??
(await db.tenantSubscriptionProduct.create({
data: {
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: product.id,
customEntitlementPlanId: entitlementPlanIds.business,
fromCheckoutSessionId: "hivegrid-demo",
quantity: 1,
currentPeriodStart: now,
currentPeriodEnd: periodEnd,
},
}));
await db.tenantSubscriptionProduct.update({
where: { id: tenantProduct.id },
data: { customEntitlementPlanId: entitlementPlanIds.business, cancelledAt: null, endsAt: null, quantity: 1, currentPeriodStart: now, currentPeriodEnd: periodEnd },
});
const tenantPrice = await db.tenantSubscriptionProductPrice.findFirst({ where: { tenantSubscriptionProductId: tenantProduct.id, subscriptionPriceId: price.id }, select: { id: true } });
if (!tenantPrice) {
await db.tenantSubscriptionProductPrice.create({ data: { tenantSubscriptionProductId: tenantProduct.id, subscriptionPriceId: price.id } });
}
}
async function seedContacts(db: DbClient, tenantId: string, ownerUserId: string) {
const kontaktIdByKey = new Map<string, string>();
for (const contact of ALL_DEMO_CONTACTS) {
const adresseId = `demo-adr-${contact.key}`;
await db.adresse.upsert({
where: { id: adresseId },
create: { id: adresseId, tenantId, strasse: contact.adresse.strasse, hausnummer: contact.adresse.hausnummer, plz: contact.adresse.plz, ort: contact.adresse.ort, land: "DE" },
update: { strasse: contact.adresse.strasse, hausnummer: contact.adresse.hausnummer, plz: contact.adresse.plz, ort: contact.adresse.ort },
});
const kontaktId = `demo-kontakt-${contact.key}`;
const base = {
tenantId,
createdByUserId: ownerUserId,
zustaendigerUserId: ownerUserId,
kontaktTyp: contact.typ,
kontaktStatus: contact.status,
vorname: contact.typ === "privatperson" ? contact.vorname ?? null : null,
nachname: contact.typ === "privatperson" ? contact.nachname ?? null : null,
orgName: contact.typ === "organisation" ? contact.orgName ?? null : null,
orgMerkmal: contact.typ === "organisation" ? contact.orgMerkmal ?? null : null,
primaerEmail: contact.email,
primaerTelefon: contact.telefon,
adresseId,
// Master data stays null where the type cannot show it: a private person
// has no Handelsregister, an organisation no Position.
website: contact.stammdaten?.website ?? null,
ustIdNr: contact.stammdaten?.ustIdNr ?? null,
handelsregister: contact.stammdaten?.handelsregister ?? null,
kundennummer: contact.stammdaten?.kundennummer ?? null,
kundeSeit: contact.stammdaten?.kundeSeitIso ? new Date(`${contact.stammdaten.kundeSeitIso}T00:00:00.000Z`) : null,
branche: contact.stammdaten?.branche ?? null,
mitarbeiterzahl: contact.stammdaten?.mitarbeiterzahl ?? null,
position: contact.stammdaten?.position ?? null,
erreichbarkeit: contact.stammdaten?.erreichbarkeit ?? null,
notizen: contact.stammdaten?.notizen ?? null,
isDemoData: true,
};
await db.kontakt.upsert({ where: { id: kontaktId }, create: { id: kontaktId, ...base }, update: base });
const emailId = `demo-kmail-${contact.key}`;
await db.kontaktEmail.upsert({
where: { id: emailId },
create: { id: emailId, tenantId, kontaktId, email: contact.email, primaer: true },
update: { email: contact.email, primaer: true },
});
const telefonId = `demo-ktel-${contact.key}`;
await db.kontaktTelefon.upsert({
where: { id: telefonId },
create: { id: telefonId, tenantId, kontaktId, telefon: contact.telefon, typ: "haupt", primaer: true },
update: { telefon: contact.telefon, typ: "haupt", primaer: true },
});
for (const weitere of contact.weitereTelefone ?? []) {
const weitereId = `demo-ktel-${contact.key}-${weitere.key}`;
await db.kontaktTelefon.upsert({
where: { id: weitereId },
create: { id: weitereId, tenantId, kontaktId, telefon: weitere.telefon, typ: weitere.typ, primaer: false },
update: { telefon: weitere.telefon, typ: weitere.typ, primaer: false },
});
}
kontaktIdByKey.set(contact.key, kontaktId);
}
return kontaktIdByKey;
}
// Locked demo board (WF-P8 S00): visible on the boards start page but denied
// for every demo user via user-level PipelineAccess rules, so the greyed-out
// "Nutzung anfragen" state is demonstrable on staging.
const HIVEGRID_DEMO_LOCKED_PIPELINE: DemoPipelineSeed = {
key: "notfall",
name: "Notfall-Reparatur",
typHint: "auftrag",
position: 2,
isDefault: false,
stages: [
{ key: "eingang", name: "Eingang", stageKind: "offen", winProbability: 100, color: "#ef4444" },
{ key: "vor-ort", name: "Vor Ort", stageKind: "offen", winProbability: 100, color: "#f59e0b" },
{ key: "behoben", name: "Behoben", stageKind: "offen", winProbability: 100, color: "#3b82f6" },
{ key: "abgerechnet", name: "Abgerechnet", stageKind: "gewonnen", winProbability: 100, color: "#22c55e" },
],
};
async function seedPipelines(db: DbClient, tenantId: string, ownerUserId: string, userIdByKey: Map<string, string>) {
const stageIdByKey = new Map<string, string>();
const pipelineIdByKey = new Map<string, string>();
for (const pipeline of HIVEGRID_DEMO_PIPELINES) {
const pipelineId = `demo-pipe-${pipeline.key}`;
await db.pipeline.upsert({
where: { id: pipelineId },
create: { id: pipelineId, tenantId, createdByUserId: ownerUserId, name: pipeline.name, typHint: pipeline.typHint, position: pipeline.position, isDefault: pipeline.isDefault, isDemoData: true },
update: { name: pipeline.name, typHint: pipeline.typHint, position: pipeline.position, isDefault: pipeline.isDefault, isDemoData: true },
});
pipelineIdByKey.set(pipeline.key, pipelineId);
for (let index = 0; index < pipeline.stages.length; index += 1) {
const stage = pipeline.stages[index];
const stageId = `demo-stage-${pipeline.key}-${stage.key}`;
await db.pipelineStage.upsert({
where: { id: stageId },
create: { id: stageId, tenantId, pipelineId, name: stage.name, stageKind: stage.stageKind, winProbability: stage.winProbability, color: stage.color, position: index, isDemoData: true },
update: { name: stage.name, stageKind: stage.stageKind, winProbability: stage.winProbability, color: stage.color, position: index, isDemoData: true },
});
stageIdByKey.set(`${pipeline.key}:${stage.key}`, stageId);
}
}
// Locked board: seeded like the others, then denied per demo user (deny-based
// PipelineAccess). Idempotent via fixed ids/upserts.
const locked = HIVEGRID_DEMO_LOCKED_PIPELINE;
const lockedPipelineId = `demo-pipe-${locked.key}`;
await db.pipeline.upsert({
where: { id: lockedPipelineId },
create: { id: lockedPipelineId, tenantId, createdByUserId: ownerUserId, name: locked.name, typHint: locked.typHint, position: locked.position, isDefault: false, isDemoData: true },
update: { name: locked.name, typHint: locked.typHint, position: locked.position, isDefault: false, isDemoData: true },
});
for (let index = 0; index < locked.stages.length; index += 1) {
const stage = locked.stages[index];
const stageId = `demo-stage-${locked.key}-${stage.key}`;
await db.pipelineStage.upsert({
where: { id: stageId },
create: { id: stageId, tenantId, pipelineId: lockedPipelineId, name: stage.name, stageKind: stage.stageKind, winProbability: stage.winProbability, color: stage.color, position: index, isDemoData: true },
update: { name: stage.name, stageKind: stage.stageKind, winProbability: stage.winProbability, color: stage.color, position: index, isDemoData: true },
});
}
for (const userId of new Set(userIdByKey.values())) {
await db.pipelineAccess.upsert({
where: { pipelineId_principalType_principalId: { pipelineId: lockedPipelineId, principalType: "user", principalId: userId } },
create: { tenantId, pipelineId: lockedPipelineId, principalType: "user", principalId: userId, kannSehen: false, kannBearbeiten: false },
update: { kannSehen: false, kannBearbeiten: false },
});
}
return { pipelineIdByKey, stageIdByKey };
}
/**
* Writes one project address slot and its extras. The address row is shared CRM
* data, the extras belong to this project's slot — hence two upserts, not one.
*/
async function upsertProjectAddress(
db: DbClient,
tenantId: string,
projectKey: string,
projektId: string,
slot: "projekt" | "rechnung" | "bauherr",
address: DemoAddressSeed,
) {
const adresseId = `demo-padr-${projectKey}-${slot}`;
const fields = { strasse: address.strasse, hausnummer: address.hausnummer, plz: address.plz, ort: address.ort, land: "DE" };
await db.adresse.upsert({ where: { id: adresseId }, create: { id: adresseId, tenantId, ...fields }, update: fields });
const extras = {
bauabschnitt: address.bauabschnitt ?? null,
zufahrt: address.zufahrt ?? null,
koordinaten: address.koordinaten ?? null,
empfaenger: address.empfaenger ?? null,
zahlungsziel: address.zahlungsziel ?? null,
rechnungsEmail: address.rechnungsEmail ?? null,
postErwuenscht: address.postErwuenscht ?? false,
telefon: address.telefon ?? null,
ansprechpartnerVorOrt: address.ansprechpartnerVorOrt ?? null,
notizen: address.notizen ?? null,
};
const detailId = `demo-padrdetail-${projectKey}-${slot}`;
await db.projektAdressDetail.upsert({
where: { id: detailId },
create: { id: detailId, tenantId, projektId, slot, ...extras },
update: extras,
});
return adresseId;
}
async function seedProjects(
db: DbClient,
tenantId: string,
ownerUserId: string,
userIdByKey: Map<string, string>,
pipelineIdByKey: Map<string, string>,
stageIdByKey: Map<string, string>,
kontaktIdByKey: Map<string, string>,
) {
// WF-P8 S06: the SHK reason set plus one tenant-created reason and one
// archived leftover, so the admin table has something to show for every
// state it renders (template vs. own, active vs. archived, used vs. unused).
const DEMO_LOST_REASONS = [
{ key: "preis", name: "Preis zu hoch", beschreibung: "Angebot lag über dem Budgetrahmen des Kunden.", kategorie: "Preis", istVorlage: true, archiviert: false },
{ key: "budget", name: "Kein Budget", beschreibung: "Kunde hat aktuell kein Budget für die Maßnahme.", kategorie: "Budget", istVorlage: true, archiviert: false },
{ key: "wettbewerb", name: "Wettbewerber gewonnen", beschreibung: "Auftrag ging an einen anderen Anbieter.", kategorie: "Wettbewerb", istVorlage: true, archiviert: false },
{ key: "verschoben", name: "Projekt verschoben", beschreibung: "Vorhaben wurde auf unbestimmte Zeit verschoben.", kategorie: "Zeitplan", istVorlage: true, archiviert: false },
{ key: "unerreichbar", name: "Kunde nicht erreichbar", beschreibung: "Keine Rückmeldung trotz mehrfacher Kontaktversuche.", kategorie: "Kommunikation", istVorlage: true, archiviert: false },
{ key: "dublette", name: "Dublette (Testdaten)", beschreibung: "Wurde beim Onboarding versehentlich doppelt angelegt.", kategorie: "Sonstiges", istVorlage: false, archiviert: true },
] as const;
// The "Verloren" demo project points at the first reason.
const lostReasonId = "demo-lostreason-preis";
for (const [index, reason] of DEMO_LOST_REASONS.entries()) {
const fields = {
name: reason.name,
beschreibung: reason.beschreibung,
kategorie: reason.kategorie,
istVorlage: reason.istVorlage,
position: index * 10,
isDemoData: true,
archivedAt: reason.archiviert ? new Date("2026-07-01T00:00:00.000Z") : null,
};
await db.lostReason.upsert({
where: { id: `demo-lostreason-${reason.key}` },
create: { id: `demo-lostreason-${reason.key}`, tenantId, ...fields },
update: fields,
});
}
const projektIdByKey = new Map<string, string>();
for (const project of HIVEGRID_DEMO_PROJECTS) {
const projektId = `demo-projekt-${project.key}`;
const pipelineId = pipelineIdByKey.get(project.pipeline);
const stageId = stageIdByKey.get(`${project.pipeline}:${project.stage}`);
if (!pipelineId || !stageId) {
throw new Error(`Demo project ${project.key} references an unknown pipeline/stage (${project.pipeline}:${project.stage}).`);
}
const adressen = project.adressen ?? {};
const projektAdresseId = adressen.projekt ? await upsertProjectAddress(db, tenantId, project.key, projektId, "projekt", adressen.projekt) : null;
const rechnungsAdresseId = adressen.rechnung ? await upsertProjectAddress(db, tenantId, project.key, projektId, "rechnung", adressen.rechnung) : null;
const bauherrAdresseId = adressen.bauherr ? await upsertProjectAddress(db, tenantId, project.key, projektId, "bauherr", adressen.bauherr) : null;
const data = {
tenantId,
createdByUserId: ownerUserId,
projektNummer: project.nummer,
projektname: project.name,
beschreibung: project.beschreibung ?? null,
projekttyp: project.pipeline === "auftrag" ? "Auftrag" : "Verkaufschance",
quelle: project.quelle ?? null,
promotion: project.promotion ?? null,
email: project.kontaktdaten?.email ?? null,
telefon: project.kontaktdaten?.telefon ?? null,
fax: project.kontaktdaten?.fax ?? null,
prioritaet: project.prioritaet,
pipelineId,
stageId,
potenziellerAuftragswert: project.potenziellerAuftragswert ?? null,
auftragsvolumen: project.auftragsvolumen ?? null,
startDatum: project.startOffsetDays === undefined ? null : demoDateOnlyUtc(project.startOffsetDays),
deadline: project.deadlineOffsetDays === undefined ? null : demoDateOnlyUtc(project.deadlineOffsetDays),
zustaendigePersonId: ownerUserId,
projektleiterId: project.projektleiterKey ? userIdByKey.get(project.projektleiterKey) ?? null : null,
projektAdresseId,
rechnungsAdresseId,
bauherrAdresseId,
wonAt: project.won ? new Date() : null,
lostAt: project.lost ? new Date() : null,
lostReasonId: project.lost ? lostReasonId : null,
isDemoData: true,
};
await db.projekt.upsert({ where: { id: projektId }, create: { id: projektId, ...data }, update: data });
projektIdByKey.set(project.key, projektId);
// Members are a list, so the seed has to be able to shrink it again: delete
// the demo rows for this project first, then write the current selection.
const memberIds = [
...(project.zustaendigeKeys ?? []).map((key) => ({ key, rolle: "zustaendig" as const })),
...(project.monteurKeys ?? []).map((key) => ({ key, rolle: "monteur" as const })),
].flatMap((entry) => {
const userId = userIdByKey.get(entry.key);
return userId ? [{ id: `demo-pmitglied-${project.key}-${entry.rolle}-${entry.key}`, userId, rolle: entry.rolle }] : [];
});
// Scoped to the seed's own id prefix: a member somebody added by hand in a
// local tenant must survive a reseed.
await db.projektMitglied.deleteMany({
where: { tenantId, projektId, id: { startsWith: `demo-pmitglied-${project.key}-`, notIn: memberIds.map((member) => member.id) } },
});
for (const member of memberIds) {
const fields = { tenantId, projektId, userId: member.userId, rolle: member.rolle, createdByUserId: ownerUserId, archivedAt: null };
await db.projektMitglied.upsert({ where: { id: member.id }, create: { id: member.id, ...fields }, update: fields });
}
const kontaktId = kontaktIdByKey.get(project.contactKey);
if (kontaktId) {
const linkId = `demo-pk-${project.key}`;
await db.projektKontakt.upsert({
where: { id: linkId },
create: { id: linkId, tenantId, projektId, kontaktId, rolle: "auftraggeber", primaer: true },
update: { projektId, kontaktId, rolle: "auftraggeber", primaer: true },
});
}
}
return projektIdByKey;
}
/**
* WF-P8 S05 + S02 side data: the field template of the sales board, the notes
* and appointments the detail screen and its quick actions show, the successor
* board M04 needs to trigger at all, and one deliberately stale stage change so
* the "Hängt N T" tag appears on a card.
*/
/**
* WF-P8 S01/S03 tags. Uses the shared CRM `Tag`/`TagAssignment` pair with
* `entityType = "projekt"` — the polymorphic model the schema already documents
* for exactly this, so tags need no project-owned table.
*
* `farbe` carries the kit tone name, not a hex: the Tag_Label tone is an enum, so
* a stored hex could not be rendered in its own colour anyway.
*/
async function seedProjectTags(db: DbClient, tenantId: string, projektIdByKey: Map<string, string>) {
const TAGS = [
{ key: "pv", name: "PV / Solar", farbe: "yellow-subtle" },
{ key: "waermepumpe", name: "Wärmepumpe", farbe: "sky-subtle" },
{ key: "heizung", name: "Heizung", farbe: "orange-subtle" },
{ key: "bad", name: "Bad / Sanitär", farbe: "blue-subtle" },
] as const;
const tagIdByKey = new Map<string, string>();
for (const tag of TAGS) {
const id = `demo-tag-${tag.key}`;
const fields = { tenantId, name: tag.name, farbe: tag.farbe };
// Upsert on the natural unique key: the tenant may already carry a tag of
// this name from the CRM, and a second one would break @@unique.
const existing = await db.tag.findFirst({ where: { tenantId, name: tag.name }, select: { id: true } });
if (existing) {
await db.tag.update({ where: { id: existing.id }, data: { farbe: tag.farbe } });
tagIdByKey.set(tag.key, existing.id);
continue;
}
await db.tag.upsert({ where: { id }, create: { id, ...fields }, update: fields });
tagIdByKey.set(tag.key, id);
}
const ASSIGNMENTS: { projectKey: string; tagKeys: readonly string[] }[] = [
{ projectKey: "heizungstausch-schneider", tagKeys: ["heizung", "waermepumpe"] },
{ projectKey: "bad-sanierung-wagner", tagKeys: ["bad"] },
{ projectKey: "waermepumpe-mueller", tagKeys: ["waermepumpe"] },
{ projectKey: "pv-anlage-koch", tagKeys: ["pv"] },
{ projectKey: "waermepumpe-weber", tagKeys: ["waermepumpe", "heizung"] },
{ projectKey: "badumbau-schulz", tagKeys: ["bad"] },
];
for (const assignment of ASSIGNMENTS) {
const projektId = projektIdByKey.get(assignment.projectKey);
if (!projektId) continue;
for (const tagKey of assignment.tagKeys) {
const tagId = tagIdByKey.get(tagKey);
if (!tagId) continue;
const fields = { tenantId, tagId, entityType: "projekt", entityId: projektId };
await db.tagAssignment.upsert({
where: { tagId_entityId_entityType: { tagId, entityId: projektId, entityType: "projekt" } },
create: fields,
update: fields,
});
}
}
}
async function seedProjectDetailAndTemplate(
db: DbClient,
tenantId: string,
ownerUserId: string,
userIdByKey: Map<string, string>,
pipelineIdByKey: Map<string, string>,
stageIdByKey: Map<string, string>,
projektIdByKey: Map<string, string>,
) {
const salesPipelineId = pipelineIdByKey.get("sales");
const auftragPipelineId = pipelineIdByKey.get("auftrag");
const flagshipId = projektIdByKey.get("heizungstausch-schneider");
if (!salesPipelineId || !auftragPipelineId || !flagshipId) {
throw new Error("Demo detail seed is missing the sales/auftrag pipeline or the flagship project.");
}
// M04 Pipeline-Übergabe only triggers when the board declares a successor.
await db.pipeline.update({ where: { id: salesPipelineId }, data: { nachfolgePipelineId: auftragPipelineId } });
const GROUPS = [
{ key: "grunddaten", name: "Grunddaten", reihenfolge: 0, istSystem: true },
{ key: "planung", name: "Planung & Verantwortliche", reihenfolge: 1, istSystem: false },
{ key: "technik", name: "Technik", reihenfolge: 2, istSystem: false },
] as const;
const groupIdByKey = new Map<string, string>();
for (const group of GROUPS) {
const id = `demo-fieldgroup-${group.key}`;
const fields = { tenantId, pipelineId: salesPipelineId, name: group.name, reihenfolge: group.reihenfolge, istSystem: group.istSystem, isDemoData: true };
await db.pipelineFieldGroup.upsert({ where: { id }, create: { id, ...fields }, update: fields });
groupIdByKey.set(group.key, id);
}
// Two custom fields with options, on purpose in both shapes: the canonical one
// the editor writes, and the historical `{ select: [...] }` one older rows
// carry, so the tolerant parser stays covered by the demo data too.
const DEFINITIONS = [
{
key: "aufmass_status",
label: "Aufmaß-Status",
datentyp: "select" as const,
optionen: {
options: [
{ value: "offen", label: "Offen", color: "#f59e0b" },
{ value: "geplant", label: "Geplant", color: "#3b82f6" },
{ value: "erledigt", label: "Erledigt", color: "#22c55e" },
],
},
},
{ key: "dachform", label: "Dachform", datentyp: "select" as const, optionen: { select: ["Satteldach", "Flachdach", "Pultdach"] } },
{ key: "foerdernummer", label: "Fördernummer", datentyp: "text" as const, optionen: null },
];
const definitionIdByKey = new Map<string, string>();
for (const definition of DEFINITIONS) {
const id = `demo-cfdef-${definition.key}`;
const fields = {
tenantId,
entityType: "projekt" as const,
key: definition.key,
label: definition.label,
datentyp: definition.datentyp,
// Same conversion the custom-field service uses: an absent option list is
// a JSON null in the column, not a `null` scalar Prisma would reject.
optionen: definition.optionen === null ? Prisma.JsonNull : (definition.optionen as Prisma.InputJsonValue),
isDemoData: true,
};
await db.customFieldDefinition.upsert({ where: { id }, create: { id, ...fields }, update: fields });
definitionIdByKey.set(definition.key, id);
}
// Grunddaten holds the system fields the screen always shows; Technik the two
// custom ones; "Fördernummer" stays ungrouped so the pool is not empty.
const FIELD_CONFIGS = [
{ fieldKey: "projektname", group: "grunddaten", istSystem: true, pflicht: true, reihenfolge: 0 },
{ fieldKey: "status", group: "grunddaten", istSystem: true, pflicht: true, reihenfolge: 1 },
{ fieldKey: "prioritaet", group: "grunddaten", istSystem: true, pflicht: false, reihenfolge: 2 },
{ fieldKey: "quelle", group: "grunddaten", istSystem: true, pflicht: false, reihenfolge: 3 },
{ fieldKey: "projektleiter", group: "planung", istSystem: true, pflicht: false, reihenfolge: 0 },
{ fieldKey: "deadline", group: "planung", istSystem: true, pflicht: false, reihenfolge: 1, hinweis: "Verbindlicher Termin gegenüber dem Kunden." },
{ fieldKey: "aufmass_status", group: "technik", istSystem: false, pflicht: false, reihenfolge: 0, hinweis: "Erst setzen, wenn das Aufmaß vor Ort abgeschlossen ist." },
{ fieldKey: "dachform", group: "technik", istSystem: false, pflicht: false, reihenfolge: 1 },
{ fieldKey: "foerdernummer", group: null, istSystem: false, pflicht: false, reihenfolge: 0 },
] as const;
for (const config of FIELD_CONFIGS) {
const id = `demo-fieldconfig-${config.fieldKey}`;
const fields = {
tenantId,
pipelineId: salesPipelineId,
fieldKey: config.fieldKey,
groupId: config.group ? groupIdByKey.get(config.group) ?? null : null,
sichtbar: true,
pflicht: config.pflicht,
reihenfolge: config.reihenfolge,
istSystem: config.istSystem,
gesperrt: false,
hinweis: "hinweis" in config ? config.hinweis : null,
};
await db.pipelineFieldConfig.upsert({ where: { id }, create: { id, ...fields }, update: fields });
}
// One stored value, so the retype guard has something to refuse on.
const aufmassDefinitionId = definitionIdByKey.get("aufmass_status");
if (aufmassDefinitionId) {
const valueId = "demo-cfvalue-aufmass-flagship";
const fields = { tenantId, definitionId: aufmassDefinitionId, entityType: "projekt" as const, entityId: flagshipId, wert: "geplant" };
await db.customFieldValue.upsert({ where: { id: valueId }, create: { id: valueId, ...fields }, update: fields });
}
const NOTES = [
{ key: "foerderung", inhalt: "Familie ist förderprogramm-affin und möchte vor dem Sommer entscheiden.", sichtbarkeit: "alle" as const, autor: "vertrieb" },
{ key: "wettbewerb", inhalt: "Zwei Vergleichsangebote liegen vor, Preisgespräch ist angekündigt.", sichtbarkeit: "innendienst" as const, autor: "buero" },
{ key: "intern", inhalt: "Eigene Notiz: beim Nachfassen zuerst die Heizlastberechnung ansprechen.", sichtbarkeit: "nur_ich" as const, autor: "owner" },
];
for (const note of NOTES) {
const id = `demo-pnotiz-${note.key}`;
const fields = {
tenantId,
projektId: flagshipId,
autorUserId: userIdByKey.get(note.autor) ?? ownerUserId,
inhalt: note.inhalt,
sichtbarkeit: note.sichtbarkeit,
isDemoData: true,
archivedAt: null,
};
await db.projektNotiz.upsert({ where: { id }, create: { id, ...fields }, update: fields });
}
const APPOINTMENTS = [
{ key: "aufmass", titel: "Aufmaß vor Ort", typ: "vor_ort" as const, offsetDays: 3, hour: 9, assigned: "monteur" },
{ key: "angebot", titel: "Angebotsgespräch", typ: "telefon" as const, offsetDays: 6, hour: 14, assigned: "vertrieb" },
{ key: "planung", titel: "Planungsabstimmung", typ: "online" as const, offsetDays: 10, hour: 11, assigned: "buero" },
];
for (const appointment of APPOINTMENTS) {
const id = `demo-ptermin-${appointment.key}`;
const startAt = demoDate(appointment.offsetDays, appointment.hour);
const fields = {
tenantId,
projektId: flagshipId,
createdByUserId: ownerUserId,
assignedToUserId: userIdByKey.get(appointment.assigned) ?? ownerUserId,
titel: appointment.titel,
startAt,
endAt: new Date(startAt.getTime() + 90 * 60 * 1000),
status: "geplant" as const,
typ: appointment.typ,
isDemoData: true,
archivedAt: null,
};
await db.projektTermin.upsert({ where: { id }, create: { id, ...fields }, update: fields });
}
// Two stage moves on the flagship project, so the S02 rail "Verlauf" tile has
// history to show instead of its empty state.
const flagshipMoves = [
{ key: "neu-qualifiziert", from: "sales:neu", to: "sales:qualifiziert", offsetDays: -18 },
{ key: "qualifiziert-angebot", from: "sales:qualifiziert", to: "sales:angebot", offsetDays: -6 },
];
for (const move of flagshipMoves) {
const fromStageId = stageIdByKey.get(move.from);
const toStageId = stageIdByKey.get(move.to);
if (!fromStageId || !toStageId) continue;
const id = `demo-pstagechange-${move.key}`;
const fields = {
tenantId,
projektId: flagshipId,
fromStageId,
toStageId,
changedByUserId: userIdByKey.get("vertrieb") ?? ownerUserId,
createdAt: demoDate(move.offsetDays, 10),
};
await db.projektStageChange.upsert({ where: { id }, create: { id, ...fields }, update: fields });
}
// A stage change older than STUCK_AFTER_DAYS, so one card carries the
// "Hängt N T" tag instead of the tag only being reachable by waiting a week.
const stuckProjektId = projektIdByKey.get("heizlast-becker");
const neuStageId = stageIdByKey.get("sales:neu");
if (stuckProjektId && neuStageId) {
const id = "demo-pstagechange-stuck";
const fields = {
tenantId,
projektId: stuckProjektId,
fromStageId: neuStageId,
toStageId: neuStageId,
changedByUserId: ownerUserId,
createdAt: demoDate(-21, 8),
};
await db.projektStageChange.upsert({ where: { id }, create: { id, ...fields }, update: fields });
}
}
async function seedLeads(db: DbClient, tenantId: string, ownerUserId: string) {
const sourceIdByKey = new Map<string, string>();
for (const source of HIVEGRID_DEMO_LEAD_SOURCES) {
const created = await db.leadSource.upsert({
where: { tenantId_key: { tenantId, key: source.key } },
create: { tenantId, type: source.type, key: source.key, name: source.name, displayLabel: source.displayLabel, isDemoData: true },
update: { type: source.type, name: source.name, displayLabel: source.displayLabel, isDemoData: true },
});
sourceIdByKey.set(source.key, created.id);
}
const leadIdByKey = new Map<string, string>();
for (const lead of HIVEGRID_DEMO_LEADS) {
const leadId = `demo-lead-${lead.key}`;
const sourceId = lead.sourceKey ? sourceIdByKey.get(lead.sourceKey) ?? null : null;
const data = {
tenantId,
createdByUserId: ownerUserId,
zustaendigerUserId: ownerUserId,
quelle: lead.quelle,
sourceId,
status: lead.status,
vorname: lead.vorname,
nachname: lead.nachname,
email: lead.email,
telefon: lead.telefon,
message: lead.message,
spamScore: lead.spamScore ?? 0,
isQuarantined: lead.isQuarantined ?? false,
convertedAt: lead.status === "converted" ? new Date() : null,
lostAt: lead.status === "lost" ? new Date() : null,
spamMarkedAt: lead.status === "spam" ? new Date() : null,
isDemoData: true,
};
await db.inboxLead.upsert({ where: { id: leadId }, create: { id: leadId, ...data }, update: data });
leadIdByKey.set(lead.key, leadId);
}
return leadIdByKey;
}
function buildDemoFormDefinition(form: DemoFormSeed) {
return {
title: form.name,
submitLabel: "Absenden",
successMessage: "Vielen Dank, wir melden uns schnellstmöglich.",
gdprConsentLabel: "Ich stimme der Verarbeitung meiner Angaben zur Bearbeitung der Anfrage zu.",
captchaEnabled: true,
fields: form.fields.map((field) => ({
key: field.key,
type: field.type,
label: field.label,
required: field.required ?? false,
...(field.helpText ? { helpText: field.helpText } : {}),
...(field.placeholder ? { placeholder: field.placeholder } : {}),
...(field.options ? { options: field.options } : {}),
})),
};
}
async function seedForms(db: DbClient, tenantId: string, ownerUserId: string, leadIdByKey: Map<string, string>) {
const formIdByKey = new Map<string, string>();
for (const form of HIVEGRID_DEMO_FORMS) {
const formId = `demo-form-${form.key}`;
const definition = buildDemoFormDefinition(form);
const status = form.status ?? "published";
const isPublished = status === "published";
// Internal forms never expose a public link (WF-P16 S01 type contract).
const isPublic = isPublished && form.subtype !== "internal";
const fieldMapping = form.actionFieldMapping ?? DEMO_LEAD_FIELD_MAPPING;
const formData = {
slug: form.slug,
name: form.name,
subtype: form.subtype,
status,
publishedAt: isPublished ? new Date() : null,
isPublic,
isDemoData: true,
definition,
allowedOrigins: isPublic ? ["https://www.hivegrid-demo.local"] : [],
notifyEmails: ["buero@hivegrid.de"],
targetType: form.targetType,
fieldMapping,
config: { honeypotEnabled: true, captchaEnabled: true },
isEnabled: true,
};
await db.form.upsert({
where: { id: formId },
create: {
id: formId,
tenantId,
createdByUserId: ownerUserId,
key: `demo_${form.key}`,
...formData,
},
update: formData,
});
formIdByKey.set(form.key, formId);
await db.formField.deleteMany({ where: { formId, tenantId } });
await db.formField.createMany({
data: form.fields.map((field, position) => ({
formId,
tenantId,
fieldKey: field.key,
fieldType: field.type,
label: field.label,
helpText: field.helpText ?? null,
placeholder: field.placeholder ?? null,
required: field.required ?? false,
position,
options: field.options ?? [],
validationRules: {},
conditionalLogic: [],
isSystem: field.type === "honeypot",
})),
});
const actionId = `demo-formaction-${form.key}-primary`;
const actionType = form.targetType === "create-lead" ? "create_lead" : "send_email_to_team";
const actionName = form.targetType === "create-lead" ? "Lead erzeugen" : "Team benachrichtigen";
await db.formAction.upsert({
where: { id: actionId },
create: {
id: actionId,
formId,
tenantId,
actionType,
name: actionName,
position: 0,
enabled: true,
fieldMapping,
actionConfig: { source: "hivegrid-demo" },
},
update: {
actionType,
name: actionName,
enabled: true,
fieldMapping,
actionConfig: { source: "hivegrid-demo" },
},
});
for (const submission of form.submissions) {
const submissionId = `demo-formsub-${form.key}-${submission.key}`;
const linkedEntityId = submission.linkedLeadKey ? leadIdByKey.get(submission.linkedLeadKey) ?? null : null;
await db.formSubmission.upsert({
where: { id: submissionId },
create: {
id: submissionId,
formId,
tenantId,
payload: { values: submission.values },
sourceOrigin: submission.sourceOrigin,
ipHash: `demo-ip-${submission.key}`,
userAgent: "HiveGrid demo seed",
status: submission.status,
result: { seeded: true },
linkedEntityType: submission.linkedEntityType ?? null,
linkedEntityId,
idempotencyKey: `demo:${form.key}:${submission.key}`,
gdprAccepted: true,
},
update: {
payload: { values: submission.values },
sourceOrigin: submission.sourceOrigin,
userAgent: "HiveGrid demo seed",
status: submission.status,
result: { seeded: true },
linkedEntityType: submission.linkedEntityType ?? null,
linkedEntityId,
gdprAccepted: true,
},
});
const logStatus = submission.status === "route-failed" ? "failed" : submission.status === "spam" ? "skipped" : "success";
await db.formActionLog.upsert({
where: { id: `demo-formactionlog-${form.key}-${submission.key}` },
create: {
id: `demo-formactionlog-${form.key}-${submission.key}`,
formActionId: actionId,
submissionId,
formId,
tenantId,
actionType,
status: logStatus,
inputSnapshot: { values: submission.values },
outputSnapshot: { seeded: true, linkedEntityId },
errorMessage: submission.actionErrorMessage ?? null,
targetType: submission.linkedEntityType ?? null,
targetId: linkedEntityId,
idempotencyKey: `demo:${form.key}:${submission.key}:primary`,
finishedAt: new Date(),
},
update: {
status: logStatus,
inputSnapshot: { values: submission.values },
outputSnapshot: { seeded: true, linkedEntityId },
errorMessage: submission.actionErrorMessage ?? null,
targetType: submission.linkedEntityType ?? null,
targetId: linkedEntityId,
finishedAt: new Date(),
},
});
}
}
return formIdByKey;
}
async function seedTasks(
db: DbClient,
tenantId: string,
ownerUserId: string,
userIdByKey: Map<string, string>,
projektIdByKey: Map<string, string>,
kontaktIdByKey: Map<string, string>,
) {
for (const task of HIVEGRID_DEMO_TASKS) {
const taskId = `demo-task-${task.key}`;
const assignedToUserId = userIdByKey.get(task.assigneeKey) ?? ownerUserId;
const linkedEntityId = task.linkedProjectKey ? projektIdByKey.get(task.linkedProjectKey) : task.linkedContactKey ? kontaktIdByKey.get(task.linkedContactKey) : null;
const data = {
tenantId,
createdByUserId: ownerUserId,
title: task.title,
description: task.description ?? null,
status: task.status,
priority: task.priority,
assignedToUserId,
linkedEntityType: task.linkedEntityType ?? null,
linkedEntityId: linkedEntityId ?? null,
completedAt: task.completed ? new Date() : null,
isDemoData: true,
};
await db.task.upsert({ where: { id: taskId }, create: { id: taskId, ...data }, update: data });
}
}
async function seedInvoices(db: DbClient, tenantId: string, ownerUserId: string, projektIdByKey: Map<string, string>) {
const invoices = [
{ nummer: "RE-2026-0001", projectKey: "rohrbruch-davinci", betrag: "890.00", status: "bezahlt" as const },
{ nummer: "RE-2026-0002", projectKey: "wartung-baeckerei", betrag: "1450.00", status: "gestellt" as const },
];
for (const invoice of invoices) {
const projektId = projektIdByKey.get(invoice.projectKey);
if (!projektId) {
continue;
}
const data = {
tenantId,
projektId,
createdByUserId: ownerUserId,
betrag: invoice.betrag,
status: invoice.status,
quelle: "manuell" as const,
isDemoData: true,
};
await db.rechnung.upsert({
where: { tenantId_rechnungsnummer: { tenantId, rechnungsnummer: invoice.nummer } },
create: { rechnungsnummer: invoice.nummer, ...data },
update: data,
});
}
}
async function seedNotifications(db: DbClient, tenantId: string, ownerUserId: string) {
const notifications = [
{ sourceKey: "demo-notif-lead-1", category: "leads", messageKey: "notifications.lead.new", status: "SENT" as const },
{ sourceKey: "demo-notif-project-1", category: "projects", messageKey: "notifications.project.won", status: "READ" as const },
{ sourceKey: "demo-notif-task-1", category: "tasks", messageKey: "notifications.task.assigned", status: "PENDING" as const },
{ sourceKey: "demo-notif-invoice-1", category: "billing", messageKey: "notifications.invoice.paid", status: "SENT" as const },
];
for (const notification of notifications) {
const data = {
channel: "IN_APP" as const,
category: notification.category,
messageKey: notification.messageKey,
status: notification.status,
sentAt: notification.status === "SENT" || notification.status === "READ" ? new Date() : null,
readAt: notification.status === "READ" ? new Date() : null,
};
await db.notificationDelivery.upsert({
where: { notification_delivery_source_key: { tenantId, userId: ownerUserId, channel: "IN_APP", sourceKey: notification.sourceKey } },
create: { tenantId, userId: ownerUserId, sourceKey: notification.sourceKey, ...data },
update: data,
});
}
}
async function seedActivities(
db: DbClient,
tenantId: string,
ownerUserId: string,
kontaktIdByKey: Map<string, string>,
projektIdByKey: Map<string, string>,
leadIdByKey: Map<string, string>,
) {
// Typed inserts into the central Activity stream — equivalent to
// `logActivity()` from @hivegrid/activity (which just validates and calls
// `activity.create`), written directly here because that package is not a
// root-workspace dependency of standalone scripts. `activityType`/`subjectType`
// strings match the ActivityType/ActivitySubjectType unions.
const entries: { activityType: string; subjectType: string; subjectId?: string; summaryText: string }[] = [
{ activityType: "contact_created", subjectType: "contact", subjectId: kontaktIdByKey.get("thomas-schneider"), summaryText: "Kontakt Thomas Schneider angelegt (Neukunde Heizungstausch)." },
{ activityType: "contact_created", subjectType: "company", subjectId: kontaktIdByKey.get("hausverwaltung-mueller"), summaryText: "Firma Hausverwaltung Müller & Partner GmbH als Bestandskunde angelegt." },
{ activityType: "project_updated", subjectType: "project", subjectId: projektIdByKey.get("heizungstausch-schneider"), summaryText: "Projekt Heizungstausch EFH Schneider in Stufe Angebot verschoben." },
{ activityType: "lead_created", subjectType: "lead", subjectId: leadIdByKey.get("klein-waermepumpe"), summaryText: "Neuer Lead über das Website-Kontaktformular: Familie Klein (Wärmepumpe)." },
{ activityType: "note_added", subjectType: "project", subjectId: projektIdByKey.get("wartung-baeckerei"), summaryText: "Notiz: Wartungsvertrag Bäckerei Sonnenschein läuft, Jahrestermin einplanen." },
];
const withSubject = entries.filter((entry): entry is typeof entry & { subjectId: string } => Boolean(entry.subjectId));
const subjectIds = withSubject.map((entry) => entry.subjectId);
// Direct create has no natural unique key; delete the demo subjects' activities
// first so re-runs keep a stable count instead of piling up duplicates.
await db.activity.deleteMany({ where: { tenantId, subjectId: { in: subjectIds } } });
for (const entry of withSubject) {
await db.activity.create({
data: {
tenantId,
actorUserId: ownerUserId,
actorKind: "user",
activityType: entry.activityType,
subjectType: entry.subjectType,
subjectId: entry.subjectId,
summaryText: entry.summaryText,
},
});
}
}
async function seedApiKeyAndWebhook(db: DbClient, tenantId: string, ownerUserId: string) {
const key = "hgd_demo_website_lead_intake_not_for_auth";
const apiKey = await db.apiKey.upsert({
where: { tenantId_alias: { tenantId, alias: HIVEGRID_DEMO_API_KEY_ALIAS } },
create: {
tenantId,
createdByUserId: ownerUserId,
alias: HIVEGRID_DEMO_API_KEY_ALIAS,
key,
...deriveLegacyApiKeyHashMetadata(key, undefined, new Date("2026-06-01T00:00:00.000Z")),
// Incoming-webhook scope is required so the seeded website endpoint (authMode
// "api_key") actually accepts POST /v1/webhooks/incoming/:tenant/:slug requests.
scopes: ["public_api:read", "public_api:write", "public_api:webhooks:incoming"],
expires: null,
active: true,
},
update: {
key,
...deriveLegacyApiKeyHashMetadata(key, undefined, new Date("2026-06-01T00:00:00.000Z")),
// Incoming-webhook scope is required so the seeded website endpoint (authMode
// "api_key") actually accepts POST /v1/webhooks/incoming/:tenant/:slug requests.
scopes: ["public_api:read", "public_api:write", "public_api:webhooks:incoming"],
expires: null,
active: true,
},
});
await db.publicIncomingWebhookEndpoint.upsert({
where: { tenantId_slug: { tenantId, slug: HIVEGRID_DEMO_WEBHOOK_SLUG } },
create: {
tenantId,
slug: HIVEGRID_DEMO_WEBHOOK_SLUG,
name: "Website Kontaktformular",
authMode: "api_key",
apiKeyId: apiKey.id,
status: "active",
isDemoData: true,
},
update: { name: "Website Kontaktformular", authMode: "api_key", apiKeyId: apiKey.id, status: "active", isDemoData: true },
});
return apiKey;
}
function demoDate(dayOffset: number, hour: number, minute = 0): Date {
const value = new Date();
value.setDate(value.getDate() + dayOffset);
value.setHours(hour, minute, 0, 0);
return value;
}
/** Calendar-date-only value at UTC midnight (matches AvailabilityService's `@db.Date` storage). */
function demoDateOnlyUtc(dayOffset: number): Date {
const value = new Date();
value.setDate(value.getDate() + dayOffset);
return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
}
async function seedBookingAndCalendar(
db: DbClient,
tenantId: string,
ownerUserId: string,
userIdByKey: Map<string, string>,
kontaktIdByKey: Map<string, string>,
) {
const calendarConnectionIdByUserKey = new Map<string, string>();
for (const userKey of ["owner", "vertrieb", "monteur"]) {
const userId = userIdByKey.get(userKey);
if (!userId) {
continue;
}
const connectionId = `demo-calconn-${userKey}`;
await db.calendarConnection.upsert({
where: { id: connectionId },
create: {
id: connectionId,
tenantId,
userId,
provider: "google",
externalAccountEmail: `${userKey}@kalender.hivegrid-demo.local`,
externalAccountId: `demo-google-${userKey}`,
oauthScopes: ["calendar.readonly", "calendar.events"],
selectedCalendars: [{ id: "primary", summary: "HiveGrid Demo" }],
syncDirection: "bidirectional",
status: userKey === "monteur" ? "paused" : "active",
lastSyncAt: demoDate(-1, 7),
lastErrorText: userKey === "monteur" ? "Demo: Verbindung pausiert, Reconnect erforderlich." : null,
isDemoData: true,
},
update: {
externalAccountEmail: `${userKey}@kalender.hivegrid-demo.local`,
oauthScopes: ["calendar.readonly", "calendar.events"],
selectedCalendars: [{ id: "primary", summary: "HiveGrid Demo" }],
syncDirection: "bidirectional",
status: userKey === "monteur" ? "paused" : "active",
lastSyncAt: demoDate(-1, 7),
lastErrorText: userKey === "monteur" ? "Demo: Verbindung pausiert, Reconnect erforderlich." : null,
isDemoData: true,
},
});
calendarConnectionIdByUserKey.set(userKey, connectionId);
for (const [index, dayOfWeek] of (["monday", "tuesday", "wednesday", "thursday", "friday"] as const).entries()) {
await db.availabilityRule.upsert({
where: { id: `demo-avail-${userKey}-${dayOfWeek}` },
create: {
id: `demo-avail-${userKey}-${dayOfWeek}`,
tenantId,
providerUserId: userId,
dayOfWeek,
startTime: index === 4 ? "08:00" : "08:30",
endTime: index === 4 ? "14:00" : "17:00",
timezone: "Europe/Berlin",
},
update: {
startTime: index === 4 ? "08:00" : "08:30",
endTime: index === 4 ? "14:00" : "17:00",
timezone: "Europe/Berlin",
},
});
}
// Date exceptions for the /availability editor (AK-P16b): one full-day
// absence and one custom window, upcoming so the screen shows live data.
if (userKey !== "monteur") {
const exceptionSeeds = [
{ suffix: "urlaub", dayOffset: 8, kind: "unavailable" as const, startTime: null, endTime: null, reason: "Demo: Urlaubstag" },
{ suffix: "fortbildung", dayOffset: 10, kind: "custom_window" as const, startTime: "10:00", endTime: "14:00", reason: "Demo: Fortbildung am Vormittag" },
];
for (const exception of exceptionSeeds) {
await db.availabilityException.upsert({
where: { id: `demo-availex-${userKey}-${exception.suffix}` },
create: {
id: `demo-availex-${userKey}-${exception.suffix}`,
tenantId,
providerUserId: userId,
date: demoDateOnlyUtc(exception.dayOffset),
kind: exception.kind,
startTime: exception.startTime,
endTime: exception.endTime,
reason: exception.reason,
timezone: "Europe/Berlin",
},
update: {
date: demoDateOnlyUtc(exception.dayOffset),
kind: exception.kind,
startTime: exception.startTime,
endTime: exception.endTime,
reason: exception.reason,
timezone: "Europe/Berlin",
},
});
}
}
}
const appointmentIdByKey = new Map<string, string>();
for (const page of HIVEGRID_DEMO_BOOKING_PAGES) {
const pageId = `demo-booking-page-${page.key}`;
await db.bookingPage.upsert({
where: { id: pageId },
create: {
id: pageId,
tenantId,
createdByUserId: ownerUserId,
slug: page.slug,
title: page.title,
description: page.description,
durationMinutes: page.durationMinutes,
bufferBeforeMinutes: 10,
bufferAfterMinutes: 15,
slotIncrementMinutes: 15,
minNoticeHours: 4,
maxAdvanceDays: 45,
assignmentStrategy: "first_available",
confirmationEmailSubject: "Ihr HiveGrid Demo-Termin ist bestätigt",
confirmationEmailBody: "Vielen Dank für die Buchung. Wir melden uns vor dem Termin mit den Details.",
internalEventTitleTemplate: "HiveGrid Termin: {{customerName}}",
redirectUrlAfterBooking: "https://www.hivegrid-demo.local/danke",
intakeFormId: page.intakeFormKey ? `demo-form-${page.intakeFormKey}` : null,
isPublished: true,
isDemoData: true,
},
update: {
slug: page.slug,
title: page.title,
description: page.description,
durationMinutes: page.durationMinutes,
bufferBeforeMinutes: 10,
bufferAfterMinutes: 15,
slotIncrementMinutes: 15,
minNoticeHours: 4,
maxAdvanceDays: 45,
assignmentStrategy: "first_available",
confirmationEmailSubject: "Ihr HiveGrid Demo-Termin ist bestätigt",
confirmationEmailBody: "Vielen Dank für die Buchung. Wir melden uns vor dem Termin mit den Details.",
internalEventTitleTemplate: "HiveGrid Termin: {{customerName}}",
redirectUrlAfterBooking: "https://www.hivegrid-demo.local/danke",
intakeFormId: page.intakeFormKey ? `demo-form-${page.intakeFormKey}` : null,
isPublished: true,
isDemoData: true,
},
});
for (const [index, providerKey] of page.providerKeys.entries()) {
const providerUserId = userIdByKey.get(providerKey);
if (!providerUserId) {
continue;
}
await db.bookingPageProvider.upsert({
where: { bookingPageId_providerUserId: { bookingPageId: pageId, providerUserId } },
create: { tenantId, bookingPageId: pageId, providerUserId, displayOrder: index, isActive: true },
update: { displayOrder: index, isActive: true },
});
}
for (const appointment of page.appointments) {
const providerUserId = userIdByKey.get(appointment.providerKey) ?? ownerUserId;
const startAt = demoDate(appointment.dayOffset, appointment.startHour, appointment.startMinute);
const endAt = new Date(startAt.getTime() + page.durationMinutes * 60_000);
const appointmentId = `demo-appt-${appointment.key}`;
const kontaktId = kontaktIdByKey.get(appointment.contactKey) ?? null;
await db.appointment.upsert({
where: { id: appointmentId },
create: {
id: appointmentId,
tenantId,
bookingPageId: pageId,
providerUserId,
startAt,
endAt,
timezone: "Europe/Berlin",
status: appointment.status,
kontaktId,
intakeAnswers: appointment.intakeAnswers,
cancelledAt: appointment.status === "cancelled" ? new Date() : null,
cancelledByKind: appointment.status === "cancelled" ? "customer" : null,
cancellationReason: appointment.status === "cancelled" ? "Demo: Kunde hat Termin verschoben." : null,
notesInternal: appointment.notesInternal ?? null,
isDemoData: true,
},
update: {
bookingPageId: pageId,
providerUserId,
startAt,
endAt,
timezone: "Europe/Berlin",
status: appointment.status,
kontaktId,
intakeAnswers: appointment.intakeAnswers,
cancelledAt: appointment.status === "cancelled" ? new Date() : null,
cancelledByKind: appointment.status === "cancelled" ? "customer" : null,
cancellationReason: appointment.status === "cancelled" ? "Demo: Kunde hat Termin verschoben." : null,
notesInternal: appointment.notesInternal ?? null,
isDemoData: true,
},
});
appointmentIdByKey.set(appointment.key, appointmentId);
const calendarEventId = `demo-calevent-appt-${appointment.key}`;
await db.calendarEvent.upsert({
where: { id: calendarEventId },
create: {
id: calendarEventId,
tenantId,
userId: providerUserId,
source: "hivegrid_internal",
title: `${page.title}: ${appointment.intakeAnswers.vorname} ${appointment.intakeAnswers.nachname}`,
description: appointment.intakeAnswers.anliegen ?? page.description,
startsAt: startAt,
endsAt: endAt,
timeZone: "Europe/Berlin",
isBusyForAvailability: true,
internalEntityLink: { type: "appointment", id: appointmentId },
isDemoData: true,
},
update: {
title: `${page.title}: ${appointment.intakeAnswers.vorname} ${appointment.intakeAnswers.nachname}`,
description: appointment.intakeAnswers.anliegen ?? page.description,
startsAt: startAt,
endsAt: endAt,
timeZone: "Europe/Berlin",
isBusyForAvailability: true,
internalEntityLink: { type: "appointment", id: appointmentId },
isDemoData: true,
},
});
await db.appointment.update({ where: { id: appointmentId }, data: { internalCalendarEventId: calendarEventId } });
}
}
const ownerConnectionId = calendarConnectionIdByUserKey.get("owner");
const ownerCalendarUserId = userIdByKey.get("owner") ?? ownerUserId;
if (ownerConnectionId) {
await db.calendarEvent.upsert({
where: { id: "demo-calevent-material-abholung" },
create: {
id: "demo-calevent-material-abholung",
tenantId,
userId: ownerCalendarUserId,
connectionId: ownerConnectionId,
source: "external_synced",
provider: "google",
externalEventId: "demo-ext-material-abholung",
title: "Materialabholung Großhandel",
description: "Demo-Termin aus externem Kalender.",
startsAt: demoDate(1, 7, 30),
endsAt: demoDate(1, 8, 15),
timeZone: "Europe/Berlin",
isBusyForAvailability: true,
internalEntityLink: { type: "external_calendar" },
isDemoData: true,
},
update: {
startsAt: demoDate(1, 7, 30),
endsAt: demoDate(1, 8, 15),
isDemoData: true,
},
});
// Additional external events so the interim month/week grid (AK-P16a DoD 5)
// shows source variety: a private busy slot and a multi-day all-day fair.
await db.calendarEvent.upsert({
where: { id: "demo-calevent-zahnarzt" },
create: {
id: "demo-calevent-zahnarzt",
tenantId,
userId: ownerCalendarUserId,
connectionId: ownerConnectionId,
source: "external_synced",
provider: "google",
externalEventId: "demo-ext-zahnarzt",
title: "Privat: Zahnarzt",
description: "Demo-Termin aus externem Kalender.",
startsAt: demoDate(3, 13, 0),
endsAt: demoDate(3, 14, 0),
timeZone: "Europe/Berlin",
isBusyForAvailability: true,
internalEntityLink: { type: "external_calendar" },
isDemoData: true,
},
update: {
startsAt: demoDate(3, 13, 0),
endsAt: demoDate(3, 14, 0),
isDemoData: true,
},
});
await db.calendarEvent.upsert({
where: { id: "demo-calevent-messe" },
create: {
id: "demo-calevent-messe",
tenantId,
userId: ownerCalendarUserId,
connectionId: ownerConnectionId,
source: "external_synced",
provider: "google",
externalEventId: "demo-ext-messe",
title: "Handwerksmesse Freiburg",
description: "Demo: zweitägige Messe aus dem externen Kalender.",
startsAt: demoDate(9, 0, 0),
endsAt: demoDate(11, 0, 0),
timeZone: "Europe/Berlin",
isAllDay: true,
isBusyForAvailability: false,
internalEntityLink: { type: "external_calendar" },
isDemoData: true,
},
update: {
startsAt: demoDate(9, 0, 0),
endsAt: demoDate(11, 0, 0),
isAllDay: true,
isDemoData: true,
},
});
await db.calendarConflict.upsert({
where: { id: "demo-calconflict-owner-1" },
create: {
id: "demo-calconflict-owner-1",
tenantId,
connectionId: ownerConnectionId,
userId: ownerCalendarUserId,
externalEventId: "demo-ext-material-abholung",
resolution: "hivegrid_won",
descriptionText: "Demo-Konflikt: Externer Termin überschnitt sich mit einer Beratung, HiveGrid-Zeitfenster blieb führend.",
isDemoData: true,
},
update: {
resolution: "hivegrid_won",
descriptionText: "Demo-Konflikt: Externer Termin überschnitt sich mit einer Beratung, HiveGrid-Zeitfenster blieb führend.",
isDemoData: true,
},
});
}
return appointmentIdByKey;
}
function automationFlowData(rule: DemoAutomationSeed) {
return {
triggerKey: rule.triggerKey,
steps: rule.steps.map((step) => ({
stepKey: step.key,
kind: step.kind,
nodeType: step.nodeType,
parentStepIds: step.parentStepIds,
summaryKey: step.summaryText,
})),
};
}
async function seedAutomations(db: DbClient, tenantId: string, ownerUserId: string) {
for (const ruleSeed of HIVEGRID_DEMO_AUTOMATIONS) {
const ruleId = `demo-auto-${ruleSeed.key}`;
await db.automationRule.upsert({
where: { id: ruleId },
create: {
id: ruleId,
tenantId,
name: ruleSeed.name,
description: ruleSeed.description,
status: ruleSeed.status,
enabled: ruleSeed.enabled,
createdVia: "demo-seed",
triggerKey: ruleSeed.triggerKey,
flowData: automationFlowData(ruleSeed),
createdByUserId: ownerUserId,
isDemoData: true,
},
update: {
name: ruleSeed.name,
description: ruleSeed.description,
status: ruleSeed.status,
enabled: ruleSeed.enabled,
triggerKey: ruleSeed.triggerKey,
flowData: automationFlowData(ruleSeed),
isDemoData: true,
},
});
// The real step ids, keyed by stepKey. Step executions reference them by FK,
// and the id is only the synthetic demo one for rows this seed created.
const stepIdByKey = new Map<string, string>();
for (const [index, step] of ruleSeed.steps.entries()) {
// Upsert on the natural unique key, not on the synthetic demo id: a step
// for this (ruleId, stepKey) can already exist with a cuid written by the
// automation editor, and matching by id would then try to INSERT a
// duplicate and abort the whole seed.
const savedStep = await db.automationRuleStep.upsert({
where: { ruleId_stepKey: { ruleId, stepKey: step.key } },
create: {
id: `demo-auto-step-${ruleSeed.key}-${step.key}`,
tenantId,
ruleId,
stepKey: step.key,
stepKind: step.kind,
nodeType: step.nodeType,
config: {},
parentStepIds: step.parentStepIds,
position: { x: 160 + index * 220, y: 120 },
sortOrder: index,
summaryText: step.summaryText,
isDemoData: true,
},
update: {
stepKind: step.kind,
nodeType: step.nodeType,
config: {},
parentStepIds: step.parentStepIds,
position: { x: 160 + index * 220, y: 120 },
sortOrder: index,
summaryText: step.summaryText,
isDemoData: true,
},
});
stepIdByKey.set(step.key, savedStep.id);
}
if (ruleSeed.anomaly) {
// Active trigger-volume anomaly so the S01 warning banner and the M02
// dialog have real data. pausedUntil is refreshed on every seed run.
const now = new Date();
const windowMinutes = 5;
const windowStart = new Date(Math.floor(now.getTime() / (windowMinutes * 60_000)) * windowMinutes * 60_000);
await db.automationTriggerMeter.upsert({
where: { id: `demo-auto-meter-${ruleSeed.key}` },
create: {
id: `demo-auto-meter-${ruleSeed.key}`,
tenantId,
triggerKey: ruleSeed.triggerKey,
windowStart,
windowMinutes,
count: 2000,
pausedUntil: new Date(now.getTime() + 60 * 60_000),
anomalyText: ruleSeed.anomaly.anomalyText,
},
update: {
windowStart,
count: 2000,
pausedUntil: new Date(now.getTime() + 60 * 60_000),
anomalyText: ruleSeed.anomaly.anomalyText,
},
});
}
for (const [executionIndex, executionSeed] of ruleSeed.executions.entries()) {
const executionId = `demo-auto-exec-${ruleSeed.key}-${executionSeed.key}`;
const createdAt = demoDate(-executionIndex, 9 + executionIndex, 15);
const isOpenEnded = executionSeed.status === "running" || executionSeed.status === "paused";
await db.automationExecution.upsert({
where: { id: executionId },
create: {
id: executionId,
tenantId,
ruleId,
triggerKey: ruleSeed.triggerKey,
triggerPayload: { source: "hivegrid-demo", executionKey: executionSeed.key },
status: executionSeed.status,
dryRun: executionSeed.dryRun,
idempotencyKey: `demo:${ruleSeed.key}:${executionSeed.key}`,
summaryText: executionSeed.summaryText,
errorText: executionSeed.errorText ?? null,
queuedAt: createdAt,
startedAt: createdAt,
endedAt: isOpenEnded ? null : new Date(createdAt.getTime() + 42_000),
durationMs: isOpenEnded ? null : 42_000,
createdByUserId: ownerUserId,
isDemoData: true,
createdAt,
},
update: {
triggerPayload: { source: "hivegrid-demo", executionKey: executionSeed.key },
status: executionSeed.status,
dryRun: executionSeed.dryRun,
summaryText: executionSeed.summaryText,
errorText: executionSeed.errorText ?? null,
queuedAt: createdAt,
startedAt: createdAt,
endedAt: isOpenEnded ? null : new Date(createdAt.getTime() + 42_000),
durationMs: isOpenEnded ? null : 42_000,
isDemoData: true,
createdAt,
},
});
for (const [stepIndex, step] of ruleSeed.steps.entries()) {
const ruleStepId = stepIdByKey.get(step.key);
if (!ruleStepId) continue;
const lastStep = stepIndex === ruleSeed.steps.length - 1;
const failedStep = executionSeed.status === "failed" && lastStep;
const stepStatus =
executionSeed.status === "skipped"
? "skipped"
: executionSeed.status === "paused"
? "queued"
: failedStep
? "failed"
: executionSeed.status === "running" && lastStep
? "running"
: "success";
const stepData = {
ruleStepId,
stepKind: step.kind,
nodeType: step.nodeType,
status: stepStatus,
input: step.input ?? { source: "hivegrid-demo" },
output: failedStep || stepStatus === "queued" ? {} : (step.output ?? { ok: true }),
summaryText: failedStep ? (executionSeed.errorText ?? "Demo-Schritt fehlgeschlagen") : step.summaryText,
errorText: failedStep ? (executionSeed.errorText ?? "Demo-Schritt fehlgeschlagen") : null,
startedAt: createdAt,
endedAt: failedStep ? new Date(createdAt.getTime() + 30_000) : new Date(createdAt.getTime() + 20_000 + stepIndex * 5_000),
durationMs: failedStep ? 30_000 : 20_000 + stepIndex * 5_000,
sortOrder: stepIndex,
} as const;
await db.automationStepExecution.upsert({
where: { id: `demo-auto-stepexec-${ruleSeed.key}-${executionSeed.key}-${step.key}` },
create: {
id: `demo-auto-stepexec-${ruleSeed.key}-${executionSeed.key}-${step.key}`,
tenantId,
executionId,
stepKey: step.key,
...stepData,
},
update: stepData,
});
}
}
}
}
async function logCounts(db: DbClient, tenantId: string) {
const [
kontakte,
leads,
forms,
formSubmissions,
bookingPages,
appointments,
calendarEvents,
automations,
automationExecutions,
projekte,
tasks,
rechnungen,
apiKeys,
webhooks,
notifications,
activities,
pipelines,
] = await Promise.all([
db.kontakt.count({ where: { tenantId } }),
db.inboxLead.count({ where: { tenantId } }),
db.form.count({ where: { tenantId } }),
db.formSubmission.count({ where: { tenantId } }),
db.bookingPage.count({ where: { tenantId } }),
db.appointment.count({ where: { tenantId } }),
db.calendarEvent.count({ where: { tenantId } }),
db.automationRule.count({ where: { tenantId } }),
db.automationExecution.count({ where: { tenantId } }),
db.projekt.count({ where: { tenantId } }),
db.task.count({ where: { tenantId } }),
db.rechnung.count({ where: { tenantId } }),
db.apiKey.count({ where: { tenantId } }),
db.publicIncomingWebhookEndpoint.count({ where: { tenantId } }),
db.notificationDelivery.count({ where: { tenantId } }),
db.activity.count({ where: { tenantId } }),
db.pipeline.count({ where: { tenantId } }),
]);
process.stdout.write(
`Demo tenant counts — Kontakte: ${kontakte}, Leads: ${leads}, Forms: ${forms}, FormSubmissions: ${formSubmissions}, ` +
`BookingPages: ${bookingPages}, Appointments: ${appointments}, CalendarEvents: ${calendarEvents}, Automations: ${automations}, ` +
`AutomationExecutions: ${automationExecutions}, Projekte: ${projekte}, Tasks: ${tasks}, ` +
`Rechnungen: ${rechnungen}, ApiKeys: ${apiKeys}, Webhooks: ${webhooks}, Notifications: ${notifications}, ` +
`Activities: ${activities}, Pipelines: ${pipelines}\n`,
);
}
export async function seedHivegridDemo(env: EnvRecord = process.env) {
assertCanRunDemoSeed(env);
const db = getDbClient();
try {
const { tenant, userIdByKey } = await seedTenantAndUsers(db);
const ownerUserId = userIdByKey.get("owner");
if (!ownerUserId) {
throw new Error("Demo owner user was not created.");
}
await seedFeaturesAndSubscription(db, tenant.id);
const kontaktIdByKey = await seedContacts(db, tenant.id, ownerUserId);
const { pipelineIdByKey, stageIdByKey } = await seedPipelines(db, tenant.id, ownerUserId, userIdByKey);
const projektIdByKey = await seedProjects(db, tenant.id, ownerUserId, userIdByKey, pipelineIdByKey, stageIdByKey, kontaktIdByKey);
await seedProjectDetailAndTemplate(db, tenant.id, ownerUserId, userIdByKey, pipelineIdByKey, stageIdByKey, projektIdByKey);
await seedProjectTags(db, tenant.id, projektIdByKey);
const leadIdByKey = await seedLeads(db, tenant.id, ownerUserId);
await seedForms(db, tenant.id, ownerUserId, leadIdByKey);
await seedTasks(db, tenant.id, ownerUserId, userIdByKey, projektIdByKey, kontaktIdByKey);
await seedInvoices(db, tenant.id, ownerUserId, projektIdByKey);
await seedNotifications(db, tenant.id, ownerUserId);
await seedActivities(db, tenant.id, ownerUserId, kontaktIdByKey, projektIdByKey, leadIdByKey);
await seedApiKeyAndWebhook(db, tenant.id, ownerUserId);
await seedBookingAndCalendar(db, tenant.id, ownerUserId, userIdByKey, kontaktIdByKey);
await seedAutomations(db, tenant.id, ownerUserId);
await logCounts(db, tenant.id);
return { tenantId: tenant.id, tenantSlug: tenant.slug };
} finally {
await db.$disconnect();
}
}
const isDirectExecution = process.argv[1]?.endsWith("seed-hivegrid-demo.ts") || process.argv[1]?.endsWith("seed-hivegrid-demo.js");
if (isDirectExecution) {
seedHivegridDemo()
.then(({ tenantSlug }) => {
process.stdout.write(`HiveGrid demo tenant "${tenantSlug}" seeded.\n`);
process.stdout.write(`Login: ${HIVEGRID_DEMO_OWNER_EMAIL} / ${HIVEGRID_DEMO_PASSWORD} at http://localhost:3000/${tenantSlug}/dashboard\n`);
})
.catch((error) => {
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
process.exitCode = 1;
});
}