462 lines
18 KiB
TypeScript
462 lines
18 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
db: {
|
|
onboarding: { findUnique: vi.fn() },
|
|
onboardingSession: { findFirst: vi.fn(), findUnique: vi.fn(), update: vi.fn() },
|
|
onboardingSessionStep: { findMany: vi.fn(), updateMany: vi.fn() },
|
|
user: { findUnique: vi.fn() },
|
|
tenantUser: { count: vi.fn() },
|
|
tenantUserInvitation: { count: vi.fn() },
|
|
kontakt: { count: vi.fn(), create: vi.fn() },
|
|
projekt: { count: vi.fn(), create: vi.fn() },
|
|
task: { create: vi.fn(), deleteMany: vi.fn() },
|
|
tenantSubscription: { findUnique: vi.fn() },
|
|
onboardingDemoProvisioning: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
|
|
$transaction: vi.fn(),
|
|
},
|
|
ensureDefaultSalesPipeline: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
|
|
vi.mock("~/utils/integrations/projects/projectService.server", () => ({ ensureDefaultSalesPipeline: mocks.ensureDefaultSalesPipeline }));
|
|
|
|
import { getFirstStepsChecklist, updateFirstStepsChecklist } from "./akP20OnboardingService";
|
|
import { SHK_FIRST_STEPS, SHK_FIRST_STEPS_CHECKLIST_CODE, SHK_FIRST_STEPS_CHECKLIST_ID } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
|
|
|
|
function canonicalCatalog() {
|
|
return {
|
|
id: SHK_FIRST_STEPS_CHECKLIST_ID,
|
|
title: SHK_FIRST_STEPS_CHECKLIST_CODE,
|
|
type: "page",
|
|
realtime: false,
|
|
active: true,
|
|
canBeDismissed: true,
|
|
height: null,
|
|
steps: SHK_FIRST_STEPS.map((step) => ({ ...step })),
|
|
};
|
|
}
|
|
|
|
function sessionStep(index: number, id = `session_step_${index + 1}`) {
|
|
return {
|
|
id,
|
|
completedAt: null,
|
|
step: { ...SHK_FIRST_STEPS[index]! },
|
|
};
|
|
}
|
|
|
|
function legacyCatalogSteps() {
|
|
return SHK_FIRST_STEPS.map((step, index) => ({ ...step, id: `legacy_step_${index + 1}` }));
|
|
}
|
|
|
|
function legacySession(status = "active") {
|
|
return {
|
|
id: "legacy_session_1",
|
|
status,
|
|
onboarding: { steps: legacyCatalogSteps() },
|
|
};
|
|
}
|
|
|
|
const mutationSpies = [mocks.db.onboardingSession.update, mocks.db.onboardingSessionStep.updateMany, mocks.ensureDefaultSalesPipeline];
|
|
|
|
function expectNoChecklistWrites() {
|
|
for (const mutation of mutationSpies) {
|
|
expect(mutation).not.toHaveBeenCalled();
|
|
}
|
|
}
|
|
|
|
describe("getFirstStepsChecklist read path", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(null);
|
|
mocks.db.onboardingSession.findFirst.mockResolvedValue(null);
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
|
|
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([]);
|
|
mocks.db.user.findUnique.mockResolvedValue(null);
|
|
mocks.db.tenantUser.count.mockResolvedValue(1);
|
|
mocks.db.tenantUserInvitation.count.mockResolvedValue(0);
|
|
mocks.db.kontakt.count.mockResolvedValue(0);
|
|
mocks.db.projekt.count.mockResolvedValue(0);
|
|
mocks.db.tenantSubscription.findUnique.mockResolvedValue(null);
|
|
});
|
|
|
|
it("returns an empty checklist without provisioning when no definition exists", async () => {
|
|
const checklist = await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
|
|
|
|
expect(checklist).toEqual({
|
|
id: "",
|
|
status: "active",
|
|
dismissed: false,
|
|
completedCount: 0,
|
|
totalCount: 0,
|
|
percentComplete: 0,
|
|
items: [],
|
|
});
|
|
expect(mocks.db.onboarding.findUnique).toHaveBeenCalledWith({
|
|
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 } },
|
|
},
|
|
});
|
|
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
|
|
expect(mocks.db.onboardingSession.findFirst).toHaveBeenCalledWith({
|
|
where: {
|
|
userId: "user_1",
|
|
tenantId: "tenant_1",
|
|
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" },
|
|
});
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("derives auto-completion in memory without persisting session or step updates", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1", status: "active" });
|
|
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([sessionStep(0), sessionStep(1)]);
|
|
mocks.db.user.findUnique.mockResolvedValue({ firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" });
|
|
mocks.db.kontakt.count.mockResolvedValue(1);
|
|
|
|
const checklist = await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
|
|
|
|
expect(checklist).toMatchObject({ id: "session_1", status: "active", completedCount: 2, totalCount: 3, percentComplete: 67 });
|
|
expect(checklist.items).toEqual([
|
|
expect.objectContaining({ id: "session_step_1", block: "profile", completed: true }),
|
|
expect.objectContaining({ id: "shk-first-steps-team-detection-v1", block: "team", completed: false, canComplete: false }),
|
|
expect.objectContaining({ id: "session_step_2", block: "contacts", completed: true }),
|
|
]);
|
|
expect(mocks.db.onboardingSessionStep.findMany).toHaveBeenCalledWith({
|
|
where: {
|
|
onboardingSessionId: "session_1",
|
|
stepId: { in: SHK_FIRST_STEPS.map((step) => step.id) },
|
|
},
|
|
include: { step: true },
|
|
orderBy: { step: { order: "asc" } },
|
|
});
|
|
expect(mocks.db.tenantUserInvitation.count).toHaveBeenCalledWith({
|
|
where: {
|
|
tenantId: "tenant_1",
|
|
pending: true,
|
|
status: "pending",
|
|
revokedAt: null,
|
|
OR: [{ expiresAt: null }, { expiresAt: { gt: expect.any(Date) } }],
|
|
},
|
|
});
|
|
expect(mocks.db.onboardingSession.findFirst).not.toHaveBeenCalled();
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("keeps an existing legacy checklist session readable without migrating it", async () => {
|
|
const legacySteps = legacyCatalogSteps();
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
|
|
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
|
|
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([
|
|
{ id: "legacy_session_step_1", completedAt: null, step: legacySteps[0] },
|
|
{ id: "legacy_session_step_2", completedAt: null, step: legacySteps[1] },
|
|
]);
|
|
mocks.db.user.findUnique.mockResolvedValue({ firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" });
|
|
|
|
const checklist = await getFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1" });
|
|
|
|
expect(checklist).toMatchObject({ id: "legacy_session_1", completedCount: 1, totalCount: 3, percentComplete: 33 });
|
|
expect(checklist.items).toEqual([
|
|
expect.objectContaining({ id: "legacy_session_step_1", block: "profile", titleKey: "onboarding.firstSteps.profile" }),
|
|
expect.objectContaining({ id: "shk-first-steps-team-detection-v1", block: "team", titleKey: "onboarding.firstSteps.team" }),
|
|
expect.objectContaining({ id: "legacy_session_step_2", block: "contacts", titleKey: "onboarding.firstSteps.contacts" }),
|
|
]);
|
|
expect(mocks.db.onboardingSessionStep.findMany).toHaveBeenCalledWith({
|
|
where: {
|
|
onboardingSessionId: "legacy_session_1",
|
|
stepId: { in: legacySteps.map((step) => step.id) },
|
|
},
|
|
include: { step: true },
|
|
orderBy: { step: { order: "asc" } },
|
|
});
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("binds every checklist read to the requested tenant and user", async () => {
|
|
const contexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
|
|
const observeContext = () => contexts.push(getRlsExecutionContext());
|
|
mocks.db.onboarding.findUnique.mockImplementation(async () => {
|
|
observeContext();
|
|
return canonicalCatalog();
|
|
});
|
|
mocks.db.onboardingSession.findUnique.mockImplementation(async () => {
|
|
observeContext();
|
|
return { id: "session_1", status: "active" };
|
|
});
|
|
mocks.db.onboardingSessionStep.findMany.mockImplementation(async () => {
|
|
observeContext();
|
|
return [sessionStep(0)];
|
|
});
|
|
mocks.db.user.findUnique.mockImplementation(async () => {
|
|
observeContext();
|
|
return { firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" };
|
|
});
|
|
mocks.db.tenantUser.count.mockImplementation(async () => {
|
|
observeContext();
|
|
return 1;
|
|
});
|
|
mocks.db.tenantUserInvitation.count.mockImplementation(async () => {
|
|
observeContext();
|
|
return 0;
|
|
});
|
|
mocks.db.kontakt.count.mockImplementation(async () => {
|
|
observeContext();
|
|
return 0;
|
|
});
|
|
mocks.db.projekt.count.mockImplementation(async () => {
|
|
observeContext();
|
|
return 0;
|
|
});
|
|
mocks.db.tenantSubscription.findUnique.mockImplementation(async () => {
|
|
observeContext();
|
|
return null;
|
|
});
|
|
|
|
await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
|
|
|
|
expect(contexts).toHaveLength(9);
|
|
for (const context of contexts) {
|
|
expect(context).toMatchObject({ tenantId: "tenant_1", userId: "user_1" });
|
|
}
|
|
});
|
|
|
|
it("updates only the existing session and never re-provisions tenant defaults", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
|
|
mocks.db.onboardingSession.update.mockResolvedValue({ id: "session_1", status: "dismissed" });
|
|
|
|
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" });
|
|
|
|
expect(mocks.db.onboarding.findUnique).toHaveBeenCalledWith({
|
|
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 } },
|
|
},
|
|
});
|
|
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
|
|
where: { id: "session_1" },
|
|
data: { status: "dismissed", dismissedAt: expect.any(Date) },
|
|
});
|
|
expect(mocks.ensureDefaultSalesPipeline).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("reactivates a dismissed session on the show action", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
|
|
mocks.db.onboardingSession.update.mockResolvedValue({ id: "session_1", status: "active" });
|
|
|
|
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "show" });
|
|
|
|
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
|
|
where: { id: "session_1" },
|
|
data: { status: "active", dismissedAt: null },
|
|
});
|
|
});
|
|
|
|
it("updates an existing legacy session without replacing or provisioning it", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
|
|
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
|
|
mocks.db.onboardingSession.update.mockResolvedValue({ id: "legacy_session_1", status: "dismissed" });
|
|
|
|
await updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" });
|
|
|
|
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
|
|
where: { id: "legacy_session_1" },
|
|
data: { status: "dismissed", dismissedAt: expect.any(Date) },
|
|
});
|
|
expect(mocks.ensureDefaultSalesPipeline).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("completes only a semantic checklist step from an existing legacy session", async () => {
|
|
const legacySteps = legacyCatalogSteps();
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
|
|
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
|
|
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 1 });
|
|
|
|
await expect(
|
|
updateFirstStepsChecklist({
|
|
tenantId: "legacy_tenant",
|
|
userId: "user_1",
|
|
action: "complete",
|
|
sessionStepId: "legacy_session_step_1",
|
|
})
|
|
).resolves.toEqual({ count: 1 });
|
|
|
|
expect(mocks.db.onboardingSessionStep.updateMany).toHaveBeenCalledWith({
|
|
where: {
|
|
id: "legacy_session_step_1",
|
|
onboardingSessionId: "legacy_session_1",
|
|
stepId: { in: legacySteps.map((step) => step.id) },
|
|
},
|
|
data: { completedAt: expect.any(Date) },
|
|
});
|
|
});
|
|
|
|
it("does not use a malformed legacy catalog as a compatibility fallback", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(null);
|
|
mocks.db.onboardingSession.findFirst.mockResolvedValue({
|
|
...legacySession(),
|
|
onboarding: { steps: legacyCatalogSteps().slice(0, 3) },
|
|
});
|
|
|
|
await expect(updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" })).rejects.toMatchObject({
|
|
code: "foundation.not_found",
|
|
});
|
|
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("isolates checklist reads and writes from a previously bound tenant transaction", async () => {
|
|
const oldTransaction = {};
|
|
const contexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
|
|
const observeContext = () => contexts.push(getRlsExecutionContext());
|
|
mocks.db.onboarding.findUnique.mockImplementation(async () => {
|
|
observeContext();
|
|
return canonicalCatalog();
|
|
});
|
|
mocks.db.onboardingSession.findUnique.mockImplementation(async () => {
|
|
observeContext();
|
|
return { id: "session_1" };
|
|
});
|
|
mocks.db.onboardingSession.update.mockImplementation(async () => {
|
|
observeContext();
|
|
return { id: "session_1", status: "dismissed" };
|
|
});
|
|
|
|
await runWithRlsContext({ tenantId: "tenant_old", userId: "user_1" }, () =>
|
|
runWithRlsTransaction(oldTransaction, async () => {
|
|
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" });
|
|
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_old", userId: "user_1", transaction: oldTransaction });
|
|
})
|
|
);
|
|
|
|
expect(contexts).toHaveLength(3);
|
|
for (const context of contexts) {
|
|
expect(context).toMatchObject({ tenantId: "tenant_1", userId: "user_1" });
|
|
expect(context?.transaction).toBeUndefined();
|
|
}
|
|
});
|
|
|
|
it("fails closed before any query when a caller tries to replace the authenticated RLS user", async () => {
|
|
await runWithRlsContext({ tenantId: "tenant_1", userId: "authenticated_user" }, async () => {
|
|
await expect(getFirstStepsChecklist({ tenantId: "tenant_1", userId: "other_user" })).rejects.toMatchObject({
|
|
code: "foundation.not_found",
|
|
});
|
|
await expect(
|
|
updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "other_user", action: "hide" })
|
|
).rejects.toMatchObject({ code: "foundation.not_found" });
|
|
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1", userId: "authenticated_user" });
|
|
});
|
|
|
|
expect(mocks.db.onboarding.findUnique).not.toHaveBeenCalled();
|
|
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
|
|
expect(mocks.db.onboardingSession.findFirst).not.toHaveBeenCalled();
|
|
expect(mocks.db.onboardingSessionStep.findMany).not.toHaveBeenCalled();
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("fails closed instead of creating defaults for a tenant without a bootstrap session", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
|
|
|
|
await expect(updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" })).rejects.toMatchObject({
|
|
code: "foundation.not_found",
|
|
});
|
|
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("fails closed for a catalog with generated or duplicated step identities", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue({
|
|
...canonicalCatalog(),
|
|
steps: SHK_FIRST_STEPS.map((step, index) => (index === 0 ? { ...step, id: "generated-step" } : { ...step })),
|
|
});
|
|
|
|
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" })).rejects.toMatchObject({
|
|
code: "foundation.not_found",
|
|
});
|
|
|
|
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it.each([
|
|
["type", "modal"],
|
|
["realtime", true],
|
|
["canBeDismissed", false],
|
|
["height", "md"],
|
|
] as const)("fails closed when the canonical catalog %s drifts", async (field, value) => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue({
|
|
...canonicalCatalog(),
|
|
[field]: value,
|
|
});
|
|
|
|
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" })).rejects.toMatchObject({
|
|
code: "foundation.not_found",
|
|
});
|
|
|
|
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
|
|
expectNoChecklistWrites();
|
|
});
|
|
|
|
it("completes only a canonical step belonging to the selected SHK session", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
|
|
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 1 });
|
|
|
|
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "complete", sessionStepId: "session_step_1" })).resolves.toEqual({
|
|
count: 1,
|
|
});
|
|
|
|
expect(mocks.db.onboardingSessionStep.updateMany).toHaveBeenCalledWith({
|
|
where: {
|
|
id: "session_step_1",
|
|
onboardingSessionId: "session_1",
|
|
stepId: { in: SHK_FIRST_STEPS.map((step) => step.id) },
|
|
},
|
|
data: { completedAt: expect.any(Date) },
|
|
});
|
|
});
|
|
|
|
it("returns not found when a submitted session step is outside the canonical SHK session", async () => {
|
|
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
|
|
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
|
|
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 0 });
|
|
|
|
await expect(
|
|
updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "complete", sessionStepId: "foreign_step" })
|
|
).rejects.toMatchObject({ code: "foundation.not_found" });
|
|
});
|
|
});
|