/** * 生产重算客户按天结算单(取价回退修复后)。直接 import 已部署的 dist 代码。 * 用法: node regen-customer-statements.mjs [branch] [dateFrom] [dateTo] * 在生产 server 目录下运行(需 .env 提供 DB 连接)。 */ import { writeFileSync } from 'node:fs'; import { pool } from './dist/db.js'; import { runWithTenantDataAccess } from './dist/services/tenantSchemaService.js'; import { generateCustomerStatements } from './dist/services/financeReconciliationService.js'; async function main() { const branch = process.argv[2] || 'BR002'; const dateFrom = process.argv[3] || '2026-07-17'; const dateTo = process.argv[4] || '2026-07-24'; await runWithTenantDataAccess(branch, async (c) => { const stmts = await c.query( `SELECT * FROM customer_statements WHERE cycle_code ~ '^[0-9]{8}$' AND statement_status < 20 AND COALESCE(paid_amount,0)=0 ORDER BY cycle_code` ); const nos = stmts.rows.map((r) => r.statement_no); let lines = []; if (nos.length) { const l = await c.query( `SELECT * FROM statement_lines WHERE statement_type='customer' AND statement_no = ANY($1::text[])`, [nos] ); lines = l.rows; } const backupFile = `customer_statements_backup_${branch}_${Date.now()}.json`; writeFileSync(backupFile, JSON.stringify({ statements: stmts.rows, lines }, null, 2)); console.log(`已备份 ${stmts.rows.length} 张结算单 + ${lines.length} 行明细 -> ${backupFile}`); }); const result = await runWithTenantDataAccess(branch, async (ctx) => generateCustomerStatements({ dateFrom, dateTo }, ctx) ); console.log(`重算完成: created=${result.created} updated=${result.updated} skipped=${result.skipped}`); await runWithTenantDataAccess(branch, async (c) => { const stmt = await c.query( `SELECT COALESCE(SUM(total_amount),0)::numeric AS total FROM customer_statements WHERE cycle_code ~ '^[0-9]{8}$' AND cycle_code >= $1 AND cycle_code <= $2`, [dateFrom.replace(/-/g, ''), dateTo.replace(/-/g, '')] ); console.log(`重算后 ${dateFrom}~${dateTo} 结算单合计 = ¥${Number(stmt.rows[0].total).toFixed(2)}`); }); await pool.end(); process.exit(0); } main().catch((e) => { console.error(e); process.exit(1); });