#!/usr/bin/env node /** * 清除「order_code 有值,但 orders 表中不存在该订单」的孤儿数据。 * 不删除 order_code IS NULL 的期间成本(如未分摊人工/固定成本分摊余额)。 * * 用法(生产): * NODE_PATH=./node_modules node --env-file=.env /tmp/prod-cleanup-orphan-order-refs.cjs * NODE_PATH=./node_modules node --env-file=.env /tmp/prod-cleanup-orphan-order-refs.cjs --execute */ const { Pool } = require('pg'); const EXECUTE = process.argv.includes('--execute'); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); /** table, column, optional extra WHERE */ const TARGETS = [ { table: 'cost_details', column: 'order_code' }, { table: 'purchase_orders', column: 'order_code' }, { table: 'supplier_preparations', column: 'order_code' }, { table: 'inspections', column: 'order_code' }, { table: 'inspection_returns', column: 'order_code' }, { table: 'inspection_loss_confirmations', column: 'order_code' }, { table: 'processing_tasks', column: 'order_code' }, { table: 'processing_logs', column: 'order_code' }, { table: 'delivery_tasks', column: 'order_code' }, { table: 'delivery_signatures', column: 'order_code' }, { table: 'delivery_person_locations', column: 'order_code' }, { table: 'sign_records', column: 'order_code' }, { table: 'picking_tasks', column: 'order_code' }, { table: 'picking_items', column: 'order_code' }, { table: 'allocation_tasks', column: 'order_code' }, { table: 'order_items', column: 'order_code' }, { table: 'after_sales', column: 'order_code' }, { table: 'product_substitutions', column: 'order_code' }, { table: 'statement_lines', column: 'order_code' }, { table: 'exception_tickets', column: 'related_order_code' }, { table: 'cost_adjustments', column: 'order_code' }, ]; async function tableExists(client, table) { const r = await client.query( `SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = $1 LIMIT 1`, [table] ); return r.rowCount > 0; } async function columnExists(client, table, column) { const r = await client.query( `SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2 LIMIT 1`, [table, column] ); return r.rowCount > 0; } async function main() { if (!process.env.DATABASE_URL) { console.error('缺少 DATABASE_URL'); process.exit(1); } console.log(`=== 孤儿订单引用清理 (${EXECUTE ? 'EXECUTE' : 'DRY-RUN'}) ===\n`); const client = await pool.connect(); const summary = []; try { // 先列 distinct orphan codes 样本 const sampleCodes = new Set(); for (const t of TARGETS) { if (!(await tableExists(client, t.table))) { summary.push({ table: t.table, status: 'skip_no_table' }); continue; } if (!(await columnExists(client, t.table, t.column))) { summary.push({ table: t.table, status: 'skip_no_column', column: t.column }); continue; } const countSql = ` SELECT COUNT(*)::int AS cnt FROM ${t.table} x WHERE x.${t.column} IS NOT NULL AND TRIM(x.${t.column}::text) <> '' AND NOT EXISTS ( SELECT 1 FROM orders o WHERE o.order_code = x.${t.column} )`; const cnt = Number((await client.query(countSql)).rows[0]?.cnt) || 0; if (cnt > 0) { const codes = await client.query( `SELECT DISTINCT x.${t.column}::text AS order_code FROM ${t.table} x WHERE x.${t.column} IS NOT NULL AND TRIM(x.${t.column}::text) <> '' AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = x.${t.column}) LIMIT 30` ); for (const row of codes.rows) sampleCodes.add(row.order_code); } let deleted = 0; if (EXECUTE && cnt > 0) { const del = await client.query( `DELETE FROM ${t.table} x WHERE x.${t.column} IS NOT NULL AND TRIM(x.${t.column}::text) <> '' AND NOT EXISTS ( SELECT 1 FROM orders o WHERE o.order_code = x.${t.column} )` ); deleted = del.rowCount || 0; } summary.push({ table: t.table, column: t.column, orphan_count: cnt, deleted: EXECUTE ? deleted : 0, }); console.log( `${t.table}.${t.column}: orphan=${cnt}${EXECUTE ? `, deleted=${deleted}` : ' (dry-run)'}` ); } // cost_details 额外金额汇总 if (await tableExists(client, 'cost_details')) { const amt = await client.query( `SELECT COALESCE(SUM(COALESCE(amount,0)),0)::numeric AS total FROM cost_details cd WHERE cd.order_code IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code)` ); console.log(`\ncost_details 孤儿金额合计: ¥${amt.rows[0].total}`); } console.log('\n孤儿订单号样本:', [...sampleCodes].slice(0, 40)); console.log('\n汇总:', JSON.stringify(summary, null, 2)); if (!EXECUTE) { console.log('\n[dry-run] 未删除。加上 --execute 执行清理。'); } else { console.log('\n清理完成。期间成本(order_code 为空)已保留。'); } } finally { client.release(); await pool.end(); } } main().catch((e) => { console.error(e); process.exit(1); });