#!/usr/bin/env node /** 只读:列出分公司及各表 branch_code 分布 */ 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 pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const BRANCH_TABLES = [ 'customers', 'suppliers', 'orders', 'purchase_orders', 'supplier_preparations', 'delivery_tasks', 'inventory', 'customer_statements', 'supplier_statements', 'profiles', 'categories', 'warehouses', 'delivery_persons', 'inspections', 'picking_tasks', 'system_configs', 'after_sales', 'exception_tickets', 'invoices', 'customer_delivery_assignments', 'processing_tasks', 'cost_details', ]; async function main() { const branches = ( await pool.query(`SELECT branch_code, branch_name, contact_name, contact_phone, status FROM branches ORDER BY branch_code`) ).rows; console.log('=== BRANCHES ==='); console.log(JSON.stringify(branches, null, 2)); console.log('\n=== COUNTS BY branch_code ==='); for (const table of BRANCH_TABLES) { const exists = await pool.query(`SELECT to_regclass('public.' || $1) IS NOT NULL AS ok`, [table]); if (!exists.rows[0]?.ok) continue; const cols = await pool.query( `SELECT column_name FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name='branch_code'`, [table] ); if (!cols.rowCount) continue; const rows = ( await pool.query(`SELECT branch_code, count(*)::int AS c FROM ${table} GROUP BY branch_code ORDER BY branch_code`) ).rows; if (rows.length) console.log(table, JSON.stringify(rows)); } const users = ( await pool.query( `SELECT p.username, p.full_name, p.branch_code, array_agg(ur.role::text) roles FROM profiles p LEFT JOIN user_roles ur ON ur.user_id = p.id GROUP BY p.id, p.username, p.full_name, p.branch_code ORDER BY p.branch_code NULLS FIRST, p.username` ) ).rows; console.log('\n=== USERS ==='); console.log(JSON.stringify(users, null, 2)); await pool.end(); } main().catch((e) => { console.error(e); process.exit(1); });