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

222 lines
9.7 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 { SalesItemsReport } from "@/app/lib/services/adminDashboard";
import { periodRange } from "@/app/lib/malaysiaPeriod";
import { xlsxRows } from "@/test/readXlsx";
import ReportsPage from "./page";
// add-sku-supplier: the Sales by item tab lists settled order lines per component SKU, filterable by supplier.
// 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 getSalesItemsReport = 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: vi.fn().mockResolvedValue({ orders: { content: [], totalElements: 0 }, periodRevenue: 0, periodOrders: 0 }),
getRewardsReport: vi.fn().mockResolvedValue({ credits: { content: [], totalElements: 0 }, totals: [] }),
getSalesItemsReport: (p: unknown) => getSalesItemsReport(p),
};
});
vi.mock("@/app/lib/services/adminCatalog", () => ({
listCatalogRows: vi.fn().mockResolvedValue([
{ id: "1", code: "SUP01", name: "Acme Baby", status: "Y" },
{ id: "2", code: "SUP02", name: "Old Co", status: "N" },
]),
}));
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 line = (lineId: number, skuVariationCode: string, supplierCode: string | null, bundle = false, saleChannel = "NORMAL", sourcePlatform = "CP") => ({
lineId,
transactionDateTime: "2026-10-12T14:36:05",
documentNo: `IN${lineId}`,
saleChannel,
sourcePlatform,
productCode: "ZZQA-CAT-1",
productName: "Cat tee",
skuVariationCode,
supplierId: supplierCode ? 1 : null,
supplierCode,
supplierName: supplierCode ? "Acme Baby" : null,
qty: 2,
amount: 119.8,
bundle,
});
const report = (rows = [line(192, "ZZQA-CAT-1-RED", "SUP01"), line(193, "KIT-SOCK", null, true)], totalElements = rows.length): SalesItemsReport =>
({ content: rows, totalElements });
beforeEach(() => {
router.reset("tab=items");
getSalesItemsReport.mockReset();
downloadXlsx.mockReset();
getSalesItemsReport.mockResolvedValue(report());
});
const panel = () => screen.getByRole("tabpanel", { name: /sales by item/i });
test("offers a Sales by item tab that lists lines of this month with their SKU and supplier", async () => {
render(<ReportsPage />);
expect(screen.getByRole("tab", { name: "Sales by item" })).toBeInTheDocument();
// Qty is SKU units; a bundle's line amount repeats on each component row, so it is labelled as the line's.
expect(await within(panel()).findByRole("columnheader", { name: "Line amount" })).toBeInTheDocument();
const row = (await within(panel()).findByText("ZZQA-CAT-1-RED")).closest("tr") as HTMLElement;
expect(within(row).getByText("IN192")).toBeInTheDocument();
expect(within(row).getByText("SUP01 · Acme Baby")).toBeInTheDocument();
expect(within(row).getByText("RM 119.80")).toBeInTheDocument();
const bundleRow = within(panel()).getByText("KIT-SOCK").closest("tr") as HTMLElement;
expect(within(bundleRow).getByText("Bundle")).toBeInTheDocument();
expect(within(bundleRow).getByText("—")).toBeInTheDocument();
const month = periodRange("month");
expect(getSalesItemsReport).toHaveBeenCalledWith({ page: 0, size: 20, from: month.from, to: month.to, supplierId: undefined });
});
test("filters by supplier, including an inactive one", async () => {
render(<ReportsPage />);
await within(panel()).findByText("ZZQA-CAT-1-RED");
const user = userEvent.setup();
await user.click(within(panel()).getByRole("combobox", { name: "Supplier" }));
expect(await screen.findByRole("option", { name: "SUP02 · Old Co (inactive)" })).toBeInTheDocument();
await user.click(screen.getByRole("option", { name: "SUP01 · Acme Baby" }));
await waitFor(() => expect(getSalesItemsReport).toHaveBeenLastCalledWith(expect.objectContaining({ page: 0, supplierId: "1" })));
});
test("exports every line of the filtered set", async () => {
render(<ReportsPage />);
await within(panel()).findByText("ZZQA-CAT-1-RED");
await userEvent.setup().click(within(panel()).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("sales-by-item.xlsx");
const rows = await xlsxRows(bytes);
expect(rows[0]).toEqual(["Date", "Order no", "Channel", "Item code", "Item", "SKU", "Supplier code", "Supplier", "Qty", "Line amount", "Bundle"]);
expect(rows).toHaveLength(3);
expect(rows[1]).toEqual(["2026-10-12 14:36", "IN192", "Web", "ZZQA-CAT-1", "Cat tee", "ZZQA-CAT-1-RED", "SUP01", "Acme Baby", 2, 119.8, "No"]);
expect(rows[2][10]).toBe("Yes");
});
// add-sku-barcodes polish: the item code sits above the item name so the table fits a 1280px screen.
test("stacks the item code over its name", async () => {
render(<ReportsPage />);
const row = (await within(panel()).findByText("ZZQA-CAT-1-RED")).closest("tr") as HTMLElement;
expect(within(row).getByText("ZZQA-CAT-1")).toBeInTheDocument();
expect(within(row).getByText("Cat tee")).toBeInTheDocument();
});
// ─── BABYBOO-54 B3: Sales by item header sorting (URL prefix "items.") ────────
test.each([
["Date", "date"],
["Order no", "documentNo"],
["Channel", "channel"],
["Item", "item"],
["SKU", "sku"],
["Supplier", "supplier"],
["Qty", "qty"],
["Line amount", "amount"],
])("Sales by item: clicking %s sorts server-side by %s, then desc", async (header, key) => {
const user = userEvent.setup();
render(<ReportsPage />);
await within(panel()).findByText("ZZQA-CAT-1-RED");
getSalesItemsReport.mockClear();
await user.click(within(panel()).getByRole("button", { name: header }));
await waitFor(() => expect(getSalesItemsReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "asc", page: 0 })));
expect(router.getSearch().get("items.sortBy")).toBe(key);
expect(router.getSearch().get("items.sortDir")).toBe("asc");
await user.click(within(panel()).getByRole("button", { name: header }));
await waitFor(() => expect(getSalesItemsReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "desc" })));
expect(router.getSearch().get("items.sortDir")).toBe("desc");
});
test("Sales by item: with no sort chosen the loader gets no sortBy/sortDir", async () => {
render(<ReportsPage />);
await within(panel()).findByText("ZZQA-CAT-1-RED");
const arg = getSalesItemsReport.mock.calls[0][0] as Record<string, unknown>;
expect(arg.sortBy).toBeUndefined();
expect(arg.sortDir).toBeUndefined();
});
test("Sales by item: the export uses the chosen sort", async () => {
const user = userEvent.setup();
render(<ReportsPage />);
await within(panel()).findByText("ZZQA-CAT-1-RED");
await user.click(within(panel()).getByRole("button", { name: "Qty" }));
await waitFor(() => expect(getSalesItemsReport).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: "qty" })));
getSalesItemsReport.mockClear();
await user.click(within(panel()).getByRole("button", { name: /export \.xlsx/i }));
await waitFor(() => expect(downloadXlsx).toHaveBeenCalledTimes(1));
expect(getSalesItemsReport).toHaveBeenCalledWith(expect.objectContaining({ sortBy: "qty", sortDir: "asc" }));
});
// ─── dashboard-channel-split 3.2: channel column uses the Sales listing's order types ───
test("Sales by item labels the channel with the listing's order types, in the table and the export", async () => {
getSalesItemsReport.mockResolvedValue(
report([line(1, "SKU-OUT", null, false, "OUTLET", "BO"), line(2, "SKU-BO", null, false, "NORMAL", "BO")]),
);
render(<ReportsPage />);
const out = (await within(panel()).findByText("SKU-OUT")).closest("tr") as HTMLElement;
expect(within(out).getByText("Outlet")).toBeInTheDocument();
expect(within(out).queryByText("Counter")).not.toBeInTheDocument();
const bo = within(panel()).getByText("SKU-BO").closest("tr") as HTMLElement;
expect(within(bo).getByText("Counter")).toBeInTheDocument();
await userEvent.setup().click(within(panel()).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[2])).toEqual(["Outlet", "Counter"]);
});