'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 逐函数执行(按 sort_order;任一失败立即以失败出参返回) const results = []; let lastFn = null; let lastParams = null; let executed = false; 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 }); } 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 !== groupType) return false; if (!groupSubType) return true; // 群未绑子类型:只按主类型放行 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[results.length - 1]; const replyCfg = (cfg.replies || {})[cand.sub_type_id]; // 回复表显式配置:is_reply=0 静默;is_reply=1 用自定义文案(占位符替换) if (replyCfg && replyCfg.is_reply === 0) { return { handled: true, silent: true }; } let reply; if (replyCfg && replyCfg.reply) { reply = this._renderReply(replyCfg.reply, subType, results, text); } else { // 无回复配置:函数返回值兜底(与 v1 buildReply 同构语义) reply = this._buildReplyFromResult(results); } const thoughts = results.map((r, idx) => ({ round: idx, action: 'rule', function: r.fn, params: r.params, reason: `v2 关键词命中: ${cand.keyword}`, functionResult: r.result, })); return { handled: true, reply, fn: lastFn || last.fn, params: lastParams || last.params, result: last.result, matchedKey: cand.keyword, thoughts, }; } /** * 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}。 * @param {string} tpl 模板文案。 * @param {Object} subType 子类型记录。 * @param {Array} results 函数执行结果。 * @param {string} text 消息正文。 * @return {string} 渲染后的文案。 */ _renderReply(tpl, subType, results, text) { const last = results[results.length - 1]; const params = (last && last.params) || {}; return String(tpl) .replace(/\{sub_type_name\}/g, subType.name || '') .replace(/\{keyword\}/g, String(params.keyword || '')) .replace(/\{express\}/g, String(params.express || '')) .replace(/\{text\}/g, text.slice(0, 200)); } /** * 无回复配置时,从函数返回值兜底构建回复(direct_reply.messages → data.message → error)。 * @param {Array} results 函数执行结果数组。 * @return {string|string[]|null} 回复文本。 */ _buildReplyFromResult(results) { const replies = []; for (const r of results) { const result = r.result; if (!result || typeof result !== 'object') continue; if (result.success === false) { replies.push(String(result.error || '操作失败,请联系客服处理')); continue; } const data = result.data || {}; if (data.direct_reply === true && Array.isArray(data.messages) && data.messages.length > 0) { replies.push(...data.messages.map(m => String(m))); } else if (data.message) { replies.push(String(data.message)); } } if (replies.length === 0) return null; return replies.length === 1 ? replies[0] : replies; } } module.exports = InboxV2RulesService;