#!/usr/bin/env node /** * 扫清今日配送日历史合单从单:缺本单入库则补入库并改挂本单采购。 * 设计:docs/design/20260731-depart-respect-reservations.md * * node scripts/prod-clear-merge-guests-today.mjs # dry-run * node scripts/prod-clear-merge-guests-today.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 SCHEMAS = ['tenant_br002', 'tenant_br001', 'tenant_br003']; 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 newPurchaseCode() { return `PUR${Date.now()}CLR${Math.floor(Math.random() * 10000)}`; } async function clearSchema(client, schema) { await client.query(`SET search_path TO ${schema}, public`); console.log(`\n======== ${schema} ========`); const guests = await client.query(` SELECT oi.id AS order_item_id, oi.order_code, oi.sku_code, oi.item_name, oi.unit, oi.quantity::float AS qty, oi.branch_code, o.order_status, o.delivery_date::text, po.purchase_code AS old_po, po.order_code AS host_order, po.actual_price, po.purchase_price, EXISTS ( SELECT 1 FROM inspections i WHERE i.order_code = oi.order_code AND i.sku_code IS NOT DISTINCT FROM oi.sku_code AND i.compliance_status >= 40 AND i.inbound_batch_no IS NOT NULL ) AS self_inbound FROM order_items oi JOIN orders o ON o.order_code = oi.order_code JOIN order_item_fulfillments f ON f.order_item_id = oi.id AND f.purchase_code IS NOT NULL JOIN purchase_orders po ON po.purchase_code = f.purchase_code WHERE o.order_status BETWEEN 40 AND 50 AND COALESCE(oi.quantity, 0) > 0 AND po.order_code IS DISTINCT FROM oi.order_code AND po.purchase_status < 80 AND po.purchase_status <> 40 AND COALESCE(o.delivery_date, CURRENT_DATE) = (NOW() AT TIME ZONE 'Asia/Shanghai')::date ORDER BY oi.order_code, oi.item_name `); console.log('GUEST_LINES', guests.rows.length); if (!guests.rows.length) return { fixed: 0, skipped: 0 }; let fixed = 0; let skipped = 0; for (const g of guests.rows) { const branch = g.branch_code || 'BR002'; const qty = Number(g.qty) || 0; const sku = String(g.sku_code || '').trim(); if (!sku || qty <= 0) { skipped += 1; continue; } const availR = await client.query( `SELECT COALESCE(SUM(available_qty),0)::float AS a FROM inventory WHERE sku_code=$1 AND available_qty>0 AND branch_code=$2`, [sku, branch] ); const otherRes = await client.query( `SELECT COALESCE(SUM(qty),0)::float AS r FROM inventory_reservations WHERE sku_code=$1 AND status=10 AND branch_code=$2 AND order_code IS DISTINCT FROM $3`, [sku, branch, g.order_code] ); const avail = Number(availR.rows[0].a) || 0; const other = Number(otherRes.rows[0].r) || 0; const claimable = Math.max(0, avail - other); console.log( 'LINE', JSON.stringify({ order: g.order_code, item: g.item_name, sku, qty, self_inbound: g.self_inbound, avail, other_reserved: other, claimable, host: g.host_order, old_po: g.old_po, }) ); // 可扣量已够:只需解绑履约到本单采购(不再加库存,防虚库存) const gap = Math.round(Math.max(0, qty - claimable) * 100) / 100; const onlyRebind = gap <= 1e-9; if (!EXECUTE) { console.log( ' DRY would', onlyRebind ? 'rebind-only' : 'rebind+inbound', g.order_code, g.item_name, 'gap', gap ); fixed += 1; continue; } await client.query('BEGIN'); try { const cost = Number(g.actual_price) || Number(g.purchase_price) || 0; const purchaseCode = newPurchaseCode(); const batchNo = newBatchNo(); const inboundQty = gap; await client.query( `INSERT INTO purchase_orders ( purchase_code, order_code, sku_code, supplier_code, purchaser_code, purchaser_name, purchase_qty, purchase_price, actual_qty, actual_price, total_amount, purchase_status, is_temporary_supplier, source_type, source_id, remark, branch_code ) VALUES ( $1, $2, $3, NULL, 'PUR001', '运维', $4, $5, $4, $5, $6, 30, false, 'order_no_supplier', $7, $8, $9 )`, [ purchaseCode, g.order_code, sku, qty, cost, Math.round(qty * cost * 100) / 100, g.order_item_id, `运维扫清历史合单从单:原挂 ${g.old_po}(主单 ${g.host_order})`, branch, ] ); await client.query( `UPDATE order_item_fulfillments SET purchase_code = $2, inventory_cover_qty = 0, updated_at = NOW() WHERE order_item_id = $1::uuid`, [g.order_item_id, purchaseCode] ); // 验收覆盖:有缺口则新建批次入库;够用则复用现有批次写本单验收(不增 available) let useBatch = batchNo; let createdInv = false; if (inboundQty > 1e-9) { createdInv = true; 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, sku, inboundQty, cost, branch] ); 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, sku, inboundQty, g.order_code, `运维扫清合单从单补缺口入库`] ); } else if (!g.self_inbound) { const hostBatch = await client.query( `SELECT inbound_batch_no FROM inspections WHERE order_code = $1 AND sku_code IS NOT DISTINCT FROM $2 AND compliance_status >= 40 AND inbound_batch_no IS NOT NULL ORDER BY created_at DESC LIMIT 1`, [g.host_order, sku] ); if (hostBatch.rows[0]?.inbound_batch_no) { useBatch = String(hostBatch.rows[0].inbound_batch_no); } else { const anyBatch = await client.query( `SELECT batch_no FROM inventory WHERE sku_code = $1 AND available_qty > 0 AND branch_code = $2 ORDER BY created_at DESC LIMIT 1`, [sku, branch] ); if (!anyBatch.rows[0]) { throw new Error(`无可用批次可复用:${g.item_name}`); } useBatch = String(anyBatch.rows[0].batch_no); } } if (!g.self_inbound || inboundQty > 1e-9) { 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, sku, qty, cost, `BT${Date.now().toString(36).toUpperCase()}`, branch, g.item_name || sku, g.unit || '斤', useBatch, JSON.stringify({ purchase_code: purchaseCode, repair: 'clear_merge_guest_20260731', old_po: g.old_po, reuse_batch: !createdInv, inbound_gap: inboundQty, }), ] ); console.log(' INSP', insp.rows[0].id, 'batch', useBatch, 'newInv', createdInv, 'gap', inboundQty); } await client.query( `INSERT INTO inventory_reservations ( order_item_id, order_code, sku_code, branch_code, qty, status ) SELECT $1::uuid, $2, $3, $4, $5, 10 WHERE NOT EXISTS ( SELECT 1 FROM inventory_reservations WHERE order_item_id = $1::uuid AND status = 10 )`, [g.order_item_id, g.order_code, sku, branch, qty] ); await client.query('COMMIT'); console.log(' FIXED', g.order_code, g.item_name, { purchaseCode, inboundQty, batchNo: inboundQty > 0 ? batchNo : null, }); fixed += 1; } catch (e) { await client.query('ROLLBACK').catch(() => undefined); console.error(' FAIL', g.order_code, g.item_name, e.message); throw e; } } // remaining guests today const left = await client.query(` SELECT COUNT(*)::int AS n FROM order_items oi JOIN orders o ON o.order_code = oi.order_code JOIN order_item_fulfillments f ON f.order_item_id = oi.id AND f.purchase_code IS NOT NULL JOIN purchase_orders po ON po.purchase_code = f.purchase_code WHERE o.order_status BETWEEN 40 AND 50 AND COALESCE(oi.quantity, 0) > 0 AND po.order_code IS DISTINCT FROM oi.order_code AND po.purchase_status < 80 AND po.purchase_status <> 40 AND COALESCE(o.delivery_date, CURRENT_DATE) = (NOW() AT TIME ZONE 'Asia/Shanghai')::date `); console.log('REMAINING_GUESTS', left.rows[0].n, 'fixed', fixed, 'skipped', skipped); return { fixed, skipped }; } async function main() { const pool = new pg.Pool({ connectionString: loadDatabaseUrl() }); const client = await pool.connect(); try { console.log(EXECUTE ? 'EXECUTE' : 'DRY-RUN'); for (const schema of SCHEMAS) { await clearSchema(client, schema); } } finally { client.release(); await pool.end(); } } main().catch((e) => { console.error(e); process.exit(1); });