Files
co-lite/solvway-admin-portal/app/lib/catalogImport.ts
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

525 lines
27 KiB
TypeScript

import type ExcelJS from "exceljs";
import { toXlsx } from "./xlsx";
import { MAX_OPTIONS, OPTION_SEPARATOR } from "./catalogSetup";
import { defaultCountryId, quickTypes } from "./productPage";
import type { AdminLocationNode, ProductOptions } from "./types";
// Catalogue bulk import (add-catalogue-bulk-import, simplify-catalogue-import-template): the single-sheet template the
// admin downloads, and the parser that turns a filled copy into the request for POST /api/products/import/{validate,
// commit}. The parser checks the sheet shape, required cells, Lists values and numbers; the server matches stored
// records, generates variant codes, links each variation to one unit of its SKU variant and applies the Product Setup
// rules. Sheet names, headers and notes are the file's format, read back by this parser, so they stay in English.
export interface ImportLists {
brands: string[];
categories: string[];
/** Active price types, MEMBER first: one price column each. */
priceTypes: string[];
suppliers: { id: number; code: string }[];
/** The Malaysia country node id stamped on new price rows ("" when Locations has none). */
country: string;
/** Sellable country codes; the Country column exists only when more than one. */
countries: string[];
}
export interface ImportRowError { sheet: string; row: number; message: string }
export interface ImportSkuVariant {
row: number; variant: string | null; variantName: string | null;
weight: number | null; lengthCm: number | null; widthCm: number | null; heightCm: number | null; barcode: string | null;
}
export interface ImportSku { row: number; code: string; name: string | null; supplierId: number | null; variants: ImportSkuVariant[] }
export type ImportFulfilment = "ANY" | "PICKUP_ONLY" | "DELIVERY_ONLY";
export interface ImportComponent { row: number; skuCode: string; optionValues: string | null; qty: number; qtyFoc: number }
export interface ImportGroupProduct { row: number; code: string }
export type ImportProductType = "STANDARD" | "BUNDLE" | "GROUP";
export interface ImportVariation {
row: number; skuCode: string | null; optionValues: string | null; option: string | null; optionValue: string | null;
components: ImportComponent[]; prices: Record<string, number>;
/** ISO code of the row's Country cell; absent or null means the server default. */
country?: string | null;
}
export interface ImportSalesItem {
row: number; code: string; name: string | null; brand: string | null; category: string | null; status: string | null;
shortDesc: string | null; compareAtPrice: number | null; allowOversell: boolean; fulfilment: ImportFulfilment;
tags: string[]; productType: ImportProductType; groupPickCount: number | null; groupProducts: ImportGroupProduct[];
variations: ImportVariation[];
}
export interface CatalogImportRequest {
country: string | null;
skus: ImportSku[];
salesItems: ImportSalesItem[];
}
export interface CatalogImportResult {
committed: boolean; skusCreated: number; skusUpdated: number; itemsCreated: number; itemsUpdated: number;
itemsPriced: number; errors: ImportRowError[];
}
export const MAX_IMPORT_ROWS = 2000;
const PRODUCTS = "Products";
const FULFILMENT: [string, ImportFulfilment][] = [["Pickup & delivery", "ANY"], ["Pickup only", "PICKUP_ONLY"], ["Delivery only", "DELIVERY_ONLY"]];
/** The header of a price type's column, worded as on the product page. */
export function priceColumn(type: string): string {
return type === "MEMBER" ? "Selling price" : type === "EVENT" ? "Event price" : `${type} price`;
}
const PRICE_NOTE = "Price in RM from today. A changed price replaces the current one from today; blank keeps the stored "
+ "price. Later or regional prices are set on the product page.";
/** Column title -> the note on its header cell, in column order. One row per product option carrying its SKU variant. */
const PRODUCT_COLUMNS: Record<string, string> = {
"Product code": "Required. One row per product option: repeat the product columns (Product name to Tags) on every row of the same Product code. An existing code updates that product.",
"Product name": "Required.",
Brand: "Required. Pick from the list.",
Category: "Required. Pick from the list.",
Status: "Required. A new product has no image yet, so create it Inactive, add images in Products, then activate it.",
"Short description": "Optional; blank clears it.",
MSRP: "Optional; blank clears it.",
"Allow backorder": "Yes or No; blank means No.",
Fulfilment: "Pickup & delivery (blank), Pickup only or Delivery only.",
Tags: "Optional, separated by commas; blank clears them.",
"Product SKU code": "Blank means the Product code. Each row is one unit of that SKU's variant; repeat the Product SKU code, Product SKU name, Supplier ID and Options on every row of the same SKU. An existing code updates that SKU.",
"Product SKU name": "Required.",
"Supplier ID": "Optional. Pick from the list; blank clears it.",
Options: "Option names, up to three, joined by \" / \", e.g. Colour / Size. Blank for a SKU with no variants. Every row of a SKU uses the same options.",
"Option values": "This row's variant values in the same order, e.g. Red / L. The variant code is made from the SKU code and these values (TEE-1-RED-L); an existing variant with the same values is updated. Blank for a SKU with no variants.",
"Weight (kg)": "Required, greater than 0. Rows of the same variant must match.",
"Length (cm)": "Required, greater than 0. Rows of the same variant must match.",
"Width (cm)": "Required, greater than 0. Rows of the same variant must match.",
"Height (cm)": "Required, greater than 0. Rows of the same variant must match.",
Barcode: "Optional. Added to the variant; existing barcodes are kept. Rows of the same variant must match.",
"Product type": "Standard, Bundle or Group. Blank means Standard. Every row of the same Product code uses the same type.",
"Bundle option": "Bundle rows only: the name of the choice the buyer makes, e.g. Pack. Blank with Bundle option value blank is the single default option. Rows of the same Bundle option and value are one option of the bundle.",
"Bundle option value": "Bundle rows only: this option's value, e.g. Travel Kit. Fill it together with Bundle option.",
Qty: "Bundle rows only: units of this SKU variant in the bundle; a whole number of 1 or more, blank means 1.",
"FOC qty": "Bundle rows only: free-of-charge units on top of Qty; a whole number of 0 or more, blank means 0.",
"Pick count": "Group rows only, required: how many of the included products the buyer picks; a whole number of 1 or more. Same on every row of the group.",
"Includes product": "Group rows only, required: the code of a product in this group, one per row. It may be in this file or already stored.",
};
const PRODUCT_TYPES = ["Standard", "Bundle", "Group"];
const STANDARD_BLANK = ["Bundle option", "Bundle option value", "Qty", "FOC qty", "Pick count", "Includes product"];
const BUNDLE_REFERENCE_BLANK = ["Supplier ID", "Options", "Weight (kg)", "Length (cm)", "Width (cm)", "Height (cm)", "Barcode"];
const GROUP_BLANK = ["Product SKU code", "Product SKU name", "Option values", "Bundle option", "Bundle option value", "Qty",
"FOC qty", ...BUNDLE_REFERENCE_BLANK];
// Columns kept as text so Excel does not turn a code like 0123 or a long barcode into a number.
const TEXT_COLUMNS = ["Product SKU code", "Options", "Option values", "Barcode", "Product code", "Tags",
"Bundle option", "Bundle option value", "Includes product"];
// Data column title -> Lists column title.
const DROPDOWNS: Record<string, string> = {
Brand: "Brands", Category: "Categories", Status: "Status", "Allow backorder": "Yes/No", Fulfilment: "Fulfilment",
"Supplier ID": "Suppliers", "Product type": "Product type", Country: "Country",
};
const COUNTRY_NOTE = "Optional. The country this row's prices are for; blank means the default country.";
export function importListsFrom(options: ProductOptions, locations: AdminLocationNode[], countries: string[] = []): ImportLists {
const codes = (rows: ProductOptions["brands"]) => rows.filter((r) => r.status === "Y" && r.code).map((r) => r.code as string);
return {
brands: codes(options.brands),
categories: codes(options.categories),
priceTypes: quickTypes(options.priceTypes),
suppliers: options.suppliers.filter((s) => s.status === "Y" && s.code && s.id != null)
.map((s) => ({ id: Number(s.id), code: s.code as string })),
country: defaultCountryId(locations),
countries,
};
}
function columnLetter(index: number): string {
let s = "";
for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) s = String.fromCharCode(65 + ((n - 1) % 26)) + s;
return s;
}
export async function buildImportTemplate(lists: ImportLists): Promise<Uint8Array> {
const { default: Excel } = await import("exceljs");
const wb = new Excel.Workbook();
const multiCountry = lists.countries.length > 1;
const columns: Record<string, string> = {
...PRODUCT_COLUMNS,
...Object.fromEntries(lists.priceTypes.map((type) => [priceColumn(type), PRICE_NOTE])),
...(multiCountry ? { Country: COUNTRY_NOTE } : {}),
};
const ws = wb.addWorksheet(PRODUCTS, { views: [{ state: "frozen", ySplit: 1 }] });
const headers = Object.keys(columns);
ws.addRow(headers).font = { bold: true };
headers.forEach((h, i) => {
const column = ws.getColumn(i + 1);
column.width = Math.max(h.length + 4, 12);
if (TEXT_COLUMNS.includes(h)) column.numFmt = "@";
ws.getRow(1).getCell(i + 1).note = columns[h];
});
const listColumns: [string, string[]][] = [
["Status", ["Active", "Inactive"]],
["Yes/No", ["Yes", "No"]],
["Fulfilment", FULFILMENT.map(([label]) => label)],
["Product type", PRODUCT_TYPES],
["Brands", lists.brands],
["Categories", lists.categories],
["Suppliers", lists.suppliers.map((s) => s.code)],
...(multiCountry ? [["Country", lists.countries] as [string, string[]]] : []),
];
const listsSheet = wb.addWorksheet("Lists", { state: "hidden" });
listsSheet.getRow(1).font = { bold: true };
const listRange: Record<string, string> = {};
listColumns.forEach(([title, values], i) => {
const column = listsSheet.getColumn(i + 1);
column.values = [title, ...values];
column.width = Math.max(title.length, ...values.map((v) => v.length), 10) + 2;
const letter = columnLetter(i);
if (values.length > 0) listRange[title] = `Lists!$${letter}$2:$${letter}$${values.length + 1}`;
});
for (const [title, list] of Object.entries(DROPDOWNS)) {
const range = listRange[list];
if (!range) continue;
const column = headers.indexOf(title) + 1;
// exceljs merges these identical per-cell rules into one range when it writes the file.
for (let r = 2; r <= MAX_IMPORT_ROWS + 1; r++) {
ws.getCell(r, column).dataValidation = { type: "list", allowBlank: true, formulae: [range] };
}
}
return new Uint8Array(await wb.xlsx.writeBuffer());
}
export interface CatalogExportRow {
productCode: string; productName: string | null; brand: string | null; category: string | null;
status: "Y" | "N"; shortDesc: string | null; compareAtPrice: number | null; allowOversell: boolean;
fulfilment: ImportFulfilment; tags: string[]; productType: ImportProductType;
skuCode: string | null; skuName: string | null; supplierCode: string | null; options: string | null;
optionValues: string | null; weight: number | null; lengthCm: number | null; widthCm: number | null;
heightCm: number | null; barcode: string | null; bundleOption: string | null; bundleOptionValue: string | null;
qty: number | null; qtyFoc: number | null; pickCount: number | null; includesProduct: string | null;
prices: Record<string, number>;
country?: string | null;
}
export interface CatalogExport { rows: CatalogExportRow[]; productsWithoutOptions: string[]; unusedSkus: string[] }
/** The import template with one row per export row, in the cell values the parser reads back. */
export async function buildCatalogueFile(lists: ImportLists, rows: CatalogExportRow[]): Promise<Uint8Array> {
const { default: Excel } = await import("exceljs");
const wb = new Excel.Workbook();
await wb.xlsx.load((await buildImportTemplate(lists)) as unknown as ArrayBuffer);
const ws = wb.getWorksheet(PRODUCTS)!;
const column = new Map<string, number>();
ws.getRow(1).eachCell((cell, col) => column.set(String(cell.value), col));
const fulfilment = new Map(FULFILMENT.map(([label, value]) => [value, label]));
const productType = (type: ImportProductType) => type[0] + type.slice(1).toLowerCase();
rows.forEach((r, i) => {
const cells: Record<string, string | number | null> = {
"Product code": r.productCode, "Product name": r.productName, Brand: r.brand, Category: r.category,
Status: r.status === "Y" ? "Active" : "Inactive", "Short description": r.shortDesc, MSRP: r.compareAtPrice,
"Allow backorder": r.allowOversell ? "Yes" : "No", Fulfilment: fulfilment.get(r.fulfilment) ?? null,
Tags: r.tags.join(", ") || null, "Product SKU code": r.skuCode, "Product SKU name": r.skuName,
"Supplier ID": r.supplierCode, Options: r.options, "Option values": r.optionValues, "Weight (kg)": r.weight,
"Length (cm)": r.lengthCm, "Width (cm)": r.widthCm, "Height (cm)": r.heightCm, Barcode: r.barcode,
"Product type": productType(r.productType), "Bundle option": r.bundleOption,
"Bundle option value": r.bundleOptionValue, Qty: r.qty, "FOC qty": r.qtyFoc, "Pick count": r.pickCount,
"Includes product": r.includesProduct,
};
for (const type of lists.priceTypes) cells[priceColumn(type)] = r.prices[type] ?? null;
if (column.has("Country")) cells.Country = r.country ?? null;
for (const [title, value] of Object.entries(cells)) {
if (value != null) ws.getCell(i + 2, column.get(title)!).value = value;
}
});
return new Uint8Array(await wb.xlsx.writeBuffer());
}
type Row = { row: number; get: (title: string) => string | null; cellErrors: string[] };
/** An Excel error value (#N/A, #REF!...) in the cell or its formula result, else null. */
function cellError(value: ExcelJS.CellValue): string | null {
if (value == null || typeof value !== "object" || value instanceof Date) return null;
if ("error" in value) return String(value.error);
if ("result" in value) return cellError(value.result as ExcelJS.CellValue);
return null;
}
function cellText(value: ExcelJS.CellValue): string | null {
if (value == null) return null;
if (value instanceof Date) return value.toISOString().slice(0, 10);
if (typeof value === "object") {
if ("richText" in value) return cellText(value.richText.map((r) => r.text).join(""));
if ("text" in value) return cellText(value.text as ExcelJS.CellValue); // hyperlink
if ("result" in value) return cellText(value.result as ExcelJS.CellValue); // formula
return null;
}
const text = String(value).trim();
return text === "" ? null : text;
}
function readRows(ws: ExcelJS.Worksheet): { headers: string[]; rows: Row[] } {
const columns = new Map<string, number>();
ws.getRow(1).eachCell((cell, col) => {
const title = cellText(cell.value);
if (title) columns.set(title, col);
});
const rows: Row[] = [];
ws.eachRow((r, rowNumber) => {
if (rowNumber === 1) return;
const texts = new Map<string, string | null>();
const cellErrors: string[] = [];
for (const [title, col] of columns) {
const value = r.getCell(col).value;
const error = cellError(value);
if (error) cellErrors.push(`${title} has the Excel error ${error}`);
texts.set(title, error ? null : cellText(value));
}
if (cellErrors.length > 0 || [...texts.values()].some((t) => t != null)) {
rows.push({ row: rowNumber, get: (t) => texts.get(t) ?? null, cellErrors });
}
});
return { headers: [...columns.keys()], rows };
}
/** "Red/L" or " Red / L " as the product page writes it: "Red / L". */
const splitOptions = (text: string | null) => (text == null ? [] : text.split("/").map((p) => p.trim()));
const joinOptions = (text: string | null) => (text == null ? null : splitOptions(text).join(OPTION_SEPARATOR));
export async function parseImportWorkbook(
data: ArrayBuffer | Uint8Array,
lists: ImportLists,
): Promise<{ request: CatalogImportRequest; errors: ImportRowError[] }> {
const request: CatalogImportRequest = { country: lists.country || null, skus: [], salesItems: [] };
const errors: ImportRowError[] = [];
const { default: Excel } = await import("exceljs");
const wb = new Excel.Workbook();
try {
await wb.xlsx.load(data as ArrayBuffer);
} catch {
return { request, errors: [{ sheet: "File", row: 0, message: "This file is not a valid .xlsx workbook" }] };
}
const products = wb.getWorksheet(PRODUCTS);
if (!products) {
return { request, errors: [{ sheet: "File", row: 0, message: "This is the old import template. Download the new one and copy your rows into it." }] };
}
const { headers, rows } = readRows(products);
if (rows.length > MAX_IMPORT_ROWS) {
errors.push({ sheet: PRODUCTS, row: 1, message: `${PRODUCTS} has more than 2,000 rows; split the file` });
return { request, errors };
}
const priceColumns = new Map(lists.priceTypes.map((type) => [priceColumn(type), type]));
for (const title of headers) {
if (title.endsWith(" price") && !priceColumns.has(title)) {
errors.push({ sheet: PRODUCTS, row: 1, message: `${title} is not an active price type; download the template again` });
}
}
// Cell readers that record an error on the current sheet and row.
const sheet = PRODUCTS;
let at: Row = { row: 0, get: () => null, cellErrors: [] };
const begin = (row: Row) => {
at = row;
row.cellErrors.forEach((message) => fail(message));
};
const fail = (message: string) => errors.push({ sheet, row: at.row, message });
const text = (title: string, required = false) => {
const value = at.get(title);
if (required && value == null) fail(`${title} is required`);
return value;
};
const number = (title: string, { required = false, positive = false } = {}) => {
const value = text(title, required);
if (value == null) return null;
const n = Number(value);
if (!Number.isFinite(n) || n < 0 || (positive && n <= 0)) {
fail(`${title} must be a number ${positive ? "greater than 0" : "of 0 or more"}`);
return null;
}
return n;
};
const fromList = (title: string, values: string[], required = false) => {
const value = text(title, required);
if (value == null) return null;
const match = values.find((v) => v.toLowerCase() === value.toLowerCase());
if (match === undefined) fail(`${title} ${value} is not in the list`);
return match ?? null;
};
/** A whole number of at least `min`; blank is null (an error too when required). */
const whole = (title: string, min: number, required = false) => {
const value = at.get(title);
const n = value == null ? NaN : Number(value);
if (value != null ? !Number.isInteger(n) || n < min : required) {
fail(`${title} must be a whole number of ${min} or more`);
return null;
}
return value == null ? null : n;
};
/** Checks a later row of a code repeats the first row's value of each shared column. */
const sameAsFirst = (first: Row, titles: string[]) => {
for (const title of titles) {
if ((at.get(title) ?? "").toLowerCase() !== (first.get(title) ?? "").toLowerCase()) {
fail(`${title} differs from row ${first.row} of the same code`);
}
}
};
const skuFirst = new Map<string, Row>();
const itemFirst = new Map<string, Row>();
const itemColumns = ["Product name", "Brand", "Category", "Status", "Short description", "MSRP", "Allow backorder",
"Fulfilment", "Tags"];
const measures = [["Weight (kg)", "weight"], ["Length (cm)", "lengthCm"], ["Width (cm)", "widthCm"],
["Height (cm)", "heightCm"]] as const;
const sameItemColumns = [...itemColumns, "Pick count"];
const itemFor = (code: string, row: Row, type: string): ImportSalesItem => {
const key = code.toLowerCase();
const first = itemFirst.get(key);
if (first) {
sameAsFirst(first, sameItemColumns);
const item = request.salesItems.find((i) => i.code.toLowerCase() === key)!;
// Blank means Standard, so compare the resolved type rather than the cell.
if (item.productType !== type.toUpperCase()) fail(`Product type differs from row ${first.row} of the same code`);
return item;
}
itemFirst.set(key, row);
const status = fromList("Status", ["Active", "Inactive"], true);
const fulfilment = fromList("Fulfilment", FULFILMENT.map(([label]) => label));
const item: ImportSalesItem = {
row: row.row,
code,
name: text("Product name", true),
brand: fromList("Brand", lists.brands, true),
category: fromList("Category", lists.categories, true),
status: status == null ? null : status === "Active" ? "Y" : "N",
shortDesc: text("Short description"),
compareAtPrice: number("MSRP"),
allowOversell: fromList("Allow backorder", ["Yes", "No"]) === "Yes",
fulfilment: FULFILMENT.find(([label]) => label === fulfilment)?.[1] ?? "ANY",
tags: (text("Tags") ?? "").split(",").map((t) => t.trim()).filter(Boolean),
productType: type.toUpperCase() as ImportProductType,
groupPickCount: type === "Group" ? whole("Pick count", 1, true) : null,
groupProducts: [],
variations: [],
};
request.salesItems.push(item);
return item;
};
for (const row of rows) {
begin(row);
const code = text("Product code", true);
const kind = fromList("Product type", PRODUCT_TYPES);
if (kind == null && at.get("Product type") != null) continue; // not in the list: already reported
const type = kind ?? "Standard";
if (type === "Group") {
const includes = text("Includes product", true);
for (const title of [...GROUP_BLANK, ...priceColumns.keys()]) {
if (at.get(title) != null) fail(`${title} must be blank on a Group row`);
}
const fulfilment = fromList("Fulfilment", FULFILMENT.map(([label]) => label));
if (fulfilment != null && fulfilment !== "Pickup & delivery") fail("A group has no fulfilment restriction; leave Fulfilment blank");
if (code == null) continue;
const item = itemFor(code, row, type);
if (includes == null) continue;
const same = item.groupProducts.find((g) => g.code.toLowerCase() === includes.toLowerCase());
if (same) fail(`Includes product repeats the product of row ${same.row}`);
else item.groupProducts.push({ row: row.row, code: includes });
continue;
}
const bundle = type === "Bundle";
if (!bundle) for (const title of STANDARD_BLANK) if (at.get(title) != null) fail(`${title} is only for Bundle or Group rows`);
const skuCode = bundle ? text("Product SKU code", true) : text("Product SKU code") ?? code;
// A Bundle row without a Product SKU name only references an existing SKU variant.
const defines = !bundle || at.get("Product SKU name") != null;
if (!defines) {
for (const title of BUNDLE_REFERENCE_BLANK) if (at.get(title) != null) fail(`${title} needs Product SKU name on a Bundle row`);
}
const optionValues = joinOptions(text("Option values"));
const variant: ImportSkuVariant = {
row: row.row,
variant: joinOptions(text("Options")),
variantName: optionValues,
weight: null, lengthCm: null, widthCm: null, heightCm: null, barcode: null,
};
if (defines) {
const options = splitOptions(text("Options"));
const values = splitOptions(text("Option values"));
if (options.length > MAX_OPTIONS) fail("A SKU has at most three options");
else if (options.length !== values.length || [...options, ...values].some((p) => p === "")) {
fail("Option values must give one value for each of the Options");
}
variant.weight = number("Weight (kg)", { required: true, positive: true });
variant.lengthCm = number("Length (cm)", { required: true, positive: true });
variant.widthCm = number("Width (cm)", { required: true, positive: true });
variant.heightCm = number("Height (cm)", { required: true, positive: true });
variant.barcode = text("Barcode");
}
const prices: Record<string, number> = {};
for (const [title, type] of priceColumns) {
const price = number(title);
if (price != null) prices[type] = price;
}
const country = headers.includes("Country") ? text("Country")?.toUpperCase() : undefined;
const bundleOption = bundle ? text("Bundle option") : null;
const bundleValue = bundle ? text("Bundle option value") : null;
if ((bundleOption == null) !== (bundleValue == null)) fail("Bundle option and Bundle option value go together");
const qty = bundle ? whole("Qty", 1) ?? 1 : 1;
const qtyFoc = bundle ? whole("FOC qty", 0) ?? 0 : 0;
if (code == null || skuCode == null) continue;
if (defines) {
// Codes match stored records case-insensitively, so "s1" joins "S1" (the first spelling is kept).
const skuKey = skuCode.toLowerCase();
const skuFirstRow = skuFirst.get(skuKey);
if (skuFirstRow) {
sameAsFirst(skuFirstRow, ["Product SKU name", "Supplier ID"]);
if ((joinOptions(skuFirstRow.get("Options")) ?? "").toLowerCase() !== (variant.variant ?? "").toLowerCase()) {
fail(`Options differs from row ${skuFirstRow.row} of the same code`);
}
const sku = request.skus.find((s) => s.code.toLowerCase() === skuKey)!;
const same = sku.variants.find((v) => (v.variantName ?? "").toLowerCase() === (variant.variantName ?? "").toLowerCase());
if (same) {
for (const [title, key] of measures) {
if (variant[key] !== same[key]) fail(`${title} differs from row ${same.row} of the same variant`);
}
if (variant.barcode !== same.barcode) fail(`Barcode differs from row ${same.row} of the same variant`);
} else {
sku.variants.push(variant);
}
} else {
skuFirst.set(skuKey, row);
const supplier = fromList("Supplier ID", lists.suppliers.map((s) => s.code));
request.skus.push({
row: row.row,
code: skuCode,
name: text("Product SKU name", true),
supplierId: lists.suppliers.find((s) => s.code === supplier)?.id ?? null,
variants: [variant],
});
}
}
const item = itemFor(code, row, type);
if (!bundle) {
item.variations.push({ row: row.row, skuCode, optionValues, option: null, optionValue: null, components: [], prices, country });
continue;
}
const lower = (v: string | null) => (v ?? "").toLowerCase();
let variation = item.variations.find((v) => lower(v.option) === lower(bundleOption) && lower(v.optionValue) === lower(bundleValue));
if (variation) {
for (const [title, priceType] of priceColumns) {
if (prices[priceType] !== variation.prices[priceType]) fail(`${title} differs from row ${variation.row} of the same option`);
}
} else {
variation = { row: row.row, skuCode: null, optionValues: null, option: bundleOption, optionValue: bundleValue, components: [], prices, country };
item.variations.push(variation);
}
const same = variation.components.find((c) => lower(c.skuCode) === lower(skuCode) && lower(c.optionValues) === lower(optionValues));
if (same) fail(`Product SKU code repeats the component of row ${same.row}`);
else variation.components.push({ row: row.row, skuCode, optionValues, qty, qtyFoc });
}
return { request, errors };
}
export async function importErrorsXlsx(errors: ImportRowError[]): Promise<Uint8Array> {
return toXlsx(errors as unknown as Record<string, unknown>[],
[{ key: "sheet", title: "Sheet" }, { key: "row", title: "Row" }, { key: "message", title: "Message" }], "Errors");
}