import { CatalogError, foundationErrors } from "@hivegrid/foundation"; import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server"; import { hasExactShkFirstSteps, SHK_FIRST_STEPS, SHK_FIRST_STEPS_CHECKLIST_CODE, SHK_FIRST_STEPS_CHECKLIST_ID, } from "~/domain/tenant-bootstrap/tenantBootstrap.constants"; import { db } from "~/utils/db.server"; import { ensureDefaultSalesPipeline } from "~/utils/integrations/projects/projectService.server"; const SHK_DEMO_TEMPLATE_CODE = "shk-demo-v1"; const checklistSteps = [ { ...SHK_FIRST_STEPS[0], titleKey: "onboarding.firstSteps.profile", href: "settings/profile" }, { ...SHK_FIRST_STEPS[1], titleKey: "onboarding.firstSteps.contacts", href: "contacts" }, { ...SHK_FIRST_STEPS[2], titleKey: "onboarding.firstSteps.projects", href: "projects" }, { ...SHK_FIRST_STEPS[3], titleKey: "onboarding.firstSteps.billing", href: "settings/billing" }, ] as const; const TEAM_CHECKLIST_ITEM = { id: "shk-first-steps-team-detection-v1", block: "team", titleKey: "onboarding.firstSteps.team", href: "settings/team/members/new", canComplete: false, } as const; type DemoEntityMap = Record; type FirstStepsBlock = (typeof checklistSteps)[number]["block"] | typeof TEAM_CHECKLIST_ITEM.block; type FirstStepsCatalogStep = { id: string; order: number; block: string }; type ResolvedFirstStepsSession = { id: string; status: string; stepIds: string[]; }; export async function getFirstStepsChecklist(input: { tenantId: string; userId: string }) { return await withChecklistRlsContext(input, () => getFirstStepsChecklistInContext(input)); } async function getFirstStepsChecklistInContext(input: { tenantId: string; userId: string }) { const session = await findFirstStepsSession(input); if (!session) { return emptyFirstStepsChecklist(); } const rows = await db.onboardingSessionStep.findMany({ where: { onboardingSessionId: session.id, stepId: { in: session.stepIds }, }, include: { step: true }, orderBy: { step: { order: "asc" } }, }); if (rows.length === 0) { return emptyFirstStepsChecklist(); } const autoCompletedBlocks = await detectFirstStepsCompletion(input); const dismissed = session.status === "dismissed"; const items: Array<{ id: string; block: string; titleKey: string; href: string; completed: boolean; hidden: boolean; canComplete?: boolean; }> = rows.flatMap((row) => { const config = checklistSteps.find((step) => step.order === row.step.order && step.block === row.step.block); if (!config) return []; const completed = Boolean(row.completedAt) || autoCompletedBlocks.has(row.step.block as FirstStepsBlock); return [ { id: row.id, block: row.step.block, titleKey: config.titleKey, href: config.href, completed, hidden: dismissed, }, ]; }); if (items.length !== rows.length) return emptyFirstStepsChecklist(); items.splice(1, 0, { ...TEAM_CHECKLIST_ITEM, completed: autoCompletedBlocks.has(TEAM_CHECKLIST_ITEM.block), hidden: dismissed, }); const completedCount = items.filter((item) => item.completed).length; return { id: session.id, status: !dismissed && items.length > 0 && completedCount === items.length ? "completed" : session.status, dismissed, completedCount, totalCount: items.length, percentComplete: items.length > 0 ? Math.round((completedCount / items.length) * 100) : 0, items, }; } function emptyFirstStepsChecklist() { return { id: "", status: "active", dismissed: false, completedCount: 0, totalCount: 0, percentComplete: 0, items: [], }; } async function detectFirstStepsCompletion(input: { tenantId: string; userId: string }): Promise> { const now = new Date(); const [user, memberCount, pendingInvitationCount, contactCount, projectCount, subscription] = await Promise.all([ db.user.findUnique({ where: { id: input.userId }, select: { firstName: true, lastName: true, email: true } }), db.tenantUser.count({ where: { tenantId: input.tenantId } }), db.tenantUserInvitation.count({ where: { tenantId: input.tenantId, pending: true, status: "pending", revokedAt: null, OR: [{ expiresAt: null }, { expiresAt: { gt: now } }], }, }), db.kontakt.count({ where: { tenantId: input.tenantId, isDemoData: false } }), db.projekt.count({ where: { tenantId: input.tenantId, isDemoData: false } }), db.tenantSubscription.findUnique({ where: { tenantId: input.tenantId }, select: { status: true } }), ]); const completed = new Set(); if (user?.firstName && user.lastName && user.email) completed.add("profile"); if (memberCount > 1 || pendingInvitationCount > 0) completed.add("team"); if (contactCount > 0) completed.add("contacts"); if (projectCount > 0) completed.add("projects"); if (subscription?.status === "trial" || subscription?.status === "active") completed.add("billing"); return completed; } export async function updateFirstStepsChecklist(input: { tenantId: string; userId: string; sessionStepId?: string | null; action: "complete" | "hide" | "show"; }) { return await withChecklistRlsContext(input, () => updateFirstStepsChecklistInContext(input)); } async function updateFirstStepsChecklistInContext(input: { tenantId: string; userId: string; sessionStepId?: string | null; action: "complete" | "hide" | "show"; }) { const session = await findFirstStepsSession(input); if (!session) { throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-session" }); } if (input.action === "hide") { return await db.onboardingSession.update({ where: { id: session.id }, data: { status: "dismissed", dismissedAt: new Date() }, }); } if (input.action === "show") { return await db.onboardingSession.update({ where: { id: session.id }, data: { status: "active", dismissedAt: null }, }); } if (!input.sessionStepId) { throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-step" }); } const result = await db.onboardingSessionStep.updateMany({ where: { id: input.sessionStepId, onboardingSessionId: session.id, stepId: { in: session.stepIds }, }, data: { completedAt: new Date() }, }); if (result.count !== 1) { throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-step" }); } return result; } async function findFirstStepsSession(input: { tenantId: string; userId: string }): Promise { const canonicalCatalog = await findCanonicalFirstStepsCatalog(); if (canonicalCatalog) { const canonicalSession = await db.onboardingSession.findUnique({ where: { onboardingId_userId_tenantId: { onboardingId: canonicalCatalog.id, userId: input.userId, tenantId: input.tenantId, }, }, }); if (canonicalSession) { return { id: canonicalSession.id, status: canonicalSession.status, stepIds: SHK_FIRST_STEPS.map((step) => step.id), }; } } const legacySession = await db.onboardingSession.findFirst({ where: { userId: input.userId, tenantId: input.tenantId, onboardingId: { not: SHK_FIRST_STEPS_CHECKLIST_ID }, onboarding: { title: SHK_FIRST_STEPS_CHECKLIST_CODE }, }, select: { id: true, status: true, onboarding: { select: { steps: { select: { id: true, order: true, block: true } }, }, }, }, orderBy: { createdAt: "asc" }, }); if (!legacySession || !hasExactLegacyFirstSteps(legacySession.onboarding.steps)) { return null; } return { id: legacySession.id, status: legacySession.status, stepIds: legacySession.onboarding.steps.map((step) => step.id), }; } function hasExactLegacyFirstSteps(steps: ReadonlyArray): boolean { return ( steps.length === checklistSteps.length && checklistSteps.every((expected) => steps.some((actual) => actual.order === expected.order && actual.block === expected.block)) ); } async function findCanonicalFirstStepsCatalog() { const onboarding = await db.onboarding.findUnique({ where: { id: SHK_FIRST_STEPS_CHECKLIST_ID }, select: { id: true, title: true, type: true, realtime: true, active: true, canBeDismissed: true, height: true, steps: { select: { id: true, order: true, block: true } }, }, }); if ( !onboarding || onboarding.title !== SHK_FIRST_STEPS_CHECKLIST_CODE || onboarding.type !== "page" || onboarding.realtime !== false || !onboarding.active || onboarding.canBeDismissed !== true || onboarding.height !== null || !hasExactShkFirstSteps(onboarding.steps) ) { return null; } return onboarding; } function withChecklistRlsContext(input: { tenantId: string; userId: string }, operation: () => T): T { const current = getRlsExecutionContext(); if (current?.userId && current.userId !== input.userId) { throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-session" }); } const bindTarget = () => runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, operation); if (current?.userId === input.userId && (current.transaction || (current.tenantId && current.tenantId !== input.tenantId))) { return runWithIsolatedUserRlsContext(input.userId, bindTarget); } return bindTarget(); } export async function getDemoDataStatus(tenantId: string) { return await db.onboardingDemoProvisioning.findFirst({ where: { tenantId, templateCode: SHK_DEMO_TEMPLATE_CODE, status: "active", deletedAt: null }, orderBy: { createdAt: "desc" }, }); } export async function provisionShkDemoData(input: { tenantId: string; userId: string }) { const existing = await getDemoDataStatus(input.tenantId); if (existing) { return existing; } const { pipeline, firstOpenStage } = await ensureDefaultSalesPipeline({ tenantId: input.tenantId, userId: input.userId }); const contacts = await Promise.all( ["Muster GmbH", "Solar Schmidt", "Elektro Weber", "Hausverwaltung Nord", "Ada Lovelace"].map((name, index) => db.kontakt.create({ data: { tenantId: input.tenantId, createdByUserId: input.userId, kontaktTyp: index === 4 ? "privatperson" : "organisation", kontaktStatus: index < 2 ? "kunde" : "kontakt", orgName: index === 4 ? null : name, vorname: index === 4 ? "Ada" : null, nachname: index === 4 ? "Lovelace" : null, primaerEmail: `demo-${index + 1}@example.invalid`, isDemoData: true, zustaendigerUserId: input.userId, }, }) ) ); const projects = await Promise.all( ["Heizungstausch Musterstraße", "PV-Angebot Nord", "Wartung Bestandshaus"].map((name, index) => db.projekt.create({ data: { tenantId: input.tenantId, createdByUserId: input.userId, projektNummer: `DEMO-${String(index + 1).padStart(4, "0")}`, projektname: name, projekttyp: index === 2 ? "auftrag" : "deal", quelle: "demo", pipelineId: pipeline.id, stageId: firstOpenStage.id, zustaendigePersonId: input.userId, isDemoData: true, }, }) ) ); const tasks = await Promise.all( ["Demo-Kontakt prüfen", "Demo-Projekt kalkulieren", "Demo-Angebot versenden"].map((title, index) => db.task.create({ data: { tenantId: input.tenantId, createdByUserId: input.userId, assignedToUserId: input.userId, title, linkedEntityType: "project", linkedEntityId: projects[index % projects.length].id, isDemoData: true, }, }) ) ); const entitiesCreated: DemoEntityMap = { kontakt: contacts.map((item) => item.id), projekt: projects.map((item) => item.id), task: tasks.map((item) => item.id), }; return await db.onboardingDemoProvisioning.create({ data: { tenantId: input.tenantId, createdByUserId: input.userId, templateCode: SHK_DEMO_TEMPLATE_CODE, entitiesCreated, removableUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), }, }); } export async function deleteShkDemoData(input: { tenantId: string; provisioningId: string }) { const provisioning = await db.onboardingDemoProvisioning.findFirst({ where: { id: input.provisioningId, tenantId: input.tenantId, status: "active", deletedAt: null }, }); if (!provisioning) { return null; } const entities = provisioning.entitiesCreated as DemoEntityMap; await db.$transaction([ db.task.deleteMany({ where: { tenantId: input.tenantId, id: { in: entities.task ?? [] }, isDemoData: true } }), db.projekt.deleteMany({ where: { tenantId: input.tenantId, id: { in: entities.projekt ?? [] }, isDemoData: true } }), db.kontakt.deleteMany({ where: { tenantId: input.tenantId, id: { in: entities.kontakt ?? [] }, isDemoData: true } }), db.onboardingDemoProvisioning.update({ where: { id: provisioning.id }, data: { status: "deleted", deletedAt: new Date() }, }), ]); return provisioning; }