#!/usr/bin/env node /** * 按 Excel JSON 回填报价单商品分类(及规格/品牌),并确保一级/二级分类存在。 * * node scripts/backfill-quote-product-categories.cjs --file rows.json --sheet QS... --branch BR002 --dry-run * node scripts/backfill-quote-product-categories.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 fileArgIdx = args.indexOf('--file'); const sheetArgIdx = args.indexOf('--sheet'); const branchArgIdx = args.indexOf('--branch'); const filePath = fileArgIdx >= 0 ? args[fileArgIdx + 1] : null; const sheetCode = sheetArgIdx >= 0 ? args[sheetArgIdx + 1] : 'QS17838668334475C5C'; const branchCode = branchArgIdx >= 0 ? args[branchArgIdx + 1] : 'BR002'; function normalizeName(value) { return String(value ?? '') .trim() .replace(/\s+/g, '') .replace(/(/g, '(') .replace(/)/g, ')'); } function cleanCategoryName(value) { const name = String(value ?? '').trim(); if (!name || name === '-' || name === '—' || name === '/') return ''; return name; } 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) { const created = []; 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, level: 1 }; categories.push(l1); created.push(l1Name); } if (!l2Name) return { categoryCode: l1.code, created }; 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, level: 2 }; categories.push(l2); created.push(`${l1Name}/${l2Name}`); } return { categoryCode: l2.code, created }; } 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 byName = new Map(); for (const row of rows) { const name = String(row['商品名'] ?? row['商品名称'] ?? '').trim(); if (!name) continue; byName.set(normalizeName(name), { name, l1: cleanCategoryName(row['分类'] ?? row['一级分类']), l2: cleanCategoryName(row['二级分类']), brand: cleanCategoryName(row['厂家'] ?? row['品牌']), spec: cleanCategoryName(row['规格详情']), unit: String(row['规格'] ?? row['单位'] ?? '').trim() || null, }); } 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, excelNames: byName.size }); const items = await client.query( `SELECT i.sku_code, i.sku_name, s.category_code, pc.parent_code AS catalog_parent FROM customer_quote_sheet_items i LEFT JOIN skus s ON s.sku_code = i.sku_code LEFT JOIN product_catalog pc ON pc.code = i.sku_code AND pc.item_type = 'product' WHERE i.quote_sheet_code = $1 ORDER BY i.sort_order, i.sku_code`, [sheetCode] ); const catRes = await client.query( `SELECT code, name, parent_code, level FROM product_catalog WHERE item_type = 'category' AND branch_code = $1`, [branchCode] ); const categories = catRes.rows.map((r) => ({ ...r })); const plan = []; let missingExcel = 0; let alreadyOk = 0; for (const item of items.rows) { const meta = byName.get(normalizeName(item.sku_name)); if (!meta || !meta.l1) { missingExcel += 1; continue; } const current = item.category_code || item.catalog_parent || ''; plan.push({ sku_code: item.sku_code, sku_name: item.sku_name, current, l1: meta.l1, l2: meta.l2, brand: meta.brand, spec: meta.spec, unit: meta.unit, }); } console.log('plan', { quoteItems: items.rows.length, toUpdate: plan.length, missingExcel, sample: plan.filter((p) => !p.current).slice(0, 8), }); if (dryRun) { console.log('\nDRY-RUN 完成。加 --execute 写入分类。'); return; } await client.query('BEGIN'); const createdCats = []; let updated = 0; try { for (const row of plan) { const { categoryCode, created } = await ensureCategory(client, categories, row.l1, row.l2); createdCats.push(...created); await client.query( `UPDATE product_catalog SET parent_code = $2, brand = COALESCE(NULLIF($3, ''), brand), spec = COALESCE(NULLIF($4, ''), spec), unit = COALESCE(NULLIF($5, ''), unit), updated_at = NOW() WHERE item_type = 'product' AND code = $1`, [row.sku_code, categoryCode, row.brand || '', row.spec || '', row.unit || ''] ); // 兼容:若 trigger 未同步 category,再显式更新 skus await client.query( `UPDATE skus SET category_code = $2, brand = COALESCE(NULLIF($3, ''), brand), spec = COALESCE(NULLIF($4, ''), spec), unit = COALESCE(NULLIF($5, ''), unit) WHERE sku_code = $1`, [row.sku_code, categoryCode, row.brand || '', row.spec || '', row.unit || ''] ); updated += 1; } await client.query('COMMIT'); } catch (error) { await client.query('ROLLBACK'); throw error; } const check = await pool.query( `SELECT COUNT(*)::int AS n, COUNT(*) FILTER (WHERE COALESCE(s.category_code,'')='')::int AS no_cat FROM customer_quote_sheet_items i JOIN skus s ON s.sku_code = i.sku_code WHERE i.quote_sheet_code = $1`, [sheetCode] ); console.log('\ndone', { updated, categoriesCreated: [...new Set(createdCats)], quote_items: check.rows[0], }); } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });