Files
co-lite/solvway-customer-portal/app/store/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

507 lines
21 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import type { CurrentEventConfig, MemberVoucherRow } from "@/app/lib/types";
const routerMocks = vi.hoisted(() => ({ push: vi.fn() }));
const memberMocks = vi.hoisted(() => ({
member: { memberCode: "M001", name: "Ada", initials: "A", phone: "" } as unknown,
}));
vi.mock("@/app/lib/clientApi", () => ({ apiGet: vi.fn() }));
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: routerMocks.push }) }));
vi.mock("@/app/lib/MemberContext", () => ({
useMember: () => ({ member: memberMocks.member, loading: false, refresh: vi.fn() }),
}));
import { apiGet } from "@/app/lib/clientApi";
import StorePage from "./page";
const mockApiGet = apiGet as unknown as ReturnType<typeof vi.fn>;
function mockApis(
config: CurrentEventConfig,
balance = 500,
emrmProfileUpdate: "Y" | "N" = "Y",
vouchers?: MemberVoucherRow[],
) {
mockApiGet.mockImplementation((path: string) => {
if (path === "/api/points/balance") return Promise.resolve({ balance });
if (path === "/api/event/current-config") return Promise.resolve(config);
if (path === "/api/member/profile") return Promise.resolve({ emrmProfileUpdate });
if (path === "/api/voucher") return Promise.resolve(vouchers ?? []);
return Promise.resolve({});
});
}
const CONFIG_WITH_DOC: CurrentEventConfig = {
currentEventTasteRewards: "https://example.com/how-to-redeem.png",
currentEventTasteRewardsProductList: [
{ uuid: "p1", displayName: "Free Coffee", priceDisplay: "1,000 Points", uploadPath: "https://example.com/coffee.png" },
{ uuid: "p2", displayName: "Tote Bag", priceDisplay: "2,000 Points", uploadPath: "https://example.com/tote.png" },
],
};
describe("StorePage", () => {
beforeEach(() => {
mockApiGet.mockReset();
routerMocks.push.mockReset();
});
it("renders each reward with its image, name and price and no per-card redeem button", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
expect(await screen.findByText("Free Coffee")).toBeInTheDocument();
expect(screen.getByText("Tote Bag")).toBeInTheDocument();
expect(screen.getByText("1,000 Points")).toBeInTheDocument();
expect(screen.getByAltText("Free Coffee")).toBeInTheDocument();
expect(screen.getByAltText("Tote Bag")).toBeInTheDocument();
// exactly one "How to redeem" action total (the single hero button), not one per card
expect(screen.getAllByRole("button", { name: /how to redeem/i })).toHaveLength(1);
// and the guide image is shown once, inline
expect(screen.getAllByAltText("How to redeem")).toHaveLength(1);
});
it("lets the History link wrap below the eyebrow instead of squeezing it at large text sizes", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
const history = (await screen.findByText("History")).closest("a") as HTMLElement;
const row = history.parentElement as HTMLElement;
expect(history).toHaveAttribute("href", "/store/history");
expect(row.className).toContain("flex-wrap");
// pinned to the right whether it shares the row or drops to its own line
expect(history.className).toContain("ml-auto");
expect(history.className).toContain("flex-shrink-0");
});
it("does not render a tier progress indicator in the hero", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
await screen.findByText("Free Coffee");
expect(screen.queryByText(/progress/i)).not.toBeInTheDocument();
});
it("shows the how-to-redeem image up front, above the title and balance card", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
const img = await screen.findByAltText("How to redeem");
expect(img).toHaveAttribute("src", "https://example.com/how-to-redeem.png");
const heading = screen.getByRole("heading", { name: "Rewards" });
// DOCUMENT_POSITION_FOLLOWING: the heading comes after the image in the DOM.
expect(img.compareDocumentPosition(heading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(img.compareDocumentPosition(screen.getByText("Your Balance")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it("does not auto-open the lightbox on entering the page — the image is already inline", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
await screen.findByAltText("How to redeem");
await screen.findByText("Free Coffee");
// only the inline copy; the lightbox (titled "How to Redeem") is closed
expect(document.querySelectorAll('img[src="https://example.com/how-to-redeem.png"]')).toHaveLength(1);
expect(screen.queryByText("How to Redeem")).not.toBeInTheDocument();
});
it("keeps the How to redeem button, which opens the document in a lightbox", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: /how to redeem/i }));
// inline copy + lightbox copy
await waitFor(() =>
expect(document.querySelectorAll('img[src="https://example.com/how-to-redeem.png"]')).toHaveLength(2),
);
});
it("opens the guide full-screen when the inline image is tapped", async () => {
mockApis(CONFIG_WITH_DOC);
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: "Enlarge the redemption guide" }));
await waitFor(() =>
expect(document.querySelectorAll('img[src="https://example.com/how-to-redeem.png"]')).toHaveLength(2),
);
});
it("renders no guide image and no How to redeem button when no document is available", async () => {
mockApis({ currentEventTasteRewardsProductList: CONFIG_WITH_DOC.currentEventTasteRewardsProductList });
render(<StorePage />);
await screen.findByText("Free Coffee");
expect(screen.queryByAltText("How to redeem")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /how to redeem/i })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Enlarge the redemption guide" })).not.toBeInTheDocument();
});
it("shows the add-on cost as '+ (RM x)' and a clean points price when addOnCostLabel is present", async () => {
// the mobile-api space-appends the raw add-on amount to priceDisplay ("3,000 Points 50")
mockApis({
currentEventTasteRewardsProductList: [
{ uuid: "p3", displayName: "Fine Wine", priceDisplay: "3,000 Points 50", addOnCostLabel: "50", uploadPath: "https://example.com/wine.png" },
],
});
render(<StorePage />);
// points price renders without the raw trailing add-on number...
expect(await screen.findByText("3,000 Points")).toBeInTheDocument();
// ...and the add-on is shown separately, formatted
expect(screen.getByText("+ (RM 50)")).toBeInTheDocument();
// the raw appended form is never shown
expect(screen.queryByText("3,000 Points 50")).not.toBeInTheDocument();
});
it("labels a reward 'Fully Redeemed' only when its available stock is <= 0", async () => {
mockApis({
currentEventTasteRewardsProductList: [
{ uuid: "s1", displayName: "Sold Out Zero", priceDisplay: "1,000 Points", uploadPath: "https://example.com/1.png", stockBalance: 0 },
{ uuid: "s2", displayName: "Sold Out Negative", priceDisplay: "1,500 Points", uploadPath: "https://example.com/2.png", stockBalance: -3 },
{ uuid: "s3", displayName: "In Stock", priceDisplay: "2,000 Points", uploadPath: "https://example.com/3.png", stockBalance: 5 },
{ uuid: "s4", displayName: "Unknown Stock", priceDisplay: "3,000 Points", uploadPath: "https://example.com/4.png" },
],
});
render(<StorePage />);
await screen.findByText("Sold Out Zero");
// Exactly the two non-positive-stock rewards are labelled fully redeemed.
expect(screen.getAllByText(/fully redeemed/i)).toHaveLength(2);
// The in-stock and unknown-stock rewards still render normally.
expect(screen.getByText("In Stock")).toBeInTheDocument();
expect(screen.getByText("Unknown Stock")).toBeInTheDocument();
});
it("shows only the points price and no add-on label when addOnCostLabel is absent", async () => {
mockApis({
currentEventTasteRewardsProductList: [
{ uuid: "p4", displayName: "Plain Reward", priceDisplay: "2,000 Points", uploadPath: "https://example.com/plain.png" },
],
});
render(<StorePage />);
expect(await screen.findByText("2,000 Points")).toBeInTheDocument();
expect(screen.queryByText(/RM/)).not.toBeInTheDocument();
});
});
describe("StorePage — Redeem at counter needs no complete profile", () => {
beforeEach(() => {
mockApiGet.mockReset();
routerMocks.push.mockReset();
memberMocks.member = { memberCode: "M001", name: "Ada", initials: "A", phone: "" };
});
it("shows the member QR when the profile is incomplete", async () => {
mockApis(CONFIG_WITH_DOC, 500, "N");
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: /redeem at counter/i }));
expect(await screen.findByText("M001")).toBeInTheDocument();
expect(routerMocks.push).not.toHaveBeenCalled();
});
it("shows the member QR when the profile is complete", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y");
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: /redeem at counter/i }));
expect(await screen.findByText("M001")).toBeInTheDocument();
expect(routerMocks.push).not.toHaveBeenCalled();
});
it("shows the member QR when the profile flag is missing", async () => {
mockApiGet.mockImplementation((path: string) => {
if (path === "/api/points/balance") return Promise.resolve({ balance: 500 });
if (path === "/api/event/current-config") return Promise.resolve(CONFIG_WITH_DOC);
if (path === "/api/member/profile") return Promise.resolve({});
return Promise.resolve({});
});
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: /redeem at counter/i }));
expect(await screen.findByText("M001")).toBeInTheDocument();
expect(routerMocks.push).not.toHaveBeenCalled();
});
});
describe("StorePage — vouchers section", () => {
beforeEach(() => {
mockApiGet.mockReset();
routerMocks.push.mockReset();
});
it("renders a redeemable voucher with its image, name and amount, linking to /vouchers/{uuid}", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{
uuid: "1",
name: "New First-Time User",
currencySymbol: "RM",
amount: 10,
redeemable: true,
reason: null,
imageUrl: "https://example.com/voucher.png",
},
]);
render(<StorePage />);
expect(await screen.findByText("New First-Time User")).toBeInTheDocument();
expect(screen.getByText(/RM10/)).toBeInTheDocument();
expect(screen.getByAltText("New First-Time User")).toHaveAttribute(
"src",
"https://example.com/voucher.png",
);
expect(screen.getByRole("link", { name: /redeem/i })).toHaveAttribute("href", "/vouchers/1");
});
// Snowflake uuids are ~3e18, past Number.MAX_SAFE_INTEGER (~9e15). Held as a number the id
// loses its low digits — 3271922645582381056 stringifies to 3271922645582381000 — and the
// Redeem link points at a voucher that does not exist. mobile-api emits it as a string for
// this reason; this test fails the moment the type regresses to number.
it("keeps every digit of a Snowflake-sized uuid in the Redeem link", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{
uuid: "3271922645582381056",
name: "Testing Voucher",
currencySymbol: "RM",
amount: 150,
redeemable: true,
reason: null,
},
]);
render(<StorePage />);
expect(await screen.findByText("Testing Voucher")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /redeem/i })).toHaveAttribute(
"href",
"/vouchers/3271922645582381056",
);
});
it("renders an ineligible voucher with its humanised reason and no control at all", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{ uuid: "2", name: "Old Gift", currencySymbol: "RM", amount: 5, redeemable: false, reason: "ALREADY_REDEEMED" },
]);
render(<StorePage />);
expect(await screen.findByText("Old Gift")).toBeInTheDocument();
expect(screen.getByText(/already redeemed/i)).toBeInTheDocument();
expect(screen.queryByRole("link", { name: /redeem/i })).toBeNull();
// "Redeem at counter" and "How to redeem" are the page's own buttons — match exactly.
expect(screen.queryByRole("button", { name: "Redeem" })).toBeNull();
});
it("hides expired and inactive vouchers and counts only the ones shown", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{ uuid: "5", name: "Lapsed Voucher", currencySymbol: "RM", amount: 5, redeemable: false, reason: "EXPIRED" },
{ uuid: "8", name: "Switched Off", currencySymbol: "RM", amount: 5, redeemable: false, reason: "NOT_ACTIVE" },
{ uuid: "9", name: "Live Voucher", currencySymbol: "RM", amount: 5, redeemable: true, reason: null },
{ uuid: "10", name: "Coming Soon", currencySymbol: "RM", amount: 5, redeemable: false, reason: "NOT_STARTED" },
]);
render(<StorePage />);
expect(await screen.findByText("Live Voucher")).toBeInTheDocument();
expect(screen.getByText("Coming Soon")).toBeInTheDocument();
expect(screen.queryByText("Lapsed Voucher")).not.toBeInTheDocument();
expect(screen.queryByText("Switched Off")).not.toBeInTheDocument();
expect(screen.getByText("2 total")).toBeInTheDocument();
});
it("renders no voucher section when every voucher is expired or inactive", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{ uuid: "5", name: "Lapsed Voucher", currencySymbol: "RM", amount: 5, redeemable: false, reason: "EXPIRED" },
{ uuid: "8", name: "Switched Off", currencySymbol: "RM", amount: 5, redeemable: false, reason: "NOT_ACTIVE" },
]);
render(<StorePage />);
await screen.findByText("Free Coffee");
expect(screen.queryByText(/your vouchers/i)).not.toBeInTheDocument();
});
it("keeps a Redeem button, and its hint, for a voucher blocked only by an incomplete profile", async () => {
mockApis(CONFIG_WITH_DOC, 500, "N", [
{
uuid: "6",
name: "New First-Time User",
currencySymbol: "RM",
amount: 10,
redeemable: false,
reason: "PROFILE_INCOMPLETE",
},
]);
render(<StorePage />);
expect(await screen.findByText("New First-Time User")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Redeem" })).toBeInTheDocument();
expect(screen.getByText(/complete your profile to redeem/i)).toBeInTheDocument();
// It must not navigate — the modal is the whole point.
expect(screen.queryByRole("link", { name: /redeem/i })).toBeNull();
});
it("opens the voucher's complete-profile modal when that Redeem button is tapped", async () => {
mockApis(CONFIG_WITH_DOC, 500, "N", [
{
uuid: "6",
name: "New First-Time User",
currencySymbol: "RM",
amount: 10,
redeemable: false,
reason: "PROFILE_INCOMPLETE",
},
]);
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: "Redeem" }));
const dialog = await screen.findByRole("dialog", { name: "New First-Time User" });
expect(within(dialog).getByText("Complete your profile to unlock rewards!")).toBeInTheDocument();
expect(within(dialog).getByRole("link", { name: "Complete Profile" })).toHaveAttribute("href", "/settings/profile");
});
it("renders no voucher section at all when the member has none", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", []);
render(<StorePage />);
await screen.findByText("Free Coffee");
expect(screen.queryByText(/your vouchers/i)).not.toBeInTheDocument();
});
it("falls back gracefully rather than rendering a broken img when a voucher has no imageUrl", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{ uuid: "3", name: "No Image Voucher", currencySymbol: "RM", amount: 8, redeemable: true, reason: null },
]);
render(<StorePage />);
expect(await screen.findByText("No Image Voucher")).toBeInTheDocument();
expect(screen.queryByAltText("No Image Voucher")).not.toBeInTheDocument();
});
it("still renders the product grid above which the voucher section sits", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [
{ uuid: "4", name: "Voucher A", currencySymbol: "RM", amount: 1, redeemable: true, reason: null },
]);
render(<StorePage />);
const voucherName = await screen.findByText("Voucher A");
const productName = screen.getByText("Free Coffee");
expect(voucherName.compareDocumentPosition(productName) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
});
describe("StorePage — voucher card layout and detail modal", () => {
beforeEach(() => {
mockApiGet.mockReset();
routerMocks.push.mockReset();
});
const LONG = "Exclusive Tastefully Star Club Member Welcome Gift Voucher For New Members";
const VOUCHER: MemberVoucherRow = {
uuid: "7",
name: LONG,
description: "Spend RM50 at any booth during the event.",
currencySymbol: "RM",
amount: 50,
redeemable: true,
reason: null,
imageUrl: "https://example.com/v7.png",
};
it("shows the whole voucher title on the card instead of truncating it", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [VOUCHER]);
render(<StorePage />);
const title = await screen.findByText(LONG);
expect(title.className).not.toContain("truncate");
expect(title.className).toContain("break-words");
});
it("stacks image | content on the card, with the Redeem button under the text, not in the row", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [VOUCHER]);
render(<StorePage />);
const title = await screen.findByText(LONG);
const redeem = screen.getByRole("link", { name: /redeem/i });
const details = screen.getByRole("button", { name: `View details: ${LONG}` });
// The card row has exactly two children: the image column and the content column…
const content = redeem.parentElement as HTMLElement;
const row = content.parentElement as HTMLElement;
expect(row.children).toHaveLength(2);
// …and the title text and the Redeem button live together in the content column.
expect(content.contains(title)).toBe(true);
expect(content.contains(details)).toBe(true);
expect(content.className).toContain("flex-col");
// Full width of the column, so it is a comfortable tap target.
expect(redeem.className).toContain("w-full");
});
it("opens a detail modal from the card with the image, title, description and button", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [VOUCHER]);
render(<StorePage />);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("button", { name: `View details: ${LONG}` }));
const dialog = await screen.findByRole("dialog", { name: LONG });
expect(dialog).toBeInTheDocument();
expect(screen.getAllByAltText(LONG).length).toBeGreaterThan(0);
expect(screen.getByText("Spend RM50 at any booth during the event.")).toBeInTheDocument();
// card link + modal link
expect(screen.getAllByRole("link", { name: /redeem/i })).toHaveLength(2);
});
it("closes the detail modal again", async () => {
mockApis(CONFIG_WITH_DOC, 500, "Y", [VOUCHER]);
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: `View details: ${LONG}` }));
await screen.findByRole("dialog");
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("treats the card and its Redeem button identically for a profile-incomplete voucher", async () => {
const incomplete = { ...VOUCHER, uuid: "8", name: "New User Voucher", redeemable: false, reason: "PROFILE_INCOMPLETE" };
const dialogContents = async (open: () => void) => {
mockApis(CONFIG_WITH_DOC, 500, "N", [incomplete]);
const view = render(<StorePage />);
await screen.findByText("New User Voucher");
open();
const dialog = await screen.findByRole("dialog", { name: "New User Voucher" });
const html = dialog.innerHTML;
view.unmount();
return html;
};
const viaCard = await dialogContents(() =>
fireEvent.click(screen.getByRole("button", { name: "View details: New User Voucher" })),
);
const viaButton = await dialogContents(() => fireEvent.click(screen.getByRole("button", { name: "Redeem" })));
expect(viaButton).toBe(viaCard);
expect(viaCard).toContain("Complete your profile to unlock rewards!");
});
it("does not raise the plain complete-profile popup on /store any more", async () => {
mockApis(CONFIG_WITH_DOC, 500, "N", [
{ ...VOUCHER, uuid: "9", name: "New User Voucher", redeemable: false, reason: "PROFILE_INCOMPLETE" },
]);
render(<StorePage />);
fireEvent.click(await screen.findByRole("button", { name: "Redeem" }));
await screen.findByRole("dialog", { name: "New User Voucher" });
// exactly one dialog and exactly one Complete Profile action (the voucher modal's)
expect(screen.getAllByRole("dialog")).toHaveLength(1);
expect(screen.getAllByText("Complete Profile")).toHaveLength(1);
});
});