#!/usr/bin/env node /** * 待配送订单:按分公司可用库存差额补录入库 * 设计:docs/design/20260803-prod-delivery-gap-backfill.md * * node scripts/prod-backfill-delivery-stock-gaps.mjs # dry-run * node scripts/prod-backfill-delivery-stock-gaps.mjs --execute */ import pg from 'pg'; import { readFileSync, existsSync } from 'fs'; import { resolve, dirname } from 'path'; import { fileURLToPath } from 'url'; const __dirname = dirname(fileURLToPath(import.meta.url)); const EXECUTE = process.argv.includes('--execute'); const SCHEMA = 'tenant_br002'; const REMARK = '补录'; function loadDatabaseUrl() { for (const p of [resolve(__dirname, '../.env'), '/opt/ai-fresh-delivery/server/.env']) { if (!existsSync(p)) continue; const m = readFileSync(p, 'utf8').match(/^DATABASE_URL=(.+)$/m); if (m) return m[1].trim().replace(/^["']|["']$/g, ''); } throw new Error('DATABASE_URL not found'); } function newBatchNo() { const d = new Date(); const ymd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`; return `IN${ymd}${Math.random().toString(36).slice(2, 8).toUpperCase()}`; } function round3(n) { return Math.round(Number(n) * 1000) / 1000; } async function resolveCost(client, { orderCode, skuCode, branchCode }) { const po = await client.query( `SELECT COALESCE(actual_price, purchase_price, 0)::float AS p FROM purchase_orders WHERE order_code = $1 AND sku_code = $2 ORDER BY created_at DESC LIMIT 1`, [orderCode, skuCode] ); if (Number(po.rows[0]?.p) > 0) return Number(po.rows[0].p); const insp = await client.query( `SELECT COALESCE(purchase_price, 0)::float AS p FROM inspections WHERE order_code = $1 AND sku_code = $2 AND COALESCE(purchase_price,0) > 0 ORDER BY created_at DESC LIMIT 1`, [orderCode, skuCode] ); if (Number(insp.rows[0]?.p) > 0) return Number(insp.rows[0].p); const inv = await client.query( `SELECT cost_price::float AS p FROM inventory WHERE sku_code = $1 AND branch_code IS NOT DISTINCT FROM $2 AND cost_price IS NOT NULL ORDER BY created_at DESC LIMIT 1`, [skuCode, branchCode] ); return Number(inv.rows[0]?.p) || 0; } async function main() { const pool = new pg.Pool({ connectionString: loadDatabaseUrl() }); const client = await pool.connect(); try { await client.query(`SET search_path TO ${SCHEMA}, public`); // 发车口径:claimable = avail − 他单预留;gap = need − claimable const gaps = await client.query(` WITH need AS ( SELECT o.order_code, o.branch_code, oi.sku_code, MAX(COALESCE(NULLIF(TRIM(oi.item_name),''), oi.sku_code)) AS item_name, MAX(COALESCE(NULLIF(TRIM(oi.unit),''), '斤')) AS unit, SUM(GREATEST(0, COALESCE(oi.quantity,0)))::float AS need_qty FROM orders o JOIN order_items oi ON oi.order_code = o.order_code WHERE o.deleted_at IS NULL AND o.order_status = 50 AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> '' GROUP BY o.order_code, o.branch_code, oi.sku_code ), avail AS ( SELECT sku_code, branch_code, COALESCE(SUM(available_qty),0)::float AS avail FROM inventory WHERE available_qty > 0 GROUP BY sku_code, branch_code ), already_out AS ( SELECT DISTINCT related_order_code AS order_code FROM inventory_logs WHERE operation_type IN ('picking_out','delivery_loading_out') ), scored AS ( SELECT n.order_code, n.branch_code, n.sku_code, n.item_name, n.unit, n.need_qty, COALESCE(a.avail,0)::float AS avail, COALESCE(( SELECT SUM(ir.qty)::float FROM inventory_reservations ir WHERE ir.sku_code = n.sku_code AND ir.status = 10 AND ir.branch_code IS NOT DISTINCT FROM n.branch_code AND ir.order_code IS DISTINCT FROM n.order_code ), 0)::float AS other_resv FROM need n LEFT JOIN avail a ON a.sku_code = n.sku_code AND a.branch_code IS NOT DISTINCT FROM n.branch_code LEFT JOIN already_out ao ON ao.order_code = n.order_code WHERE ao.order_code IS NULL ) SELECT order_code, branch_code, sku_code, item_name, unit, need_qty, avail, other_resv, GREATEST(0, avail - other_resv)::float AS claimable, ROUND((need_qty - GREATEST(0, avail - other_resv))::numeric, 3)::float AS gap FROM scored WHERE need_qty > GREATEST(0, avail - other_resv) + 1e-6 ORDER BY order_code, gap DESC`); console.log(`schema=${SCHEMA} gaps=${gaps.rowCount} execute=${EXECUTE}`); for (const g of gaps.rows) console.log(JSON.stringify(g)); if (!EXECUTE) { console.log('(dry-run) 加 --execute 才写入;备注=', REMARK); return; } let filled = 0; for (const g of gaps.rows) { const gap = round3(g.gap); if (!(gap > 0)) continue; const cost = await resolveCost(client, { orderCode: g.order_code, skuCode: g.sku_code, branchCode: g.branch_code, }); const batchNo = newBatchNo(); const bt = `BT${Date.now().toString(36).toUpperCase()}${Math.floor(Math.random() * 1000)}`; await client.query('BEGIN'); try { // 事务内再锁读可用 + 他单预留,避免并发双补 const live = await client.query( `SELECT id, available_qty::float AS available_qty FROM inventory WHERE sku_code = $1 AND available_qty > 0 AND branch_code IS NOT DISTINCT FROM $2 FOR UPDATE`, [g.sku_code, g.branch_code] ); await client.query( `SELECT id FROM inventory_reservations WHERE sku_code = $1 AND status = 10 AND branch_code IS NOT DISTINCT FROM $2 FOR UPDATE`, [g.sku_code, g.branch_code] ); const liveAvail = live.rows.reduce((s, r) => s + (Number(r.available_qty) || 0), 0); const otherResv = await client.query( `SELECT COALESCE(SUM(qty),0)::float AS r FROM inventory_reservations WHERE sku_code = $1 AND status = 10 AND branch_code IS NOT DISTINCT FROM $2 AND order_code IS DISTINCT FROM $3`, [g.sku_code, g.branch_code, g.order_code] ); const liveClaimable = Math.max(0, liveAvail - (Number(otherResv.rows[0]?.r) || 0)); const liveGap = round3(Number(g.need_qty) - liveClaimable); if (!(liveGap > 1e-6)) { await client.query('ROLLBACK'); console.log('SKIP_ALREADY_ENOUGH', g.order_code, g.sku_code); continue; } const insp = await client.query( `INSERT INTO inspections ( order_code, sku_code, supplier_code, prepare_qty, actual_qty, purchase_price, batch_no, branch_code, source_type, item_name, unit, quality_rating, loss_qty, compliance_status, inspection_time, inbound_batch_no, processing_details ) VALUES ( $1, $2, NULL, $3, $3, $4, $5, $6, 'purchase', $7, $8, 'A', 0, 40, NOW(), $9, $10::jsonb ) RETURNING id`, [ g.order_code, g.sku_code, liveGap, cost, bt, g.branch_code, g.item_name, g.unit || '斤', batchNo, JSON.stringify({ repair: 'delivery_gap_backfill_20260807', remark: REMARK, gap: liveGap, need: Number(g.need_qty), avail_before: liveAvail, claimable_before: liveClaimable, }), ] ); await client.query( `INSERT INTO inventory ( batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status, branch_code, production_date ) VALUES ($1,$2,$3,$3,NULL,$4,10,$5,(NOW() AT TIME ZONE 'Asia/Shanghai')::date)`, [batchNo, g.sku_code, liveGap, cost, g.branch_code] ); await client.query( `INSERT INTO inventory_logs ( batch_no, sku_code, operation_type, quantity, before_qty, after_qty, related_order_code, remark ) VALUES ($1,$2,'inspection_in',$3,0,$3,$4,$5)`, [batchNo, g.sku_code, liveGap, g.order_code, REMARK] ); await client.query('COMMIT'); filled += 1; console.log('FILLED', { order: g.order_code, sku: g.sku_code, item: g.item_name, gap: liveGap, cost, batchNo, insp: insp.rows[0].id, }); } catch (err) { await client.query('ROLLBACK').catch(() => undefined); console.error('FAIL', g.order_code, g.sku_code, err?.message || err); } } console.log(`DONE filled=${filled}`); } finally { client.release(); await pool.end(); } } main().catch((err) => { console.error(err); process.exit(1); });