/** * 清理 E2E 测试数据,并将旧 CYC* 履约周期更新为当前自然月周期。 * * 用法(生产机): * cd /opt/ai-fresh-delivery/server && node scripts/cleanup-e2e-test-data.mjs * node scripts/cleanup-e2e-test-data.mjs --execute * * 本地: * node server/scripts/cleanup-e2e-test-data.mjs --dry-run */ import pg from 'pg'; import { createRequire } from 'module'; import { fileURLToPath } from 'url'; import path from 'path'; const require = createRequire(import.meta.url); const { currentCycleCode } = require('./test-helpers.js'); const { Pool } = pg; const EXECUTE = process.argv.includes('--execute'); const DRY_RUN = !EXECUTE; const TARGET_CYCLE = process.env.TARGET_CYCLE || currentCycleCode(); const CYCLE_TABLES = [ 'orders', 'cost_details', 'bid_prices', 'customer_statements', 'supplier_statements', 'cost_adjustments', 'fixed_costs', ]; /** 测试订单:E2E 全链路;ORD_MP 客户小程序 E2E;ORD+旧周期为页面流程测试残留 */ const TEST_ORDER_SQL = ` SELECT order_code FROM orders WHERE order_code LIKE 'E2E%' OR order_code LIKE 'ORD_MP_%' OR (order_code LIKE 'ORD%' AND cycle_code ~ '^CYC') OR COALESCE(remark, '') ILIKE '%E2E%' OR COALESCE(remark, '') ILIKE '%流程测试%' OR COALESCE(remark, '') ILIKE '%全链路%' ORDER BY order_code `; 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 deleteByOrderCodes(client, orderCodes, dryRun = DRY_RUN) { 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 (pickCodes.length && (await columnExists(client, 'sign_records', 'pick_code'))) { steps.push({ label: 'sign_records(pick)', sql: `DELETE FROM sign_records WHERE pick_code = ANY($1::text[])`, params: [pickCodes], }); } else if (await columnExists(client, 'sign_records', 'order_code')) { steps.push({ label: 'sign_records(order)', sql: `DELETE FROM sign_records WHERE order_code = ANY($1::text[])`, params: [orderCodes], }); } 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); 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(related_order_code)', 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(related_order_code)', sql: `DELETE FROM exception_tickets WHERE related_order_code = ANY($1::text[])`, params: [orderCodes], }); } if (await tableExists(client, 'purchase_orders')) { steps.push({ label: 'purchase_orders(E2E code)', sql: `DELETE FROM purchase_orders WHERE purchase_code LIKE 'E2E%'`, params: [], }); } steps.push({ label: 'orders', sql: `DELETE FROM orders WHERE order_code = ANY($1::text[])`, params: [orderCodes], }); for (const step of steps) { if (dryRun) { console.log(` [dry] would delete from ${step.label}`); continue; } const r = await client.query(step.sql, step.params); console.log(` deleted ${step.label}: ${r.rowCount}`); } } async function updateLegacyCycles(client, dryRun = DRY_RUN) { console.log(`\n=== 更新旧履约周期 CYC* → ${TARGET_CYCLE} ===`); for (const table of CYCLE_TABLES) { if (!(await tableExists(client, table))) { console.log(` skip ${table} (missing)`); continue; } const preview = await client.query( `SELECT COUNT(*)::int AS c FROM ${table} WHERE cycle_code ~ '^CYC'` ); const count = preview.rows[0]?.c ?? 0; if (!count) { console.log(` ${table}: 0 rows`); continue; } if (dryRun) { const sample = await client.query( `SELECT cycle_code, COUNT(*)::int AS c FROM ${table} WHERE cycle_code ~ '^CYC' GROUP BY 1 ORDER BY 1 LIMIT 5` ); console.log(` [dry] ${table}: ${count} rows`, sample.rows); continue; } if (table === 'bid_prices') { // 避免 (bid_code, cycle_code, sku_code) 冲突:先删目标周期重复项 await client.query( `DELETE FROM bid_prices t USING bid_prices s WHERE t.cycle_code = $1 AND s.cycle_code ~ '^CYC' AND t.bid_code = s.bid_code AND t.sku_code = s.sku_code`, [TARGET_CYCLE] ); } const r = await client.query( `UPDATE ${table} SET cycle_code = $1 WHERE cycle_code ~ '^CYC'`, [TARGET_CYCLE] ); console.log(` updated ${table}: ${r.rowCount} rows`); } } export async function cleanupTestOrders(orderCodes, { execute = false, databaseUrl = process.env.DATABASE_URL } = {}) { if (!databaseUrl) throw new Error('DATABASE_URL required'); const pool = new Pool({ connectionString: databaseUrl }); const client = await pool.connect(); const dryRun = !execute; try { if (dryRun) { await deleteByOrderCodes(client, orderCodes, true); return; } await client.query('BEGIN'); try { await deleteByOrderCodes(client, orderCodes, false); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); throw e; } } finally { client.release(); await pool.end(); } } async function runCli() { const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); console.log(`\n=== E2E 测试数据清理 ===`); console.log(`模式: ${DRY_RUN ? 'DRY-RUN(加 --execute 执行)' : 'EXECUTE'}`); console.log(`目标周期: ${TARGET_CYCLE}\n`); try { await updateLegacyCycles(client, DRY_RUN); const orders = (await client.query(TEST_ORDER_SQL)).rows.map((r) => r.order_code); console.log(`\n=== 删除测试订单 (${orders.length}) ===`); if (orders.length) { console.log(orders.join(', ')); if (DRY_RUN) { await deleteByOrderCodes(client, orders, true); } else { await client.query('BEGIN'); try { await deleteByOrderCodes(client, orders, false); await client.query('COMMIT'); console.log(' committed'); } catch (e) { await client.query('ROLLBACK'); throw e; } } } else { console.log(' (无匹配测试订单)'); } console.log('\n完成。'); } finally { client.release(); await pool.end(); } } const isMain = process.argv[1] && path.resolve(fileURLToPath(import.meta.url)) === path.resolve(process.argv[1]); if (isMain) { runCli().catch((e) => { console.error(e); process.exit(1); }); }