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

1212 lines
61 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 { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { pickDate } from "@/test/pickDate";
import { pickTime } from "@/test/pickTime";
import type { CampaignView } from "@/app/lib/types";
// add-promotions-campaigns plan Task 9b: one sectioned form for every phase-1 campaign, with a live
// summary, fields that appear only when they apply, and frozen rules once a campaign is redeemed.
const svc = vi.hoisted(() => ({
createCampaign: vi.fn(),
updateCampaign: vi.fn(),
setCampaignStatus: vi.fn(),
duplicateCampaign: vi.fn(),
}));
vi.mock("@/app/lib/services/adminPromotions", () => ({
createCampaign: (i: unknown) => svc.createCampaign(i),
updateCampaign: (u: string, i: unknown) => svc.updateCampaign(u, i),
setCampaignStatus: (u: string, s: string) => svc.setCampaignStatus(u, s),
duplicateCampaign: (u: string) => svc.duplicateCampaign(u),
}));
const catalogue = vi.hoisted(() => ({ listProducts: vi.fn(), getProductVariations: vi.fn() }));
vi.mock("@/app/lib/services/adminProduct", () => ({ listProducts: (q: unknown) => catalogue.listProducts(q) }));
vi.mock("@/app/lib/services/adminStock", () => ({ getProductVariations: (id: string) => catalogue.getProductVariations(id) }));
const BRA = { id: "19", productCode: "BA-002", productName: "Isa Uchi Seamless 2 In 1 Maternity & Nursing Bra", productStatus: "Y" };
const E2E = { id: "24", productCode: "E2E0928P1", productName: "E2E0928 Test Product", productStatus: "Y" };
const OLD = { id: "30", productCode: "OLD-1", productName: "Retired Thing", productStatus: "N" };
const VARIATIONS: Record<string, { skuVariationId: string; variationId: string; label: string }[]> = {
"19": [
{ skuVariationId: "a", variationId: "20", label: "Colour: Black" },
{ skuVariationId: "b", variationId: "21", label: "Colour: Blue" },
{ skuVariationId: "c", variationId: "22", label: "Size: S" },
{ skuVariationId: "d", variationId: "22", label: "Size: S (dup)" },
{ skuVariationId: "e", variationId: "23", label: "Size: M" },
{ skuVariationId: "f", variationId: "24", label: "Size: L" },
],
"24": [{ skuVariationId: "g", variationId: "29", label: "Size: Standard" }],
"30": [{ skuVariationId: "h", variationId: "40", label: "Size: One" }],
};
import { CampaignForm } from "./CampaignForm";
import { ApiError } from "@/app/lib/clientApi";
const stored: CampaignView = {
uuid: "C-7",
name: "Raya sale",
customerLabel: "RAYA 20%",
benefitType: "PERCENT_OFF",
benefitValue: 20,
maxDiscountCap: 30,
claimType: "SHARED_CODE",
sharedCode: "RAYA15",
channelOnline: true,
channelOutlet: false,
channelEvent: false,
allProducts: true,
products: [],
ranks: ["GIRAFFE"],
minSpend: 100,
maxUsesTotal: 500,
maxUsesPerMember: null,
budgetAmount: null,
effectiveFrom: "2026-10-01T00:00",
effectiveTo: "2026-10-15T23:59",
status: "ACTIVE",
usedCount: 3,
usedAmount: 45,
locked: false,
};
function renderForm(initial: CampaignView | null = null) {
const onSaved = vi.fn();
const onCancel = vi.fn();
render(<CampaignForm initial={initial} onSaved={onSaved} onCancel={onCancel} />);
return { onSaved, onCancel };
}
// Fixture data, not a typing test: one change event per field, because each keystroke re-renders the
// whole form (60-80 ms in jsdom) and these keystrokes pushed form tests toward the 20 s test timeout.
async function fillMinimalNewCampaign() {
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Raya sale" } });
fireEvent.change(screen.getByLabelText("Customer label"), { target: { value: "RAYA 20%" } });
fireEvent.change(screen.getByLabelText("Value"), { target: { value: "20" } });
// DateTimePicker: date picked from the calendar, time from the dropdown
pickDate("Starts", "2026-10-01");
await pickTime("Starts time", "00:00");
pickDate("Ends", "2026-10-15");
await pickTime("Ends time", "23:59");
}
beforeEach(() => {
Object.values(svc).forEach((f) => f.mockReset());
catalogue.listProducts.mockReset();
catalogue.listProducts.mockResolvedValue({ items: [BRA, E2E, OLD], total: 3 });
catalogue.getProductVariations.mockReset();
catalogue.getProductVariations.mockImplementation((id: string) => Promise.resolve(VARIATIONS[id] ?? []));
});
async function pickProduct(user: ReturnType<typeof userEvent.setup>, label: string, query: string, name: RegExp) {
await user.type(screen.getByRole("combobox", { name: label }), query);
await user.click(await screen.findByText(name));
}
async function chooseProducts(user: ReturnType<typeof userEvent.setup>, names: string[], query?: string) {
await user.click(screen.getByRole("button", { name: "Choose products" }));
const dialog = await screen.findByRole("dialog", { name: "Select eligible products" });
if (query) await user.type(within(dialog).getByPlaceholderText("Search name or code"), query);
for (const name of names) await user.click(within(dialog).getByRole("checkbox", { name }));
await user.click(within(dialog).getByRole("button", { name: "Done" }));
}
const STEPS = ["What's the offer?", "Who gets it?", "How long, and how much can it cost?"];
describe("CampaignForm sections", () => {
it("spaces each label from its control", () => {
renderForm();
for (const name of ["Name", "Minimum spend (RM)", "Budget (RM)"]) {
expect(screen.getByText(name, { selector: "label" }).parentElement).toHaveClass("space-y-1.5");
}
});
it("names the missing time on Starts and Ends when only dates are entered", () => {
renderForm();
pickDate("Starts", "2026-10-01");
pickDate("Ends", "2026-10-15");
expect(screen.getAllByText("Enter a time")).toHaveLength(2);
});
it("opens the Starts calendar on the current month when empty", () => {
renderForm();
fireEvent.click(screen.getByLabelText("Starts"));
const dialogs = screen.getAllByRole("dialog");
const [month, year] = Array.from(dialogs[dialogs.length - 1].querySelectorAll("select"));
const now = new Date();
expect([month.value, year.value]).toEqual([String(now.getMonth()), String(now.getFullYear())]);
});
it("does not publish while a date has no time, and names the missing time", async () => {
const user = userEvent.setup();
renderForm();
await user.type(screen.getByLabelText("Name"), "Raya sale");
pickDate("Starts", "2026-10-01");
await user.click(screen.getByRole("button", { name: "Publish" }));
expect(svc.createCampaign).not.toHaveBeenCalled();
expect(screen.getAllByText("Enter a time").length).toBeGreaterThan(0);
});
it("groups the fields into the three numbered steps, mechanics first", () => {
renderForm();
expect(document.querySelectorAll("fieldset")).toHaveLength(3);
const [offer, who, limits] = STEPS.map((name) => screen.getByRole("group", { name }));
expect(offer.compareDocumentPosition(who) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(who.compareDocumentPosition(limits) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
const mechanics = within(offer).getByRole("radiogroup", { name: "Benefit type" });
expect(within(mechanics).getAllByRole("radio").map((r) => r.getAttribute("value"))).toEqual(
["PERCENT_OFF", "AMOUNT_OFF", "BUY_X_GET_Y", "GIFT", "FIXED_PRICE"],
);
for (const name of ["Percentage off", "Amount off", "Buy X get Y", "Gift", "Fixed price"]) {
expect(within(offer).getByRole("radio", { name })).toBeInTheDocument();
}
});
it("puts each section in a card and keeps Save and Cancel in a sticky bar", () => {
renderForm();
for (const legend of STEPS) {
expect(screen.getByRole("group", { name: legend }).closest("[data-slot='card']")).not.toBeNull();
}
const bar = screen.getByRole("button", { name: "Save draft" }).closest(".sticky") as HTMLElement;
expect(bar).not.toBeNull();
expect(within(bar).getByRole("button", { name: "Cancel" })).toBeInTheDocument();
});
it("heads a new campaign, with a way back to the list", async () => {
const user = userEvent.setup();
const { onCancel } = renderForm();
expect(screen.getByRole("heading", { name: "New campaign" })).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Back to campaigns" }));
expect(onCancel).toHaveBeenCalled();
});
it("heads an existing campaign with its name and status", () => {
renderForm(stored);
expect(screen.getByRole("heading", { name: "Edit campaign" })).toBeInTheDocument();
expect(screen.getByText("Active")).toHaveAttribute("data-variant", "positive");
});
it("puts the live summary in the sticky footer beside exactly one primary button", () => {
renderForm();
const bar = screen.getByRole("button", { name: "Save draft" }).closest(".sticky") as HTMLElement;
expect(within(bar).getByTestId("campaign-summary")).toBeInTheDocument();
expect(bar.querySelectorAll("button[data-variant='default']")).toHaveLength(1);
expect(within(bar).getByRole("button", { name: "Publish" })).toHaveAttribute("data-variant", "default");
});
it("makes Publish the only primary button when editing a draft", () => {
renderForm({ ...stored, status: "DRAFT" });
const bar = screen.getByRole("button", { name: "Save" }).closest(".sticky") as HTMLElement;
expect(bar.querySelectorAll("button[data-variant='default']")).toHaveLength(1);
expect(within(bar).getByRole("button", { name: "Save" })).toHaveAttribute("data-variant", "outline");
expect(within(bar).getByRole("button", { name: "Publish" })).toHaveAttribute("data-variant", "default");
});
it("has one primary button for an existing non-draft and a locked campaign", () => {
const { unmount } = render(<CampaignForm initial={stored} onSaved={vi.fn()} onCancel={vi.fn()} />);
const bar = screen.getByRole("button", { name: "Save" }).closest(".sticky") as HTMLElement;
expect(bar.querySelectorAll("button[data-variant='default']")).toHaveLength(1);
expect(screen.getByRole("button", { name: "Save" })).toHaveAttribute("data-variant", "default");
unmount();
renderForm({ ...stored, locked: true });
expect(screen.getByRole("button", { name: "Duplicate" })).toHaveAttribute("data-variant", "outline");
expect(screen.getByRole("button", { name: "Save" })).toHaveAttribute("data-variant", "default");
});
it("shows the maximum cap only for a percentage benefit", async () => {
const user = userEvent.setup();
renderForm();
expect(screen.getByLabelText("Maximum cap (RM)")).toBeInTheDocument();
await user.click(screen.getByRole("radio", { name: "Amount off" }));
expect(screen.queryByLabelText("Maximum cap (RM)")).not.toBeInTheDocument();
});
it("shows the code field only for a shared code, and upper-cases it as typed", async () => {
const user = userEvent.setup();
renderForm();
expect(screen.queryByLabelText("Code")).not.toBeInTheDocument();
await user.click(screen.getByRole("radio", { name: "Shared code" }));
await user.type(screen.getByLabelText("Code"), "raya15");
expect(screen.getByLabelText("Code")).toHaveValue("RAYA15");
});
it("offers benefit and claim type as radio groups", async () => {
renderForm();
const benefit = screen.getByRole("radiogroup", { name: "Benefit type" });
expect(within(benefit).getAllByRole("radio").map((r) => r.getAttribute("value"))).toEqual(
["PERCENT_OFF", "AMOUNT_OFF", "BUY_X_GET_Y", "GIFT", "FIXED_PRICE"],
);
const claim = screen.getByRole("radiogroup", { name: "Claim type" });
expect(within(claim).getAllByRole("radio").map((r) => r.getAttribute("value"))).toEqual(["AUTO", "SHARED_CODE", "UNIQUE_CODE"]);
expect(screen.getByRole("radio", { name: "Percentage off" })).toBeChecked();
await userEvent.click(screen.getByRole("radio", { name: "Amount off" }));
expect(screen.getByRole("radio", { name: "Amount off" })).toBeChecked();
expect(screen.getByRole("radio", { name: "Automatic" })).toBeInTheDocument();
});
it("offers the three member ranks and the three channels", () => {
renderForm();
for (const name of ["Otter", "Squirrel", "Giraffe", "Online", "Branch counter", "Event POS"]) {
expect(screen.getByRole("button", { name })).toHaveAttribute("aria-pressed");
}
expect(screen.getByRole("radio", { name: "All products" })).toBeInTheDocument();
});
it("offers no include/exclude, variant or add-rule control for selected products", async () => {
// Spec "No rule controls" (promo-product-picker-and-hints).
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
expect(screen.getByText("Nothing chosen yet")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Choose products" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Add product rule" })).not.toBeInTheDocument();
expect(screen.queryByLabelText("Rule 1")).not.toBeInTheDocument();
expect(screen.queryByRole("combobox", { name: "Variant 1" })).not.toBeInTheDocument();
});
it("clears the cap and the code when their benefit or claim no longer applies", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.type(screen.getByLabelText("Maximum cap (RM)"), "30");
await user.click(screen.getByRole("radio", { name: "Shared code" }));
await user.type(screen.getByLabelText("Code"), "RAYA15");
await user.click(screen.getByRole("radio", { name: "Amount off" }));
await user.click(screen.getByRole("radio", { name: "Automatic" }));
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0].maxDiscountCap).toBeNull();
expect(svc.createCampaign.mock.calls[0][0].sharedCode).toBeNull();
});
it("lets the admin pick products when not all products apply", async () => {
const user = userEvent.setup();
renderForm();
await user.type(screen.getByLabelText("Value"), "10"); // the summary names products only once a benefit is set
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await chooseProducts(user, [BRA.productName]);
expect(screen.getByTestId("campaign-summary")).toHaveTextContent("BA-002");
});
});
describe("CampaignForm limit field hints", () => {
it("names each limit's blank meaning and explains it under the field", () => {
// Spec "Campaign Limit Fields Explain Themselves" (promo-product-picker-and-hints).
renderForm();
const fields: [string, string, string][] = [
["Budget (RM)", "No limit", "Total discount value the campaign may award before it closes. Leave blank for no limit."],
["Total uses", "No limit", "Maximum redemptions across all members. Leave blank for unlimited."],
["Uses per member", "No limit", "Maximum redemptions by any single member."],
["Minimum spend (RM)", "Any amount", "Minimum order subtotal required for the campaign to apply."],
["Minimum quantity (items)", "Any quantity", "Minimum number of items required in the order."],
];
for (const [label, placeholder, hint] of fields) {
const input = screen.getByLabelText(label);
expect(input).toHaveAttribute("placeholder", placeholder);
expect(input).toHaveAccessibleDescription(hint);
}
});
});
describe("CampaignForm summary", () => {
it("updates the plain-language summary as fields change", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Giraffe" }));
expect(screen.getByTestId("campaign-summary")).toHaveTextContent(
"20% off all products, Giraffe, Online, 1 Oct 2026 – 15 Oct 2026, automatic",
);
});
});
describe("CampaignForm saving", () => {
it("opens a new form with no warning", () => {
renderForm();
expect(screen.queryByRole("status")).toBeNull();
});
it("lets budget, minimum spend and maximum cap take cents", () => {
renderForm();
for (const label of ["Budget (RM)", "Minimum spend (RM)", "Maximum cap (RM)"]) {
expect(screen.getByLabelText(label)).toHaveAttribute("step", "0.01");
}
});
it("saves a budget with cents as a number", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
fireEvent.change(screen.getByLabelText("Budget (RM)"), { target: { value: "49.90" } });
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0].budgetAmount).toBe(49.9);
});
it("saves a new campaign as a draft with numbers, not strings", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
const input = svc.createCampaign.mock.calls[0][0];
expect(input).toMatchObject({
name: "Raya sale",
customerLabel: "RAYA 20%",
benefitType: "PERCENT_OFF",
benefitValue: 20,
claimType: "AUTO",
channelOnline: true,
allProducts: true,
effectiveFrom: "2026-10-01T00:00",
effectiveTo: "2026-10-15T23:59",
});
expect(input.maxUsesTotal).toBeNull();
expect(svc.setCampaignStatus).not.toHaveBeenCalled();
});
it("saves the minimum quantity as a number", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.type(screen.getByLabelText("Minimum quantity (items)"), "3");
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0].minQuantity).toBe(3);
});
it("does not save a fractional minimum quantity", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.type(screen.getByLabelText("Minimum quantity (items)"), "2.5");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(svc.createCampaign).not.toHaveBeenCalled();
expect((screen.getByLabelText("Minimum quantity (items)") as HTMLInputElement).validity.valid).toBe(false);
});
it("a buy X get Y campaign asks for its quantities and saves them", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Buy X get Y" }));
expect(screen.queryByLabelText("Maximum cap (RM)")).not.toBeInTheDocument();
expect(screen.getByLabelText("Percent off the free units (%)")).toHaveValue(100);
await user.type(screen.getByLabelText("Buy quantity"), "2");
await user.type(screen.getByLabelText("Get quantity"), "1");
await user.type(screen.getByLabelText("Maximum sets per order"), "3");
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({
benefitType: "BUY_X_GET_Y", benefitValue: 100, buyQty: 2, getQty: 1, maxRewardSets: 3,
maxDiscountCap: null, giftProductCode: null, giftQty: null,
});
});
it("a gift campaign asks for the product, quantity and price, and may be free", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Gift" }));
expect(screen.getByLabelText("Gift price (RM, 0 = free)")).toHaveValue(0);
await pickProduct(user, "Gift product", "E2E0928", /E2E0928 Test Product/);
await user.click(screen.getByRole("combobox", { name: "Gift variant" }));
await user.click(await screen.findByRole("option", { name: "Size: Standard" }));
await user.type(screen.getByLabelText("Gift quantity"), "1");
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({
benefitType: "GIFT", benefitValue: 0, giftProductCode: "E2E0928P1", giftVariationId: "29", giftQty: 1,
buyQty: null, getQty: null, maxRewardSets: null,
});
});
it("switching back to a discount clears the reward fields", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Buy X get Y" }));
await user.type(screen.getByLabelText("Buy quantity"), "2");
await user.click(screen.getByRole("radio", { name: "Percentage off" }));
await user.clear(screen.getByLabelText("Value"));
await user.type(screen.getByLabelText("Value"), "20");
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({ benefitType: "PERCENT_OFF", benefitValue: 20, buyQty: null, getQty: null });
});
it("publishes by saving then activating", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, uuid: "C-9", status: "DRAFT" });
svc.setCampaignStatus.mockResolvedValue({ ...stored, uuid: "C-9", status: "ACTIVE" });
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Publish" }));
await waitFor(() => expect(svc.setCampaignStatus).toHaveBeenCalledWith("C-9", "ACTIVE"));
expect(onSaved).toHaveBeenCalledWith(expect.objectContaining({ status: "ACTIVE" }));
});
it("updates an existing campaign by its uuid", async () => {
const user = userEvent.setup();
svc.updateCampaign.mockResolvedValue(stored);
renderForm(stored);
await user.clear(screen.getByLabelText("Name"));
await user.type(screen.getByLabelText("Name"), "Raya sale 2");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(svc.updateCampaign).toHaveBeenCalled());
expect(svc.updateCampaign.mock.calls[0][0]).toBe("C-7");
expect(svc.updateCampaign.mock.calls[0][1].name).toBe("Raya sale 2");
});
it("shows a server rejection inline and does not report success", async () => {
const user = userEvent.setup();
svc.createCampaign.mockRejectedValue(new ApiError("Code RAYA15 is already used by campaign Old Raya", 409));
const { onSaved } = renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Code RAYA15 is already used by campaign Old Raya");
expect(onSaved).not.toHaveBeenCalled();
});
});
describe("CampaignForm when the campaign has redemptions", () => {
const locked: CampaignView = { ...stored, locked: true };
it("freezes every rule except the end date, caps and budget", () => {
renderForm(locked);
expect(screen.getByText(
"This campaign has redemptions. Only the end date, caps and budget can change.",
)).toBeInTheDocument();
expect(screen.getByRole("status")).toHaveTextContent("This campaign has redemptions.");
for (const label of ["Name", "Customer label", "Value", "Maximum cap (RM)", "Starts", "Minimum spend (RM)", "Minimum quantity (items)", "Code"]) {
expect(screen.getByLabelText(label)).toBeDisabled();
}
expect(screen.getByRole("button", { name: "Giraffe" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Online" })).toBeDisabled();
for (const label of ["Ends", "Total uses", "Uses per member", "Budget (RM)"]) {
expect(screen.getByLabelText(label)).toBeEnabled();
}
});
it("offers Duplicate, which reports the new draft", async () => {
const user = userEvent.setup();
svc.duplicateCampaign.mockResolvedValue({ ...stored, uuid: "C-10", status: "DRAFT", locked: false });
const { onSaved } = renderForm(locked);
await user.click(screen.getByRole("button", { name: "Duplicate" }));
await waitFor(() => expect(svc.duplicateCampaign).toHaveBeenCalledWith("C-7"));
expect(onSaved).toHaveBeenCalledWith(expect.objectContaining({ uuid: "C-10" }));
});
it("still saves the end date and limits of a locked campaign", async () => {
const user = userEvent.setup();
svc.updateCampaign.mockResolvedValue(locked);
const { onSaved } = renderForm(locked);
await user.clear(screen.getByLabelText("Total uses"));
await user.type(screen.getByLabelText("Total uses"), "800");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(svc.updateCampaign).toHaveBeenCalled());
expect(svc.updateCampaign.mock.calls[0][1].maxUsesTotal).toBe(800);
expect(onSaved).toHaveBeenCalled();
});
it("disables the benefit and claim choices and the product rules", () => {
renderForm({ ...locked, allProducts: false, products: [{ productCode: "DIAPER", variationId: null, mode: "INCLUDE" }] });
for (const name of ["Percentage off", "Amount off", "Automatic", "Shared code", "Unique code per member"]) {
expect(screen.getByRole("radio", { name })).toBeDisabled();
}
expect(screen.getByText("DIAPER")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Choose products" })).toBeDisabled();
});
it("shows a Duplicate failure inline", async () => {
const user = userEvent.setup();
svc.duplicateCampaign.mockRejectedValue(new Error("Campaign not found"));
const { onSaved } = renderForm(locked);
await user.click(screen.getByRole("button", { name: "Duplicate" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Campaign not found");
expect(onSaved).not.toHaveBeenCalled();
});
it("does not offer Publish for an already active campaign", () => {
renderForm(locked);
expect(screen.queryByRole("button", { name: "Publish" })).not.toBeInTheDocument();
});
});
describe("CampaignForm POS channels (add-promotions-campaigns PR 2)", () => {
it("Branch counter and Event POS can be chosen and are saved", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Branch counter" }));
await user.click(screen.getByRole("button", { name: "Event POS" }));
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({ channelOutlet: true, channelEvent: true });
expect(screen.queryByText(/arrive with the POS update/)).not.toBeInTheDocument();
});
});
describe("CampaignForm product and variant pickers", () => {
it("picks a product by name in the dialog and saves it as a whole-product include", async () => {
// Spec "Pick a product rule by name".
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await chooseProducts(user, [BRA.productName], "nursing");
const box = screen.getByRole("group", { name: "Products" });
expect(within(box).getByText(/Isa Uchi Seamless/)).toBeInTheDocument();
expect(within(box).getByText(/BA-002/)).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0].products).toEqual([
{ productCode: "BA-002", variationId: null, mode: "INCLUDE" },
]);
});
it("saves several products ticked at once", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await chooseProducts(user, [E2E.productName, BRA.productName]);
expect(screen.getByText("2 products chosen")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0].products).toEqual([
{ productCode: "BA-002", variationId: null, mode: "INCLUDE" },
{ productCode: "E2E0928P1", variationId: null, mode: "INCLUDE" },
]);
});
it("keeps the chosen products when the dialog is cancelled", async () => {
const user = userEvent.setup();
renderForm({ ...stored, allProducts: false, products: [{ productCode: "BA-002", variationId: null, mode: "INCLUDE" }] });
await screen.findByText(/Isa Uchi Seamless/);
await user.click(screen.getByRole("button", { name: "Choose products" }));
const dialog = await screen.findByRole("dialog", { name: "Select eligible products" });
await user.click(within(dialog).getByRole("checkbox", { name: BRA.productName }));
await user.click(within(dialog).getByRole("button", { name: "Cancel" }));
expect(screen.queryByRole("dialog", { name: "Select eligible products" })).not.toBeInTheDocument();
expect(screen.getByText(/Isa Uchi Seamless/)).toBeInTheDocument();
});
it("tags an inactive product in the dialog", async () => {
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await user.click(screen.getByRole("button", { name: "Choose products" }));
const dialog = await screen.findByRole("dialog", { name: "Select eligible products" });
await user.type(within(dialog).getByPlaceholderText("Search name or code"), "retired");
expect(within(dialog).getByText("Inactive")).toBeInTheDocument();
});
it("keeps the catalogue pages that loaded when a later page fails", async () => {
const user = userEvent.setup();
const page0 = Array.from({ length: 100 }, (_, i) => ({ id: `p${i}`, productCode: `P-${i}`, productName: `Product ${i}`, productStatus: "Y" }));
catalogue.listProducts.mockImplementation((q: { page?: number }) =>
q.page ? Promise.reject(new Error("boom")) : Promise.resolve({ items: page0, total: 101 }));
renderForm();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await waitFor(() => expect(catalogue.listProducts).toHaveBeenCalledTimes(2));
await user.click(screen.getByRole("button", { name: "Choose products" }));
const dialog = await screen.findByRole("dialog", { name: "Select eligible products" });
expect(within(dialog).getByRole("checkbox", { name: "Product 0" })).toBeInTheDocument();
});
it("sends no product rows when All products is chosen after picking some", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await chooseProducts(user, [BRA.productName]);
await user.click(screen.getByRole("radio", { name: "All products" }));
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({ allProducts: true, products: [] });
});
it("lists the whole catalogue, not only its first page", async () => {
// Spec "Whole catalogue": the form used to load only the first 100 products.
const user = userEvent.setup();
const page0 = Array.from({ length: 100 }, (_, i) => ({ id: `p${i}`, productCode: `P-${i}`, productName: `Product ${i}`, productStatus: "Y" }));
catalogue.listProducts.mockImplementation((q: { page?: number }) =>
Promise.resolve(q.page ? { items: [E2E], total: 101 } : { items: page0, total: 101 }));
renderForm();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await waitFor(() => expect(catalogue.listProducts).toHaveBeenCalledWith(expect.objectContaining({ page: 1, pageSize: 100 })));
await user.click(screen.getByRole("button", { name: "Choose products" }));
const dialog = await screen.findByRole("dialog", { name: "Select eligible products" });
expect(within(dialog).getByRole("checkbox", { name: E2E.productName })).toBeInTheDocument();
expect(within(dialog).getByRole("checkbox", { name: "Product 0" })).toBeInTheDocument();
});
it("blocks saving a gift on a multi-variant product until a variant is chosen", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Gift" }));
await pickProduct(user, "Gift product", "BA-002", /Nursing Bra/);
// The server also rejects a gift with no quantity (PromotionAdminService.validate).
fireEvent.change(screen.getByLabelText("Gift quantity"), { target: { value: "1" } });
await waitFor(() => expect(screen.getByRole("combobox", { name: "Gift variant" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(await screen.findByRole("region", { name: "Fix these before saving" })).toHaveTextContent("Choose a gift variant — this product has several.");
expect(svc.createCampaign).not.toHaveBeenCalled();
await user.click(screen.getByRole("combobox", { name: "Gift variant" }));
await user.click(await screen.findByRole("option", { name: "Colour: Blue" }));
expect(screen.queryByText(/Choose a gift variant/)).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({ giftProductCode: "BA-002", giftVariationId: "21" });
});
it("also blocks Publish for that gift", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Gift" }));
await pickProduct(user, "Gift product", "BA-002", /Nursing Bra/);
await waitFor(() => expect(screen.getByRole("combobox", { name: "Gift variant" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Publish" }));
expect(await screen.findByRole("region", { name: "Fix these before saving" })).toBeInTheDocument();
expect(svc.createCampaign).not.toHaveBeenCalled();
});
it("shows an existing gift product by name and code", async () => {
renderForm({ ...stored, benefitType: "GIFT", benefitValue: 0, giftProductCode: "E2E0928P1", giftVariationId: "29", giftQty: 1 });
expect(await screen.findByText("E2E0928 Test Product")).toBeInTheDocument();
expect(screen.getByText(/· E2E0928P1/)).toBeInTheDocument();
// The picker shows "Variant 29" until the product's variants load; wait for the resolved label.
const variant = await screen.findByRole("combobox", { name: "Gift variant" });
await waitFor(() => expect(variant).toHaveTextContent("Size: Standard"));
});
it("shows the bare code of a chosen product that is not in the catalogue, and keeps it on save", async () => {
const user = userEvent.setup();
svc.updateCampaign.mockResolvedValue(stored);
renderForm({ ...stored, allProducts: false, products: [{ productCode: "GONE-9", variationId: null, mode: "INCLUDE" }] });
await waitFor(() => expect(catalogue.listProducts).toHaveBeenCalled());
await act(async () => { await new Promise((r) => setTimeout(r, 0)); });
expect(within(screen.getByRole("group", { name: "Products" })).getByText("GONE-9")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(svc.updateCampaign).toHaveBeenCalled());
expect(svc.updateCampaign.mock.calls[0][1].products).toEqual([{ productCode: "GONE-9", variationId: null, mode: "INCLUDE" }]);
});
it("disables the pickers of a locked campaign", async () => {
renderForm({ ...stored, locked: true, benefitType: "GIFT", benefitValue: 0, giftProductCode: "E2E0928P1", giftVariationId: "29" });
expect(await screen.findByText("E2E0928 Test Product")).toBeInTheDocument();
expect(screen.getByRole("combobox", { name: "Gift variant" })).toBeDisabled();
expect(screen.queryByRole("button", { name: "Change Gift product" })).not.toBeInTheDocument();
});
describe("gift variant guard", () => {
const BLOCKED_UNKNOWN = "Couldn't load this product's variants — reload the page to try again.";
async function startGift(user: ReturnType<typeof userEvent.setup>, query: string, name: RegExp) {
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Gift" }));
await pickProduct(user, "Gift product", query, name);
// The server also rejects a gift with no quantity (PromotionAdminService.validate).
fireEvent.change(screen.getByLabelText("Gift quantity"), { target: { value: "1" } });
}
it("blocks saving while the gift variants are still loading", async () => {
const user = userEvent.setup();
catalogue.getProductVariations.mockReturnValue(new Promise(() => {}));
renderForm();
await startGift(user, "BA-002", /Nursing Bra/);
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(await screen.findByRole("region", { name: "Fix these before saving" })).toHaveTextContent("Loading gift variants — try again in a moment.");
expect(svc.createCampaign).not.toHaveBeenCalled();
});
it("blocks saving when the variants could not be loaded", async () => {
const user = userEvent.setup();
catalogue.getProductVariations.mockRejectedValue(new Error("boom"));
renderForm();
await startGift(user, "BA-002", /Nursing Bra/);
await screen.findByText("Couldn't load variants");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(await screen.findByRole("region", { name: "Fix these before saving" })).toHaveTextContent(BLOCKED_UNKNOWN);
expect(svc.createCampaign).not.toHaveBeenCalled();
});
it("blocks saving a saved gift whose product is not in the catalogue and has no variant", async () => {
const user = userEvent.setup();
renderForm({ ...stored, benefitType: "GIFT", benefitValue: 0, giftProductCode: "GONE-9", giftVariationId: null, giftQty: 1 });
await waitFor(() => expect(catalogue.listProducts).toHaveBeenCalled());
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("region", { name: "Fix these before saving" })).toHaveTextContent(BLOCKED_UNKNOWN);
expect(svc.updateCampaign).not.toHaveBeenCalled();
});
it("says loading, not could-not-load, while the catalogue is still loading", async () => {
const user = userEvent.setup();
catalogue.listProducts.mockReturnValue(new Promise(() => {}));
renderForm({ ...stored, benefitType: "GIFT", benefitValue: 0, giftProductCode: "BA-002", giftVariationId: null, giftQty: 1 });
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("region", { name: "Fix these before saving" })).toHaveTextContent("Loading gift variants — try again in a moment.");
expect(svc.updateCampaign).not.toHaveBeenCalled();
});
it("lets a locked campaign save its end date even with a blank gift variant on a multi-variant product", async () => {
const user = userEvent.setup();
svc.updateCampaign.mockResolvedValue(stored);
renderForm({ ...stored, locked: true, benefitType: "GIFT", benefitValue: 0, giftProductCode: "BA-002", giftVariationId: null, giftQty: 1 });
await waitFor(() => expect(catalogue.getProductVariations).toHaveBeenCalled());
await user.clear(screen.getByLabelText("Total uses"));
await user.type(screen.getByLabelText("Total uses"), "800");
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(svc.updateCampaign).toHaveBeenCalled());
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.queryByRole("region", { name: "Fix these before saving" })).not.toBeInTheDocument();
});
it("saves an unresolved gift that already has a variant", async () => {
const user = userEvent.setup();
svc.updateCampaign.mockResolvedValue(stored);
renderForm({ ...stored, benefitType: "GIFT", benefitValue: 0, giftProductCode: "GONE-9", giftVariationId: "5", giftQty: 1 });
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(svc.updateCampaign).toHaveBeenCalled());
});
it("saves a single-variant gift product with a blank variant", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await startGift(user, "E2E0928", /E2E0928 Test Product/);
await waitFor(() => expect(screen.getByRole("combobox", { name: "Gift variant" })).toBeEnabled());
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
expect(svc.createCampaign.mock.calls[0][0]).toMatchObject({ giftProductCode: "E2E0928P1", giftVariationId: null });
});
});
it("warns that saving removes older exclude and variant rules", async () => {
renderForm({ ...stored, allProducts: true, products: [{ productCode: "BA-002", variationId: null, mode: "EXCLUDE" }] });
expect(await screen.findByText("This campaign has older exclude or variant product rules. Saving removes them.")).toBeInTheDocument();
});
it("leaves a locked campaign's older rules as they are", () => {
renderForm({ ...stored, locked: true, allProducts: true, products: [{ productCode: "BA-002", variationId: null, mode: "EXCLUDE" }] });
expect(screen.getByTestId("campaign-summary")).toHaveTextContent("all products except BA-002");
expect(screen.queryByText(/Saving removes them/)).not.toBeInTheDocument();
});
it("drops older exclude rows and variant ids, keeping each included product once", async () => {
// Spec "Older exclude and variant rules": the form no longer authors either.
const user = userEvent.setup();
svc.updateCampaign.mockResolvedValue(stored);
renderForm({ ...stored, allProducts: false, products: [
{ productCode: "E2E0928P1", variationId: null, mode: "EXCLUDE" },
{ productCode: "BA-002", variationId: "20", mode: "INCLUDE" },
{ productCode: "BA-002", variationId: "21", mode: "INCLUDE" },
] });
await screen.findByText(/Isa Uchi Seamless/);
await user.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(svc.updateCampaign).toHaveBeenCalled());
expect(svc.updateCampaign.mock.calls[0][1].products).toEqual([{ productCode: "BA-002", variationId: null, mode: "INCLUDE" }]);
});
});
describe("CampaignForm three-step controls (redesign-campaign-form-three-steps)", () => {
async function saveDraft(user: ReturnType<typeof userEvent.setup>) {
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
return svc.createCampaign.mock.calls[0][0];
}
it("presses the All rank chip by default and explains it", () => {
renderForm();
const ranks = screen.getByRole("group", { name: "Rank" });
expect(within(ranks).getByRole("button", { name: "All" })).toHaveAttribute("aria-pressed", "true");
for (const name of ["Otter", "Squirrel", "Giraffe"]) {
expect(within(ranks).getByRole("button", { name })).toHaveAttribute("aria-pressed", "false");
}
expect(screen.getByText("Everyone, including guests who are not members.")).toBeInTheDocument();
});
it("pressing a rank then All saves no ranks", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Squirrel" }));
expect(screen.getByRole("button", { name: "Squirrel" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("button", { name: "All" })).toHaveAttribute("aria-pressed", "false");
expect(screen.getByText("None selected: everyone, including guests.")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "All" }));
expect(screen.getByRole("button", { name: "Squirrel" })).toHaveAttribute("aria-pressed", "false");
expect((await saveDraft(user)).ranks).toEqual([]);
});
it("asks for no code when each member gets a unique code", async () => {
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("radio", { name: "Unique code per member" }));
expect(screen.queryByLabelText("Code")).not.toBeInTheDocument();
});
it("shows the product rules only for Selected products", async () => {
const user = userEvent.setup();
renderForm();
const products = screen.getByRole("radiogroup", { name: "Products" });
expect(within(products).getByRole("radio", { name: "All products" })).toBeChecked();
expect(screen.queryByRole("button", { name: "Choose products" })).not.toBeInTheDocument();
await user.click(within(products).getByRole("radio", { name: "Selected products" }));
expect(screen.getByRole("button", { name: "Choose products" })).toBeInTheDocument();
await user.click(within(products).getByRole("radio", { name: "All products" }));
expect(screen.queryByRole("button", { name: "Choose products" })).not.toBeInTheDocument();
});
it("toggles each channel chip into the saved payload", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
const channels = screen.getByRole("group", { name: "Channels" });
expect(within(channels).getByRole("button", { name: "Online" })).toHaveAttribute("aria-pressed", "true");
await user.click(within(channels).getByRole("button", { name: "Online" }));
await user.click(within(channels).getByRole("button", { name: "Branch counter" }));
await user.click(within(channels).getByRole("button", { name: "Event POS" }));
expect(within(channels).getByRole("button", { name: "Online" })).toHaveAttribute("aria-pressed", "false");
expect(await saveDraft(user)).toMatchObject({ channelOnline: false, channelOutlet: true, channelEvent: true });
});
it("prefixes the money fields with RM", async () => {
const user = userEvent.setup();
renderForm();
// The addon sits beside its input, hidden from assistive tech; the label stays on the input.
const prefix = (label: string) =>
screen.getByLabelText(label).parentElement!.querySelector('[aria-hidden="true"]')?.textContent ?? null;
for (const label of ["Budget (RM)", "Minimum spend (RM)", "Maximum cap (RM)"]) {
expect(prefix(label)).toBe("RM");
}
expect(prefix("Value")).toBeNull();
await user.click(screen.getByRole("radio", { name: "Amount off" }));
expect(prefix("Value")).toBe("RM");
});
it("on a locked campaign leaves only Ends, budget, total uses and uses per member editable", () => {
renderForm({ ...stored, locked: true });
const ends = screen.getByLabelText("Ends");
const editable = [
ends,
// The calendar button beside Ends; both pickers name theirs "Open calendar", so it is found next to Ends.
within(ends.parentElement!).getByRole("button"),
screen.getByRole("combobox", { name: "Ends time" }),
screen.getByLabelText("Budget (RM)"),
screen.getByLabelText("Total uses"),
screen.getByLabelText("Uses per member"),
];
const controls = STEPS.flatMap((name) => {
const step = screen.getByRole("group", { name });
return (["button", "radio", "textbox", "spinbutton", "combobox"] as const).flatMap((role) => within(step).queryAllByRole(role));
});
for (const el of editable) {
expect(controls).toContain(el);
expect(el).toBeEnabled();
}
const frozen = controls.filter((el) => !editable.includes(el));
// Step 1: 5 mechanics, value, cap, name, customer label (9). Step 2: 3 claim types, code, 4 rank chips,
// 2 product choices, 3 channel chips (13). Step 3: Starts date, its calendar, its time, min spend, min items (5).
expect(frozen).toHaveLength(27);
for (const el of frozen) expect(el).toBeDisabled();
});
});
describe("CampaignForm checks before saving (redesign-campaign-form-three-steps)", () => {
const fixList = () => screen.queryByRole("heading", { name: "Fix these before saving" })?.closest<HTMLElement>("[data-slot='alert']") ?? null;
const items = () => within(fixList()!).getAllByRole("button").map((b) => b.textContent);
function expectNothingSent() {
expect(svc.createCampaign).not.toHaveBeenCalled();
expect(svc.updateCampaign).not.toHaveBeenCalled();
expect(svc.setCampaignStatus).not.toHaveBeenCalled();
}
it("shows no list before any save attempt", () => {
renderForm();
expect(fixList()).toBeNull();
});
it("Publish on an empty campaign sends nothing and lists what is missing", async () => {
// Nothing on the empty form is required to the browser (no date is picked, so neither time is
// required), so reportValidity passes and the client checks are what stops the save.
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("button", { name: "Publish" }));
expectNothingSent();
expect(items()).toEqual([
"Give the campaign a name.",
"Enter the customer label.",
"Enter a value above 0.",
"Set a start date and time.",
"Set an end date and time.",
]);
expect(fixList()).toHaveFocus();
});
it("moves focus to the channels when their item is chosen", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
const channels = screen.getByRole("group", { name: "Channels" });
await user.click(within(channels).getByRole("button", { name: "Online" }));
await user.click(screen.getByRole("button", { name: "Save draft" }));
expectNothingSent();
await user.click(within(fixList()!).getByRole("button", { name: "Choose at least one channel." }));
expect(channels).toContainElement(document.activeElement as HTMLElement);
});
it("asks for a 3 to 40 character shared code and sends nothing", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Shared code" }));
await user.type(screen.getByLabelText("Code"), "AB");
await user.click(screen.getByRole("button", { name: "Save draft" }));
expectNothingSent();
expect(items()).toEqual(["Enter a code of 3 to 40 letters or digits."]);
});
it("marks the field inline and drops its item once fixed, leaving the others", async () => {
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("button", { name: "Save draft" }));
const name = screen.getByLabelText("Name");
expect(name).toHaveAttribute("aria-invalid", "true");
expect(name).toHaveAttribute("aria-describedby", "campaign-name-error campaign-name-hint");
expect(document.getElementById("campaign-name-error")).toHaveTextContent("Give the campaign a name.");
expect(name).toHaveAccessibleDescription(expect.stringContaining("Give the campaign a name."));
fireEvent.change(name, { target: { value: "Raya sale" } });
expect(items()).not.toContain("Give the campaign a name.");
expect(items()).toContain("Enter the customer label.");
expect(name).not.toHaveAttribute("aria-invalid");
expect(document.getElementById("campaign-name-error")).toBeNull();
expect(screen.getByLabelText("Customer label")).toHaveAttribute("aria-invalid", "true");
});
it("focuses a field from its item", async () => {
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("button", { name: "Save draft" }));
await user.click(within(fixList()!).getByRole("button", { name: "Enter the customer label." }));
expect(screen.getByLabelText("Customer label")).toHaveFocus();
});
it("checks only the end date on a locked campaign with a blank end", async () => {
const user = userEvent.setup();
renderForm({ ...stored, locked: true, name: "", effectiveTo: "" });
await user.click(screen.getByRole("button", { name: "Save" }));
expectNothingSent();
expect(items()).toEqual(["Set an end date and time."]);
});
it("stops checking live after a successful save", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
const { onSaved } = renderForm();
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(fixList()).not.toBeNull();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
// Breaking a field after the save shows nothing until the next attempt.
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "" } });
expect(fixList()).toBeNull();
expect(screen.getByLabelText("Name")).not.toHaveAttribute("aria-invalid");
});
it("focuses the list again on a second failed attempt", async () => {
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(fixList()).toHaveFocus();
await user.click(screen.getByLabelText("Name"));
expect(fixList()).not.toHaveFocus();
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(fixList()).toHaveFocus();
});
it("names the list as a region, not an alert", async () => {
const user = userEvent.setup();
renderForm();
await user.click(screen.getByRole("button", { name: "Save draft" }));
expect(screen.getByRole("region", { name: "Fix these before saving" })).toBe(fixList());
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("publishes once the failing checks are fixed", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, uuid: "C-9", status: "DRAFT" });
svc.setCampaignStatus.mockResolvedValue({ ...stored, uuid: "C-9", status: "ACTIVE" });
const { onSaved } = renderForm();
await user.click(screen.getByRole("button", { name: "Publish" }));
expectNothingSent();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("button", { name: "Publish" }));
await waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(svc.setCampaignStatus).toHaveBeenCalledTimes(1);
expect(svc.setCampaignStatus).toHaveBeenCalledWith("C-9", "ACTIVE");
});
it("lists a gift quantity of 0 before the browser's own validation", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Gift" }));
fireEvent.change(screen.getByLabelText("Gift quantity"), { target: { value: "0" } });
await user.click(screen.getByRole("button", { name: "Save draft" }));
expectNothingSent();
expect(items()).toContain("Gift quantity must be a whole number of at least 1.");
});
it("lists a fractional buy quantity and marks both quantities", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Buy X get Y" }));
fireEvent.change(screen.getByLabelText("Buy quantity"), { target: { value: "1.5" } });
fireEvent.change(screen.getByLabelText("Get quantity"), { target: { value: "1" } });
await user.click(screen.getByRole("button", { name: "Save draft" }));
expectNothingSent();
expect(items()).toEqual(["Buy and get quantities must be whole numbers of at least 1."]);
for (const label of ["Buy quantity", "Get quantity"]) {
expect(screen.getByLabelText(label)).toHaveAttribute("aria-invalid", "true");
expect(screen.getByLabelText(label)).toHaveAttribute("aria-describedby", "campaign-buy-qty-error");
}
});
it("focuses Choose products when Selected products has none", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Selected products" }));
await user.click(screen.getByRole("button", { name: "Save draft" }));
await user.click(within(fixList()!).getByRole("button", { name: "Choose at least one product to include." }));
expect(screen.getByRole("button", { name: "Choose products" })).toHaveFocus();
});
it("treats a campaign whose products are only excluded as having none chosen", async () => {
const user = userEvent.setup();
renderForm({ ...stored, allProducts: false, products: [{ productCode: "BA-002", variationId: null, mode: "EXCLUDE" }] });
await waitFor(() => expect(catalogue.listProducts).toHaveBeenCalled());
expect(screen.getByText("Nothing chosen yet")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Save" }));
expectNothingSent();
await user.click(within(fixList()!).getByRole("button", { name: "Choose at least one product to include." }));
expect(screen.getByRole("button", { name: "Choose products" })).toHaveFocus();
});
it("marks the gift product group and focuses its search from the item", async () => {
const user = userEvent.setup();
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Gift" }));
fireEvent.change(screen.getByLabelText("Gift quantity"), { target: { value: "1" } });
await user.click(screen.getByRole("button", { name: "Save draft" }));
const group = screen.getByRole("group", { name: "Gift product" });
// aria-invalid is not supported on role="group"; the group points at its message instead.
expect(group).not.toHaveAttribute("aria-invalid");
expect(group).toHaveAttribute("aria-describedby", "campaign-gift-product-error");
expect(document.getElementById("campaign-gift-product-error")).toHaveTextContent("Choose the gift product.");
await user.click(within(fixList()!).getByRole("button", { name: "Choose the gift product." }));
expect(screen.getByRole("combobox", { name: "Gift product" })).toHaveFocus();
});
});
describe("CampaignForm exposure warnings (redesign-campaign-form-three-steps)", () => {
it("warns when the amount off wipes out the minimum spend, and still saves", async () => {
const user = userEvent.setup();
svc.createCampaign.mockResolvedValue({ ...stored, status: "DRAFT" });
renderForm();
await fillMinimalNewCampaign();
await user.click(screen.getByRole("radio", { name: "Amount off" }));
fireEvent.change(screen.getByLabelText("Value"), { target: { value: "50" } });
fireEvent.change(screen.getByLabelText("Minimum spend (RM)"), { target: { value: "30" } });
const warning = screen.getByText(
"RM50.00 off a RM30.00 minimum: a basket at the minimum would come to nothing. Raise the minimum above the discount.",
).closest("[role='status']") as HTMLElement;
expect(warning).not.toBeNull();
expect(screen.getByLabelText("Minimum spend (RM)").getAttribute("aria-describedby")!.split(" ")).toContain("campaign-min-spend-warning");
expect(document.getElementById("campaign-min-spend-warning")).toContainElement(warning);
await user.click(screen.getByRole("button", { name: "Save draft" }));
await waitFor(() => expect(svc.createCampaign).toHaveBeenCalled());
});
it("warns about a percentage with no cap and no budget until a budget is set", () => {
renderForm();
fireEvent.change(screen.getByLabelText("Value"), { target: { value: "10" } });
const text = "No maximum cap and no total budget: a percentage keeps growing with the basket, so the cost is unlimited. Set a cap or a budget.";
const warning = screen.getByText(text).closest("[role='status']") as HTMLElement;
expect(warning).not.toBeNull();
expect(screen.getByLabelText("Maximum cap (RM)")).toHaveAttribute("aria-describedby", "campaign-max-cap-warning");
expect(document.getElementById("campaign-max-cap-warning")).toContainElement(warning);
fireEvent.change(screen.getByLabelText("Budget (RM)"), { target: { value: "500" } });
expect(screen.queryByText(text)).not.toBeInTheDocument();
expect(screen.getByLabelText("Maximum cap (RM)")).not.toHaveAttribute("aria-describedby");
});
});