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

224 lines
9.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import { PosPromoPanel } from "./PosPromoPanel";
import type { MemberCheckoutPreviewResult } from "@/app/lib/types";
// add-promotions-campaigns PR 2: the operator enters a code for the customer and sees what the cart
// is discounted by. The panel sits inside the POS sale <form>, so it must never submit it.
function quote(over: Partial<MemberCheckoutPreviewResult> = {}): MemberCheckoutPreviewResult {
return {
orderTotal: 100, acornPaid: 0, productPaid: 0, applePaid: 0, gatewayResidual: 0,
grossTotal: 100, discountTotal: 0, discountLines: [], ...over,
};
}
function renderPanel(props: Partial<Parameters<typeof PosPromoPanel>[0]> = {}) {
const onApply = vi.fn();
const onRemove = vi.fn();
const onRetry = vi.fn();
const onSubmit = vi.fn((e: React.FormEvent) => e.preventDefault());
render(
<form onSubmit={onSubmit}>
<PosPromoPanel
quote={quote()}
loading={false}
error={null}
code=""
appliedCode={null}
onApply={onApply}
onRemove={onRemove}
onRetry={onRetry}
{...props}
/>
</form>,
);
return { onApply, onRemove, onRetry, onSubmit };
}
describe("PosPromoPanel", () => {
it("applies the typed code with the button without submitting the sale form", () => {
const { onApply, onSubmit } = renderPanel();
fireEvent.change(screen.getByLabelText("Promo code"), { target: { value: "raya15" } });
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
expect(onApply).toHaveBeenCalledWith("raya15");
expect(onSubmit).not.toHaveBeenCalled();
});
it("Enter in the code field applies the code instead of placing the sale", () => {
const { onApply, onSubmit } = renderPanel();
const input = screen.getByLabelText("Promo code");
fireEvent.change(input, { target: { value: "raya15" } });
fireEvent.keyDown(input, { key: "Enter" });
expect(onApply).toHaveBeenCalledWith("raya15");
expect(onSubmit).not.toHaveBeenCalled();
});
it("has no form of its own, since a nested form inside the sale form is invalid HTML", () => {
renderPanel();
expect(document.querySelectorAll("form")).toHaveLength(1);
});
it("Remove clears the field for the next code", () => {
const { onRemove } = renderPanel({ code: "RAYA15", appliedCode: "RAYA15", quote: quote({ promoCode: "RAYA15" }) });
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
expect(onRemove).toHaveBeenCalled();
});
it("Apply is disabled until something is typed", () => {
renderPanel();
expect(screen.getByRole("button", { name: "Apply" }).hasAttribute("disabled")).toBe(true);
});
it("an applied code is shown with Remove", () => {
const { onRemove } = renderPanel({ code: "RAYA15", appliedCode: "RAYA15", quote: quote({ promoCode: "RAYA15" }) });
expect(screen.getByText("RAYA15 applied")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
expect(onRemove).toHaveBeenCalled();
});
it("a refused code shows why, in operator words", () => {
renderPanel({
code: "RAYA15",
quote: quote({ promoCode: "RAYA15", promoRejection: "MIN_SPEND_NOT_MET", promoShortfall: 20 }),
});
expect(screen.getByRole("status").textContent).toBe("Spend RM 20.00 more to use this code");
});
it("a refused code states the missing item count", () => {
renderPanel({
code: "RAYA15",
quote: quote({ promoCode: "RAYA15", promoRejection: "MIN_QUANTITY_NOT_MET", promoShortfall: 2 }),
});
expect(screen.getByRole("status").textContent).toBe("Add 2 more items to use this code");
});
it("a one-item shortfall is singular", () => {
renderPanel({
code: "RAYA15",
quote: quote({ promoCode: "RAYA15", promoRejection: "MIN_QUANTITY_NOT_MET", promoShortfall: 1 }),
});
expect(screen.getByRole("status").textContent).toBe("Add 1 more item to use this code");
});
it.each([
["NOT_FOUND", "Code not recognised"],
["EXPIRED", "This offer has expired"],
["NOT_VALID_FOR_CHANNEL", "This code cannot be used at this counter"],
["LOGIN_REQUIRED", "This offer is for members. Select the member first"],
["NOT_FOR_YOUR_RANK", "This offer is not available for this member's rank"],
["NOT_VALID_FOR_ACCOUNT", "This code belongs to another member"],
["USAGE_LIMIT_REACHED", "This offer is fully redeemed"],
["NOT_VALID_FOR_ITEMS", "This code is not valid for the items in the cart"],
["CODE_USED", "This code has already been used"],
["NOT_ACTIVE", "This offer is not available right now"],
])("rejection %s reads %s", (rejection, text) => {
renderPanel({ code: "X", quote: quote({ promoCode: "X", promoRejection: rejection }) });
expect(screen.getByRole("status").textContent).toBe(text);
});
it("a better automatic offer is explained", () => {
renderPanel({ code: "RAYA15", quote: quote({ promoCode: "RAYA15", promoNotice: "BETTER_OFFER_APPLIED" }) });
expect(screen.getByRole("status").textContent).toBe("A better offer is already on these items");
});
it("shows the subtotal and one discount row per campaign when the cart is discounted", () => {
renderPanel({
quote: quote({
grossTotal: 150,
discountTotal: 25,
orderTotal: 125,
discountLines: [
{ lineIndex: 0, productCode: "A", campaignLabel: "RAYA 20%", amount: 10 },
{ lineIndex: 1, productCode: "B", campaignLabel: "RAYA 20%", amount: 5 },
{ lineIndex: 2, productCode: "C", campaignLabel: "Member RM10", amount: 10 },
],
}),
});
expect(screen.getByText("Subtotal")).toBeTruthy();
expect(screen.getByText("RM 150.00")).toBeTruthy();
expect(screen.getByText("Discount (RAYA 20%)")).toBeTruthy();
expect(screen.getByText("-RM 15.00")).toBeTruthy();
expect(screen.getByText("Discount (Member RM10)")).toBeTruthy();
expect(screen.getByText("-RM 10.00")).toBeTruthy();
});
it("shows no summary rows when nothing is discounted", () => {
renderPanel();
expect(screen.queryByText("Subtotal")).toBeNull();
});
it("says it is pricing while the quote loads", () => {
renderPanel({ quote: null, loading: true });
expect(screen.getByText("Pricing…")).toBeTruthy();
});
it("shows a quote failure so the operator knows the total is unavailable", () => {
renderPanel({ quote: null, error: "A product line is not available" });
expect(screen.getByRole("alert").textContent).toBe(
"Could not price the cart: A product line is not available",
);
});
it("a failed quote can be retried without editing the cart", () => {
const { onRetry, onSubmit } = renderPanel({ quote: null, error: "Service unavailable" });
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(onRetry).toHaveBeenCalled();
expect(onSubmit).not.toHaveBeenCalled();
});
// add-promotion-reward-lines: the engine's reward lines, and the gifts that need the operator's OK.
const freeDiaper = {
lineIndex: 1, campaignId: 9, campaignLabel: "B2G1", productCode: "DIAPER", variationId: "V-D",
productName: null, qty: 1, unitPrice: 60, netUnitPrice: 0, status: "APPLIED" as const,
};
const bottleOffer = {
lineIndex: null, campaignId: 11, campaignLabel: "BOTTLE DEAL", productCode: "BOTTLE", variationId: "V-B",
productName: "Baby Bottle 250ml", qty: 1, unitPrice: 12, netUnitPrice: 10, status: "NEEDS_ACCEPTANCE" as const,
};
it("lists applied rewards as free lines, named from the catalogue when the server has no name", () => {
renderPanel({ quote: quote({ rewardLines: [freeDiaper] }), nameFor: (code: string) => (code === "DIAPER" ? "Diaper L" : undefined) });
const row = screen.getByTestId("reward-line-9-DIAPER-V-D");
expect(row.textContent).toContain("Diaper L × 1");
expect(row.textContent).toContain("Free");
expect(row.textContent).toContain("B2G1");
});
it("offers a special-price gift, and Add accepts it without submitting the sale", () => {
const onAcceptReward = vi.fn();
const { onSubmit } = renderPanel({ quote: quote({ rewardLines: [bottleOffer] }), onAcceptReward });
fireEvent.click(screen.getByRole("button", { name: "Add Baby Bottle 250ml for RM 10.00" }));
expect(onAcceptReward).toHaveBeenCalledWith(11);
expect(onSubmit).not.toHaveBeenCalled();
});
it("an accepted special-price gift can be removed; a free reward cannot", () => {
const onRemoveReward = vi.fn();
const { onSubmit } = renderPanel({
quote: quote({ rewardLines: [{ ...bottleOffer, lineIndex: 1, status: "APPLIED" }, freeDiaper] }),
acceptedRewardCampaignIds: [11], onRemoveReward,
});
fireEvent.click(screen.getByRole("button", { name: "Remove Baby Bottle 250ml" }));
expect(onRemoveReward).toHaveBeenCalledWith(11);
expect(onSubmit).not.toHaveBeenCalled();
expect(screen.getAllByRole("button", { name: /^Remove / })).toHaveLength(1);
});
it("an accepted special-price gift shows its price, not Free", () => {
renderPanel({ quote: quote({ rewardLines: [{ ...bottleOffer, lineIndex: 1, status: "APPLIED" }] }) });
expect(screen.getByTestId("reward-line-11-BOTTLE-V-B").textContent).toContain("RM 10.00");
});
it("announces a reward dropped for stock, falling back to the product code", () => {
renderPanel({ quote: quote({ rewardOutOfStock: ["TEETHER"] }) });
expect(screen.getByText("Free TEETHER is out of stock and was not added")).toBeTruthy();
});
it("shows no reward block when there are no rewards", () => {
renderPanel();
expect(screen.queryByTestId(/^reward-line-/)).toBeNull();
});
});