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
90 lines
4.7 KiB
TypeScript
90 lines
4.7 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { render, screen, waitFor } from "@testing-library/react";
|
|
import userEvent from "@testing-library/user-event";
|
|
import type { GiftCard } from "@/app/lib/types";
|
|
import { formatDate } from "./giftCardLabels";
|
|
|
|
// listing-exports task 6.2: Gift cards Cards tab "Export .xlsx".
|
|
|
|
const svc = vi.hoisted(() => ({ listGiftCards: vi.fn() }));
|
|
vi.mock("@/app/lib/services/adminGiftCards", async (importActual) => ({
|
|
...(await importActual<typeof import("@/app/lib/services/adminGiftCards")>()),
|
|
listGiftCards: (f: unknown) => svc.listGiftCards(f),
|
|
}));
|
|
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
|
const xlsx = vi.hoisted(() => ({ toXlsx: vi.fn(), downloadXlsx: vi.fn() }));
|
|
vi.mock("@/app/lib/xlsx", () => xlsx);
|
|
|
|
import { memoryRouter } from "@/test/memoryRouter";
|
|
import { CardsPanel } from "./CardsPanel";
|
|
|
|
const card = (over: Partial<GiftCard> = {}): GiftCard => ({
|
|
uuid: "U-7", code: null, codeLast4: "6789", currency: "MYR", initialValue: 100, balance: 70,
|
|
status: "ACTIVE", expiresAt: "2029-10-06", source: "ADMIN", recipientName: "Amy",
|
|
recipientEmail: "amy@example.my", message: null, reason: "Goodwill", batchRef: "GCB-1",
|
|
issuedBy: "Ops Admin", emailSentAt: null, createDate: "2026-10-06T09:00:00", ...over,
|
|
});
|
|
const pageOf = (cards: GiftCard[]) => ({ content: cards, totalElements: cards.length, page: 0, size: 20, outstandingBalance: 70 });
|
|
const exportCall = () => svc.listGiftCards.mock.calls.find((c) => c[0].size === 500)?.[0];
|
|
|
|
beforeEach(() => {
|
|
memoryRouter.reset("/gift-cards", "status=ACTIVE");
|
|
svc.listGiftCards.mockReset().mockResolvedValue(pageOf([card()]));
|
|
xlsx.toXlsx.mockReset().mockResolvedValue(new Uint8Array([1]));
|
|
xlsx.downloadXlsx.mockReset();
|
|
});
|
|
|
|
describe("CardsPanel export", () => {
|
|
it("exports every matching card with the table's columns", async () => {
|
|
render(<CardsPanel reloadKey={0} />);
|
|
await screen.findByText("•••• 6789", { exact: false });
|
|
await userEvent.setup().click(screen.getByRole("button", { name: "Export .xlsx" }));
|
|
|
|
await waitFor(() => expect(xlsx.toXlsx).toHaveBeenCalled());
|
|
expect(exportCall()).toEqual(expect.objectContaining({ page: 0, size: 500, status: "ACTIVE" }));
|
|
const [rows, columns] = xlsx.toXlsx.mock.calls[0] as [Record<string, unknown>[], { key: string; title: string }[]];
|
|
expect(columns.map((c) => c.title)).toEqual(["Card", "Balance", "Initial value", "Status", "Expires", "Source", "Recipient", "Issued"]);
|
|
const row = rows[0]!;
|
|
const cell = (title: string) => row[columns.find((c) => c.title === title)!.key];
|
|
expect(rows).toHaveLength(1);
|
|
expect(String(cell("Card"))).toContain("6789");
|
|
expect(String(cell("Card"))).not.toContain("ABCD");
|
|
expect(Number(cell("Balance"))).toBe(70);
|
|
expect(Number(cell("Initial value"))).toBe(100);
|
|
expect(cell("Status")).toBe("Active");
|
|
expect(cell("Expires")).toBe(formatDate("2029-10-06"));
|
|
expect(cell("Source")).toBe("Admin");
|
|
expect(cell("Recipient")).toBe("amy@example.my");
|
|
expect(cell("Issued")).toBe(formatDate("2026-10-06T09:00:00"));
|
|
expect(xlsx.downloadXlsx).toHaveBeenCalledWith(expect.stringMatching(/^gift-cards-\d{4}-\d{2}-\d{2}\.xlsx$/), expect.anything());
|
|
});
|
|
|
|
it("leaves the recipient blank when there is none", async () => {
|
|
svc.listGiftCards.mockResolvedValue(pageOf([card({ recipientEmail: null })]));
|
|
render(<CardsPanel reloadKey={0} />);
|
|
await screen.findByText("•••• 6789", { exact: false });
|
|
await userEvent.setup().click(screen.getByRole("button", { name: "Export .xlsx" }));
|
|
|
|
await waitFor(() => expect(xlsx.toXlsx).toHaveBeenCalled());
|
|
const [rows, columns] = xlsx.toXlsx.mock.calls[0] as [Record<string, unknown>[], { key: string; title: string }[]];
|
|
expect([null, "", undefined]).toContain(rows[0]![columns.find((c) => c.title === "Recipient")!.key]);
|
|
});
|
|
|
|
it("is disabled when there are no cards", async () => {
|
|
svc.listGiftCards.mockResolvedValue(pageOf([]));
|
|
render(<CardsPanel reloadKey={0} />);
|
|
expect(await screen.findByRole("button", { name: "Export .xlsx" })).toBeDisabled();
|
|
});
|
|
|
|
it("shows an error and downloads nothing when the export fetch fails", async () => {
|
|
svc.listGiftCards.mockImplementation((f: { size: number }) =>
|
|
f.size === 500 ? Promise.reject(new Error("boom")) : Promise.resolve(pageOf([card()])));
|
|
render(<CardsPanel reloadKey={0} />);
|
|
await screen.findByText("•••• 6789", { exact: false });
|
|
await userEvent.setup().click(screen.getByRole("button", { name: "Export .xlsx" }));
|
|
|
|
expect(await screen.findByText("Export failed. Please try again.")).toBeInTheDocument();
|
|
expect(xlsx.downloadXlsx).not.toHaveBeenCalled();
|
|
});
|
|
});
|