#!/usr/bin/env node /** * 列出并删除最近批量导入的 product_catalog 数据(商品 + 分类) * 用法: * node prod-cleanup-recent-import.js list [--hours 24] * node prod-cleanup-recent-import.js delete --hours 2 [--dry-run] * node prod-cleanup-recent-import.js delete --codes CATxxx,SKUxxx [--dry-run] */ require('dotenv').config(); const path = require('path'); const { Pool } = require('pg'); function parseArgs(argv) { const args = { action: argv[2] || 'list', hours: 2, dryRun: false, codes: [], since: '', until: '', codePrefix: [], }; for (let i = 3; i < argv.length; i += 1) { const arg = argv[i]; if (arg === '--dry-run') args.dryRun = true; else if (arg === '--hours' && argv[i + 1]) { args.hours = Number(argv[++i]) || 2; } else if (arg === '--since' && argv[i + 1]) { args.since = argv[++i]; } else if (arg === '--until' && argv[i + 1]) { args.until = argv[++i]; } else if (arg === '--code-prefix' && argv[i + 1]) { args.codePrefix = argv[++i].split(',').map((s) => s.trim()).filter(Boolean); } else if (arg === '--codes' && argv[i + 1]) { args.codes = argv[++i].split(',').map((s) => s.trim()).filter(Boolean); } } return args; } async function fetchTargets(pool, { hours, codes, since, until, codePrefix }) { if (codes.length) { const products = await pool.query( `SELECT item_type, code, name, parent_code, created_at FROM product_catalog WHERE code = ANY($1::text[])`, [codes] ); const categoryCodes = products.rows .filter((r) => r.item_type === 'category') .map((r) => r.code); const productParentCodes = products.rows .filter((r) => r.item_type === 'product' && r.parent_code) .map((r) => r.parent_code); const extraCodes = [...new Set([...categoryCodes, ...productParentCodes])].filter( (c) => !codes.includes(c) ); if (extraCodes.length) { const extra = await pool.query( `SELECT item_type, code, name, parent_code, created_at FROM product_catalog WHERE code = ANY($1::text[])`, [extraCodes] ); return [...products.rows, ...extra.rows]; } return products.rows; } if (since || until || codePrefix.length) { const conditions = []; const params = []; if (since) { params.push(since); conditions.push(`created_at >= $${params.length}::timestamptz`); } if (until) { params.push(until); conditions.push(`created_at <= $${params.length}::timestamptz`); } if (codePrefix.length) { const prefixConditions = codePrefix.map((prefix) => { params.push(`${prefix}%`); return `code LIKE $${params.length}`; }); conditions.push(`(${prefixConditions.join(' OR ')})`); } const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''; const recent = await pool.query( `SELECT item_type, code, name, parent_code, created_at FROM product_catalog ${where} ORDER BY created_at DESC, item_type, name`, params ); return recent.rows; } const recent = await pool.query( `SELECT item_type, code, name, parent_code, created_at FROM product_catalog WHERE created_at >= NOW() - ($1::text || ' hours')::interval ORDER BY created_at DESC, item_type, name`, [String(hours)] ); return recent.rows; } async function deleteImported(pool, rows, dryRun) { const products = rows.filter((r) => r.item_type === 'product'); const categories = rows.filter((r) => r.item_type === 'category'); const l2 = categories.filter((c) => c.parent_code); const l1 = categories.filter((c) => !c.parent_code); console.log('\n=== 待删除商品 ==='); console.table(products.map(({ code, name, parent_code, created_at }) => ({ code, name, parent_code, created_at }))); console.log('\n=== 待删除二级分类 ==='); console.table(l2.map(({ code, name, parent_code, created_at }) => ({ code, name, parent_code, created_at }))); console.log('\n=== 待删除一级分类 ==='); console.table(l1.map(({ code, name, created_at }) => ({ code, name, created_at }))); if (dryRun) { console.log('\n[dry-run] 未执行删除'); return; } const client = await pool.connect(); try { await client.query('BEGIN'); for (const row of products) { await client.query('DELETE FROM product_catalog WHERE code = $1', [row.code]); console.log('deleted product', row.code, row.name); } for (const row of l2) { const childProducts = await client.query( 'SELECT COUNT(*)::int AS c FROM product_catalog WHERE item_type = $1 AND parent_code = $2', ['product', row.code] ); if (childProducts.rows[0].c > 0) { console.log('skip L2 category (has products)', row.code, row.name); continue; } await client.query('DELETE FROM product_catalog WHERE code = $1', [row.code]); console.log('deleted L2 category', row.code, row.name); } for (const row of l1) { const childCats = await client.query( 'SELECT COUNT(*)::int AS c FROM product_catalog WHERE item_type = $1 AND parent_code = $2', ['category', row.code] ); const childProducts = await client.query( 'SELECT COUNT(*)::int AS c FROM product_catalog WHERE item_type = $1 AND parent_code = $2', ['product', row.code] ); if (childCats.rows[0].c > 0 || childProducts.rows[0].c > 0) { console.log('skip L1 category (has children)', row.code, row.name); continue; } await client.query('DELETE FROM product_catalog WHERE code = $1', [row.code]); console.log('deleted L1 category', row.code, row.name); } await client.query('COMMIT'); console.log('\n删除完成'); } catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); } } async function main() { const args = parseArgs(process.argv); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); try { const rows = await fetchTargets(pool, args); console.log( `\n找到 ${rows.length} 条记录 (hours=${args.hours}, since=${args.since || '-'}, until=${args.until || '-'}, prefix=${args.codePrefix.join('|') || '-'}, codes=${args.codes.join(',') || 'auto'})` ); console.table(rows.map(({ item_type, code, name, parent_code, created_at }) => ({ item_type, code, name, parent_code, created_at, }))); if (args.action === 'delete') { await deleteImported(pool, rows, args.dryRun); } } finally { await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });