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

277 lines
13 KiB
TypeScript

import { describe, it, expect, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
import { usePosQuote } from "./usePosQuote";
import type { PosLine } from "./shared";
import type { MemberCheckoutPreviewResult, PosQuotePayload } from "@/app/lib/types";
// add-promotions-campaigns PR 2: every POS cart is priced by a promotion-aware quote. The hook owns the
// entered code and returns the quote the cart, the split and the receipt total from.
function line(pPricingId: string, qty: number, unitPrice = 50): PosLine {
return { key: Number(pPricingId), pPricingId, variationId: "V", label: `P${pPricingId}`, unitPrice, qty };
}
function quote(over: Partial<MemberCheckoutPreviewResult> = {}): MemberCheckoutPreviewResult {
return {
orderTotal: 100, acornPaid: 0, productPaid: 0, applePaid: 0, gatewayResidual: 0,
grossTotal: 100, discountTotal: 0, discountLines: [], ...over,
};
}
function deferred<T>() {
let resolve!: (v: T) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
describe("usePosQuote", () => {
it("does not quote an empty cart", () => {
const fetchQuote = vi.fn();
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, []));
expect(fetchQuote).not.toHaveBeenCalled();
expect(result.current.quote).toBeNull();
expect(result.current.loading).toBe(false);
});
it("quotes the cart lines for the member, without a code until one is applied", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote({ orderTotal: 90, discountTotal: 10 }));
const { result } = renderHook(() => usePosQuote(fetchQuote, "MY0001", [line("1", 2)]));
await waitFor(() => expect(result.current.quote?.orderTotal).toBe(90));
expect(fetchQuote).toHaveBeenCalledWith({ memberCode: "MY0001", lines: [{ pPricingId: "1", qty: 2 }] });
expect(result.current.appliedCode).toBeNull();
});
it("quotes a walk-in without a member code", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
await waitFor(() => expect(fetchQuote).toHaveBeenCalledTimes(1));
const payload: PosQuotePayload = fetchQuote.mock.calls[0][0];
expect(payload).not.toHaveProperty("memberCode");
expect(payload).not.toHaveProperty("promoCode");
});
it("an accepted code becomes the applied code, as the server normalised it", async () => {
const fetchQuote = vi.fn()
.mockResolvedValueOnce(quote())
.mockResolvedValueOnce(quote({ orderTotal: 85, discountTotal: 15, promoCode: "RAYA15" }));
const { result } = renderHook(() => usePosQuote(fetchQuote, "MY0001", [line("1", 2)]));
await waitFor(() => expect(result.current.quote).not.toBeNull());
act(() => result.current.applyCode(" raya15 "));
await waitFor(() => expect(result.current.appliedCode).toBe("RAYA15"));
expect(fetchQuote).toHaveBeenLastCalledWith({
memberCode: "MY0001", lines: [{ pPricingId: "1", qty: 2 }], promoCode: "raya15",
});
expect(result.current.code).toBe("raya15");
expect(result.current.quote?.orderTotal).toBe(85);
});
it("a refused code is not applied and its reason is exposed", async () => {
const fetchQuote = vi.fn().mockResolvedValue(
quote({ promoCode: "NOPE", promoRejection: "MIN_SPEND_NOT_MET", promoShortfall: 20 }),
);
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
act(() => result.current.applyCode("nope"));
await waitFor(() => expect(result.current.quote?.promoRejection).toBe("MIN_SPEND_NOT_MET"));
expect(result.current.appliedCode).toBeNull();
});
it("applying the same code again re-checks it (the offer may have been resumed)", async () => {
// e2e 2026-09-26: after a campaign was paused and resumed, re-applying its code did nothing.
const fetchQuote = vi.fn().mockResolvedValueOnce(quote())
.mockResolvedValueOnce(quote({ promoCode: "RAYA15", promoRejection: "NOT_ACTIVE" }))
.mockResolvedValueOnce(quote({ promoCode: "RAYA15" }));
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
act(() => result.current.applyCode("RAYA15"));
await waitFor(() => expect(result.current.quote?.promoRejection).toBe("NOT_ACTIVE"));
act(() => result.current.applyCode("raya15 ".toUpperCase()));
await waitFor(() => expect(result.current.appliedCode).toBe("RAYA15"));
expect(fetchQuote).toHaveBeenCalledTimes(3);
});
it("removing the code re-quotes without it", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote({ promoCode: "RAYA15" }));
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
act(() => result.current.applyCode("RAYA15"));
await waitFor(() => expect(result.current.appliedCode).toBe("RAYA15"));
fetchQuote.mockResolvedValue(quote());
act(() => result.current.removeCode());
await waitFor(() => expect(result.current.appliedCode).toBeNull());
expect(result.current.code).toBe("");
expect(fetchQuote).toHaveBeenLastCalledWith({ lines: [{ pPricingId: "1", qty: 1 }] });
});
it("a cart change re-quotes and a slower earlier answer never overwrites the newer one", async () => {
const first = deferred<MemberCheckoutPreviewResult>();
const second = deferred<MemberCheckoutPreviewResult>();
const fetchQuote = vi.fn().mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
const { result, rerender } = renderHook(({ lines }) => usePosQuote(fetchQuote, undefined, lines), {
initialProps: { lines: [line("1", 1)] },
});
rerender({ lines: [line("1", 2)] });
await waitFor(() => expect(fetchQuote).toHaveBeenCalledTimes(2));
await act(async () => second.resolve(quote({ orderTotal: 100 })));
await act(async () => first.resolve(quote({ orderTotal: 50 })));
expect(result.current.quote?.orderTotal).toBe(100);
expect(result.current.loading).toBe(false);
});
it("the same cart re-rendered with a new array does not re-quote", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
const { rerender } = renderHook(({ lines }) => usePosQuote(fetchQuote, undefined, lines), {
initialProps: { lines: [line("1", 1)] },
});
await waitFor(() => expect(fetchQuote).toHaveBeenCalledTimes(1));
rerender({ lines: [line("1", 1)] });
rerender({ lines: [line("1", 1)] });
expect(fetchQuote).toHaveBeenCalledTimes(1);
});
it("while a new quote loads the old one is withdrawn, so no sale can use a stale total", async () => {
const pending = deferred<MemberCheckoutPreviewResult>();
const fetchQuote = vi.fn().mockResolvedValueOnce(quote({ orderTotal: 50 })).mockReturnValueOnce(pending.promise);
const { result, rerender } = renderHook(({ lines }) => usePosQuote(fetchQuote, undefined, lines), {
initialProps: { lines: [line("1", 1)] },
});
await waitFor(() => expect(result.current.quote?.orderTotal).toBe(50));
rerender({ lines: [line("1", 2)] });
await waitFor(() => expect(result.current.loading).toBe(true));
expect(result.current.quote).toBeNull();
});
it("the applied code stays applied while the same code is re-priced, so order keys stay stable", async () => {
let hold = false;
const fetchQuote = vi.fn((p: PosQuotePayload) =>
hold ? new Promise<MemberCheckoutPreviewResult>(() => {}) : Promise.resolve(quote({ promoCode: p.promoCode ?? null })));
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
act(() => result.current.applyCode("RAYA15"));
await waitFor(() => expect(result.current.appliedCode).toBe("RAYA15"));
hold = true;
act(() => result.current.refresh());
await waitFor(() => expect(result.current.loading).toBe(true));
expect(result.current.quote).toBeNull();
expect(result.current.appliedCode).toBe("RAYA15");
});
it("a different code is not applied until its own quote accepts it", async () => {
const fetchQuote = vi.fn((p: PosQuotePayload) =>
p.promoCode === "OTHER" ? new Promise<MemberCheckoutPreviewResult>(() => {}) : Promise.resolve(quote({ promoCode: p.promoCode ?? null })));
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
act(() => result.current.applyCode("RAYA15"));
await waitFor(() => expect(result.current.appliedCode).toBe("RAYA15"));
act(() => result.current.applyCode("OTHER"));
await waitFor(() => expect(result.current.loading).toBe(true));
expect(result.current.appliedCode).toBeNull();
});
it("a failed quote reports the error and leaves no quote", async () => {
const fetchQuote = vi.fn().mockRejectedValue(new Error("A product line is not available"));
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
await waitFor(() => expect(result.current.error).toBe("A product line is not available"));
expect(result.current.quote).toBeNull();
expect(result.current.loading).toBe(false);
});
it("a failed quote without a message reports a message code, translated where it renders", async () => { // localise-admin-pos-events
const fetchQuote = vi.fn().mockRejectedValue("boom");
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
await waitFor(() => expect(result.current.error).toBe("PosPriceCartFailed"));
});
it("refresh re-quotes the same cart (after the counter refused a changed offer)", async () => {
const fetchQuote = vi.fn().mockResolvedValueOnce(quote({ orderTotal: 90 })).mockResolvedValueOnce(quote({ orderTotal: 100 }));
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 2)]));
await waitFor(() => expect(result.current.quote?.orderTotal).toBe(90));
act(() => result.current.refresh());
await waitFor(() => expect(result.current.quote?.orderTotal).toBe(100));
expect(fetchQuote).toHaveBeenCalledTimes(2);
});
it("emptying the cart clears the quote", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
const { result, rerender } = renderHook(({ lines }) => usePosQuote(fetchQuote, undefined, lines), {
initialProps: { lines: [line("1", 1)] },
});
await waitFor(() => expect(result.current.quote).not.toBeNull());
rerender({ lines: [] });
await waitFor(() => expect(result.current.quote).toBeNull());
});
// add-promotion-reward-lines: special-price gifts the operator accepts are re-quoted and carried to the sale.
it("an accepted gift is re-quoted and exposed for the sale; clearing forgets it", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
const { result } = renderHook(() => usePosQuote(fetchQuote, "MY0001", [line("1", 1)]));
await waitFor(() => expect(result.current.quote).not.toBeNull());
expect(fetchQuote.mock.calls[0][0]).not.toHaveProperty("acceptedRewardCampaignIds");
expect(result.current.acceptedRewardCampaignIds).toEqual([]);
act(() => result.current.acceptReward(11));
await waitFor(() => expect(fetchQuote).toHaveBeenCalledTimes(2));
expect(fetchQuote).toHaveBeenLastCalledWith({
memberCode: "MY0001", lines: [{ pPricingId: "1", qty: 1 }], acceptedRewardCampaignIds: [11],
});
expect(result.current.acceptedRewardCampaignIds).toEqual([11]);
act(() => result.current.acceptReward(11));
expect(result.current.acceptedRewardCampaignIds).toEqual([11]);
act(() => result.current.clearRewards());
expect(result.current.acceptedRewardCampaignIds).toEqual([]);
});
it("removing an accepted gift re-quotes without it", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
const { result } = renderHook(() => usePosQuote(fetchQuote, "MY0001", [line("1", 1)]));
await waitFor(() => expect(result.current.quote).not.toBeNull());
act(() => result.current.acceptReward(11));
await waitFor(() => expect(fetchQuote).toHaveBeenCalledTimes(2));
act(() => result.current.removeReward(11));
expect(result.current.acceptedRewardCampaignIds).toEqual([]);
await waitFor(() => expect(fetchQuote).toHaveBeenCalledTimes(3));
expect(fetchQuote.mock.calls[2][0]).not.toHaveProperty("acceptedRewardCampaignIds");
});
it("removing the code keeps an accepted gift", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
const { result } = renderHook(() => usePosQuote(fetchQuote, undefined, [line("1", 1)]));
await waitFor(() => expect(result.current.quote).not.toBeNull());
act(() => result.current.applyCode("RAYA15"));
act(() => result.current.acceptReward(11));
act(() => result.current.removeCode());
expect(result.current.acceptedRewardCampaignIds).toEqual([11]);
});
it("emptying the cart forgets accepted gifts, so the next customer never inherits one", async () => {
const fetchQuote = vi.fn().mockResolvedValue(quote());
const { result, rerender } = renderHook(({ cart }) => usePosQuote(fetchQuote, undefined, cart), {
initialProps: { cart: [line("1", 1)] },
});
await waitFor(() => expect(result.current.quote).not.toBeNull());
act(() => result.current.acceptReward(11));
expect(result.current.acceptedRewardCampaignIds).toEqual([11]);
rerender({ cart: [] });
expect(result.current.acceptedRewardCampaignIds).toEqual([]);
});
});