#!/usr/bin/env node /** * 修复:自采已入库但供应商备货状态未同步,导致订单卡在 30、无配送单。 * Usage: node scripts/prod-repair-stuck-orders.mjs [branch_code] */ import pg from 'pg'; import { readFileSync } from 'fs'; const branch = process.argv[2] || 'BR002'; const env = readFileSync('/opt/ai-fresh-delivery/server/.env', 'utf8'); const url = env.match(/^DATABASE_URL=(.+)$/m)[1].trim().replace(/^["']|["']$/g, ''); const pool = new pg.Pool({ connectionString: url }); function newBatchNo() { return `IN${Date.now().toString().slice(-9)}${Math.random().toString(36).slice(2, 6).toUpperCase()}`; } async function autoReadySupplierPreps(client, orderCode) { const r = await client.query( `UPDATE supplier_preparations sp SET prepare_status = 30, prepare_time = COALESCE(sp.prepare_time, NOW()) WHERE sp.order_code = $1 AND COALESCE(sp.prepare_status, 10) < 30 AND COALESCE(sp.is_stockout, false) = false AND COALESCE(sp.transferred_to_purchase, false) = false AND NOT EXISTS ( SELECT 1 FROM purchase_orders po WHERE po.order_code = sp.order_code AND COALESCE(po.purchase_status, 10) IN (10, 32) ) AND EXISTS ( SELECT 1 FROM inspections i WHERE i.order_code = sp.order_code AND COALESCE(i.source_type, 'supplier') = 'purchase' AND i.compliance_status >= 40 AND i.inbound_batch_no IS NOT NULL ) AND NOT EXISTS ( SELECT 1 FROM inspections i WHERE i.order_code = sp.order_code AND i.sku_code IS NOT DISTINCT FROM sp.sku_code AND COALESCE(i.supplier_code, '') = COALESCE(sp.supplier_code, '') AND i.compliance_status >= 40 AND i.inbound_batch_no IS NOT NULL ) RETURNING sp.id`, [orderCode] ); return r.rowCount || 0; } async function ensureSupplierInspections(client, orderCode, branchCode) { const preps = await client.query( `SELECT sp.* FROM supplier_preparations sp WHERE sp.order_code = $1 AND COALESCE(sp.prepare_status, 10) >= 30 AND COALESCE(sp.is_stockout, false) = false AND NOT EXISTS ( SELECT 1 FROM inspections i WHERE i.order_code = sp.order_code AND i.sku_code IS NOT DISTINCT FROM sp.sku_code AND COALESCE(i.supplier_code, '') = COALESCE(sp.supplier_code, '') )`, [orderCode] ); let created = 0; for (const prep of preps.rows) { const itemName = prep.item_name || prep.sku_code || '未知商品'; await client.query( `INSERT INTO inspections ( order_code, sku_code, supplier_code, prepare_qty, purchase_price, batch_no, branch_code, source_type, item_name ) VALUES ($1, $2, $3, $4, $5, $6, $7, 'supplier', $8)`, [ orderCode, prep.sku_code, prep.supplier_code, prep.prepare_qty, prep.purchase_price, `BT${Date.now()}${Math.random().toString(36).slice(2, 6)}`, branchCode, itemName, ] ); created += 1; } return created; } async function passPendingInspections(client, orderCode) { const pending = await client.query( `SELECT id, prepare_qty, item_name FROM inspections WHERE order_code = $1 AND inspection_time IS NULL AND inbound_batch_no IS NULL`, [orderCode] ); let passed = 0; for (const row of pending.rows) { const qty = Number(row.prepare_qty) || 0; if (qty <= 0) continue; const batchNo = newBatchNo(); await client.query( `UPDATE inspections SET actual_qty = $2, quality_rating = '合格', loss_qty = 0, compliance_status = 40, inspection_time = NOW(), inbound_batch_no = $3 WHERE id = $1`, [row.id, qty, batchNo] ); passed += 1; } return passed; } async function ensureDeliveryTask(client, orderCode, branchCode) { const existing = await client.query( `SELECT task_code FROM delivery_tasks WHERE order_code = $1 LIMIT 1`, [orderCode] ); if (existing.rowCount) return existing.rows[0].task_code; const order = await client.query( `SELECT customer_code FROM orders WHERE order_code = $1`, [orderCode] ); const customerCode = order.rows[0]?.customer_code; let personCode = null; if (customerCode) { const bind = await client.query( `SELECT person_code FROM customer_delivery_assignments WHERE customer_code = $1 ORDER BY is_primary DESC NULLS LAST, updated_at DESC LIMIT 1`, [customerCode] ); personCode = bind.rows[0]?.person_code || null; } const taskCode = `DT${Date.now()}_${Math.random().toString(36).slice(2, 7)}`; await client.query( `INSERT INTO delivery_tasks (task_code, order_code, person_code, task_status, branch_code) VALUES ($1, $2, $3, 10, $4)`, [taskCode, orderCode, personCode, branchCode] ); return taskCode; } try { const stuck = await pool.query( `SELECT order_code, order_status, branch_code FROM orders WHERE branch_code = $1 AND order_status IN (30, 40, 45) AND delivery_date::date >= CURRENT_DATE - 2 ORDER BY updated_at DESC`, [branch] ); console.log(`Repairing ${stuck.rowCount} orders in ${branch}...`); for (const order of stuck.rows) { const code = order.order_code; const client = await pool.connect(); try { await client.query('BEGIN'); const ready = await autoReadySupplierPreps(client, code); const branchCode = order.branch_code; const created = await ensureSupplierInspections(client, code, branchCode); const passed = await passPendingInspections(client, code); await client.query( `UPDATE orders SET order_status = 40 WHERE order_code = $1 AND order_status = 30`, [code] ); await client.query( `UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status < 50`, [code] ); const taskCode = await ensureDeliveryTask(client, code, branchCode); await client.query('COMMIT'); const after = await pool.query(`SELECT order_status FROM orders WHERE order_code = $1`, [code]); console.log( JSON.stringify({ order_code: code, ready_preps: ready, inspections_created: created, inspections_passed: passed, task_code: taskCode, new_status: after.rows[0]?.order_status, }) ); } catch (error) { await client.query('ROLLBACK').catch(() => undefined); console.error('FAILED', code, error.message); } finally { client.release(); } } } finally { await pool.end(); }