#!/usr/bin/env node /** * 按分类名称智能调整 is_fresh(生鲜/非生鲜) */ const path = require('path'); const pg = require(path.join(__dirname, '../server/node_modules/pg')); const dotenv = require(path.join(__dirname, '../server/node_modules/dotenv')); const { inferCategoryIsFresh, } = require('./categoryFreshness.cjs'); dotenv.config({ path: path.join(__dirname, '../server/.env') }); const execute = process.argv.includes('--execute'); const dryRun = !execute; async function main() { if (!process.env.DATABASE_URL) { console.error('缺少 DATABASE_URL'); process.exit(1); } const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { const { rows: categories } = await client.query(` SELECT code, name, parent_code, level, is_fresh, branch_code FROM product_catalog WHERE item_type = 'category' ORDER BY COALESCE(parent_code, code), level, name `); const nameByCode = new Map(categories.map((row) => [row.code, row.name])); const changes = []; for (const row of categories) { const parentName = row.parent_code ? nameByCode.get(row.parent_code) || null : null; const target = inferCategoryIsFresh(row.name, parentName); const current = row.is_fresh === true; if (current !== target) { changes.push({ code: row.code, name: row.name, parent_name: parentName, from: current, to: target, }); } } if (dryRun) await client.query('BEGIN'); for (const change of changes) { if (!dryRun) { await client.query( `UPDATE product_catalog SET is_fresh = $2, updated_at = NOW() WHERE item_type = 'category' AND code = $1`, [change.code, change.to] ); } } if (dryRun) await client.query('ROLLBACK'); else await client.query('COMMIT'); console.log( JSON.stringify( { dryRun, totalCategories: categories.length, changed: changes.length, toFresh: changes.filter((item) => item.to).length, toNonFresh: changes.filter((item) => !item.to).length, changes: changes.map((item) => ({ name: item.parent_name ? `${item.parent_name} / ${item.name}` : item.name, from: item.from ? '生鲜' : '非生鲜', to: item.to ? '生鲜' : '非生鲜', })), }, null, 2 ) ); if (dryRun) console.log('\n[dry-run] 未写入。确认后加 --execute'); else console.log('\n分类生鲜属性已更新。'); } catch (error) { await client.query('ROLLBACK').catch(() => {}); throw error; } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });