#!/usr/bin/env node /** * 删除测试客户 CUS35178701641(公司名「测试」)及 ORD_MP_* 小程序测试订单的全部关联数据。 * 用法: node prod-cleanup-test-customer.cjs [--execute] */ process.chdir('/opt/ai-fresh-delivery/server'); require('./dist/env.js').loadEnv(); const { pool } = require('./dist/db.js'); const EXECUTE = process.argv.includes('--execute'); const TEST_CUSTOMER = process.env.TEST_CUSTOMER_CODE || 'CUS35178701641'; 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 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`, [table, column] ); return r.rowCount > 0; } async function collectOrderCodes(client) { const byCustomer = await client.query( `SELECT order_code FROM orders WHERE customer_code = $1`, [TEST_CUSTOMER] ); const byMp = await client.query(`SELECT order_code FROM orders WHERE order_code LIKE 'ORD_MP_%'`); const orphanMp = await client.query( `SELECT DISTINCT order_code FROM ( SELECT order_code FROM cost_details WHERE order_code LIKE 'ORD_MP_%' UNION SELECT order_code FROM supplier_preparations WHERE order_code LIKE 'ORD_MP_%' UNION SELECT order_code FROM purchase_orders WHERE order_code LIKE 'ORD_MP_%' UNION SELECT order_code FROM inspections WHERE order_code LIKE 'ORD_MP_%' ) t WHERE order_code IS NOT NULL` ); return [...new Set([ ...byCustomer.rows.map((r) => r.order_code), ...byMp.rows.map((r) => r.order_code), ...orphanMp.rows.map((r) => r.order_code), ])].filter(Boolean); } async function deleteOrders(client, orderCodes, dryRun) { if (!orderCodes.length) return; const pickCodes = ( await client.query(`SELECT pick_code FROM picking_tasks WHERE order_code = ANY($1::text[])`, [orderCodes]) ).rows.map((r) => r.pick_code); const inspectionIds = ( await client.query(`SELECT id FROM inspections WHERE order_code = ANY($1::text[])`, [orderCodes]) ).rows.map((r) => r.id); const steps = []; if (pickCodes.length && (await tableExists(client, 'picking_items'))) { steps.push({ label: 'picking_items', sql: `DELETE FROM picking_items WHERE pick_code = ANY($1::text[])`, params: [pickCodes], }); } if (inspectionIds.length && (await tableExists(client, 'inspection_returns'))) { steps.push({ label: 'inspection_returns', sql: `DELETE FROM inspection_returns WHERE inspection_id = ANY($1::uuid[])`, params: [inspectionIds], }); } if (inspectionIds.length && (await tableExists(client, 'inspection_loss_confirmations'))) { steps.push({ label: 'inspection_loss_confirmations', sql: `DELETE FROM inspection_loss_confirmations WHERE inspection_id = ANY($1::uuid[])`, params: [inspectionIds], }); } const orderTables = ( await client.query( `SELECT DISTINCT table_name FROM information_schema.columns WHERE table_schema = 'public' AND column_name = 'order_code' AND table_name <> 'orders' ORDER BY table_name` ) ).rows.map((r) => r.table_name).filter((t) => t !== 'statement_lines'); for (const table of orderTables) { steps.push({ label: table, sql: `DELETE FROM ${table} WHERE order_code = ANY($1::text[])`, params: [orderCodes], }); } if (await columnExists(client, 'inventory_logs', 'related_order_code')) { steps.push({ label: 'inventory_logs', sql: `DELETE FROM inventory_logs WHERE related_order_code = ANY($1::text[])`, params: [orderCodes], }); } if (await columnExists(client, 'exception_tickets', 'related_order_code')) { steps.push({ label: 'exception_tickets', sql: `DELETE FROM exception_tickets WHERE related_order_code = ANY($1::text[])`, params: [orderCodes], }); } steps.push({ label: 'orders', sql: `DELETE FROM orders WHERE order_code = ANY($1::text[])`, params: [orderCodes], }); for (const step of steps) { if (dryRun) { const countSql = step.sql.replace(/^DELETE FROM /, 'SELECT COUNT(*)::int AS c FROM '); const preview = await client.query(countSql, step.params); console.log(` [dry] ${step.label}: ${preview.rows[0]?.c ?? '?'}`); } else { const r = await client.query(step.sql, step.params); console.log(` deleted ${step.label}: ${r.rowCount}`); } } } async function cleanupSupplierStatements(client, orderCodes, dryRun) { if (!orderCodes.length) return; const stmtNos = ( await client.query( `SELECT DISTINCT statement_no FROM statement_lines WHERE statement_type = 'supplier' AND order_code = ANY($1::text[])`, [orderCodes] ) ).rows.map((r) => r.statement_no); if (dryRun) { const cnt = await client.query( `SELECT COUNT(*)::int AS c FROM statement_lines WHERE statement_type = 'supplier' AND order_code = ANY($1::text[])`, [orderCodes] ); console.log(` [dry] supplier statement_lines to remove: ${cnt.rows[0]?.c ?? 0} (${stmtNos.length} statements)`); return; } await client.query( `DELETE FROM statement_lines WHERE statement_type = 'supplier' AND order_code = ANY($1::text[])`, [orderCodes] ); for (const statementNo of stmtNos) { const sum = await client.query( `SELECT COALESCE(SUM(line_amount), 0)::numeric AS total FROM statement_lines WHERE statement_no = $1 AND statement_type = 'supplier'`, [statementNo] ); const total = Number(sum.rows[0]?.total || 0); if (total <= 0) { await client.query(`DELETE FROM statement_disputes WHERE statement_no = $1`, [statementNo]); await client.query(`DELETE FROM supplier_statements WHERE statement_no = $1`, [statementNo]); console.log(` removed empty supplier statement ${statementNo}`); } else { await client.query( `UPDATE supplier_statements SET total_amount = $2, payable_amount = $2 - COALESCE(deduction_amount, 0) WHERE statement_no = $1`, [statementNo, total] ); console.log(` recalculated supplier statement ${statementNo} -> ${total}`); } } } async function deleteTestCustomer(client, dryRun) { const customer = await client.query( `SELECT customer_code, company_name FROM customers WHERE customer_code = $1`, [TEST_CUSTOMER] ); if (!customer.rowCount) { console.log(' test customer already removed'); return; } console.log(` customer: ${customer.rows[0].company_name} (${TEST_CUSTOMER})`); const orderLeft = await client.query(`SELECT COUNT(*)::int AS c FROM orders WHERE customer_code = $1`, [ TEST_CUSTOMER, ]); if (orderLeft.rows[0]?.c > 0) { console.log(` skip customer delete: ${orderLeft.rows[0].c} orders remain`); return; } if (dryRun) { console.log(' [dry] would delete customer portal data and customer row'); return; } const portalUsers = await client.query(`SELECT user_id FROM customer_portal_users WHERE customer_code = $1`, [ TEST_CUSTOMER, ]); const portalUserIds = portalUsers.rows.map((r) => String(r.user_id)); const tables = [ 'alias_recognition_logs', 'customer_alias_stats', 'customer_quote_sheet_customers', 'customer_quote_versions', 'customer_processing_aliases', 'customer_sku_aliases', 'customer_image_aliases', 'customer_skus', 'customer_recipients', 'customer_portal_users', 'customer_delivery_assignments', ]; for (const table of tables) { if (await tableExists(client, table)) { const r = await client.query(`DELETE FROM ${table} WHERE customer_code = $1`, [TEST_CUSTOMER]); if (r.rowCount) console.log(` deleted ${table}: ${r.rowCount}`); } } const statements = await client.query(`SELECT statement_no FROM customer_statements WHERE customer_code = $1`, [ TEST_CUSTOMER, ]); for (const stmt of statements.rows) { const statementNo = String(stmt.statement_no); await client.query(`DELETE FROM statement_disputes WHERE statement_no = $1`, [statementNo]); await client.query(`DELETE FROM statement_lines WHERE statement_no = $1`, [statementNo]); await client.query(`DELETE FROM customer_statements WHERE statement_no = $1`, [statementNo]); } await client.query(`DELETE FROM customers WHERE customer_code = $1`, [TEST_CUSTOMER]); for (const userId of portalUserIds) { const other = await client.query( `SELECT 1 FROM supplier_users WHERE user_id = $1 UNION ALL SELECT 1 FROM purchaser_users WHERE user_id = $1 UNION ALL SELECT 1 FROM delivery_person_users WHERE user_id = $1 UNION ALL SELECT 1 FROM customer_portal_users WHERE user_id = $1 LIMIT 1`, [userId] ); if (other.rowCount) continue; await client.query(`DELETE FROM user_roles WHERE user_id = $1`, [userId]); await client.query(`DELETE FROM profiles WHERE id = $1`, [userId]); await client.query(`DELETE FROM auth.users WHERE id = $1`, [userId]); } console.log(' deleted test customer and portal users'); } (async () => { const client = await pool.connect(); const dryRun = !EXECUTE; console.log(`\n=== 清理测试客户 ${TEST_CUSTOMER} / ORD_MP_* ===`); console.log(`模式: ${dryRun ? 'DRY-RUN(加 --execute 执行)' : 'EXECUTE'}\n`); try { const orderCodes = await collectOrderCodes(client); console.log(`订单/孤儿引用 (${orderCodes.length}):`); console.log(orderCodes.join(', ') || '(无)'); if (dryRun) { await cleanupSupplierStatements(client, orderCodes, true); await deleteOrders(client, orderCodes, true); await deleteTestCustomer(client, true); } else { await client.query('BEGIN'); try { await cleanupSupplierStatements(client, orderCodes, false); await deleteOrders(client, orderCodes, false); await deleteTestCustomer(client, false); await client.query('COMMIT'); console.log('\ncommitted'); } catch (e) { await client.query('ROLLBACK'); throw e; } } console.log('\n完成'); } finally { client.release(); await pool.end(); } })().catch((e) => { console.error(e); process.exit(1); });