Files
co-lite/solvway-admin-portal/app/network/page.test.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

461 lines
20 KiB
TypeScript

import { describe, test, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AdminMember, AdminSponsorHistoryRow, AdminTreeNode } from "@/app/lib/types";
import { ApiError } from "@/app/lib/clientApi";
import type { MemberSearchComboboxProps } from "@/app/components/members/MemberSearchCombobox";
import NetworkPage from "./page";
// Task 5 wiring tests exercise the network page's use of the combobox, not the
// combobox's own search/debounce behaviour (covered by Task 4's
// MemberSearchCombobox.test.tsx) — so it's replaced with a minimal double: an
// input distinguished by its accessible name (`aria-label`, matching how the
// real component wires accessible naming — see MemberSearchCombobox.tsx),
// where pressing Enter simulates picking a suggestion and calls `onSelect`
// with a synthesized AdminMember for the typed code.
//
// `key={initialQuery}` + `defaultValue={initialQuery}` (Task 10 fix round 1):
// the real component re-syncs its visible value whenever `initialQuery`
// changes to a genuinely new value after mount (see the re-sync effect and
// its own dedicated tests in MemberSearchCombobox.test.tsx) — remounting on
// prop change is this double's equivalent for that same wiring contract,
// so a page-level test can assert the *displayed* value updates when the
// page passes a new prefilled member down (not just that a callback fired
// with the right argument).
vi.mock("@/app/components/members/MemberSearchCombobox", () => ({
MemberSearchCombobox: ({ onSelect, placeholder, initialQuery, "aria-label": ariaLabel }: MemberSearchComboboxProps) => (
<input
key={initialQuery ?? ""}
aria-label={ariaLabel}
placeholder={placeholder}
defaultValue={initialQuery}
onKeyDown={event => {
if (event.key !== "Enter") return;
// The real cmdk-backed combobox owns Enter itself (selects the
// highlighted suggestion) rather than letting it fall through to
// native form submission — match that so this double doesn't
// accidentally submit the surrounding placement-correction <form>
// while a field is still being filled in.
event.preventDefault();
const code = (event.target as HTMLInputElement).value.trim().toUpperCase();
if (!code) return;
onSelect({ memberCode: code, name: code, status: "Y" } as AdminMember);
}}
/>
),
}));
// In-memory router double for useQueryState.
const router = vi.hoisted(() => {
let pathname = "/network";
let search = new URLSearchParams();
const listeners = new Set<() => void>();
const pushed: string[] = [];
return {
pushed,
push: (url: string) => {
pushed.push(url);
},
getPathname: () => pathname,
getSearch: () => search,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
replace: (url: string) => {
const [path, qs] = url.split("?");
pathname = path || pathname;
search = new URLSearchParams(qs ?? "");
listeners.forEach(l => l());
},
reset: () => {
pathname = "/network";
search = new URLSearchParams();
pushed.length = 0;
},
};
});
vi.mock("next/navigation", async () => {
const { useSyncExternalStore } = await import("react");
return {
usePathname: () => useSyncExternalStore(router.subscribe, router.getPathname, router.getPathname),
useSearchParams: () => useSyncExternalStore(router.subscribe, router.getSearch, router.getSearch),
useRouter: () => ({ replace: router.replace, push: router.push }),
};
});
const auth = vi.hoisted(() => ({ hasModule: vi.fn(), loading: false }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ hasModule: auth.hasModule, loading: auth.loading }),
}));
const network = vi.hoisted(() => ({
getNetworkTree: vi.fn(),
getMemberUpline: vi.fn(),
getPlacementHistory: vi.fn(),
}));
vi.mock("@/app/lib/services/network", async () => {
const actual = await vi.importActual<typeof import("@/app/lib/services/network")>(
"@/app/lib/services/network",
);
return {
...actual,
getNetworkTree: (code: string) => network.getNetworkTree(code),
getMemberUpline: (code: string) => network.getMemberUpline(code),
getPlacementHistory: (code: string) => network.getPlacementHistory(code),
};
});
const tree: AdminTreeNode = {
mbid: "BB0100",
member: { memberCode: "BB0100", name: "AINA TAN", rank: "OTTER", status: "Y", dateJoin: "2025-03-01" },
children: [
{
mbid: "BB0101",
member: { memberCode: "BB0101", name: "WEI MING LEE", rank: "SQUIRREL", status: "Y" },
children: [{ mbid: "BB0110", member: { memberCode: "BB0110", name: "NURUL HASSAN" } }],
},
{ mbid: "BB0102", member: { memberCode: "BB0102", name: "SITI AMINAH", rank: "M", status: "S" } },
],
};
const historyRows: AdminSponsorHistoryRow[] = [
{
id: 3,
memberCode: "BB0100",
memberName: "AINA TAN",
oldSponsorCode: "BB0001",
newSponsorCode: "BB0002",
doneBy: "admin1",
createDateTime: "2026-08-01T10:30:00",
},
];
function renderPage() {
return render(<NetworkPage />);
}
beforeEach(() => {
router.reset();
auth.hasModule.mockReset();
auth.hasModule.mockReturnValue(true);
auth.loading = false;
network.getNetworkTree.mockReset();
network.getNetworkTree.mockResolvedValue(tree);
network.getMemberUpline.mockReset();
network.getMemberUpline.mockResolvedValue([tree.children![0]]);
network.getPlacementHistory.mockReset();
network.getPlacementHistory.mockResolvedValue({ content: historyRows, totalElements: 1 });
});
test("loads the real tree from a chosen root with labelled rank/status and downline counts", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
expect(await screen.findByText("AINA TAN")).toBeInTheDocument();
expect(screen.getByText("WEI MING LEE")).toBeInTheDocument();
expect(screen.getByText("Otter")).toBeInTheDocument();
expect(screen.getByText("Squirrel")).toBeInTheDocument();
expect(screen.getByText("Suspended")).toBeInTheDocument();
expect(screen.getByText("2 direct · 3 total")).toBeInTheDocument();
expect(network.getNetworkTree).toHaveBeenCalledWith("BB0100");
expect(screen.queryByText("OTTER")).toBeNull();
});
test("shows the upline chain", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Upline" }));
expect(await screen.findByText("WEI MING LEE")).toBeInTheDocument();
});
test("shows the dated placement history", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Placement history" }));
expect(await screen.findByText("1 Aug 2026, 10:30")).toBeInTheDocument();
expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
expect(screen.getByText("BB0001")).toBeInTheDocument();
expect(screen.getByText("BB0002")).toBeInTheDocument();
});
// fit-admin-listing-pages: member, old sponsor and new sponsor are member cells, not "code · name".
test("shows each placement-history member as a code linking to the member, with the name below", async () => {
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Placement history" }));
const row = (await screen.findByText("1 Aug 2026, 10:30")).closest("tr")!;
expect(within(row).getByRole("link", { name: "BB0100" })).toHaveAttribute("href", "/members/BB0100");
expect(within(row).getByText("AINA TAN")).toBeInTheDocument();
expect(within(row).getByRole("link", { name: "BB0001" })).toHaveAttribute("href", "/members/BB0001");
expect(within(row).getByRole("link", { name: "BB0002" })).toHaveAttribute("href", "/members/BB0002");
expect(within(row).queryByText(/·/)).toBeNull();
});
test("shows each move's reason, with a dash for a blank or placeholder remark (show-placement-remarks)", async () => {
network.getPlacementHistory.mockResolvedValue({
content: [
{ ...historyRows[0], id: 4, remarks: "Giraffe promotion — qualifying recruit passed up (BB0009)" },
{ ...historyRows[0], id: 5, remarks: "-", createDateTime: "2026-08-02T09:00:00" },
{ ...historyRows[0], id: 6, remarks: "", createDateTime: "2026-08-03T09:00:00" },
{ ...historyRows[0], id: 7, remarks: " ", createDateTime: "2026-08-04T09:00:00" },
],
totalElements: 4,
});
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Placement history" }));
const table = await screen.findByRole("table", { name: "Placement history" });
expect(within(table).getByRole("columnheader", { name: "Reason" })).toBeInTheDocument();
expect(within(table).getByText("Giraffe promotion — qualifying recruit passed up (BB0009)")).toBeInTheDocument();
// A long reason wraps instead of widening the table (the shared cell is nowrap).
expect(within(table).getByText("Giraffe promotion — qualifying recruit passed up (BB0009)")).toHaveClass("whitespace-normal");
const rows = within(table).getAllByRole("row").slice(1);
expect(rows).toHaveLength(4);
for (const row of rows.slice(1)) {
const cells = within(row).getAllByRole("cell");
expect(cells[cells.length - 1]).toHaveTextContent(/^—$/);
}
});
test("choosing a root member sets the root query param and loads its tree", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
expect(await screen.findByText("AINA TAN")).toBeInTheDocument();
expect(network.getNetworkTree).toHaveBeenCalledWith("BB0100");
expect(router.getSearch().get("root")).toBe("BB0100");
});
// BABYBOO-43: placement is corrected on /rank-referral, never on the network page.
test("the network page has no placement-correction form", async () => {
const user = userEvent.setup();
renderPage();
expect(screen.queryByRole("heading", { name: "Correct placement" })).toBeNull();
expect(screen.queryByLabelText("New sponsor code")).toBeNull();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
await screen.findByText("AINA TAN");
expect(screen.queryByRole("heading", { name: "Correct placement" })).toBeNull();
expect(screen.queryByRole("button", { name: "Correct placement" })).toBeNull();
expect(screen.queryByLabelText("New sponsor code")).toBeNull();
});
test("a user without BO_NETWORK sees the not-authorised state and no data is fetched", async () => {
auth.hasModule.mockReturnValue(false);
renderPage();
expect(await screen.findByTestId("not-authorized")).toBeInTheDocument();
expect(network.getNetworkTree).not.toHaveBeenCalled();
});
// Task 10 — per-node inline actions menu, wired through the chart to the
// page's existing root-select and placement-correction state.
describe("Task 10 — per-node inline actions", () => {
test("'Set as tree root' from a node's actions menu updates the root param and reloads the tree at that node", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Chart" }));
await user.click(screen.getByRole("button", { name: "Actions for WEI MING LEE" }));
await user.click(screen.getByRole("menuitem", { name: "Set as tree root" }));
await waitFor(() => expect(network.getNetworkTree).toHaveBeenCalledWith("BB0101"));
});
test("'Correct placement' from a node's actions menu opens the referral tab of Rank & referral for that member", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Chart" }));
await user.click(screen.getByRole("button", { name: "Actions for WEI MING LEE" }));
await user.click(screen.getByRole("menuitem", { name: "Correct placement" }));
expect(router.pushed).toEqual(["/rank-referral?tab=referral&member=BB0101"]);
});
test("'Correct placement' is not offered without BO_RANK_REFERRAL", async () => {
auth.hasModule.mockImplementation((name: string) => name !== "BO_RANK_REFERRAL");
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Chart" }));
await user.click(screen.getByRole("button", { name: "Actions for WEI MING LEE" }));
expect(screen.getByRole("menuitem", { name: "Set as tree root" })).toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: "Correct placement" })).toBeNull();
});
test("'View full profile' from a node's actions menu links to the member's profile page", async () => {
const user = userEvent.setup();
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Chart" }));
await user.click(screen.getByRole("button", { name: "Actions for WEI MING LEE" }));
expect(screen.getByRole("menuitem", { name: "View full profile" })).toHaveAttribute(
"href",
"/members/BB0101",
);
});
test("'Copy member code' from a node's actions menu copies that member's code", async () => {
// user-event installs its own clipboard stub on navigator.clipboard
// during setup(), which would otherwise clobber this mock — so the mock
// must be applied AFTER setup(), before rendering.
const user = userEvent.setup();
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, "clipboard", {
value: { writeText },
configurable: true,
writable: true,
});
renderPage();
const rootInput = screen.getByLabelText("Tree root (member code)");
await user.type(rootInput, "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Chart" }));
await user.click(screen.getByRole("button", { name: "Actions for WEI MING LEE" }));
await user.click(screen.getByRole("menuitem", { name: "Copy member code" }));
expect(writeText).toHaveBeenCalledWith("BB0101");
});
});
// Task 11 — state polish. The redesign (Tasks 5/8/9/10) didn't change how the
// page picks between loading/empty/no-match/error, so these lock the existing,
// already-correct behaviour against regression rather than introduce new UI.
describe("Task 11 — state polish (regression lock)", () => {
test("shows the choose-a-root empty state before any root is picked, with no tabs rendered", () => {
renderPage();
expect(screen.getByText("Enter a member code to load the tree")).toBeInTheDocument();
expect(screen.queryByRole("tab", { name: "Tree" })).toBeNull();
expect(network.getNetworkTree).not.toHaveBeenCalled();
});
test("shows loading skeletons while the tree/upline/history are being fetched, and clears them once loaded", async () => {
let resolveTree!: (root: AdminTreeNode) => void;
network.getNetworkTree.mockReturnValue(
new Promise<AdminTreeNode>(resolve => {
resolveTree = resolve;
}),
);
const user = userEvent.setup();
const { container } = renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
expect(container.querySelectorAll('[data-slot="skeleton"]').length).toBeGreaterThan(0);
expect(screen.queryByText("AINA TAN")).toBeNull();
resolveTree(tree);
expect(await screen.findByText("AINA TAN")).toBeInTheDocument();
expect(container.querySelectorAll('[data-slot="skeleton"]').length).toBe(0);
});
test("shows the no-upline empty state when the root has no upline entries", async () => {
network.getMemberUpline.mockResolvedValueOnce([]);
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Upline" }));
expect(await screen.findByText("This member has no upline entries")).toBeInTheDocument();
});
test("shows the no-placement-history empty state when there are no recorded changes", async () => {
network.getPlacementHistory.mockResolvedValueOnce({ content: [], totalElements: 0 });
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.click(screen.getByRole("tab", { name: "Placement history" }));
expect(
await screen.findByText("No placement changes recorded for this member"),
).toBeInTheDocument();
});
test("shows the no-match empty state for a search term that matches no member, in place of the tab content", async () => {
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
await screen.findByText("AINA TAN");
await user.type(screen.getByLabelText("Search members"), "zzznotfound");
expect(await screen.findByText("No member matches “zzznotfound”")).toBeInTheDocument();
expect(screen.queryByText("AINA TAN")).toBeNull();
});
test("shows an error state with a working retry when the root member is not found (404), instead of a blank page", async () => {
network.getNetworkTree.mockRejectedValueOnce(new ApiError("Not found", 404));
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "ZZ9999{Enter}");
expect(
await screen.findByText("No member found for “ZZ9999”"),
).toBeInTheDocument();
expect(screen.getByRole("alert")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Retry" }));
expect(network.getNetworkTree).toHaveBeenCalledTimes(2);
expect(await screen.findByText("AINA TAN")).toBeInTheDocument();
});
test("shows an error state with a working retry for a generic fetch failure", async () => {
network.getNetworkTree.mockRejectedValueOnce(new Error("Network unreachable"));
const user = userEvent.setup();
renderPage();
await user.type(screen.getByLabelText("Tree root (member code)"), "BB0100{Enter}");
expect(await screen.findByText("Network unreachable")).toBeInTheDocument();
expect(screen.getByRole("alert")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Retry" }));
expect(network.getNetworkTree).toHaveBeenCalledTimes(2);
expect(await screen.findByText("AINA TAN")).toBeInTheDocument();
});
});