fix(intake): normalize SKU workbook dimensions to centimeters

(cherry picked from commit 58c3a40d2c2ea4e2fe1c3cc97af499390a8c658f)
This commit is contained in:
WuYongJie 2026-12-01 11:18:32 +08:00
parent afe94b2be1
commit 0cb57a4fd1
9 changed files with 95 additions and 21 deletions

View File

@ -173,13 +173,23 @@ describe("automatic SKU import identity generation", () => {
expect(second).toMatchObject({ successCount: 0, skippedCount: 2, generatedCount: 0 });
});
it("matches legacy size separators without creating a duplicate SKU or rewriting its name", () => {
const specName = "SJDSMQ实木BD30边柜胡桃色60*40*120";
const first = buildSkuItemsFromAutoImportedWorkbookRows({ ...options, currentItems: [], rows: [{ ...row, size: "60*40*120", specName }] });
const second = buildSkuItemsFromAutoImportedWorkbookRows({ ...options, currentItems: first.items, rows: [{ ...row, size: "60/40/120", specName }] });
expect(second).toMatchObject({ successCount: 0, skippedCount: 1, generatedCount: 0 });
expect(second.items).toBe(first.items);
expect(second.items[0]).toMatchObject({ size: "60*40*120", specName });
it("updates a legacy millimeter size on the existing SKU without recoding or renaming", () => {
const specName = "SJDSMQ实木BD30边柜胡桃色1400*600*750";
const imported = { ...row, size: "140/60/75", specName };
const first = buildSkuItemsFromAutoImportedWorkbookRows({ ...options, currentItems: [], rows: [imported] });
const [sku] = first.items;
const legacy = { ...sku, size: "1400*600*750mm" };
const second = buildSkuItemsFromAutoImportedWorkbookRows({ ...options, currentItems: [legacy], rows: [imported] });
expect(second).toMatchObject({ successCount: 1, updatedCount: 1, generatedCount: 0 });
expect(second.items).toEqual([{ ...legacy, size: "140/60/75" }]);
});
it("does not reinterpret a normalized size above the unitless threshold when matching an exact repeat", () => {
const imported = { ...row, size: "400/60/75" };
const first = buildSkuItemsFromAutoImportedWorkbookRows({ ...options, currentItems: [], rows: [imported] });
const repeat = buildSkuItemsFromAutoImportedWorkbookRows({ ...options, currentItems: first.items, rows: [imported] });
expect(repeat.items).toBe(first.items);
expect(repeat).toMatchObject({ skippedCount: 1, generatedCount: 0 });
});
it("updates imported details without blocking an unchanged specification or consuming a new number", () => {

View File

@ -1,4 +1,5 @@
import { normalizeSkuAutoImportSize, SkuAutoImportValidationError, type NonIntegratedSkuAutoImportRow } from '@/lib/non-integrated-sku-auto-import';
import { SkuAutoImportValidationError, type NonIntegratedSkuAutoImportRow } from '@/lib/non-integrated-sku-auto-import';
import { normalizeSkuWorkbookSize } from '@/lib/non-integrated-sku-import-size';
import type { NonIntegratedSkuItem } from '../../nonIntegratedStorage';
import { updateAutoImportGroup, type AutoImportSupplier } from './skuAutoImportUpdateHelpers';
@ -15,8 +16,8 @@ export class SkuAutoImportMatchRequired extends Error {
}
}
function specificationKey(item: Pick<NonIntegratedSkuItem, 'model' | 'size' | 'color' | 'material'>) {
return [item.model.toUpperCase(), normalizeSkuAutoImportSize(item.size), item.color, item.material].map(value => value.trim()).join('\u001f');
function specificationKey(item: Pick<NonIntegratedSkuItem, 'model' | 'color' | 'material'>) {
return [item.model.toUpperCase(), item.color, item.material].map(value => value.trim()).join('\u001f');
}
export function matchAutoImportGroup({ items, row, model, targetBatchNo, spu, supplier, selectedId }: {
@ -31,7 +32,14 @@ export function matchAutoImportGroup({ items, row, model, targetBatchNo, spu, su
const key = specificationKey({ ...row, model });
const groups = new Map<string, NonIntegratedSkuItem[]>();
const batchItems = items.filter(item => (item.batchNo || 1) === targetBatchNo);
const matchingGroups = new Set(batchItems.filter(item => specificationKey(item) === key).map(item => item.packageGroupId || item.id));
const sameSpecification = batchItems.filter(item => specificationKey(item) === key);
const size = row.size.trim();
// The incoming size already has its units converted. Try the saved value first,
// then check older entries whose dimensions were stored in a different format.
const exactMatches = sameSpecification.filter(item => item.size.trim() === size);
const matchingItems = exactMatches.length ? exactMatches
: sameSpecification.filter(item => normalizeSkuWorkbookSize(item.size) === size);
const matchingGroups = new Set(matchingItems.map(item => item.packageGroupId || item.id));
for (const item of batchItems) {
const groupKey = item.packageGroupId || item.id;
if (!matchingGroups.has(groupKey)) continue;

View File

@ -17,6 +17,7 @@ export function updateAutoImportGroup(
const importedSpecName = [row.specName, item.packageSuffix ? `${item.packageSuffix}包` : ''].filter(Boolean).join(' ');
const updated = {
...item,
size: row.size,
boardMaterialType: row.boardMaterialType || item.boardMaterialType,
installMethod: row.installMethod || item.installMethod,
executeStandard: row.executeStandard || item.executeStandard,

View File

@ -22,6 +22,7 @@ describe("approved SKU automatic coding template", () => {
const bytes = fs.readFileSync(path.join(process.cwd(), "public/templates/sku-auto-code-import.xlsx"));
const parsed = XLSX.read(bytes);
expect(XLSX.utils.sheet_to_json(parsed.Sheets[parsed.SheetNames[0]], { header: 1 })[0]).toEqual(headers);
expect(parsed.Sheets["填写说明"].C8.v).toBe("填写产品尺寸长宽高,例如:120/60/75");
await expect(parseNonIntegratedSkuWorkbook(fileFromBytes(bytes))).resolves.toMatchObject({ mode: "auto", rows: [] });
});
@ -64,10 +65,16 @@ describe("approved SKU automatic coding template", () => {
["60x40x120", "60/40/120"],
["60X40X120", "60/40/120"],
[" 60 * 40 × 120 ", "60/40/120"],
["60.5 × 40.2 x 120 mm", "60.5/40.2/120 mm"],
["60/40/120", "60/40/120"],
["60.5 × 40.2 x 120 mm", "6.05/4.02/12"],
["1400/600/750", "140/60/75"],
["1400*600*750mm", "140/60/75"],
["140*60*75", "140/60/75"],
["300/60/75", "300/60/75"],
["400/60/75cm", "400/60/75"],
["1.4/0.6/0.75米", "140/60/75"],
["1.4m × 60厘米 × 750毫米", "140/60/75"],
["XL加长款", "XL加长款"],
])("normalizes numeric size separators without rewriting factory names: %s", async (size, expected) => {
])("normalizes product dimensions without rewriting factory names: %s", async (size, expected) => {
const custom = [...values];
const specName = "SJDSMQ实木BD30边柜胡桃色60*40*120";
custom[1] = specName;
@ -78,7 +85,7 @@ describe("approved SKU automatic coding template", () => {
it("continues to accept the previous template without the optional specification-name column", async () => {
const priorHeaders = headers.filter((_, index) => index !== 1);
const priorValues = values.filter((_, index) => index !== 1);
await expect(parseNonIntegratedSkuWorkbook(createFile([priorHeaders, priorValues]))).resolves.toMatchObject({ mode: "auto", rows: [{ specName: "", size: "1200/600/750 mm", executeStandard: "GB/T3324-2024" }] });
await expect(parseNonIntegratedSkuWorkbook(createFile([priorHeaders, priorValues]))).resolves.toMatchObject({ mode: "auto", rows: [{ specName: "", size: "120/60/75", executeStandard: "GB/T3324-2024" }] });
});
it("reports the actual Excel row after blank rows and validates pasted values", async () => {

View File

@ -1,5 +1,6 @@
import { EXECUTION_STANDARD_OPTIONS } from "@/app/intake/non-integrated/workspaces/basic-info/executionStandardDirectory";
import { INSTALL_METHOD_OPTIONS, SKU_BOARD_MATERIAL_TYPE_OPTIONS } from "@/app/intake/non-integrated/workspaces/basic-info/skuFieldConfig";
import { normalizeSkuWorkbookSize } from "./non-integrated-sku-import-size";
export const SKU_AUTO_IMPORT_COLUMNS = [
{ key: "image", label: "图片", required: false },
@ -45,11 +46,6 @@ export function normalizeSkuAutoImportHeader(value: string) {
return value.replace(/\s+/g, "").replace(/[**]/g, "");
}
export function normalizeSkuAutoImportSize(value: string) {
// Only replace separators between numbers; keep dimension labels and units intact.
return value.trim().replace(/(\d)\s*[*×xX]\s*(?=\d)/g, "$1/");
}
export function isSkuAutoImportHeader(headers: string[]) {
const normalized = headers.map(normalizeSkuAutoImportHeader);
// A full exported workbook must keep using the existing import path.
@ -80,7 +76,7 @@ export async function parseSkuAutoImportRows(
for (const column of SKU_AUTO_IMPORT_COLUMNS) {
row[column.key] = String(cells[headers.indexOf(column.label)] ?? "").trim();
}
row.size = normalizeSkuAutoImportSize(row.size);
row.size = normalizeSkuWorkbookSize(row.size);
const problems = SKU_AUTO_IMPORT_COLUMNS.filter(column => column.required && !row[column.key])
.map(column => `${column.label}必填`);
if (row.model && !/^K(?:0[1-9]|[1-9]\d)$/.test(row.model)) problems.push("型号只能选择 K01~K99");

View File

@ -88,6 +88,25 @@ describe("parseNonIntegratedSkuWorkbook", () => {
"简化资料表已停用",
);
});
it("normalizes the complete template's size field without changing the specified code or name", async () => {
const headers = NON_INTEGRATED_SKU_TEMPLATE_COLUMNS.map(column => column.label);
const inputs = ["1400/600/750", "1400*600*750mm", "140*60*75"];
const rows = inputs.map((size, index) => headers.map(header => {
if (header === "尺寸") return size;
if (header === "货号") return `SZ02300${index + 1}`;
if (header === "规格名称") return "厂家原名称 140*60*75";
return "";
}));
await expect(parseNonIntegratedSkuWorkbook(createWorkbookFile([headers, ...rows]))).resolves.toMatchObject({
mode: "standard",
rows: inputs.map((_, index) => ({
skuCode: `SZ02300${index + 1}`,
specName: "厂家原名称 140*60*75",
size: "140/60/75",
})),
});
});
});
describe("findSkuImportSpuPrefixErrors", () => {

View File

@ -0,0 +1,31 @@
const DECIMAL_WITH_UNIT = /^(\d+(?:\.\d+)?|\.\d+)\s*(mm|毫米|cm|厘米|公分|m|米)?$/i;
const UNITLESS_MILLIMETER_THRESHOLD = 300;
function toCentimeterExponent(unit: string | undefined) {
if (!unit) return undefined;
if (/^(mm|毫米)$/i.test(unit)) return -1;
if (/^(m|米)$/i.test(unit)) return 2;
return 0;
}
export function normalizeSkuWorkbookSize(value: string) {
const text = value.trim();
const axes = text.normalize("NFKC").split(/\s*[/×*x]\s*/i)
.map(part => part.match(DECIMAL_WITH_UNIT));
if (axes.length !== 3 || !axes.every((axis): axis is RegExpMatchArray => axis !== null)) return text;
const dimensions = axes.map(axis => axis[1]);
const units = axes.map(axis => toCentimeterExponent(axis[2]));
const explicitUnits = new Set(units.filter(unit => unit !== undefined));
if (units[2] === undefined && explicitUnits.size > 1) return text;
// The trailing unit covers unmarked axes. With no units, infer one unit for the whole triple.
const commonUnit = units[2] ?? units.find(unit => unit !== undefined)
?? (dimensions.some(dimension => Number(dimension) > UNITLESS_MILLIMETER_THRESHOLD) ? -1 : 0);
const centimeters = dimensions.map((dimension, index) =>
Number(`${dimension}e${units[index] ?? commonUnit}`),
);
return centimeters.every(dimension => Number.isFinite(dimension) && dimension > 0)
? centimeters.join("/")
: text;
}

View File

@ -1,6 +1,7 @@
import { NON_INTEGRATED_SKU_TEMPLATE_COLUMNS, type NonIntegratedSkuExportRow, type NonIntegratedSkuImportRow, type NonIntegratedSkuWorkbookImport } from "./non-integrated-sku-workbook-schema";
import { isSkuAutoImportHeader, parseSkuAutoImportRows, type SkuWorkbookProgress } from "./non-integrated-sku-auto-import";
import { attachSkuWorkbookImages } from "./non-integrated-sku-workbook-images";
import { normalizeSkuWorkbookSize } from "./non-integrated-sku-import-size";
function normalizeWorkbookCellValue(value: unknown) {
if (value === null || value === undefined) return ''
@ -103,6 +104,7 @@ export async function parseNonIntegratedSkuWorkbook(
? ''
: normalizeWorkbookCellValue(row[cellIndex])
}
importRow.size = normalizeSkuWorkbookSize(importRow.size)
return { ...importRow, rowNumber: headerRowIndex + index + 2 }
})
.filter((row) =>