const { Pool } = require('pg'); const DRY_CATEGORY = process.env.DRY_CATEGORY || 'CAT78659053039'; const BRANCH = process.env.BRANCH_CODE || 'BR002'; /** 录单名称 → 商品主数据名称(可选别名映射) */ const NAME_ALIASES = { 黄灯笼盖辣椒酱: '黄灯笼黄辣椒酱', 干辣椒筒筒: '干海椒筒(中辣)', 干海椒段: '干海椒节', 辣椒段辣的: '海椒节(辣)', }; const TARGET_NAMES = [ '纯牛奶', '豆浆', '干海椒段', '干海椒丝', '干辣椒筒筒', '黄灯笼盖辣椒酱', '辣椒段辣的', ]; async function resolveProduct(client, orderName) { const candidates = [orderName]; if (NAME_ALIASES[orderName]) candidates.push(NAME_ALIASES[orderName]); for (const name of candidates) { const exact = await client.query( `SELECT code, name, parent_code, branch_code FROM product_catalog WHERE item_type = 'product' AND TRIM(name) = TRIM($1) ORDER BY CASE WHEN branch_code = $2 THEN 0 ELSE 1 END, updated_at DESC NULLS LAST LIMIT 1`, [name, BRANCH] ); if (exact.rowCount) return { row: exact.rows[0], matchedName: name, orderName }; } const fuzzy = await client.query( `SELECT code, name, parent_code, branch_code FROM product_catalog WHERE item_type = 'product' AND branch_code = $2 AND name ILIKE $1 ORDER BY length(name) ASC, updated_at DESC NULLS LAST LIMIT 1`, [`%${orderName.replace(/[%_]/g, '')}%`, BRANCH] ); if (fuzzy.rowCount) return { row: fuzzy.rows[0], matchedName: fuzzy.rows[0].name, orderName }; return { row: null, matchedName: null, orderName }; } async function syncCategory(client, skuCode, categoryCode) { await client.query( `UPDATE product_catalog SET parent_code = $2, updated_at = NOW() WHERE item_type = 'product' AND code = $1`, [skuCode, categoryCode] ); await client.query( `UPDATE skus SET category_code = $2 WHERE sku_code = $1`, [skuCode, categoryCode] ); } async function createProduct(client, name, categoryCode, branchCode) { const skuCode = `SKU${Date.now()}${Math.floor(Math.random() * 1000)}`; const barcode = skuCode; await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, unit, barcode, cost_price, sale_price, status, branch_code ) VALUES ('product', $1, $2, $3, '斤', $4, 0, 0, 1, $5)`, [skuCode, name, categoryCode, barcode, branchCode] ); await client.query( `INSERT INTO skus (sku_code, sku_name, category_code, unit, barcode, status, branch_code) VALUES ($1, $2, $3, '斤', $4, 1, $5) ON CONFLICT (sku_code) DO UPDATE SET sku_name = EXCLUDED.sku_name, category_code = EXCLUDED.category_code, unit = EXCLUDED.unit, branch_code = COALESCE(skus.branch_code, EXCLUDED.branch_code)`, [skuCode, name, categoryCode, barcode, branchCode] ); return { code: skuCode, name, parent_code: categoryCode, branch_code: branchCode }; } async function main() { const dryRun = process.argv.includes('--dry-run'); const createMissing = process.argv.includes('--create-missing'); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { const cat = await client.query( `SELECT category_code, category_name FROM categories WHERE category_code = $1 LIMIT 1`, [DRY_CATEGORY] ); if (!cat.rowCount) throw new Error(`分类不存在: ${DRY_CATEGORY}`); console.log(`目标分类: ${cat.rows[0].category_name} (${DRY_CATEGORY})`); await client.query('BEGIN'); const results = []; for (const orderName of TARGET_NAMES) { const { row, matchedName } = await resolveProduct(client, orderName); if (!row) { if (createMissing) { if (dryRun) { results.push({ orderName, status: 'would_create' }); continue; } const created = await createProduct(client, orderName, DRY_CATEGORY, BRANCH); results.push({ orderName, skuCode: created.code, catalogName: created.name, matchedName: created.name, previousCategory: null, status: 'created', }); continue; } results.push({ orderName, status: 'not_found' }); continue; } const already = row.parent_code === DRY_CATEGORY; if (!dryRun && !already) { await syncCategory(client, row.code, DRY_CATEGORY); } results.push({ orderName, skuCode: row.code, catalogName: row.name, matchedName, previousCategory: row.parent_code, status: already ? 'already_dry_goods' : dryRun ? 'would_update' : 'updated', }); } if (dryRun) await client.query('ROLLBACK'); else await client.query('COMMIT'); console.log(JSON.stringify(results, null, 2)); const missing = results.filter((r) => r.status === 'not_found'); if (missing.length) { console.error(`未找到 ${missing.length} 个商品:`, missing.map((r) => r.orderName).join(', ')); process.exitCode = 1; } } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });