#!/usr/bin/env node /** * 删除生产环境全部财务业务数据(保留客户/供应商主数据及银行字段配置)。 * * 清理范围:成本、结算单、发票、中标价、客户报价版本/报价单等。 * * 用法: * node scripts/prod-delete-finance-data.mjs * node scripts/prod-delete-finance-data.mjs --execute */ import pg from 'pg'; import dotenv from 'dotenv'; import path from 'path'; import { fileURLToPath } from 'url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); dotenv.config({ path: path.join(__dirname, '..', '.env') }); const EXECUTE = process.argv.includes('--execute'); const DRY_RUN = !EXECUTE; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); /** 按外键依赖顺序删除 */ const FINANCE_DELETE_ORDER = [ 'statement_disputes', 'invoices', 'statement_lines', 'customer_statements', 'supplier_statements', 'cost_details', 'cost_adjustments', 'fixed_costs', 'customer_quote_sheet_items', 'customer_quote_sheet_customers', 'customer_quote_sheets', 'customer_quote_versions', 'bid_prices', ]; async function tableExists(client, table) { const r = await client.query(`SELECT to_regclass('public.' || $1) IS NOT NULL AS ok`, [table]); return Boolean(r.rows[0]?.ok); } async function deleteFinanceData(client, dryRun = DRY_RUN) { for (const table of FINANCE_DELETE_ORDER) { if (!(await tableExists(client, table))) { console.log(` skip ${table} (missing)`); continue; } if (dryRun) { const preview = await client.query(`SELECT count(*)::int AS c FROM ${table}`); console.log(` [dry] ${table}: ${preview.rows[0]?.c ?? 0} rows`); continue; } const r = await client.query(`DELETE FROM ${table}`); console.log(` deleted ${table}: ${r.rowCount}`); } } async function main() { if (!process.env.DATABASE_URL) { throw new Error('DATABASE_URL required'); } console.log(`=== 删除全部财务数据 (${DRY_RUN ? 'DRY-RUN,加 --execute 执行' : 'EXECUTE'}) ===`); const client = await pool.connect(); try { const counts = {}; for (const table of FINANCE_DELETE_ORDER) { if (!(await tableExists(client, table))) continue; const r = await client.query(`SELECT count(*)::int AS c FROM ${table}`); counts[table] = r.rows[0]?.c ?? 0; } console.log('当前财务数据量:', counts); const total = Object.values(counts).reduce((sum, n) => sum + Number(n || 0), 0); if (!total) { console.log('无财务业务数据,无需删除。'); return; } if (DRY_RUN) { console.log('\n--- 将删除的行数预览 ---'); await deleteFinanceData(client, true); console.log('\n确认后执行: node scripts/prod-delete-finance-data.mjs --execute'); return; } await client.query('BEGIN'); try { await deleteFinanceData(client, false); await client.query('COMMIT'); console.log('\n财务数据已全部删除并提交。'); const after = {}; for (const table of FINANCE_DELETE_ORDER) { if (!(await tableExists(client, table))) continue; const r = await client.query(`SELECT count(*)::int AS c FROM ${table}`); after[table] = r.rows[0]?.c ?? 0; } console.log('删除后剩余:', after); } catch (error) { await client.query('ROLLBACK'); throw error; } } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });