diff --git a/app/service/inbox/rules.js b/app/service/inbox/rules.js index e812236..033e529 100644 --- a/app/service/inbox/rules.js +++ b/app/service/inbox/rules.js @@ -336,13 +336,25 @@ const SILENT_RE = /^(好|好的|好的呢|好嘞|嗯|嗯嗯|哦|哦哦|ok|okay| // ============================ 规则表(顺序即优先级) ============================ +/** + * 运单号标签:"物流单号 / 物流单 号 / 物 流单号 / 快递单号 / 运单号" 等 + * 只是单号前缀说明,不代表"要查物流"。判定查询意图前先剔除标签词, + * 避免机器人格式"物流单号:SF123 拦截"因含"物流"被误判为物流查询而整条静默(不回信)。 + * 兼容 IM 转写时在标签字符间断插空格的情况(实测生产存在"物 流单号")。 + * 仅剔除标签本身,聊天正文里的"物流显示签收"等仍保留,查询类消息继续被守卫拦住。 + */ +const WAYBILL_LABEL_RE = /(物\s*流|快\s*递|运\s*单|包\s*裹|邮\s*件)\s*单\s*号?/g; + +/** 物流查询意图关键词:命中即认为不是拦截请求 */ +const TRACKING_QUERY_RE = /(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/; + /** * 拦截类规则的防误判守卫:询问物流进度/查快递等不是拦截请求, * 取消/撤销类语义属于 cancelIntercept(双保险,长词优先已能保证) * @param {string} t 消息正文 * @return {boolean} 是否允许命中拦截规则 */ -const INTERCEPT_GUARD = t => !/(到哪|在哪|哪里|快递到|物流|轨迹|查单|查快递|查物流|到哪里|取消拦截|撤销拦截|解除拦截|不拦截|不用拦截)/.test(t); +const INTERCEPT_GUARD = t => !TRACKING_QUERY_RE.test(String(t || '').replace(WAYBILL_LABEL_RE, ' ')); /** 货主群(store) */ const STORE_RULES = [ diff --git a/script/tmp-check-inbox-intercept-guard.cjs b/script/tmp-check-inbox-intercept-guard.cjs new file mode 100644 index 0000000..4975cd7 --- /dev/null +++ b/script/tmp-check-inbox-intercept-guard.cjs @@ -0,0 +1,104 @@ +/** + * 临时校验:拦截规则防误判守卫(INTERCEPT_GUARD)修复效果。 + * 背景:机器人格式 "物流单号:SF123 拦截" 因含"物流"被守卫拦掉 → 规则未命中 → 静默不回信。 + * 用 fake ctx 直接实例化 inbox.rules Service,不连库、不写库。 + * 运行:node script/tmp-check-inbox-intercept-guard.cjs + */ +'use strict'; + +const RulesService = require('../app/service/inbox/rules'); + +function buildService(groupType, calls) { + const svc = Object.create(RulesService.prototype); + const registry = new Map([ + [ 'interceptWaybill', { groups: [ 'bound:store:after_sales' ] }], + [ 'cancelIntercept', { groups: [ 'bound:store:after_sales' ] }], + [ 'queryWeight', { groups: [ 'bound:store:after_sales' ] }], + ]); + svc.ctx = { + inboxContext: { group_type: groupType }, + logger: { info() {}, warn() {}, error() {} }, + service: { + inbox: { + groups: { + resolveActiveGroups: () => [ 'bound:store:after_sales' ], + isFunctionAvailable: def => Array.isArray(def.groups) && def.groups.length > 0, + }, + functions: { + registry, + callFunction: async (fn, params) => { + calls.push({ fn, params }); + return { success: true, data: { direct_reply: true, message: `MOCK ${fn}` } }; + }, + }, + }, + }, + }; + return svc; +} + +const CASES = [ + // [说明, 正文, 期望是否已处理, 期望函数] + [ '机器人格式-物流单号+拦截', '优禾康官方旗舰店LSFJY202609143442\n物流单号:SF5151786672496 拦截', true, 'interceptWaybill' ], + [ '机器人格式-单号中间带空格', '罗斯福医疗器械专营店LSFJY202608307192\n物流单 号:SF5117392937919 拦截', true, 'interceptWaybill' ], + [ '机器人格式-物流二字被空格断开', '优禾康番茄健康监测专卖店LSFJY202609022796\n物 流单号:SF6048940605674 拦截', true, 'interceptWaybill' ], + [ '机器人格式-快递单号标签', '快递单号:SF5151786672496 拦截', true, 'interceptWaybill' ], + [ '普通拦截请求', '拦截 SF5151786672496', true, 'interceptWaybill' ], + [ '取消拦截(长词优先)', '取消拦截 SF5151786672496', true, 'cancelIntercept' ], + [ '查询物流到哪了(不应拦截)', '这个件拦截的物流到哪了 SF5151786672496', false, null ], + [ '标签外仍有物流查询词(不应拦截)', '物流单号:SF5151786672496 拦截,顺便查下这个物流到哪了', false, null ], + [ '查快递(无拦截词)', '帮我查快递 SF5151786672496 到哪了', false, null ], + [ '客服对话-物流显示签收+拦截有风险', '772077887170843:已登记退回,物流显示签收,已通知站点核实处理,因签收之后的包裹拦截有风险', false, null ], + [ '客服对话-物流轨迹查询', '麻烦看下这个件拦截了没有,物流轨迹一直没更新 SF5151786672496', false, null ], + [ '确认语静默', '好的', true, null ], +]; + +(async () => { + let pass = 0; + const fails = []; + for (const [ desc, text, expectHandled, expectFn ] of CASES) { + const calls = []; + const svc = buildService('store', calls); + const res = await svc.handle(text); + const handled = !!res.handled; + const fn = res.fn || null; + const ok = handled === expectHandled && fn === expectFn; + if (ok) pass++; + else fails.push({ desc, expectHandled, expectFn, handled, fn, silent: !!res.silent, calls }); + console.log( + `${ok ? '✅' : '❌'} ${desc} → handled=${handled} fn=${fn} silent=${!!res.silent} ` + + `reply=${res.reply ? JSON.stringify(String(res.reply).slice(0, 40)) : '-'}` + ); + } + console.log(`\n结果:${pass}/${CASES.length} 通过`); + if (fails.length > 0) { + console.log('失败明细:', JSON.stringify(fails, null, 2)); + process.exitCode = 1; + } + + // ---- 生产群上下文模拟:真实分组解析 + 函数可用性(groups.js 为纯逻辑,不连库)---- + const GroupsService = require('../app/service/inbox/groups'); + const prodCtx = { + inboxContext: { + warehouse_id: 1000028, + store_id: 1000249, + group_type: 'store', + sub_type: 'after_sales', + group_id: '47357811653@chatroom', + }, + logger: { info() {}, warn() {}, error() {} }, + }; + const groupsSvc = Object.create(GroupsService.prototype); + groupsSvc.ctx = prodCtx; + const active = groupsSvc.resolveActiveGroups(); + const available = groupsSvc.isFunctionAvailable( + { groups: [ 'bound:warehouse:customer_service', 'bound:store:after_sales' ] }, + active + ); + console.log( + '\n生产群 47357811653@chatroom(store/after_sales/store_id=1000249) ' + + `activeGroups=${JSON.stringify(active)} interceptWaybill可用=${available}` + ); + if (!available) process.exitCode = 1; +})(); + diff --git a/script/tmp-push-inbox-robot-intercept.cjs b/script/tmp-push-inbox-robot-intercept.cjs new file mode 100644 index 0000000..5f4140d --- /dev/null +++ b/script/tmp-push-inbox-robot-intercept.cjs @@ -0,0 +1,310 @@ +/** + * 临时脚本:本地以「机器人拦截格式」推送一条站内信,验证规则引擎修复效果(不连生产、不清理数据)。 + * + * 格式来源(生产 优禾康(天豹)顺丰对接群 实测): + * <店铺名>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`); + + const 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); + 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; +});