import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { useState } from "react"; import { render, screen, act, fireEvent, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import type { AdminMember, MemberCheckoutPreviewResult, MemberWalletBalance, PosWalletBalanceView, SplitSaleResult, SplitSettlementStatus, } from "@/app/lib/types"; import type { PosLine } from "@/app/pos/shared"; import { SplitTenderPanel } from "./SplitTenderPanel"; import { ApiError } from "@/app/lib/clientApi"; const LINES: PosLine[] = [ { key: 1, pPricingId: "p1", variationId: "v1", label: "Coffee", unitPrice: 50, qty: 2 }, ]; interface HarnessProps { total?: number; place: (p: unknown) => Promise; poll?: (uuid: string) => Promise; cancel?: (uuid: string) => Promise; onReceipt?: (r: unknown) => void; walletInfo?: PosWalletBalanceView | null; /** The member is now picked once in the page's Buyer section (redesign-pos-layout Task 4) — the * panel no longer has its own combobox, so a test that needs a member supplies it here. */ walletMember?: AdminMember | null; /** Wallet legs the member can fund, as the wallet preview reports them (balance + server max). */ walletOptions?: { walletTypeCode: string; balance: number; max: number }[]; previewWallet?: (p: unknown) => Promise; promoCode?: string | null; onOfferChanged?: () => void; onPendingChange?: (pending: boolean) => void; buildReceipt?: (sale: { uuid: string; documentNo?: string }) => unknown; extraFields?: Record; onFulfilmentRefused?: () => void; } // Drives the page-owned wallet member + PIN + receipt state the panel expects as props. function Harness({ total = 100, place, poll, cancel, onReceipt, walletInfo = null, walletMember = null, walletOptions, previewWallet, promoCode = null, onOfferChanged = () => {}, onPendingChange, buildReceipt, extraFields, onFulfilmentRefused, }: HarnessProps) { const [pin, setPin] = useState(""); const [receipt, setReceipt] = useState(null); if (receipt) return
placed
; return ( Promise.resolve({ orderTotal: total, acornPaid: 0, productPaid: 0, applePaid: 0, gatewayResidual: 0, walletOptions: walletOptions ?? [], }))) as never } cartSignature="sig" promoCode={promoCode} onOfferChanged={onOfferChanged} onPendingChange={onPendingChange} place={place as never} poll={poll ?? (() => Promise.resolve({ status: "PENDING" }))} cancel={cancel ?? (() => Promise.resolve(true))} buildReceipt={buildReceipt ?? ((sale) => ({ ...sale }))} extraFields={extraFields} onFulfilmentRefused={onFulfilmentRefused} setReceipt={(r) => { onReceipt?.(r); setReceipt(r); }} /> ); } const MEMBER = { memberCode: "MY0001", name: "Test Member" }; const OPTIONS = [ { walletTypeCode: "PRODUCT", balance: 80, max: 80 }, { walletTypeCode: "ACORN", balance: 30, max: 20 }, ]; const leg = (name: string) => screen.findByRole("group", { name }); const amountInput = (name: string) => screen.findByLabelText(`${name} amount`); const placeBtn = () => screen.getByRole("button", { name: /place split sale/i }); describe("SplitTenderPanel — allocation gate", () => { afterEach(() => vi.clearAllMocks()); it("disables submit until remaining allocates to exactly zero", async () => { const user = userEvent.setup(); render(); expect(placeBtn()).toBeDisabled(); await user.type(screen.getByLabelText("Cash"), "60"); expect(placeBtn()).toBeDisabled(); // remaining 40 await user.type(screen.getByLabelText("Gateway"), "40"); expect(placeBtn()).toBeEnabled(); // remaining 0, no wallet leg }); it("requires a member and a PIN when a wallet leg is used", async () => { const user = userEvent.setup(); render( , ); const product = await amountInput("Product"); await user.clear(product); await user.type(product, "100"); expect(placeBtn()).toBeDisabled(); // remaining 0 but no PIN await user.type(screen.getByLabelText("Member PIN"), "1234"); expect(placeBtn()).toBeEnabled(); }); it("needs no PIN when every wallet amount is 0", async () => { const user = userEvent.setup(); render(); await leg("Product"); expect(screen.queryByLabelText("Member PIN")).not.toBeInTheDocument(); await user.type(screen.getByLabelText("Cash"), "100"); expect(placeBtn()).toBeEnabled(); }); it("wallet + cash + gateway must equal the total exactly", async () => { const user = userEvent.setup(); render(); const product = await amountInput("Product"); await user.type(product, "50"); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.type(screen.getByLabelText("Cash"), "49.99"); expect(placeBtn()).toBeDisabled(); await user.clear(screen.getByLabelText("Cash")); await user.type(screen.getByLabelText("Cash"), "50"); expect(placeBtn()).toBeEnabled(); }); }); describe("SplitTenderPanel — submit flows", () => { afterEach(() => { vi.clearAllMocks(); vi.useRealTimers(); }); it("settles immediately (gateway 0) and shows the receipt directly", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: true, uuid: "u1", documentNo: "DOC-1" }); const onReceipt = vi.fn(); render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(place).toHaveBeenCalledTimes(1); expect(screen.getByTestId("receipt")).toBeInTheDocument(); expect(onReceipt).toHaveBeenCalledWith(expect.objectContaining({ uuid: "u1" })); }); it("clears the PIN from state after submit (structured failure keeps the panel)", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: false, pinVerifyStatus: "FAIL" }); // The member is now picked in the page's Buyer section, not through a combobox inside this // panel (redesign-pos-layout Task 4) — pass it directly via the walletMember prop. render( , ); await user.type(await amountInput("Product"), "100"); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.click(placeBtn()); // Panel stays (no receipt) and the PIN field is cleared. expect(screen.queryByTestId("receipt")).not.toBeInTheDocument(); expect(screen.getByLabelText("Member PIN")).toHaveValue(""); // The PIN that was submitted was passed to place, never retained afterwards. expect(place).toHaveBeenCalledWith(expect.objectContaining({ candidatePin: "1234" })); }); it("renders a QR for a gateway leg and shows the receipt once polling reports PAID", async () => { vi.useFakeTimers(); const place = vi .fn() .mockResolvedValue({ success: true, uuid: "u1", redirectUrl: "https://pay.example/u1" }); const poll = vi.fn().mockResolvedValue({ status: "PAID" }); const onReceipt = vi.fn(); render(); // fireEvent (synchronous) instead of userEvent — userEvent's internal delays deadlock under // fake timers. fireEvent.change(screen.getByLabelText("Gateway"), { target: { value: "100" } }); fireEvent.click(placeBtn()); await act(async () => { await vi.advanceTimersByTimeAsync(0); // flush place() resolution }); // QR is on screen (an inside the gateway-qr container). const qr = screen.getByTestId("split-gateway-qr"); expect(qr.querySelector("svg")).not.toBeNull(); await act(async () => { await vi.advanceTimersByTimeAsync(2500); // one poll tick → PAID }); expect(poll).toHaveBeenCalledWith("u1"); expect(onReceipt).toHaveBeenCalledWith(expect.objectContaining({ uuid: "u1" })); expect(screen.getByTestId("receipt")).toBeInTheDocument(); }); it("cancels the pending gateway sale on timeout", async () => { vi.useFakeTimers(); const place = vi .fn() .mockResolvedValue({ success: true, uuid: "u1", redirectUrl: "https://pay.example/u1" }); const poll = vi.fn().mockResolvedValue({ status: "PENDING" }); const cancel = vi.fn().mockResolvedValue(true); render(); fireEvent.change(screen.getByLabelText("Gateway"), { target: { value: "100" } }); fireEvent.click(placeBtn()); await act(async () => { await vi.advanceTimersByTimeAsync(0); }); await act(async () => { await vi.advanceTimersByTimeAsync(5 * 60_000); // default timeout }); expect(cancel).toHaveBeenCalledWith("u1"); }); }); describe("SplitTenderPanel — per-wallet legs", () => { afterEach(() => vi.clearAllMocks()); it("shows one leg per wallet with a balance, from the wallet preview, and no Apple toggle", async () => { const previewWallet = vi.fn().mockResolvedValue({ orderTotal: 100, acornPaid: 0, productPaid: 0, applePaid: 0, gatewayResidual: 0, walletOptions: [ { walletTypeCode: "PRODUCT", balance: 80, max: 80 }, { walletTypeCode: "ACORN", balance: 0, max: 0 }, { walletTypeCode: "APPLE", balance: 15, max: 15 }, ], }); render(); expect(await leg("Product")).toBeInTheDocument(); expect(await leg("Apples")).toBeInTheDocument(); expect(screen.queryByRole("group", { name: "Acorns" })).not.toBeInTheDocument(); expect(screen.queryByLabelText(/use apple wallet/i)).not.toBeInTheDocument(); expect(previewWallet).toHaveBeenCalledWith(expect.objectContaining({ memberCode: "MY0001" })); }); it("shows no legs for a walk-in", () => { render(); expect(screen.queryByRole("group", { name: "Product" })).not.toBeInTheDocument(); }); it("caps each leg at its max", async () => { const user = userEvent.setup(); render(); const acorn = await amountInput("Acorns"); // balance 30, max 20 (yellow-label items only) await user.type(acorn, "30"); expect(acorn).toHaveValue(20); }); it("caps each leg at the due minus the other legs", async () => { const user = userEvent.setup(); render(); const product = await amountInput("Product"); await user.type(product, "80"); await user.type(screen.getByLabelText("Cash"), "10"); const acorn = await amountInput("Acorns"); await user.type(acorn, "20"); expect(acorn).toHaveValue(10); // 100 - 80 product - 10 cash }); it("the gateway leg shows the remainder", async () => { const user = userEvent.setup(); render(); await user.type(await amountInput("Product"), "50"); await user.type(await amountInput("Acorns"), "20"); await user.type(screen.getByLabelText("Cash"), "10"); expect(screen.getByTestId("split-remaining")).toHaveTextContent("RM 20.00"); await user.type(screen.getByLabelText("Gateway"), "20"); expect(screen.getByTestId("split-remaining")).toHaveTextContent("RM 0.00"); }); it("submits walletAmounts with cash and gateway, and no walletAmount or election", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: true, uuid: "u1" }); render(); await user.type(await amountInput("Product"), "50"); await user.type(await amountInput("Acorns"), "20"); await user.type(screen.getByLabelText("Cash"), "30"); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.click(placeBtn()); const payload = place.mock.calls[0][0]; expect(payload).toMatchObject({ walletAmounts: { PRODUCT: 50, ACORN: 20 }, cashAmount: 30, candidatePin: "1234", expectedTotal: 100, }); expect(payload).not.toHaveProperty("walletAmount"); expect(payload).not.toHaveProperty("election"); }); it("sends no PIN when no wallet amount is used", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: true, uuid: "u1" }); render(); await leg("Product"); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(place.mock.calls[0][0]).not.toHaveProperty("candidatePin"); }); it("the client key changes when a wallet amount changes and holds for an unchanged retry", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: false, messages: ["Gateway down"] }); render(); await user.type(await amountInput("Product"), "50"); await user.type(screen.getByLabelText("Cash"), "50"); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.click(placeBtn()); await screen.findByText(/Gateway down/); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.click(placeBtn()); // unchanged retry await screen.findByText(/Gateway down/); // Move 10 from cash to Acorns: a different split of the same total. await user.type(await amountInput("Acorns"), "10"); await user.clear(screen.getByLabelText("Cash")); await user.type(screen.getByLabelText("Cash"), "40"); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.click(placeBtn()); const [first, retry, changed] = place.mock.calls.map((c) => c[0].clientKey); expect(retry).toBe(first); expect(changed).not.toBe(first); }); it("a wallet refusal shows its message in the leg it names and keeps the panel", async () => { const user = userEvent.setup(); const place = vi .fn() .mockRejectedValue( new ApiError("refused", 400, { error: "refused", code: "AcornsOverYellowLabel", details: { walletTypeCode: "ACORN" } }), ); render(); await user.type(await amountInput("Acorns"), "20"); await user.type(screen.getByLabelText("Cash"), "80"); await user.type(screen.getByLabelText("Member PIN"), "1234"); await user.click(placeBtn()); const acorns = await leg("Acorns"); expect(await within(acorns).findByRole("alert")).toHaveTextContent(/yellow-label/i); expect(within(await leg("Product")).queryByRole("alert")).not.toBeInTheDocument(); expect(screen.queryByTestId("receipt")).not.toBeInTheDocument(); expect(screen.getByLabelText("Member PIN")).toHaveValue(""); }); it("a fulfilment refusal (422) names the product instead of a generic failure", async () => { const user = userEvent.setup(); const place = vi .fn() .mockRejectedValue( new ApiError("refused", 422, { error: "refused", code: "FulfilmentNotAllowed", details: { productCode: "P-PRAM" } }), ); const onFulfilmentRefused = vi.fn(); render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(await screen.findByText(/P-PRAM can't be sold with this fulfilment method/)).toBeInTheDocument(); // The page re-reads its products so the picker follows the new restriction. expect(onFulfilmentRefused).toHaveBeenCalledWith({ code: "FulfilmentNotAllowed", params: { name: "P-PRAM" } }); expect(screen.queryByTestId("receipt")).not.toBeInTheDocument(); }); }); describe("SplitTenderPanel — promotions (add-promotions-campaigns PR 2)", () => { afterEach(() => vi.clearAllMocks()); it("sends the applied code and confirms the net total it allocated", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: true, uuid: "u-1" }); render(); await user.type(screen.getByLabelText("Cash"), "80"); await user.click(placeBtn()); expect(place).toHaveBeenCalledWith(expect.objectContaining({ promoCode: "RAYA", expectedTotal: 80 })); }); it("without a code it still confirms the total, so an automatic offer cannot change silently", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: true, uuid: "u-2" }); render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(place.mock.calls[0][0].expectedTotal).toBe(100); expect(place.mock.calls[0][0]).not.toHaveProperty("promoCode"); }); it("a changed offer (412) shows the message and asks the page to re-price", async () => { const user = userEvent.setup(); const onOfferChanged = vi.fn(); const place = vi.fn().mockRejectedValue(new ApiError("An offer is no longer available, total updated", 412)); render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(await screen.findByText("An offer is no longer available, total updated")).toBeInTheDocument(); expect(onOfferChanged).toHaveBeenCalledTimes(1); }); it("any other failure does not re-price", async () => { const user = userEvent.setup(); const onOfferChanged = vi.fn(); const place = vi.fn().mockRejectedValue(new ApiError("Out of stock", 409)); render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(await screen.findByText("Out of stock")).toBeInTheDocument(); expect(onOfferChanged).not.toHaveBeenCalled(); }); }); describe("SplitTenderPanel — pending gateway sale", () => { afterEach(() => { vi.clearAllMocks(); vi.useRealTimers(); }); async function placeGatewaySale(props: Partial = {}) { const place = vi .fn() .mockResolvedValue({ success: true, uuid: "u1", redirectUrl: "https://pay.example/u1" }); const utils = render(); fireEvent.change(screen.getByLabelText("Gateway"), { target: { value: "100" } }); fireEvent.click(placeBtn()); await act(async () => { await vi.advanceTimersByTimeAsync(0); }); return utils; } it("reports pending while the QR shows and not pending after cancel", async () => { vi.useFakeTimers(); const onPendingChange = vi.fn(); await placeGatewaySale({ onPendingChange }); expect(screen.getByTestId("split-gateway-qr")).toBeInTheDocument(); expect(onPendingChange).toHaveBeenLastCalledWith(true); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); await act(async () => { await vi.advanceTimersByTimeAsync(0); }); expect(onPendingChange).toHaveBeenLastCalledWith(false); }); it("reports not pending once the payment fails", async () => { vi.useFakeTimers(); const onPendingChange = vi.fn(); await placeGatewaySale({ onPendingChange, poll: vi.fn().mockResolvedValue({ status: "FAILED" }), }); await act(async () => { await vi.advanceTimersByTimeAsync(2500); }); expect(onPendingChange).toHaveBeenLastCalledWith(false); }); it("shows the receipt built when the sale was placed, not one built at payment time", async () => { vi.useFakeTimers(); let buyer = "Alice"; const onReceipt = vi.fn(); await placeGatewaySale({ poll: vi.fn().mockResolvedValue({ status: "PAID" }), onReceipt, buildReceipt: (sale) => ({ ...sale, buyerName: buyer }), }); buyer = "Bob"; // the page's buyer changes while the QR is showing await act(async () => { await vi.advanceTimersByTimeAsync(2500); }); expect(onReceipt).toHaveBeenCalledWith(expect.objectContaining({ uuid: "u1", buyerName: "Alice" })); }); }); describe("SplitTenderPanel — sale fields from the page (redesign-pos-sale-flow)", () => { afterEach(() => vi.clearAllMocks()); it("forwards the page's fulfilment and walk-in fields with the split sale", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: true, uuid: "u-3" }); render( , ); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(place).toHaveBeenCalledWith( expect.objectContaining({ fulfilmentMode: "PICKUP", pickupBranchCode: "MYB", guestPhone: "0123456789", buyerType: "GUEST", cashAmount: 100, }), ); }); }); describe("SplitTenderPanel — in the payment dialog (redesign-pos-sale-flow review fixes)", () => { afterEach(() => vi.clearAllMocks()); it("reports busy while the sale is being placed, so the dialog cannot close mid-request", async () => { const user = userEvent.setup(); const onPendingChange = vi.fn(); render( {}))} onPendingChange={onPendingChange} />); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(onPendingChange).toHaveBeenLastCalledWith(true); }); it("pins Place split sale in an opaque footer, so fields scrolled under it never show through the disabled button", () => { render(); const footer = placeBtn().parentElement as HTMLElement; expect(placeBtn().className).not.toMatch(/\bsticky\b/); expect(footer.className).toMatch(/\bsticky\b/); expect(footer.className).toMatch(/\bbottom-0\b/); expect(footer.className).toMatch(/\bbg-background\b/); }); it("a panel remounted for the same cart and allocation retries with the same key", async () => { const user = userEvent.setup(); const place = vi.fn().mockResolvedValue({ success: false, messages: ["Gateway down"] }); const first = render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); first.unmount(); render(); await user.type(screen.getByLabelText("Cash"), "100"); await user.click(placeBtn()); expect(place).toHaveBeenCalledTimes(2); expect(place.mock.calls[1][0].clientKey).toBe(place.mock.calls[0][0].clientKey); }); }); describe("SplitTenderPanel — wallet balances line", () => { const noop = () => Promise.resolve({ success: true } as SplitSaleResult); const view = (balances: MemberWalletBalance[]): PosWalletBalanceView => ({ memberCode: "MY0001", memberName: "Test Member", balances, pinSet: true, locked: false, }); it("lists every enabled wallet balance in server order, Gift card through money formatting", () => { render( , ); expect(screen.getByTestId("split-wallet-balances").textContent).toBe( "Wallet balance: Product 120.00 · Acorns 45.00 · Gift card RM 64.00", ); }); it("omits disabled wallets, shows an enabled zero balance, and falls back to the raw code", () => { render( , ); expect(screen.getByTestId("split-wallet-balances").textContent).toBe( "Wallet balance: Product 0.00 · MYSTERY 3.00", ); }); it("renders nothing for a walk-in or a member with no enabled wallet", () => { const { unmount } = render(); expect(screen.queryByTestId("split-wallet-balances")).toBeNull(); unmount(); render(); expect(screen.queryByTestId("split-wallet-balances")).toBeNull(); }); }); describe("SplitTenderPanel — member change", () => { it("drops the old member's legs and amounts before the new member's preview resolves", async () => { const user = userEvent.setup(); const result = { orderTotal: 100, acornPaid: 0, productPaid: 0, applePaid: 0, gatewayResidual: 0, walletOptions: OPTIONS }; let resolveSecond: (v: typeof result) => void = () => {}; const previewWallet = vi .fn() .mockResolvedValueOnce(result) .mockReturnValueOnce(new Promise((r) => { resolveSecond = r; })); const { rerender } = render(); await user.type(await amountInput("Product"), "30"); expect(await amountInput("Product")).toHaveValue(30); rerender(); expect(screen.queryByRole("group", { name: "Product" })).not.toBeInTheDocument(); resolveSecond(result); expect(await amountInput("Product")).toHaveValue(null); }); });