#!/usr/bin/env node /** * 从自贡分公司历史订单提取最新成交价,写入报价单并物化 customer_quote_versions。 * * 用法(生产机): * node scripts/prod-migrate-zigong-quote-from-orders.mjs [--dry-run|--execute] [branchKeyword] * * 策略: * - 每个客户取 (customer_code, sku_code) 最新订单行的 COALESCE(locked_price, price) * - 价格画像相同的客户合并到同一张报价单(同 SKU 必须同价) * - 价格画像不同的客户各建一张报价单 */ import pg from 'pg'; import { readFileSync } from 'fs'; import { createHash } from 'crypto'; const args = process.argv.slice(2); const execute = args.includes('--execute'); const dryRun = !execute; const branchKeyword = args.find((a) => !a.startsWith('--')) || '自贡'; const envPath = process.env.ENV_PATH || '/opt/ai-fresh-delivery/server/.env'; function loadDbUrl() { if (process.env.DATABASE_URL) return process.env.DATABASE_URL; const env = readFileSync(envPath, 'utf8'); return env.match(/^DATABASE_URL=(.+)$/m)[1].trim().replace(/^["']|["']$/g, ''); } function newSheetCode() { return `QS${Date.now()}${Math.random().toString(36).slice(2, 6).toUpperCase()}`; } function newQuoteVersionCode() { return `QV${Date.now()}${Math.random().toString(36).slice(2, 8).toUpperCase()}`; } function computeExpiresAt(from, cycle) { const daysMap = { week: 7, half_month: 15, month: 30, half_year: 180, year: 365 }; const days = daysMap[cycle] || 30; return new Date(from.getTime() + days * 86400000); } function priceFingerprint(items) { const sorted = [...items].sort((a, b) => a.sku_code.localeCompare(b.sku_code)); const raw = sorted.map((i) => `${i.sku_code}:${Number(i.price).toFixed(2)}`).join('|'); return createHash('sha1').update(raw).digest('hex').slice(0, 12); } const EXTRACT_SQL = ` WITH ranked AS ( SELECT o.customer_code, oi.sku_code, COALESCE(NULLIF(TRIM(oi.unit), ''), '斤') AS unit, COALESCE(NULLIF(TRIM(oi.item_name), ''), s.sku_name, oi.sku_code) AS sku_name, COALESCE(NULLIF(oi.locked_price, 0), oi.price)::numeric AS price, o.created_at, ROW_NUMBER() OVER ( PARTITION BY o.customer_code, oi.sku_code ORDER BY o.created_at DESC, oi.created_at DESC NULLS LAST, oi.id DESC ) AS rn FROM order_items oi JOIN orders o ON o.order_code = oi.order_code LEFT JOIN skus s ON s.sku_code = oi.sku_code WHERE o.branch_code = $1 AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> '' AND COALESCE(NULLIF(oi.locked_price, 0), oi.price) > 0 ) SELECT customer_code, sku_code, unit, sku_name, price FROM ranked WHERE rn = 1 ORDER BY customer_code, sku_code `; async function nextSheetVersionNo(client, branchCode) { const r = await client.query( `SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version FROM customer_quote_sheets WHERE branch_code = $1`, [branchCode] ); return Number(r.rows[0]?.next_version) || 1; } async function activateQuoteSheet(client, quoteSheetCode) { const result = await client.query( `UPDATE customer_quote_sheets SET approval_status = 30, approved_at = NOW(), status = 1, effective_at = COALESCE(effective_at, NOW()), expires_at = COALESCE(expires_at, NOW() + INTERVAL '30 days'), updated_at = NOW() WHERE quote_sheet_code = $1 RETURNING *`, [quoteSheetCode] ); if (!result.rows.length) throw new Error(`报价单不存在: ${quoteSheetCode}`); const sheet = result.rows[0]; await client.query( `UPDATE customer_quote_sheets SET status = 3, updated_at = NOW() WHERE quote_sheet_code <> $1 AND status = 1 AND approval_status = 30 AND branch_code IS NOT DISTINCT FROM $2 AND quote_sheet_code IN ( SELECT qsc1.quote_sheet_code FROM customer_quote_sheet_customers qsc1 WHERE qsc1.customer_code IN ( SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1 ) )`, [quoteSheetCode, sheet.branch_code] ); const [itemsResult, customersResult] = await Promise.all([ client.query(`SELECT * FROM customer_quote_sheet_items WHERE quote_sheet_code = $1`, [quoteSheetCode]), client.query(`SELECT customer_code FROM customer_quote_sheet_customers WHERE quote_sheet_code = $1`, [ quoteSheetCode, ]), ]); for (const customerRow of customersResult.rows) { const customerCode = customerRow.customer_code; for (const item of itemsResult.rows) { const versionResult = await client.query( `SELECT COALESCE(MAX(version_no), 0) + 1 AS next_version FROM customer_quote_versions WHERE customer_code = $1 AND sku_code = $2`, [customerCode, item.sku_code] ); const versionNo = Number(versionResult.rows[0]?.next_version) || 1; await client.query( `UPDATE customer_quote_versions SET status = 0, expired_at = NOW() WHERE customer_code = $1 AND sku_code = $2 AND status = 1 AND branch_code IS NOT DISTINCT FROM $3`, [customerCode, item.sku_code, sheet.branch_code] ); await client.query( `INSERT INTO customer_quote_versions (quote_version_code, customer_code, sku_code, unit, price, version_no, source_type, branch_code, status, approval_status, quote_cycle, expires_at, effective_at, quote_sheet_code, approved_at) VALUES ($1,$2,$3,$4,$5,$6,'order_price_migration',$7,1,30,$8,$9,NOW(),$10,NOW())`, [ newQuoteVersionCode(), customerCode, item.sku_code, item.unit, item.price, versionNo, sheet.branch_code, sheet.quote_cycle, sheet.expires_at, quoteSheetCode, ] ); } } return sheet; } async function createQuoteSheetForGroup(client, branchCode, customerCodes, items, versionNo) { const quoteSheetCode = newSheetCode(); const effectiveAt = new Date(); const quoteCycle = 'month'; const expiresAt = computeExpiresAt(effectiveAt, quoteCycle); const title = `自贡订单价格迁移 V${versionNo}`; await client.query( `INSERT INTO customer_quote_sheets (quote_sheet_code, title, version_no, quote_cycle, effective_at, expires_at, status, approval_status, branch_code, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, 0, 10, $7, NOW(), NOW())`, [quoteSheetCode, title, versionNo, quoteCycle, effectiveAt.toISOString(), expiresAt.toISOString(), branchCode] ); for (const customerCode of customerCodes) { await client.query( `INSERT INTO customer_quote_sheet_customers (quote_sheet_code, customer_code) VALUES ($1, $2)`, [quoteSheetCode, customerCode] ); } for (let i = 0; i < items.length; i += 1) { const item = items[i]; await client.query( `INSERT INTO customer_quote_sheet_items (quote_sheet_code, sku_code, sku_name, unit, price, sort_order) VALUES ($1, $2, $3, $4, $5, $6)`, [quoteSheetCode, item.sku_code, item.sku_name, item.unit, item.price, i] ); } await activateQuoteSheet(client, quoteSheetCode); return { quoteSheetCode, title, customerCount: customerCodes.length, itemCount: items.length }; } const pool = new pg.Pool({ connectionString: loadDbUrl() }); try { console.log(`\n=== 自贡订单价格 → 报价库迁移 (${dryRun ? 'DRY-RUN' : 'EXECUTE'}) ===\n`); const branches = await pool.query( `SELECT branch_code, branch_name FROM branches WHERE branch_name ILIKE $1 OR branch_code ILIKE $1 ORDER BY branch_code LIMIT 5`, [`%${branchKeyword}%`] ); if (!branches.rowCount) { const all = await pool.query(`SELECT branch_code, branch_name FROM branches ORDER BY branch_code`); console.error('未找到分公司,全部:', all.rows); process.exit(1); } const branch = branches.rows[0]; const branchCode = branch.branch_code; console.log('branch', branch); const existing = await pool.query( `SELECT quote_sheet_code, title, version_no, status, approval_status, (SELECT COUNT(*)::int FROM customer_quote_sheet_items i WHERE i.quote_sheet_code = qs.quote_sheet_code) AS items, (SELECT COUNT(*)::int FROM customer_quote_sheet_customers c WHERE c.quote_sheet_code = qs.quote_sheet_code) AS customers FROM customer_quote_sheets qs WHERE branch_code = $1 AND status = 1 AND approval_status = 30 AND (expires_at IS NULL OR expires_at > NOW()) ORDER BY version_no DESC`, [branchCode] ); console.log('active_quote_sheets_before', existing.rows); const extracted = await pool.query(EXTRACT_SQL, [branchCode]); console.log('extracted_price_lines', extracted.rowCount); if (!extracted.rowCount) { console.log('无可迁移的订单价格(需 sku_code 且 price>0)'); process.exit(0); } const byCustomer = new Map(); for (const row of extracted.rows) { const code = row.customer_code; if (!byCustomer.has(code)) byCustomer.set(code, []); byCustomer.get(code).push({ sku_code: row.sku_code, sku_name: row.sku_name, unit: row.unit, price: Number(row.price), }); } const groups = new Map(); for (const [customerCode, items] of byCustomer.entries()) { const fp = priceFingerprint(items); if (!groups.has(fp)) { groups.set(fp, { items, customers: [] }); } groups.get(fp).customers.push(customerCode); } console.log('customers_with_prices', byCustomer.size); console.log('quote_sheet_groups', groups.size); const customerNames = await pool.query( `SELECT customer_code, company_name FROM customers WHERE branch_code = $1`, [branchCode] ); const nameMap = new Map(customerNames.rows.map((r) => [r.customer_code, r.company_name])); for (const [fp, group] of groups.entries()) { const labels = group.customers.map((c) => `${c}(${nameMap.get(c) || '?'})`).join(', '); console.log(`\n[group ${fp}] customers=${group.customers.length} items=${group.items.length}`); console.log(' ', labels.slice(0, 200) + (labels.length > 200 ? '…' : '')); console.log(' sample_items', group.items.slice(0, 5)); } if (dryRun) { console.log('\nDRY-RUN 完成。加 --execute 写入报价单。'); process.exit(0); } const client = await pool.connect(); try { await client.query('BEGIN'); let versionNo = await nextSheetVersionNo(client, branchCode); const created = []; for (const [, group] of groups.entries()) { const result = await createQuoteSheetForGroup( client, branchCode, group.customers, group.items, versionNo ); created.push(result); versionNo += 1; } await client.query('COMMIT'); console.log('\ncreated_sheets', JSON.stringify(created, null, 2)); const after = await pool.query( `SELECT COUNT(*)::int AS active_versions FROM customer_quote_versions WHERE branch_code = $1 AND status = 1 AND source_type = 'order_price_migration'`, [branchCode] ); console.log('materialized_migration_versions', after.rows[0]); } catch (error) { await client.query('ROLLBACK'); throw error; } finally { client.release(); } } finally { await pool.end(); }