Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
552 lines
25 KiB
TypeScript
552 lines
25 KiB
TypeScript
import { test, expect, vi, beforeEach } from "vitest";
|
||
import { act, render, screen, within } from "@testing-library/react";
|
||
import userEvent from "@testing-library/user-event";
|
||
import type { DashboardData } from "@/app/lib/services/adminDashboard";
|
||
import type { SidebarLink } from "@/app/lib/aclSidebar";
|
||
import DashboardPage from "./page";
|
||
|
||
const auth = vi.hoisted(() => ({
|
||
state: { name: "Aiman" as string | null, roles: [{ name: "ROLE_OPS" }], modules: ["BO_DASHBOARD"], loading: false },
|
||
links: [] as unknown[],
|
||
}));
|
||
vi.mock("@/app/lib/AdminAuthContext", () => ({
|
||
useAdminAuth: () => ({
|
||
name: auth.state.name,
|
||
roles: auth.state.roles,
|
||
loading: auth.state.loading,
|
||
hasModule: (m: string) => auth.state.modules.includes(m),
|
||
}),
|
||
}));
|
||
// The Event dashboard has its own tests; here only the homepage's choice between dashboards is under test.
|
||
vi.mock("@/app/components/dashboard/EventDashboard", () => ({
|
||
EventDashboard: ({ switcher }: { switcher?: React.ReactNode }) => (
|
||
<div>
|
||
<h1>Event dashboard stub</h1>
|
||
{switcher}
|
||
</div>
|
||
),
|
||
}));
|
||
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => auth.links as SidebarLink[] }));
|
||
|
||
const router = vi.hoisted(() => {
|
||
let search = new URLSearchParams();
|
||
const listeners = new Set<() => void>();
|
||
return {
|
||
getSearch: () => search,
|
||
subscribe: (l: () => void) => {
|
||
listeners.add(l);
|
||
return () => listeners.delete(l);
|
||
},
|
||
replace: vi.fn((url: string) => {
|
||
search = new URLSearchParams(url.split("?")[1] ?? "");
|
||
listeners.forEach(l => l());
|
||
}),
|
||
reset: (qs = "") => {
|
||
search = new URLSearchParams(qs);
|
||
},
|
||
};
|
||
});
|
||
vi.mock("next/navigation", async () => {
|
||
const { useSyncExternalStore } = await import("react");
|
||
return {
|
||
usePathname: () => "/",
|
||
useSearchParams: () => useSyncExternalStore(router.subscribe, router.getSearch, router.getSearch),
|
||
useRouter: () => ({ replace: router.replace }),
|
||
};
|
||
});
|
||
// The page's handling of what the picker emits is under test; the picker has its own tests.
|
||
vi.mock("@/app/components/ui/date-range-picker", () => ({
|
||
DateRangePicker: ({ onChange }: { onChange: (r: { from: string; to: string }) => void }) => (
|
||
<div>
|
||
<button type="button" onClick={() => onChange({ from: "2026-09-03", to: "" })}>pick start</button>
|
||
<button type="button" onClick={() => onChange({ from: "2026-09-03", to: "2026-09-10" })}>pick range</button>
|
||
<button type="button" onClick={() => onChange({ from: "", to: "" })}>clear range</button>
|
||
</div>
|
||
),
|
||
}));
|
||
|
||
const fixture: DashboardData = {
|
||
from: "2026-09-01",
|
||
to: "2026-09-30",
|
||
members: {
|
||
total: 38,
|
||
active: 37,
|
||
newThisMonth: 36,
|
||
byRank: { OTTER: 8, SQUIRREL: 19, GIRAFFE: 10 },
|
||
byStatus: { Y: 37, N: 1 },
|
||
newPerDay: [
|
||
{ date: "2026-09-01", byRank: { OTTER: 2, SQUIRREL: 0, GIRAFFE: 1 } },
|
||
{ date: "2026-09-02", byRank: { OTTER: 0, SQUIRREL: 33, GIRAFFE: 0 } },
|
||
],
|
||
},
|
||
sales: {
|
||
daily: [
|
||
{ date: "2026-09-01", revenue: 0, orders: 0 },
|
||
{ date: "2026-09-02", revenue: 155.5, orders: 3 },
|
||
],
|
||
byChannel: [
|
||
{ channel: "NORMAL", revenue: 100.5, orders: 1 },
|
||
{ channel: "EVENT", revenue: 35, orders: 1 },
|
||
{ channel: "OUTLET", revenue: 20, orders: 1 },
|
||
],
|
||
periodRevenue: 155.5,
|
||
periodOrders: 3,
|
||
},
|
||
rewardTotals: [
|
||
{ rewardCode: "SELF_ACORN", walletType: "ACORN", total: 5000, count: 25 },
|
||
{ rewardCode: "SPONSOR_APPLE", walletType: "APPLE", total: 1100, count: 11 },
|
||
],
|
||
topEarners: [
|
||
{ memberCode: "MY5891174", name: "Giraffe Sponsor", total: 900 },
|
||
{ memberCode: "MY4973362", name: "Bob Lee", total: 300 },
|
||
],
|
||
previous: {
|
||
from: "2026-08-01",
|
||
to: "2026-08-31",
|
||
members: { total: 30, active: 30, newThisMonth: 40, byRank: {}, byStatus: {}, newPerDay: [] },
|
||
sales: { daily: [], byChannel: [], periodRevenue: 100, periodOrders: 4 },
|
||
rewardTotals: [{ rewardCode: "SELF_ACORN", walletType: "ACORN", total: 5000, count: 20 }],
|
||
},
|
||
};
|
||
|
||
const getDashboard = vi.fn();
|
||
vi.mock("@/app/lib/services/adminDashboard", async () => {
|
||
const actual = await vi.importActual<typeof import("@/app/lib/services/adminDashboard")>(
|
||
"@/app/lib/services/adminDashboard",
|
||
);
|
||
return { ...actual, getDashboard: (p?: unknown) => getDashboard(p) };
|
||
});
|
||
|
||
beforeEach(() => {
|
||
getDashboard.mockReset();
|
||
router.reset();
|
||
router.replace.mockClear();
|
||
vi.useRealTimers();
|
||
auth.state = { name: "Aiman", roles: [{ name: "ROLE_OPS" }], modules: ["BO_DASHBOARD"], loading: false };
|
||
auth.links = [];
|
||
});
|
||
|
||
function kpis() {
|
||
return within(screen.getByRole("region", { name: "Key performance indicators" }));
|
||
}
|
||
|
||
test("shows a loading skeleton while the figures are fetched", () => {
|
||
getDashboard.mockReturnValue(new Promise(() => {}));
|
||
const { container } = render(<DashboardPage />);
|
||
expect(screen.getByText("Dashboard")).toBeInTheDocument();
|
||
expect(container.querySelectorAll('[data-slot="skeleton"]').length).toBeGreaterThan(0);
|
||
});
|
||
|
||
test("renders live member, sales and reward figures", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(kpis().getByText("RM 155.50")).toBeInTheDocument(); // revenue in the period
|
||
expect(kpis().getByText("1,100.00")).toBeInTheDocument(); // Apples credited
|
||
expect(kpis().getByText("5,000.00")).toBeInTheDocument(); // Acorns credited
|
||
expect(kpis().getByText("36")).toBeInTheDocument(); // new members in the period
|
||
expect(kpis().getByText("3")).toBeInTheDocument(); // orders in the period
|
||
expect(kpis().queryByText("38")).not.toBeInTheDocument(); // no total-members tile
|
||
});
|
||
|
||
test("shows exactly five KPI tiles in the ticket's order", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
const region = await screen.findByRole("region", { name: "Key performance indicators" });
|
||
// The hero band: revenue leads, then the four tiles — still the ticket's order.
|
||
const labels = Array.from(region.querySelectorAll("[data-slot='kpi']")).map(tile => tile.querySelector("p")?.textContent);
|
||
expect(labels).toEqual(["Revenue (settled)", "Apples credited", "Acorns credited", "New members", "Orders"]);
|
||
});
|
||
|
||
test("each KPI tile shows its change against the previous period", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
const region = await screen.findByRole("region", { name: "Key performance indicators" });
|
||
// Each hero-band figure is a [data-slot="kpi"] group with its label, value and change.
|
||
const tile = (label: string) => within(within(region).getByText(label).closest("[data-slot='kpi']") as HTMLElement);
|
||
expect(tile("Revenue (settled)").getByText("+55.5%")).toBeInTheDocument(); // 155.5 vs 100
|
||
expect(tile("Orders").getByText("−25.0%")).toBeInTheDocument(); // 3 vs 4
|
||
expect(tile("New members").getByText("−10.0%")).toBeInTheDocument(); // 36 vs 40
|
||
expect(tile("Acorns credited").getByText("0.0%")).toBeInTheDocument(); // 5,000 vs 5,000
|
||
expect(tile("Apples credited").getByText("—")).toBeInTheDocument(); // nothing credited before: no base
|
||
expect(tile("Apples credited").getByText("No figure in the previous period to compare with")).toHaveClass("sr-only");
|
||
expect(tile("Revenue (settled)").getByText("vs Aug 2026")).toBeInTheDocument();
|
||
});
|
||
|
||
test("shows Acorns and Apples credited as separate tiles, never added together", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(kpis().getByText("Acorns credited")).toBeInTheDocument();
|
||
expect(kpis().getByText("Apples credited")).toBeInTheDocument();
|
||
expect(kpis().queryByText("6,100.00")).not.toBeInTheDocument();
|
||
expect(kpis().queryByText("Rewards credited")).not.toBeInTheDocument();
|
||
});
|
||
|
||
test("an admin without BO_DASHBOARD sees a welcome page with granted module tiles and no dashboard call", async () => {
|
||
auth.state.modules = ["BO_WEB_ORDERS", "BO_MEMBERS"];
|
||
auth.links = [
|
||
{ name: "Sales Listing", url: "/orders/web", children: [] },
|
||
{ name: "Sales Orders", url: "", children: [{ name: "Delivery", url: "/orders/delivery", children: [] }] },
|
||
{ name: "Members", url: "/members", children: [] },
|
||
];
|
||
render(<DashboardPage />);
|
||
|
||
expect(screen.getByRole("heading", { name: /welcome, aiman/i })).toBeInTheDocument();
|
||
expect(screen.getByText("ROLE_OPS")).toBeInTheDocument();
|
||
const tiles = screen.getAllByRole("link").map(a => [a.textContent, a.getAttribute("href")]);
|
||
expect(tiles).toEqual([
|
||
["Sales Listing", "/orders/web"],
|
||
["Delivery", "/orders/delivery"],
|
||
["Members", "/members"],
|
||
]);
|
||
expect(getDashboard).not.toHaveBeenCalled();
|
||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||
expect(screen.queryByText(/RM /)).not.toBeInTheDocument();
|
||
});
|
||
|
||
test("waits for the session before deciding between the dashboard and the welcome page", () => {
|
||
auth.state.loading = true;
|
||
auth.state.modules = [];
|
||
render(<DashboardPage />);
|
||
|
||
expect(getDashboard).not.toHaveBeenCalled();
|
||
expect(screen.queryByText(/welcome/i)).not.toBeInTheDocument();
|
||
});
|
||
|
||
test("renders the shared page header and labels terminated members", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, members: { ...fixture.members, byStatus: { Y: 37, T: 1 } } });
|
||
render(<DashboardPage />);
|
||
|
||
expect(await screen.findByRole("heading", { level: 1, name: "Dashboard" })).toBeInTheDocument();
|
||
expect(screen.getByText("Terminated")).toBeInTheDocument();
|
||
});
|
||
|
||
test("shows babyboo's ranks, not the demo ranks", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, members: { ...fixture.members, byRank: { OTTER: 8, GIRAFFE: 10 } } });
|
||
render(<DashboardPage />);
|
||
|
||
const rank = within((await screen.findByText("Rank mix")).closest("[data-slot='card']") as HTMLElement);
|
||
expect(rank.getByText("Otter")).toBeInTheDocument(); // translated rank names (BABYBOO-25)
|
||
expect(rank.getByText("Squirrel")).toBeInTheDocument(); // absent from the data -> still listed, as 0
|
||
expect(rank.getByText("Giraffe")).toBeInTheDocument();
|
||
expect(screen.queryByText("Diamond")).not.toBeInTheDocument();
|
||
});
|
||
|
||
test("breaks revenue down by Web, Event and Outlet as rows, not a table", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
const card = within((await screen.findByText("Revenue by channel")).closest("[data-slot='card']") as HTMLElement);
|
||
expect(card.queryByRole("table")).not.toBeInTheDocument();
|
||
expect(card.getByText("Web")).toBeInTheDocument();
|
||
expect(card.getByText("RM 100.50")).toBeInTheDocument();
|
||
expect(card.getByText("Event")).toBeInTheDocument();
|
||
expect(card.getByText("RM 35.00")).toBeInTheDocument();
|
||
expect(card.getByText("Outlet")).toBeInTheDocument(); // the Sales listing's label for OUTLET
|
||
expect(card.getByText("RM 20.00")).toBeInTheDocument();
|
||
expect(card.queryByText("Counter")).not.toBeInTheDocument(); // no back-office NORMAL orders
|
||
});
|
||
|
||
test("lists rewards credited by type", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
const card = within((await screen.findByText("Rewards by type")).closest("[data-slot='card']") as HTMLElement);
|
||
expect(card.getByText("Self Acorn")).toBeInTheDocument();
|
||
expect(card.getByText("5,000.00")).toBeInTheDocument();
|
||
expect(card.getByText("Sponsor Apple")).toBeInTheDocument();
|
||
});
|
||
|
||
test("top earners link to the real member page by member code", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
const link = await screen.findByRole("link", { name: /Giraffe Sponsor/ });
|
||
expect(link).toHaveAttribute("href", "/members/MY5891174");
|
||
expect(screen.getAllByTestId("top-earner-name").map(el => el.textContent)).toEqual(["Giraffe Sponsor", "Bob Lee"]);
|
||
});
|
||
|
||
test("falls back to the member code when a top earner has no name", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, topEarners: [{ memberCode: "MY1", name: null, total: 5 }] });
|
||
render(<DashboardPage />);
|
||
|
||
expect(await screen.findByRole("link", { name: /MY1/ })).toHaveAttribute("href", "/members/MY1");
|
||
});
|
||
|
||
test("says so when nobody earned anything, instead of an empty list", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, topEarners: [], rewardTotals: [] });
|
||
render(<DashboardPage />);
|
||
|
||
expect(await screen.findByText("No rewards credited in this period.")).toBeInTheDocument();
|
||
});
|
||
|
||
test("pairs the trend charts with accessible data tables and labels the months", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
const revenue = await screen.findByRole("table", { name: "Daily settled revenue" });
|
||
expect(revenue).toHaveTextContent("01/09/2026");
|
||
expect(revenue).toHaveTextContent("02/09/2026");
|
||
expect(revenue).toHaveTextContent("RM 155.50");
|
||
const growth = screen.getByRole("table", { name: "New members by day" });
|
||
const sept1 = within(within(growth).getByText("01/09/2026").closest("tr") as HTMLElement);
|
||
expect(sept1.getAllByRole("cell").map(c => c.textContent)).toEqual(["2", "0", "1"]); // OTTER, SQUIRREL, GIRAFFE
|
||
expect(within(growth).getAllByRole("columnheader").map(c => c.textContent)).toEqual(["Date", "Otter", "Squirrel", "Giraffe"]);
|
||
});
|
||
|
||
test("top earners are titled as Apple earners", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
|
||
expect(await screen.findByText("Top earners (Apple)")).toBeInTheDocument();
|
||
});
|
||
|
||
test("does not show any demo fixture data", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
for (const demo of ["Farah Kumar", "Wellness", "Sales by package", "Commission by level", "Pending Payouts"]) {
|
||
expect(screen.queryByText(new RegExp(demo))).not.toBeInTheDocument();
|
||
}
|
||
});
|
||
|
||
test("shows an error with a retry action when loading fails", async () => {
|
||
getDashboard.mockRejectedValue(new Error("Network error"));
|
||
render(<DashboardPage />);
|
||
|
||
expect(await screen.findByRole("alert")).toHaveTextContent("Network error");
|
||
|
||
getDashboard.mockResolvedValue(fixture);
|
||
await userEvent.click(screen.getByRole("button", { name: "Retry" }));
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(kpis().getByText("RM 155.50")).toBeInTheDocument();
|
||
});
|
||
|
||
test("KPI figures never truncate a label or a value, and the skeleton mirrors the hero band", async () => {
|
||
getDashboard.mockReturnValueOnce(new Promise(() => {}));
|
||
const sk = render(<DashboardPage />);
|
||
// The skeleton band: a lead block plus four tile placeholders.
|
||
const skBand = sk.container.querySelector(".rounded-2xl")!;
|
||
expect(skBand.querySelectorAll(".rounded-xl")).toHaveLength(4);
|
||
sk.unmount();
|
||
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
const region = await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(region.querySelectorAll("[data-slot='kpi']")).toHaveLength(5);
|
||
expect(kpis().getByText("New members").className).not.toMatch(/truncate/);
|
||
expect(kpis().getByText("RM 155.50").className).toMatch(/whitespace-nowrap/);
|
||
});
|
||
|
||
test("sends the URL period to the API and labels the figures with it", async () => {
|
||
router.reset("from=2026-08-01&to=2026-08-31");
|
||
getDashboard.mockResolvedValue({ ...fixture, from: "2026-08-01", to: "2026-08-31" });
|
||
render(<DashboardPage />);
|
||
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(getDashboard).toHaveBeenCalledWith({ from: "2026-08-01", to: "2026-08-31" });
|
||
expect(screen.getByText("Aug 2026")).toBeInTheDocument(); // the header's reporting period
|
||
expect(screen.getAllByText("Settled, Aug 2026")).toHaveLength(2); // the revenue trend and revenue by channel
|
||
});
|
||
|
||
test("with no period in the URL it asks for the default period", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(getDashboard).toHaveBeenCalledWith({ from: undefined, to: undefined });
|
||
});
|
||
|
||
test("a previous period that is not a whole month is labelled by its dates", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, previous: { ...fixture.previous, from: "2026-08-26", to: "2026-09-02" } });
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(kpis().getAllByText("vs 26/08/2026 – 02/09/2026")).toHaveLength(5);
|
||
});
|
||
|
||
test("the Revenue and Orders tiles show the period totals", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, sales: { ...fixture.sales, periodRevenue: 42, periodOrders: 7 } });
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(kpis().getByText("RM 42.00")).toBeInTheDocument();
|
||
expect(kpis().getByText("7")).toBeInTheDocument();
|
||
});
|
||
|
||
test("a custom range that is not a whole month is labelled by its dates", async () => {
|
||
router.reset("from=2026-09-03&to=2026-09-10");
|
||
getDashboard.mockResolvedValue({ ...fixture, from: "2026-09-03", to: "2026-09-10" });
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(screen.getByText("03/09/2026 – 10/09/2026")).toBeInTheDocument();
|
||
});
|
||
|
||
test("choosing Last month writes its dates to the URL and refetches", async () => {
|
||
vi.useFakeTimers({ now: new Date("2026-09-30T04:00:00Z"), toFake: ["Date"] });
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
|
||
await userEvent.click(screen.getByRole("combobox", { name: "Period" }));
|
||
await userEvent.click(await screen.findByRole("option", { name: "Last month" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/?from=2026-08-01&to=2026-08-31");
|
||
await vi.waitFor(() => expect(getDashboard).toHaveBeenLastCalledWith({ from: "2026-08-01", to: "2026-08-31" }));
|
||
});
|
||
|
||
test("choosing This month clears the period from the URL", async () => {
|
||
router.reset("from=2026-08-01&to=2026-08-31");
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
|
||
await userEvent.click(screen.getByRole("combobox", { name: "Period" }));
|
||
await userEvent.click(await screen.findByRole("option", { name: "This month" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/");
|
||
});
|
||
|
||
test("snapshot member figures are labelled current", async () => {
|
||
router.reset("from=2026-08-01&to=2026-08-31");
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(screen.getByText("Members per rank, current")).toBeInTheDocument();
|
||
expect(screen.getByText("Share of all members, current")).toBeInTheDocument();
|
||
});
|
||
|
||
test("a half-picked range changes neither the URL nor the figures", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
const calls = getDashboard.mock.calls.length;
|
||
|
||
await userEvent.click(screen.getByRole("button", { name: "pick start" }));
|
||
|
||
expect(router.replace).not.toHaveBeenCalled();
|
||
expect(getDashboard).toHaveBeenCalledTimes(calls);
|
||
});
|
||
|
||
test("a whole custom range goes to the URL and is fetched", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
|
||
await userEvent.click(screen.getByRole("button", { name: "pick range" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/?from=2026-09-03&to=2026-09-10");
|
||
await vi.waitFor(() => expect(getDashboard).toHaveBeenLastCalledWith({ from: "2026-09-03", to: "2026-09-10" }));
|
||
expect(screen.getByRole("combobox", { name: "Period" })).toHaveTextContent("Custom range");
|
||
});
|
||
|
||
test("clearing the range returns to the default period", async () => {
|
||
router.reset("from=2026-09-03&to=2026-09-10");
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
|
||
await userEvent.click(screen.getByRole("button", { name: "clear range" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/");
|
||
await vi.waitFor(() => expect(getDashboard).toHaveBeenLastCalledWith({ from: undefined, to: undefined }));
|
||
});
|
||
|
||
test("a rejected period shows the error state with a retry", async () => {
|
||
router.reset("from=2026-09-10&to=2026-09-01");
|
||
getDashboard.mockRejectedValue(new Error("from must not be after to"));
|
||
render(<DashboardPage />);
|
||
expect(await screen.findByRole("alert")).toHaveTextContent("from must not be after to");
|
||
expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();
|
||
});
|
||
|
||
test("a custom range that starts on the 1st but ends mid-month is labelled by its dates", async () => {
|
||
router.reset("from=2026-08-01&to=2026-08-10");
|
||
getDashboard.mockResolvedValue({ ...fixture, from: "2026-08-01", to: "2026-08-10" });
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(screen.getByText("01/08/2026 – 10/08/2026")).toBeInTheDocument();
|
||
});
|
||
|
||
test("the default period (this month to today) is labelled by its month", async () => {
|
||
getDashboard.mockResolvedValue({ ...fixture, from: "2026-09-01", to: "2026-09-29" });
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(screen.getByText("Sep 2026")).toBeInTheDocument();
|
||
});
|
||
|
||
test("navigating to the bare dashboard URL after a custom pick shows This month again", async () => {
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
await userEvent.click(screen.getByRole("button", { name: "pick range" }));
|
||
await vi.waitFor(() => expect(screen.getByRole("combobox", { name: "Period" })).toHaveTextContent("Custom range"));
|
||
|
||
act(() => router.replace("/")); // e.g. the sidebar Dashboard link: same route, component stays mounted
|
||
|
||
await vi.waitFor(() => expect(screen.getByRole("combobox", { name: "Period" })).toHaveTextContent("This month"));
|
||
});
|
||
|
||
test("an event operator without BO_DASHBOARD sees only the Event dashboard, with no selector", async () => {
|
||
auth.state.modules = ["BO_DASHBOARD_EVENT", "BO_POS"];
|
||
render(<DashboardPage />);
|
||
|
||
expect(await screen.findByRole("heading", { name: "Event dashboard stub" })).toBeInTheDocument();
|
||
expect(screen.queryByRole("combobox", { name: "Dashboard" })).not.toBeInTheDocument();
|
||
expect(getDashboard).not.toHaveBeenCalled();
|
||
expect(screen.queryByRole("region", { name: "Key performance indicators" })).not.toBeInTheDocument();
|
||
});
|
||
|
||
test("an admin with both dashboards starts on General and can switch to Event", async () => {
|
||
auth.state.modules = ["BO_DASHBOARD", "BO_DASHBOARD_EVENT"];
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(screen.getByRole("combobox", { name: "Dashboard" })).toHaveTextContent("General");
|
||
|
||
await userEvent.click(screen.getByRole("combobox", { name: "Dashboard" }));
|
||
await userEvent.click(await screen.findByRole("option", { name: "Event" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/?dashboard=event");
|
||
expect(await screen.findByRole("heading", { name: "Event dashboard stub" })).toBeInTheDocument();
|
||
expect(screen.getByRole("combobox", { name: "Dashboard" })).toHaveTextContent("Event");
|
||
});
|
||
|
||
test("switching dashboards drops the General dashboard's period from the URL", async () => {
|
||
auth.state.modules = ["BO_DASHBOARD", "BO_DASHBOARD_EVENT"];
|
||
router.reset("from=2026-08-01&to=2026-08-31");
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
|
||
await userEvent.click(screen.getByRole("combobox", { name: "Dashboard" }));
|
||
await userEvent.click(await screen.findByRole("option", { name: "Event" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/?dashboard=event");
|
||
});
|
||
|
||
test("the chosen dashboard survives a reload, and General clears it from the URL", async () => {
|
||
auth.state.modules = ["BO_DASHBOARD", "BO_DASHBOARD_EVENT"];
|
||
router.reset("dashboard=event");
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
expect(await screen.findByRole("heading", { name: "Event dashboard stub" })).toBeInTheDocument();
|
||
|
||
await userEvent.click(screen.getByRole("combobox", { name: "Dashboard" }));
|
||
await userEvent.click(await screen.findByRole("option", { name: "General" }));
|
||
|
||
expect(router.replace).toHaveBeenLastCalledWith("/");
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
});
|
||
|
||
test("a dashboard the admin is not granted falls back to the default", async () => {
|
||
router.reset("dashboard=event");
|
||
getDashboard.mockResolvedValue(fixture);
|
||
render(<DashboardPage />);
|
||
await screen.findByRole("region", { name: "Key performance indicators" });
|
||
expect(screen.queryByRole("heading", { name: "Event dashboard stub" })).not.toBeInTheDocument();
|
||
expect(screen.queryByRole("combobox", { name: "Dashboard" })).not.toBeInTheDocument();
|
||
});
|