456 lines
18 KiB
TypeScript
456 lines
18 KiB
TypeScript
import "@testing-library/jest-dom";
|
|
import React from "react";
|
|
import { fireEvent, render, screen } from "@testing-library/react";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { MemoryRouter } from "react-router";
|
|
import DashboardRoute, { loader } from "./dashboard";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { getAppDashboardStats } from "~/utils/services/appDashboardService";
|
|
import { getTenant } from "~/utils/db/tenants.db.server";
|
|
import { loadDashboardData } from "~/utils/data/useDashboardData";
|
|
import PeriodHelper from "~/utils/helpers/PeriodHelper";
|
|
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
|
import { requireAuth } from "~/utils/loaders.middleware";
|
|
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
|
import { loadAppData } from "~/utils/data/.server/appData";
|
|
import { evaluateDashboardModuleGates, type DashboardModuleGateDecision } from "~/services/dashboard-registry/gating.server";
|
|
import { getDashboardModuleDefinitions, type DashboardModuleDefinition, type DashboardModuleId } from "~/services/dashboard-registry/registry.server";
|
|
import { loadDashboardVM } from "~/services/dashboard/dashboard.server";
|
|
import { getFirstStepsChecklist } from "~/utils/services/.server/akP20OnboardingService";
|
|
import { toFirstStepsChecklistVM } from "@hivegrid/view-models";
|
|
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
|
|
|
const translatedT = vi.fn((key: string) => `translated:${key}`);
|
|
const computedGte = new Date("2026-02-03T04:05:06.000Z");
|
|
const tenant = { id: "tenant_1", slug: "acme" };
|
|
const appData = { mySubscription: { status: "past_due", trialStartsAt: null, trialEndsAt: null, products: [] } };
|
|
const stats = [{ name: "Contacts", stat: "7", previousStat: "3" }];
|
|
const dashboardData = { users: 4 };
|
|
const firstStepsChecklistSource = {
|
|
id: "checklist_1",
|
|
status: "active",
|
|
dismissed: false,
|
|
completedCount: 1,
|
|
totalCount: 2,
|
|
percentComplete: 50,
|
|
items: [
|
|
{ id: "step_1", block: "profile", titleKey: "onboarding.firstSteps.profile", href: "settings/profile", completed: true, hidden: false },
|
|
{ id: "step_2", block: "contacts", titleKey: "onboarding.firstSteps.contacts", href: "contacts", completed: false, hidden: false },
|
|
],
|
|
};
|
|
const firstStepsChecklist = toFirstStepsChecklistVM({
|
|
...firstStepsChecklistSource,
|
|
items: firstStepsChecklistSource.items.map((item) => ({ ...item, href: `/acme/${item.href}` })),
|
|
});
|
|
const dashboardVm = {
|
|
activeRole: "office",
|
|
generatedAt: "2026-07-01T00:00:00.000Z",
|
|
streamUrl: "/acme/dashboard.stream",
|
|
canCustomize: true,
|
|
layout: {
|
|
role: "office",
|
|
nameKey: "app.dashboard.roles.office.name",
|
|
descriptionKey: "app.dashboard.roles.office.description",
|
|
mobileFirst: false,
|
|
widgets: [
|
|
{
|
|
key: "projects.kpis",
|
|
titleKey: "app.dashboard.widgets.projectKpis.title",
|
|
descriptionKey: "app.dashboard.widgets.projectKpis.description",
|
|
domain: "projects",
|
|
kind: "kpi",
|
|
period: "30d",
|
|
visible: true,
|
|
loadingMode: "lazy",
|
|
metrics: [{ labelKey: "app.dashboard.metrics.activeProjects", value: "3" }],
|
|
items: [],
|
|
chart: null,
|
|
series: null,
|
|
position: { x: 0, y: 1 },
|
|
size: { w: 4, h: 2 },
|
|
},
|
|
],
|
|
},
|
|
};
|
|
const registryModules = getDashboardModuleDefinitions();
|
|
const getRegistryModule = (moduleId: DashboardModuleId): DashboardModuleDefinition => {
|
|
const module = registryModules.find((definition) => definition.id === moduleId);
|
|
if (!module) {
|
|
throw new Error(`Missing dashboard registry module in test fixture: ${moduleId}`);
|
|
}
|
|
return module;
|
|
};
|
|
const summaryModule = getRegistryModule("summary-stats");
|
|
const featureGatedModule = getRegistryModule("subscription-health");
|
|
const planGatedModule = getRegistryModule("priority-insights");
|
|
let routeLoaderData: unknown;
|
|
const navigateMock = vi.hoisted(() => vi.fn());
|
|
let moduleDecisions: DashboardModuleGateDecision[] = [
|
|
{ module: summaryModule, allowed: true },
|
|
{
|
|
module: planGatedModule,
|
|
allowed: false,
|
|
diagnostic: { moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" },
|
|
},
|
|
];
|
|
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/services/appDashboardService", () => ({
|
|
getAppDashboardStats: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/db/tenants.db.server", () => ({
|
|
getTenant: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/data/useDashboardData", () => ({
|
|
loadDashboardData: vi.fn(),
|
|
useDashboardData: vi.fn(() => ({ users: 4 })),
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/PeriodHelper", () => ({
|
|
default: { getGreaterThanOrEqualsFromRequest: vi.fn() },
|
|
defaultPeriodFilter: "30d",
|
|
PeriodFilters: [],
|
|
}));
|
|
|
|
vi.mock("~/modules/metrics/services/.server/MetricTracker", () => ({
|
|
createMetrics: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/loaders.middleware", () => ({
|
|
requireAuth: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/services/.server/urlService", () => ({
|
|
getTenantIdFromUrl: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/data/.server/appData", () => ({
|
|
loadAppData: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/services/.server/akP20OnboardingService", () => ({
|
|
getFirstStepsChecklist: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("react-router", async () => {
|
|
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
|
return {
|
|
...actual,
|
|
useLoaderData: () => routeLoaderData,
|
|
useNavigate: () => navigateMock,
|
|
};
|
|
});
|
|
|
|
vi.mock("~/services/dashboard-registry/gating.server", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("~/services/dashboard-registry/gating.server")>();
|
|
return {
|
|
...actual,
|
|
evaluateDashboardModuleGates: vi.fn(),
|
|
};
|
|
});
|
|
|
|
vi.mock("~/services/dashboard/dashboard.server", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("~/services/dashboard/dashboard.server")>();
|
|
return {
|
|
...actual,
|
|
loadDashboardVM: vi.fn(),
|
|
};
|
|
});
|
|
|
|
vi.mock("~/modules/metrics/utils/defaultHeaders", () => ({
|
|
serverTimingHeaders: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/components/app/ProfileBanner", () => ({
|
|
default: () => <div data-testid="profile-banner" />,
|
|
}));
|
|
|
|
vi.mock("~/components/ui/stats/DashboardStats", () => ({
|
|
DashboardStats: ({ items }: { items: Array<{ name: string; stat: string }> }) => (
|
|
<dl>
|
|
{items.map((item) => (
|
|
<div key={item.name}>
|
|
<dt>{item.name}</dt>
|
|
<dd>{item.stat}</dd>
|
|
</div>
|
|
))}
|
|
</dl>
|
|
),
|
|
}));
|
|
|
|
vi.mock("~/components/ui/input/InputSelect", () => ({
|
|
default: ({ value }: { value: string }) => <div aria-label="period-filter">{value}</div>,
|
|
}));
|
|
|
|
vi.mock("~/components/ui/errors/ServerError", () => ({
|
|
default: () => null,
|
|
}));
|
|
|
|
vi.mock("~/utils/data/useAppData", () => ({
|
|
useAppData: vi.fn(() => ({ user: {}, permissions: ["app.dashboard.view", "dashboard.read", "dashboard.customize"] })),
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/PermissionsHelper", () => ({
|
|
getUserHasPermission: vi.fn(() => true),
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
|
verifyUserHasPermission: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: vi.fn(() => ({ t: (key: string) => key, i18n: { language: "de" } })),
|
|
}));
|
|
|
|
describe("app tenant dashboard route contract", () => {
|
|
beforeEach(() => {
|
|
navigateMock.mockReset();
|
|
vi.clearAllMocks();
|
|
process.env.APP_NAME = "HiveGrid";
|
|
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
|
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
|
|
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
|
vi.mocked(requireAuth).mockResolvedValue({ userId: "user_1" } as never);
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
dashboard: dashboardVm,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [],
|
|
firstStepsChecklist,
|
|
};
|
|
moduleDecisions = [
|
|
{ module: summaryModule, allowed: true },
|
|
{
|
|
module: planGatedModule,
|
|
allowed: false,
|
|
diagnostic: { moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" },
|
|
},
|
|
];
|
|
vi.mocked(loadAppData).mockResolvedValue(appData as never);
|
|
vi.mocked(evaluateDashboardModuleGates).mockResolvedValue(moduleDecisions as never);
|
|
vi.mocked(loadDashboardVM).mockResolvedValue(dashboardVm as never);
|
|
vi.mocked(getFirstStepsChecklist).mockResolvedValue(firstStepsChecklistSource as never);
|
|
vi.mocked(getUserHasPermission).mockReturnValue(true);
|
|
vi.mocked(getAppDashboardStats).mockResolvedValue(stats as never);
|
|
vi.mocked(loadDashboardData).mockResolvedValue(dashboardData as never);
|
|
vi.mocked(PeriodHelper.getGreaterThanOrEqualsFromRequest).mockReturnValue(computedGte);
|
|
vi.mocked(createMetrics).mockResolvedValue({
|
|
time: async <T,>(value: T | Promise<T>) => value,
|
|
getServerTimingHeader: () => ({ "Server-Timing": "app.dashboard;dur=1" }),
|
|
} as never);
|
|
});
|
|
|
|
it("passes tenant, translations, and the computed period boundary into the KPI service while preserving loader data", async () => {
|
|
const request = new Request("https://example.com/acme/dashboard?period=month");
|
|
const params = { tenant: "acme" };
|
|
|
|
const response = (await loader({ request, params, context: {}, unstable_pattern: "app.$tenant/dashboard" })) as Response;
|
|
const body = await response.json();
|
|
|
|
expect(requireAuth).toHaveBeenCalledWith({ request, params });
|
|
expect(getTranslations).toHaveBeenCalledWith(request);
|
|
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
|
expect(loadAppData).toHaveBeenCalledWith({ request, params, t: translatedT, time: expect.any(Function) });
|
|
expect(getTenant).toHaveBeenCalledWith("tenant_1");
|
|
expect(PeriodHelper.getGreaterThanOrEqualsFromRequest).toHaveBeenCalledWith({ request });
|
|
expect(getAppDashboardStats).toHaveBeenCalledWith({ t: translatedT, tenant, gte: computedGte });
|
|
expect(loadDashboardData).toHaveBeenCalledWith({ request, params });
|
|
expect(loadDashboardVM).toHaveBeenCalledWith({ request, params });
|
|
expect(getFirstStepsChecklist).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" });
|
|
expect(evaluateDashboardModuleGates).toHaveBeenCalledWith({
|
|
request,
|
|
params,
|
|
subscription: appData.mySubscription,
|
|
redirectPaths: {
|
|
"feature-flag": "/feature-disabled?tenant=acme",
|
|
plan: "/plan-required/acme",
|
|
},
|
|
});
|
|
expect(vi.mocked(evaluateDashboardModuleGates).mock.calls[0]?.[0].redirectPaths?.plan).toBe("/plan-required/acme");
|
|
expect(body).toMatchObject({
|
|
title: "translated:app.sidebar.dashboard | HiveGrid",
|
|
users: 4,
|
|
dashboard: dashboardVm,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [moduleDecisions[1].diagnostic],
|
|
firstStepsChecklist,
|
|
});
|
|
expect(body.modules.map((module: DashboardModuleDefinition) => module.id)).toEqual(["summary-stats"]);
|
|
expect(body.moduleDiagnostics.map((diagnostic: { moduleId: DashboardModuleId }) => diagnostic.moduleId)).toEqual(["priority-insights"]);
|
|
expect(response.headers.get("Server-Timing")).toBe("app.dashboard;dur=1");
|
|
});
|
|
|
|
it("returns a localized 404 when the tenant is not found", async () => {
|
|
vi.mocked(getTenant).mockResolvedValue(null);
|
|
const request = new Request("https://example.com/acme/dashboard");
|
|
const params = { tenant: "acme" };
|
|
|
|
try {
|
|
await loader({ request, params, context: {}, unstable_pattern: "app.$tenant/dashboard" });
|
|
throw new Error("Expected loader to throw");
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(Response);
|
|
expect((error as Response).status).toBe(404);
|
|
await expect((error as Response).json()).resolves.toEqual({ error: "translated:app.dashboard.errors.tenantNotFound" });
|
|
}
|
|
});
|
|
|
|
it("does not load or render the checklist without checklist permission", async () => {
|
|
vi.mocked(getUserHasPermission).mockImplementation((_data, permission) => permission !== "app.onboarding.checklist.update");
|
|
const request = new Request("https://example.com/acme/dashboard");
|
|
const params = { tenant: "acme" };
|
|
|
|
const response = (await loader({ request, params, context: {}, unstable_pattern: "app.$tenant/dashboard" })) as Response;
|
|
const body = await response.json();
|
|
|
|
expect(getFirstStepsChecklist).not.toHaveBeenCalled();
|
|
expect(body.firstStepsChecklist).toEqual({ status: "empty" });
|
|
|
|
routeLoaderData = body;
|
|
vi.mocked(getUserHasPermission).mockReturnValue(true);
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
expect(screen.queryByText("onboarding.firstSteps.dashboardTitle")).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("renders the allowed summary registry module with the existing dashboard stats", () => {
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.getByRole("heading", { name: "app.dashboard.summary" })).toBeInTheDocument();
|
|
expect(screen.getByText("Contacts")).toBeInTheDocument();
|
|
expect(screen.getByText("7")).toBeInTheDocument();
|
|
expect(screen.queryByTestId("profile-banner")).not.toBeInTheDocument();
|
|
expect(screen.getByText("onboarding.firstSteps.dashboardTitle")).toBeInTheDocument();
|
|
expect(screen.getByRole("button", { name: "onboarding.firstSteps.open" })).toBeEnabled();
|
|
fireEvent.click(screen.getByRole("button", { name: "onboarding.firstSteps.open" }));
|
|
expect(navigateMock).toHaveBeenCalledWith("../onboarding/checklist");
|
|
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
|
// R-P11b interim screen (AD-28): the widget grid renders the single layout the
|
|
// loader derived; there is no role switcher to pick another one.
|
|
expect(document.querySelector("[data-ui-id^='ui.dashboard.roleSwitcher']")).not.toBeInTheDocument();
|
|
expect(document.querySelector('[data-ui-id="ui.dashboard.widget.projects.kpis"]')).toBeInTheDocument();
|
|
expect(document.querySelector('[data-ui-id="ui.dashboard.live.toggle"]')).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("omits gated summary content when the summary module is feature-disabled", () => {
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
dashboard: dashboardVm,
|
|
stats,
|
|
modules: [],
|
|
moduleDiagnostics: [{ moduleId: "summary-stats", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled?tenant=acme" }],
|
|
firstStepsChecklist,
|
|
};
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.queryByRole("heading", { name: "app.dashboard.summary" })).not.toBeInTheDocument();
|
|
expect(screen.queryByText("Contacts")).not.toBeInTheDocument();
|
|
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("renders plan-required diagnostics with the safe tenant-aware plan link and no gated module content", () => {
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
dashboard: dashboardVm,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [{ moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" }],
|
|
firstStepsChecklist,
|
|
};
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.getByText("app.dashboard.moduleDiagnostics.planRequiredTitle")).toBeInTheDocument();
|
|
expect(screen.getByText("app.dashboard.moduleDiagnostics.planRequiredDescription")).toBeInTheDocument();
|
|
expect(screen.getByRole("link", { name: "app.dashboard.moduleDiagnostics.viewPlanOptions" })).toHaveAttribute("href", "/plan-required/acme");
|
|
expect(screen.queryByText(planGatedModule.titleKey)).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("suppresses feature-disabled diagnostics entirely while still hiding the gated module content", () => {
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
dashboard: dashboardVm,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [
|
|
{ moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled", redirectPath: "https://unsafe.example.com/feature" },
|
|
],
|
|
firstStepsChecklist,
|
|
};
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
|
expect(screen.queryByRole("link", { name: "app.dashboard.moduleDiagnostics.learnMore" })).not.toBeInTheDocument();
|
|
expect(screen.queryByText(featureGatedModule.titleKey)).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("keeps loader diagnostics redacted from tenant, user, subscription, provider, token, and raw feature inputs", async () => {
|
|
moduleDecisions = [
|
|
{ module: summaryModule, allowed: true },
|
|
{
|
|
module: featureGatedModule,
|
|
allowed: false,
|
|
diagnostic: { moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled" },
|
|
},
|
|
{
|
|
module: planGatedModule,
|
|
allowed: false,
|
|
diagnostic: { moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" },
|
|
},
|
|
];
|
|
vi.mocked(evaluateDashboardModuleGates).mockResolvedValue(moduleDecisions as never);
|
|
|
|
const response = (await loader({
|
|
request: new Request(
|
|
"https://example.com/acme/dashboard?tenantId=tenant_1&userId=user_123&subscriptionId=sub_123&providerKey=pk_live_secret&token=tok_secret&rawFeature=billing.enterprise.secret_feature"
|
|
),
|
|
params: { tenant: "acme" },
|
|
context: {},
|
|
unstable_pattern: "app.$tenant/dashboard",
|
|
})) as Response;
|
|
const body = await response.json();
|
|
const diagnosticPayload = JSON.stringify(body.moduleDiagnostics);
|
|
|
|
expect(body.modules).toEqual([summaryModule]);
|
|
expect(body.moduleDiagnostics).toEqual([moduleDecisions[1].diagnostic, moduleDecisions[2].diagnostic]);
|
|
expect(body.moduleDiagnostics.map((diagnostic: { moduleId: DashboardModuleId }) => diagnostic.moduleId)).toEqual([
|
|
"subscription-health",
|
|
"priority-insights",
|
|
]);
|
|
expect(diagnosticPayload).not.toContain("tenant_1");
|
|
expect(diagnosticPayload).not.toContain("user_123");
|
|
expect(diagnosticPayload).not.toContain("sub_123");
|
|
expect(diagnosticPayload).not.toContain("pk_live_secret");
|
|
expect(diagnosticPayload).not.toContain("tok_secret");
|
|
expect(diagnosticPayload).not.toContain("billing.enterprise.secret_feature");
|
|
});
|
|
});
|