Files
SupplierSystem/scripts/backfill-tax-from-catalog-xlsx.cjs
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

569 lines
23 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 根据「商品编码.xlsx」(增值税税收分类编码)为商品基础数据补全 tax_code。
* 只填空值;仅写入高置信度匹配,目标准确率 ≥ 90%。
*
* 用法:
* node scripts/backfill-tax-from-catalog-xlsx.cjs --xlsx "..." --dry-run
* node scripts/backfill-tax-from-catalog-xlsx.cjs --xlsx "..." --execute
*/
const fs = require('fs');
const path = require('path');
const XLSX = require('xlsx');
const pg = require(path.join(__dirname, '../server/node_modules/pg'));
const dotenv = require(path.join(__dirname, '../server/node_modules/dotenv'));
dotenv.config({ path: path.join(__dirname, '../server/.env') });
const MIN_CONFIDENCE = 90; // 只写入 ≥90 分的匹配
/** 分类回退:仅叶子分类且语义明确时给 ≥90 分 */
const CATEGORY_TAX_NAME = {
叶菜类: { taxName: '芹菜等叶菜类蔬菜', conf: 90 },
根茎类: { taxName: '萝卜等根菜类蔬菜', conf: 90 },
根菜类: { taxName: '萝卜等根菜类蔬菜', conf: 90 },
瓜类: { taxName: '瓜类蔬菜', conf: 92 },
茄果类: { taxName: '番茄等茄果类蔬菜', conf: 90 },
葱蒜类: { taxName: '葱蒜类蔬菜', conf: 90 },
白菜类: { taxName: '白菜类蔬菜', conf: 92 },
芥菜类: { taxName: '芥菜类蔬菜', conf: 92 },
甘蓝类: { taxName: '甘蓝类蔬菜', conf: 92 },
豆类: { taxName: '菜豆等豆类蔬菜', conf: 90 },
豆制品类: { taxName: '豆腐及豆制品', conf: 92 },
菌菇类: { taxName: '香菇等食用菌', conf: 92 },
芽苗类: { taxName: '芹菜等叶菜类蔬菜', conf: 78 },
玉米类: { taxName: '玉米', conf: 90 },
水果类: { taxName: '其他未列明水果', conf: 90 },
其他蔬菜: { taxName: '其他蔬菜', conf: 85 },
鲜肉: { taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', conf: 78 },
蛋类: { taxName: '禽蛋', conf: 90 },
面食: { taxName: '米、面制半成品', conf: 90 },
干杂: { taxName: '调味品', conf: 78 },
日杂: { taxName: '其他日用杂品', conf: 86 },
蔬菜: { taxName: '蔬菜及食用菌', conf: 70 },
};
const NAME_TAX_RULES = [
// 日杂
{ keywords: ['一次性桌布', '桌布'], taxName: '台布(桌布)', conf: 94 },
{ keywords: ['抽纸', '纸巾', '卫生纸', '维邦纸'], taxName: '卫生用纸制品', conf: 94 },
{ keywords: ['洗洁精', '洗衣粉', '洗衣液'], taxName: '合成洗涤剂', conf: 94 },
{ keywords: ['扫帚', '拖把', '钢丝球', '粘鼠板'], taxName: '清洁清扫类工具及其已加工材料', conf: 92 },
{ keywords: ['工作服'], taxName: '特种服装', conf: 92 },
{ keywords: ['手套', '保鲜膜', '食品袋', '垃圾袋', '保鲜袋', '勺子', '磨刀石', '灭害灵', '碱片'], taxName: '其他日用杂品', conf: 91 },
{ keywords: ['打包盒', '圆盒', '纸碗'], taxName: '塑料作面类似箱、包容器', conf: 94 },
{ keywords: ['一次性筷子', '筷子'], taxName: '木制一次性筷子', conf: 95 },
// 面食/半成品(优先于肉类短词;细粉名须在「米粉」前)
{ keywords: ['抄手皮', '饺子皮', '馄饨皮'], taxName: '米、面制半成品', conf: 94 },
{ keywords: ['玉米粉', '玉米淀粉', '糯米粉'], taxName: '其他谷物细粉', conf: 95 },
{ keywords: ['粉条', '粉皮'], taxName: '淀粉制品', conf: 94 },
{ keywords: ['河粉', '方便面', '叶儿粑', '发糕', '包子', '馒头', '抄手', '水饺', '馄饨', '面条', '挂面', '凉面', '宽面', '凉粉', '凉皮', '冰粉'], taxName: '米、面制半成品', conf: 93 },
{ keywords: ['米粉'], taxName: '米、面制半成品', conf: 93, exactish: true },
// 调味 / 腌渍(优先于蔬菜短词)
{ keywords: ['海椒面', '辣椒面', '花椒面', '椒面'], taxName: '复合调味品', conf: 93 },
{ keywords: ['火锅底料', '干锅酱'], taxName: '复合调味品', conf: 94 },
{ keywords: ['藤椒油'], taxName: '其他食用植物油', conf: 94 },
{ keywords: ['海椒酱', '番茄酱', '豆瓣', '豆豉', '酱油', '生抽', '老抽', '蚝油', '料酒', '味精', '鸡精', '沙拉酱'], taxName: '调味品', conf: 93 },
{ keywords: ['泡酸菜', '泡海椒', '榨菜', '泡菜', '腌菜', '芽菜', '咸菜', '酸菜'], taxName: '腌渍菜', conf: 94 },
{ keywords: ['干木耳', '干香菇'], taxName: '干制蔬菜(脱水蔬菜)', conf: 94 },
{ keywords: ['小米辣', '小米椒'], taxName: '番茄等茄果类蔬菜', conf: 93 },
{ keywords: ['醋'], taxName: '醋及醋代用品', conf: 94 },
{ keywords: ['盐'], taxName: '加工盐', conf: 94, exactish: true },
{ keywords: ['白糖', '冰糖', '红糖'], taxName: '成品糖', conf: 94 },
{ keywords: ['八角粉', '八角', '花椒'], taxName: '香料原料', conf: 93 },
{ keywords: ['芝麻'], taxName: '油料作物', conf: 90 },
// 粮油粉
{ keywords: ['糯米粉', '面粉', '生粉', '淀粉', '土豆粉', '豆粉'], taxName: '其他谷物细粉', conf: 92 },
{ keywords: ['大米', '糯米'], taxName: '大米', conf: 94 },
{ keywords: ['食用油', '菜籽油', '调和油', '色拉油', '葵花油', '橄榄油'], taxName: '食用植物油及食用植物油脂', conf: 95 },
{ keywords: ['香油', '芝麻油', '麻油'], taxName: '食用植物油及食用植物油脂', conf: 95 },
// 水产(避免被鲜肉分类带走)
{ keywords: ['泥鳅', '鳝鱼', '黄鳝', '草鱼', '鲫鱼', '鲢鱼', '鲈鱼'], taxName: '淡水鱼', conf: 95 },
{ keywords: ['牛蛙', '蛙'], taxName: '其他淡水产品', conf: 94 },
{ keywords: ['虾皮'], taxName: '甲壳水产品加工品', conf: 95 },
{ keywords: ['虾', '小龙虾'], taxName: '淡水虾', conf: 93 },
{ keywords: ['花生米'], taxName: '花生', conf: 95 },
{ keywords: ['花生'], taxName: '花生', conf: 94 },
// 肉类
{ keywords: ['午餐肉'], taxName: '畜肉类罐头', conf: 95 },
{ keywords: ['火腿肠'], taxName: '蒸煮香肠制品', conf: 95 },
{ keywords: ['香肠', '腊肉', '广味'], taxName: '腌腊肉制品', conf: 94 },
{ keywords: ['三线肉', '二刀肉', '五花肉', '前腿肉', '核桃肉', '猪头肉', '夹缝肉', '瘦肉', '碎肉', '绞肉', '肉沫', '颗粒肉', '肥肉', '肥牛', '里脊', '排骨', '精排', '仔排', '筒骨', '猪蹄', '肘子', '肥肠', '大肠', '肚子', '郡肝', '鸡尖', '兔腿', '兔肚', '棒骨', '大骨', '掌中宝', '猪皮', '猪肝', '猪腰', '猪脑', '猪尾', '猪利', '心力肚', '油边', '边油', '耳叶', '羊血', '血旺'], taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', conf: 92 },
{ keywords: ['牛肉', '牛肋', '牛腱', '牛排', '羊肉'], taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', conf: 94 },
{ keywords: ['花鲢', '鲢鱼'], taxName: '淡水鱼', conf: 94 },
{ keywords: ['豆芽'], taxName: '菜豆等豆类蔬菜', conf: 92 },
{ keywords: ['酸豆角', '藤椒豇豆'], taxName: '腌渍菜', conf: 93 },
{ keywords: ['草果'], taxName: '香料原料', conf: 93 },
{ keywords: ['食用碱'], taxName: '其他日用杂品', conf: 90 },
{ keywords: ['啤酒'], taxName: '啤酒', conf: 95 },
{ keywords: ['红苕尖', '红苕粉', '红苕'], taxName: '山药等薯芋类蔬菜', conf: 92 },
{ keywords: ['灯笼椒'], taxName: '番茄等茄果类蔬菜', conf: 92 },
{ keywords: ['鱼蛋', '鱼丸'], taxName: '鱼糜(熟肉)制品', conf: 92 },
{ keywords: ['绞肉机'], taxName: '其他日用杂品', conf: 90 },
{ keywords: ['三黄鸡', '卤兔', '兔'], taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', conf: 92, requireCategory: ['鲜肉'] },
{ keywords: ['鸡', '鸭', '鹅', '鸽'], taxName: '猪、牛、羊、鸡、鸭、鹅鲜、冷、冻肉', conf: 91, requireCategory: ['鲜肉'] },
{ keywords: ['泡姜', '泡椒', '泡豇豆', '泡野山椒', '野山椒'], taxName: '腌渍菜', conf: 94 },
{ keywords: ['干鱿鱼', '鱿鱼'], taxName: '干制水产品', conf: 93 },
{ keywords: ['海带'], taxName: '海水藻类', conf: 94 },
{ keywords: ['折耳根', '鱼腥草'], taxName: '芹菜等叶菜类蔬菜', conf: 93 },
{ keywords: ['玉兰片', '笋尖', '笋子', '干笋'], taxName: '竹笋等多年生及杂类蔬菜', conf: 92 },
{ keywords: ['大料', '蒸肉粉', '干锅料'], taxName: '复合调味品', conf: 92 },
{ keywords: ['米线'], taxName: '米、面制半成品', conf: 93 },
{ keywords: ['干枣', '枣子'], taxName: '干制水果', conf: 92 },
{ keywords: ['豆腐', '豆干', '豆皮', '腐竹', '豆泡', '千张', '卤筋'], taxName: '豆腐及豆制品', conf: 93 },
{ keywords: ['鸡蛋', '鸭蛋', '鹅蛋', '鹌鹑蛋'], taxName: '鸡蛋', conf: 95 },
{ keywords: ['蘑菇', '香菇', '平菇', '金针菇', '木耳', '银耳', '口蘑'], taxName: '香菇等食用菌', conf: 94 },
{ keywords: ['酸奶'], taxName: '液体乳', conf: 92 },
{ keywords: ['生姜', '仔姜', '上好仔姜', '黄姜'], taxName: '山药等薯芋类蔬菜', conf: 94 },
{ keywords: ['姜'], taxName: '山药等薯芋类蔬菜', conf: 92, requireCategory: ['其他蔬菜', '葱蒜类', '根茎类'] },
{ keywords: ['大蒜', '大葱', '香葱', '洋葱', '韭菜', '香菜', '芹菜', '菠菜', '生菜', '油麦', '空心菜'], taxName: '葱蒜类蔬菜', conf: 92 },
{ keywords: ['蒜'], taxName: '葱蒜类蔬菜', conf: 90, minCoreLen: 2 },
{ keywords: ['土豆'], taxName: '马铃薯', conf: 96 },
{ keywords: ['萝卜', '胡萝卜', '莲藕'], taxName: '萝卜等根菜类蔬菜', conf: 92 },
{ keywords: ['山药', '红薯', '芋头'], taxName: '山药等薯芋类蔬菜', conf: 93 },
{ keywords: ['青笋', '莴笋', '油麦菜'], taxName: '芹菜等叶菜类蔬菜', conf: 93 },
{ keywords: ['黄瓜', '冬瓜', '南瓜', '丝瓜', '苦瓜', '西葫芦', '付瓜'], taxName: '瓜类蔬菜', conf: 93 },
{ keywords: ['番茄', '西红柿', '茄子', '青椒', '辣椒', '二荆条', '海椒'], taxName: '番茄等茄果类蔬菜', conf: 92 },
{ keywords: ['白菜', '包菜', '甘蓝', '上海青'], taxName: '白菜类蔬菜', conf: 93 },
{ keywords: ['娃娃菜'], taxName: '芥菜类蔬菜', conf: 92 },
{ keywords: ['玉米'], taxName: '玉米', conf: 92 },
];
function parseArgs(argv) {
const args = {
dryRun: !argv.includes('--execute'),
xlsx: '',
databaseUrl: process.env.DATABASE_URL || '',
minConfidence: MIN_CONFIDENCE,
};
for (let i = 2; i < argv.length; i += 1) {
const a = argv[i];
if (a === '--xlsx') args.xlsx = argv[++i] || '';
else if (a === '--database-url') args.databaseUrl = argv[++i] || '';
else if (a === '--min-confidence') args.minConfidence = Number(argv[++i]) || MIN_CONFIDENCE;
}
return args;
}
function normalizeName(value) {
return String(value || '')
.trim()
.replace(/\s+/g, '')
.replace(/[()()【】\[\]{}]/g, '')
.replace(/[·•\-_]/g, '')
.toLowerCase();
}
function coreName(raw) {
let s = String(raw || '').trim();
// 去掉半成品. 前缀
s = s.replace(/^半成品[.\s]*/g, '');
s = s.replace(/[((][^))]*[))]/g, '');
// 去掉加工/精修等后缀,便于匹配鲜品条目
s = s.replace(/(加工|精修)$/g, '');
s = s.replace(
/\d+(\.\d+)?\s*(kg|g|ml|l|斤|两|升|毫升|克|千克|包|袋|箱|瓶|桶|件|个|只|条|根|把|捆|盒|罐|听|支|卷|板|片|块|颗|粒|枚|cm)/gi,
''
);
s = s.replace(/\d+$/g, '');
return s.trim();
}
/** 从「说明」提取可匹配别名 */
function extractAliases(description) {
const text = String(description || '');
if (!text) return [];
const aliases = new Set();
const pushParts = (chunk) => {
String(chunk || '')
.split(/[、,,;;\/]/)
.map((x) => x.trim())
.filter((x) => x.length >= 2 && x.length <= 20 && !/详见|不包括|种用|又称|别名/.test(x))
.forEach((x) => aliases.add(x));
};
// 别名:xxx、yyy
const aliasBlocks = text.matchAll(/别名[::]\s*([^()();;。]+)/g);
for (const m of aliasBlocks) pushParts(m[1]);
// 又称xxx、yyy
const alsoKnown = text.matchAll(/又称\s*([^。;;]+)/g);
for (const m of alsoKnown) {
pushParts(
String(m[1])
.replace(/([^)]*)/g, '')
.replace(/\([^)]*\)/g, '')
);
}
// 包括xxx、yyy(截到句号或括号说明前)
const includeMatch = text.match(/包括([^。]+)/);
if (includeMatch) {
const chunk = includeMatch[1]
.replace(/([^)]*)/g, '')
.replace(/\([^)]*\)/g, '');
pushParts(chunk);
}
return [...aliases];
}
function specificityScore(taxCode) {
// 尾部 0 越少越细
const code = String(taxCode || '');
const trimmed = code.replace(/0+$/, '');
return trimmed.length;
}
function preferMoreSpecific(existing, candidate) {
if (!existing) return candidate;
return specificityScore(candidate.tax_code) >= specificityScore(existing.tax_code)
? candidate
: existing;
}
function inferTaxRate(shortName, taxName, existingRate) {
if (existingRate !== null && existingRate !== undefined && Number.isFinite(Number(existingRate))) {
return Number(existingRate);
}
const short = String(shortName || '');
const name = String(taxName || '');
// 常见农产品免税
if (
/蔬菜|水果|鲜.*肉|禽蛋|蛋|水产|谷物|大米|食用菌|干豆|坚果|香料/.test(short) ||
/蔬菜|水果|鲜、冷、冻肉|禽蛋|鸡蛋|淡水|海水|谷物|大米|食用菌/.test(name)
) {
return 0;
}
if (/调味|制品|加工|塑料|容器|筷子|淀粉|面粉|半成品|糕点|豆制品|腌渍|酱|油/.test(short + name)) {
return 0.13;
}
return null;
}
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();
const byAlias = new Map(); // aliasNorm -> entry
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 shortName = String(row['商品和服务分类简称'] || '').trim();
const description = String(row['说明'] || '').trim();
const entry = {
tax_code: code,
name,
short_name: shortName,
description,
norm: normalizeName(name),
};
entries.push(entry);
byName.set(name, preferMoreSpecific(byName.get(name), entry));
byNorm.set(entry.norm, preferMoreSpecific(byNorm.get(entry.norm), entry));
// 名称本身
byAlias.set(entry.norm, preferMoreSpecific(byAlias.get(entry.norm), entry));
for (const alias of extractAliases(description)) {
const an = normalizeName(alias);
if (!an || an.length < 2) continue;
// 短别名(1-2字)容易撞车,仅在尚无记录时写入
if (an.length <= 2 && byAlias.has(an)) continue;
byAlias.set(an, preferMoreSpecific(byAlias.get(an), entry));
}
}
return { entries, byName, byNorm, byAlias };
}
function resolveTaxByName(taxName, catalog) {
if (!taxName) return null;
return catalog.byName.get(taxName) || null;
}
function matchKeywordRule(raw, core, categoryName, rule, catalog) {
if (rule.requireCategory && !rule.requireCategory.includes(categoryName)) {
return null;
}
for (const kw of rule.keywords) {
let hit = false;
if (rule.exactish) {
const n = normalizeName(core);
hit = n === normalizeName(kw) || n === `${normalizeName(kw)}袋`;
} else {
hit = core.includes(kw) || raw.includes(kw);
}
if (!hit) continue;
if (rule.minCoreLen && normalizeName(core).length < rule.minCoreLen) continue;
const entry = resolveTaxByName(rule.taxName, catalog);
if (entry) {
return { entry, reason: `keyword:${kw}`, confidence: rule.conf };
}
}
return null;
}
function matchProduct(productName, categoryName, catalog) {
const raw = String(productName || '').trim();
const core = coreName(raw);
const candidates = [raw, core].filter(Boolean);
// 1) 精确 / 核心名 = 官方名称
for (const c of candidates) {
const n = normalizeName(c);
if (catalog.byNorm.has(n)) {
return { entry: catalog.byNorm.get(n), reason: 'exact_name', confidence: 98 };
}
}
// 2) 别名表精确命中(说明字段);不做模糊包含,避免误伤
for (const c of candidates) {
const n = normalizeName(c);
if (n && catalog.byAlias.has(n)) {
return { entry: catalog.byAlias.get(n), reason: 'alias', confidence: 95 };
}
}
// 3) 关键词规则(长词优先,已按数组顺序)
for (const rule of NAME_TAX_RULES) {
const hit = matchKeywordRule(raw, core, categoryName, rule, catalog);
if (hit) return hit;
}
// 4) 分类回退
if (/午餐肉|罐头|火腿/.test(raw) && categoryName === '鲜肉') {
// 加工肉不应回退到鲜肉编码
} else {
const catRule = CATEGORY_TAX_NAME[categoryName];
if (catRule) {
const entry = resolveTaxByName(catRule.taxName, catalog);
if (entry) {
return { entry, reason: `category:${categoryName}`, confidence: catRule.conf };
}
}
}
return null;
}
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');
process.exit(1);
}
const catalog = loadTaxCatalog(args.xlsx);
console.log(
JSON.stringify(
{
catalogEntries: catalog.entries.length,
aliasIndex: catalog.byAlias.size,
minConfidence: args.minConfidence,
dryRun: args.dryRun,
},
null,
2
)
);
const pool = new pg.Pool({ connectionString: args.databaseUrl });
const client = await pool.connect();
try {
const { rows: products } = await client.query(`
SELECT
p.code,
p.name,
p.tax_code,
p.tax_rate,
p.parent_code,
c.name AS category_name,
c2.name AS parent_category_name
FROM product_catalog p
LEFT JOIN product_catalog c
ON c.code = p.parent_code AND c.item_type = 'category'
LEFT JOIN product_catalog c2
ON c2.code = c.parent_code AND c2.item_type = 'category'
WHERE p.item_type = 'product'
ORDER BY p.name
`);
const empty = products.filter((p) => !String(p.tax_code || '').trim());
const alreadyFilled = products.filter((p) => String(p.tax_code || '').trim());
const updates = [];
const lowConfidence = [];
const unmatched = [];
// 用已有税编样本评估准确率(精确码 + 同大类兼容)
let validateTotal = 0;
let validateHit = 0;
let validateCompatible = 0;
const validateMiss = [];
for (const row of alreadyFilled) {
const categoryName = row.category_name || row.parent_category_name || '(无分类)';
const matched = matchProduct(row.name, categoryName, catalog);
if (!matched || matched.confidence < args.minConfidence) continue;
validateTotal += 1;
const existing = String(row.tax_code).trim();
const predicted = String(matched.entry.tax_code);
const existingEntry = catalog.entries.find((e) => e.tax_code === existing);
if (existing === predicted) {
validateHit += 1;
validateCompatible += 1;
continue;
}
const sameFamily = existing.slice(0, 11) === predicted.slice(0, 11);
const sameShort =
existingEntry &&
existingEntry.short_name &&
existingEntry.short_name === matched.entry.short_name;
if (sameFamily || sameShort) {
validateCompatible += 1;
} else {
validateMiss.push({
name: row.name,
existing,
existingName: existingEntry ? existingEntry.name : '',
predicted,
predictedName: matched.entry.name,
reason: matched.reason,
confidence: matched.confidence,
});
}
}
for (const row of empty) {
const categoryName = row.category_name || row.parent_category_name || '(无分类)';
const matched = matchProduct(row.name, categoryName, catalog);
if (!matched) {
unmatched.push({ code: row.code, name: row.name, category: categoryName });
continue;
}
const payload = {
code: row.code,
name: row.name,
category: categoryName,
tax_code: matched.entry.tax_code,
tax_name: matched.entry.name,
short_name: matched.entry.short_name,
tax_rate: inferTaxRate(matched.entry.short_name, matched.entry.name, row.tax_rate),
reason: matched.reason,
confidence: matched.confidence,
};
if (matched.confidence >= args.minConfidence) {
updates.push(payload);
} else {
lowConfidence.push(payload);
}
}
const report = {
dryRun: args.dryRun,
totalProducts: products.length,
emptyTax: empty.length,
willUpdate: updates.length,
lowConfidenceSkipped: lowConfidence.length,
unmatched: unmatched.length,
coverageOfEmpty: empty.length
? Number((((updates.length) / empty.length) * 100).toFixed(1))
: 100,
validationAgainstExisting: {
compared: validateTotal,
sameCode: validateHit,
compatibleFamilyOrShort: validateCompatible,
exactAccuracyPct: validateTotal
? Number(((validateHit / validateTotal) * 100).toFixed(1))
: null,
compatibleAccuracyPct: validateTotal
? Number(((validateCompatible / validateTotal) * 100).toFixed(1))
: null,
missSample: validateMiss.slice(0, 20),
},
byReason: updates.reduce((acc, u) => {
acc[u.reason] = (acc[u.reason] || 0) + 1;
return acc;
}, {}),
sampleUpdates: updates.slice(0, 40),
sampleLowConfidence: lowConfidence.slice(0, 20),
sampleUnmatched: unmatched.slice(0, 40),
};
const reportPath = path.join(__dirname, 'backfill-tax-from-catalog-report.json');
fs.writeFileSync(
reportPath,
JSON.stringify({ ...report, updates, lowConfidence, unmatched }, null, 2),
'utf8'
);
console.log(JSON.stringify(report, null, 2));
console.log(`\n完整报告: ${reportPath}`);
if (args.dryRun) {
console.log('\n[dry-run] 未写入。确认后加 --execute');
return;
}
await client.query('BEGIN');
let applied = 0;
for (const u of updates) {
await client.query(
`UPDATE product_catalog
SET tax_code = $2,
tax_rate = COALESCE($3, tax_rate),
updated_at = NOW()
WHERE code = $1 AND item_type = 'product'`,
[u.code, u.tax_code, u.tax_rate]
);
await client.query(
`UPDATE skus
SET tax_code = $2,
tax_rate = COALESCE($3, tax_rate)
WHERE sku_code = $1`,
[u.code, u.tax_code, u.tax_rate]
);
applied += 1;
}
await client.query('COMMIT');
console.log(`\n已写入 ${applied} 条 tax_code。`);
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
throw error;
} finally {
client.release();
await pool.end();
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});