#!/usr/bin/env node /** * 生产重置:仅保留「基础平台」分公司 (BR001),删除其他分公司及其全部业务数据。 * 保留:super_admin、平台级 permissions/roles、全局 skus(如有)。 * * 用法(在 test-api 上): * node prod-reset-to-platform-branch.mjs --dry-run * node prod-reset-to-platform-branch.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 KEEP_BRANCH = 'BR001'; const PLATFORM_NAME = '基础平台'; const SUPER_ADMIN = 'a0000000-0000-0000-0000-000000000001'; const execute = process.argv.includes('--execute'); const dryRun = !execute; /** 按 FK 依赖顺序删除(先子表后主表) */ const DELETE_ALL_ORDER = [ 'picking_scan_logs', 'picking_items', 'picking_containers', 'picking_tasks', 'inspection_returns', 'inspection_loss_confirmations', 'processing_logs', 'processing_tasks', 'inspections', 'delivery_signatures', 'order_allocation_batches', 'order_items', 'statement_disputes', 'statement_lines', 'sign_records', 'supplier_preparations', 'allocation_tasks', 'delivery_tasks', 'orders', 'after_sales', 'exception_tickets', 'cost_details', 'customer_statements', 'supplier_statements', 'invoices', 'cost_adjustments', 'fixed_costs', 'customer_quote_sheets', 'customer_quote_versions', 'customer_skus', 'customer_sku_aliases', 'customer_image_aliases', 'customer_alias_stats', 'alias_recognition_logs', 'voice_recognition_logs', 'customer_recipients', 'customer_portal_users', 'customer_processing_aliases', 'customer_delivery_assignments', 'customers', 'inventory_logs', 'inventory', 'purchase_orders', 'product_substitutions', 'supplier_rating_snapshots', 'market_price_indices', 'market_prices', 'seasonal_recommendations', 'bid_prices', 'sku_suppliers', 'supplier_users', 'supplier_categories', 'suppliers', 'delivery_location_history', 'delivery_person_locations', 'delivery_schedules', 'delivery_person_users', 'delivery_persons', 'warehouse_locations', 'warehouses', 'operation_logs', 'notifications', 'smart_classification_rules', ]; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); 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 hasBranchColumn(client, table) { const r = await client.query( `SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name='branch_code' LIMIT 1`, [table] ); return (r.rowCount || 0) > 0; } async function hasColumn(client, table, col) { 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, col] ); return (r.rowCount || 0) > 0; } async function deleteForBranches(client, table, branchCodes) { if (!(await tableExists(client, table))) return 0; if (await hasColumn(client, table, 'branch_code')) { const r = await client.query(`DELETE FROM ${table} WHERE branch_code = ANY($1::varchar[])`, [branchCodes]); return r.rowCount || 0; } if (await hasColumn(client, table, 'customer_code')) { const r = await client.query( `DELETE FROM ${table} WHERE customer_code IN (SELECT customer_code FROM customers WHERE branch_code = ANY($1::varchar[]))`, [branchCodes] ); return r.rowCount || 0; } if (await hasColumn(client, table, 'supplier_code')) { const r = await client.query( `DELETE FROM ${table} WHERE supplier_code IN (SELECT supplier_code FROM suppliers WHERE branch_code = ANY($1::varchar[]))`, [branchCodes] ); return r.rowCount || 0; } if (await hasColumn(client, table, 'order_no')) { const r = await client.query( `DELETE FROM ${table} WHERE order_no IN (SELECT order_no FROM orders WHERE branch_code = ANY($1::varchar[]))`, [branchCodes] ); return r.rowCount || 0; } return 0; } async function purgeForBranch(client, table, branchCode) { if (!(await tableExists(client, table))) return 0; if (await hasColumn(client, table, 'branch_code')) { const r = await client.query(`DELETE FROM ${table} WHERE branch_code = $1`, [branchCode]); return r.rowCount || 0; } if (await hasColumn(client, table, 'customer_code')) { const r = await client.query( `DELETE FROM ${table} WHERE customer_code IN (SELECT customer_code FROM customers WHERE branch_code = $1)`, [branchCode] ); return r.rowCount || 0; } if (await hasColumn(client, table, 'supplier_code')) { const r = await client.query( `DELETE FROM ${table} WHERE supplier_code IN (SELECT supplier_code FROM suppliers WHERE branch_code = $1)`, [branchCode] ); return r.rowCount || 0; } if (await hasColumn(client, table, 'order_no')) { const r = await client.query( `DELETE FROM ${table} WHERE order_no IN (SELECT order_no FROM orders WHERE branch_code = $1)`, [branchCode] ); return r.rowCount || 0; } return 0; } async function deleteAllFromTable(client, table) { if (!(await tableExists(client, table))) return 0; const r = await client.query(`DELETE FROM ${table}`); return r.rowCount || 0; } async function main() { const client = await pool.connect(); try { const branches = (await client.query(`SELECT branch_code, branch_name FROM branches ORDER BY branch_code`)).rows; const removeBranches = branches.filter((b) => b.branch_code !== KEEP_BRANCH).map((b) => b.branch_code); console.log('Mode:', dryRun ? 'DRY-RUN' : 'EXECUTE'); console.log('Keep branch:', KEEP_BRANCH, PLATFORM_NAME); console.log('Remove branches:', removeBranches.length ? removeBranches.join(', ') : '(none)'); if (dryRun) { for (const bc of removeBranches) { for (const table of ['orders', 'customers', 'suppliers', 'profiles']) { if (!(await tableExists(client, table)) || !(await hasBranchColumn(client, table))) continue; const r = await client.query(`SELECT count(*)::int c FROM ${table} WHERE branch_code = $1`, [bc]); if (r.rows[0]?.c) console.log(` would delete ${table}@${bc}:`, r.rows[0].c); } } const keep = branches.find((b) => b.branch_code === KEEP_BRANCH); console.log('Current BR001 name:', keep?.branch_name || '(missing — will create)'); return; } await client.query('BEGIN'); await client.query('ALTER TABLE product_catalog DISABLE TRIGGER trg_sync_product_catalog_to_legacy').catch(() => {}); for (const table of ['bid_prices']) { const n = await deleteAllFromTable(client, table); if (n) console.log('delete global', table, n); } // 1. 删除其他分公司业务数据 for (const table of DELETE_ALL_ORDER) { if (removeBranches.length) { const n = await deleteForBranches(client, table, removeBranches); if (n) console.log('delete branch-scoped', table, n); } } // product_catalog 按 branch(无 FK 但需清理) if (await tableExists(client, 'product_catalog') && removeBranches.length) { const n = ( await client.query(`DELETE FROM product_catalog WHERE branch_code = ANY($1::varchar[])`, [removeBranches]) ).rowCount; if (n) console.log('delete product_catalog', n); } // categories 复合主键 if (removeBranches.length) { const n = ( await client.query(`DELETE FROM categories WHERE branch_code = ANY($1::varchar[])`, [removeBranches]) ).rowCount; if (n) console.log('delete categories', n); } // system_configs 分公司配置 if (removeBranches.length) { const n = ( await client.query(`DELETE FROM system_configs WHERE branch_code = ANY($1::varchar[])`, [removeBranches]) ).rowCount; if (n) console.log('delete system_configs (branch)', n); } // 2. 删除其他分公司用户(保留 super_admin) if (removeBranches.length) { const users = ( await client.query(`SELECT id FROM profiles WHERE branch_code = ANY($1::varchar[])`, [removeBranches]) ).rows; for (const { id } of users) { await client.query(`DELETE FROM purchaser_users WHERE user_id = $1`, [id]).catch(() => {}); await client.query(`DELETE FROM supplier_users WHERE user_id = $1`, [id]).catch(() => {}); await client.query(`DELETE FROM delivery_person_users WHERE user_id = $1`, [id]).catch(() => {}); await client.query(`DELETE FROM user_roles WHERE user_id = $1`, [id]); await client.query(`DELETE FROM profiles WHERE id = $1`, [id]); await client.query(`DELETE FROM auth.users WHERE id = $1`, [id]); } console.log('deleted branch users', users.length); } // 3. 删除其他分公司 if (removeBranches.length) { const n = ( await client.query(`DELETE FROM branches WHERE branch_code = ANY($1::varchar[])`, [removeBranches]) ).rowCount; console.log('deleted branches', n); } // 4. 确保 BR001 = 基础平台 const keepRow = await client.query(`SELECT branch_code FROM branches WHERE branch_code = $1`, [KEEP_BRANCH]); if (!keepRow.rowCount) { await client.query( `INSERT INTO branches (branch_code, branch_name, contact_name, contact_phone, status) VALUES ($1, $2, '平台管理', '13800000000', 1)`, [KEEP_BRANCH, PLATFORM_NAME] ); console.log('created', KEEP_BRANCH, PLATFORM_NAME); } else { await client.query( `UPDATE branches SET branch_name = $2, status = 1, updated_at = NOW() WHERE branch_code = $1`, [KEEP_BRANCH, PLATFORM_NAME] ); console.log('renamed', KEEP_BRANCH, '->', PLATFORM_NAME); } // 5. BR001 LLM 配置 await client.query( `INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code) VALUES ( 'branch_llm_config', '{"enabled": false, "provider": "ark", "apiKeys": "", "model": "doubao-seed-2-0-lite-260428", "imageModel": "doubao-seedream-4-0-250828", "imageSize": "512x512", "baseUrl": "https://ark.cn-beijing.volces.com/api/v3"}'::jsonb, 'ai', '分公司大模型配置', $1 ) ON CONFLICT ((COALESCE(branch_code, '__GLOBAL__')), config_key) DO NOTHING`, [KEEP_BRANCH] ); // 6. 清空 BR001 残留业务数据(用户要「只留基础平台」= 干净 slate) for (const table of ['customer_recipients', 'customer_portal_users', 'customer_processing_aliases']) { if (!(await tableExists(client, table))) continue; const n = (await client.query(`DELETE FROM ${table}`)).rowCount; if (n) console.log('purge portal', table, n); } for (const table of DELETE_ALL_ORDER) { const n = await purgeForBranch(client, table, KEEP_BRANCH); if (n) console.log('purge keep-branch', table, n); } if (await tableExists(client, 'product_catalog')) { const n = (await client.query(`DELETE FROM product_catalog WHERE branch_code = $1`, [KEEP_BRANCH])).rowCount; if (n) console.log('purge product_catalog', n); } if (await tableExists(client, 'categories')) { const n = (await client.query(`DELETE FROM categories WHERE branch_code = $1`, [KEEP_BRANCH])).rowCount; if (n) console.log('purge categories', n); } // 7. 非 super_admin 的 BR001 用户也清掉(重新由运维创建) const branchUsers = ( await client.query(`SELECT id FROM profiles WHERE branch_code = $1 AND id <> $2`, [KEEP_BRANCH, SUPER_ADMIN]) ).rows; for (const { id } of branchUsers) { await client.query(`DELETE FROM purchaser_users WHERE user_id = $1`, [id]).catch(() => {}); await client.query(`DELETE FROM supplier_users WHERE user_id = $1`, [id]).catch(() => {}); await client.query(`DELETE FROM delivery_person_users WHERE user_id = $1`, [id]).catch(() => {}); await client.query(`DELETE FROM user_roles WHERE user_id = $1`, [id]); await client.query(`DELETE FROM profiles WHERE id = $1`, [id]); await client.query(`DELETE FROM auth.users WHERE id = $1`, [id]); } if (branchUsers.length) console.log('purged non-superadmin BR001 users', branchUsers.length); // 8. 清理 branch_code IS NULL 的遗留业务行(保留 profiles.super_admin) for (const table of DELETE_ALL_ORDER) { if (!(await tableExists(client, table)) || !(await hasBranchColumn(client, table))) continue; const n = (await client.query(`DELETE FROM ${table} WHERE branch_code IS NULL`)).rowCount; if (n) console.log('purge null branch', table, n); } if (await tableExists(client, 'product_catalog')) { const n = (await client.query(`DELETE FROM product_catalog WHERE branch_code IS NULL`)).rowCount; if (n) console.log('purge null product_catalog', n); } await client.query('ALTER TABLE product_catalog ENABLE TRIGGER trg_sync_product_catalog_to_legacy').catch(() => {}); await client.query('COMMIT'); console.log('\n=== DONE ==='); const summary = ( await pool.query( `SELECT 'branches' AS item, count(*)::int AS cnt FROM branches UNION ALL SELECT 'orders', count(*)::int FROM orders UNION ALL SELECT 'customers', count(*)::int FROM customers UNION ALL SELECT 'profiles', count(*)::int FROM profiles` ) ).rows; console.log(JSON.stringify(summary, null, 2)); } catch (e) { if (!dryRun) await client.query('ROLLBACK').catch(() => {}); throw e; } finally { client.release(); await pool.end(); } } main().catch((e) => { console.error(e); process.exit(1); });