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

872 lines
42 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 { PosSellableEvent, PosEventProduct, PosTender } from "@/app/lib/types";
// /pos Event POS — redesign-pos-sale-flow (BABYBOO-38): step bar, customer dialog, Take now / Pick up /
// Deliver, tap-to-add grid, payment dialog and receipt dialog, on top of the event picker.
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(() => ({
listSellableEvents: vi.fn(),
listEventProducts: vi.fn(),
listPosTenders: vi.fn(),
placeSale: vi.fn(),
readMemberWallet: vi.fn(),
previewWallet: vi.fn(),
placeWalletSale: vi.fn(),
quoteSale: vi.fn(),
placeSplitSale: vi.fn(),
pollSplitStatus: vi.fn(),
cancelSplit: vi.fn(),
listPosPickupOutlets: vi.fn(),
}));
vi.mock("@/app/lib/services/adminPos", () => ({
listSellableEvents: () => svc.listSellableEvents(),
listEventProducts: (eventId?: string) => svc.listEventProducts(eventId),
listPosTenders: () => svc.listPosTenders(),
placeSale: (p: unknown) => svc.placeSale(p),
readMemberWallet: (c: string) => svc.readMemberWallet(c),
previewWallet: (p: unknown) => svc.previewWallet(p),
placeWalletSale: (p: unknown) => svc.placeWalletSale(p),
quoteSale: (p: unknown) => svc.quoteSale(p),
placeSplitSale: (p: unknown) => svc.placeSplitSale(p),
pollSplitStatus: (uuid: string) => svc.pollSplitStatus(uuid),
cancelSplit: (uuid: string) => svc.cancelSplit(uuid),
listPosPickupOutlets: () => svc.listPosPickupOutlets(),
}));
// add-gift-card-counter
const gc = vi.hoisted(() => ({ check: vi.fn(), amounts: vi.fn(), sell: vi.fn() }));
vi.mock("@/app/lib/services/posGiftCards", async (orig) => ({
...(await orig<typeof import("@/app/lib/services/posGiftCards")>()),
checkPosGiftCard: (code: string) => gc.check(code),
listPosGiftCardAmounts: () => gc.amounts(),
sellEventGiftCard: (b: unknown) => gc.sell(b),
}));
const MEMBER = {
memberCode: "MY0001",
name: "Test Member",
phoneNoPrefix: "60",
phoneNo: "123456789",
addressDetails: "1 Jalan B, Petaling Jaya",
postCode: "47300",
};
vi.mock("@/app/components/members/MemberSearchCombobox", () => ({
MemberSearchCombobox: ({ onSelect }: { onSelect: (m: typeof MEMBER) => void }) => (
<button type="button" onClick={() => onSelect(MEMBER)}>
select member
</button>
),
}));
import PosPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
import type { MemberCheckoutPreviewResult, PosQuotePayload } from "@/app/lib/types";
// add-event-summary: the feed now carries the sales window and a sellable flag.
const LIVE = { salesFrom: "2020-01-01T00:00", salesTo: "2099-12-31T23:59", sellable: true };
const EVENT: PosSellableEvent = { id: "ev-1", name: "Summer Fair", warehouseId: "wh-1", ...LIVE };
const EVENT2: PosSellableEvent = { id: "ev-2", name: "Winter Market", warehouseId: "wh-2", ...LIVE };
const ENDED: PosSellableEvent = { id: "ev-3", name: "Penang Fair", warehouseId: "wh-3", salesFrom: "2020-09-12T10:00", salesTo: "2020-09-14T22:00", sellable: false };
const UPCOMING: PosSellableEvent = { id: "ev-4", name: "Mid Valley Fair", warehouseId: "wh-4", salesFrom: "2099-10-16T10:00", salesTo: "2099-10-18T22:00", sellable: false };
const PRODUCTS: PosEventProduct[] = [
{ pPricingId: "p1", variationId: "v1", label: "Coffee", unitPrice: 5, productCode: "C1", sku: "", category: "Drinks", imageUrl: "https://cdn.example/coffee.png" },
{ pPricingId: "p2", variationId: "v2", label: "Cake", unitPrice: 8, productCode: "C2", sku: "", category: "Food" },
];
const TENDERS: PosTender[] = [
{ id: "tm-cash", label: "Cash", paymentType: "PC", wallet: false },
{ id: "tm-card", label: "Terminal", paymentType: "CC", wallet: false },
{ id: "tm-wallet", label: "Member Wallet", paymentType: "DWP", wallet: true },
];
const OUTLETS = [{ branchCode: "MYB", name: "HQ", warehouseId: "2" }];
function grossQuote(p: PosQuotePayload, over: Partial<MemberCheckoutPreviewResult> = {}): MemberCheckoutPreviewResult {
const gross = p.lines.reduce(
(sum, l) => sum + (PRODUCTS.find((x) => x.pPricingId === l.pPricingId)?.unitPrice ?? 0) * l.qty, 0);
return {
orderTotal: gross, acornPaid: 0, productPaid: 0, applePaid: 0, gatewayResidual: 0,
grossTotal: gross, discountTotal: 0, discountLines: [], promoCode: p.promoCode ?? null, ...over,
};
}
function raya(p: PosQuotePayload): MemberCheckoutPreviewResult {
return grossQuote(p, {
orderTotal: 4, grossTotal: 5, discountTotal: 1,
discountLines: [{ lineIndex: 0, productCode: "C1", campaignLabel: "RAYA RM1", amount: 1 }],
promoCode: p.promoCode ? p.promoCode.toUpperCase() : null,
});
}
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
auth.hasModule.mockReturnValue(true);
svc.listSellableEvents.mockResolvedValue([EVENT]);
svc.listEventProducts.mockResolvedValue(PRODUCTS);
svc.listPosTenders.mockResolvedValue(TENDERS);
svc.listPosPickupOutlets.mockResolvedValue(OUTLETS);
svc.placeSale.mockResolvedValue({ documentNo: "DOC-1", uuid: "uuid-1" });
svc.quoteSale.mockImplementation((p: PosQuotePayload) => Promise.resolve(grossQuote(p)));
svc.readMemberWallet.mockResolvedValue({
memberCode: "MY0001", memberName: "Test Member", pinSet: true, locked: false,
balances: [{ walletTypeCode: "PRODUCT", balance: 100, enabled: "Y" }],
});
svc.previewWallet.mockResolvedValue({
orderTotal: 5, productPaid: 0, acornPaid: 0, applePaid: 0, gatewayResidual: 0,
walletOptions: [{ walletTypeCode: "PRODUCT", balance: 100, max: 5 }, { walletTypeCode: "ACORN", balance: 30, max: 2 }],
});
svc.placeWalletSale.mockResolvedValue({ success: true, orderUuid: "uuid-w", pinVerifyStatus: "OK" });
});
type User = ReturnType<typeof userEvent.setup>;
const charge = () => screen.getByRole("button", { name: /^Charge/ });
// hidden: a modal dialog marks the page behind it aria-hidden, and some checks look behind it.
const eventPicker = () => screen.getByRole("combobox", { name: /event/i, hidden: true });
async function addCoffee(user: User) {
await user.click(await screen.findByRole("button", { name: /^Add Coffee/ }));
}
async function openPayment(user: User) {
await waitFor(() => expect(charge()).toBeEnabled());
await user.click(charge());
return screen.findByRole("dialog", { name: "Payment" });
}
async function completeSale(user: User) {
await waitFor(() => expect(screen.getByRole("button", { name: "Complete sale" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Complete sale" }));
}
/** DWL: the operator now enters how much each wallet pays (free-wallet-split) before the PIN. */
async function enterWalletAmount(user: User, wallet: string, amount: string) {
const input = await screen.findByLabelText(`${wallet} amount`);
await user.clear(input);
await user.type(input, amount);
}
async function chooseMember(user: User) {
await user.click(screen.getByRole("button", { name: /Add customer|Change/ }));
await user.click(await screen.findByRole("button", { name: "select member" }));
await screen.findByText(/PRODUCT 100\.00/);
}
describe("Event POS — event picker", () => {
it("preselects the only sellable event and shows the step bar beside it", async () => {
render(<PosPage />);
await waitFor(() => expect(eventPicker()).toHaveTextContent("Summer Fair"));
expect(screen.getByRole("list", { name: "Sale progress" })).toBeInTheDocument();
});
it("restores the last-picked event when several are open, and writes a new pick", async () => {
svc.listSellableEvents.mockResolvedValue([EVENT, EVENT2]);
localStorage.setItem("pos.lastEventId", "ev-2");
const user = userEvent.setup();
render(<PosPage />);
await waitFor(() => expect(eventPicker()).toHaveTextContent("Winter Market"));
await user.click(eventPicker());
await user.click(await screen.findByRole("option", { name: /^Summer Fair/ }));
expect(localStorage.getItem("pos.lastEventId")).toBe("ev-1");
});
it("does not restore a remembered event that has closed", async () => {
svc.listSellableEvents.mockResolvedValue([EVENT, EVENT2]);
localStorage.setItem("pos.lastEventId", "ev-closed");
render(<PosPage />);
await waitFor(() => expect(eventPicker()).toHaveTextContent(/select an event/i));
});
it("selects the only sellable event even when upcoming and ended events are listed", async () => { // add-event-summary
svc.listSellableEvents.mockResolvedValue([EVENT, UPCOMING, ENDED]);
render(<PosPage />);
await waitFor(() => expect(eventPicker()).toHaveTextContent("Summer Fair"));
});
it("does not restore an ended event", async () => { // add-event-summary
svc.listSellableEvents.mockResolvedValue([EVENT, EVENT2, ENDED]);
localStorage.setItem("pos.lastEventId", "ev-3");
render(<PosPage />);
await waitFor(() => expect(eventPicker()).toHaveTextContent(/select an event/i));
expect(svc.listEventProducts).not.toHaveBeenCalledWith("ev-3");
});
it("says nothing is open for sales when the feed holds only upcoming and ended events", async () => { // review fix
svc.listSellableEvents.mockResolvedValue([UPCOMING, ENDED]);
render(<PosPage />);
expect(await screen.findByText(/No sellable events right now/)).toBeInTheDocument();
expect(eventPicker()).toBeInTheDocument();
});
it("shows upcoming and ended events with their state but does not let them be picked", async () => { // add-event-summary
svc.listSellableEvents.mockResolvedValue([EVENT, UPCOMING, ENDED]);
const user = userEvent.setup();
render(<PosPage />);
await waitFor(() => expect(eventPicker()).toHaveTextContent("Summer Fair"));
await user.click(eventPicker());
expect(await screen.findByRole("option", { name: /^Mid Valley Fair.*Starts 16 Oct/ })).toHaveAttribute("aria-disabled", "true");
await user.click(screen.getByRole("option", { name: /^Penang Fair.*Ended/ }));
expect(eventPicker()).toHaveTextContent("Summer Fair");
});
it("re-reads the product feed for the event and shows its stock state", async () => {
svc.listEventProducts.mockImplementation((eventId?: string) =>
Promise.resolve(eventId ? [{ ...PRODUCTS[0], availability: "SOLD_OUT" }, PRODUCTS[1]] : PRODUCTS));
render(<PosPage />);
await waitFor(() => expect(svc.listEventProducts).toHaveBeenCalledWith(EVENT.id));
await waitFor(() => expect(screen.getByRole("button", { name: /^Add Coffee/ })).toBeDisabled());
expect(screen.getByRole("button", { name: /^Add Coffee/ })).toHaveTextContent("Order in");
expect(screen.getByRole("button", { name: /^Add Cake/ })).toBeEnabled();
});
it("a pre-order product blocks Take now at the event, naming it", async () => {
svc.listEventProducts.mockImplementation((eventId?: string) =>
Promise.resolve(eventId ? [{ ...PRODUCTS[0], availability: "PRE_ORDER" }, PRODUCTS[1]] : PRODUCTS));
const user = userEvent.setup();
render(<PosPage />);
await waitFor(() => expect(svc.listEventProducts).toHaveBeenCalledWith(EVENT.id));
await addCoffee(user);
expect(await screen.findByText("Coffee is not in stock here. Choose Pick up or Deliver, or remove it.")).toBeInTheDocument();
});
it("changing the event clears the cart", async () => {
svc.listSellableEvents.mockResolvedValue([EVENT, EVENT2]);
const user = userEvent.setup();
render(<PosPage />);
await user.click(await screen.findByRole("combobox", { name: /event/i }));
await user.click(await screen.findByRole("option", { name: /^Summer Fair/ }));
await addCoffee(user);
expect(screen.getByTestId("cart-total")).toHaveTextContent("RM 5.00");
await user.click(eventPicker());
await user.click(await screen.findByRole("option", { name: /^Winter Market/ }));
expect(screen.getByText("No items yet")).toBeInTheDocument();
});
});
describe("Event POS — sale flow", () => {
it("a walk-in cash sale carries the event, take now, and Start new sale keeps the event", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
expect(screen.getByTestId(/^cart-image-/)).toHaveAttribute("src", "https://cdn.example/coffee.png");
const dialog = await openPayment(user);
expect(within(dialog).getByRole("radio", { name: /Cash/ })).toHaveAttribute("aria-checked", "true");
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expect(within(receipt).getByTestId("receipt-collection")).toHaveTextContent("Taken in store");
expect(within(receipt).getByText("Summer Fair")).toBeInTheDocument();
// BABYBOO-39: the product-name cell wraps (class-level check; jsdom has no layout to measure overflow).
expect(within(receipt).getByRole("cell", { name: "Coffee" })).toHaveClass("whitespace-normal", "[overflow-wrap:anywhere]");
expect(within(receipt).getByRole("cell", { name: "Coffee" })).not.toHaveClass("break-words");
// overflow-wrap is inherited: the header <dl> carries it once; amounts (wallet-split <dl>) stay plain.
const [header, ...others] = Array.from(receipt.querySelectorAll("dl"));
expect(header).toHaveClass("[overflow-wrap:anywhere]");
others.forEach((dl) => expect(dl).not.toHaveClass("[overflow-wrap:anywhere]"));
receipt.querySelectorAll("dd").forEach((dd) => expect(dd).not.toHaveClass("[overflow-wrap:anywhere]"));
expect(svc.placeSale).toHaveBeenCalledWith(
expect.objectContaining({ eventId: "ev-1", buyerType: "GUEST", paymentMethodId: "tm-cash", fulfilmentMode: "TAKE_NOW" }),
);
await user.click(within(receipt).getByRole("button", { name: "Start new sale" }));
expect(screen.getByText("No items yet")).toBeInTheDocument();
expect(eventPicker()).toHaveTextContent("Summer Fair");
expect(svc.listSellableEvents).toHaveBeenCalledTimes(1);
});
it("Start new sale re-reads the event's products so the next sale sees fresh stock", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
const reads = svc.listEventProducts.mock.calls.filter((c) => c[0] === "ev-1").length;
await user.click(within(receipt).getByRole("button", { name: "Start new sale" }));
await waitFor(() => expect(svc.listEventProducts.mock.calls.filter((c) => c[0] === "ev-1").length).toBe(reads + 1));
});
it("Start new sale clears the product search so the next customer sees the full grid", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await user.type(screen.getByRole("searchbox", { name: /Scan barcode/ }), "coff");
expect(screen.queryByRole("button", { name: /^Add Cake/ })).not.toBeInTheDocument();
await openPayment(user);
await completeSale(user);
await user.click(await screen.findByRole("button", { name: "Start new sale" }));
expect(await screen.findByRole("button", { name: /^Add Cake/ })).toBeInTheDocument();
expect(screen.getByRole("searchbox", { name: /Scan barcode/ })).toHaveValue("");
});
it("a failed sale stays in the payment dialog with its error", async () => {
svc.placeSale.mockRejectedValue(new Error("Out of stock at the event"));
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
const dialog = await openPayment(user);
await completeSale(user);
expect(await within(dialog).findByRole("alert")).toHaveTextContent("Out of stock at the event");
expect(screen.queryByRole("dialog", { name: "Payment complete" })).not.toBeInTheDocument();
});
it("a member's wallet sale carries the event and the member's PIN", async () => {
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await chooseMember(user);
await addCoffee(user);
await openPayment(user);
await user.click(screen.getByRole("radio", { name: /Member Wallet/ }));
await enterWalletAmount(user, "Product", "5");
await user.type(await screen.findByLabelText(/member pin/i), "1234");
await completeSale(user);
await screen.findByRole("dialog", { name: "Payment complete" });
expect(svc.placeWalletSale).toHaveBeenCalledWith(
expect.objectContaining({ eventId: "ev-1", memberCode: "MY0001", candidatePin: "1234", fulfilmentMode: "TAKE_NOW" }),
);
});
it("the wallet card is members-only for a walk-in", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
expect(screen.getByRole("radio", { name: /Member Wallet/ })).toBeDisabled();
});
it("no configured tenders shows an empty state and no Charge", async () => {
svc.listPosTenders.mockResolvedValue([]);
render(<PosPage />);
expect(await screen.findByText(/No POS payment methods configured/)).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /^Charge/ })).not.toBeInTheDocument();
});
});
describe("Event POS — pick up and deliver", () => {
it("Pick up sends the outlet with the event sale", async () => {
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await chooseMember(user);
await addCoffee(user);
await user.click(screen.getByRole("radio", { name: "Pick up" }));
expect(charge()).toBeDisabled();
await user.click(await screen.findByRole("radio", { name: "HQ (MYB)" }));
await openPayment(user);
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expect(within(receipt).getByTestId("receipt-collection")).toHaveTextContent("Pick up at HQ");
expect(svc.placeSale).toHaveBeenCalledWith(
expect.objectContaining({ eventId: "ev-1", fulfilmentMode: "PICKUP", pickupBranchCode: "MYB" }),
);
});
it("Deliver sends the member's pre-filled address", async () => {
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await chooseMember(user);
await addCoffee(user);
await user.click(screen.getByRole("radio", { name: "Deliver" }));
await openPayment(user);
await completeSale(user);
await screen.findByRole("dialog", { name: "Payment complete" });
expect(svc.placeSale).toHaveBeenCalledWith(
expect.objectContaining({
fulfilmentMode: "DELIVERY",
receiver: "Test Member",
contactNo: "60123456789",
addressDetails: "1 Jalan B, Petaling Jaya",
postcode: "47300",
}),
);
});
});
describe("Event POS — quote carries the event", () => { // SG 7b: the quote prices in the event's branch country
it("sends the selected event's id with the cart quote", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await waitFor(() => expect(svc.quoteSale).toHaveBeenCalledWith(expect.objectContaining({ eventId: "ev-1" })));
});
});
describe("Event POS — promotions", () => {
it("a walk-in cash sale confirms the net total and prints the discount", async () => {
svc.quoteSale.mockImplementation((p: PosQuotePayload) => Promise.resolve(raya(p)));
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
expect(await screen.findByTestId(/^line-discount-/)).toHaveTextContent("RAYA RM1 -RM 1.00");
expect(screen.getByTestId("cart-total")).toHaveTextContent("RM 4.00");
await openPayment(user);
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expect(svc.placeSale).toHaveBeenCalledWith(expect.objectContaining({ expectedTotal: 4 }));
expect(within(receipt).getByText("Discount (RAYA RM1)")).toBeInTheDocument();
expect(within(receipt).getByTestId("receipt-total")).toHaveTextContent("RM 4.00");
});
it("a cart that cannot be priced cannot be charged, and says why", async () => {
svc.quoteSale.mockRejectedValue(new Error("A product line is not available in the current sale catalogue."));
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not price the cart");
expect(charge()).toBeDisabled();
});
it("an offer that changed before the sale is explained in the dialog and re-priced", async () => {
svc.quoteSale.mockImplementation((p: PosQuotePayload) => Promise.resolve(raya(p)));
svc.placeSale.mockRejectedValueOnce(new ApiError("An offer is no longer available, total updated", 412));
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await screen.findByTestId(/^line-discount-/);
svc.quoteSale.mockImplementation((p: PosQuotePayload) => Promise.resolve(grossQuote(p)));
const dialog = await openPayment(user);
await completeSale(user);
expect(await within(dialog).findByRole("alert")).toHaveTextContent("An offer is no longer available, total updated");
await waitFor(() => expect(within(dialog).getByTestId("amount-due")).toHaveTextContent("RM 5.00"));
expect(screen.queryByRole("dialog", { name: "Payment complete" })).not.toBeInTheDocument();
});
it("Start new sale clears the promo code", async () => {
svc.quoteSale.mockImplementation((p: PosQuotePayload) => Promise.resolve(p.promoCode ? raya(p) : grossQuote(p)));
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await user.type(screen.getByLabelText("Promo code"), "raya");
await user.click(screen.getByRole("button", { name: "Apply" }));
await screen.findByText("RAYA applied");
await openPayment(user);
await completeSale(user);
await user.click(await screen.findByRole("button", { name: "Start new sale" }));
await addCoffee(user);
await waitFor(() => expect(svc.quoteSale).toHaveBeenLastCalledWith({ eventId: "ev-1", lines: [{ pPricingId: "p1", qty: 1 }] }));
});
});
describe("Event POS — split sale", () => {
beforeEach(() => {
svc.placeSplitSale.mockResolvedValue({ success: true, uuid: "u1", redirectUrl: "https://pay.example/u1" });
svc.pollSplitStatus.mockResolvedValue({ status: "PENDING" });
svc.cancelSplit.mockResolvedValue(true);
});
it("a restriction landing while a split gateway payment is pending waits: payment stays open and locked", async () => {
let land: (p: unknown) => void = () => {};
svc.placeSale.mockImplementationOnce(() => {
const slow = new Promise((r) => (land = r));
svc.listEventProducts.mockImplementation((eventId?: string) => (eventId ? slow : Promise.resolve(PRODUCTS)));
return Promise.reject(new ApiError("FulfilmentNotAllowed", 422, { code: "FulfilmentNotAllowed", details: { productCode: "C1" } }));
});
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
await completeSale(user);
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Payment" })).not.toBeInTheDocument());
await openPayment(user);
await user.click(screen.getByRole("radio", { name: /Split/ }));
await user.type(screen.getByLabelText("Gateway"), "5");
await user.click(screen.getByRole("button", { name: /place split sale/i }));
expect(await screen.findByTestId("split-gateway-qr")).toBeInTheDocument();
land([{ ...PRODUCTS[0], fulfilment: "DELIVERY_ONLY" }, PRODUCTS[1]]);
await new Promise((r) => setTimeout(r, 50));
// The customer may be paying: never close or unlock a pending gateway sale.
expect(screen.getByRole("dialog", { name: "Payment" })).toBeInTheDocument();
expect(screen.getByTestId("split-gateway-qr")).toBeInTheDocument();
});
it("locks the sale and the event while the gateway QR is pending, and Cancel unlocks it", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
await user.click(screen.getByRole("radio", { name: /Split/ }));
await user.type(screen.getByLabelText("Gateway"), "5");
await user.click(screen.getByRole("button", { name: /place split sale/i }));
expect(await screen.findByTestId("split-gateway-qr")).toBeInTheDocument();
expect(screen.getByRole("button", { name: /Back to sale/ })).toBeDisabled();
expect(eventPicker()).toBeDisabled();
expect(svc.placeSplitSale).toHaveBeenCalledWith(expect.objectContaining({ eventId: "ev-1", fulfilmentMode: "TAKE_NOW" }));
await user.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.getByRole("button", { name: /Back to sale/ })).toBeEnabled();
expect(eventPicker()).toBeEnabled();
});
it("a gift card that covers the sale goes with the event sale (add-gift-card-counter)", async () => {
gc.check.mockResolvedValue({ balance: 100, expiresAt: "2029-10-09", last4: "5678" });
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
const dialog = await openPayment(user);
await user.type(within(dialog).getByLabelText(/gift card code/i), "ABCD1234EFGH5678");
await user.click(within(dialog).getByRole("button", { name: /^apply/i }));
expect(await within(dialog).findByText(/left to pay/i)).toBeInTheDocument();
await user.click(within(dialog).getByRole("button", { name: "Complete sale" }));
await waitFor(() => expect(svc.placeSale).toHaveBeenCalledTimes(1));
expect(svc.placeSale).toHaveBeenCalledWith(
expect.objectContaining({ eventId: "ev-1", giftCardCodes: ["ABCD1234EFGH5678"] }),
);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expect(within(receipt).getByText(/^Gift card •••• 5678 RM\s?5\.00$/)).toBeInTheDocument();
});
it("Sell gift card sells for the selected event (add-gift-card-counter)", async () => {
gc.amounts.mockResolvedValue([{ id: 1, amount: 50, active: "Y", sortOrder: 1 }]);
gc.sell.mockResolvedValue({ saleUuid: "s1", code: "ABCD1234EFGH5678", last4: "5678", amount: 50, expiresAt: "2029-10-09" });
const user = userEvent.setup();
render(<PosPage />);
const sellButton = await screen.findByRole("button", { name: "Sell gift card" });
await waitFor(() => expect(sellButton).toBeEnabled());
await user.click(sellButton);
const dialog = await screen.findByRole("dialog", { name: "Sell gift card" });
await user.click(await within(dialog).findByRole("radio", { name: /RM\s?50\.00/ }));
await user.click(within(dialog).getByRole("radio", { name: /Cash/ }));
await user.click(within(dialog).getByRole("button", { name: /^sell/i }));
expect(await within(dialog).findByText("ABCD-1234-EFGH-5678")).toBeInTheDocument();
expect(gc.sell).toHaveBeenCalledWith(expect.objectContaining({ eventId: "ev-1", amount: 50 }));
});
});
// BABYBOO-39 item 3: the receipt names the event warehouse by its code (never the raw id) and labels the
// tender "Payment Method".
describe("Event POS — receipt names the warehouse and payment method", () => {
const EXPO: PosSellableEvent = {
id: "ev-8", name: "MV Expo", warehouseId: "44", warehouseCode: "EVT-MV-EXPO-004", warehouseName: "MV Expo WH", ...LIVE,
};
const field = (receipt: HTMLElement, label: string) =>
within(receipt).getByText(label, { selector: "dt" }).nextElementSibling;
const expectReceipt = (receipt: HTMLElement, warehouse: string, payment: string, rawId: string) => {
expect(field(receipt, "Warehouse")).toHaveTextContent(warehouse);
expect(field(receipt, "Payment Method")).toHaveTextContent(payment);
expect(within(receipt).queryByText("Tender")).not.toBeInTheDocument();
expect(receipt.textContent).not.toContain(rawId);
};
it("a cash sale's receipt shows the warehouse code, not the id", async () => {
svc.listSellableEvents.mockResolvedValue([EXPO]);
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expectReceipt(receipt, "EVT-MV-EXPO-004", "Cash", "44");
});
it("a wallet sale's receipt shows the warehouse code and Payment Method", async () => {
svc.listSellableEvents.mockResolvedValue([EXPO]);
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await chooseMember(user);
await addCoffee(user);
await openPayment(user);
await user.click(screen.getByRole("radio", { name: /Member Wallet/ }));
await enterWalletAmount(user, "Product", "5");
await user.type(await screen.findByLabelText(/member pin/i), "1234");
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expectReceipt(receipt, "EVT-MV-EXPO-004", "Member Wallet", "44");
});
it("a split sale's receipt shows the warehouse code and Payment Method", async () => {
svc.listSellableEvents.mockResolvedValue([EXPO]);
svc.placeSplitSale.mockResolvedValue({ success: true, uuid: "u2", documentNo: "DOC-2" });
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
await user.click(screen.getByRole("radio", { name: /Split/ }));
await user.type(screen.getByLabelText("Cash"), "5");
await user.click(screen.getByRole("button", { name: /place split sale/i }));
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expectReceipt(receipt, "EVT-MV-EXPO-004", "Split", "44");
});
it("shows — when the warehouse code is unknown, never the raw id", async () => {
const user = userEvent.setup();
render(<PosPage />);
await addCoffee(user);
await openPayment(user);
await completeSale(user);
const receipt = await screen.findByRole("dialog", { name: "Payment complete" });
expectReceipt(receipt, "—", "Cash", "wh-1");
});
});
describe("Event POS — wallet tender, per-wallet amounts (free-wallet-split)", () => {
async function openWalletCard(user: User) {
await screen.findByRole("button", { name: /^Add Coffee/ });
await chooseMember(user);
await addCoffee(user);
await openPayment(user);
await user.click(screen.getByRole("radio", { name: /Member Wallet/ }));
}
it("hides the wallet tender when every balance is 0", async () => {
svc.readMemberWallet.mockResolvedValue({
memberCode: "MY0001", memberName: "Test Member", pinSet: true, locked: false,
balances: [{ walletTypeCode: "PRODUCT", balance: 0, enabled: "Y" }, { walletTypeCode: "ACORN", balance: 0, enabled: "Y" }],
});
svc.previewWallet.mockResolvedValue({
orderTotal: 5, productPaid: 0, acornPaid: 0, applePaid: 0, gatewayResidual: 0, walletOptions: [],
});
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await user.click(screen.getByRole("button", { name: /Add customer|Change/ }));
await user.click(await screen.findByRole("button", { name: "select member" }));
await addCoffee(user);
await openPayment(user);
await waitFor(() => expect(svc.readMemberWallet).toHaveBeenCalled());
await waitFor(() => expect(screen.queryByRole("radio", { name: /Member Wallet/ })).not.toBeInTheDocument());
});
it("shows a leg for each wallet the preview offers", async () => {
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
expect(await screen.findByRole("group", { name: "Product" })).toBeInTheDocument();
expect(screen.getByRole("group", { name: "Acorns" })).toBeInTheDocument();
});
it("Complete sale stays disabled until the amounts equal the total exactly", async () => {
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
await user.type(await screen.findByLabelText(/member pin/i), "1234");
expect(screen.getByRole("button", { name: "Complete sale" })).toBeDisabled();
await enterWalletAmount(user, "Product", "3");
expect(screen.getByRole("button", { name: "Complete sale" })).toBeDisabled(); // 3 of 5
await enterWalletAmount(user, "Acorns", "2");
await waitFor(() => expect(screen.getByRole("button", { name: "Complete sale" })).toBeEnabled());
});
it("the sale carries walletAmounts and no election or single walletAmount", async () => {
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
await enterWalletAmount(user, "Product", "3");
await enterWalletAmount(user, "Acorns", "2");
await user.type(await screen.findByLabelText(/member pin/i), "1234");
await completeSale(user);
await screen.findByRole("dialog", { name: "Payment complete" });
const payload = svc.placeWalletSale.mock.calls[0][0];
expect(payload).toMatchObject({
eventId: "ev-1", memberCode: "MY0001", candidatePin: "1234", walletAmounts: { PRODUCT: 3, ACORN: 2 },
});
expect(payload).not.toHaveProperty("election");
expect(payload).not.toHaveProperty("walletAmount");
});
// The preview only supplies walletOptions; amounts are checked at sale time, so a refused amount
// never blanks the legs during a cart change or Refresh.
it("the wallet preview body carries neither walletAmounts nor an election", async () => {
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
await screen.findByRole("group", { name: "Product" });
expect(svc.previewWallet).toHaveBeenCalled();
for (const [payload] of svc.previewWallet.mock.calls) {
expect(payload).not.toHaveProperty("walletAmounts");
expect(payload).not.toHaveProperty("election");
}
});
it("a retry keeps the idempotency key, a corrected amount gets a new one", async () => {
svc.placeWalletSale.mockResolvedValue({ success: false, pinVerifyStatus: "FAIL" });
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
await enterWalletAmount(user, "Product", "5");
await user.type(await screen.findByLabelText(/member pin/i), "1234");
await completeSale(user);
await screen.findByRole("alert");
await user.type(screen.getByLabelText(/member pin/i), "1234");
await completeSale(user); // unchanged retry
await screen.findByRole("alert");
await enterWalletAmount(user, "Product", "3");
await enterWalletAmount(user, "Acorns", "2");
await user.type(screen.getByLabelText(/member pin/i), "1234");
await completeSale(user);
await waitFor(() => expect(svc.placeWalletSale).toHaveBeenCalledTimes(3));
const [first, retry, changed] = svc.placeWalletSale.mock.calls.map((c) => c[0].clientKey);
expect(retry).toBe(first);
expect(changed).not.toBe(first);
});
it("a wallet refusal shows in the leg it names", async () => {
svc.placeWalletSale.mockRejectedValue(
new ApiError("refused", 400, { error: "refused", code: "WalletAmountOverBalance", details: { walletTypeCode: "PRODUCT" } }),
);
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
await enterWalletAmount(user, "Product", "5");
await user.type(await screen.findByLabelText(/member pin/i), "1234");
await completeSale(user);
const product = await screen.findByRole("group", { name: "Product" });
expect(await within(product).findByRole("alert")).toHaveTextContent(/more than the member's Product balance/i);
expect(screen.queryByRole("dialog", { name: "Payment complete" })).not.toBeInTheDocument();
});
it("the PIN step is unchanged: a wrong PIN shows the error and clears the field", async () => {
svc.placeWalletSale.mockResolvedValue({ success: false, pinVerifyStatus: "FAIL" });
const user = userEvent.setup();
render(<PosPage />);
await openWalletCard(user);
await enterWalletAmount(user, "Product", "5");
await user.type(await screen.findByLabelText(/member pin/i), "1234");
await completeSale(user);
expect(await screen.findByRole("alert")).toHaveTextContent(/incorrect pin/i);
expect(screen.getByLabelText(/member pin/i)).toHaveValue("");
});
});
describe("Event POS — product fulfilment restriction", () => {
const restricted = (fulfilment: "PICKUP_ONLY" | "DELIVERY_ONLY") => () =>
svc.listEventProducts.mockImplementation((eventId?: string) =>
Promise.resolve(eventId ? [{ ...PRODUCTS[0], fulfilment }, PRODUCTS[1]] : PRODUCTS));
it("a delivery-only line moves the sale to Deliver and disables the other options", async () => {
restricted("DELIVERY_ONLY")();
const user = userEvent.setup();
render(<PosPage />);
await waitFor(() => expect(svc.listEventProducts).toHaveBeenCalledWith(EVENT.id));
await chooseMember(user);
await addCoffee(user);
await waitFor(() => expect(screen.getByRole("radio", { name: "Deliver" })).toHaveAttribute("aria-checked", "true"));
expect(screen.getByRole("radio", { name: "Take now" })).toBeDisabled();
expect(screen.getByRole("radio", { name: "Pick up" })).toBeDisabled();
expect(screen.getByDisplayValue("Test Member")).toBeInTheDocument();
});
it("a pickup-only line blocks Deliver, naming it, and keeps Take now", async () => {
restricted("PICKUP_ONLY")();
const user = userEvent.setup();
render(<PosPage />);
await waitFor(() => expect(svc.listEventProducts).toHaveBeenCalledWith(EVENT.id));
await addCoffee(user);
expect(screen.getByRole("radio", { name: "Take now" })).toHaveAttribute("aria-checked", "true");
expect(screen.getByRole("radio", { name: "Deliver" })).toBeDisabled();
expect(screen.getByRole("radio", { name: "Deliver" })).toHaveAccessibleDescription("Coffee is pickup only");
});
it("a refused sale closes payment and names the product on the order pane", async () => {
svc.placeSale.mockRejectedValue(
new ApiError("FulfilmentNotAllowed", 422, { code: "FulfilmentNotAllowed", details: { productCode: "C1" } }),
);
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await addCoffee(user);
await openPayment(user);
await completeSale(user);
// Closed, so a second click can't send a fulfilment the re-read products changed behind the dialog.
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Payment" })).not.toBeInTheDocument());
expect(screen.getByRole("alert")).toHaveTextContent("Coffee can't be sold with this fulfilment method.");
});
it("a restriction that moves the fulfilment while payment is open closes payment", async () => {
let land: (p: unknown) => void = () => {};
svc.placeSale.mockImplementationOnce(() => {
const slow = new Promise((r) => (land = r));
svc.listEventProducts.mockImplementation((eventId?: string) => (eventId ? slow : Promise.resolve(PRODUCTS)));
return Promise.reject(new ApiError("FulfilmentNotAllowed", 422, { code: "FulfilmentNotAllowed", details: { productCode: "C1" } }));
});
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await addCoffee(user);
await openPayment(user);
await completeSale(user);
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Payment" })).not.toBeInTheDocument());
await openPayment(user);
land([{ ...PRODUCTS[0], fulfilment: "DELIVERY_ONLY" }, PRODUCTS[1]]);
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Payment" })).not.toBeInTheDocument());
expect(screen.getByRole("radio", { name: "Deliver" })).toHaveAttribute("aria-checked", "true");
});
it("a restriction landing while a sale is being placed waits until the sale settles", async () => {
let land: (p: unknown) => void = () => {};
let settle: (e: unknown) => void = () => {};
svc.placeSale
.mockImplementationOnce(() => {
const slow = new Promise((r) => (land = r));
svc.listEventProducts.mockImplementation((eventId?: string) => (eventId ? slow : Promise.resolve(PRODUCTS)));
return Promise.reject(new ApiError("FulfilmentNotAllowed", 422, { code: "FulfilmentNotAllowed", details: { productCode: "C1" } }));
})
.mockImplementationOnce(() => new Promise((_, reject) => (settle = reject)));
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await addCoffee(user);
await openPayment(user);
await completeSale(user);
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Payment" })).not.toBeInTheDocument());
await openPayment(user);
await completeSale(user); // hangs: the sale is being placed
land([{ ...PRODUCTS[0], fulfilment: "DELIVERY_ONLY" }, PRODUCTS[1]]);
await new Promise((r) => setTimeout(r, 50));
expect(screen.getByRole("dialog", { name: "Payment" })).toBeInTheDocument();
settle(new ApiError("Boom", 500, {}));
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Payment" })).not.toBeInTheDocument());
expect(screen.getByRole("radio", { name: "Deliver" })).toHaveAttribute("aria-checked", "true");
});
it("re-reads the products after a refused sale, so the picker follows the product's new restriction", async () => {
svc.placeSale.mockImplementation(() => {
restricted("DELIVERY_ONLY")(); // an admin restricted Coffee after it went into the cart
return Promise.reject(new ApiError("FulfilmentNotAllowed", 422, { code: "FulfilmentNotAllowed", details: { productCode: "C1" } }));
});
const user = userEvent.setup();
render(<PosPage />);
await screen.findByRole("button", { name: /^Add Coffee/ });
await addCoffee(user);
await openPayment(user);
await completeSale(user);
await waitFor(() => expect(screen.getByRole("radio", { name: "Take now" })).toBeDisabled());
expect(screen.getByRole("radio", { name: "Deliver" })).toHaveAttribute("aria-checked", "true");
});
});