/** * 回填历史零价订单明细(销售价): * - 数量/单位:按供应商/验收修改后的(inspections.actual_qty + inspections.unit 优先,其次备货,最后录单); * - 价格:按客户报价单销售价(customer_quote_versions,status=1,取最新生效); * - 报价单没有的:标记 needs_customer_price 并打印提示,不回填; * - 重算 amount = actual_qty × 报价销售价,并更新 quantity/unit 为验收口径; * - 重算订单总额,重建受影响客户结算单(pending)。 * * 用法: npx tsx backfill-zero-prices.ts BR002 [--apply] */ import { pool } from './src/db'; import { runWithTenantDataAccess } from './src/services/tenantSchemaService'; import { upsertCustomerStatementForDay } from './src/services/financeReconciliationService'; async function main() { const branch = process.argv[2] || 'BR002'; const apply = process.argv.includes('--apply'); console.log(`=== 回填零价明细销售价 (${branch}) ${apply ? '【写库】' : '【dry-run】'} ===\n`); await runWithTenantDataAccess(branch, async () => { const rows = await pool.query( `SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.quantity AS item_qty, oi.unit AS item_unit, o.customer_code, o.created_at AS order_created, -- 验收修改后的数量/单位(优先) i.actual_qty AS insp_qty, i.unit AS insp_unit, -- 其次备货 sp.prepare_qty AS prep_qty, sp.unit AS prep_unit, -- 客户报价单销售价(最新生效,不按单位过滤) ( SELECT q.price FROM customer_quote_versions q WHERE q.customer_code = o.customer_code AND q.sku_code = oi.sku_code AND q.status = 1 ORDER BY q.effective_at DESC NULLS LAST LIMIT 1 ) AS quote_sale_price, ( SELECT q.unit FROM customer_quote_versions q WHERE q.customer_code = o.customer_code AND q.sku_code = oi.sku_code AND q.status = 1 ORDER BY q.effective_at DESC NULLS LAST LIMIT 1 ) AS quote_unit FROM order_items oi JOIN orders o ON o.order_code = oi.order_code AND o.deleted_at IS NULL LEFT JOIN LATERAL ( SELECT actual_qty, unit FROM inspections i WHERE i.order_code = oi.order_code AND i.sku_code = oi.sku_code AND i.actual_qty IS NOT NULL ORDER BY i.inspection_time DESC NULLS LAST, i.created_at DESC NULLS LAST LIMIT 1 ) i ON TRUE LEFT JOIN LATERAL ( SELECT prepare_qty, unit FROM supplier_preparations sp WHERE sp.order_code = oi.order_code AND sp.sku_code = oi.sku_code AND sp.prepare_qty IS NOT NULL ORDER BY sp.prepare_time DESC NULLS LAST, sp.created_at DESC NULLS LAST LIMIT 1 ) sp ON TRUE WHERE o.order_status >= 90 AND COALESCE(NULLIF(oi.locked_price,0), NULLIF(oi.price,0), CASE WHEN COALESCE(oi.quantity,0)>0 THEN COALESCE(oi.amount,0)/oi.quantity ELSE 0 END, 0) = 0 ORDER BY o.created_at, oi.order_code, oi.sku_code` ); const toFill: Array = []; const noQuote: Array = []; for (const r of rows.rows) { // 数量/单位:验收 > 备货 > 录单 const qty = Number(r.insp_qty) > 0 ? Number(r.insp_qty) : Number(r.prep_qty) > 0 ? Number(r.prep_qty) : Number(r.item_qty) > 0 ? Number(r.item_qty) : 0; const unit = (r.insp_unit && String(r.insp_unit).trim()) || (r.prep_unit && String(r.prep_unit).trim()) || r.item_unit; const salePrice = Number(r.quote_sale_price) > 0 ? Number(r.quote_sale_price) : 0; if (salePrice > 0 && qty > 0) { toFill.push({ ...r, fill_qty: qty, fill_unit: unit, fill_price: salePrice }); } else { noQuote.push({ ...r, fill_qty: qty, fill_unit: unit }); } } console.log(`可按报价回填: ${toFill.length} 条`); console.log(`报价单没有(需提示): ${noQuote.length} 条\n`); if (noQuote.length) { console.log('--- 报价单没有销售价(需业务补报价)---'); for (const r of noQuote) { console.log(` ${r.order_code} | ${r.item_name} (${r.sku_code}) | ${r.customer_code} | 数量${r.fill_qty}${r.fill_unit}`); } console.log(''); } console.log('--- 回填预览(数量/单位按验收,价格按报价单)---'); let totalAmt = 0; for (const r of toFill) { const amt = Math.round(r.fill_qty * r.fill_price * 100) / 100; totalAmt += amt; const unitNote = r.quote_unit && r.quote_unit !== r.fill_unit ? ` (报价单位:${r.quote_unit})` : ''; console.log(` ${r.order_code} | ${r.item_name} | ${r.fill_qty}${r.fill_unit} × ¥${r.fill_price} = ¥${amt}${unitNote}`); } console.log(`\n合计回填销售额: ¥${totalAmt.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`); if (!apply) { console.log('\n加 --apply 才真正写库。'); return; } // 备份原始值到 JSON 日志文件(不建表,避免 schema 权限问题) const fs = await import('fs'); const backupRows = await pool.query( `SELECT id, order_code, sku_code, item_name, quantity, unit, price, locked_price, amount FROM order_items WHERE id = ANY($1)`, [toFill.map((r) => r.id)] ); const backupFile = `order_items_backup_20260725_${Date.now()}.json`; fs.writeFileSync(backupFile, JSON.stringify(backupRows.rows, null, 2)); console.log(`\n已备份 ${backupRows.rows.length} 条原始值到 ${backupFile}`); // 回填:更新 quantity/unit 为验收口径 + 销售价 let filled = 0; const affectedOrders = new Set(); for (const r of toFill) { const amt = Math.round(r.fill_qty * r.fill_price * 100) / 100; await pool.query( `UPDATE order_items SET quantity = $1, unit = $2, price = $3, locked_price = $3, amount = $4, price_source = 'backfill_quote', price_locked_at = NOW(), needs_customer_price = false WHERE id = $5`, [r.fill_qty, r.fill_unit, r.fill_price, amt, r.id] ); affectedOrders.add(r.order_code); filled += 1; } console.log(`已回填 ${filled} 条,涉及订单 ${affectedOrders.size} 单`); // 无报价的标记提示(不动数量价格) for (const r of noQuote) { await pool.query( `UPDATE order_items SET needs_customer_price = true, price_source = 'missing' WHERE id = $1`, [r.id] ); } console.log(`已标记 ${noQuote.length} 条无报价明细为 needs_customer_price`); // 重算订单总额 for (const code of affectedOrders) { await pool.query( `UPDATE orders o SET total_amount = COALESCE(( SELECT SUM(COALESCE(amount, quantity*price, 0)) FROM order_items WHERE order_code = o.order_code ), 0), updated_at = NOW() WHERE o.order_code = $1`, [code] ); } console.log(`已重算 ${affectedOrders.size} 个订单总额`); // 重建受影响客户结算单(pending) const stmtDays = await pool.query( `SELECT DISTINCT o.customer_code, to_char(COALESCE(sr.delivery_sign_time, dt.end_time, o.updated_at) AT TIME ZONE 'Asia/Shanghai'::text, 'YYYY-MM-DD') AS day FROM orders o LEFT JOIN LATERAL (SELECT delivery_sign_time FROM sign_records WHERE order_code=o.order_code ORDER BY delivery_sign_time DESC NULLS LAST LIMIT 1) sr ON TRUE LEFT JOIN LATERAL (SELECT end_time FROM delivery_tasks WHERE order_code=o.order_code ORDER BY end_time DESC NULLS LAST LIMIT 1) dt ON TRUE WHERE o.order_code = ANY($1)`, [[...affectedOrders]] ); let stmtOk = 0; for (const r of stmtDays.rows) { try { const res = await upsertCustomerStatementForDay(String(r.customer_code), String(r.day)); if (res === 'created' || res === 'updated') stmtOk += 1; } catch (e: any) { console.error(` 重建结算单失败 ${r.customer_code}/${r.day}:`, e?.message); } } console.log(`已重建客户结算单 ${stmtOk}/${stmtDays.rows.length} 张`); // 验证 const after = await pool.query( `SELECT COUNT(*)::int AS cnt FROM order_items oi JOIN orders o ON o.order_code=oi.order_code AND o.deleted_at IS NULL WHERE o.order_status >= 90 AND COALESCE(NULLIF(oi.locked_price,0), NULLIF(oi.price,0), CASE WHEN COALESCE(oi.quantity,0)>0 THEN COALESCE(oi.amount,0)/oi.quantity ELSE 0 END, 0) = 0` ); console.log(`\n回填后仍为 0 价的明细: ${after.rows[0].cnt} 条(应为无报价的 ${noQuote.length} 条)`); }); await pool.end(); console.log('\n完成。'); } main().catch((e) => { console.error(e); process.exit(1); });