#!/usr/bin/env node /** * 将 Excel 全部字段同步进商品库 + 报价单明细: * 商品名、分类、二级分类、规格(单位)、厂家(品牌)、规格详情、销售价格、成本价 * * node scripts/sync-luzhou-excel-full.cjs --file rows.json --sheet QS... --branch BR002 --execute */ const fs = require('fs'); const path = require('path'); const pgPath = fs.existsSync('/opt/ai-fresh-delivery/server/node_modules/pg') ? '/opt/ai-fresh-delivery/server/node_modules/pg' : path.join(__dirname, '../server/node_modules/pg'); const dotenvPath = fs.existsSync('/opt/ai-fresh-delivery/server/node_modules/dotenv') ? '/opt/ai-fresh-delivery/server/node_modules/dotenv' : path.join(__dirname, '../server/node_modules/dotenv'); const envFile = fs.existsSync('/opt/ai-fresh-delivery/server/.env') ? '/opt/ai-fresh-delivery/server/.env' : path.join(__dirname, '../server/.env'); const { Pool } = require(pgPath); const dotenv = require(dotenvPath); dotenv.config({ path: envFile }); const args = process.argv.slice(2); const execute = args.includes('--execute'); const dryRun = !execute; const filePath = args[args.indexOf('--file') + 1]; const sheetCode = args.includes('--sheet') ? args[args.indexOf('--sheet') + 1] : 'QS17838668334475C5C'; const branchCode = args.includes('--branch') ? args[args.indexOf('--branch') + 1] : 'BR002'; function normalizeName(value) { return String(value ?? '') .trim() .replace(/\s+/g, '') .replace(/(/g, '(') .replace(/)/g, ')'); } function cleanText(value) { const text = String(value ?? '').trim(); if (!text || text === '-' || text === '—' || text === '/') return ''; return text; } 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()}`; } async function ensureCategory(client, categories, l1Name, l2Name) { let l1 = categories.find((c) => !c.parent_code && normalizeName(c.name) === normalizeName(l1Name)); if (!l1) { const code = await generateUniqueCode(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, NULL, 1, 0, 5, true, 1, $3)`, [code, l1Name, branchCode] ); l1 = { code, name: l1Name, parent_code: null }; categories.push(l1); } if (!l2Name) return l1.code; let l2 = categories.find( (c) => c.parent_code === l1.code && normalizeName(c.name) === normalizeName(l2Name) ); if (!l2) { const code = await generateUniqueCode(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, 2, 0, 5, false, 1, $4)`, [code, l2Name, l1.code, branchCode] ); l2 = { code, name: l2Name, parent_code: l1.code }; categories.push(l2); } return l2.code; } async function main() { if (!process.env.DATABASE_URL) throw new Error('缺少 DATABASE_URL'); if (!filePath) throw new Error('请指定 --file'); const rows = JSON.parse(fs.readFileSync(path.resolve(filePath), 'utf8')); const excelMap = new Map(); for (const row of rows) { const name = String(row['商品名'] ?? row['商品名称'] ?? '').trim(); if (!name) continue; if (name.includes('AI生成') || name.includes('仅供参考')) continue; const sale = Number(row['销售价格'] ?? row['销售价'] ?? row['售价']); const cost = Number(row['成本价'] ?? row['采购价']); if (!(Number.isFinite(sale) && sale > 0)) continue; excelMap.set(normalizeName(name), { name, l1: cleanText(row['分类'] ?? row['一级分类']), l2: cleanText(row['二级分类']), unit: cleanText(row['规格'] ?? row['单位']) || '斤', brand: cleanText(row['厂家'] ?? row['品牌']), spec: cleanText(row['规格详情']), sale_price: sale, cost_price: Number.isFinite(cost) && cost >= 0 ? cost : 0, }); } const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { console.log(`\n=== 全字段同步 (${dryRun ? 'DRY-RUN' : 'EXECUTE'}) ===`); console.log({ sheetCode, branchCode, excelRows: excelMap.size }); const items = await client.query( `SELECT i.id, i.sku_code, i.sku_name FROM customer_quote_sheet_items i WHERE i.quote_sheet_code = $1`, [sheetCode] ); const catRes = await client.query( `SELECT code, name, parent_code FROM product_catalog WHERE item_type = 'category' AND branch_code = $1`, [branchCode] ); const categories = catRes.rows.map((r) => ({ ...r })); const matched = []; const unmatchedQuote = []; for (const item of items.rows) { const meta = excelMap.get(normalizeName(item.sku_name)); if (!meta) { unmatchedQuote.push(item.sku_name); continue; } matched.push({ ...item, ...meta }); excelMap.delete(normalizeName(item.sku_name)); } const excelOnly = [...excelMap.values()]; console.log({ quoteItems: items.rows.length, matched: matched.length, unmatchedQuote: unmatchedQuote.length, excelOnlyNotInQuote: excelOnly.length, excelOnlySample: excelOnly.slice(0, 10).map((x) => x.name), }); if (dryRun) { console.log('sample', matched.slice(0, 3)); console.log('\nDRY-RUN 完成'); return; } await client.query('BEGIN'); let updatedProducts = 0; let updatedQuoteItems = 0; let createdProducts = 0; try { for (const row of matched) { if (!row.l1) throw new Error(`商品「${row.name}」缺少分类`); const categoryCode = await ensureCategory(client, categories, row.l1, row.l2); await client.query( `UPDATE product_catalog SET parent_code = $2, unit = $3, spec = NULLIF($4, ''), brand = NULLIF($5, ''), sale_price = $6, cost_price = $7, updated_at = NOW() WHERE item_type = 'product' AND code = $1`, [row.sku_code, categoryCode, row.unit, row.spec, row.brand, row.sale_price, row.cost_price] ); await client.query( `UPDATE skus SET category_code = $2, unit = $3, spec = NULLIF($4, ''), brand = NULLIF($5, ''), sale_price = $6, cost_price = $7 WHERE sku_code = $1`, [row.sku_code, categoryCode, row.unit, row.spec, row.brand, row.sale_price, row.cost_price] ); updatedProducts += 1; await client.query( `UPDATE customer_quote_sheet_items SET sku_name = $2, unit = $3, price = $4, sale_price = $4, cost_price = $5 WHERE id = $1`, [row.id, row.name, row.unit, row.sale_price, row.cost_price] ); updatedQuoteItems += 1; } // Excel 有但报价单没有的:建品并加入报价单 for (const row of excelOnly) { if (!row.l1) continue; const categoryCode = await ensureCategory(client, categories, row.l1, row.l2); const skuCode = await generateUniqueCode(client, 'SKU'); await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, unit, spec, brand, sale_price, cost_price, status, branch_code ) VALUES ('product', $1, $2, $3, $4, NULLIF($5,''), NULLIF($6,''), $7, $8, 1, $9)`, [ skuCode, row.name, categoryCode, row.unit, row.spec, row.brand, row.sale_price, row.cost_price, branchCode, ] ); const sort = await client.query( `SELECT COALESCE(MAX(sort_order), -1) + 1 AS n FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [sheetCode] ); await client.query( `INSERT INTO customer_quote_sheet_items (quote_sheet_code, sku_code, sku_name, unit, price, cost_price, sale_price, sort_order) VALUES ($1,$2,$3,$4,$5,$6,$5,$7)`, [ sheetCode, skuCode, row.name, row.unit, row.sale_price, row.cost_price, Number(sort.rows[0].n) || 0, ] ); createdProducts += 1; } await client.query('COMMIT'); } catch (error) { await client.query('ROLLBACK'); throw error; } const check = await pool.query( `SELECT COUNT(*)::int AS items, COUNT(*) FILTER (WHERE COALESCE(s.category_code,'')='')::int AS no_cat, COUNT(*) FILTER (WHERE COALESCE(s.brand,'')='' AND i.sku_name ILIKE '%伊利%')::int AS yili_no_brand FROM customer_quote_sheet_items i JOIN skus s ON s.sku_code = i.sku_code WHERE i.quote_sheet_code = $1`, [sheetCode] ); const egg = await pool.query( `SELECT i.sku_name, i.unit, i.cost_price, i.sale_price, s.cost_price AS sku_cost, s.sale_price AS sku_sale, s.brand, s.spec, c.name AS cat FROM customer_quote_sheet_items i JOIN skus s ON s.sku_code = i.sku_code LEFT JOIN product_catalog c ON c.code = s.category_code WHERE i.quote_sheet_code = $1 AND i.sku_name IN ('鸡蛋','伊利奶粉','半成品尖白菜') ORDER BY i.sku_name`, [sheetCode] ); console.log('\ndone', { updatedProducts, updatedQuoteItems, createdProducts, check: check.rows[0], sample: egg.rows, }); } finally { client.release(); await pool.end(); } } main().catch((e) => { console.error(e); process.exit(1); });