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
688 lines
32 KiB
TypeScript
688 lines
32 KiB
TypeScript
import { describe, it, expect } from "vitest";
|
|
import ExcelJS from "exceljs";
|
|
import {
|
|
buildImportTemplate,
|
|
importErrorsXlsx,
|
|
importListsFrom,
|
|
parseImportWorkbook,
|
|
type ImportLists,
|
|
} from "./catalogImport";
|
|
import type { AdminLocationNode, CatalogRow } from "./types";
|
|
|
|
// add-catalogue-bulk-import, simplify-catalogue-import-template, babyboo-56-single-sheet-import: the single-sheet template the admin downloads and the
|
|
// parser that turns a filled copy into the import request. Each test fills the real template, so headers and sheet
|
|
// names stay in step with the parser.
|
|
|
|
const lists: ImportLists = {
|
|
brands: ["BB", "LUMI"],
|
|
categories: ["APPAREL"],
|
|
priceTypes: ["MEMBER", "EVENT", "WHOLESALE"],
|
|
suppliers: [{ id: 3, code: "SUP-A" }],
|
|
country: "2",
|
|
countries: [],
|
|
};
|
|
|
|
type Rows = Record<string, Record<string, unknown>[]>;
|
|
|
|
async function load(data: Uint8Array): Promise<ExcelJS.Workbook> {
|
|
const wb = new ExcelJS.Workbook();
|
|
await wb.xlsx.load(data as unknown as ArrayBuffer);
|
|
return wb;
|
|
}
|
|
|
|
async function filled(rows: Rows, edit: (wb: ExcelJS.Workbook) => void = () => {}): Promise<Uint8Array> {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
edit(wb);
|
|
for (const [sheet, data] of Object.entries(rows)) {
|
|
const ws = wb.getWorksheet(sheet)!;
|
|
const headers = (ws.getRow(1).values as unknown[]).slice(1).map(String);
|
|
data.forEach((record, i) => {
|
|
const rowNumber = typeof record.__row === "number" ? record.__row : i + 2;
|
|
for (const [title, value] of Object.entries(record)) {
|
|
if (title === "__row") continue;
|
|
const col = headers.indexOf(title);
|
|
if (col < 0) throw new Error(`no column ${title} on ${sheet}`);
|
|
ws.getRow(rowNumber).getCell(col + 1).value = value as ExcelJS.CellValue;
|
|
}
|
|
});
|
|
}
|
|
return new Uint8Array(await wb.xlsx.writeBuffer());
|
|
}
|
|
|
|
const HEADERS = ["Product code", "Product name", "Brand", "Category", "Status", "Short description", "MSRP",
|
|
"Allow backorder", "Fulfilment", "Tags", "Product SKU code", "Product SKU name", "Supplier ID", "Options",
|
|
"Option values", "Weight (kg)", "Length (cm)", "Width (cm)", "Height (cm)", "Barcode", "Product type", "Bundle option",
|
|
"Bundle option value", "Qty", "FOC qty", "Pick count", "Includes product"];
|
|
|
|
const row = (extra: Record<string, unknown> = {}) => ({
|
|
"Product code": "TEE-1",
|
|
"Product name": "Tee",
|
|
Brand: "BB",
|
|
Category: "APPAREL",
|
|
Status: "Inactive",
|
|
"Short description": "Soft",
|
|
MSRP: 30,
|
|
"Allow backorder": "Yes",
|
|
Fulfilment: "Pickup only",
|
|
Tags: "cotton, baby ,",
|
|
"Product SKU code": "TEE-1",
|
|
"Product SKU name": "Tee",
|
|
"Supplier ID": "SUP-A",
|
|
Options: "Colour / Size",
|
|
"Option values": "Red / L",
|
|
"Weight (kg)": 0.3,
|
|
"Length (cm)": 20,
|
|
"Width (cm)": 10,
|
|
"Height (cm)": 5,
|
|
"Selling price": 19.9,
|
|
...extra,
|
|
});
|
|
|
|
const plain = (extra: Record<string, unknown> = {}) => ({
|
|
"Product code": "P1", "Product name": "Plain", Brand: "BB", Category: "APPAREL", Status: "Active",
|
|
"Product SKU name": "Plain", "Weight (kg)": 1, "Length (cm)": 30, "Width (cm)": 20, "Height (cm)": 10, ...extra,
|
|
});
|
|
|
|
describe("buildImportTemplate", () => {
|
|
it("has one Products sheet to fill and a hidden Lists sheet", async () => {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
|
|
expect(wb.worksheets.map((w) => w.name)).toEqual(["Products", "Lists"]);
|
|
expect(wb.getWorksheet("Lists")!.state).toBe("hidden");
|
|
const header = (wb.getWorksheet("Products")!.getRow(1).values as unknown[]).slice(1);
|
|
expect(header).toEqual([...HEADERS, "Selling price", "Event price", "WHOLESALE price"]);
|
|
for (const old of ["Item code", "Name", "SKU code", "SKU name", "Supplier code", "Compare-at price"]) {
|
|
expect(header).not.toContain(old);
|
|
}
|
|
});
|
|
|
|
it("explains each column in a note on its header", async () => {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
|
|
const ws = wb.getWorksheet("Products")!;
|
|
const note = (address: string) => {
|
|
const value = ws.getCell(address).note;
|
|
return typeof value === "string" ? value : (value?.texts ?? []).map((t) => t.text).join("");
|
|
};
|
|
ws.getRow(1).eachCell((cell) => expect(note(cell.address)).not.toBe(""));
|
|
expect(note("N1")).toMatch(/Colour \/ Size/);
|
|
const price = (ws.getRow(1).values as unknown[]).indexOf("Selling price");
|
|
expect(note(ws.getRow(1).getCell(price).address)).toMatch(/today/);
|
|
});
|
|
|
|
it("offers active values as dropdowns", async () => {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
|
|
const listValues: string[] = [];
|
|
wb.getWorksheet("Lists")!.eachRow((r) => r.eachCell((cell) => listValues.push(String(cell.value))));
|
|
expect(listValues).toEqual(expect.arrayContaining(["BB", "LUMI", "APPAREL", "SUP-A", "Active", "Yes", "Pickup only"]));
|
|
const ws = wb.getWorksheet("Products")!;
|
|
for (const address of ["C2", "D2", "E2", "H2", "I2", "M2", "C500", "M500"]) {
|
|
const v = ws.getCell(address).dataValidation;
|
|
expect(v?.type).toBe("list");
|
|
expect(String(v?.formulae?.[0])).toContain("Lists!");
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("buildImportTemplate bundle and group columns", () => {
|
|
it("puts the seven bundle/group columns after Barcode and before the price columns, with a note saying blank = Standard", async () => {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
const ws = wb.getWorksheet("Products")!;
|
|
const header = (ws.getRow(1).values as unknown[]).slice(1);
|
|
expect(header.slice(header.indexOf("Barcode"))).toEqual(["Barcode", "Product type", "Bundle option", "Bundle option value",
|
|
"Qty", "FOC qty", "Pick count", "Includes product", "Selling price", "Event price", "WHOLESALE price"]);
|
|
const raw = ws.getRow(1).getCell(header.indexOf("Product type") + 1).note;
|
|
const note = typeof raw === "string" ? raw : (raw?.texts ?? []).map((t) => t.text).join("");
|
|
expect(note).toMatch(/blank/i);
|
|
expect(note).toMatch(/Standard/);
|
|
});
|
|
|
|
it("offers Standard, Bundle and Group as a Product type dropdown", async () => {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
const listValues: string[] = [];
|
|
wb.getWorksheet("Lists")!.eachRow((r) => r.eachCell((cell) => listValues.push(String(cell.value))));
|
|
expect(listValues).toEqual(expect.arrayContaining(["Product type", "Standard", "Bundle", "Group"]));
|
|
const ws = wb.getWorksheet("Products")!;
|
|
const col = (ws.getRow(1).values as unknown[]).indexOf("Product type");
|
|
for (const r of [2, 500]) {
|
|
const v = ws.getCell(r, col).dataValidation;
|
|
expect(v?.type).toBe("list");
|
|
expect(String(v?.formulae?.[0])).toContain("Lists!");
|
|
}
|
|
});
|
|
|
|
it("keeps Bundle option, Bundle option value and Includes product as text", async () => {
|
|
const wb = await load(await buildImportTemplate(lists));
|
|
const ws = wb.getWorksheet("Products")!;
|
|
const headers = (ws.getRow(1).values as unknown[]);
|
|
for (const title of ["Bundle option", "Bundle option value", "Includes product"]) {
|
|
expect(ws.getColumn(headers.indexOf(title)).numFmt).toBe("@");
|
|
}
|
|
});
|
|
});
|
|
|
|
const bundle = (extra: Record<string, unknown> = {}) => ({
|
|
"Product code": "BND", "Product name": "Bundle", Brand: "BB", Category: "APPAREL", Status: "Active",
|
|
"Product type": "Bundle", "Product SKU code": "WIPES", "Selling price": 50, ...extra,
|
|
});
|
|
const group = (extra: Record<string, unknown> = {}) => ({
|
|
"Product code": "GRP", "Product name": "Group", Brand: "BB", Category: "APPAREL", Status: "Active",
|
|
"Product type": "Group", "Pick count": 1, "Includes product": "P1", ...extra,
|
|
});
|
|
const problems = async (rows: Record<string, unknown>[]) => {
|
|
const { errors } = await parseImportWorkbook(await filled({ Products: rows }), lists);
|
|
return errors.map((e) => `${e.row}: ${e.message}`);
|
|
};
|
|
const hasError = async (rows: Record<string, unknown>[], rowNo: number, pattern: RegExp) => {
|
|
const found = (await problems(rows)).filter((m) => m.startsWith(`${rowNo}: `));
|
|
expect(found.join(" | ")).toMatch(pattern);
|
|
};
|
|
|
|
describe("parseImportWorkbook bundle rows", () => {
|
|
it("builds a two-option bundle with components, defaults and prices from the first row", async () => {
|
|
const file = await filled({
|
|
Products: [
|
|
bundle({ "Bundle option": "Pack", "Bundle option value": "Travel Kit", "Option values": "Large", Qty: 2, "FOC qty": 1 }),
|
|
bundle({ "Bundle option": "pack", "Bundle option value": "travel kit", "Product SKU code": "SOAP" }),
|
|
bundle({ "Bundle option": "Pack", "Bundle option value": "Family", "Selling price": 80, "Event price": 70 }),
|
|
],
|
|
});
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toEqual([]);
|
|
expect(request.salesItems).toHaveLength(1);
|
|
expect(request.salesItems[0]).toMatchObject({ code: "BND", productType: "BUNDLE", groupPickCount: null, groupProducts: [] });
|
|
expect(request.salesItems[0].variations).toEqual([
|
|
{
|
|
row: 2, skuCode: null, optionValues: null, option: "Pack", optionValue: "Travel Kit", prices: { MEMBER: 50 },
|
|
components: [
|
|
{ row: 2, skuCode: "WIPES", optionValues: "Large", qty: 2, qtyFoc: 1 },
|
|
{ row: 3, skuCode: "SOAP", optionValues: null, qty: 1, qtyFoc: 0 },
|
|
],
|
|
},
|
|
{
|
|
row: 4, skuCode: null, optionValues: null, option: "Pack", optionValue: "Family", prices: { MEMBER: 80, EVENT: 70 },
|
|
components: [{ row: 4, skuCode: "WIPES", optionValues: null, qty: 1, qtyFoc: 0 }],
|
|
},
|
|
]);
|
|
});
|
|
|
|
it("makes a bundle row with both option cells blank the default option", async () => {
|
|
const { request, errors } = await parseImportWorkbook(await filled({ Products: [bundle()] }), lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.salesItems[0].variations[0]).toMatchObject({ option: null, optionValue: null, skuCode: null });
|
|
});
|
|
|
|
it("adds no SKU row and skips the Options count check on reference-only rows", async () => {
|
|
const { request, errors } = await parseImportWorkbook(
|
|
await filled({ Products: [bundle({ "Option values": "Red / L" })] }), lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toEqual([]);
|
|
expect(request.salesItems[0].variations[0].components[0]).toMatchObject({ skuCode: "WIPES", optionValues: "Red / L" });
|
|
});
|
|
|
|
it("adds the SKU row when a bundle row carries a full SKU definition", async () => {
|
|
const { request, errors } = await parseImportWorkbook(await filled({
|
|
Products: [bundle({
|
|
"Product SKU code": "NEWSKU", "Product SKU name": "New sku", "Supplier ID": "SUP-A", Options: "Colour", "Option values": "Red",
|
|
"Weight (kg)": 1, "Length (cm)": 2, "Width (cm)": 3, "Height (cm)": 4,
|
|
})],
|
|
}), lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toEqual([{
|
|
row: 2, code: "NEWSKU", name: "New sku", supplierId: 3,
|
|
variants: [{ row: 2, variant: "Colour", variantName: "Red", weight: 1, lengthCm: 2, widthCm: 3, heightCm: 4, barcode: null }],
|
|
}]);
|
|
expect(request.salesItems[0].variations[0].components).toEqual([
|
|
{ row: 2, skuCode: "NEWSKU", optionValues: "Red", qty: 1, qtyFoc: 0 },
|
|
]);
|
|
});
|
|
|
|
it("requires Product SKU code", async () => {
|
|
await hasError([bundle({ "Product SKU code": null })], 2, /Product SKU code is required/);
|
|
});
|
|
|
|
it("rejects a bad Qty and a bad FOC qty", async () => {
|
|
await hasError([bundle({ Qty: 0 })], 2, /Qty must be a whole number of 1 or more/);
|
|
await hasError([bundle({ Qty: 1.5 })], 2, /Qty must be a whole number of 1 or more/);
|
|
await hasError([bundle({ "FOC qty": -1 })], 2, /FOC qty must be a whole number of 0 or more/);
|
|
await hasError([bundle({ "FOC qty": "x" })], 2, /FOC qty must be a whole number of 0 or more/);
|
|
});
|
|
|
|
it("requires Bundle option and Bundle option value together", async () => {
|
|
await hasError([bundle({ "Bundle option": "Pack" })], 2, /Bundle option and Bundle option value go together/);
|
|
await hasError([bundle({ "Bundle option value": "Kit" })], 2, /Bundle option and Bundle option value go together/);
|
|
});
|
|
|
|
it("reports a price that differs from the option's first row", async () => {
|
|
await hasError([
|
|
bundle({ "Bundle option": "Pack", "Bundle option value": "Kit" }),
|
|
bundle({ "Bundle option": "Pack", "Bundle option value": "Kit", "Product SKU code": "SOAP", "Selling price": 60 }),
|
|
], 3, /Selling price differs from row 2 of the same option/);
|
|
});
|
|
|
|
it("reports the same SKU variant twice in one option", async () => {
|
|
await hasError([
|
|
bundle({ "Option values": "Red" }),
|
|
bundle({ "Product SKU code": "wipes", "Option values": "RED" }),
|
|
], 3, /repeats the component of row 2/);
|
|
});
|
|
|
|
it("reports detail columns filled on a reference-only row", async () => {
|
|
for (const [col, value] of [["Supplier ID", "SUP-A"], ["Options", "Colour"], ["Weight (kg)", 1], ["Length (cm)", 1],
|
|
["Width (cm)", 1], ["Height (cm)", 1], ["Barcode", "123"]] as const) {
|
|
await hasError([bundle({ [col]: value })], 2, new RegExp(`${col.replace(/[()]/g, "\\$&")} needs Product SKU name on a Bundle row`));
|
|
}
|
|
});
|
|
|
|
it("reports a product type or pick count that differs from the product's first row", async () => {
|
|
await hasError([bundle(), bundle({ "Product type": "Standard" })], 3, /Product type differs from row 2 of the same code/);
|
|
await hasError([bundle({ "Pick count": null }), bundle({ "Product SKU code": "S2", "Pick count": 2 })], 3,
|
|
/Pick count/);
|
|
});
|
|
|
|
it("reports a product type that is not in the list", async () => {
|
|
await hasError([bundle({ "Product type": "Kit" })], 2, /Product type Kit is not in the list/);
|
|
});
|
|
});
|
|
|
|
describe("parseImportWorkbook group rows", () => {
|
|
it("builds a group with a pick count and its included products", async () => {
|
|
const { request, errors } = await parseImportWorkbook(await filled({
|
|
Products: [group({ "Product type": "group" }), group({ "Includes product": "P2", "Product type": "GROUP" })],
|
|
}), lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toEqual([]);
|
|
expect(request.salesItems).toHaveLength(1);
|
|
expect(request.salesItems[0]).toMatchObject({
|
|
row: 2, code: "GRP", productType: "GROUP", groupPickCount: 1,
|
|
groupProducts: [{ row: 2, code: "P1" }, { row: 3, code: "P2" }], variations: [],
|
|
});
|
|
});
|
|
|
|
it("requires Includes product and a whole Pick count of 1 or more", async () => {
|
|
await hasError([group({ "Includes product": null })], 2, /Includes product is required/);
|
|
await hasError([group({ "Pick count": null })], 2, /Pick count must be a whole number of 1 or more/);
|
|
await hasError([group({ "Pick count": 0 })], 2, /Pick count must be a whole number of 1 or more/);
|
|
await hasError([group({ "Pick count": 1.5 })], 2, /Pick count must be a whole number of 1 or more/);
|
|
});
|
|
|
|
it("requires the SKU, bundle and price columns to be blank", async () => {
|
|
for (const [col, value] of [["Product SKU code", "X"], ["Product SKU name", "X"], ["Supplier ID", "SUP-A"], ["Options", "A"],
|
|
["Option values", "A"], ["Weight (kg)", 1], ["Length (cm)", 1], ["Width (cm)", 1], ["Height (cm)", 1], ["Barcode", "1"],
|
|
["Bundle option", "Pack"], ["Bundle option value", "Kit"], ["Qty", 2], ["FOC qty", 1], ["Selling price", 5],
|
|
["Event price", 5]] as const) {
|
|
await hasError([group({ [col]: value })], 2, new RegExp(`${col.replace(/[()]/g, "\\$&")} must be blank on a Group row`));
|
|
}
|
|
});
|
|
|
|
it("allows only a blank or Pickup & delivery fulfilment", async () => {
|
|
expect((await problems([group({ Fulfilment: "Pickup & delivery" })]))).toEqual([]);
|
|
await hasError([group({ Fulfilment: "Pickup only" })], 2, /A group has no fulfilment restriction; leave Fulfilment blank/);
|
|
});
|
|
|
|
it("reports the same Includes product twice", async () => {
|
|
await hasError([group(), group({ "Includes product": "p1" })], 3, /repeats the product of row 2/);
|
|
});
|
|
});
|
|
|
|
describe("parseImportWorkbook standard rows and compatibility", () => {
|
|
it("reports bundle and group columns filled on a standard row", async () => {
|
|
for (const [col, value] of [["Bundle option", "Pack"], ["Bundle option value", "Kit"], ["Qty", 2], ["FOC qty", 1],
|
|
["Pick count", 1], ["Includes product", "P2"]] as const) {
|
|
await hasError([plain({ [col]: value })], 2, new RegExp(`${col} is only for Bundle or Group rows`));
|
|
await hasError([plain({ "Product type": "Standard", [col]: value })], 2, new RegExp(`${col} is only for Bundle or Group rows`));
|
|
}
|
|
});
|
|
|
|
it("parses a file with none of the new columns to today's request plus the default new fields", async () => {
|
|
const file = await filled({ Products: [plain({ "Selling price": 9 })] }, (wb) => {
|
|
const ws = wb.getWorksheet("Products")!;
|
|
const headers = ws.getRow(1).values as unknown[];
|
|
for (let i = headers.length - 1; i >= 1; i--) {
|
|
if (["Product type", "Bundle option", "Bundle option value", "Qty", "FOC qty", "Pick count", "Includes product"]
|
|
.includes(String(headers[i]))) ws.spliceColumns(i, 1);
|
|
}
|
|
});
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.salesItems).toEqual([{
|
|
row: 2, code: "P1", name: "Plain", brand: "BB", category: "APPAREL", status: "Y", shortDesc: null, compareAtPrice: null,
|
|
allowOversell: false, fulfilment: "ANY", tags: [], productType: "STANDARD", groupPickCount: null, groupProducts: [],
|
|
variations: [{ row: 2, skuCode: "P1", optionValues: null, option: null, optionValue: null, components: [], prices: { MEMBER: 9 } }],
|
|
}]);
|
|
});
|
|
|
|
it("gives a standard row the default new fields", async () => {
|
|
const { request } = await parseImportWorkbook(await filled({ Products: [plain({ "Product type": "standard" })] }), lists);
|
|
|
|
expect(request.salesItems[0]).toMatchObject({ productType: "STANDARD", groupPickCount: null, groupProducts: [] });
|
|
expect(request.salesItems[0].variations[0]).toMatchObject({ option: null, optionValue: null, components: [] });
|
|
});
|
|
});
|
|
|
|
describe("parseImportWorkbook", () => {
|
|
it("groups rows by code and maps every column", async () => {
|
|
const file = await filled({
|
|
Products: [
|
|
row({ Barcode: 9555000001, "Event price": 15 }),
|
|
row({ "Option values": "Blue/M", "Weight (kg)": "0.25", "Selling price": null }),
|
|
{ ...plain({ Brand: "BB", "Product code": "PROMO", "Product name": "Promo", "Product SKU code": "P2", "WHOLESALE price": 0 }) },
|
|
],
|
|
});
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.country).toBe("2");
|
|
expect(request.skus).toEqual([
|
|
{
|
|
row: 2, code: "TEE-1", name: "Tee", supplierId: 3,
|
|
variants: [
|
|
{ row: 2, variant: "Colour / Size", variantName: "Red / L", weight: 0.3, lengthCm: 20, widthCm: 10, heightCm: 5, barcode: "9555000001" },
|
|
{ row: 3, variant: "Colour / Size", variantName: "Blue / M", weight: 0.25, lengthCm: 20, widthCm: 10, heightCm: 5, barcode: null },
|
|
],
|
|
},
|
|
{
|
|
row: 4, code: "P2", name: "Plain", supplierId: null,
|
|
variants: [{ row: 4, variant: null, variantName: null, weight: 1, lengthCm: 30, widthCm: 20, heightCm: 10, barcode: null }],
|
|
},
|
|
]);
|
|
expect(request.salesItems).toEqual([
|
|
{
|
|
row: 2, code: "TEE-1", name: "Tee", brand: "BB", category: "APPAREL", status: "N", shortDesc: "Soft",
|
|
compareAtPrice: 30, allowOversell: true, fulfilment: "PICKUP_ONLY", tags: ["cotton", "baby"],
|
|
productType: "STANDARD", groupPickCount: null, groupProducts: [],
|
|
variations: [
|
|
{ row: 2, skuCode: "TEE-1", optionValues: "Red / L", prices: { MEMBER: 19.9, EVENT: 15 }, option: null, optionValue: null, components: [], },
|
|
{ row: 3, skuCode: "TEE-1", optionValues: "Blue / M", prices: {}, option: null, optionValue: null, components: [], },
|
|
],
|
|
},
|
|
{
|
|
row: 4, code: "PROMO", name: "Promo", brand: "BB", category: "APPAREL", status: "Y", shortDesc: null,
|
|
compareAtPrice: null, allowOversell: false, fulfilment: "ANY", tags: [],
|
|
productType: "STANDARD", groupPickCount: null, groupProducts: [],
|
|
variations: [{ row: 4, skuCode: "P2", optionValues: null, prices: { WHOLESALE: 0 }, option: null, optionValue: null, components: [], }],
|
|
},
|
|
]);
|
|
});
|
|
|
|
it("reads a simple product row with a blank Product SKU code as its own default SKU", async () => {
|
|
const file = await filled({ Products: [plain()] });
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toEqual([
|
|
{
|
|
row: 2, code: "P1", name: "Plain", supplierId: null,
|
|
variants: [{ row: 2, variant: null, variantName: null, weight: 1, lengthCm: 30, widthCm: 20, heightCm: 10, barcode: null }],
|
|
},
|
|
]);
|
|
expect(request.salesItems).toHaveLength(1);
|
|
expect(request.salesItems[0]).toMatchObject({ code: "P1" });
|
|
expect(request.salesItems[0].variations).toEqual([{ row: 2, skuCode: "P1", optionValues: null, prices: {}, option: null, optionValue: null, components: [], }]);
|
|
});
|
|
|
|
it("reads a product with two colour rows as one SKU with two variants and one Sales Item with two variations", async () => {
|
|
const file = await filled({
|
|
Products: [
|
|
row({ Options: "Colour", "Option values": "Red" }),
|
|
row({ Options: "Colour", "Option values": "Blue" }),
|
|
],
|
|
});
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toHaveLength(1);
|
|
expect(request.skus[0].variants.map((v) => v.variantName)).toEqual(["Red", "Blue"]);
|
|
expect(request.salesItems).toHaveLength(1);
|
|
expect(request.salesItems[0].variations.map((v) => [v.skuCode, v.optionValues])).toEqual([["TEE-1", "Red"], ["TEE-1", "Blue"]]);
|
|
});
|
|
|
|
it("lists a SKU variant shared by two products once", async () => {
|
|
const file = await filled({
|
|
Products: [row(), row({ "Product code": "TEE-2", "Product name": "Tee two" })],
|
|
});
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus).toHaveLength(1);
|
|
expect(request.skus[0].variants).toHaveLength(1);
|
|
expect(request.salesItems.map((s) => s.code)).toEqual(["TEE-1", "TEE-2"]);
|
|
expect(request.salesItems.map((s) => s.variations[0].skuCode)).toEqual(["TEE-1", "TEE-1"]);
|
|
});
|
|
|
|
it("reports a product column that differs from the product's first row", async () => {
|
|
const file = await filled({ Products: [row(), row({ "Option values": "Blue / M", Brand: "LUMI" })] });
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([expect.objectContaining({ sheet: "Products", row: 3, message: expect.stringMatching(/Brand/) })]);
|
|
});
|
|
|
|
it("reports a SKU variant whose measurements differ between rows", async () => {
|
|
const file = await filled({ Products: [row(), row({ "Product code": "TEE-2", "Weight (kg)": 0.6 })].map((r, i) => (i === 0 ? { ...r, "Weight (kg)": 0.5 } : r)) });
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([expect.objectContaining({ sheet: "Products", row: 3, message: expect.stringMatching(/Weight \(kg\)/) })]);
|
|
});
|
|
|
|
it("matches list values regardless of case and stores the list's spelling", async () => {
|
|
const file = await filled({ Products: [row({ Brand: "lumi", Category: "apparel", Status: "active", "Allow backorder": "no", Fulfilment: "delivery only" })] });
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.salesItems[0]).toMatchObject({ brand: "LUMI", category: "APPAREL", status: "Y", allowOversell: false, fulfilment: "DELIVERY_ONLY" });
|
|
});
|
|
|
|
it("reports each bad cell with its sheet and row", async () => {
|
|
const file = await filled({
|
|
Products: [
|
|
row({ Brand: "UNKNOWN", Status: "Live", Fulfilment: "Teleport", "Selling price": -1 }),
|
|
row({ "Product SKU name": "Other name", "Option values": "Blue", "Weight (kg)": "heavy", "Supplier ID": "NOPE" }),
|
|
],
|
|
});
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
const at = (r: number) => errors.filter((e) => e.sheet === "Products" && e.row === r).map((e) => e.message).join(" | ");
|
|
expect(at(2)).toMatch(/Brand/);
|
|
expect(at(2)).toMatch(/Status/);
|
|
expect(at(2)).toMatch(/Fulfilment/);
|
|
expect(at(2)).toMatch(/Selling price/);
|
|
expect(at(3)).toMatch(/Product SKU name/);
|
|
expect(at(3)).toMatch(/Weight/);
|
|
expect(at(3)).toMatch(/Supplier/);
|
|
expect(at(3)).toMatch(/Option values/);
|
|
});
|
|
|
|
it("requires the mandatory cells", async () => {
|
|
const file = await filled({ Products: [{ "Product code": "S9" }] });
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
const messages = errors.filter((e) => e.sheet === "Products" && e.row === 2).map((e) => e.message).join(" | ");
|
|
for (const title of ["Product name", "Brand", "Category", "Status", "Product SKU name", "Weight", "Length", "Width", "Height"]) {
|
|
expect(messages).toMatch(title);
|
|
}
|
|
});
|
|
|
|
it("allows at most three options", async () => {
|
|
const file = await filled({ Products: [row({ Options: "A / B / C / D", "Option values": "1 / 2 / 3 / 4" })] });
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([expect.objectContaining({ sheet: "Products", row: 2, message: expect.stringMatching(/three options/) })]);
|
|
});
|
|
|
|
it("treats codes that differ only in case as one code", async () => {
|
|
const file = await filled({ Products: [row(), row({ "Product code": "tee-1", "Product SKU code": "tee-1", "Option values": "Blue / M" })] });
|
|
|
|
const { request, errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.skus.map((s) => [s.code, s.variants.length])).toEqual([["TEE-1", 2]]);
|
|
expect(request.salesItems.map((s) => [s.code, s.variations.length])).toEqual([["TEE-1", 2]]);
|
|
});
|
|
|
|
it("reports a price column for a price type that is not active", async () => {
|
|
const file = await filled({}, (wb) => {
|
|
const ws = wb.getWorksheet("Products")!;
|
|
ws.getRow(1).getCell(ws.columnCount + 1).value = "RETIRED price";
|
|
});
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([expect.objectContaining({ sheet: "Products", row: 1, message: expect.stringMatching(/RETIRED/) })]);
|
|
});
|
|
|
|
it("reports an Excel error cell instead of reading it as blank", async () => {
|
|
// Refuter L2: blank clears a field, so a #N/A must not pass for blank.
|
|
const file = await filled({ Products: [row({ "Short description": { formula: "NA()", result: { error: "#N/A" } } })] });
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors).toEqual([expect.objectContaining({ sheet: "Products", row: 2, message: expect.stringMatching(/Short description.*#N\/A/) })]);
|
|
});
|
|
|
|
it("refuses a sheet over 2,000 rows", async () => {
|
|
const rows = Array.from({ length: 2001 }, (_, i) => row({ "Option values": `V${i}` }));
|
|
const file = await filled({ Products: rows });
|
|
|
|
const { errors } = await parseImportWorkbook(file, lists);
|
|
|
|
expect(errors.some((e) => e.sheet === "Products" && /2,000/.test(e.message))).toBe(true);
|
|
});
|
|
|
|
it("refuses the old two-tab template", async () => {
|
|
const wb = new ExcelJS.Workbook();
|
|
for (const name of ["SKU", "Sales Item", "Lists"]) wb.addWorksheet(name);
|
|
|
|
const { errors } = await parseImportWorkbook(new Uint8Array(await wb.xlsx.writeBuffer()), lists);
|
|
|
|
expect(errors).toEqual([{ sheet: "File", row: 0, message: "This is the old import template. Download the new one and copy your rows into it." }]);
|
|
});
|
|
|
|
it("reports a file that is not a workbook", async () => {
|
|
const { errors } = await parseImportWorkbook(new TextEncoder().encode("not a workbook"), lists);
|
|
|
|
expect(errors).toHaveLength(1);
|
|
expect(errors[0].message).toMatch(/xlsx/i);
|
|
});
|
|
});
|
|
|
|
describe("importErrorsXlsx", () => {
|
|
it("lists sheet, row and message", async () => {
|
|
const wb = await load(await importErrorsXlsx([{ sheet: "SKU", row: 5, message: "weight: must be greater than 0" }]));
|
|
|
|
const ws = wb.worksheets[0];
|
|
expect((ws.getRow(1).values as unknown[]).slice(1)).toEqual(["Sheet", "Row", "Message"]);
|
|
expect((ws.getRow(2).values as unknown[]).slice(1)).toEqual(["SKU", 5, "weight: must be greater than 0"]);
|
|
});
|
|
});
|
|
|
|
describe("importListsFrom", () => {
|
|
it("takes active codes, price types with MEMBER first, and the Malaysia country id", () => {
|
|
const row = (code: string, status = "Y") => ({ code, status }) as CatalogRow;
|
|
const loc = (id: number, code: string, type: AdminLocationNode["type"], status: "Y" | "N") =>
|
|
({ id, code, name: code, type, status, parent: null }) as AdminLocationNode;
|
|
|
|
const result = importListsFrom(
|
|
{
|
|
brands: [row("BB"), row("OLD", "N")],
|
|
categories: [row("APPAREL")],
|
|
priceTypes: [row("EVENT"), row("MEMBER"), row("ZZ_QA_TEST", "N")],
|
|
suppliers: [{ ...row("SUP-A"), id: "3" }],
|
|
},
|
|
[loc(1, "GLOBAL", "G", "Y"), loc(2, "MY", "C", "Y"), loc(3, "SG", "C", "Y")],
|
|
);
|
|
|
|
expect(result).toEqual({
|
|
brands: ["BB"],
|
|
categories: ["APPAREL"],
|
|
priceTypes: ["MEMBER", "EVENT"],
|
|
suppliers: [{ id: 3, code: "SUP-A" }],
|
|
country: "2",
|
|
countries: [],
|
|
});
|
|
});
|
|
|
|
it("carries the sellable country codes it is given", () => {
|
|
const result = importListsFrom({ brands: [], categories: [], priceTypes: [], suppliers: [] }, [], ["MY", "SG"]);
|
|
|
|
expect(result.countries).toEqual(["MY", "SG"]);
|
|
});
|
|
});
|
|
|
|
// SG-ready phase 3 Task 5: the Country column exists only when more than one country is sellable.
|
|
describe("catalogue import country column", () => {
|
|
const two: ImportLists = { ...lists, countries: ["MY", "SG"] };
|
|
const one: ImportLists = { ...lists, countries: ["MY"] };
|
|
const headerOf = async (l: ImportLists) =>
|
|
((await load(await buildImportTemplate(l))).getWorksheet("Products")!.getRow(1).values as unknown[]).slice(1).map(String);
|
|
|
|
async function fileWith(l: ImportLists, country?: string): Promise<Uint8Array> {
|
|
const wb = await load(await buildImportTemplate(l));
|
|
const ws = wb.getWorksheet("Products")!;
|
|
const headers = (ws.getRow(1).values as unknown[]).slice(1).map(String);
|
|
for (const [title, value] of Object.entries({ ...plain({ "Selling price": 9 }), ...(country === undefined ? {} : { Country: country }) })) {
|
|
const col = headers.indexOf(title);
|
|
if (col >= 0) ws.getRow(2).getCell(col + 1).value = value as ExcelJS.CellValue;
|
|
}
|
|
return new Uint8Array(await wb.xlsx.writeBuffer());
|
|
}
|
|
|
|
it("adds no Country header when one country or none is sellable", async () => {
|
|
expect(await headerOf(one)).not.toContain("Country");
|
|
expect(await headerOf({ ...lists, countries: [] })).not.toContain("Country");
|
|
});
|
|
|
|
it("adds a Country header with a Lists dropdown of the codes when several are sellable", async () => {
|
|
const wb = await load(await buildImportTemplate(two));
|
|
const headers = (wb.getWorksheet("Products")!.getRow(1).values as unknown[]).slice(1).map(String);
|
|
expect(headers).toContain("Country");
|
|
const listValues: string[] = [];
|
|
wb.getWorksheet("Lists")!.eachRow((r) => r.eachCell((cell) => listValues.push(String(cell.value))));
|
|
expect(listValues).toEqual(expect.arrayContaining(["Country", "MY", "SG"]));
|
|
const v = wb.getWorksheet("Products")!.getCell(2, headers.indexOf("Country") + 1).dataValidation;
|
|
expect(v?.type).toBe("list");
|
|
expect(String(v?.formulae?.[0])).toContain("Lists!");
|
|
});
|
|
|
|
it("sends no country on a variation row when the file has no Country column", async () => {
|
|
const { request, errors } = await parseImportWorkbook(await fileWith(one), one);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.country).toBe("2");
|
|
expect(request.salesItems[0].variations[0].country ?? null).toBeNull();
|
|
});
|
|
|
|
it("sends the upper-cased code from a Country cell on that row's variation", async () => {
|
|
const { request, errors } = await parseImportWorkbook(await fileWith(two, "sg"), two);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.salesItems[0].variations[0].country).toBe("SG");
|
|
});
|
|
|
|
it("sends no country when the Country cell is blank", async () => {
|
|
const { request, errors } = await parseImportWorkbook(await fileWith(two), two);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(request.salesItems[0].variations[0].country ?? null).toBeNull();
|
|
});
|
|
});
|