#!/usr/bin/env node /** * 删除指定分公司的分类数据(categories + product_catalog 分类行) * * 用法: * node prod-purge-branch-categories.mjs [BRANCH] --dry-run (默认) * node prod-purge-branch-categories.mjs [BRANCH] --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 args = process.argv.slice(2).filter((a) => !a.startsWith('--')); const execute = process.argv.includes('--execute'); const dryRun = !execute; const BRANCH = args[0] || 'BR001'; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); async function countRows(client, sql, params = []) { const { rows } = await client.query(sql, params); return Number(rows[0]?.c ?? 0); } async function main() { const client = await pool.connect(); try { const counts = { smart_classification_rules: await countRows( client, `SELECT COUNT(*)::int AS c FROM smart_classification_rules WHERE branch_code = $1`, [BRANCH] ), product_catalog_categories: await countRows( client, `SELECT COUNT(*)::int AS c FROM product_catalog WHERE branch_code = $1 AND item_type = 'category'`, [BRANCH] ), categories: await countRows(client, `SELECT COUNT(*)::int AS c FROM categories WHERE branch_code = $1`, [ BRANCH, ]), }; console.log(JSON.stringify({ dryRun, branch: BRANCH, toDelete: counts }, null, 2)); if (dryRun) { console.log('\n[dry-run] 未执行删除。确认后加 --execute'); return; } await client.query('BEGIN'); await client.query('ALTER TABLE product_catalog DISABLE TRIGGER trg_sync_product_catalog_to_legacy').catch(() => {}); const rules = ( await client.query(`DELETE FROM smart_classification_rules WHERE branch_code = $1`, [BRANCH]) ).rowCount; const catalog = ( await client.query( `DELETE FROM product_catalog WHERE branch_code = $1 AND item_type = 'category'`, [BRANCH] ) ).rowCount; const categories = (await client.query(`DELETE FROM categories WHERE branch_code = $1`, [BRANCH])).rowCount; await client.query('ALTER TABLE product_catalog ENABLE TRIGGER trg_sync_product_catalog_to_legacy').catch(() => {}); await client.query('COMMIT'); console.log(JSON.stringify({ branch: BRANCH, smart_classification_rules: rules, product_catalog_categories: catalog, categories }, null, 2)); } catch (e) { await client.query('ROLLBACK').catch(() => {}); throw e; } finally { client.release(); await pool.end(); } } main().catch((e) => { console.error(e); process.exit(1); });