#!/usr/bin/env node /** * 将源分公司商品库克隆到目标分公司(新 sku_code),并按商品名回写目标分公司报价单明细。 * * 用法: * node scripts/clone-products-to-branch.cjs --from BR001 --to BR002 --dry-run * node scripts/clone-products-to-branch.cjs --from BR001 --to BR002 --execute */ const path = require('path'); const { Pool } = require(path.join(__dirname, '../server/node_modules/pg')); const dotenv = require(path.join(__dirname, '../server/node_modules/dotenv')); dotenv.config({ path: path.join(__dirname, '../server/.env') }); const args = process.argv.slice(2); const execute = args.includes('--execute'); const fromIdx = args.indexOf('--from'); const toIdx = args.indexOf('--to'); const fromBranch = fromIdx >= 0 ? args[fromIdx + 1] : 'BR001'; const toBranch = toIdx >= 0 ? args[toIdx + 1] : 'BR002'; function generateCode(prefix) { return `${prefix}${Date.now().toString().slice(-9)}${Math.floor(Math.random() * 90 + 10)}`; } async function uniqueCode(client, prefix) { for (let i = 0; i < 8; i += 1) { const code = generateCode(prefix); const { rows } = await client.query(`SELECT 1 FROM product_catalog WHERE code = $1 LIMIT 1`, [code]); if (!rows.length) return code; } return `${prefix}${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`; } async function main() { if (!process.env.DATABASE_URL) throw new Error('缺少 DATABASE_URL'); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { console.log(`\n=== Clone products ${fromBranch} -> ${toBranch} (${execute ? 'EXECUTE' : 'DRY-RUN'}) ===\n`); const existingTarget = await client.query( `SELECT COUNT(*)::int AS n FROM product_catalog WHERE item_type='product' AND branch_code=$1`, [toBranch] ); console.log('target_products_before', existingTarget.rows[0].n); const sourceCats = await client.query( `SELECT code, name, parent_code, level, sort_order, loss_threshold, is_fresh, requires_photo_inspection, status FROM product_catalog WHERE item_type='category' AND branch_code=$1 ORDER BY level ASC, sort_order ASC NULLS LAST, name ASC`, [fromBranch] ); const sourceProducts = await client.query( `SELECT code, name, parent_code, unit, spec, barcode, brand, image_url, default_loss_threshold, sale_price, cost_price, is_prepackaged, tax_code, tax_rate, status FROM product_catalog WHERE item_type='product' AND branch_code=$1 ORDER BY name ASC`, [fromBranch] ); console.log('source_categories', sourceCats.rowCount, 'source_products', sourceProducts.rowCount); if (!execute) { console.log('\nDRY-RUN 完成。确认后加 --execute'); return; } await client.query('BEGIN'); await client.query(`ALTER TABLE product_catalog DISABLE TRIGGER trg_sync_product_catalog_to_legacy`); const categoryMap = new Map(); // fromCode -> toCode for (const cat of sourceCats.rows) { const existing = await client.query( `SELECT code FROM product_catalog WHERE item_type='category' AND branch_code=$1 AND name=$2 AND COALESCE(parent_code,'') = COALESCE($3,'') LIMIT 1`, [toBranch, cat.name, cat.parent_code ? categoryMap.get(cat.parent_code) || null : null] ); if (existing.rows[0]) { categoryMap.set(cat.code, existing.rows[0].code); continue; } const mappedParent = cat.parent_code ? categoryMap.get(cat.parent_code) || null : null; const newCode = await uniqueCode(client, 'CAT'); await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, level, sort_order, loss_threshold, is_fresh, requires_photo_inspection, status, branch_code ) VALUES ('category', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`, [ newCode, cat.name, mappedParent, cat.level || 1, cat.sort_order || 0, cat.loss_threshold ?? 5, cat.is_fresh ?? true, cat.requires_photo_inspection !== false, cat.status ?? 1, toBranch, ] ); await client.query( `INSERT INTO categories ( branch_code, category_code, parent_code, category_name, level, sort_order, loss_threshold, is_fresh, requires_photo_inspection, status ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) ON CONFLICT (branch_code, category_code) DO UPDATE SET parent_code = EXCLUDED.parent_code, category_name = EXCLUDED.category_name, level = EXCLUDED.level, sort_order = EXCLUDED.sort_order, loss_threshold = EXCLUDED.loss_threshold, is_fresh = EXCLUDED.is_fresh, requires_photo_inspection = EXCLUDED.requires_photo_inspection, status = EXCLUDED.status`, [ toBranch, newCode, mappedParent, cat.name, cat.level || 1, cat.sort_order || 0, cat.loss_threshold ?? 5, cat.is_fresh ?? true, cat.requires_photo_inspection !== false, cat.status ?? 1, ] ); categoryMap.set(cat.code, newCode); } const productMap = new Map(); // fromSku -> toSku let createdProducts = 0; let skippedProducts = 0; for (const product of sourceProducts.rows) { const existing = await client.query( `SELECT code FROM product_catalog WHERE item_type='product' AND branch_code=$1 AND name=$2 LIMIT 1`, [toBranch, product.name] ); if (existing.rows[0]) { productMap.set(product.code, existing.rows[0].code); skippedProducts += 1; continue; } const newCode = await uniqueCode(client, 'SKU'); const parentCode = product.parent_code ? categoryMap.get(product.parent_code) || null : null; await client.query( `INSERT INTO product_catalog ( item_type, code, name, parent_code, unit, spec, barcode, brand, image_url, default_loss_threshold, sale_price, cost_price, is_prepackaged, tax_code, tax_rate, status, branch_code ) VALUES ( 'product', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16 )`, [ newCode, product.name, parentCode, product.unit || '斤', product.spec, newCode, product.brand, product.image_url, product.default_loss_threshold, product.sale_price || 0, product.cost_price || 0, product.is_prepackaged || false, product.tax_code, product.tax_rate, product.status ?? 1, toBranch, ] ); await client.query( `INSERT INTO skus ( branch_code, sku_code, sku_name, category_code, unit, spec, barcode, image_url, is_prepackaged, brand, tax_code, tax_rate, default_loss_threshold, sale_price, cost_price, status ) VALUES ( $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16 ) ON CONFLICT (sku_code) DO UPDATE SET branch_code = EXCLUDED.branch_code, sku_name = EXCLUDED.sku_name, category_code = EXCLUDED.category_code`, [ toBranch, newCode, product.name, parentCode, product.unit || '斤', product.spec, newCode, product.image_url, product.is_prepackaged || false, product.brand, product.tax_code, product.tax_rate, product.default_loss_threshold, product.sale_price || 0, product.cost_price || 0, product.status ?? 1, ] ); productMap.set(product.code, newCode); createdProducts += 1; } // 回写目标分公司报价单明细 / 版本(按原 sku_code 映射) let remappedItems = 0; let remappedVersions = 0; for (const [fromSku, toSku] of productMap.entries()) { if (fromSku === toSku) continue; const items = await client.query( `UPDATE customer_quote_sheet_items i SET sku_code = $2 FROM customer_quote_sheets qs WHERE i.quote_sheet_code = qs.quote_sheet_code AND qs.branch_code = $3 AND i.sku_code = $1`, [fromSku, toSku, toBranch] ); remappedItems += items.rowCount || 0; const versions = await client.query( `UPDATE customer_quote_versions SET sku_code = $2 WHERE branch_code = $3 AND sku_code = $1`, [fromSku, toSku, toBranch] ); remappedVersions += versions.rowCount || 0; } await client.query(`ALTER TABLE product_catalog ENABLE TRIGGER trg_sync_product_catalog_to_legacy`); await client.query('COMMIT'); const after = await client.query( `SELECT COUNT(*)::int AS n FROM product_catalog WHERE item_type='product' AND branch_code=$1`, [toBranch] ); console.log('\nresult', { categoriesMapped: categoryMap.size, createdProducts, skippedProducts, remappedItems, remappedVersions, target_products_after: after.rows[0].n, }); } catch (error) { await client.query('ROLLBACK').catch(() => {}); await client .query(`ALTER TABLE product_catalog ENABLE TRIGGER trg_sync_product_catalog_to_legacy`) .catch(() => {}); throw error; } finally { client.release(); await pool.end(); } } main().catch((error) => { console.error(error); process.exit(1); });