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

248 lines
11 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { AdminRefundPage, AdminRefundRequest } from "@/app/lib/types";
// Route /orders/refunds IS in ROUTE_MODULES (module BO_REFUND_REQUESTS), so RequireModule gates it.
const auth = vi.hoisted(() => ({ hasModule: vi.fn(), loading: false }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ hasModule: auth.hasModule, loading: auth.loading }),
}));
const svc = vi.hoisted(() => ({
listRefunds: vi.fn(),
getRefund: vi.fn(),
approveRefund: vi.fn(),
rejectRefund: vi.fn(),
retryRefundEmail: vi.fn(),
}));
vi.mock("@/app/lib/services/adminRefunds", () => svc);
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import RefundRequestsPage from "./page";
function row(overrides: Partial<AdminRefundRequest> = {}): AdminRefundRequest {
return {
uuid: "U-31", documentNo: "RR00000031", orderUuid: "O-1", orderDocumentNo: "IN00000128",
buyerCode: "MY3619941", status: "P", reasonCode: "WRONG_ITEM", remark: null, refundAmount: 89,
decisionReason: null, decidedBy: null, decidedAt: null, walletTrxnRef: null, stockDocumentNos: null,
lastError: null, emailSentAt: null, createDate: "2026-09-21T10:12:00",
lines: [{ orderDetailsId: 11, productName: "Diaper L 40s", qty: 2, netUnitPrice: 34.5, amount: 69 }],
...overrides,
};
}
function pageOf(rows: AdminRefundRequest[], pendingCount = rows.length): AdminRefundPage {
return { content: rows, totalElements: rows.length, page: 0, size: 20, pendingCount };
}
beforeEach(() => {
memoryRouter.reset("/orders/refunds");
Object.values(svc).forEach(fn => fn.mockReset());
auth.hasModule.mockReset();
auth.hasModule.mockReturnValue(true);
});
describe("Refund Requests page", () => {
// BABYBOO-50: the member code links to the member with the buyer's name below.
it("shows the member code with the member's name below", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row({ buyerName: "Aina Rahman" })]));
render(<RefundRequestsPage />);
expect(await screen.findByRole("link", { name: "MY3619941" })).toHaveAttribute("href", "/members/MY3619941");
expect(screen.getByText("Aina Rahman")).toBeInTheDocument();
});
it("opens on Pending in the Status select with the pending count, and shows no tabs", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()], 4));
render(<RefundRequestsPage />);
expect(await screen.findByText("RR00000031")).toBeInTheDocument();
expect(svc.listRefunds).toHaveBeenCalledWith(expect.objectContaining({ status: "P", page: 0 }));
expect(screen.queryByRole("tab")).not.toBeInTheDocument();
expect(screen.getByRole("combobox", { name: "Status" })).toHaveTextContent(/pending \(4\)/i);
expect(screen.getByText("89.00")).toBeInTheDocument();
});
it("falls back to Pending for an unknown status in the URL", async () => {
memoryRouter.reset("/orders/refunds", "status=BOGUS");
svc.listRefunds.mockResolvedValue(pageOf([row()], 4));
render(<RefundRequestsPage />);
expect(await screen.findByText("RR00000031")).toBeInTheDocument();
expect(svc.listRefunds).toHaveBeenCalledWith(expect.objectContaining({ status: "P" }));
expect(screen.getByRole("combobox", { name: "Status" })).toHaveTextContent(/pending \(4\)/i);
});
it("shows the shared header, formatted dates and a toned status badge", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
expect(await screen.findByText("21 Sep 2026, 10:12")).toBeInTheDocument();
expect(screen.getByRole("table")).toHaveTextContent("Pending");
expect(screen.getAllByText("Pending").find(e => e.className.includes("text-warning"))).toBeDefined();
expect(screen.getByRole("columnheader", { name: /refund/i })).toHaveClass("text-right");
// fix-gift-refund-wording: the amount column does not name a payout.
expect(screen.getByRole("columnheader", { name: /refund/i })).toHaveTextContent(/^Refund$/);
});
it("choosing Approved in the Status select asks for approved requests", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
await userEvent.click(screen.getByRole("combobox", { name: "Status" }));
await userEvent.click(await screen.findByRole("option", { name: "Approved" }));
await waitFor(() => expect(svc.listRefunds).toHaveBeenLastCalledWith(expect.objectContaining({ status: "A" })));
expect(memoryRouter.getSearch().get("status")).toBe("A");
});
it("opens the drawer for a row without leaving the page", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
svc.getRefund.mockResolvedValue({
request: row(), buyerName: "Tan Mei Ling", orderDate: null, grandTotal: 97, shippingCost: 8,
tenders: [], stockEffects: [],
});
render(<RefundRequestsPage />);
await userEvent.click(await screen.findByRole("button", { name: "RR00000031" }));
const drawer = await screen.findByRole("dialog", { name: /RR00000031/ });
expect(within(drawer).getByText("Tan Mei Ling · MY3619941")).toBeInTheDocument();
expect(svc.getRefund).toHaveBeenCalledWith("U-31");
});
it("does not render the queue without the module", () => {
auth.hasModule.mockReturnValue(false);
render(<RefundRequestsPage />);
expect(screen.queryByRole("combobox", { name: "Status" })).not.toBeInTheDocument();
expect(svc.listRefunds).not.toHaveBeenCalled();
});
it("Status All offers four options and sends no status param", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()], 4));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
svc.listRefunds.mockClear();
await userEvent.click(screen.getByRole("combobox", { name: "Status" }));
const names = (await screen.findAllByRole("option")).map(o => o.textContent);
expect(names).toEqual(["All", "Pending (4)", "Approved", "Rejected"]);
await userEvent.click(screen.getByRole("option", { name: "All" }));
await waitFor(() => expect(svc.listRefunds).toHaveBeenCalled());
expect(svc.listRefunds.mock.calls.at(-1)![0].status).toBeUndefined();
expect(memoryRouter.getSearch().get("status")).toBe("ALL");
});
it("sends each text filter under its own param after the debounce, and no q", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
await userEvent.type(screen.getByRole("searchbox", { name: "Request No." }), "RR31");
await userEvent.type(screen.getByRole("searchbox", { name: "Invoice No." }), "IN00000010");
await userEvent.type(screen.getByRole("searchbox", { name: "Member" }), "MY6217232");
await waitFor(() =>
expect(svc.listRefunds).toHaveBeenLastCalledWith(
expect.objectContaining({ requestNo: "RR31", invoiceNo: "IN00000010", member: "MY6217232", status: "P", page: 0 }),
),
);
expect(svc.listRefunds.mock.calls.at(-1)![0].q).toBeUndefined();
expect(memoryRouter.getSearch().get("invoiceNo")).toBe("IN00000010");
});
it("has no combined search box", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
expect(screen.queryByRole("searchbox", { name: /search request no/i })).not.toBeInTheDocument();
});
it.each([
["P", "P", /pending/i],
["A", "A", /approved/i],
["R", "R", /rejected/i],
["ALL", undefined, /^all$/i],
])("reads status=%s from the URL on mount", async (param, sent, label) => {
memoryRouter.reset("/orders/refunds", `status=${param}&invoiceNo=IN1`);
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await waitFor(() => expect(svc.listRefunds).toHaveBeenCalled());
const arg = svc.listRefunds.mock.calls.at(-1)![0];
expect(arg.status).toBe(sent);
expect(arg.invoiceNo).toBe("IN1");
expect(screen.getByRole("combobox", { name: "Status" })).toHaveTextContent(label);
expect(screen.getByRole("searchbox", { name: "Invoice No." })).toHaveValue("IN1");
});
it("Clear filters empties the text filters from the URL but keeps the status", async () => {
memoryRouter.reset("/orders/refunds", "status=A&invoiceNo=IN1");
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
await userEvent.click(screen.getByRole("button", { name: "Clear filters" }));
await waitFor(() => expect(memoryRouter.getSearch().get("invoiceNo")).toBeNull());
expect(memoryRouter.getSearch().get("status")).toBe("A");
});
});
// fit-admin-listing-pages: the member is one Wallet-style cell — code on top (linking to the member), name below.
describe("refunds member cell", () => {
it("links the member code to the member", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
const link = await screen.findByRole("link", { name: "MY3619941" });
expect(link).toHaveAttribute("href", "/members/MY3619941");
});
});
// BABYBOO-54 B2: server-side header sorting. No URL prefix on this page.
describe("refunds server-side header sorting", () => {
it.each([
["Request", "documentNo"],
["Submitted", "createDate"],
["Invoice", "orderDocumentNo"],
["Member", "buyerCode"],
["Refund", "refundAmount"],
["Status", "status"],
["Lines", "lines"],
["Decided by", "decidedBy"],
])("clicking the %s header sorts asc by %s, then desc", async (header, key) => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
const table = within(screen.getByRole("table"));
await userEvent.click(table.getByRole("button", { name: header }));
await waitFor(() => expect(svc.listRefunds).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "asc" })));
expect(memoryRouter.getSearch().get("sortBy")).toBe(key);
await userEvent.click(table.getByRole("button", { name: header }));
await waitFor(() => expect(svc.listRefunds).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "desc" })));
});
it("changing the sort returns to the first page", async () => {
memoryRouter.reset("/orders/refunds", "page=2");
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
await userEvent.click(within(screen.getByRole("table")).getByRole("button", { name: "Request" }));
await waitFor(() => expect(svc.listRefunds).toHaveBeenLastCalledWith(expect.objectContaining({ page: 0, sortBy: "documentNo" })));
expect(memoryRouter.getSearch().has("page")).toBe(false);
});
it("Actions column has no sort button", async () => {
svc.listRefunds.mockResolvedValue(pageOf([row()]));
render(<RefundRequestsPage />);
await screen.findByText("RR00000031");
const table = within(screen.getByRole("table"));
expect(table.queryByRole("button", { name: /^Actions?$/ })).toBeNull();
});
});