Files
co-lite/solvway-admin-portal/app/reports/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

487 lines
22 KiB
TypeScript

import { test, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { RewardsReport, SalesReport } from "@/app/lib/services/adminDashboard";
import { periodRange } from "@/app/lib/malaysiaPeriod";
import { xlsxRows } from "@/test/readXlsx";
import ReportsPage from "./page";
// In-memory router double — see app/members/page.test.tsx for why this is
// needed instead of the real next/navigation hooks under jsdom.
const router = vi.hoisted(() => {
let pathname = "/reports";
let search = new URLSearchParams();
const listeners = new Set<() => void>();
return {
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: (qs = "") => {
pathname = "/reports";
search = new URLSearchParams(qs);
},
};
});
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 }),
};
});
const getSalesReport = vi.fn();
const getRewardsReport = vi.fn();
const downloadXlsx = 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,
getSalesReport: (p: unknown) => getSalesReport(p),
getRewardsReport: (p: unknown) => getRewardsReport(p),
};
});
vi.mock("@/app/lib/xlsx", async () => {
const actual = await vi.importActual<typeof import("@/app/lib/xlsx")>("@/app/lib/xlsx");
return { ...actual, downloadXlsx: (filename: string, bytes: Uint8Array) => downloadXlsx(filename, bytes) };
});
const order = (documentNo: string, grandTotal: string, saleChannel: string, buyerCode: string | null, sourcePlatform = "CP") => ({
id: documentNo,
uuid: `u-${documentNo}`,
documentNo,
transactionDateTime: "2026-09-29T00:10:00",
buyerCode,
buyerName: null as string | null,
buyerEmail: null as string | null,
buyerType: buyerCode ? "M" : "G",
grandTotal,
totalDiscount: "0.0",
currencySymbol: "RM",
status: "Y",
saleChannel,
sourcePlatform,
eventId: null,
fulfilmentMode: "PICKUP",
});
function salesReport(rows = [order("IN0000071", "35.0", "EVENT", "MY1"), order("IN0000072", "100.5", "NORMAL", null)], totalElements = rows.length): SalesReport {
return {
orders: { content: rows, number: 0, size: 10, totalElements, totalPages: Math.ceil(totalElements / 10) },
periodRevenue: 135.5,
periodOrders: totalElements,
} as unknown as SalesReport;
}
const credit = (memberCode: string, rewardCode: string, amount: number) => ({
date: "2026-09-29T00:05:00",
memberCode,
memberName: `Name ${memberCode}`,
rewardCode,
walletType: rewardCode.endsWith("APPLE") ? "APPLE" : "ACORN",
amount,
sourceMemberCode: "SRC1",
});
function rewardsReport(rows = [credit("MY1", "SELF_ACORN", 200), credit("MY2", "SPONSOR_APPLE", 50)], totalElements = rows.length): RewardsReport {
return {
credits: { content: rows, number: 0, size: 10, totalElements, totalPages: 1 },
totals: [
{ rewardCode: "SELF_ACORN", walletType: "ACORN", total: 200, count: 1 },
{ rewardCode: "SPONSOR_APPLE", walletType: "APPLE", total: 50, count: 1 },
],
};
}
beforeEach(() => {
router.reset();
getSalesReport.mockReset();
getRewardsReport.mockReset();
downloadXlsx.mockReset();
getSalesReport.mockResolvedValue(salesReport());
getRewardsReport.mockResolvedValue(rewardsReport());
});
function renderPage() {
return render(<ReportsPage />);
}
const salesPanel = () => screen.getByRole("tabpanel", { name: /^sales/i });
const rewardsPanel = () => screen.getByRole("tabpanel", { name: /^rewards/i });
test("offers Sales and Rewards tabs, and no Commissions tab", () => {
renderPage();
expect(screen.getByRole("tab", { name: "Sales" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "Rewards" })).toBeInTheDocument();
expect(screen.queryByRole("tab", { name: /commissions/i })).not.toBeInTheDocument();
});
test("sales defaults to this month in Malaysia time and lists live settled orders with a total", async () => {
renderPage();
expect(await within(salesPanel()).findByText("IN0000071")).toBeInTheDocument();
expect(within(salesPanel()).getByText("IN0000072")).toBeInTheDocument();
expect(within(salesPanel()).getByText("Event")).toBeInTheDocument();
expect(within(salesPanel()).getByText("Web")).toBeInTheDocument();
expect(within(salesPanel()).getByText("Guest")).toBeInTheDocument(); // no buyer code
expect(within(salesPanel()).getByText("RM 135.50")).toBeInTheDocument(); // period total, not just this page
const month = periodRange("month");
expect(getSalesReport).toHaveBeenCalledWith({ page: 0, size: 20, from: month.from, to: month.to });
});
// fit-admin-listing-pages: the Buyer column is a member cell, like every member column.
test("shows the buyer as the member code linking to the member above the name, and a guest as Guest above the email", async () => {
getSalesReport.mockResolvedValue(salesReport([
{ ...order("IN0000081", "10.0", "NORMAL", "MY3619941"), buyerName: "QA TESTER" },
{ ...order("IN0000082", "10.0", "NORMAL", null), buyerEmail: "amy@example.my" },
]));
renderPage();
const member = (await within(salesPanel()).findByText("IN0000081")).closest("tr")!;
expect(within(member).getByRole("link", { name: "MY3619941" })).toHaveAttribute("href", "/members/MY3619941");
expect(within(member).getByText("QA TESTER")).toBeInTheDocument();
const guest = within(salesPanel()).getByText("IN0000082").closest("tr")!;
expect(within(guest).getByText("Guest")).toBeInTheDocument();
expect(within(guest).getByText("amy@example.my")).toBeInTheDocument();
});
test("changing the period re-queries with that period's Malaysia-time bounds", async () => {
renderPage();
await within(salesPanel()).findByText("IN0000071");
const user = userEvent.setup();
await user.click(within(salesPanel()).getByRole("combobox", { name: "Period" }));
await user.click(screen.getByRole("option", { name: "Last 30 days" }));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith({ page: 0, size: 20, ...periodRange("30d") }));
await user.click(within(salesPanel()).getByRole("combobox", { name: "Period" }));
await user.click(screen.getByRole("option", { name: "All time" }));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith({ page: 0, size: 20, from: "", to: "" }));
});
test("pages through the settled orders", async () => {
getSalesReport.mockResolvedValue(salesReport([order("IN0000071", "35.0", "EVENT", "MY1")], 25));
renderPage();
await within(salesPanel()).findByText("IN0000071");
await userEvent.setup().click(within(salesPanel()).getByRole("button", { name: /next/i }));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith(expect.objectContaining({ page: 1, size: 20 })));
});
test("exporting sales downloads the whole filtered set, not just the visible page", async () => {
const all = Array.from({ length: 25 }, (_, i) => order(`IN${1000 + i}`, "10.0", "NORMAL", "MY1"));
getSalesReport.mockReset();
getSalesReport
.mockResolvedValueOnce(salesReport(all.slice(0, 10), 25))
.mockResolvedValueOnce(salesReport(all, 25));
renderPage();
await within(salesPanel()).findByText("IN1000");
await userEvent.setup().click(within(salesPanel()).getByRole("button", { name: /export \.xlsx/i }));
await waitFor(() => expect(downloadXlsx).toHaveBeenCalledTimes(1));
const exportArgs = getSalesReport.mock.calls[getSalesReport.mock.calls.length - 1][0] as { size: number; page: number };
expect(exportArgs.page).toBe(0);
expect(exportArgs.size).toBeGreaterThanOrEqual(25);
const [filename, bytes] = downloadXlsx.mock.calls[0] as [string, Uint8Array];
expect(filename).toBe("sales-report.xlsx");
const rows = await xlsxRows(bytes);
expect(rows[0]).toEqual(["Order no", "Date", "Buyer", "Channel", "Amount", "Refunded"]);
expect(rows).toHaveLength(26);
expect(rows[1][0]).toBe("IN1000");
});
test("on-screen dates use the shared format, the title is an h1, and unrefunded cells show a dash", async () => {
getSalesReport.mockResolvedValue({ ...salesReport(), refunds: { "u-IN0000072": 39 } });
renderPage();
expect(screen.getByRole("heading", { level: 1, name: "Reports" })).toBeInTheDocument();
const other = (await within(salesPanel()).findByText("IN0000071")).closest("tr") as HTMLElement;
expect(within(other).getByText("29 Sep 2026, 00:10")).toBeInTheDocument();
expect(within(other).getByText("—")).toBeInTheDocument();
});
test("a refunded order shows its refunded amount in the row and in the export", async () => {
getSalesReport.mockResolvedValue({ ...salesReport(), refunds: { "u-IN0000072": 39 } });
renderPage();
const row = (await within(salesPanel()).findByText("IN0000072")).closest("tr") as HTMLElement;
expect(within(row).getByText("RM 39.00")).toBeInTheDocument();
const other = within(salesPanel()).getByText("IN0000071").closest("tr") as HTMLElement;
expect(within(other).queryByText("RM 39.00")).not.toBeInTheDocument();
await userEvent.setup().click(within(salesPanel()).getByRole("button", { name: /export \.xlsx/i }));
await waitFor(() => expect(downloadXlsx).toHaveBeenCalledTimes(1));
const rows = await xlsxRows((downloadXlsx.mock.calls[0] as [string, Uint8Array])[1]);
expect(rows[2][0]).toBe("IN0000072");
expect(rows[2][5]).toBe(39);
});
test("an export larger than the cap asks for a narrower period instead of one unbounded request", async () => {
getSalesReport.mockReset();
getSalesReport.mockResolvedValue(salesReport(undefined, 10_001));
renderPage();
await within(salesPanel()).findByText("IN0000071");
await userEvent.setup().click(within(salesPanel()).getByRole("button", { name: /export \.xlsx/i }));
expect(await within(salesPanel()).findByText(/narrow the period/i)).toBeInTheDocument();
expect(getSalesReport).toHaveBeenCalledTimes(1);
expect(downloadXlsx).not.toHaveBeenCalled();
});
test("the sales export is disabled with no rows", async () => {
getSalesReport.mockResolvedValue(salesReport([], 0));
renderPage();
expect(await within(salesPanel()).findByText("No settled orders in this period")).toBeInTheDocument();
expect(within(salesPanel()).getByRole("button", { name: /export \.xlsx/i })).toBeDisabled();
});
test("a failed sales export shows an error and downloads nothing", async () => {
getSalesReport.mockReset();
getSalesReport.mockResolvedValueOnce(salesReport()).mockRejectedValueOnce(new Error("Export failed"));
renderPage();
await within(salesPanel()).findByText("IN0000071");
await userEvent.setup().click(within(salesPanel()).getByRole("button", { name: /export \.xlsx/i }));
expect(await within(salesPanel()).findByText("Export failed")).toBeInTheDocument();
expect(downloadXlsx).not.toHaveBeenCalled();
});
test("shows a visible error when the sales report cannot load", async () => {
getSalesReport.mockRejectedValue(new Error("Network error"));
renderPage();
expect(await screen.findByText("Network error")).toBeInTheDocument();
expect(screen.getByRole("alert")).toBeInTheDocument();
});
test("the Rewards tab lists reward credits with per-type totals", async () => {
renderPage();
await userEvent.setup().click(screen.getByRole("tab", { name: "Rewards" }));
const panel = rewardsPanel();
expect(await within(panel).findByText("Name MY1")).toBeInTheDocument();
expect(within(panel).getAllByText("Self Acorn").length).toBeGreaterThan(0);
expect(within(panel).getAllByText("Sponsor Apple").length).toBeGreaterThan(0);
expect(within(panel).getAllByText("200.00").length).toBeGreaterThan(0); // SELF_ACORN total
const month = periodRange("month");
expect(getRewardsReport).toHaveBeenCalledWith({ page: 0, size: 20, from: month.from, to: month.to, rewardCode: undefined });
});
test("filtering the Rewards tab by type sends the reward code", async () => {
renderPage();
const user = userEvent.setup();
await user.click(screen.getByRole("tab", { name: "Rewards" }));
await within(rewardsPanel()).findByText("Name MY1");
await user.click(within(rewardsPanel()).getByRole("combobox", { name: "Reward type" }));
await user.click(screen.getByRole("option", { name: "Self Acorn" }));
await waitFor(() =>
expect(getRewardsReport).toHaveBeenLastCalledWith(expect.objectContaining({ rewardCode: "SELF_ACORN", page: 0 })),
);
});
test("exporting rewards downloads the whole filtered set", async () => {
const all = Array.from({ length: 12 }, (_, i) => credit(`MY${i}`, "SELF_ACORN", 10));
getRewardsReport.mockReset();
getRewardsReport
.mockResolvedValueOnce(rewardsReport(all.slice(0, 10), 12))
.mockResolvedValueOnce(rewardsReport(all, 12));
renderPage();
const user = userEvent.setup();
await user.click(screen.getByRole("tab", { name: "Rewards" }));
await within(rewardsPanel()).findByText("Name MY0");
await user.click(within(rewardsPanel()).getByRole("button", { name: /export \.xlsx/i }));
await waitFor(() => expect(downloadXlsx).toHaveBeenCalledTimes(1));
const [filename, bytes] = downloadXlsx.mock.calls[0] as [string, Uint8Array];
expect(filename).toBe("rewards-report.xlsx");
const rows = await xlsxRows(bytes);
expect(rows[0]).toEqual(["Date", "Member code", "Member", "Reward type", "Amount", "Source"]);
expect(rows).toHaveLength(13);
});
test("the period lives in the URL under the tab's prefix and the bar labels its fields", async () => {
renderPage();
await within(salesPanel()).findByText("IN0000071");
const user = userEvent.setup();
expect(within(salesPanel()).getByText("Period", { selector: "span" })).toBeInTheDocument();
expect(within(salesPanel()).getByText("Date", { selector: "span" })).toBeInTheDocument();
await user.click(within(salesPanel()).getByRole("combobox", { name: "Period" }));
await user.click(screen.getByRole("option", { name: "Last 30 days" }));
await waitFor(() => expect(router.getSearch().get("sales.preset")).toBe("30d"));
expect(router.getSearch().get("page")).toBeNull();
});
test("a period in the URL populates the control and the request on mount", async () => {
router.reset("sales.preset=30d");
renderPage();
await within(salesPanel()).findByText("IN0000071");
expect(getSalesReport).toHaveBeenCalledWith({ page: 0, size: 20, ...periodRange("30d") });
expect(within(salesPanel()).getByRole("combobox", { name: "Period" })).toHaveTextContent("Last 30 days");
});
test("a custom range in the URL is sent as-is", async () => {
router.reset("sales.preset=custom&sales.from=2026-09-01&sales.to=2026-09-15");
renderPage();
await within(salesPanel()).findByText("IN0000071");
expect(getSalesReport).toHaveBeenCalledWith({ page: 0, size: 20, from: "2026-09-01", to: "2026-09-15" });
});
test("Clear filters returns the Rewards tab to this month and drops its keys", async () => {
router.reset("tab=rewards&rewards.preset=all&rewards.reward=SELF_ACORN");
renderPage();
await within(rewardsPanel()).findByText("Name MY1");
expect(getRewardsReport).toHaveBeenLastCalledWith(expect.objectContaining({ from: "", to: "", rewardCode: "SELF_ACORN" }));
await userEvent.setup().click(within(rewardsPanel()).getByRole("button", { name: /clear filters/i }));
const month = periodRange("month");
await waitFor(() => expect(getRewardsReport).toHaveBeenLastCalledWith({ page: 0, size: 20, from: month.from, to: month.to, rewardCode: undefined }));
expect(router.getSearch().toString()).toBe("tab=rewards");
});
test("choosing Custom range keeps the current period instead of clearing it", async () => {
renderPage();
await within(salesPanel()).findByText("IN0000071");
const user = userEvent.setup();
const month = periodRange("month");
await user.click(within(salesPanel()).getByRole("combobox", { name: "Period" }));
await user.click(screen.getByRole("option", { name: "Custom range" }));
await waitFor(() => expect(router.getSearch().get("sales.preset")).toBe("custom"));
expect(router.getSearch().get("sales.from")).toBe(month.from);
expect(router.getSearch().get("sales.to")).toBe(month.to);
});
test("an unknown preset in the URL falls back to this month", async () => {
router.reset("sales.preset=bogus");
renderPage();
await within(salesPanel()).findByText("IN0000071");
expect(getSalesReport).toHaveBeenLastCalledWith({ page: 0, size: 20, ...periodRange("month") });
});
// fit-admin-listing-pages: the member is one Wallet-style cell — code on top (linking to the member), name below.
test("the Rewards tab shows one Member column, code above name", async () => {
renderPage();
await userEvent.setup().click(screen.getByRole("tab", { name: "Rewards" }));
const panel = rewardsPanel();
const link = await within(panel).findByRole("link", { name: "MY1" });
expect(link).toHaveAttribute("href", "/members/MY1");
expect(within(link.closest("td")!).getByText("Name MY1")).toBeInTheDocument();
const headers = within(panel).getAllByRole("columnheader").map(h => h.textContent?.trim());
expect(headers).toContain("Member");
expect(headers).not.toContain("Member code");
});
// ─── BABYBOO-54: Sales report header sorting ──────────────────────────────────
// Assumes useTableSort("sales.") (the tab's URL prefix); the Date column (id "date") must send the backend key transactionDateTime.
test("sales report: Order no, Date and Refunded headers sort server-side (task 2.6)", async () => {
const user = userEvent.setup();
renderPage();
await within(salesPanel()).findByText("IN0000071");
getSalesReport.mockClear();
await user.click(within(salesPanel()).getByRole("button", { name: "Order no" }));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: "documentNo", sortDir: "asc" })));
expect(router.getSearch().get("sales.sortBy")).toBe("documentNo");
await user.click(within(salesPanel()).getByRole("button", { name: "Date" }));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: "transactionDateTime", sortDir: "asc" })));
await user.click(within(salesPanel()).getByRole("button", { name: "Refunded" }));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: "refunded", sortDir: "asc" })));
expect(router.getSearch().get("sales.sortBy")).toBe("refunded");
});
// ─── BABYBOO-54 B2: Rewards tab header sorting (URL prefix "rewards.") ─────────
test.each([
["Date", "date"],
["Member", "member"],
["Reward type", "type"],
["Amount", "amount"],
["Source", "source"],
])("Rewards tab: clicking %s sorts server-side by %s, then desc", async (header, key) => {
const user = userEvent.setup();
renderPage();
await user.click(screen.getByRole("tab", { name: "Rewards" }));
await within(rewardsPanel()).findByText("Name MY1");
const btn = () => within(within(rewardsPanel()).getByRole("table")).getByRole("button", { name: header });
await user.click(btn());
await waitFor(() => expect(getRewardsReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "asc", page: 0 })));
expect(router.getSearch().get("rewards.sortBy")).toBe(key);
await user.click(btn());
await waitFor(() => expect(getRewardsReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "desc" })));
});
test("Rewards tab: changing the sort returns to page 1", async () => {
router.reset("tab=rewards&rewards.page=2");
const user = userEvent.setup();
renderPage();
await within(rewardsPanel()).findByText("Name MY1");
await user.click(within(within(rewardsPanel()).getByRole("table")).getByRole("button", { name: "Amount" }));
await waitFor(() => expect(getRewardsReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: "amount", page: 0 })));
expect(router.getSearch().has("rewards.page")).toBe(false);
});
// ─── BABYBOO-54 task 1.1: Sales report Buyer / Channel / Amount sort ───────────
// Buyer sends the listing's customer key, Channel the type key, Amount the field amountOf() shows (grandTotal).
test.each([
["Buyer", "customer"],
["Channel", "type"],
["Amount", "grandTotal"],
])("sales report: clicking %s sorts server-side by %s", async (header, key) => {
const user = userEvent.setup();
renderPage();
await within(salesPanel()).findByText("IN0000071");
getSalesReport.mockClear();
await user.click(within(within(salesPanel()).getByRole("columnheader", { name: new RegExp(`^${header}`) })).getByRole("button"));
await waitFor(() => expect(getSalesReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "asc" })));
expect(router.getSearch().get("sales.sortBy")).toBe(key);
});
// ─── dashboard-channel-split 3.2: channel column uses the Sales listing's order types ───
test("the Sales channel column uses the listing's order types, in the table and the export", async () => {
getSalesReport.mockResolvedValue(
salesReport([
order("IN-OUT", "10.0", "OUTLET", null, "BO"),
order("IN-BO", "20.0", "NORMAL", null, "BO"),
order("IN-CP", "30.0", "NORMAL", null, "CP"),
]),
);
renderPage();
const cell = async (no: string) => (await within(salesPanel()).findByText(no)).closest("tr") as HTMLElement;
expect(within(await cell("IN-OUT")).getByText("Outlet")).toBeInTheDocument();
expect(within(await cell("IN-OUT")).queryByText("Counter")).not.toBeInTheDocument();
expect(within(await cell("IN-BO")).getByText("Counter")).toBeInTheDocument();
expect(within(await cell("IN-CP")).getByText("Web")).toBeInTheDocument();
await userEvent.setup().click(within(salesPanel()).getByRole("button", { name: /export \.xlsx/i }));
await waitFor(() => expect(downloadXlsx).toHaveBeenCalledTimes(1));
const rows = await xlsxRows((downloadXlsx.mock.calls[0] as [string, Uint8Array])[1]);
expect(rows.slice(1).map(r => r[3])).toEqual(["Outlet", "Counter", "Web"]);
});