'use strict'; const ExcelJS = require('exceljs'); const fs = require('fs'); /** * 商品批量导入的列定义与解析工具。 * * 只接受下面这些字段,表头按中文名匹配(允许少量别名); * 未识别的列会在结果里以 ignored_columns 返回,不参与导入。 * 「所属货主」按下属公司名称匹配(subsidiary_name),由控制器解析为 subsidiary_id。 */ const IMPORT_COLUMNS = [ { field: 'item_code', label: '商品编码', required: true, type: 'text', max: 50 }, { field: 'item_name', label: '商品名称', type: 'text', max: 255 }, { field: 'goods_code', label: '货物编码', type: 'text', max: 100, aliases: [ '货品编码' ] }, { field: 'sku_property', label: 'SKU规格', type: 'text', max: 100, aliases: [ '规格', 'SKU 规格' ] }, { field: 'category_name', label: '分类', type: 'text', max: 100, aliases: [ '商品分类' ] }, { field: 'brand_name', label: '品牌', type: 'text', max: 100, aliases: [ '商品品牌' ] }, { field: 'barcode', label: '条码', type: 'text', max: 100 }, { field: 'stock_unit', label: '单位', type: 'text', max: 20, aliases: [ '库存单位' ] }, { field: 'retail_price', label: '零售价', type: 'money' }, { field: 'cost_price', label: '成本价', type: 'money' }, { field: 'tag_price', label: '标签价', type: 'money', aliases: [ '标价' ] }, { field: 'subsidiary_name', label: '所属货主', type: 'text', max: 100, aliases: [ '货主', '下属公司', '所属公司' ], }, { field: 'remark', label: '备注', type: 'text', max: 255 }, ]; /** 允许的表头(含别名)→ 字段定义 */ const HEADER_MAP = new Map(); for (const col of IMPORT_COLUMNS) { HEADER_MAP.set(col.label, col); for (const alias of col.aliases || []) HEADER_MAP.set(alias, col); } /** * 单元格取值归一化(兼容富文本 / 公式 / 超链接 / 日期) * @param {*} value 原始单元格值 * @return {string} 文本 */ function cellText(value) { if (value == null) return ''; if (value instanceof Date) return value.toISOString().slice(0, 10); if (typeof value === 'object') { if (Array.isArray(value.richText)) return value.richText.map(item => item.text || '').join('').trim(); if (value.text != null) return String(value.text).trim(); if (value.result != null) return String(value.result).trim(); if (value.hyperlink != null) return String(value.hyperlink).trim(); return ''; } return String(value).trim(); } /** * 金额解析(去千分位与货币符号) * @param {string} text 文本 * @return {{ok: boolean, value?: number, message?: string}} 解析结果 */ function parseMoney(text) { const cleaned = String(text || '').replace(/[¥,,\s]/g, ''); if (!cleaned) return { ok: true, value: undefined }; const num = Number(cleaned); if (!Number.isFinite(num)) return { ok: false, message: `不是有效金额:${text}` }; if (num < 0) return { ok: false, message: '金额不能为负数' }; return { ok: true, value: Number(num.toFixed(2)) }; } /** * 读取 Excel 文件并解析为待导入行 * @param {string|Buffer} source 文件路径或文件内容 * @return {Promise<{rows: Array, ignoredColumns: Array, headerError: string|null}>} 解析结果 */ async function parseImportFile(source) { const buffer = typeof source === 'string' ? fs.readFileSync(source) : source; const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(buffer); const sheet = workbook.worksheets[0]; if (!sheet) return { rows: [], ignoredColumns: [], headerError: '文件中没有任何工作表' }; const headerRow = sheet.getRow(1); const columnByIndex = new Map(); const ignoredColumns = []; headerRow.eachCell({ includeEmpty: false }, (cell, colNumber) => { const label = cellText(cell.value); if (!label) return; const col = HEADER_MAP.get(label); if (col) { if (!columnByIndex.has(col.field)) columnByIndex.set(col.field, colNumber); } else { ignoredColumns.push(label); } }); if (!columnByIndex.has('item_code')) { return { rows: [], ignoredColumns, headerError: '缺少「商品编码」列(第一行应为表头)' }; } const rows = []; const lastRow = sheet.actualRowCount || sheet.rowCount; for (let rowNumber = 2; rowNumber <= lastRow; rowNumber++) { const row = sheet.getRow(rowNumber); const raw = {}; for (const col of IMPORT_COLUMNS) { const colNumber = columnByIndex.get(col.field); raw[col.field] = colNumber ? cellText(row.getCell(colNumber).value) : ''; } // 整行为空则跳过 if (Object.values(raw).every(text => !text)) continue; rows.push({ rowNumber, raw }); } return { rows, ignoredColumns, headerError: null }; } /** * 校验并把一行原始文本转换为待写入的商品字段 * 只返回「填了值」的字段:空单元格不覆盖已有数据 * @param {Object} raw 原始文本(按字段名) * @return {{data: Object, errors: Array}} 结果 */ function normalizeRow(raw) { const data = {}; const errors = []; for (const col of IMPORT_COLUMNS) { const text = String(raw[col.field] == null ? '' : raw[col.field]).trim(); if (col.type === 'money') { const parsed = parseMoney(text); if (!parsed.ok) { errors.push(`${col.label}${parsed.message}`); continue; } if (parsed.value !== undefined) data[col.field] = parsed.value; continue; } if (!text) { if (col.required) errors.push(`${col.label}不能为空`); continue; } if (col.max && text.length > col.max) { errors.push(`${col.label}超长(最多 ${col.max} 字符)`); continue; } data[col.field] = text; } return { data, errors }; } module.exports = { IMPORT_COLUMNS, parseImportFile, normalizeRow, cellText, parseMoney, };