/** * 临时脚本:本地以「机器人拦截格式」推送一条站内信,验证规则引擎修复效果(不连生产、不清理数据)。 * * 格式来源(生产 优禾康(天豹)顺丰对接群 实测): * <店铺名>LSFJY<日期><序号>\n物流单号:<运单号> 拦截 * * 走真实入站链路:POST /warehouse?method=inbox.push(interface_type_id=3,MD5 签名) * → receiver.receive 写库 → setImmediate 异步 handleApiMessage → rules 规则引擎 → 回信 * * 用法:node script/tmp-push-inbox-robot-intercept.cjs */ 'use strict'; const path = require('path'); const projectRoot = path.resolve(__dirname, '..'); const mysql = require('mysql2/promise'); const { signRequest } = require('../app/lib/api_sign'); const BASE_URL = process.env.INBOX_BASE_URL || 'http://127.0.0.1:6060'; const APP_KEY = process.env.INBOX_APP_KEY || 'AK2026080103072276d0e140'; // 本地 warehouse 100000 应用 /** 测试群(本地 100000 / 货主 1000000 的售后群) */ const GROUP = { group_id: 'g_after_sales_1785917104039', group_name: '测试售后群_1785917104039', user_id: 'wxid_robot_uat_0001', user_name: '探域售后机器人', }; /** * 用例来源:从本地库自动挑选**真实存在**的顺丰运单(货主 1000000、订单在待处理/波次中、 * 未拦截、无未完结拦截工单),并按运单号形态去重覆盖(纯数字 / SF+数字 / 其他前缀)。 * 正文固定用生产机器人原文格式。 */ const WAREHOUSE_ID = 100000; const STORE_ID = 1000000; const CASE_LIMIT = Number(process.env.INBOX_CASE_LIMIT || 4); /** 生产原文里的店铺单号前缀(仅用于拼出同款正文) */ const SHOP_CODE = '优禾康官方旗舰店LSFJY202609143442'; /** * 运单号形态归类:开头字母前缀;纯数字归 DIGITS * @param {string} code 运单号。 * @return {string} 形态标签。 */ function waybillPattern(code) { const m = String(code).match(/^[A-Za-z]+/); return m ? m[0].toUpperCase() : 'DIGITS'; } /** * 查询可用的顺丰测试运单。 * @param {Object} conn mysql2 连接。 * @param {number} limit 最多取几个(按运单号形态去重后)。 * @return {Promise} 用例列表 [{ tag, desc, waybill, expressId, orderId, content }]。 */ async function findSfCases(conn, limit) { const [ rows ] = await conn.query( 'SELECT e.id AS express_id, e.waybill_code, e.order_id, e.logistics_name, e.logistics_interface_id, ' + 'd.step, d.wave_id, d.intercept_status ' + 'FROM wms_order_express e JOIN wms_order_delivery_100000 d ON d.id = e.order_id ' + 'WHERE e.warehouse_id = ? AND e.store_id = ? AND e.logistics_code = "SF" ' + 'AND d.step IN (1,2,3) AND (d.intercept_status IS NULL OR d.intercept_status = "none") ' + 'AND (e.is_intercept IS NULL OR e.is_intercept <> "Y") ' + 'AND e.id NOT IN (SELECT waybill_id FROM wms_after_sale WHERE waybill_id IS NOT NULL ' + ' AND sub_type = "intercept" AND status NOT IN ("completed","closed","cancelled")) ' + 'ORDER BY e.id DESC', [ WAREHOUSE_ID, STORE_ID ] ); const picked = []; const usedPatterns = new Set(); for (const row of rows) { const pattern = waybillPattern(row.waybill_code); if (usedPatterns.has(pattern)) continue; usedPatterns.add(pattern); picked.push({ tag: String(picked.length + 1), waybill: row.waybill_code, expressId: row.express_id, orderId: row.order_id, desc: `形态=${pattern} 顺丰运单 ${row.waybill_code} (express id=${row.express_id}, order=${row.order_id})`, content: `${SHOP_CODE}\n物流单号:${row.waybill_code} 拦截`, }); if (picked.length >= limit) break; } return picked; } function loadDbConfig() { const factory = require(path.resolve(projectRoot, 'config/config.local.js')); const config = typeof factory === 'function' ? factory({ name: 'wms-inbox-push' }) : factory; const client = config.mysql.clients.wms; return { host: client.host, port: Number(client.port), user: client.user, password: client.password, database: client.database, charset: client.charset || 'utf8mb4', }; } async function getAppSecret(conn, appKey) { const [ rows ] = await conn.query( 'SELECT self_app_key, self_app_secret, warehouse_id FROM wms_api_app WHERE self_app_key = ?', [ appKey ] ); if (rows.length === 0) throw new Error(`本地库未找到 app_key=${appKey} 的应用`); return rows[0]; } async function pushMessage({ appKey, secret, requestId, content }) { const body = { requestId, groupId: GROUP.group_id, groupName: GROUP.group_name, userId: GROUP.user_id, userName: GROUP.user_name, content, extData: { type: 1, source: 'wx' }, flags: {}, }; const query = { method: 'inbox.push', v: '1.0', timestamp: String(Math.floor(Date.now() / 1000)), app_key: appKey, }; const { sign, canonicalQuery } = signRequest({ query, body, selfAppSecret: secret }); const search = new URLSearchParams({ ...query, sign }).toString(); const url = `${BASE_URL}/warehouse?${search}`; const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const text = await res.text(); let json = null; try { json = JSON.parse(text); } catch (e) { /* 保留原始文本 */ } return { status: res.status, json, text, canonicalQuery }; } /** * 轮询等待异步处理完成(ai_thoughts 或回信出现)。 * @param {Object} conn mysql2 连接实例。 * @param {string} extId 入站消息外部唯一键。 * @param {Object} [opts] 轮询配置。 * @param {number} [opts.timeoutMs] 最长等待毫秒数。 * @param {number} [opts.intervalMs] 轮询间隔毫秒数。 * @return {Promise} { inbound, replies, timedOut }。 */ async function waitProcessed(conn, extId, { timeoutMs = 20000, intervalMs = 1000 } = {}) { const deadline = Date.now() + timeoutMs; let inbound = null; while (Date.now() < deadline) { const [ rows ] = await conn.query( 'SELECT id, direction, group_id, group_name, user_id, user_name, content, ai_thoughts, push_status, created_at ' + 'FROM wms_inbox_message WHERE ext_id = ? AND direction = "inbound" ORDER BY id DESC LIMIT 1', [ extId ] ); inbound = rows[0] || null; if (inbound) { const [ replies ] = await conn.query( 'SELECT id, content, push_status, created_at FROM wms_inbox_message WHERE parent_id = ? ORDER BY id', [ inbound.id ] ); if ((inbound.ai_thoughts && String(inbound.ai_thoughts).length > 2) || replies.length > 0) { return { inbound, replies }; } } await new Promise(r => setTimeout(r, intervalMs)); } const [ replies ] = inbound ? await conn.query('SELECT id, content, push_status, created_at FROM wms_inbox_message WHERE parent_id = ? ORDER BY id', [ inbound.id ]) : [[]]; return { inbound, replies, timedOut: true }; } async function collectSideEffects(conn, waybills) { if (waybills.length === 0) return { express: [], afterSales: [], orders: [] }; const [ express ] = await conn.query( 'SELECT id, waybill_code, order_id, store_id, is_intercept FROM wms_order_express WHERE warehouse_id = ? AND waybill_code IN (?)', [ WAREHOUSE_ID, waybills ] ); const expressIds = express.map(r => r.id); const orderIds = express.map(r => r.order_id).filter(Boolean); let afterSales = []; if (expressIds.length > 0) { const [ rows ] = await conn.query( 'SELECT id, after_sale_no, waybill_id, waybill_no, type, sub_type, status, title FROM wms_after_sale WHERE waybill_id IN (?) ORDER BY id DESC', [ expressIds ] ); afterSales = rows; } let orders = []; if (orderIds.length > 0) { const [ rows ] = await conn.query( 'SELECT id, step, wave_id, intercept_status, intercept_time FROM wms_order_delivery_100000 WHERE id IN (?)', [ orderIds ] ); orders = rows; } return { express, afterSales, orders }; } (async () => { const dbConfig = loadDbConfig(); const conn = await mysql.createConnection(dbConfig); const app = await getAppSecret(conn, APP_KEY); console.log(`目标服务: ${BASE_URL} 应用: ${app.self_app_key} (warehouse ${app.warehouse_id})`); console.log(`测试群: ${GROUP.group_name} / ${GROUP.group_id} 发送人: ${GROUP.user_name}\n`); // 支持临时指定正文(INBOX_CONTENT=...),用于其它规则的端到端复现;不指定则自动挑顺丰运单 const adhoc = String(process.env.INBOX_CONTENT || '').trim(); let cases; if (adhoc) { cases = [{ tag: 'X', waybill: '-', desc: '自定义正文(INBOX_CONTENT)', content: adhoc }]; console.log('使用自定义正文(INBOX_CONTENT)'); } else { cases = await findSfCases(conn, CASE_LIMIT); if (cases.length === 0) { console.log('❌ 本地库没有可用的未拦截顺丰运单样本'); await conn.end(); return; } console.log(`自动挑选到 ${cases.length} 个真实顺丰运单样本(按运单号形态去重):`); for (const c of cases) console.log(` - ${c.desc}`); } const waybills = cases.map(c => c.waybill).filter(code => code && code !== '-'); const results = []; for (const item of cases) { const requestId = `UATTEST${item.tag}${Date.now()}`; const extId = `api:${APP_KEY}:${requestId}`; console.log('\n' + '='.repeat(96)); console.log(`【用例 ${item.tag}】${item.desc}`); console.log(`正文: ${JSON.stringify(item.content)}`); console.log(`requestId=${requestId} ext_id=${extId}`); const pushRes = await pushMessage({ appKey: APP_KEY, secret: app.self_app_secret, requestId, content: item.content, }); console.log(`入站响应: HTTP ${pushRes.status} ${pushRes.text}`); const { inbound, replies, timedOut } = await waitProcessed(conn, extId); if (!inbound) { console.log('❌ 未查到入站消息记录,请检查 dev 服务日志'); results.push({ ...item, ok: false, note: '未查到入站记录' }); continue; } const thoughts = Array.isArray(inbound.ai_thoughts) ? inbound.ai_thoughts : (inbound.ai_thoughts ? [ inbound.ai_thoughts ] : []); const fnName = thoughts[0] ? thoughts[0].function || '-' : '-'; console.log(`\n入站记录: id=${inbound.id} group=${inbound.group_name} 用户=${inbound.user_name}`); console.log(` ai_thoughts = ${inbound.ai_thoughts ? JSON.stringify(inbound.ai_thoughts) : 'null'}`); console.log(` push_status = ${inbound.push_status}`); if (replies.length === 0) { console.log(` ⚠ 无回信记录${timedOut ? '(等待超时)' : ''}`); } else { for (const r of replies) { console.log(` 回信 id=${r.id} push_status=${r.push_status}: ${JSON.stringify(r.content)}`); } } if (timedOut) console.log(' (等待处理超时,可能仍在异步处理中)'); results.push({ ...item, inboundId: inbound.id, fn: fnName, reply: replies.map(r => r.content).join(' | ') || '(无回信)', ok: replies.length > 0, }); } const { express, afterSales, orders } = await collectSideEffects(conn, waybills); console.log('\n' + '='.repeat(96)); console.log('副作用核对(本地库,保留不清理)'); console.log('运单:'); for (const e of express) { console.log(` express id=${e.id} ${e.waybill_code} order_id=${e.order_id} store_id=${e.store_id} is_intercept=${e.is_intercept}`); } console.log('售后工单:'); for (const a of afterSales) { console.log(` ${a.after_sale_no} waybill=${a.waybill_no} ${a.type}/${a.sub_type} status=${a.status}\n title=${a.title}`); } if (afterSales.length === 0) console.log(' (无)'); console.log('订单拦截状态:'); for (const o of orders) { console.log(` order id=${o.id} step=${o.step} wave_id=${o.wave_id} intercept_status=${o.intercept_status} intercept_time=${o.intercept_time ? o.intercept_time.toISOString() : null}`); } if (orders.length === 0) console.log(' (无)'); console.log('\n' + '='.repeat(96)); console.log('汇总'); let pass = 0; for (const r of results) { if (r.ok) pass++; console.log( `${r.ok ? '✅' : '❌'} 用例${r.tag} ${r.waybill} | fn=${r.fn || '-'} | 入站id=${r.inboundId || '-'} | ${r.reply}` ); } console.log(`\n有回信用例:${pass}/${results.length}`); await conn.end(); })().catch(err => { console.error('脚本执行失败:', err); process.exitCode = 1; });