#!/usr/bin/env node /** * 导入「自贡商品明细」类 Excel 到商品基础数据(product_catalog + skus 同步) * * 列映射: * 商品名 -> name * 分类 -> 一级分类 * 二级分类 -> 二级分类(可空) * 规格 -> unit(单位) * 规格详情 -> spec * 厂家 -> brand(写入品牌字段) * * 用法: * node scripts/import-zigong-products.cjs --file "path/to/file.xlsx" --dry-run * node scripts/import-zigong-products.cjs --file "path/to/file.xlsx" --execute * node scripts/import-zigong-products.cjs --file "path/to/file.xlsx" --execute --branch BR002 */ const fs = require('fs'); const path = require('path'); const XLSX = require('xlsx'); const pg = require(path.join(__dirname, '../server/node_modules/pg')); const dotenv = require(path.join(__dirname, '../server/node_modules/dotenv')); dotenv.config({ path: path.join(__dirname, '../server/.env') }); const execute = process.argv.includes('--execute'); const dryRun = !execute; const fileArgIdx = process.argv.indexOf('--file'); const branchArgIdx = process.argv.indexOf('--branch'); const filePath = fileArgIdx >= 0 ? process.argv[fileArgIdx + 1] : ''; const branchOverride = branchArgIdx >= 0 ? process.argv[branchArgIdx + 1] : null; function normalizeName(value) { return String(value ?? '').trim(); } function isDataRow(row) { const name = normalizeName(row['商品名'] ?? row['商品名称'] ?? row['商品名称*']); if (!name) return false; if (name.includes('AI生成') || name.includes('仅供参考')) return false; return true; } function readRows(file) { if (!fs.existsSync(file)) { throw new Error(`文件不存在: ${file}`); } const workbook = XLSX.readFile(file); const sheetName = workbook.SheetNames.find((name) => /商品|汇总|导入/i.test(name)) || workbook.SheetNames[0]; const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' }); return rows.filter(isDataRow); } function generateCode(prefix) { return `${prefix}${Date.now().toString().slice(-9)}${Math.floor(Math.random() * 90 + 10)}`; } async function generateUniqueCode(client, prefix) { for (let attempt = 0; attempt < 8; attempt++) { const code = generateCode(prefix); const { rows } = await client.query( `SELECT 1 FROM product_catalog WHERE code = $1 LIMIT 1`, [code] ); if (!rows.length) return code; } return `${prefix}${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`; } function findLevel1(categories, name, branchCode) { const normalized = normalizeName(name); return categories.find( (cat) => cat.branch_code === branchCode && !cat.parent_code && normalizeName(cat.category_name) === normalized ); } function findLevel2(categories, l1Code, l2Name, branchCode) { const normalized = normalizeName(l2Name); return categories.find( (cat) => cat.branch_code === branchCode && cat.parent_code === l1Code && normalizeName(cat.category_name) === normalized ); } async function ensureCategoryChain(client, categories, branchCode, l1Name, l2Name, dryRunMode) { const created = []; const trimmedL1 = normalizeName(l1Name); const trimmedL2 = normalizeName(l2Name); if (!trimmedL1) throw new Error('一级分类不能为空'); let l1 = findLevel1(categories, trimmedL1, branchCode); if (!l1) { const code = dryRunMode ? `CAT_DRY_${trimmedL1}` : await generateUniqueCode(client, 'CAT'); l1 = { category_code: code, category_name: trimmedL1, parent_code: null, branch_code: branchCode, level: 1, }; categories.push(l1); created.push(trimmedL1); if (!dryRunMode) { await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, level, sort_order, loss_threshold, is_fresh, status, branch_code ) VALUES ('category', $1, $2, NULL, 1, 0, 5, true, 1, $3)`, [code, trimmedL1, branchCode] ); } } if (!trimmedL2) { return { code: l1.category_code, categories, created }; } let l2 = findLevel2(categories, l1.category_code, trimmedL2, branchCode); if (!l2) { const code = dryRunMode ? `CAT_DRY_${trimmedL1}_${trimmedL2}` : await generateUniqueCode(client, 'CAT'); l2 = { category_code: code, category_name: trimmedL2, parent_code: l1.category_code, branch_code: branchCode, level: 2, }; categories.push(l2); created.push(`${trimmedL1}/${trimmedL2}`); if (!dryRunMode) { await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, level, sort_order, loss_threshold, is_fresh, status, branch_code ) VALUES ('category', $2, $3, $1, 2, 0, 5, false, 1, $4)`, [l1.category_code, code, trimmedL2, branchCode] ); } } return { code: l2.category_code, categories, created }; } async function main() { if (!filePath) { console.error('请指定 --file 路径'); process.exit(1); } if (!process.env.DATABASE_URL) { console.error('缺少 DATABASE_URL,请在 server/.env 配置或通过环境变量传入'); process.exit(1); } const rows = readRows(path.resolve(filePath)); const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { const branchResult = branchOverride ? { rows: [{ branch_code: branchOverride }] } : await client.query( `SELECT branch_code FROM branches WHERE status = 1 ORDER BY branch_code LIMIT 1` ); const branchCode = branchResult.rows[0]?.branch_code; if (!branchCode) throw new Error('未找到可用分公司 branch_code'); const existingProducts = await client.query( `SELECT code, name FROM product_catalog WHERE item_type = 'product'` ); const existingCategories = await client.query( `SELECT code AS category_code, parent_code, name AS category_name, branch_code FROM product_catalog WHERE item_type = 'category' AND branch_code = $1`, [branchCode] ); const usedNames = new Set(existingProducts.rows.map((row) => normalizeName(row.name))); const categories = existingCategories.rows.map((row) => ({ ...row, level: row.parent_code ? 2 : 1 })); const result = { dryRun, branchCode, totalRows: rows.length, success: 0, skipped: 0, failed: 0, categoriesCreated: 0, errors: [], }; if (dryRun) { await client.query('BEGIN'); } for (let index = 0; index < rows.length; index++) { const row = rows[index]; const rowNumber = index + 2; const skuName = normalizeName(row['商品名'] ?? row['商品名称'] ?? row['商品名称*']); const l1Name = normalizeName(row['分类'] ?? row['一级分类'] ?? row['一级分类*']); const l2Name = normalizeName(row['二级分类'] ?? row['二级分类*']); const unit = normalizeName(row['规格'] ?? row['单位'] ?? row['单位*']) || '斤'; const spec = normalizeName(row['规格详情'] ?? row['规格']); const brand = normalizeName(row['厂家'] ?? row['品牌'] ?? row['条码']); if (!skuName) { result.failed += 1; result.errors.push(`第 ${rowNumber} 行:商品名称为空`); continue; } if (!l1Name) { result.failed += 1; result.errors.push(`第 ${rowNumber} 行「${skuName}」:分类为空`); continue; } if (usedNames.has(skuName)) { result.skipped += 1; result.errors.push(`第 ${rowNumber} 行:商品「${skuName}」已存在,已跳过`); continue; } try { const beforeCategoryCount = categories.length; const ensured = await ensureCategoryChain( client, categories, branchCode, l1Name, l2Name, dryRun ); result.categoriesCreated += Math.max(0, categories.length - beforeCategoryCount); const skuCode = dryRun ? `SKU_DRY_${result.success + 1}` : await generateUniqueCode(client, 'SKU'); if (!dryRun) { await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, unit, spec, barcode, brand, default_loss_threshold, sale_price, cost_price, status, branch_code ) VALUES ( 'product', $1, $2, $3, $4, $5, $6, NULLIF($7, ''), 5, 0, 0, 1, $8 )`, [skuCode, skuName, ensured.code, unit, spec || null, skuCode, brand, branchCode] ); } usedNames.add(skuName); result.success += 1; } catch (error) { result.failed += 1; result.errors.push(`第 ${rowNumber} 行「${skuName}」:${error.message || error}`); } } if (dryRun) { await client.query('ROLLBACK'); } console.log(JSON.stringify(result, null, 2)); if (result.errors.length) { console.log('\n--- 明细 ---'); result.errors.slice(0, 30).forEach((line) => console.log(line)); if (result.errors.length > 30) { console.log(`... 另有 ${result.errors.length - 30} 条`); } } if (dryRun) { console.log('\n[dry-run] 未写入数据库。确认后加 --execute'); } else { console.log('\n导入完成。'); } } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });