283 lines
11 KiB
TypeScript
283 lines
11 KiB
TypeScript
import { db } from "~/utils/db.server";
|
|
import { seedShkRolesForTenant } from "../shkRoles.server";
|
|
import { seedShkFormTemplates, type FormTemplateTranslationFn } from "~/modules/forms/services/shkFormTemplates.server";
|
|
import { seedShkCustomFieldTemplate } from "~/utils/integrations/crm/customFieldService.server";
|
|
import { ensureDefaultAcceptanceFormTemplate, ensureDefaultProjectTemplate } from "~/utils/integrations/projects/auftragService.server";
|
|
import { ensureDefaultSalesPipeline } from "~/utils/integrations/projects/projectService.server";
|
|
|
|
const SHK_CHECKLIST_CODE = "shk-first-steps";
|
|
const SHK_DEMO_TEMPLATE_CODE = "shk-demo-v1";
|
|
|
|
const checklistSteps = [
|
|
{ order: 10, block: "profile", titleKey: "onboarding.firstSteps.profile", href: "settings/profile" },
|
|
{ order: 20, block: "contacts", titleKey: "onboarding.firstSteps.contacts", href: "contacts" },
|
|
{ order: 30, block: "projects", titleKey: "onboarding.firstSteps.projects", href: "projects" },
|
|
{ order: 40, block: "billing", titleKey: "onboarding.firstSteps.billing", href: "settings/subscription" },
|
|
] as const;
|
|
|
|
type DemoEntityMap = Record<string, string[]>;
|
|
type FirstStepsBlock = (typeof checklistSteps)[number]["block"];
|
|
|
|
async function getOrCreateChecklistOnboarding() {
|
|
const existing = await db.onboarding.findFirst({ where: { title: SHK_CHECKLIST_CODE } });
|
|
if (existing) {
|
|
return existing;
|
|
}
|
|
return await db.onboarding.create({
|
|
data: {
|
|
title: SHK_CHECKLIST_CODE,
|
|
type: "page",
|
|
active: true,
|
|
canBeDismissed: true,
|
|
steps: {
|
|
create: checklistSteps.map((step) => ({
|
|
order: step.order,
|
|
block: step.block,
|
|
})),
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function provisionShkTenantDefaults(input: { tenantId: string; userId: string; t?: FormTemplateTranslationFn }) {
|
|
await seedShkRolesForTenant(input.tenantId);
|
|
await Promise.all([
|
|
ensureDefaultSalesPipeline({ tenantId: input.tenantId, userId: input.userId }),
|
|
seedShkCustomFieldTemplate({ tenantId: input.tenantId }),
|
|
ensureDefaultAcceptanceFormTemplate({ tenantId: input.tenantId, userId: input.userId }),
|
|
ensureDefaultProjectTemplate({ tenantId: input.tenantId }),
|
|
input.t ? seedShkFormTemplates({ tenantId: input.tenantId, userId: input.userId, t: input.t }) : Promise.resolve({ upserted: 0 }),
|
|
]);
|
|
|
|
const onboarding = await getOrCreateChecklistOnboarding();
|
|
const session = await db.onboardingSession.upsert({
|
|
where: {
|
|
onboardingId_userId_tenantId: {
|
|
onboardingId: onboarding.id,
|
|
userId: input.userId,
|
|
tenantId: input.tenantId,
|
|
},
|
|
},
|
|
create: {
|
|
onboardingId: onboarding.id,
|
|
userId: input.userId,
|
|
tenantId: input.tenantId,
|
|
status: "active",
|
|
startedAt: new Date(),
|
|
},
|
|
update: {},
|
|
});
|
|
|
|
const steps = await db.onboardingStep.findMany({ where: { onboardingId: onboarding.id } });
|
|
const existingSessionSteps = await db.onboardingSessionStep.findMany({
|
|
where: { onboardingSessionId: session.id },
|
|
select: { stepId: true },
|
|
});
|
|
const existingStepIds = new Set(existingSessionSteps.map((step) => step.stepId));
|
|
await db.onboardingSessionStep.createMany({
|
|
data: steps
|
|
.filter((step) => !existingStepIds.has(step.id))
|
|
.map((step) => ({
|
|
onboardingSessionId: session.id,
|
|
stepId: step.id,
|
|
})),
|
|
skipDuplicates: true,
|
|
});
|
|
|
|
return session;
|
|
}
|
|
|
|
export async function getFirstStepsChecklist(input: { tenantId: string; userId: string }) {
|
|
const session = await provisionShkTenantDefaults(input);
|
|
const rows = await db.onboardingSessionStep.findMany({
|
|
where: { onboardingSessionId: session.id },
|
|
include: { step: true },
|
|
orderBy: { step: { order: "asc" } },
|
|
});
|
|
const autoCompletedBlocks = await detectFirstStepsCompletion(input);
|
|
const now = new Date();
|
|
const autoCompletedRows = rows.filter((row) => !row.completedAt && autoCompletedBlocks.has(row.step.block as FirstStepsBlock));
|
|
if (autoCompletedRows.length > 0) {
|
|
await db.onboardingSessionStep.updateMany({
|
|
where: { id: { in: autoCompletedRows.map((row) => row.id) }, onboardingSessionId: session.id },
|
|
data: { completedAt: now },
|
|
});
|
|
}
|
|
|
|
const dismissed = session.status === "dismissed";
|
|
const items = rows.map((row) => {
|
|
const config = checklistSteps.find((step) => step.block === row.step.block);
|
|
const completed = Boolean(row.completedAt) || autoCompletedBlocks.has(row.step.block as FirstStepsBlock);
|
|
return {
|
|
id: row.id,
|
|
block: row.step.block,
|
|
titleKey: config?.titleKey ?? "onboarding.firstSteps.item",
|
|
href: config?.href ?? "dashboard",
|
|
completed,
|
|
hidden: dismissed,
|
|
};
|
|
});
|
|
const completedCount = items.filter((item) => item.completed).length;
|
|
if (!dismissed && items.length > 0 && completedCount === items.length && session.status !== "completed") {
|
|
await db.onboardingSession.update({
|
|
where: { id: session.id },
|
|
data: { status: "completed", completedAt: now },
|
|
});
|
|
}
|
|
|
|
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,
|
|
};
|
|
}
|
|
|
|
async function detectFirstStepsCompletion(input: { tenantId: string; userId: string }): Promise<Set<FirstStepsBlock>> {
|
|
const [user, contactCount, projectCount, subscription] = await Promise.all([
|
|
db.user.findUnique({ where: { id: input.userId }, select: { firstName: true, lastName: true, email: true } }),
|
|
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<FirstStepsBlock>();
|
|
if (user?.firstName && user.lastName && user.email) completed.add("profile");
|
|
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";
|
|
}) {
|
|
const session = await provisionShkTenantDefaults(input);
|
|
if (input.action === "hide") {
|
|
return await db.onboardingSession.update({
|
|
where: { id: session.id },
|
|
data: { status: "dismissed", dismissedAt: new Date() },
|
|
});
|
|
}
|
|
if (!input.sessionStepId) {
|
|
throw new Error("Missing checklist step id");
|
|
}
|
|
return await db.onboardingSessionStep.updateMany({
|
|
where: {
|
|
id: input.sessionStepId,
|
|
onboardingSession: {
|
|
tenantId: input.tenantId,
|
|
userId: input.userId,
|
|
},
|
|
},
|
|
data: { completedAt: new Date() },
|
|
});
|
|
}
|
|
|
|
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;
|
|
}
|