'use strict'; /* eslint-disable no-use-before-define */ const Service = require('egg').Service; /** * 取号 target → 函数入参键映射。 * keyword 类(运单号/订单号/平台单号/收货单/入库单/出库单)合并为一个逗号分隔字符串; * express_name 取第一个匹配值。 * 注意:只保留有真实消费者的映射;plate_no 当前无函数消费 params.plate_no * (车牌函数自行从原消息提取),不入映射,避免悬空。 */ const TARGET_PARAM_MAP = { waybill_no: 'keyword', order_no: 'keyword', source_order_codes: 'keyword', receiving_no: 'keyword', entry_order_no: 'keyword', stockout_no: 'keyword', express_name: 'express', }; /** * 函数按子类型补充 issue_type 入参(函数入参语义由代码定义,引擎按子类型转译)。 */ const FN_ISSUE_TYPE_MAP = { handleStoreFeedback: { damage: 'damaged', missing_item: 'missing', mis_shipment: 'wrong', extra_item: 'multiple', }, changeAddr: { change_address: 'addr', rejected: 'return', urge: 'urge', }, }; /** 取号失败默认引导语(回复表未配置 no_number_hint 时使用)。 */ const DEFAULT_NO_NUMBER_HINT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)'; /** 单值类 target 缺参引导语。 */ const TARGET_HINT_MAP = { express_name: '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)', }; /** * v2 仓库可配置回信引擎(规则驱动,替代 v1 硬编码规则表)。 * * 链路:关键词命中(长词优先)→ 群类型白名单过滤 → 关系表取处理函数 → * 取号规则提取对象数组 → 入参组装 → callFunction(代码 groups 越权校验兜底)→ 回复表决策。 * * 出参与 v1 rules.handle 同构: * - { handled: false }:未命中; * - { handled: true, silent: true }:命中但静默(回复表 is_reply=0); * - { handled: true, reply, fn, params, result, matchedKey, thoughts }:已执行。 * * 安全三件套(取号正则):保存时校验(管理接口)+ 长度上限(DB 列 500)+ * 每次 new RegExp(绝不缓存编译对象,避免状态污染与 ReDoS 复用),非法正则跳过并告警。 */ class InboxV2RulesService extends Service { /** * v2 引擎主入口。 * @param {string} content 消息正文。 * @return {Promise} 处理结果(与 v1 rules.handle 同构)。 */ async handle(content) { const { ctx } = this; const text = String(content || '').trim(); if (!text) return { handled: false }; const groupType = String(ctx.inboxContext?.group_type || '').trim(); if (!groupType) return { handled: false }; const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); const groupSubType = String(ctx.inboxContext?.sub_type || '').trim(); const cfg = await ctx.service.inbox.v2.config.load(warehouseId); // 1. 关键词命中:长词优先;同长按 sort_order;同长同子类型只保留一次。 const candidates = this._matchKeywords(text, cfg); if (candidates.length === 0) { ctx.logger.info(`[inbox v2] 未命中关键词 group=${groupType} text=${text.slice(0, 50)}`); return { handled: false }; } const groupsSvc = ctx.service.inbox.groups; const funcSvc = ctx.service.inbox.functions; const activeGroups = groupsSvc.resolveActiveGroups(); // 2. 候选子类型逐个尝试:白名单过滤 → 取函数 → 取号 → 执行。 for (const cand of candidates) { const subType = cfg.subTypes[cand.sub_type_id]; if (!subType) continue; // 2.1 群类型白名单过滤(sub_group 维度;群 sub_type 为空时只按主类型) if (!this._groupAllowed(cfg, cand.sub_type_id, groupType, groupSubType)) { ctx.logger.info( `[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 不在群 ${groupType}:${groupSubType || '-'} 白名单,跳过` ); continue; } // 2.2 取关联函数(启用且代码已注册且群权限可用) const fns = (cfg.subTypeFunctions[cand.sub_type_id] || []).filter(f => cfg.functionEnabled[f.function_code] ); if (fns.length === 0) { ctx.logger.info(`[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 无可用函数,跳过`); continue; } // 2.3 取号规则提取(对象数组:{target, values[]}) const extracted = this._extractNumbers(text, cfg, cand.sub_type_id); if (extracted === null) { // 关联了取号规则但未提取到值 → 引导提示 const reply = this._noNumberHint(cfg, cand.sub_type_id); const thoughts = [{ round: 0, action: 'rule', function: fns[0].function_code, params: {}, reason: `v2 关键词命中: ${cand.keyword},取号失败-引导提示`, functionResult: null, }]; return { handled: true, reply, fn: fns[0].function_code, params: {}, result: null, matchedKey: cand.keyword, thoughts, }; } // 2.4 逐函数执行:函数照常执行;create_work_order=0 时注入 skip_work_order // 标记,由函数内部在建工单前自行跳过登记(其余处理不受影响)。 const replyCfgNow = (cfg.replies || {})[cand.sub_type_id]; const workOrderSkip = !!replyCfgNow && replyCfgNow.create_work_order === 0; const results = []; let lastFn = null; let lastParams = null; let executed = false; if (workOrderSkip) { ctx.inboxContext.skip_work_order = true; ctx.logger.info( `[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 配置为不登记工单,函数照常执行但跳过建单` ); } try { for (const f of fns) { const def = funcSvc.registry.get(f.function_code); if (!def || !groupsSvc.isFunctionAvailable(def, activeGroups)) { ctx.logger.info( `[inbox v2] 函数 ${f.function_code} 当前群不可用,跳过 ` + `groups=${def ? def.groups.join(',') : '-'} active=${activeGroups.join(',')}` ); continue; } const params = this._buildParams(f.function_code, subType, extracted); const result = await funcSvc.callFunction(f.function_code, params); lastFn = f.function_code; lastParams = params; executed = true; ctx.logger.info( `[inbox v2] 执行 fn=${f.function_code} sub=${subType.type}:${subType.sub_type} ` + `params=${JSON.stringify(params)} success=${!!result.success}` ); if (!result.success) { const thoughts = [{ round: 0, action: 'rule', function: f.function_code, params, reason: `v2 关键词命中: ${cand.keyword}`, functionResult: result, }]; return { handled: true, reply: String(result.error || '操作失败,请联系客服处理'), fn: f.function_code, params, result, matchedKey: cand.keyword, thoughts, }; } results.push({ fn: f.function_code, params, result }); } } finally { if (workOrderSkip) ctx.inboxContext.skip_work_order = false; } if (!executed) continue; // 2.5 回复决策:完全由回复配置控制(仓库级覆盖系统级) return this._buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text); } return { handled: false }; } /** * 关键词匹配:收集文本包含的所有关键词,按长度降序、sort_order 升序排序, * 取最长命中词集合(同长多子类型均候选)。 * @param {string} text 消息正文。 * @param {Object} cfg v2 配置。 * @return {Array<{keyword:string, sub_type_id:number}>} 候选列表。 */ _matchKeywords(text, cfg) { const hits = []; for (const k of cfg.keywords || []) { if (k.keyword && text.includes(k.keyword)) hits.push({ keyword: k.keyword, sub_type_id: k.sub_type_id }); } if (hits.length === 0) return []; hits.sort((a, b) => b.keyword.length - a.keyword.length); const maxLen = hits[0].keyword.length; const top = hits.filter(h => h.keyword.length === maxLen); const seen = new Set(); return top.filter(h => { const key = h.sub_type_id; if (seen.has(key)) return false; seen.add(key); return true; }); } /** * 群类型白名单过滤。 * @param {Object} cfg v2 配置。 * @param {number} subTypeId 子类型ID。 * @param {string} groupType 群主类型。 * @param {string} groupSubType 群子类型(可为空)。 * @return {boolean} 是否允许。 */ _groupAllowed(cfg, subTypeId, groupType, groupSubType) { const rows = (cfg.groupWhitelist || {})[subTypeId]; if (!Array.isArray(rows) || rows.length === 0) return false; return rows.some(r => { if (r.group_type === '*') return true; // 全通配:所有群可用(如 help 指令) if (r.group_type !== groupType) return false; if (!groupSubType) return true; // 群未绑子类型:只按主类型放行 if (r.sub_group === '*') return true; // 主类型内子类型通配(如 warehouse:*) return r.sub_group === groupSubType; }); } /** * 取号规则提取(安全三件套:每次 new RegExp + try/catch + 长度上限)。 * @param {string} text 消息正文。 * @param {Object} cfg v2 配置。 * @param {number} subTypeId 子类型ID。 * @return {Array|null} 提取结果数组 [{target, values[]}];未提取到任何值返回 null。 */ _extractNumbers(text, cfg, subTypeId) { const rules = (cfg.subTypeRules || {})[subTypeId]; if (!Array.isArray(rules) || rules.length === 0) return []; const out = []; let anyHit = false; for (const rule of rules) { if (!rule.regexp) continue; if (rule.regexp.length > 500) { this.ctx.logger.warn(`[inbox v2] 取号正则超长跳过 sub_type_id=${subTypeId} target=${rule.target}`); continue; } let re; try { re = new RegExp(rule.regexp, 'g'); // 每次新建,绝不缓存编译对象 } catch (e) { this.ctx.logger.warn( `[inbox v2] 取号正则非法跳过 sub_type_id=${subTypeId} target=${rule.target}: ${e.message}` ); continue; } const values = []; try { for (const m of text.matchAll(re)) { const v = String(m[0]).trim(); if (v && !values.includes(v)) values.push(v); } } catch (e) { this.ctx.logger.warn(`[inbox v2] 取号正则执行异常 target=${rule.target}: ${e.message}`); } out.push({ target: rule.target, values }); if (values.length > 0) anyHit = true; } return anyHit ? out : null; } /** * 入参组装:取号结果对象数组 → 函数 params。 * keyword 类 target 合并去重后 join(',');express/plate_no 取第一个值; * 按函数补充 issue_type。 * @param {string} fn 函数名。 * @param {Object} subType 子类型记录。 * @param {Array} extracted 提取结果。 * @return {Object} 函数入参。 */ _buildParams(fn, subType, extracted) { const params = {}; const keywordValues = []; for (const item of extracted) { const paramKey = TARGET_PARAM_MAP[item.target]; if (!paramKey || item.values.length === 0) continue; if (paramKey === 'keyword') { for (const v of item.values) { if (!keywordValues.includes(v)) keywordValues.push(v); } } else if (!params[paramKey]) { params[paramKey] = item.values[0]; } } if (keywordValues.length > 0) params.keyword = keywordValues.join(','); // 子类型 → issue_type 转译 const map = FN_ISSUE_TYPE_MAP[fn]; if (map && map[subType.sub_type]) params.issue_type = map[subType.sub_type]; return params; } /** * 取号失败引导语:回复表 no_number_hint → target 专属 → 默认。 * @param {Object} cfg v2 配置。 * @param {number} subTypeId 子类型ID。 * @return {string} 引导语。 */ _noNumberHint(cfg, subTypeId) { const replyCfg = (cfg.replies || {})[subTypeId]; if (replyCfg && replyCfg.no_number_hint) return replyCfg.no_number_hint; const rules = (cfg.subTypeRules || {})[subTypeId] || []; for (const r of rules) { if (TARGET_HINT_MAP[r.target]) return TARGET_HINT_MAP[r.target]; } return DEFAULT_NO_NUMBER_HINT; } /** * 出参构建:回复决策完全由回复配置控制(仓库级覆盖系统级)。 * @param {Object} cfg v2 配置。 * @param {Object} cand 命中候选。 * @param {Object} subType 子类型记录。 * @param {Array} results 函数执行结果数组。 * @param {string} lastFn 最后执行的函数名。 * @param {Object} lastParams 最后执行的函数入参。 * @param {string} text 消息正文。 * @return {Object} 与 v1 rules.handle 同构的出参。 */ _buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text) { const last = results.length > 0 ? results[results.length - 1] : null; const replyCfg = (cfg.replies || {})[cand.sub_type_id]; // 回复决策:完全由回复配置控制。 // - is_reply=0 → 静默; // - reply 模板渲染非空 → 回复; // - 无回复配置或模板渲染为空 → 不回复(函数已照常执行,仅不出回执)。 if (replyCfg && replyCfg.is_reply === 0) { return { handled: true, silent: true }; } let reply = null; if (replyCfg && replyCfg.reply) { const rendered = this._renderReply(replyCfg.reply, subType, results, text, lastParams); if (rendered && String(rendered).trim()) reply = rendered; } let thoughts = results.map((r, idx) => ({ round: idx, action: 'rule', function: r.fn, params: r.params, reason: `v2 关键词命中: ${cand.keyword}`, functionResult: r.result, })); if (thoughts.length === 0 && lastParams) { // 兜底(一般不可达:fns 全部不可用才出现):记录一条无函数调用的轨迹 thoughts = [{ round: 0, action: 'rule', function: lastFn, params: lastParams, reason: `v2 关键词命中: ${cand.keyword}(无可用函数)`, functionResult: null, }]; } return { handled: true, reply, fn: lastFn || (last && last.fn), params: lastParams || (last && last.params), result: last ? last.result : null, matchedKey: cand.keyword, thoughts, }; } /** * 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}/{back_text}。 * {back_text} 优先取函数返回的 data.back_text(如 help 函数生成的指令清单); * 函数未返回 back_text 时回退到 data.message(对齐 v1 rules.buildReply 口径, * 否则 interceptWaybill 等只返回 message 的函数渲染恒为空 → 静默不回信)。 * @param {string} tpl 模板文案。 * @param {Object} subType 子类型记录。 * @param {Array} results 函数执行结果。 * @param {string} text 消息正文。 * @param {Object} [fallbackParams] 未执行函数时的备用参数(create_work_order=0 场景)。 * @return {string} 渲染后的文案。 */ _renderReply(tpl, subType, results, text, fallbackParams) { const last = results.length > 0 ? results[results.length - 1] : null; const params = (last && last.params) || fallbackParams || {}; const lastData = (last && last.result && last.result.data) || {}; const backText = lastData.back_text ? String(lastData.back_text) : (typeof lastData.message === 'string' ? String(lastData.message) : ''); return String(tpl) .replace(/\{sub_type_name\}/g, subType.name || '') .replace(/\{keyword\}/g, String(params.keyword || '')) .replace(/\{express\}/g, String(params.express || '')) .replace(/\{back_text\}/g, backText) .replace(/\{text\}/g, text.slice(0, 200)); } } module.exports = InboxV2RulesService;