#!/usr/bin/env node /** * 用 Excel 重建指定分公司基础商品库(分类+商品),并按商品名回写报价单 sku_code。 * * 用法: * node scripts/replace-branch-products-from-xlsx.cjs --file "path.xlsx" --branch BR002 --dry-run * node scripts/replace-branch-products-from-xlsx.cjs --file "path.xlsx" --branch BR002 --execute */ const fs = require('fs'); const path = require('path'); const XLSX = require('xlsx'); const { Pool } = 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 args = process.argv.slice(2); const execute = args.includes('--execute'); const fileIdx = args.indexOf('--file'); const branchIdx = args.indexOf('--branch'); const filePath = fileIdx >= 0 ? args[fileIdx + 1] : 'c:/Users/ADMIN/Desktop/project/数据/自贡商品明细_去重汇总(1).xlsx'; const branchCode = branchIdx >= 0 ? args[branchIdx + 1] : 'BR002'; function normalizeName(value) { return String(value ?? '') .trim() .replace(/\s+/g, '') .replace(/(/g, '(') .replace(/)/g, ')'); } 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]; return XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: '' }).filter(isDataRow); } function generateCode(prefix) { return `${prefix}${Date.now().toString().slice(-9)}${Math.floor(Math.random() * 90 + 10)}`; } async function uniqueCode(client, prefix) { for (let i = 0; i < 8; i += 1) { 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()}`; } async function ensureCategory(client, cache, branch, name, parentCode, level) { const key = `${parentCode || ''}|${normalizeName(name)}`; if (cache.has(key)) return cache.get(key); const existing = await client.query( `SELECT code FROM product_catalog WHERE item_type='category' AND branch_code=$1 AND name=$2 AND COALESCE(parent_code,'') = COALESCE($3,'') LIMIT 1`, [branch, name, parentCode] ); if (existing.rows[0]) { cache.set(key, existing.rows[0].code); return existing.rows[0].code; } const code = await uniqueCode(client, 'CAT'); 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, $3, $4, 0, 5, $5, 1, $6)`, [code, name, parentCode, level, level === 1, branch] ); await client.query( `INSERT INTO categories ( branch_code, category_code, parent_code, category_name, level, sort_order, loss_threshold, is_fresh, status ) VALUES ($1,$2,$3,$4,$5,0,5,$6,1) ON CONFLICT (branch_code, category_code) DO UPDATE SET parent_code = EXCLUDED.parent_code, category_name = EXCLUDED.category_name, level = EXCLUDED.level, is_fresh = EXCLUDED.is_fresh, status = 1`, [branch, code, parentCode, name, level, level === 1] ); cache.set(key, code); return code; } async function main() { if (!process.env.DATABASE_URL) throw new Error('缺少 DATABASE_URL'); const rows = readRows(path.resolve(filePath)); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { console.log(`\n=== Replace branch products (${execute ? 'EXECUTE' : 'DRY-RUN'}) ===`); console.log('file', path.resolve(filePath)); console.log('branch', branchCode, 'excel_rows', rows.length); const before = await client.query( `SELECT COUNT(*) FILTER (WHERE item_type='product')::int AS products, COUNT(*) FILTER (WHERE item_type='category')::int AS categories FROM product_catalog WHERE branch_code=$1`, [branchCode] ); console.log('before', before.rows[0]); const excelNames = new Set(); const parsed = []; for (const row of rows) { const name = String(row['商品名'] ?? row['商品名称'] ?? '').trim(); const l1 = String(row['分类'] ?? row['一级分类'] ?? '').trim() || '未分类'; const l2 = String(row['二级分类'] ?? '').trim(); const unit = String(row['规格'] ?? row['单位'] ?? '').trim() || '斤'; const spec = String(row['规格详情'] ?? '').trim(); const brand = String(row['厂家'] ?? row['品牌'] ?? '').trim(); const key = normalizeName(name); if (!key || excelNames.has(key)) continue; excelNames.add(key); parsed.push({ name, l1, l2, unit, spec, brand, key }); } console.log('unique_products', parsed.length); if (!execute) { console.log('sample', parsed.slice(0, 5)); console.log('\nDRY-RUN 完成。确认后加 --execute'); return; } await client.query('BEGIN'); await client.query(`ALTER TABLE product_catalog DISABLE TRIGGER trg_sync_product_catalog_to_legacy`); const catCache = new Map(); const nameToSku = new Map(); let created = 0; let updated = 0; const existingProducts = await client.query( `SELECT code, name FROM product_catalog WHERE item_type='product' AND branch_code=$1`, [branchCode] ); const existingByName = new Map(); for (const row of existingProducts.rows) { existingByName.set(normalizeName(row.name), row.code); } for (const item of parsed) { const l1Code = await ensureCategory(client, catCache, branchCode, item.l1, null, 1); const categoryCode = item.l2 ? await ensureCategory(client, catCache, branchCode, item.l2, l1Code, 2) : l1Code; const existingCode = existingByName.get(item.key); if (existingCode) { await client.query( `UPDATE product_catalog SET name=$2, parent_code=$3, unit=$4, spec=NULLIF($5,''), brand=NULLIF($6,''), status=1, updated_at=NOW() WHERE code=$1 AND item_type='product'`, [existingCode, item.name, categoryCode, item.unit, item.spec, item.brand] ); await client.query( `UPDATE skus SET category_code=$2, unit=$3, spec=NULLIF($4,''), brand=NULLIF($5,''), sku_name=$6, status=1, branch_code=$7 WHERE sku_code=$1`, [existingCode, categoryCode, item.unit, item.spec, item.brand, item.name, branchCode] ); nameToSku.set(item.key, existingCode); updated += 1; } else { const code = await uniqueCode(client, 'SKU'); 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, NULLIF($5,''), $1, NULLIF($6,''), 5, 0, 0, 1, $7 )`, [code, item.name, categoryCode, item.unit, item.spec, item.brand, branchCode] ); await client.query( `INSERT INTO skus ( branch_code, sku_code, sku_name, category_code, unit, spec, barcode, brand, default_loss_threshold, sale_price, cost_price, status ) VALUES ($1,$2,$3,$4,$5,NULLIF($6,''),$2,NULLIF($7,''),5,0,0,1) ON CONFLICT (sku_code) DO UPDATE SET branch_code=EXCLUDED.branch_code, sku_name=EXCLUDED.sku_name, category_code=EXCLUDED.category_code, unit=EXCLUDED.unit, spec=EXCLUDED.spec, brand=EXCLUDED.brand, status=1`, [branchCode, code, item.name, categoryCode, item.unit, item.spec, item.brand] ); nameToSku.set(item.key, code); existingByName.set(item.key, code); created += 1; } } const keepCodes = [...nameToSku.values()]; const disabled = await client.query( `UPDATE product_catalog SET status=0, updated_at=NOW() WHERE item_type='product' AND branch_code=$1 AND status=1 AND NOT (code = ANY($2::text[])) RETURNING code`, [branchCode, keepCodes] ); if (disabled.rows.length) { await client.query(`UPDATE skus SET status=0 WHERE sku_code = ANY($1::text[])`, [ disabled.rows.map((r) => r.code), ]); } // 报价单按商品名回写到本分公司 sku let remappedItems = 0; let remappedVersions = 0; const quoteItems = await client.query( `SELECT i.id, i.quote_sheet_code, i.sku_code, i.sku_name, i.price FROM customer_quote_sheet_items i JOIN customer_quote_sheets qs ON qs.quote_sheet_code = i.quote_sheet_code WHERE qs.branch_code = $1`, [branchCode] ); for (const item of quoteItems.rows) { const key = normalizeName(item.sku_name); const target = nameToSku.get(key); if (!target || target === item.sku_code) continue; await client.query(`UPDATE customer_quote_sheet_items SET sku_code=$2 WHERE id=$1`, [ item.id, target, ]); remappedItems += 1; } const versions = await client.query( `SELECT quote_version_code, sku_code, customer_code FROM customer_quote_versions WHERE branch_code = $1 AND status = 1`, [branchCode] ); for (const ver of versions.rows) { const prod = await client.query( `SELECT name FROM product_catalog WHERE code=$1 AND item_type='product' LIMIT 1`, [ver.sku_code] ); const name = prod.rows[0]?.name; const target = name ? nameToSku.get(normalizeName(name)) : null; if (!target || target === ver.sku_code) continue; await client.query( `UPDATE customer_quote_versions SET sku_code=$2 WHERE quote_version_code=$1`, [ver.quote_version_code, target] ); remappedVersions += 1; } await client.query(`ALTER TABLE product_catalog ENABLE TRIGGER trg_sync_product_catalog_to_legacy`); await client.query('COMMIT'); const after = await client.query( `SELECT COUNT(*) FILTER (WHERE item_type='product' AND status=1)::int AS active_products, COUNT(*) FILTER (WHERE item_type='product' AND status=0)::int AS disabled_products, COUNT(*) FILTER (WHERE item_type='category')::int AS categories FROM product_catalog WHERE branch_code=$1`, [branchCode] ); console.log('\nresult', { created, updated, disabled: disabled.rowCount || 0, remappedItems, remappedVersions, after: after.rows[0], }); } catch (error) { await client.query('ROLLBACK').catch(() => {}); await client .query(`ALTER TABLE product_catalog ENABLE TRIGGER trg_sync_product_catalog_to_legacy`) .catch(() => {}); throw error; } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });