Files
co-lite/solvway-admin-portal/app/components/catalog-setup/SkuEditor.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

285 lines
12 KiB
TypeScript

import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
const stock = vi.hoisted(() => ({ getStockOnHand: vi.fn() }));
vi.mock("@/app/lib/services/adminStock", () => stock);
vi.mock("@/app/lib/services/adminCatalogSetup", () => ({ searchSkuVariations: vi.fn().mockResolvedValue([]) }));
vi.mock("@/app/components/products/QianyiSkuPicker", () => ({
QianyiSkuPicker: ({ onChange }: { onChange: (qySku?: string, option?: Record<string, unknown>) => void }) => (
<>
<button
type="button"
onClick={() => onChange("QY-2", { sku: "QY-2", title: "Box", weightKg: 0.5, lengthCm: 20, widthCm: 10, heightCm: 5, color: null, size: null, linkedTo: null })}
>
pick boxed QianYi
</button>
<button type="button" onClick={() => onChange(undefined)}>
clear QianYi
</button>
<button
type="button"
onClick={() => onChange("QY-1", { sku: "QY-1", title: "Black bra", weightKg: 0.5, color: null, size: null, linkedTo: null })}
>
pick QianYi
</button>
</>
),
}));
import { SkuEditor, type SkuEditorProps } from "./SkuEditor";
import { emptySku, emptySkuVariant, type SkuDraft } from "@/app/lib/catalogSetup";
function props(overrides: Partial<SkuEditorProps> = {}): SkuEditorProps {
return {
sku: emptySku(),
onChange: vi.fn(),
onUploadImage: vi.fn().mockResolvedValue("https://cdn/v.jpg"),
errors: {},
saving: false,
...overrides,
};
}
function Harness({ initial, onChange }: { initial: SkuDraft; onChange: (s: SkuDraft) => void }) {
const [sku, setSku] = useState(initial);
return (
<SkuEditor
{...props()}
sku={sku}
onChange={(next) => {
setSku(next);
onChange(next);
}}
/>
);
}
const saved: SkuDraft = {
id: 16,
code: "BA-002",
name: "Romper",
supplierId: null,
status: "Y",
optionNames: ["Colour"],
optionValues: ["Black"],
variants: [{ ...emptySkuVariant(), id: 17, code: "BA-002-BLACK", variant: "Colour", variantName: "Black", options: ["Black"], weight: "0.3", usedBy: ["P-002"], onHand: 5 }],
};
beforeEach(() => {
stock.getStockOnHand.mockReset();
stock.getStockOnHand.mockResolvedValue({ content: [{ stockOnHand: 3 }, { stockOnHand: 2 }] });
});
describe("SkuEditor", () => {
it("edits a new SKU's code", () => {
const onChange = vi.fn();
render(<SkuEditor {...props({ onChange })} />);
fireEvent.change(screen.getByLabelText("SKU code"), { target: { value: "BA-010" } });
expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ code: "BA-010" }));
});
it("opens a new SKU as one flat form: no variant name, value or code to fill", () => {
render(<SkuEditor {...props()} />);
expect(screen.getByRole("switch", { name: "This SKU has variants" })).not.toBeChecked();
expect(screen.getByLabelText("Variant 1 weight")).toBeInTheDocument();
expect(screen.getByLabelText("Variant 1 length (cm)")).toBeInTheDocument();
expect(screen.queryByLabelText("Variant 1 code")).not.toBeInTheDocument();
expect(screen.queryByLabelText("Option 1 name")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Remove variant 1" })).not.toBeInTheDocument();
});
it("generates the variant rows from the options, with suggested codes", async () => {
const onChange = vi.fn();
render(<Harness initial={{ ...emptySku(), code: "TEE-1" }} onChange={onChange} />);
await userEvent.click(screen.getByRole("switch", { name: "This SKU has variants" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Colour");
await userEvent.type(screen.getByLabelText("Option 1 values"), "Red, Blue");
await userEvent.click(screen.getByRole("button", { name: /Add option/ }));
await userEvent.type(screen.getByLabelText("Option 2 name"), "Size");
await userEvent.type(screen.getByLabelText("Option 2 values"), "S, M");
await userEvent.click(screen.getByRole("button", { name: "Generate variants" }));
expect(screen.getAllByTestId("sku-variant-row")).toHaveLength(4);
expect(screen.getByLabelText("Variant 1 Colour")).toHaveValue("Red");
expect(screen.getByLabelText("Variant 4 Size")).toHaveValue("M");
expect(screen.getByLabelText("Variant 4 code")).toHaveValue("TEE-1-BLUE-M");
const last = onChange.mock.calls.at(-1)![0] as SkuDraft;
expect(last.variants[3]).toMatchObject({ variant: "Colour / Size", variantName: "Blue / M" });
});
it("gives the first row its own code when the option is named before generating", async () => {
render(<Harness initial={{ ...emptySku(), code: "TEE-1" }} onChange={vi.fn()} />);
await userEvent.click(screen.getByRole("switch", { name: "This SKU has variants" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Colour");
await userEvent.type(screen.getByLabelText("Option 1 values"), "Red, Blue");
await userEvent.click(screen.getByRole("button", { name: "Generate variants" }));
expect(screen.getByLabelText("Variant 1 code")).toHaveValue("TEE-1-RED");
expect(screen.getByLabelText("Variant 2 code")).toHaveValue("TEE-1-BLUE");
});
it("keeps the suggested code in step with value edits until the admin types their own", async () => {
render(<Harness initial={{ ...emptySku(), code: "BA-010" }} onChange={vi.fn()} />);
await userEvent.click(screen.getByRole("switch", { name: "This SKU has variants" }));
await userEvent.type(screen.getByLabelText("Option 1 name"), "Size");
const code = screen.getByLabelText("Variant 1 code");
await userEvent.type(screen.getByLabelText("Variant 1 Size"), "S");
expect(code).toHaveValue("BA-010-S");
await userEvent.type(screen.getByLabelText("Variant 1 Size"), "M");
expect(code).toHaveValue("BA-010-SM");
fireEvent.change(screen.getByLabelText("SKU code"), { target: { value: "BA-011" } });
expect(code).toHaveValue("BA-011-SM");
fireEvent.change(code, { target: { value: "MY-OWN" } });
await userEvent.type(screen.getByLabelText("Variant 1 Size"), "L");
expect(code).toHaveValue("MY-OWN");
});
it("removes a variant row, and turns variants off only with one row left", async () => {
render(
<Harness
initial={{ ...emptySku(), code: "TEE-1", optionNames: ["Size"], optionValues: ["S, M"], variants: [{ ...emptySkuVariant(), options: [""] }] }}
onChange={vi.fn()}
/>,
);
await userEvent.click(screen.getByRole("button", { name: "Generate variants" }));
expect(screen.getAllByTestId("sku-variant-row")).toHaveLength(2);
expect(screen.getByRole("switch", { name: "This SKU has variants" })).toBeDisabled();
expect(screen.getByText("Remove variants until one is left to turn this off.")).toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Remove variant 2" }));
await userEvent.click(screen.getByRole("switch", { name: "This SKU has variants" }));
expect(screen.getByRole("switch", { name: "This SKU has variants" })).not.toBeChecked();
expect(screen.queryByLabelText("Variant 1 code")).not.toBeInTheDocument();
});
it("shows option errors at their field paths", () => {
render(
<SkuEditor
{...props({
sku: saved,
errors: { "sku.optionNames[0]": "Option name is repeated", "sku.variations[0].options": "Every option needs a value" },
})}
/>,
);
expect(screen.getByText("Option name is repeated")).toBeInTheDocument();
expect(screen.getByText("Every option needs a value")).toBeInTheDocument();
});
it("shows a saved variant's code read-only, where it is used and its on-hand", async () => {
render(<SkuEditor {...props({ sku: saved })} />);
expect(screen.getByLabelText("Variant 1 code")).toHaveAttribute("readonly");
expect(screen.getByText("Used by P-002")).toBeInTheDocument();
expect(screen.getByTestId("variant-on-hand")).toHaveTextContent("5");
// On-hand comes with the SKU view: no stock-report call per variant.
expect(stock.getStockOnHand).not.toHaveBeenCalled();
});
it("shows no on-hand for an unsaved variant", () => {
render(<SkuEditor {...props()} />);
expect(screen.getByTestId("variant-on-hand")).toHaveTextContent("—");
});
it("shows errors at their field paths", () => {
render(
<SkuEditor
{...props({ errors: { "sku.code": "SKU code already exists: BA-010", "sku.variations[0].weight": "Weight must be greater than 0" } })}
/>,
);
expect(screen.getByText("SKU code already exists: BA-010")).toBeInTheDocument();
expect(screen.getByText("Weight must be greater than 0")).toBeInTheDocument();
});
it("marks a QianYi pick as touched", async () => {
const onChange = vi.fn();
render(<SkuEditor {...props({ sku: saved, onChange })} />);
await userEvent.click(screen.getByRole("button", { name: "pick QianYi" }));
expect(onChange).toHaveBeenLastCalledWith(
expect.objectContaining({
variants: [expect.objectContaining({ qySku: "QY-1", qyTitle: "Black bra", qyTouched: true })],
}),
);
});
it("prefills a new SKU from the picked QianYi SKU, its code included, and says so", async () => {
render(<Harness initial={emptySku()} onChange={vi.fn()} />);
await userEvent.click(screen.getByRole("button", { name: "pick QianYi" }));
expect(screen.getByLabelText("SKU code")).toHaveValue("QY-1");
expect(screen.getByLabelText("Variant 1 weight")).toHaveValue(0.5);
expect(screen.getByText("Filled from QianYi: code, weight. Check before saving.")).toBeInTheDocument();
});
it("names prefilled dimensions length, width, height in the note", async () => {
render(<Harness initial={emptySku()} onChange={vi.fn()} />);
await userEvent.click(screen.getByRole("button", { name: "pick boxed QianYi" }));
expect(screen.getByText("Filled from QianYi: code, weight, length, width, height. Check before saving.")).toBeInTheDocument();
});
it("keeps the QianYi note after the link is cleared, since the filled values stay", async () => {
render(<Harness initial={emptySku()} onChange={vi.fn()} />);
await userEvent.click(screen.getByRole("button", { name: "pick QianYi" }));
await userEvent.click(screen.getByRole("button", { name: "clear QianYi" }));
expect(screen.getByLabelText("SKU code")).toHaveValue("QY-1");
expect(screen.getByText("Filled from QianYi: code, weight. Check before saving.")).toBeInTheDocument();
});
});
describe("SkuEditor variant dimensions", () => {
it("shows length, width and height inputs per variant and patches them as typed", async () => {
const onChange = vi.fn();
render(<Harness initial={{ ...emptySku(), variants: [emptySkuVariant()] }} onChange={onChange} />);
await userEvent.type(screen.getByLabelText("Variant 1 length (cm)"), "20");
await userEvent.type(screen.getByLabelText("Variant 1 width (cm)"), "10");
await userEvent.type(screen.getByLabelText("Variant 1 height (cm)"), "5");
const last = onChange.mock.calls.at(-1)![0] as SkuDraft;
expect(last.variants[0]).toMatchObject({ lengthCm: "20", widthCm: "10", heightCm: "5" });
});
});
describe("SkuEditor — missing shipping dimensions (add-shipping-rates)", () => {
const NOTE = "Missing shipping dimensions — this variant can't be delivered.";
it("warns when a variant has no weight or size", () => {
render(<SkuEditor {...props()} />);
expect(screen.getByText(NOTE)).toBeInTheDocument();
});
it("does not warn when weight, length, width and height are all filled", () => {
const sku = emptySku();
sku.variants = [{ ...sku.variants[0], weight: "0.5", lengthCm: "20", widthCm: "10", heightCm: "5" }];
render(<SkuEditor {...props({ sku })} />);
expect(screen.queryByText(NOTE)).not.toBeInTheDocument();
});
it("warns when a dimension is 0, which the server refuses", () => {
const sku = emptySku();
sku.variants = [{ ...sku.variants[0], weight: "0.5", lengthCm: "0", widthCm: "10", heightCm: "5" }];
render(<SkuEditor {...props({ sku })} />);
expect(screen.getByText(NOTE)).toBeInTheDocument();
});
});