Files
co-lite/solvway-admin-portal/app/components/product-page/VariantsSection.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

561 lines
31 KiB
TypeScript

import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
// simplify-product-setup: the Product page's Variants & prices section (an owned SKU).
const catalog = vi.hoisted(() => ({ saveCatalog: vi.fn(), getSalesItem: vi.fn(), getSku: vi.fn(), listSkus: vi.fn(), searchSkuVariations: vi.fn() }));
const product = vi.hoisted(() => ({ getProductOptions: vi.fn(), listProductTags: vi.fn(), uploadProductImage: vi.fn(), listProducts: vi.fn() }));
vi.mock("@/app/lib/services/adminCatalogSetup", () => catalog);
vi.mock("@/app/lib/services/adminProduct", () => ({
...product,
PRODUCT_STATUS_FILTER_OPTIONS: [{ value: "Y", labelKey: "Active" }, { value: "N", labelKey: "Inactive" }],
}));
const MY = { id: 2, code: "MY", name: "Malaysia", type: "C", status: "Y", parent: null };
const places = vi.hoisted(() => ({ listAdminLocations: vi.fn() }));
vi.mock("@/app/lib/services/adminLocations", () => places);
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
vi.mock("@/app/components/products/QianyiSkuPicker", () => ({
QianyiSkuPicker: ({ onChange, label }: { onChange: (sku?: string, option?: unknown) => void; label?: string }) => (
<button type="button" onClick={() => onChange("RBRAMA01", { sku: "RBRAMA01", title: "Bra", weightKg: 0.4 })}>
{label ?? "Pick QianYi"}
</button>
),
}));
import { memoryRouter } from "@/test/memoryRouter";
import { pickDate } from "@/test/pickDate";
import { todayKL } from "@/app/lib/productPage";
import { VariantsSection } from "./VariantsSection";
import { ProductSetupPage, type PageOptions } from "./ProductSetupPage";
import { emptySalesItem, emptySku, type FieldErrors, type SalesItemDraft, type SkuDraft, type PriceDraft } from "@/app/lib/catalogSetup";
const TODAY = "2026-10-21";
const OPTIONS: PageOptions = { brands: [], categories: [], priceTypes: [{ code: "MEMBER", status: "Y" }, { code: "EVENT", status: "Y" }], tags: [], locations: [MY as never] };
function Harness({
deferred = [],
errors = {},
initialItem,
initialSku,
initialPrices,
options = OPTIONS,
onState,
}: {
initialPrices?: PriceDraft[];
options?: PageOptions;
deferred?: number[];
errors?: FieldErrors;
initialItem?: SalesItemDraft;
initialSku?: SkuDraft;
onState?: (s: { item: SalesItemDraft; sku: SkuDraft | null; prices: PriceDraft[] }) => void;
}) {
const [state, setState] = useState({
item: initialItem ?? { ...emptySalesItem(), code: "YELLOW-002", name: "Yellow" },
sku: (initialSku ?? emptySku()) as SkuDraft | null,
prices: initialPrices ?? ([] as PriceDraft[]),
});
onState?.(state);
return (
<VariantsSection
item={state.item}
saved={state.item}
savedPrices={[]}
sku={state.sku}
prices={state.prices}
deferred={deferred}
onLink={() => {}}
onReload={() => {}}
errors={errors}
saving={false}
today={TODAY}
options={options}
onChange={(n) => setState((s) => ({ item: n.item ?? s.item, prices: n.prices ?? s.prices, sku: n.sku === undefined ? s.sku : n.sku }))}
/>
);
}
async function addValues(label: string, values: string[]) {
const input = screen.getByLabelText(label);
for (const v of values) await userEvent.type(input, `${v}{Enter}`);
}
async function buildSizesAndColour() {
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
await userEvent.click(screen.getByRole("button", { name: "Add option" }));
await userEvent.type(screen.getByLabelText("Option 2 name"), "Colour");
await addValues("Option 1 values", ["M", "L", "XL"]);
await addValues("Option 2 values", ["Black"]);
}
beforeEach(() => {
places.listAdminLocations.mockReset();
places.listAdminLocations.mockResolvedValue([MY]);
Object.values(catalog).forEach((f) => f.mockReset());
Object.values(product).forEach((f) => f.mockReset());
product.getProductOptions.mockResolvedValue({ brands: [{ code: "NIKE", name: "Nike", status: "Y" }], categories: [{ code: "FW", name: "Footwear", status: "Y" }], priceTypes: [{ code: "MEMBER", status: "Y" }, { code: "EVENT", status: "Y" }] });
product.listProductTags.mockResolvedValue([]);
product.uploadProductImage.mockResolvedValue({ url: "https://cdn/new.png" });
catalog.listSkus.mockResolvedValue({ items: [], total: 0 });
catalog.searchSkuVariations.mockResolvedValue([]);
memoryRouter.reset("/products/new");
});
describe("VariantsSection", () => {
it("Size M, L, XL and Colour Black make three rows with suggested codes", async () => {
render(<Harness />);
await buildSizesAndColour();
for (const code of ["YELLOW-002-M-BLACK", "YELLOW-002-L-BLACK", "YELLOW-002-XL-BLACK"]) {
expect(screen.getByDisplayValue(code)).toHaveAttribute("readonly");
}
expect(within(screen.getAllByRole("table")[0]).getAllByRole("row")).toHaveLength(4);
});
it("on a saved SKU a new variant keeps its generated code after a QianYi pick", async () => {
const { skuFromView } = await import("@/app/lib/catalogSetup");
const sku = skuFromView({
id: 5, code: "YELLOW-002", name: "Yellow", status: "Y", optionNames: ["Size"],
variations: [{ id: 51, code: "YELLOW-002-M", variant: "Size", variantName: "M", options: ["M"], usedBy: ["YELLOW-002"], onHand: 3 }],
} as never);
const comp = { skuVariationId: 51, skuVariationCode: "", skuId: 5, label: "", qty: "1", qtyFoc: "0", qyTouched: false };
const item: SalesItemDraft = { ...emptySalesItem(), id: 9, code: "YELLOW-002", name: "Yellow", variations: [{ id: 1, key: "v1", variant: "Size", variantName: "M", removable: false, components: [comp] }] };
render(<Harness initialItem={item} initialSku={sku} />);
await addValues("Option 1 values", ["XL"]);
expect(screen.getByDisplayValue("YELLOW-002-XL")).toHaveAttribute("readonly");
await userEvent.click(screen.getByRole("button", { name: "Barcodes & QianYi" }));
await userEvent.click(screen.getAllByRole("button", { name: /QianYi for/ })[1]);
expect(screen.getByDisplayValue("YELLOW-002-XL")).toBeInTheDocument();
expect(screen.queryByDisplayValue("RBRAMA01")).not.toBeInTheDocument();
});
it("a value containing a comma is refused", async () => {
render(<Harness />);
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.click(screen.getByLabelText("Option 1 values"));
await userEvent.paste("M,L");
await userEvent.keyboard("{Enter}");
expect(screen.getByText("A value can't contain a comma")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /^Remove (?!option)/ })).not.toBeInTheDocument();
});
it("removing a chip removes its row", async () => {
render(<Harness />);
await buildSizesAndColour();
await userEvent.click(screen.getByRole("button", { name: "Remove XL" }));
expect(screen.queryByDisplayValue("YELLOW-002-XL-BLACK")).not.toBeInTheDocument();
expect(within(screen.getAllByRole("table")[0]).getAllByRole("row")).toHaveLength(3);
});
it("a sold value stays as a row and says it cannot be removed", async () => {
const { skuFromView } = await import("@/app/lib/catalogSetup");
const sku = skuFromView({
id: 5, code: "YELLOW-002", name: "Yellow", status: "Y", optionNames: ["Size"],
variations: [
{ id: 51, code: "YELLOW-002-M", variant: "Size", variantName: "M", options: ["M"], usedBy: ["YELLOW-002"], onHand: 3 },
{ id: 52, code: "YELLOW-002-L", variant: "Size", variantName: "L", options: ["L"], usedBy: ["YELLOW-002"], onHand: 0 },
],
} as never);
const comp = (id: number) => ({ skuVariationId: id, skuVariationCode: "", skuId: 5, label: "", qty: "1", qtyFoc: "0", qyTouched: false });
const item: SalesItemDraft = {
...emptySalesItem(), id: 9, code: "YELLOW-002", name: "Yellow",
variations: [
{ id: 1, key: "v1", variant: "Size", variantName: "M", removable: false, components: [comp(51)] },
{ id: 2, key: "v2", variant: "Size", variantName: "L", removable: true, components: [comp(52)] },
],
};
render(<Harness initialItem={item} initialSku={sku} />);
await userEvent.click(screen.getByRole("button", { name: "Remove L" }));
// The backend refuses to remove any saved SKU variant this product still uses (SkuSetupService inUseReason).
expect(screen.getByDisplayValue("YELLOW-002-L")).toBeInTheDocument();
expect(screen.getByText("Saved, can't be removed")).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Remove M" }));
expect(screen.getByDisplayValue("YELLOW-002-M")).toBeInTheDocument();
expect(screen.getByText("Has orders, can't be removed")).toBeInTheDocument();
});
it("A new product with variants M and L lists a row per variant and price type, each from today with no end", async () => {
render(<Harness />);
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
await addValues("Option 1 values", ["M", "L"]);
const list = within(screen.getByTestId("price-list"));
const rows = list.getAllByTestId("price-row");
expect(rows).toHaveLength(4);
expect(rows.map((r) => within(r).getAllByRole("cell").slice(0, 2).map((c) => c.textContent))).toEqual([["M", "Selling price"], ["M", "Event price"], ["L", "Selling price"], ["L", "Event price"]]);
for (const r of rows) {
expect(within(r).getByPlaceholderText("No end")).toBeInTheDocument();
expect(within(r).getByRole("textbox", { name: /From$/ })).toHaveValue("21/10/2026");
}
expect(screen.queryByText(/MEMBER|EVENT/)).not.toBeInTheDocument();
});
it("Set for all variants with 129.00 fills each variant's Selling price", async () => {
render(<Harness />);
await buildSizesAndColour();
await userEvent.type(screen.getByLabelText("Selling price for all"), "129.00");
await userEvent.click(screen.getAllByRole("button", { name: "Apply" })[0]);
for (const name of ["M / Black", "L / Black", "XL / Black"]) {
expect(screen.getByLabelText(`Selling price for ${name}`)).toHaveValue(129);
}
});
it("the variants table offers only Shipping and Barcodes & QianYi, and XL shows Size missing from the Barcodes view", async () => {
render(<Harness />);
await buildSizesAndColour();
expect(screen.queryByRole("button", { name: "Prices" })).not.toBeInTheDocument();
expect(screen.getAllByRole("button", { name: /^(Shipping|Barcodes & QianYi)$/ })).toHaveLength(2);
expect(screen.getByRole("button", { name: "Shipping" })).toHaveAttribute("aria-pressed", "true");
for (const n of [1, 2, 3]) {
await userEvent.type(screen.getByLabelText(`Variant ${n} weight`), "0.5");
if (n !== 3) await userEvent.type(screen.getByLabelText(`Variant ${n} length (cm)`), "10");
await userEvent.type(screen.getByLabelText(`Variant ${n} width (cm)`), "10");
await userEvent.type(screen.getByLabelText(`Variant ${n} height (cm)`), "10");
}
await userEvent.click(screen.getByRole("button", { name: "Barcodes & QianYi" }));
const rows = within(screen.getAllByRole("table")[0]).getAllByRole("row");
expect(within(rows[3]).getByText("Size missing")).toBeInTheDocument();
expect(within(rows[1]).queryByText("Size missing")).not.toBeInTheDocument();
});
it("a QianYi pick on M sets its weight to 0.4", async () => {
render(<Harness />);
await buildSizesAndColour();
await userEvent.click(screen.getByRole("button", { name: "Barcodes & QianYi" }));
await userEvent.click(screen.getAllByRole("button", { name: /Pick QianYi|QianYi for/ })[0]);
await userEvent.click(screen.getByRole("button", { name: "Shipping" }));
expect(screen.getByLabelText("Variant 1 weight")).toHaveValue(0.4);
});
it("deferred rows are named under the table", () => {
render(
<Harness
deferred={[1]}
initialSku={{
...emptySku(), code: "Y", name: "Y", optionNames: ["Size"], optionValues: ["M, XL"],
variants: [
{ ...emptySku().variants[0], options: ["M"], variant: "Size", variantName: "M", code: "Y-M", weight: "0.5", lengthCm: "1", widthCm: "1", heightCm: "1" },
{ ...emptySku().variants[0], options: ["XL"], variant: "Size", variantName: "XL", code: "Y-XL" },
],
}}
/>,
);
expect(screen.getByText("Variants not saved yet: add shipping size (XL)")).toBeInTheDocument();
});
it("Rows follow the active price types", () => {
const priceTypes = [
{ code: "WHOLESALE", status: "Y" }, { code: "EVENT", status: "Y" }, { code: "MEMBER", status: "Y" }, { code: "ZZ_QA_TEST", status: "N" },
];
render(<Harness options={{ ...OPTIONS, priceTypes }} />);
const labels = within(screen.getByTestId("price-list")).getAllByTestId("price-row").map((r) => within(r).getAllByRole("cell")[0].textContent);
expect(labels).toEqual(["Selling price", "WHOLESALE price", "Event price"]);
expect(screen.queryByText(/ZZ_QA_TEST/)).not.toBeInTheDocument();
});
const row = (over: Partial<PriceDraft>): PriceDraft => ({ variationKey: "k1", currency: "MYR", priceType: "MEMBER", country: "", region: "", price: "129.00", status: "Y", effectiveFrom: "2026-01-01", effectiveTo: "", ...over });
const oneVariant = (variantName = "") => ({
sku: { ...emptySku(), code: "Y", name: "Y", variants: [{ ...emptySku().variants[0], code: "Y", rowKey: "k1" }] },
item: { ...emptySalesItem(), code: "Y", name: "Y", variations: [{ key: "k1", variant: variantName ? "Size" : "", variantName, removable: true, components: [] }] },
});
it("a saved row stored with the Malaysia country id shows as a normal row, with no currency, country or region field", () => {
const { sku, item } = oneVariant();
render(<Harness initialItem={item} initialSku={sku} initialPrices={[row({ id: 5, country: "2", price: "50.00" })]} />);
expect(screen.getByLabelText("Selling price for Default")).toHaveValue(50);
expect(screen.queryByText(/currency|country|region/i)).not.toBeInTheDocument();
expect(screen.queryByRole("combobox", { name: /currency|country|region/i })).not.toBeInTheDocument();
});
it("a NULL-country and a country 2 current Selling row: the slot shows the NULL one, the other is listed separately", () => {
const { sku, item } = oneVariant();
render(<Harness initialItem={item} initialSku={sku} initialPrices={[row({ id: 6, country: "2", price: "20.00" }), row({ id: 5, country: "", price: "10.00" })]} />);
expect(screen.getByLabelText("Selling price for Default")).toHaveValue(10);
expect(screen.getByLabelText("Price 1 amount")).toHaveValue(20);
expect(screen.queryByLabelText("Price 2 amount")).not.toBeInTheDocument();
});
it("an ended row is hidden until Show past prices (1) is opened", async () => {
const { sku, item } = oneVariant("M");
render(<Harness initialItem={item} initialSku={sku} initialPrices={[row({ id: 5 }), row({ id: 4, effectiveFrom: "2025-01-01", effectiveTo: "2026-10-20", price: "99.00" })]} />);
expect(screen.queryByLabelText("Price 2 amount")).not.toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Show past prices (1)" }));
expect(screen.getByLabelText("Price 2 amount")).toHaveValue(99);
});
it("a later row alone is listed as a row and leaves no empty Selling row", () => {
const { sku, item } = oneVariant();
render(<Harness initialItem={item} initialSku={sku} initialPrices={[row({ price: "119", effectiveFrom: "2026-11-01", later: true })]} />);
expect(screen.queryByLabelText(/^Selling price for Default/)).not.toBeInTheDocument();
expect(screen.getByLabelText("Price 1 amount")).toHaveValue(119);
});
it("the unsaved-variants note follows the current draft", async () => {
render(<Harness deferred={[1]} initialSku={{ ...emptySku(), code: "Y", name: "Y", optionNames: ["Size"], optionValues: ["M"], variants: [{ ...emptySku().variants[0], options: ["M"], variant: "Size", variantName: "M", code: "Y-M" }] }} />);
expect(screen.getByText("Variants not saved yet: add shipping size (M)")).toBeInTheDocument();
await addValues("Option 1 values", ["L"]);
expect(screen.getByText("Variants not saved yet: add shipping size (M, L)")).toBeInTheDocument();
});
it("removing an option value drops that row's price rows", async () => {
let last: { item: SalesItemDraft; prices: PriceDraft[] } | null = null;
render(<Harness onState={(st) => (last = st)} />);
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
await addValues("Option 1 values", ["M", "L"]);
await userEvent.type(screen.getByLabelText(/^Selling price for L/), "50");
await userEvent.tab();
expect(last!.prices).toHaveLength(1);
await userEvent.click(screen.getByRole("button", { name: "Remove L" }));
const keys = new Set(last!.item.variations.map((v) => v.key));
expect(last!.prices.filter((p) => !keys.has(p.variationKey))).toEqual([]);
});
it("an error in a hidden column set shows as a badge in the Status column; a Selling price error shows at its slot", async () => {
const { sku, item } = oneVariant();
const { unmount } = render(<Harness initialItem={item} initialSku={sku} errors={{ "pricing.quick.k1": "Price needed" }} />);
expect(screen.getByText("Price needed")).toBeInTheDocument();
expect(screen.queryByText(/^Check /)).not.toBeInTheDocument();
unmount();
render(<Harness initialItem={item} initialSku={sku} errors={{ "sku.variations[0].weight": "Weight needed", "sku.variations[0].barcodes[0].barcode": "Bad barcode" }} />);
expect(screen.getByText("Weight needed")).toBeInTheDocument();
expect(screen.getByText("Check Barcodes & QianYi")).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Barcodes & QianYi" }));
expect(screen.getByText("Check Shipping")).toBeInTheDocument();
});
it("shows the backend's field errors at their fields and the compare-at error under its field", () => {
render(<Harness errors={{ "salesItem.compareAtPrice": "Compare-at must beat selling", "sku.variations[0].code": "Code taken", "pricing.quick.nope": "x" }} />);
expect(screen.getByText("Compare-at must beat selling")).toBeInTheDocument();
expect(screen.getByText("Code taken")).toBeInTheDocument();
});
});
describe("ProductSetupPage with the Variants section", () => {
async function fillBasics() {
await userEvent.type(await screen.findByLabelText("Product code"), "YELLOW-002");
await userEvent.type(screen.getByLabelText("Product name"), "Yellow");
await userEvent.click(screen.getByRole("combobox", { name: "Brand" }));
await userEvent.click(await screen.findByRole("option", { name: "NIKE" }));
await userEvent.click(screen.getByRole("combobox", { name: "Category" }));
await userEvent.click(await screen.findByRole("option", { name: "FW" }));
await userEvent.upload(screen.getByLabelText("Product images"), new File(["x"], "a.png", { type: "image/png" }));
await waitFor(() => expect(product.uploadProductImage).toHaveBeenCalled());
}
async function fillShipping() {
for (const [label, value] of [["Variant 1 weight", "0.5"], ["Variant 1 length (cm)", "1"], ["Variant 1 width (cm)", "1"], ["Variant 1 height (cm)", "1"]]) {
await userEvent.type(screen.getByLabelText(label), value);
}
}
const saved = { salesItem: { id: 77, code: "YELLOW-002", name: "Yellow", brand: "NIKE", category: "FW", status: "N", productType: "STANDARD", groupComponentProductIds: [], images: [{ url: "https://cdn/new.png", sortOrder: 0 }], yellowLabel: false, allowOversell: false, variations: [] } };
it("a later price added from today is refused with 'Pick a date after today' and nothing is sent", async () => {
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.type(screen.getByLabelText(/^Selling price for Default/), "100");
await fillShipping();
// The Add a later price default is the first active type: Selling price.
await userEvent.click(screen.getByRole("button", { name: "Add a later price" }));
expect(within(screen.getByLabelText("Price 2 amount").closest("tr")!).getAllByRole("cell")[0].textContent).toBe("Selling price");
pickDate("Price 2 from", todayKL());
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Pick a date after today")).toBeInTheDocument();
expect(catalog.saveCatalog).not.toHaveBeenCalled();
});
it("Add a later price, choosing Selling price, adds a row from tomorrow", async () => {
render(<ProductSetupPage newType="product" />);
await userEvent.click(await screen.findByRole("button", { name: "Add a later price" }));
await userEvent.click(screen.getByRole("combobox", { name: "Price type" }));
await userEvent.click(await screen.findByRole("option", { name: "Selling price" }));
await userEvent.click(screen.getByRole("button", { name: "Add a later price" }));
const tomorrow = new Date(`${todayKL()}T00:00:00Z`);
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
const [y, m, d] = tomorrow.toISOString().slice(0, 10).split("-");
expect(screen.getByLabelText("Price 1 from")).toHaveValue(`${d}/${m}/${y}`);
});
it("a typed Selling price is sent with currency MYR and the Malaysia node's id as country", async () => {
catalog.saveCatalog.mockResolvedValue(saved);
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.type(await screen.findByLabelText(/^Selling price for Default/), "119.00");
await fillShipping();
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(catalog.saveCatalog).toHaveBeenCalledTimes(1));
expect(catalog.saveCatalog.mock.calls[0][0].pricing.rows).toEqual([expect.objectContaining({ priceType: "MEMBER", price: 119, currency: "MYR", country: "2" })]);
expect(catalog.saveCatalog.mock.calls[0][0].pricing.rows[0]).not.toHaveProperty("region");
expect(catalog.saveCatalog.mock.calls[0][0].pricing.rows[0]).not.toHaveProperty("later");
});
it("A new price starts on a set day: the dates set on the empty row are sent with the price", async () => {
catalog.saveCatalog.mockResolvedValue(saved);
render(<ProductSetupPage newType="product" />);
await fillBasics();
pickDate(screen.getByRole("textbox", { name: "Selling price From" }), "2026-11-01");
pickDate(screen.getByRole("textbox", { name: "Selling price To" }), "2026-12-31");
await userEvent.type(await screen.findByLabelText(/^Selling price for Default/), "119.00");
await fillShipping();
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(catalog.saveCatalog).toHaveBeenCalledTimes(1));
expect(catalog.saveCatalog.mock.calls[0][0].pricing.rows).toEqual([expect.objectContaining({ priceType: "MEMBER", price: 119, effectiveFrom: "2026-11-01T00:00:00", effectiveTo: "2026-12-31T23:59:59" })]);
});
it("without a Malaysia location the save is blocked and the message shows under Prices without opening anything", async () => {
places.listAdminLocations.mockResolvedValue([]);
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.type(screen.getByLabelText(/^Selling price for Default/), "100");
await fillShipping();
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Malaysia is missing from Locations")).toBeVisible();
expect(catalog.saveCatalog).not.toHaveBeenCalled();
});
it("a compare-at price not above the highest selling price blocks Save under its field", async () => {
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.type(screen.getByLabelText(/^Selling price for Default/), "100");
await userEvent.type(screen.getByLabelText("MSRP"), "90");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("MSRP must be greater than the highest selling price")).toBeInTheDocument();
expect(catalog.saveCatalog).not.toHaveBeenCalled();
});
it("a new draft with an unfinished variant saves its details only and stays on the page", async () => {
catalog.saveCatalog.mockResolvedValue({
salesItem: { id: 77, code: "YELLOW-002", name: "Yellow", brand: "NIKE", category: "FW", status: "N", productType: "STANDARD", groupComponentProductIds: [], images: [{ url: "https://cdn/new.png", sortOrder: 0 }], yellowLabel: false, allowOversell: false, variations: [] },
});
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(catalog.saveCatalog).toHaveBeenCalledTimes(1));
expect(Object.keys(catalog.saveCatalog.mock.calls[0][0])).toEqual(["salesItem"]);
expect(await screen.findByText(/Variants not saved yet: add shipping size/)).toBeInTheDocument();
expect(memoryRouter.getPathname()).toBe("/products/new");
});
const draftSaved = {
salesItem: { id: 77, code: "YELLOW-002", name: "Yellow", brand: "NIKE", category: "FW", status: "N", productType: "STANDARD", groupComponentProductIds: [], images: [{ url: "https://cdn/new.png", sortOrder: 0 }], yellowLabel: false, allowOversell: false, variations: [] },
};
it("a deferred draft save warns in the header that variants are held back, with no link away", async () => {
catalog.saveCatalog.mockResolvedValue(draftSaved);
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
await userEvent.type(screen.getByLabelText("Option 1 values"), "M{Enter}");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
const header = screen.getByRole("banner");
expect(await within(header).findByText("YELLOW-002 saved, but some variants are not saved yet. Fix them below.")).toBeInTheDocument();
expect(within(header).queryByText("YELLOW-002 created.")).not.toBeInTheDocument();
expect(within(header).queryByRole("link", { name: "Back to products" })).not.toBeInTheDocument();
});
it("Discard after a deferred draft save restores the SKU a reload would show", async () => {
catalog.saveCatalog.mockResolvedValue(draftSaved);
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
await userEvent.type(screen.getByLabelText("Option 1 values"), "M{Enter}");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText(/Variants not saved yet/)).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Discard" }));
expect(screen.getByRole("switch", { name: "Has sizes, colours or other options" })).not.toBeChecked();
expect(screen.getByLabelText("Variant 1 code")).toHaveValue("YELLOW-002");
});
it("a second Save after the first draft save sends the sales item id", async () => {
catalog.saveCatalog.mockResolvedValue(draftSaved);
render(<ProductSetupPage newType="product" />);
await fillBasics();
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await screen.findByText(/Variants not saved yet/);
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(catalog.saveCatalog).toHaveBeenCalledTimes(2));
expect(catalog.saveCatalog.mock.calls[1][0].salesItem.id).toBe(77);
});
it("Discard after a deferred save of a saved product keeps its saved SKU", async () => {
catalog.getSalesItem.mockResolvedValue({
id: 9, code: "YELLOW-002", name: "Yellow", brand: "NIKE", category: "FW", status: "N", productType: "STANDARD",
groupComponentProductIds: [], images: [{ url: "https://cdn/a.png", sortOrder: 0 }], yellowLabel: false, allowOversell: false,
variations: [{ id: 1, variant: "DEFAULT", variantName: "DEFAULT", removable: true, pricing: [], components: [{ skuVariationId: 51, skuVariationCode: "YELLOW-002", skuId: 5, skuCode: "YELLOW-002", skuName: "Yellow", variant: "DEFAULT", variantName: "DEFAULT", qty: 1, qtyFoc: 0 }] }],
});
catalog.getSku.mockResolvedValue({
id: 5, code: "YELLOW-002", name: "Yellow", status: "Y", supplierId: null, optionNames: [],
variations: [{ id: 51, code: "YELLOW-002", variant: "DEFAULT", variantName: "DEFAULT", options: [], weight: 0.5, lengthCm: 1, widthCm: 1, heightCm: 1, usedBy: ["YELLOW-002"], onHand: 0, barcodes: [] }],
});
catalog.saveCatalog.mockImplementation(async (body: { salesItem: object }) => ({ salesItem: { ...(await catalog.getSalesItem()), ...body.salesItem, id: 9, variations: (await catalog.getSalesItem()).variations } }));
render(<ProductSetupPage salesItemId={9} />);
await screen.findByLabelText("Variant 1 code");
await userEvent.click(screen.getByRole("switch", { name: "Has sizes, colours or other options" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
await userEvent.type(screen.getByLabelText("Option 1 values"), "M{Enter}L{Enter}");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText(/Variants not saved yet/)).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Discard" }));
await userEvent.type(screen.getByLabelText("Product name"), "!");
await userEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(catalog.saveCatalog).toHaveBeenCalledTimes(2));
expect(catalog.saveCatalog.mock.calls[1][0].sku?.id).toBe(5);
});
it("a saved product loads its own SKU into the section", async () => {
catalog.getSalesItem.mockResolvedValue({
id: 9, code: "YELLOW-002", name: "Yellow", brand: "NIKE", category: "FW", status: "N", productType: "STANDARD",
groupComponentProductIds: [], images: [], yellowLabel: false, allowOversell: false,
variations: [{ id: 1, variant: "DEFAULT", variantName: "DEFAULT", removable: true, pricing: [], components: [{ skuVariationId: 51, skuVariationCode: "YELLOW-002", skuId: 5, skuCode: "YELLOW-002", skuName: "Yellow", variant: "DEFAULT", variantName: "DEFAULT", qty: 1, qtyFoc: 0 }] }],
});
catalog.getSku.mockResolvedValue({
id: 5, code: "YELLOW-002", name: "Yellow", status: "Y", supplierId: null, optionNames: [],
variations: [{ id: 51, code: "YELLOW-002", variant: "DEFAULT", variantName: "DEFAULT", options: [], weight: 0.5, lengthCm: 1, widthCm: 1, heightCm: 1, usedBy: ["YELLOW-002"], onHand: 0, barcodes: [] }],
});
render(<ProductSetupPage salesItemId={9} />);
expect(await screen.findByLabelText("Variant 1 code")).toHaveValue("YELLOW-002");
expect(catalog.getSku).toHaveBeenCalledWith(5);
});
});