#!/usr/bin/env node /** * 从对账单 Excel 提取商品名 -> 税收编码/税率,回填 product_catalog(同步 skus) * * 用法: * node scripts/backfill-tax-from-statements.cjs --dry-run file1.xlsx file2.xlsx ... * node scripts/backfill-tax-from-statements.cjs --execute file1.xlsx ... */ 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 execute = process.argv.includes('--execute'); const dryRun = !execute; const files = process.argv.slice(2).filter((arg) => !arg.startsWith('--')); const SHEET_NAMES = ['开票税率明细', '免税', '有税']; function normalizeName(value) { return String(value ?? '') .trim() .replace(/\s+/g, '') .replace(/(/g, '(') .replace(/)/g, ')'); } function normalizeTaxCode(value) { const code = String(value ?? '').trim().replace(/\D/g, ''); return code || ''; } function normalizeTaxRate(value) { const num = Number(value); if (!Number.isFinite(num) || num < 0) return null; if (num >= 1) return Math.round(num) / 100; return num; } function findHeaderIndex(rows) { for (let i = 0; i < Math.min(rows.length, 10); i++) { const row = rows[i] || []; const texts = row.map((cell) => String(cell ?? '').trim()); const nameIdx = texts.findIndex((text) => text === '商品名' || text.includes('商品名')); const codeIdx = texts.findIndex((text) => text === '税率编码' || text.includes('税率编码')); const rateIdx = texts.findIndex((text) => text === '税率'); if (nameIdx >= 0 && codeIdx >= 0 && rateIdx >= 0) { return { headerRow: i, nameIdx, codeIdx, rateIdx }; } } return null; } function parseSheetRows(sheet) { const rows = XLSX.utils.sheet_to_json(sheet, { defval: '', header: 1 }); const header = findHeaderIndex(rows); if (!header) return []; const parsed = []; for (let i = header.headerRow + 1; i < rows.length; i++) { const row = rows[i] || []; const productName = String(row[header.nameIdx] ?? '').trim(); const taxCode = normalizeTaxCode(row[header.codeIdx]); const taxRate = normalizeTaxRate(row[header.rateIdx]); if (!productName || !taxCode || taxRate === null) continue; if (productName === '商品名') continue; parsed.push({ productName, taxCode, taxRate }); } return parsed; } function parseWorkbook(filePath) { const wb = XLSX.readFile(filePath); const entries = []; for (const sheetName of SHEET_NAMES) { if (!wb.Sheets[sheetName]) continue; entries.push(...parseSheetRows(wb.Sheets[sheetName])); } return entries; } function pickUniqueByName(products, predicate) { const matches = products.filter(predicate); return matches.length === 1 ? matches[0] : null; } function resolveProduct(products, taxInfo) { const exact = products.find((product) => String(product.name).trim() === taxInfo.displayName); if (exact) return exact; const key = normalizeName(taxInfo.displayName); const normalized = products.filter((product) => normalizeName(product.name) === key); if (normalized.length === 1) return normalized[0]; const excelName = taxInfo.displayName; const fuzzy = pickUniqueByName(products, (product) => { const dbName = String(product.name).trim(); if (!dbName || dbName.length < 2) return false; return excelName.includes(dbName) || dbName.includes(excelName); }); if (fuzzy) return fuzzy; return pickUniqueByName(products, (product) => { const dbName = normalizeName(product.name); const excel = normalizeName(excelName); if (dbName.length < 2 || excel.length < 2) return false; return excel.includes(dbName) || dbName.includes(excel); }); } function mergeTaxMaps(allFileEntries) { /** @type {Map} */ const map = new Map(); for (const { file, entries } of allFileEntries) { for (const entry of entries) { const key = normalizeName(entry.productName); const existing = map.get(key); if (!existing) { map.set(key, { taxCode: entry.taxCode, taxRate: entry.taxRate, displayName: entry.productName, sources: 1, conflicts: [], }); continue; } existing.sources += 1; if (existing.taxCode !== entry.taxCode || existing.taxRate !== entry.taxRate) { existing.conflicts.push(`${file}:${entry.productName}`); existing.taxCode = entry.taxCode; existing.taxRate = entry.taxRate; } } } return map; } async function main() { if (!files.length) { console.error('请传入至少一个对账单 xlsx 文件'); process.exit(1); } if (!process.env.DATABASE_URL) { console.error('缺少 DATABASE_URL'); process.exit(1); } const allFileEntries = files.map((file) => ({ file: path.basename(file), entries: parseWorkbook(path.resolve(file)), })); const taxMap = mergeTaxMaps(allFileEntries); const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { const { rows: products } = await client.query( `SELECT code, name, tax_code, tax_rate FROM product_catalog WHERE item_type = 'product'` ); const result = { dryRun, files: allFileEntries.map((item) => ({ file: item.file, rows: item.entries.length })), taxEntries: taxMap.size, matched: 0, updated: 0, alreadyFilled: 0, unmatchedExcel: [], conflicts: [], }; if (dryRun) await client.query('BEGIN'); for (const [, taxInfo] of taxMap.entries()) { const product = resolveProduct(products, taxInfo); if (!product) { result.unmatchedExcel.push(taxInfo.displayName); continue; } result.matched += 1; const currentCode = String(product.tax_code || '').trim(); const currentRate = product.tax_rate == null ? null : Number(product.tax_rate); const shouldUpdate = !currentCode || currentRate == null; if (!shouldUpdate) { if (currentCode === taxInfo.taxCode && Number(currentRate) === Number(taxInfo.taxRate)) { result.alreadyFilled += 1; continue; } result.conflicts.push({ name: product.name, current: { tax_code: currentCode, tax_rate: currentRate }, incoming: { tax_code: taxInfo.taxCode, tax_rate: taxInfo.taxRate }, }); continue; } if (!dryRun) { await client.query( `UPDATE product_catalog SET tax_code = $2, tax_rate = $3, updated_at = NOW() WHERE item_type = 'product' AND code = $1`, [product.code, taxInfo.taxCode, taxInfo.taxRate] ); } result.updated += 1; product.__taxFilled = true; } result.dbWithoutTax = products.filter( (product) => !String(product.tax_code || '').trim() ).length; result.dbStillMissingTax = products.filter( (product) => !String(product.tax_code || '').trim() && !product.__taxFilled ).length; if (taxInfoConflicts(taxMap).length) { result.taxMapConflicts = taxInfoConflicts(taxMap).slice(0, 20); } if (dryRun) await client.query('ROLLBACK'); else await client.query('COMMIT'); result.unmatchedExcel = [...new Set(result.unmatchedExcel)].sort((a, b) => a.localeCompare(b, 'zh-CN')); console.log(JSON.stringify(result, null, 2)); if (result.unmatchedExcel.length) { console.log('\n--- 对账单有但未匹配到商品库 ---'); result.unmatchedExcel.slice(0, 40).forEach((name) => console.log(name)); if (result.unmatchedExcel.length > 40) { console.log(`... 另有 ${result.unmatchedExcel.length - 40} 个`); } } if (dryRun) console.log('\n[dry-run] 未写入。确认后加 --execute'); } catch (error) { await client.query('ROLLBACK').catch(() => {}); throw error; } finally { client.release(); await pool.end(); } } function taxInfoConflicts(map) { const list = []; for (const [, info] of map.entries()) { if (info.conflicts.length) list.push({ name: info.displayName, conflicts: info.conflicts }); } return list; } main().catch((error) => { console.error(error); process.exit(1); });