#!/usr/bin/env node /** * 从预解析的 JSON(Excel 行)在生产库创建并激活泸州报价单。 * 用法(生产机): * node import-luzhou-quote-from-json.cjs --file rows.json --branch BR002 --dry-run * node import-luzhou-quote-from-json.cjs --file rows.json --branch BR002 --execute * node import-luzhou-quote-from-json.cjs --file rows.json --branch BR002 --execute --create-missing */ 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 createMissing = args.includes('--create-missing'); const fileArgIdx = args.indexOf('--file'); const branchArgIdx = args.indexOf('--branch'); const customerArgIdx = args.indexOf('--customer'); const titleArgIdx = args.indexOf('--title'); const cycleArgIdx = args.indexOf('--cycle'); const filePath = fileArgIdx >= 0 ? args[fileArgIdx + 1] : null; const branchOverride = branchArgIdx >= 0 ? args[branchArgIdx + 1] : 'BR002'; const customerOverride = customerArgIdx >= 0 ? args[customerArgIdx + 1] : null; const titleOverride = titleArgIdx >= 0 ? args[titleArgIdx + 1] : null; const quoteCycle = cycleArgIdx >= 0 ? args[cycleArgIdx + 1] : 'month'; const DEFAULT_LUZHOU_CUSTOMER_NAME = '泸州市邮政分公司'; 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 newSheetCode() { return `QS${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`; } function newQuoteVersionCode() { return `QV${Date.now()}${Math.random().toString(36).slice(2, 8).toUpperCase()}`; } function computeExpiresAt(from, cycle) { const daysMap = { week: 7, half_month: 15, month: 30, half_year: 180, year: 365 }; const days = daysMap[cycle] || 30; return new Date(from.getTime() + days * 86400000); } 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 ensureCategoryChain(client, categories, branchCode, l1Name, l2Name) { const trimmedL1 = String(l1Name || '').trim(); const trimmedL2 = String(l2Name || '').trim(); if (!trimmedL1) return null; let l1 = categories.find( (c) => !c.parent_code && String(c.name).trim() === trimmedL1 ); 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, trimmedL1, branchCode] ); l1 = { code, name: trimmedL1, parent_code: null }; categories.push(l1); } if (!trimmedL2) return l1.code; let l2 = categories.find( (c) => c.parent_code === l1.code && String(c.name).trim() === trimmedL2 ); 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, trimmedL2, l1.code, branchCode] ); l2 = { code, name: trimmedL2, parent_code: l1.code }; categories.push(l2); } return l2.code; } async function nextSheetVersionNo(client, branchCode) { const r = await client.query( `SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version FROM customer_quote_sheets WHERE branch_code = $1`, [branchCode] ); return Number(r.rows[0]?.next_version) || 1; } async function activateQuoteSheet(client, quoteSheetCode) { const result = await client.query( `UPDATE customer_quote_sheets SET approval_status = 30, approved_at = NOW(), status = 1, effective_at = COALESCE(effective_at, NOW()), expires_at = COALESCE(expires_at, NOW() + INTERVAL '30 days'), updated_at = NOW() WHERE quote_sheet_code = $1 RETURNING *`, [quoteSheetCode] ); if (!result.rows.length) throw new Error(`报价单不存在: ${quoteSheetCode}`); const sheet = result.rows[0]; await client.query( `UPDATE customer_quote_sheets SET status = 3, updated_at = NOW() WHERE quote_sheet_code <> $1 AND status = 1 AND approval_status = 30 AND branch_code IS NOT DISTINCT FROM $2 AND quote_sheet_code IN ( SELECT qsc1.quote_sheet_code FROM customer_quote_sheet_customers qsc1 WHERE qsc1.customer_code IN ( SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1 ) )`, [quoteSheetCode, sheet.branch_code] ); const [itemsResult, customersResult] = await Promise.all([ client.query(`SELECT * FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [quoteSheetCode]), client.query( `SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`, [quoteSheetCode] ), ]); for (const customerRow of customersResult.rows) { const customerCode = customerRow.customer_code; for (const item of itemsResult.rows) { const versionResult = await client.query( `SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version FROM customer_quote_versions WHERE customer_code = $1 AND sku_code = $2`, [customerCode, item.sku_code] ); const versionNo = Number(versionResult.rows[0]?.next_version) || 1; const salePrice = Number(item.sale_price ?? item.price) || 0; await client.query( `UPDATE customer_quote_versions SET status = 0, expired_at = NOW() WHERE customer_code = $1 AND sku_code = $2 AND status = 1 AND branch_code IS NOT DISTINCT FROM $3`, [customerCode, item.sku_code, sheet.branch_code] ); await client.query( `INSERT INTO customer_quote_versions (quote_version_code, customer_code, sku_code, unit, price, version_no, source_type, branch_code, status, approval_status, quote_cycle, expires_at, effective_at, quote_sheet_code, approved_at) VALUES ($1,$2,$3,$4,$5,$6,'quote_sheet',$7,1,30,$8,$9,NOW(),$10,NOW())`, [ newQuoteVersionCode(), customerCode, item.sku_code, item.unit, salePrice, versionNo, sheet.branch_code, sheet.quote_cycle, sheet.expires_at, quoteSheetCode, ] ); } } return sheet; } async function main() { if (!process.env.DATABASE_URL) throw new Error('缺少 DATABASE_URL'); if (!filePath) throw new Error('请指定 --file rows.json'); const rows = JSON.parse(fs.readFileSync(path.resolve(filePath), 'utf8')).filter(isDataRow); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { console.log(`\n=== 泸州报价单导入 (${dryRun ? 'DRY-RUN' : 'EXECUTE'}) ===\n`); console.log('file', path.resolve(filePath)); console.log('excel_rows', rows.length); let branchCode = branchOverride; const br = await client.query( `SELECT branch_code, branch_name FROM branches WHERE branch_code = $1`, [branchCode] ); console.log('branch', br.rows[0] || { branch_code: branchCode }); let customer; if (customerOverride) { const c = await client.query( `SELECT customer_code, company_name, branch_code, status FROM customers WHERE customer_code = $1`, [customerOverride] ); customer = c.rows[0]; } else { const c = await client.query( `SELECT customer_code, company_name, branch_code, status FROM customers WHERE company_name ILIKE $1 ORDER BY CASE WHEN branch_code = $2 THEN 0 ELSE 1 END, customer_code LIMIT 1`, [`%${DEFAULT_LUZHOU_CUSTOMER_NAME}%`, branchCode] ); customer = c.rows[0]; } if (!customer) throw new Error('未找到泸州客户,请用 --customer 指定'); if (customer.branch_code && customer.branch_code !== branchCode) { console.log('align_branch_to_customer', customer.branch_code); branchCode = customer.branch_code; } console.log('customer', customer); console.log('branch_code', branchCode); // Prefer branch-scoped SKUs; fall back to shared (NULL) if column exists let skus; try { skus = await client.query( `SELECT sku_code, sku_name, unit, branch_code, status FROM skus WHERE status = 1 AND (branch_code IS NULL OR branch_code = $1)`, [branchCode] ); } catch (err) { if (err && err.code === '42703') { skus = await client.query( `SELECT sku_code, sku_name, unit, NULL::text AS branch_code, status FROM skus WHERE status = 1` ); } else { throw err; } } const byName = new Map(); for (const sku of skus.rows) { const key = normalizeName(sku.sku_name); if (!key) continue; if (!byName.has(key)) byName.set(key, []); byName.get(key).push(sku); } const items = []; const missing = []; const noPrice = []; const ambiguous = []; for (const row of rows) { const name = String(row['商品名'] ?? row['商品名称'] ?? '').trim(); const key = normalizeName(name); const unit = String(row['规格'] ?? row['单位'] ?? '').trim() || '斤'; const salePrice = Number(row['销售价'] ?? row['销售价格'] ?? row['售价']); const costPrice = Number(row['成本价'] ?? row['采购价']); const categoryL1 = String(row['分类'] ?? row['一级分类'] ?? '').trim(); const categoryL2Raw = String(row['二级分类'] ?? '').trim(); const categoryL2 = !categoryL2Raw || categoryL2Raw === '-' || categoryL2Raw === '—' ? '' : categoryL2Raw; const brand = String(row['厂家'] ?? row['品牌'] ?? '').trim(); const spec = String(row['规格详情'] ?? '').trim(); if (!(Number.isFinite(salePrice) && salePrice > 0)) { noPrice.push(name); continue; } const matches = byName.get(key) || []; if (!matches.length) { missing.push({ name, unit, salePrice, costPrice, categoryL1, categoryL2, brand: brand && brand !== '-' ? brand : '', spec: spec && spec !== '-' ? spec : '', }); continue; } if (matches.length > 1) { // Prefer exact branch match matches.sort((a, b) => { const aBranch = a.branch_code === branchCode ? 0 : 1; const bBranch = b.branch_code === branchCode ? 0 : 1; return aBranch - bBranch; }); ambiguous.push({ name, codes: matches.map((m) => m.sku_code) }); } const sku = matches[0]; items.push({ sku_code: sku.sku_code, sku_name: sku.sku_name || name, unit: unit || sku.unit || '斤', sale_price: salePrice, cost_price: Number.isFinite(costPrice) && costPrice > 0 ? costPrice : 0, price: salePrice, }); } const itemMap = new Map(); for (const item of items) itemMap.set(item.sku_code, item); const uniqueItems = [...itemMap.values()]; console.log('\nmatch_summary', { excelRows: rows.length, withSalePrice: rows.length - noPrice.length, matched: uniqueItems.length, missing: missing.length, noPrice: noPrice.length, ambiguous: ambiguous.length, }); if (missing.length) console.log('missing_sample', missing.slice(0, 20)); if (ambiguous.length) console.log('ambiguous_sample', ambiguous.slice(0, 10)); console.log('item_sample', uniqueItems.slice(0, 5)); if (!uniqueItems.length && !(createMissing && missing.length)) { throw new Error('没有可写入的报价行(需销售价>0 且能匹配到 SKU)'); } if (dryRun) { console.log('\nDRY-RUN 完成。确认后加 --execute 创建并激活报价单。'); if (missing.length && !createMissing) { console.log(`提示: ${missing.length} 个商品未匹配,可加 --create-missing 自动建品后再报价。`); } return; } await client.query('BEGIN'); try { if (createMissing && missing.length) { 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 })); for (const m of missing) { const skuCode = await generateUniqueCode(client, 'SKU'); const parentCode = await ensureCategoryChain( client, categories, branchCode, m.categoryL1, m.categoryL2 ); 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, m.name, parentCode, m.unit, m.spec || '', m.brand || '', m.salePrice, m.costPrice || 0, branchCode, ] ); uniqueItems.push({ sku_code: skuCode, sku_name: m.name, unit: m.unit, sale_price: m.salePrice, cost_price: m.costPrice || 0, price: m.salePrice, }); } console.log('created_missing_products', missing.length); } const versionNo = await nextSheetVersionNo(client, branchCode); const quoteSheetCode = newSheetCode(); const effectiveAt = new Date(); const expiresAt = computeExpiresAt(effectiveAt, quoteCycle); const title = titleOverride?.trim() || `泸州报价单(Excel导入) V${versionNo}`; await client.query( `INSERT INTO customer_quote_sheets (quote_sheet_code, title, version_no, quote_cycle, effective_at, expires_at, status, approval_status, branch_code, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, 0, 10, $7, NOW(), NOW())`, [ quoteSheetCode, title, versionNo, quoteCycle, effectiveAt.toISOString(), expiresAt.toISOString(), branchCode, ] ); await client.query( `INSERT INTO customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`, [quoteSheetCode, customer.customer_code] ); for (let i = 0; i < uniqueItems.length; i += 1) { const item = uniqueItems[i]; 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, $7, $8)`, [ quoteSheetCode, item.sku_code, item.sku_name, item.unit, item.sale_price, item.cost_price, item.sale_price, i, ] ); } await activateQuoteSheet(client, quoteSheetCode); await client.query('COMMIT'); const versions = await pool.query( `SELECT COUNT(*)::int AS n FROM customer_quote_versions WHERE quote_sheet_code = $1 AND status = 1`, [quoteSheetCode] ); console.log('\ncreated', { quoteSheetCode, title, branchCode, customer: customer.company_name, customerCode: customer.customer_code, items: uniqueItems.length, activeVersions: versions.rows[0].n, expiresAt: expiresAt.toISOString(), }); } catch (error) { await client.query('ROLLBACK'); throw error; } } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });