347 lines
14 KiB
TypeScript
347 lines
14 KiB
TypeScript
import "@testing-library/jest-dom";
|
|
import React from "react";
|
|
import { 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";
|
|
|
|
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: { products: [], trial: { active: false, period: "trial-ended" } } };
|
|
const stats = [{ name: "Contacts", stat: "7", previousStat: "3" }];
|
|
const dashboardData = { users: 4 };
|
|
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;
|
|
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("react-router", async () => {
|
|
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
|
return {
|
|
...actual,
|
|
useLoaderData: () => routeLoaderData,
|
|
};
|
|
});
|
|
|
|
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("~/modules/metrics/utils/defaultHeaders", () => ({
|
|
serverTimingHeaders: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/components/app/ProfileBanner", () => ({
|
|
default: () => null,
|
|
}));
|
|
|
|
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"] })),
|
|
}));
|
|
|
|
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 })),
|
|
}));
|
|
|
|
describe("app tenant dashboard route contract", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
process.env.APP_NAME = "ToolCTRL";
|
|
vi.mocked(getTranslations).mockResolvedValue({ t: translatedT } as never);
|
|
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
|
|
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [],
|
|
};
|
|
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(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(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 | ToolCTRL",
|
|
users: 4,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [moduleDecisions[1].diagnostic],
|
|
});
|
|
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("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.queryByText("app.dashboard.moduleDiagnostics.unavailableTitle")).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("omits gated summary content when the summary module is feature-disabled", () => {
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
stats,
|
|
modules: [],
|
|
moduleDiagnostics: [{ moduleId: "summary-stats", source: "feature-flag", reason: "feature-disabled", redirectPath: "/feature-disabled?tenant=acme" }],
|
|
};
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.queryByRole("heading", { name: "app.dashboard.summary" })).not.toBeInTheDocument();
|
|
expect(screen.queryByText("Contacts")).not.toBeInTheDocument();
|
|
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableTitle")).toBeInTheDocument();
|
|
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableDescription")).toBeInTheDocument();
|
|
expect(screen.getByRole("link", { name: "app.dashboard.moduleDiagnostics.learnMore" })).toHaveAttribute("href", "/feature-disabled?tenant=acme");
|
|
});
|
|
|
|
it("renders plan-required diagnostics with the safe tenant-aware plan link and no gated module content", () => {
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [{ moduleId: "priority-insights", source: "plan", reason: "plan-required", redirectPath: "/plan-required/acme" }],
|
|
};
|
|
|
|
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("renders feature-disabled diagnostics with only the safe fallback link and no gated module content", () => {
|
|
routeLoaderData = {
|
|
...dashboardData,
|
|
stats,
|
|
modules: [summaryModule],
|
|
moduleDiagnostics: [
|
|
{ moduleId: "subscription-health", source: "feature-flag", reason: "feature-disabled", redirectPath: "https://unsafe.example.com/feature" },
|
|
],
|
|
};
|
|
|
|
render(
|
|
<MemoryRouter>
|
|
<DashboardRoute />
|
|
</MemoryRouter>
|
|
);
|
|
|
|
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableTitle")).toBeInTheDocument();
|
|
expect(screen.getByText("app.dashboard.moduleDiagnostics.unavailableDescription")).toBeInTheDocument();
|
|
expect(screen.getByRole("link", { name: "app.dashboard.moduleDiagnostics.learnMore" })).toHaveAttribute("href", "/feature-disabled");
|
|
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");
|
|
});
|
|
});
|