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

412 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { pickRange } from "@/test/pickDate";
import { memoryRouter } from "@/test/memoryRouter";
import WalletLedgerPage from "./page";
import { MessagesProvider } from "@/app/lib/i18n/MessagesProvider";
import type { AdminWalletLedgerRow } from "@/app/lib/types";
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
const auth = vi.hoisted(() => ({ hasModule: vi.fn(), loading: false }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ hasModule: auth.hasModule, loading: auth.loading }),
}));
const getAllWalletLedger = vi.fn();
const getMemberWalletBalances = vi.fn();
const adjustWallet = vi.fn();
vi.mock("@/app/lib/services/wallet", () => ({
getAllWalletLedger: (page: number, size: number, filters?: unknown) =>
getAllWalletLedger(page, size, filters),
getMemberWalletBalances: (code: string) => getMemberWalletBalances(code),
adjustWallet: (input: unknown) => adjustWallet(input),
}));
const rows: AdminWalletLedgerRow[] = [
{
transactionDateTime: "2026-08-01T10:30:00",
refNo: "REF-1001",
trxnType: "TPU",
amountIn: 100,
memberCode: "MY10001",
memberName: "AINA TAN",
walletName: "Ewallet",
},
{
transactionDateTime: "2026-07-31T09:00:00",
refNo: "REF-1000",
trxnType: "SLO",
amountOut: 25.5,
memberCode: "MY10002",
memberName: "BUDI SANTOSO",
walletName: "Bonus Wallet",
},
];
function makePage(content: AdminWalletLedgerRow[], totalElements: number) {
return { content, number: 0, size: 10, totalElements, totalPages: Math.ceil(totalElements / 10) };
}
function renderPage() {
return render(<WalletLedgerPage />);
}
beforeEach(() => {
memoryRouter.reset("/wallet");
auth.hasModule.mockReset();
auth.hasModule.mockReturnValue(true);
auth.loading = false;
getAllWalletLedger.mockReset();
// 25 total rows -> pageCount 3, so pagination controls are enabled.
getAllWalletLedger.mockResolvedValue(makePage(rows, 25));
});
describe("WalletLedgerPage (global ledger on /wallet)", () => {
it("renders the ledger rows with member links and wallet names", async () => {
renderPage();
expect(await screen.findByText("REF-1001")).toBeInTheDocument();
expect(screen.getByText("REF-1000")).toBeInTheDocument();
// Member cells link to the per-member wallet view.
const memberLink = screen.getByRole("link", { name: /MY10001/ });
expect(memberLink).toHaveAttribute("href", "/wallet/MY10001");
expect(screen.getByRole("link", { name: /MY10002/ })).toHaveAttribute("href", "/wallet/MY10002");
// Wallet names and types are shown, not raw uuids.
expect(screen.getByText("Ewallet")).toBeInTheDocument();
expect(screen.getByText("Bonus Wallet")).toBeInTheDocument();
// Friendly names, not raw enum codes.
// BABYBOO-50: the label shows twice, in the Type badge and as the Reference words.
expect(screen.getAllByText("Top-Up").length).toBeGreaterThan(0);
expect(screen.getAllByText("Sales out").length).toBeGreaterThan(0);
expect(screen.queryByText("TPU")).not.toBeInTheDocument();
expect(screen.queryByText("SLO")).not.toBeInTheDocument();
// In/Out amounts.
expect(screen.getByText("+100.00")).toBeInTheDocument();
expect(screen.getByText("−25.50")).toBeInTheDocument();
});
it("BABYBOO-50: words the reward reference, keeps the raw reference, colours wallet and direction", async () => {
getAllWalletLedger.mockResolvedValue(
makePage(
[
{
...rows[0],
refNo: "T1:MY200:SPONSOR_APPLE",
trxnType: "REI",
sourceMemberCode: "MY100",
sourceMemberName: "Aina",
walletName: "Apples",
walletTypeCode: "APPLE",
},
{ ...rows[1], refNo: "T9", trxnType: "TPR", walletName: "Product Wallet", walletTypeCode: "PRODUCT" },
{ ...rows[1], refNo: "G1", trxnType: "GCI", walletName: "Gift Card", walletTypeCode: "GIFT" },
],
3,
),
);
renderPage();
expect(await screen.findByText("Apples from Aina (MY100)'s top-up")).toBeInTheDocument();
expect(screen.getByText("T1:MY200:SPONSOR_APPLE")).toBeInTheDocument();
expect(screen.getByText("Apples").className).toContain("text-chart-1"); // Giraffe
expect(screen.getByText("Product Wallet").className).toContain("text-chart-2"); // Otter
expect(screen.getByText("Apples")).toHaveAttribute("data-variant", "default");
expect(screen.getByText("Gift Card")).toHaveAttribute("data-variant", "outline"); // Member: no tint
expect(screen.getByText("Earning in").className).toContain("text-positive");
const reversed = screen.getAllByText("Top-up reversed");
expect(reversed).toHaveLength(2); // Type badge and Reference words, never the raw code
expect(reversed.some(el => el.className.includes("text-negative"))).toBe(true);
expect(screen.queryByText("TPR")).not.toBeInTheDocument();
});
it("BABYBOO-61: a pass-up row reads as the promoted member's promotion", async () => {
getAllWalletLedger.mockResolvedValue(
makePage(
[
{
...rows[0],
refNo: "T4:MY300:PROMOTION_APPLE",
trxnType: "REI",
sourceMemberCode: "MY400",
sourceMemberName: "Barney",
walletName: "Apples",
walletTypeCode: "APPLE",
},
],
1,
),
);
renderPage();
expect(await screen.findByText("Pass-up apples from Barney (MY400)'s promotion to Giraffe")).toBeInTheDocument();
expect(screen.getByText("T4:MY300:PROMOTION_APPLE")).toBeInTheDocument();
});
it("has one h1 and formats the date with the shared formatter", async () => {
renderPage();
await screen.findByText("REF-1001");
expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
expect(screen.getByText("1 Aug 2026, 10:30")).toBeInTheDocument();
});
it("labels withdrawal codes instead of showing them raw", async () => {
getAllWalletLedger.mockResolvedValue(
makePage([{ ...rows[0], refNo: "REF-W", trxnType: "WDAO", amountIn: undefined, amountOut: 5 }], 1),
);
renderPage();
expect((await screen.findAllByText("Withdrawal fee")).length).toBeGreaterThan(0);
expect(screen.queryByText("WDAO")).not.toBeInTheDocument();
});
it("filters by exact member code from the filter input", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
getAllWalletLedger.mockResolvedValue(makePage([rows[0]], 1));
// BABYBOO-50: one Member box takes a code or a name.
const memberCodeInput = screen.getByRole("searchbox", { name: "Member" });
expect(memberCodeInput).toHaveAttribute("placeholder", "Member code or name");
await user.type(memberCodeInput, "MY10001");
await waitFor(() => {
expect(getAllWalletLedger).toHaveBeenCalledWith(1, 20, expect.objectContaining({ memberCode: "MY10001" }));
});
});
it("filters by transaction-type category from the type select", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
getAllWalletLedger.mockResolvedValue(makePage([rows[0]], 1));
const typeSelect = screen.getByRole("combobox", { name: "Type" });
await user.click(typeSelect);
// A category option (in + out grouped), not a raw enum code.
await user.click(await screen.findByRole("option", { name: "Sales" }));
await waitFor(() => {
expect(getAllWalletLedger).toHaveBeenCalledWith(1, 20, expect.objectContaining({ category: "SALES" }));
});
});
it("filters by date range from the from/to date inputs", async () => {
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
getAllWalletLedger.mockResolvedValue(makePage([rows[0]], 1));
pickRange("From", "2026-08-01", "2026-08-31");
await waitFor(() => {
expect(getAllWalletLedger).toHaveBeenCalledWith(
1, 20,
expect.objectContaining({ from: "2026-08-01", to: "2026-08-31" }),
);
});
});
it("filters by reference after the Date filter and sends refNo (BABYBOO-54)", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
getAllWalletLedger.mockResolvedValue(makePage([rows[0]], 1));
const ref = screen.getByRole("searchbox", { name: "Reference" });
const dateFrom = screen.getByLabelText("From");
expect(dateFrom.compareDocumentPosition(ref) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
await user.type(ref, "3299434405991206912");
await waitFor(() =>
expect(getAllWalletLedger).toHaveBeenLastCalledWith(
1, 20,
expect.objectContaining({ refNo: "3299434405991206912" }),
),
);
expect(memoryRouter.getSearch().get("refNo")).toBe("3299434405991206912");
});
it("filters by wallet type from the Wallet select and puts it in the URL", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
await user.click(screen.getByRole("combobox", { name: "Wallet" }));
await user.click(await screen.findByRole("option", { name: "Acorns" }));
await waitFor(() => {
expect(getAllWalletLedger).toHaveBeenCalledWith(1, 20, expect.objectContaining({ walletType: "ACORN" }));
});
expect(memoryRouter.getSearch().get("walletType")).toBe("ACORN");
});
it("choosing All wallets again drops walletType from the request and the URL", async () => {
const user = userEvent.setup();
memoryRouter.reset("/wallet", "walletType=APPLE");
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
await user.click(screen.getByRole("combobox", { name: "Wallet" }));
await user.click(await screen.findByRole("option", { name: "All wallets" }));
await waitFor(() => {
expect(getAllWalletLedger).toHaveBeenCalledWith(1, 20, expect.objectContaining({ walletType: undefined }));
});
expect(memoryRouter.getSearch().has("walletType")).toBe(false);
});
it("renders the wallet filter labels through i18n", async () => {
const user = userEvent.setup();
render(
<MessagesProvider
locale="en"
messages={{ WalletLedgerAllWallets: "Semua dompet", WalletLedgerDate: "Tarikh", WalletAcorns: "Biji ek" }}
>
<WalletLedgerPage />
</MessagesProvider>,
);
await screen.findByText("REF-1001");
expect(screen.getByText("Tarikh", { selector: "label, span, div" })).toBeInTheDocument();
await user.click(screen.getByRole("combobox", { name: "Wallet" }));
expect(await screen.findByRole("option", { name: "Semua dompet" })).toBeInTheDocument();
expect(screen.getByRole("option", { name: "Biji ek" })).toBeInTheDocument();
});
it("populates the controls and request from the URL on mount", async () => {
memoryRouter.reset("/wallet", "walletType=APPLE&memberCode=MY10001");
renderPage();
await screen.findByText("REF-1001");
expect(getAllWalletLedger).toHaveBeenCalledWith(1, 20, expect.objectContaining({ walletType: "APPLE", memberCode: "MY10001" }));
expect(screen.getByRole("searchbox", { name: "Member" })).toHaveValue("MY10001");
expect(screen.getByRole("combobox", { name: "Wallet" })).toHaveTextContent("Apples");
});
it("Clear filters empties the URL", async () => {
const user = userEvent.setup();
memoryRouter.reset("/wallet", "walletType=APPLE");
renderPage();
await screen.findByText("REF-1001");
await user.click(screen.getByRole("button", { name: "Clear filters" }));
expect(memoryRouter.getSearch().toString()).toBe("");
});
it("paginates with the DataTable controls", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
getAllWalletLedger.mockResolvedValue(makePage([rows[1]], 1));
await user.click(screen.getByRole("button", { name: /Next/ }));
await waitFor(() => {
expect(getAllWalletLedger).toHaveBeenCalledWith(2, 20, expect.objectContaining({}));
});
});
it("shows the empty state when no transactions match", async () => {
getAllWalletLedger.mockResolvedValue(makePage([], 0));
renderPage();
expect(await screen.findByText("No wallet transactions found")).toBeInTheDocument();
expect(screen.queryByText("REF-1001")).not.toBeInTheDocument();
});
it("shows the error state (not an empty table) when the read fails", async () => {
getAllWalletLedger.mockRejectedValue(new Error("payment service down"));
renderPage();
expect(await screen.findByRole("alert")).toHaveTextContent("payment service down");
expect(screen.queryByText("No wallet transactions found")).not.toBeInTheDocument();
});
it("renders the not-authorised fallback without BO_WALLET and never fetches", async () => {
auth.hasModule.mockReturnValue(false);
renderPage();
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(getAllWalletLedger).not.toHaveBeenCalled();
});
// BABYBOO-54: wallet adjustment entry point.
it("hides the Wallet adjustment button without BO_WALLET_ADJUST", async () => {
auth.hasModule.mockImplementation((m: string) => m !== "BO_WALLET_ADJUST");
renderPage();
await screen.findByText("REF-1001");
expect(screen.queryByRole("button", { name: "Wallet adjustment" })).not.toBeInTheDocument();
});
it("shows the Wallet adjustment button with BO_WALLET_ADJUST", async () => {
renderPage();
await screen.findByText("REF-1001");
expect(screen.getByRole("button", { name: "Wallet adjustment" })).toBeInTheDocument();
});
it("a saved adjustment toasts, closes the dialog and reloads the ledger", async () => {
const user = userEvent.setup();
getMemberWalletBalances.mockResolvedValue([{ walletTypeCode: "PRODUCT", balance: 100, enabled: "Y" }]);
adjustWallet.mockResolvedValue({ refNo: "x", trxnType: "AJI", amount: 25.5, balance: 125.5 });
renderPage();
await screen.findByText("REF-1001");
await user.click(screen.getByRole("button", { name: "Wallet adjustment" }));
await user.type(await screen.findByLabelText("Member code"), "MY10001");
await user.tab();
await user.click(await screen.findByRole("combobox", { name: "Wallet" }));
await user.click(await screen.findByRole("option", { name: /Product/ }));
await user.click(screen.getByRole("radio", { name: "Add" }));
await user.type(screen.getByLabelText("Amount"), "25.50");
await user.type(screen.getByLabelText("Reason"), "Goodwill");
await user.click(screen.getByRole("button", { name: "Review" }));
getAllWalletLedger.mockClear();
await user.click(await screen.findByRole("button", { name: "Confirm adjustment" }));
expect(await screen.findByText("Adjustment saved.")).toBeInTheDocument();
await waitFor(() => expect(getAllWalletLedger).toHaveBeenCalled());
expect(screen.queryByLabelText("Member code")).not.toBeInTheDocument();
});
});
// ─── BABYBOO-54: server-side header sorting ───────────────────────────────────
// Seam: the page passes sortBy/sortDir inside the `filters` argument of getAllWalletLedger,
// using the backend keys date|ref|type|in|out|wallet (column ids), and mirrors them in the URL.
describe("Wallet ledger page — header sorting", () => {
const lastFilters = () => getAllWalletLedger.mock.calls.at(-1)?.[2];
it.each([
["Date", "date"],
["Member", "member"],
["Wallet", "wallet"],
["Type", "type"],
["Reference", "ref"],
["In", "in"],
["Out", "out"],
])("clicking %s sends sortBy=%s&sortDir=asc and writes the URL", async (name, key) => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
getAllWalletLedger.mockClear();
await user.click(within(screen.getByRole("columnheader", { name })).getByRole("button"));
await waitFor(() => expect(lastFilters()).toMatchObject({ sortBy: key, sortDir: "asc" }));
expect(memoryRouter.getSearch().get("sortBy")).toBe(key);
expect(memoryRouter.getSearch().get("sortDir")).toBe("asc");
});
it("a second click on the same header flips to desc", async () => {
const user = userEvent.setup();
renderPage();
await screen.findByText("REF-1001");
const btn = () => within(screen.getByRole("columnheader", { name: "Out" })).getByRole("button");
await user.click(btn());
await user.click(btn());
await waitFor(() => expect(lastFilters()).toMatchObject({ sortBy: "out", sortDir: "desc" }));
expect(memoryRouter.getSearch().get("sortDir")).toBe("desc");
});
});