/** * 重算客户按天结算单(取价回退修复后)。 * 备份未收付结算单到 JSON,再调 generateCustomerStatements 重算。 * 已收付(status>=20 或 paid>0)由 upsertCustomerStatementForDay 自动跳过。 * 用法: npx tsx regen-customer-statements.ts [branch] [dateFrom] [dateTo] */ import { writeFileSync } from 'node:fs'; import { pool } from './src/db'; import { runWithTenantDataAccess } from './src/services/tenantSchemaService'; import { generateCustomerStatements } from './src/services/financeReconciliationService'; 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) => { // 1) 备份未收付按天结算单 + 明细 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: any[] = []; 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}`); }); // 2) 重算(generateCustomerStatements 内部对每个 customer+day upsert,已收付跳过) const result = await runWithTenantDataAccess(branch, async (ctx) => generateCustomerStatements({ dateFrom, dateTo }, ctx as any) ); console.log(`重算完成: created=${result.created} updated=${result.updated} skipped=${result.skipped}`); // 3) 校验:重算后区间结算单合计 vs 订单营收 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); });