#!/bin/bash # 清空数十张业务表,仅保留 superadmin。用法: prod-cleanup-legacy-data.sh [--yes] set -euo pipefail cd /opt/ai-fresh-delivery/server SKIP_CONFIRM=0 for arg in "$@"; do [ "$arg" = "--yes" ] && SKIP_CONFIRM=1 done DB=$(grep -m1 '^DATABASE_URL=' .env | cut -d= -f2- || true) DB_MASKED=$(node -e "try{const u=new URL(process.argv[1]); if(u.password) u.password='***'; console.log(u.toString())}catch{console.log('(DATABASE_URL 未设置或无法解析)')}" "$DB") echo "" echo "!!! 危险操作:将 DELETE 约 45 张业务表(orders/customers/skus/suppliers/...)" echo " 并删除除 superadmin 外的全部用户 (user_roles/profiles/auth.users)" echo " 目标数据库: $DB_MASKED" if [ "$SKIP_CONFIRM" -ne 1 ]; then printf '确认继续请输入 YES: ' read -r CONFIRM if [ "$CONFIRM" != "YES" ]; then echo "已取消。" exit 1 fi fi node <<'NODE' require('dotenv').config(); const fs = require('fs'); const { Pool } = require('pg'); const SUPER_ADMIN = 'a0000000-0000-0000-0000-000000000001'; const deletes = [ 'order_items', 'delivery_tasks', 'sign_records', 'supplier_preparations', 'allocation_tasks', 'orders', 'processing_logs', 'inspections', 'after_sales', 'exception_tickets', 'cost_details', 'customer_statements', 'supplier_statements', 'invoices', 'cost_adjustments', 'fixed_costs', 'customer_skus', 'customer_sku_aliases', 'customer_image_aliases', 'customer_alias_stats', 'alias_recognition_logs', 'voice_recognition_logs', 'customers', 'inventory_logs', 'inventory', 'purchase_orders', 'bid_prices', 'sku_suppliers', 'skus', 'categories', 'supplier_users', 'supplier_categories', 'suppliers', 'delivery_location_history', 'delivery_person_locations', 'delivery_schedules', 'delivery_person_users', 'delivery_persons', 'purchaser_users', 'warehouse_locations', 'warehouses', 'operation_logs', 'notifications', ]; (async () => { const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { await client.query('BEGIN'); for (const table of deletes) { const exists = await client.query(`SELECT to_regclass('public.' || $1) IS NOT NULL AS ok`, [table]); if (!exists.rows[0]?.ok) { console.log('skip', table); continue; } const r = await client.query(`DELETE FROM ${table}`); console.log('delete', table, r.rowCount); } await client.query(`DELETE FROM user_roles WHERE user_id <> $1`, [SUPER_ADMIN]); await client.query(`DELETE FROM profiles WHERE id <> $1`, [SUPER_ADMIN]); await client.query(`DELETE FROM auth.users WHERE id <> $1`, [SUPER_ADMIN]); await client.query('COMMIT'); console.log('DB cleanup committed'); } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); await pool.end(); } })().catch((e) => { console.error(e); process.exit(1); }); NODE