// Ops seed — CRM + Lead-Inbox demo data (R-P6/R-P7), idempotent, DEMO-TENANTS ONLY. // // Purpose: populate typed CRM contacts/organisations (+ tags, custom fields, a // relation, address) and a handful of inbox leads across sources/statuses so the // R-P6/R-P7 interim-UI screens render with real data on staging. Contacts are // seeded VISIBLE (isDemoData=false): the CRM contact list hides isDemoData=true // rows by default (crmService `demo=show` toggle), so demo contacts would never // show. Demo tenants are throwaway, so we favour a populated default view; a // re-run repairs contacts an earlier seed created hidden. Custom fields / lead // sources / leads keep isDemoData=true — their lists don't filter demo rows. // // No encryption needed (unlike the HR seed) — CRM/Lead rows are plaintext. Prisma // writes to RLS-protected tables go through a transaction that sets the tenant GUC // (mirrors withTenantRLS). Idempotent: keyed on natural/unique keys, upserts where // a unique constraint exists, findFirst-guard otherwise. // // Run inside the staging web container (has DATABASE_URL), via tsx: // docker exec sh -lc 'cd /myapp && node_modules/.bin/tsx scripts/ops/seed-crm-leads-demo.mts' // Flags: --dry-run (no writes, report only). import { getDbClient } from "@hivegrid/db/client.server"; const MANAGED_STAGING_TENANT_SLUG = "demo-pro-crm"; const DEMO_SLUGS = ["demo-starter-crm", "demo-business-crm"]; const DRY = process.argv.includes("--dry-run"); const db = getDbClient() as any; /** Run a callback inside a tenant-scoped RLS transaction (mirrors withTenantRLS). */ async function rls(tenantId: string, cb: (tx: any) => Promise): Promise { return db.$transaction(async (tx: any) => { await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`; return cb(tx); }); } type Member = { userId: string; email: string }; function pickMembers(members: Member[]) { const byEmail = (e: string) => members.find((m) => m.email.toLowerCase() === e); const admin = byEmail("staging-admin@hivegrid.de") ?? members[0]; const john = byEmail("john.doe@company.com") ?? members[1] ?? admin; const luna = byEmail("luna.davis@company.com") ?? members[2] ?? admin; return { admin, john, luna }; } async function seedTenant(t: { id: string; slug: string }) { if (t.slug === MANAGED_STAGING_TENANT_SLUG) { throw new Error(`${MANAGED_STAGING_TENANT_SLUG} is owned by the comprehensive normal-data seed and must not receive legacy demo rows`); } const tenantId = t.id; const tus = await db.tenantUser.findMany({ where: { tenantId }, select: { userId: true } }); const users: any[] = await db.user.findMany({ where: { id: { in: tus.map((x: any) => x.userId) } }, select: { id: true, email: true } }); const members: Member[] = users.map((u) => ({ userId: u.id, email: u.email })); if (members.length === 0) { console.log(`[${t.slug}] no members — skipped`); return; } const { admin, john, luna } = pickMembers(members); const owner = admin.userId; const summary: string[] = []; await rls(tenantId, async (tx) => { // --- Tags (unique tenantId+name) --- async function ensureTag(name: string, farbe: string): Promise { if (DRY) { const ex = await tx.tag.findFirst({ where: { tenantId, name }, select: { id: true } }); summary.push(`${ex ? "=" : "+"}tag ${name}`); return ex?.id ?? "dry"; } const tag = await tx.tag.upsert({ where: { tenantId_name: { tenantId, name } }, update: { farbe }, create: { tenantId, name, farbe }, select: { id: true } }); summary.push(`~tag ${name}`); return tag.id; } const tagVip = await ensureTag("VIP", "#e11d48"); const tagBestand = await ensureTag("Bestandskunde", "#0ea5e9"); // --- Custom field definitions (kontakt; unique tenantId+entityType+key) --- async function ensureCfDef(key: string, label: string, datentyp: string): Promise { if (DRY) { const ex = await tx.customFieldDefinition.findFirst({ where: { tenantId, entityType: "kontakt", key }, select: { id: true } }); summary.push(`${ex ? "=" : "+"}cfDef ${key}`); return ex?.id ?? "dry"; } const def = await tx.customFieldDefinition.upsert({ where: { tenantId_entityType_key: { tenantId, entityType: "kontakt", key } }, update: { label, datentyp }, create: { tenantId, entityType: "kontakt", key, label, datentyp, isDemoData: true }, select: { id: true }, }); summary.push(`~cfDef ${key}`); return def.id; } const cfBudget = await ensureCfDef("budget", "Budget", "waehrung"); await ensureCfDef("interne_quelle", "Interne Quelle", "text"); // --- Shared demo address --- let adresseId: string | null = null; if (!DRY) { const existing = await tx.adresse.findFirst({ where: { tenantId, strasse: "Torstraße", ort: "Berlin" }, select: { id: true } }); adresseId = existing?.id ?? (await tx.adresse.create({ data: { tenantId, strasse: "Torstraße", hausnummer: "1", plz: "10119", ort: "Berlin", land: "DE" }, select: { id: true } })).id; } async function assignTag(tagId: string, kontaktId: string) { if (DRY || tagId === "dry") return; await tx.tagAssignment.upsert({ where: { tagId_entityId_entityType: { tagId, entityId: kontaktId, entityType: "kontakt" } }, update: {}, create: { tenantId, tagId, entityId: kontaktId, entityType: "kontakt" }, }); } // --- Contacts (persons + orgs), idempotent by tenantId+primaerEmail+isDemoData --- async function ensureKontakt(p: { kontaktTyp: "privatperson" | "organisation"; vorname?: string; nachname?: string; orgName?: string; orgMerkmal?: string; kontaktStatus: string; email: string; telefon: string; ownerUserId: string; tags?: string[]; withAddress?: boolean; }): Promise { const label = p.orgName ?? `${p.vorname ?? ""} ${p.nachname ?? ""}`.trim(); // Match by email only (demo tenants use unique @example.com addresses). This // also repairs rows an earlier seed created hidden (isDemoData:true) — the CRM // contact list filters those out by default, so demo contacts never showed. const existing = await tx.kontakt.findFirst({ where: { tenantId, primaerEmail: p.email }, select: { id: true, isDemoData: true } }); if (existing) { if (!DRY && existing.isDemoData) await tx.kontakt.update({ where: { id: existing.id }, data: { isDemoData: false } }); summary.push(`${existing.isDemoData ? "~" : "="}kontakt ${label}${existing.isDemoData ? " (made visible)" : ""}`); if (!DRY) for (const tg of p.tags ?? []) await assignTag(tg, existing.id); return existing.id; } if (DRY) { summary.push(`+kontakt ${label}`); return "dry"; } const k = await tx.kontakt.create({ data: { tenantId, createdByUserId: owner, zustaendigerUserId: p.ownerUserId, kontaktTyp: p.kontaktTyp, kontaktStatus: p.kontaktStatus, vorname: p.vorname ?? null, nachname: p.nachname ?? null, orgName: p.orgName ?? null, orgMerkmal: p.orgMerkmal ?? null, primaerEmail: p.email, primaerTelefon: p.telefon, adresseId: p.withAddress ? adresseId : null, isDemoData: false, }, select: { id: true }, }); await tx.kontaktEmail.create({ data: { tenantId, kontaktId: k.id, email: p.email, primaer: true } }); await tx.kontaktTelefon.create({ data: { tenantId, kontaktId: k.id, telefon: p.telefon, primaer: true } }); for (const tg of p.tags ?? []) await assignTag(tg, k.id); summary.push(`+kontakt ${label}`); return k.id; } const anna = await ensureKontakt({ kontaktTyp: "privatperson", vorname: "Anna", nachname: "Becker", kontaktStatus: "kunde", email: "anna.becker@example.com", telefon: "+49 30 1110001", ownerUserId: john.userId, tags: [tagVip], withAddress: true }); await ensureKontakt({ kontaktTyp: "privatperson", vorname: "Ben", nachname: "Krüger", kontaktStatus: "kontakt", email: "ben.krueger@example.com", telefon: "+49 30 1110002", ownerUserId: luna.userId }); await ensureKontakt({ kontaktTyp: "privatperson", vorname: "Clara", nachname: "Weiss", kontaktStatus: "bestandskunde", email: "clara.weiss@example.com", telefon: "+49 30 1110003", ownerUserId: owner, tags: [tagBestand] }); const musterbau = await ensureKontakt({ kontaktTyp: "organisation", orgName: "Musterbau GmbH", orgMerkmal: "gmbh", kontaktStatus: "kunde", email: "kontakt@musterbau.example.com", telefon: "+49 30 2220001", ownerUserId: owner, tags: [tagVip], withAddress: true }); await ensureKontakt({ kontaktTyp: "organisation", orgName: "Stadtwerke Beispiel", orgMerkmal: "oeffentliche_einrichtung", kontaktStatus: "kontakt", email: "info@stadtwerke.example.com", telefon: "+49 30 2220002", ownerUserId: john.userId }); // --- Relation: Anna is the primary contact of Musterbau GmbH --- if (!DRY && anna !== "dry" && musterbau !== "dry") { await tx.kontaktRelation.upsert({ where: { vonKontaktId_zuKontaktId_rolle: { vonKontaktId: musterbau, zuKontaktId: anna, rolle: "hauptkontakt" } }, update: {}, create: { tenantId, vonKontaktId: musterbau, zuKontaktId: anna, rolle: "hauptkontakt", kontext: "Ansprechpartnerin" }, }); summary.push("~relation Musterbau→Anna"); } // --- Custom field value: budget on Musterbau GmbH --- if (!DRY && cfBudget !== "dry" && musterbau !== "dry") { await tx.customFieldValue.upsert({ where: { definitionId_entityId: { definitionId: cfBudget, entityId: musterbau } }, update: { wert: 50000 }, create: { tenantId, definitionId: cfBudget, entityType: "kontakt", entityId: musterbau, wert: 50000 }, }); summary.push("~cfValue budget=50000"); } // --- Lead source (custom; unique tenantId+key) --- if (!DRY) { await tx.leadSource.upsert({ where: { tenantId_key: { tenantId, key: "landingpage" } }, update: { name: "Landingpage Herbst", displayLabel: "Landingpage Herbst" }, create: { tenantId, key: "landingpage", name: "Landingpage Herbst", displayLabel: "Landingpage Herbst", type: "custom", isDemoData: true }, }); summary.push("~leadSource landingpage"); } // --- Inbox leads across sources/statuses, idempotent by tenantId+email+isDemoData --- async function ensureLead(l: { quelle: string; status: string; freigabe: string; vorname?: string; nachname?: string; email?: string; telefon?: string; message?: string; spamScore: number; ownerUserId: string; markerEmail: string }) { const existing = await tx.inboxLead.findFirst({ where: { tenantId, email: l.markerEmail, isDemoData: true }, select: { id: true } }); if (existing) { summary.push(`=lead ${l.markerEmail}`); return; } if (DRY) { summary.push(`+lead ${l.markerEmail}`); return; } await tx.inboxLead.create({ data: { tenantId, createdByUserId: owner, zustaendigerUserId: l.ownerUserId, quelle: l.quelle, status: l.status, weiterverarbeitungFreigabe: l.freigabe, vorname: l.vorname ?? null, nachname: l.nachname ?? null, email: l.email ?? null, telefon: l.telefon ?? null, message: l.message ?? null, spamScore: l.spamScore, isQuarantined: l.spamScore >= 50 && l.status !== "spam", isDemoData: true, }, }); summary.push(`+lead ${l.markerEmail}`); } await ensureLead({ quelle: "form", status: "new", freigabe: "unklar", vorname: "Dora", nachname: "Lang", email: "dora.lang@example.com", telefon: "+49 30 3330001", message: "Anfrage zur Badsanierung, bitte um Rückruf.", spamScore: 5, ownerUserId: owner, markerEmail: "dora.lang@example.com" }); await ensureLead({ quelle: "email", status: "qualified", freigabe: "ja", vorname: "Erik", nachname: "Falk", email: "erik.falk@example.com", telefon: "+49 30 3330002", message: "Interesse an Wärmepumpe.", spamScore: 10, ownerUserId: john.userId, markerEmail: "erik.falk@example.com" }); await ensureLead({ quelle: "aircall", status: "new", freigabe: "unklar", telefon: "+49 30 3330003", email: "anruf.lead@example.com", message: "Eingehender Anruf, Notiz: Heizungstausch.", spamScore: 0, ownerUserId: luna.userId, markerEmail: "anruf.lead@example.com" }); await ensureLead({ quelle: "manual", status: "spam", freigabe: "nein", vorname: "Spammy", nachname: "Bot", email: "promo@spam.example.com", message: "Gewinnen Sie jetzt!!!", spamScore: 88, ownerUserId: owner, markerEmail: "promo@spam.example.com" }); return null; }); console.log(`\n[${t.slug}] (${tenantId})`); for (const line of summary) console.log(" " + line); } async function main() { const tenants = await db.tenant.findMany({ where: { slug: { in: DEMO_SLUGS } }, select: { id: true, slug: true } }); if (tenants.length === 0) { console.error("No demo tenants found — aborting (safety guard)."); process.exit(1); } console.log(`CRM/Lead demo seed — ${DRY ? "DRY RUN" : "WRITE"} — tenants: ${tenants.map((t: any) => t.slug).join(", ")}`); for (const t of tenants) await seedTenant(t); console.log("\nDone."); } main().then(() => process.exit(0)).catch((e) => { console.error("SEED-ERR", e); process.exit(1); });