#!/usr/bin/env node /** * 从「商品编码.xlsx」(增值税税收分类编码)匹配商品库,写入 tax_code,并修正明显错字名称。 * * 用法: * node server/scripts/sync-tax-codes-from-xlsx.cjs --xlsx "C:/Users/ADMIN/Desktop/商品编码.xlsx" --dry-run * DATABASE_URL=... node server/scripts/sync-tax-codes-from-xlsx.cjs --xlsx "..." --apply */ const fs = require('fs'); const path = require('path'); const XLSX = require('xlsx'); const pg = require('pg'); /** 已知错字 → 正确写法(仅改明显笔误,不改俗称别名) */ const TYPO_RENAMES = new Map([ ['豆办酱', '豆瓣酱'], ['教头', '藠头'], ]); /** 分类 → 默认税收编码(货物和劳务名称须与 xlsx 一致) */ const CATEGORY_TAX_NAME = { 叶菜类: '芹菜等叶菜类蔬菜', 根菜类: '萝卜等根菜类蔬菜', 瓜类: '瓜类蔬菜', 茄果类: '番茄等茄果类蔬菜', 葱蒜类: '葱蒜类蔬菜', 白菜类: '白菜类蔬菜', 芥菜类: '芥菜类蔬菜', 甘蓝类: '甘蓝类蔬菜', 豆类: '菜豆等豆类蔬菜', 干豆类: '干豆类', 薯类: '山药等薯芋类蔬菜', 芋类: '山药等薯芋类蔬菜', 水生类: '淡水鱼', 水产类: '淡水鱼', 食用菌: '香菇等食用菌', 菌类: '香菇等食用菌', 菌菇类: '香菇等食用菌', 豆制品: '豆腐及豆制品', 猪类: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 牛类: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 兔类: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 鸡类: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 鸭类: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 家禽: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 肉类: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 耳片: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', 冻货: '冷冻水产品', 鸡蛋: '鸡蛋', 蛋类: '禽蛋', 再制蛋: '蛋制品', 水果: '其他未列明水果', 坚果类: '其他食用坚果', 调味品: '调味品', 调料: '调味品', 香料: '调味品', 酱油: '酱油及酱类制品', 醋: '醋及醋代用品', 酱: '酱油及酱类制品', 糖类: '成品糖', 粮油: '大米', 谷物: '大米', 谷物类: '大米', 粉类: '其他谷物细粉', 生粉面粉: '小麦粉', 面食: '米、面制半成品', 糕点: '糕点', 腌菜类: '腌渍菜', 泡菜: '腌渍菜', 榨菜: '腌渍菜', 浓汤: '调味品', 火锅料: '复合调味品', 卤货: '酱卤烧烤肉制品', 豆豉类: '酱油及酱类制品', 粉条: '淀粉及淀粉制品', 小米辣: '调味品', 花草类: '蔬菜及食用菌', 自采: '蔬菜及食用菌', 干杂: '调味品', 杂类: '调味品', 其他: '蔬菜及食用菌', '(无分类)': '蔬菜及食用菌', 香油: '食用植物油及食用植物油脂', 芽菜: '腌渍菜', 紫菜: '干制水产品', }; /** 名称关键词 → 税收条目名称(按数组顺序,先匹配先生效) */ const NAME_TAX_RULES = [ { keywords: ['一次性筷子'], taxName: '木制一次性筷子' }, { keywords: ['筷子'], taxName: '木制一次性筷子' }, { keywords: ['打包盒', '圆盒', '纸碗', '土碗', '毛边锅'], taxName: '塑料作面类似箱、包容器' }, { keywords: ['抄手皮', '饺子皮', '馄饨皮'], taxName: '米、面制半成品' }, { keywords: ['抄手', '水饺', '馄饨', '包子', '馒头', '面条', '挂面', '水面'], taxName: '米、面制半成品' }, { keywords: ['糯米粉', '面粉', '生粉', '淀粉'], taxName: '其他谷物细粉' }, { keywords: ['大米', '糯米', '小米', '玉米'], taxName: '大米' }, { keywords: ['食用油', '菜籽油', '调和油', '色拉油', '葵花油', '橄榄油', '油碟', '火锅油'], taxName: '食用植物油及食用植物油脂' }, { keywords: ['香油', '芝麻油', '麻油'], taxName: '食用植物油及食用植物油脂' }, { keywords: ['鸡汁', '椒麻', '麻辣', '底料', '酱汁', '蘸料', '干锅酱'], taxName: '调味品' }, { keywords: ['豆瓣', '豆豉', '酱油', '生抽', '老抽', '蚝油', '料酒', '味精', '鸡精', '火锅底料', '沙拉酱'], taxName: '调味品' }, { keywords: ['醋'], taxName: '醋及醋代用品' }, { keywords: ['盐'], taxName: '加工盐' }, { keywords: ['白糖', '冰糖', '红糖'], taxName: '成品糖' }, { keywords: ['花生', '核桃', '松子', '夏威夷果', '巴旦木', '腰果', '开心果'], taxName: '其他食用坚果' }, { keywords: ['鲍鱼'], taxName: '海水贝类' }, { keywords: ['虾', '蟹', '贝', '鱿鱼', '墨鱼', '带鱼', '黄鱼', '鲈鱼', '鲫鱼', '草鱼', '鲢鱼'], taxName: '淡水鱼' }, { keywords: ['咸蛋黄', '蛋黄'], taxName: '蛋制品' }, { keywords: ['肋排', '猪脸', '猪头皮', '仔猪', '排骨', '五花', '里脊', '猪蹄', '碎肉', '肉丝', '肉片', '内脏', '肝', '腰', '肚', '耳', '血'], taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉' }, { keywords: ['鸡', '鸭', '鹅', '鸽'], taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉' }, { keywords: ['豆腐', '豆干', '豆皮', '腐竹', '豆泡'], taxName: '豆腐及豆制品' }, { keywords: ['鸡蛋', '鸭蛋', '鹅蛋', '鹌鹑蛋'], taxName: '鸡蛋' }, { keywords: ['橙', '桔', '橘', '柚', '柠檬', '青桔'], taxName: '柑橘类水果' }, { keywords: ['苹果', '梨', '桃', '葡萄', '西瓜', '哈密瓜', '香蕉', '芒果'], taxName: '其他未列明水果' }, { keywords: ['蘑菇', '香菇', '平菇', '金针菇', '木耳', '银耳'], taxName: '香菇等食用菌' }, { keywords: ['榨菜', '泡菜', '腌菜', '芽菜', '咸菜'], taxName: '腌渍菜' }, { keywords: ['姜', '蒜', '葱', '洋葱', '圆葱', '藠头', '教头', '韭菜', '香菜', '芹菜', '菠菜', '生菜', '油麦', '空心菜', '豌豆尖', '菜心'], taxName: '葱蒜类蔬菜' }, { keywords: ['土豆', '萝卜', '胡萝卜', '莲藕', '山药', '红薯', '芋头'], taxName: '萝卜等根菜类蔬菜' }, { keywords: ['黄瓜', '冬瓜', '南瓜', '丝瓜', '苦瓜', '西葫芦'], taxName: '瓜类蔬菜' }, { keywords: ['番茄', '茄子', '青椒', '辣椒', '西红柿'], taxName: '番茄等茄果类蔬菜' }, { keywords: ['白菜', '娃娃菜', '包菜', '甘蓝'], taxName: '白菜类蔬菜' }, ]; function parseArgs(argv) { const args = { dryRun: true, xlsx: '', databaseUrl: process.env.DATABASE_URL || '' }; for (let i = 2; i < argv.length; i += 1) { const a = argv[i]; if (a === '--apply') args.dryRun = false; else if (a === '--dry-run') args.dryRun = true; else if (a === '--xlsx') args.xlsx = argv[++i] || ''; else if (a === '--database-url') args.databaseUrl = argv[++i] || ''; } return args; } function normalizeName(value) { return String(value || '') .trim() .replace(/\s+/g, '') .replace(/[()()]/g, '') .toLowerCase(); } /** 去掉品牌、规格、重量,保留核心品名用于匹配 */ function coreName(raw) { let s = String(raw || '').trim(); s = s.replace(/[((][^))]*[))]/g, ''); s = s.replace(/\d+(\.\d+)?\s*(kg|g|ml|l|斤|两|升|毫升|克|千克|包|袋|箱|瓶|桶|件|个|只|条|根|把|捆|盒|罐|听|支|卷|板|片|块|颗|粒|枚)/gi, ''); s = s.replace(/\d+$/, ''); return s.trim(); } function loadTaxCatalog(xlsxPath) { const wb = XLSX.readFile(xlsxPath); const sheet = wb.Sheets[wb.SheetNames[0]]; const rows = XLSX.utils.sheet_to_json(sheet, { defval: '' }); const entries = []; const byName = new Map(); const byNorm = new Map(); for (const row of rows) { const code = String(row['合并编码'] || '').trim(); const name = String(row['货物和劳务名称'] || '').trim(); if (!code || !name) continue; if (!/^\d{15,22}$/.test(code)) continue; const entry = { tax_code: code, name, short_name: String(row['商品和服务分类简称'] || '').trim(), norm: normalizeName(name), }; entries.push(entry); byName.set(name, entry); if (!byNorm.has(entry.norm)) byNorm.set(entry.norm, entry); } return { entries, byName, byNorm }; } function resolveTaxByName(taxName, catalog) { if (!taxName) return null; return catalog.byName.get(taxName) || null; } function applyTypoRename(name) { const trimmed = String(name || '').trim(); for (const [wrong, right] of TYPO_RENAMES) { if (trimmed === wrong || trimmed.includes(wrong)) { return trimmed.replace(wrong, right); } } return trimmed; } function matchByNameRules(skuName) { const name = coreName(skuName); for (const rule of NAME_TAX_RULES) { for (const kw of rule.keywords) { if (name.includes(kw)) { return { taxName: rule.taxName, reason: `keyword:${kw}` }; } } } return null; } function matchByExactCatalog(skuName, catalog) { const candidates = [skuName, coreName(skuName), applyTypoRename(skuName), coreName(applyTypoRename(skuName))]; for (const c of candidates) { const norm = normalizeName(c); if (!norm) continue; if (catalog.byNorm.has(norm)) { return { entry: catalog.byNorm.get(norm), reason: 'exact_tax_name' }; } } return null; } function matchByCategory(categoryName, catalog) { const taxName = CATEGORY_TAX_NAME[categoryName]; if (!taxName) return null; const entry = resolveTaxByName(taxName, catalog); if (!entry) return null; return { entry, reason: `category:${categoryName}` }; } function resolveSku(row, catalog) { const currentName = String(row.sku_name || row.catalog_name || '').trim(); const fixedName = applyTypoRename(currentName); const categoryName = row.category_name || '(无分类)'; let taxEntry = null; let reason = ''; const exact = matchByExactCatalog(fixedName, catalog); if (exact) { taxEntry = exact.entry; reason = exact.reason; } if (!taxEntry) { const rule = matchByNameRules(fixedName); if (rule) { taxEntry = resolveTaxByName(rule.taxName, catalog); reason = rule.reason; } } if (!taxEntry) { const cat = matchByCategory(categoryName, catalog); if (cat) { taxEntry = cat.entry; reason = cat.reason; } } if (!taxEntry) { return { matched: false, currentName, fixedName }; } const rename = fixedName !== currentName; return { matched: true, currentName, fixedName, rename, tax_code: taxEntry.tax_code, tax_name: taxEntry.name, reason, }; } async function main() { const args = parseArgs(process.argv); if (!args.xlsx) { console.error('请指定 --xlsx 路径'); process.exit(1); } if (!fs.existsSync(args.xlsx)) { console.error('文件不存在:', args.xlsx); process.exit(1); } if (!args.databaseUrl) { console.error('请设置 DATABASE_URL 或 --database-url'); process.exit(1); } const catalog = loadTaxCatalog(args.xlsx); console.log(`税收编码条目: ${catalog.entries.length}`); const pool = new pg.Pool({ connectionString: args.databaseUrl }); const client = await pool.connect(); try { const skuRes = await client.query(` SELECT s.sku_code, s.sku_name, s.tax_code, pc.name AS catalog_name, pc.tax_code AS catalog_tax_code, COALESCE(c.category_name, '(无分类)') AS category_name FROM skus s LEFT JOIN product_catalog pc ON pc.code = s.sku_code AND pc.item_type = 'sku' LEFT JOIN categories c ON c.category_code = s.category_code WHERE s.status = 1 ORDER BY s.sku_name `); const updates = []; const unmatched = []; for (const row of skuRes.rows) { const resolved = resolveSku(row, catalog); if (!resolved.matched) { unmatched.push({ sku_code: row.sku_code, sku_name: resolved.currentName, category: row.category_name, tax_code: row.tax_code, }); continue; } const newName = resolved.fixedName; const newTax = resolved.tax_code; const taxMissing = String(row.tax_code || '').trim() !== newTax; const nameWrong = resolved.rename; if (taxMissing || nameWrong) { updates.push({ sku_code: row.sku_code, category: row.category_name, old_name: resolved.currentName, new_name: newName, old_tax: row.tax_code || '', new_tax: newTax, tax_label: resolved.tax_name, reason: resolved.reason, rename: nameWrong, }); } } console.log(`\n待更新: ${updates.length} / ${skuRes.rows.length}`); console.log(`未匹配: ${unmatched.length}`); const renameCount = updates.filter((u) => u.rename).length; const taxCount = updates.filter((u) => u.old_tax !== u.new_tax).length; console.log(` 写 tax_code: ${taxCount}, 修正名称: ${renameCount}`); console.log('\n--- 名称修正 ---'); for (const u of updates.filter((x) => x.rename)) { console.log(`${u.sku_code} | ${u.old_name} -> ${u.new_name}`); } console.log('\n--- 前 40 条 tax_code 更新预览 ---'); for (const u of updates.slice(0, 40)) { const parts = [u.sku_code, u.old_name]; if (u.rename) parts.push(`-> ${u.new_name}`); parts.push(`码: ${u.old_tax || '(空)'} -> ${u.new_tax}`); parts.push(`(${u.tax_label}) [${u.reason}]`); console.log(parts.join(' | ')); } if (unmatched.length) { console.log('\n--- 未匹配样例 (前 20) ---'); for (const u of unmatched.slice(0, 20)) { console.log(`${u.sku_code} | ${u.category} | ${u.sku_name}`); } } const reportPath = path.join(__dirname, 'sync-tax-codes-report.json'); fs.writeFileSync( reportPath, JSON.stringify({ updated: updates, unmatched }, null, 2), 'utf8' ); console.log(`\n完整报告: ${reportPath}`); if (args.dryRun) { console.log('\n[dry-run] 未写入数据库。加 --apply 执行更新。'); return; } await client.query('BEGIN'); let applied = 0; for (const u of updates) { await client.query(`UPDATE skus SET sku_name = $2, tax_code = $3 WHERE sku_code = $1`, [ u.sku_code, u.new_name, u.new_tax, ]); await client.query( `UPDATE product_catalog SET name = $2, tax_code = $3 WHERE code = $1 AND item_type = 'sku'`, [u.sku_code, u.new_name, u.new_tax] ); applied += 1; } await client.query('COMMIT'); console.log(`\n已写入 ${applied} 条。`); } catch (err) { await client.query('ROLLBACK').catch(() => {}); throw err; } finally { client.release(); await pool.end(); } } main().catch((err) => { console.error(err); process.exit(1); });