'use strict'; const Service = require('egg').Service; const { normalizeExtDataSource } = require('../../lib/inbox_channel'); const WAREHOUSE_INTERFACE_TYPE_ID = 3; /** 历史消息过滤默认阈值:发送时间距今超过 10 分钟视为历史/补推消息,跳过 AI(可用 config.inbox.historyMessageMaxAgeMs 覆盖) */ const DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS = 10 * 60 * 1000; /** * 站内信内容处理器。 * 负责解析入站消息正文,按 source_type 分流处理, * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 */ class InboxProcessorService extends Service { /** * 从数据库拉取群信息(不缓存)。 * Egg Service 按请求实例化,进程内缓存无法跨请求共享, * 直接查库可保证 inbox.group.update/reset 修改群配置后下一条消息立即生效。 * 若群 ext_data 为空且消息携带 ext_data,自动写回群配置。 * @param {string} groupId 外部群ID * @param {number} warehouseId 仓库ID * @param {Object|null} msgExtData 入站消息的 ext_data * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, template_reply_enabled: number, ext_data: Object|null}>} 群类型/子类型/AI开关/模板回信开关/扩展数据 */ async _loadGroupInfo(groupId, warehouseId, msgExtData) { const { ctx } = this; let group = null; try { group = await ctx.model.InboxGroup.findOne({ attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'template_reply_enabled', 'ext_data' ], where: { group_id: groupId, warehouse_id: warehouseId }, raw: true, }); } catch (e) { ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); } const info = { group_type: (group && group.group_type) || '', sub_type: (group && group.sub_type) || '', ai_enabled: group ? group.ai_enabled : 0, template_reply_enabled: group ? group.template_reply_enabled : 0, ext_data: (group && group.ext_data) || null, }; // 群存在但 ext_data 为空,且入站消息带有 ext_data → 写回群配置 // 写回前按群ID格式校正渠道来源,避免把错误渠道固化进群配置 if (group && !info.ext_data && msgExtData && typeof msgExtData === 'object' && Object.keys(msgExtData).length > 0) { try { const normalizedExt = normalizeExtDataSource(groupId, msgExtData); await ctx.model.InboxGroup.update( { ext_data: normalizedExt }, { where: { group_id: groupId, warehouse_id: warehouseId } } ); info.ext_data = normalizedExt; ctx.logger.info(`[inbox processor] 群 ext_data 写回成功: ${groupId}`); } catch (e) { ctx.logger.warn(`[inbox processor] 群 ext_data 写回失败: ${e.message}`); // 写回失败不阻塞,直接返回 info(ext_data 仍为空) return info; } } return info; } /** * 判断消息是否为历史消息(发送时间距今超过阈值)。 * - flags.skipAi === true:外部显式要求跳过 AI。 * - flags.send_time 距今超过 config.inbox.historyMessageMaxAgeMs:视为历史/补推消息。 * - 未携带发送时间:按实时消息处理(向后兼容)。 * @param {Object} data 入站消息数据。 * @return {boolean} 是否应跳过 AI 处理。 */ isStaleMessage(data = {}) { const flags = data.flags || {}; if (flags.skipAi === true) return true; const sendTime = Number(flags.send_time || 0); if (!Number.isFinite(sendTime) || sendTime <= 0) return false; const maxAgeMs = Number(this.app.config.inbox?.historyMessageMaxAgeMs); const threshold = Number.isFinite(maxAgeMs) && maxAgeMs > 0 ? maxAgeMs : DEFAULT_HISTORY_MESSAGE_MAX_AGE_MS; return Date.now() - sendTime > threshold; } /** * 处理入站消息内容。 * 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。 * * @param {Object} data 入站消息数据。 * @param {string} data.content 消息正文。 * @param {number} [data.warehouse_id] 仓库ID(优先使用显式传入值)。 * @param {number} [data.store_id] 货主ID(优先使用显式传入值)。 * @return {Promise<{warehouse_id: number|null, store_id: number|null, content: string}>} 处理结果。 */ async process(data = {}) { const { ctx } = this; const content = String(data.content || '').trim(); if (!content) { throw new Error('消息正文 content 不能为空'); } // warehouse_id:优先取显式传入,否则尝试从 content 中解析 let warehouseId = data.warehouse_id != null ? Number(data.warehouse_id) : null; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { warehouseId = this.extractWarehouseId(content) || this.getWarehouseIdFromContext(); } // store_id:优先取显式传入,否则尝试从 content 中解析 let storeId = data.store_id != null ? Number(data.store_id) : null; if (!Number.isFinite(storeId) || storeId <= 0) { storeId = this.extractStoreId(content) || this.getStoreIdFromContext(); } // 写入 ctx 上下文,供下游使用 if (!ctx.inboxContext) { ctx.inboxContext = {}; } ctx.inboxContext.warehouse_id = warehouseId || null; ctx.inboxContext.store_id = storeId || null; ctx.inboxContext.group_name = data.group_name || null; ctx.inboxContext.user_name = data.user_name || null; ctx.inboxContext.group_id = data.group_id || null; ctx.inboxContext.user_id = data.user_id || null; ctx.logger.info( '[inbox processor] 内容处理完成 ' + `warehouse_id=${ctx.inboxContext.warehouse_id} ` + `store_id=${ctx.inboxContext.store_id} ` + `content_length=${content.length}` ); return { warehouse_id: ctx.inboxContext.warehouse_id, store_id: ctx.inboxContext.store_id, content, }; } /** * API 来源消息异步回执。 * 处理消息正文后,向仓库 ApiApp 回调地址 POST 确认回执。 * 回执内容为"收到",ext_data 原路带回。 * 异步执行,不阻塞入站响应。 * * @param {Object} data 入站消息数据。 * @param {number} data.warehouse_id 仓库ID。 * @param {number} [data.store_id] 货主ID。 * @param {number} [data.parent_id] 入站消息记录ID(回执的 parent_id)。 * @param {Object} [data.ext_data] 原始透传数据。 * @param {string} [data.ext_id] 外部消息ID。 * @param {string} [data.content] 消息正文。 * @return {Promise} 无返回值,异常仅记日志不抛出。 */ async handleApiMessage(data = {}) { const { ctx } = this; const { InboxMessage } = ctx.model; const warehouseId = Number(data.warehouse_id) || 0; const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id) || null; try { // 1. 处理消息正文,挂载上下文 await this.process(data); // 2. 屏蔽检查 const isBlocked = await this.isBlocked(); if (isBlocked) { ctx.logger.info(`[inbox processor] 已屏蔽,跳过回执 ext_id=${extId}`); return; } // 2.5 历史消息过滤:发送时间距今超过阈值的历史/补推消息不触发绑群与 AI,防止误建工单 if (this.isStaleMessage(data)) { ctx.logger.info(`[inbox processor] 历史消息,跳过 AI 处理 ext_id=${extId}`); return; } // 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群 const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; // 4. 加载群的 group_type / sub_type / ai_enabled / ext_data(带缓存 + 自动写回) if (ctx.inboxContext.ai_enabled === undefined) { const groupId = String(ctx.inboxContext.group_id || '').trim(); if (groupId) { const info = await this._loadGroupInfo(groupId, warehouseId, data.ext_data || null); ctx.inboxContext.group_type = info.group_type; ctx.inboxContext.sub_type = info.sub_type; ctx.inboxContext.ai_enabled = info.ai_enabled; ctx.inboxContext.template_reply_enabled = info.template_reply_enabled; ctx.inboxContext.group_ext_data = info.ext_data; } else { ctx.inboxContext.ai_enabled = 0; } } // 4.5 群未绑定任务类型 → 跳过 AI 处理 const groupType = String(ctx.inboxContext.group_type || '').trim(); if (!groupType) { ctx.logger.info(`[inbox processor] 群未绑定任务类型,跳过 AI ext_id=${extId}`); return; } // 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认) // 快递群默认 ai_enabled=0,需手动开启后才会走 AI 处理 // v2 例外:模板回信引擎(template_reply_enabled=1)优先于原链路, // 即使 ai_enabled=0 也进入第 6 步走 v2;两开关同开时仍走 v2 不走 v1/AI。 const v2Enabled = ctx.inboxContext.template_reply_enabled === 1; if (ctx.inboxContext.ai_enabled !== 1 && !v2Enabled) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); return; } // 5.1 加载屏蔽用户列表,注入上下文供 AI 判断真人接管 if (!ctx.inboxContext._blockedUserIds) { try { ctx.inboxContext._blockedUserIds = await this.loadBlockedUserIds(warehouseId); } catch (e) { ctx.logger.warn(`[inbox processor] 加载屏蔽用户列表失败: ${e.message}`); ctx.inboxContext._blockedUserIds = new Set(); } } // 5.2 注入入站消息ID,供下游函数(如 interceptWaybill)关联工单 ctx.inboxContext.inbound_message_id = parentId || null; // 6. 关键词规则引擎(主回复路径,不走 AI,节省推理费用) // v2 分叉:群开启模板回信引擎(template_reply_enabled=1)时走 v2 可配置引擎, // 模块接管模式——v2 未命中直接静默返回,不再走 v1 规则与 AI 兜底。 const text = String(data.content || '').trim(); const ruleResult = v2Enabled ? await ctx.service.inbox.v2.rules.handle(text) : await ctx.service.inbox.rules.handle(text); if (ruleResult.handled) { // 记录规则命中轨迹到入站消息,便于排查 if (ruleResult.thoughts && ruleResult.thoughts.length > 0) { try { await InboxMessage.update( { ai_thoughts: ruleResult.thoughts }, { where: { ext_id: extId } } ); } catch (e) { ctx.logger.warn(`[inbox processor] 保存规则处理记录失败: ${e.message}`); } } if (ruleResult.silent) { ctx.logger.info(`[inbox processor] 规则静默(无需回复) ext_id=${extId}`); return; } if (ruleResult.reply || (ruleResult.result && ruleResult.result.data && ruleResult.result.data.extend_props)) { // 支持多条回复(如查退回多单号):逐条独立回信; // 也支持空文案回执(如开门:content 为空,仅靠 extend_props 指令驱动) const ruleExtendProps = ruleResult.result && ruleResult.result.data && ruleResult.result.data.extend_props; const replies = Array.isArray(ruleResult.reply) ? ruleResult.reply : [ ruleResult.reply || '' ]; ctx.logger.info( `[inbox processor] 规则引擎处理完成 ext_id=${extId} ` + `fn=${ruleResult.fn || '-'} key=${ruleResult.matchedKey || '-'} replies=${replies.length}` ); // 快递群:仅执行函数,不回信 if (groupType === 'express') { ctx.logger.info(`[inbox processor] 快递群规则处理完成(不回信) ext_id=${extId}`); return; } for (let idx = 0; idx < replies.length; idx++) { const replyContent = replies[idx]; // 多条回复时每条独立 ext_id,避免回执唯一键冲突 const replyExtId = replies.length > 1 ? `${extId}:r${idx}` : extId; await this.writeOutboundReply({ warehouse_id: warehouseId, ext_id: replyExtId, parent_id: parentId, ext_data: data.ext_data || null, group_id: ctx.inboxContext?.group_id || data.group_id || null, user_id: ctx.inboxContext?.user_id || data.user_id || null, group_name: ctx.inboxContext?.group_name || data.group_name || null, user_name: ctx.inboxContext?.user_name || data.user_name || null, }, replyContent, 'rule_reply', ruleExtendProps); } } else { ctx.logger.info(`[inbox processor] 规则已执行但无回复内容 ext_id=${extId} fn=${ruleResult.fn || '-'}`); } return; } // 6.1 v2 模块接管:开启模板回信引擎的群,未命中后直接静默,不走 v1 规则与 AI 兜底 if (v2Enabled) { ctx.logger.info( `[inbox processor] v2 引擎未命中,静默(模板回信群不走 v1/AI) ext_id=${extId} ` + `content=${text.slice(0, 80)}` ); return; } // 6.5 AI 兜底(默认关闭,config.inbox.aiFallback=true 时启用) const aiFallback = !!(this.app.config.inbox && this.app.config.inbox.aiFallback); if (!aiFallback) { ctx.logger.info( `[inbox processor] 规则未命中且AI兜底关闭,静默 ext_id=${extId} ` + `content=${String(data.content || '').slice(0, 80)}` ); return; } // 7. DeepSeek 两步交互(AI 兜底,内部自行判断真人接管) const aiResult = await ctx.service.inbox.ai.processWithAI({ content: data.content || '', ext_data: data.ext_data || null, parentId: data.parent_id || null, }); // 无回复且无函数调用 → 跳过,节约资源 // AI 显式指示跳过(silent 动作)→ 同上 if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) { ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`); // 保存 AI 思考过程到入站消息,便于排查 if (aiResult.thoughts && aiResult.thoughts.length > 0) { try { await InboxMessage.update( { ai_thoughts: aiResult.thoughts }, { where: { ext_id: extId } } ); } catch (e) { ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); } } return; } const replyContent = typeof aiResult.reply === 'string' ? aiResult.reply : '已处理完成'; const aiExtendProps = aiResult.functionResult && aiResult.functionResult.data && aiResult.functionResult.data.extend_props; ctx.logger.info( `[inbox processor] AI 处理完成 ext_id=${extId} ` + `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); // 7.1 AI 推理写入入站消息(便于排查) if (aiResult.thoughts && aiResult.thoughts.length > 0) { try { await InboxMessage.update( { ai_thoughts: aiResult.thoughts }, { where: { ext_id: extId } } ); } catch (e) { ctx.logger.warn(`[inbox processor] 保存 AI 思考记录失败: ${e.message}`); } } // 8. 快递群:仅执行函数,不回信(AI 兜底分支) if (groupType === 'express') { ctx.logger.info(`[inbox processor] 快递群AI处理完成(不回信) ext_id=${extId}`); return; } // 9. 统一回信(AI 兜底分支) await this.writeOutboundReply({ warehouse_id: warehouseId, ext_id: extId, parent_id: parentId, ext_data: data.ext_data || null, group_id: ctx.inboxContext?.group_id || data.group_id || null, user_id: ctx.inboxContext?.user_id || data.user_id || null, group_name: ctx.inboxContext?.group_name || data.group_name || null, user_name: ctx.inboxContext?.user_name || data.user_name || null, }, replyContent, 'ai_reply', aiExtendProps); } catch (error) { ctx.logger.warn(`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`); } } /** * 尝试识别并执行绑群操作。 * 匹配"授权:CODE",从缓存读取绑群信息并绑定货主到群。 * * @param {Object} data 消息数据。 * @return {Promise} 是否已处理绑群。 */ async tryBindGroup(data = {}) { const { ctx } = this; const content = String(data.content || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); const groupId = String(ctx.inboxContext?.group_id || '').trim(); const bindMatch = content.match(/授权[::]\s*([A-Z0-9]{6,20})/i); if (!bindMatch || !groupId || !warehouseId) return false; const code = bindMatch[1].toUpperCase(); // 查群是否已绑定(直接查 DB,避免 ctx 上下文被仓库ID污染) try { const existingGroup = await ctx.model.InboxGroup.findOne({ attributes: [ 'store_id' ], where: { group_id: groupId, warehouse_id: warehouseId }, raw: true, }); if (existingGroup && existingGroup.store_id) { await this.writeOutboundReply(data, '已在绑定状态,无需重复操作', 'bind_confirm'); return true; } } catch (e) { ctx.logger.warn(`[inbox processor] 查群绑定状态异常: ${e.message}`); } const cacheKey = `chat:bind:${warehouseId}:${code}`; try { const cacheValue = await ctx.app.getCacheAsync(cacheKey); if (!cacheValue || !cacheValue.store_id) { await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成', 'bind_confirm'); return true; } let storeName = `货主${cacheValue.store_id}`; try { const store = await ctx.model.Store.findOne({ attributes: [ 'store_name' ], where: { id: cacheValue.store_id }, raw: true, }); if (store && store.store_name) storeName = store.store_name; } catch (e) { /* ignore */ } await ctx.model.InboxGroup.update( { store_id: cacheValue.store_id, group_type: cacheValue.group_type || 'store', sub_type: cacheValue.sub_type || null, }, { where: { group_id: groupId, warehouse_id: warehouseId } } ); ctx.inboxContext.store_id = cacheValue.store_id; ctx.inboxContext.group_type = cacheValue.group_type || 'store'; ctx.inboxContext.sub_type = cacheValue.sub_type || null; await ctx.app.setCacheAsync(cacheKey, null, 0); ctx.logger.info( `[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}` ); await this.writeOutboundReply(data, `绑定「${storeName}」成功`, 'bind_confirm'); // 绑定成功后自动查询面单余额 try { const balanceResult = await ctx.service.inbox.functions.callFunction('queryPrintBalance', {}); const balanceMsg = balanceResult?.success ? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}` : `面单余额查询失败:${balanceResult?.error || '未知错误'}`; // 使用独立 ext_id 避免与绑定成功回执冲突 await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg, 'balance'); } catch (balanceErr) { ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`); } return true; } catch (error) { ctx.logger.error(`[inbox processor] 绑群异常: ${error.message}`); return false; } } /** * 写入 outbound 回执并发送 HTTP 回调。 * group_id / user_id / group_name / user_name 为强制入参, * 缺失任一将抛出异常。 * * @param {Object} data 消息数据。 * @param {string} data.group_id 群ID(必填)。 * @param {string} data.user_id 用户ID(必填)。 * @param {string} data.group_name 群名称(必填)。 * @param {string} data.user_name 用户名称(必填)。 * @param {number} [data.reuse_message_id] 复用已有消息记录作为推送记录(重推场景): * 传入时跳过按 `sys:ack:{ext_id}` 查建,直接把推送结果回写到该记录; * 不传(0)时保持原行为(按 ext_id 幂等查建回执记录)。 * @param {string} replyContent 回复内容。 * @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。 * system 类型不要求 user_id/user_name。 * @param {Object} [extendProps=null] 回执携带的扩展指令(如开门 openDoor / 车牌登记 registerLicensePlate), * 非空时透传到 notify.reply 的 data.extend_props。 * @return {Promise} 推送是否成功(回调 HTTP 200 且返回 code=200)。 */ async writeOutboundReply(data, replyContent, source = 'ai_reply', extendProps = null) { const { ctx } = this; const { InboxMessage } = ctx.model; const warehouseId = Number(data.warehouse_id || 0); const extId = String(data.ext_id || ''); const parentId = Number(data.parent_id || 0); const isSystem = source === 'system'; const reuseMessageId = Number(data.reuse_message_id || 0); // 强制入参校验(system 类型不要求 user_id/user_name) const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim(); const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim(); const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim(); const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim(); if (!groupId || !groupName) { throw new Error(`回执缺少必填字段: group_id=${groupId || '?'}, group_name=${groupName || '?'}`); } if (!isSystem && (!userId || !userName)) { throw new Error(`回执缺少必填字段: user_id=${userId || '?'}, user_name=${userName || '?'}`); } // 按群ID格式校正渠道来源(@chatroom→wx / 纯数字→qiwe): // 群配置 ext_data 渠道错配时,回执会被桥接投递到错误渠道而丢失 const rawExtData = data.ext_data || null; const outboundExtData = normalizeExtDataSource(groupId, rawExtData); if (rawExtData && outboundExtData && rawExtData.source && rawExtData.source !== outboundExtData.source) { ctx.logger.warn( `[inbox processor] 回执 ext_data 渠道已校正 group_id=${groupId} ` + `${rawExtData.source} → ${outboundExtData.source}` ); } const ackExtId = `sys:ack:${extId}`; // 多候选路由:按 method 查询全部承接应用(id 升序),逐个尝试直到成功。 // 同一仓库可能存在多个仓库级 API 应用,必须先按「群/消息来源应用」收敛候选 // (群以 wms_inbox_group 为准):否则回执可能被首个返回 200 的其它适配器接走, // 错投且被记为已送达。 const sourceAppKey = await this.resolveReplySourceAppKey({ parentId, groupId, warehouseId, extId }); const callbackConfigs = this.orderCallbackConfigsBySource( await this.listApiAppCallbackConfigs(warehouseId, 'notify.reply'), sourceAppKey, { warehouseId, extId } ); // 重推(reuse_message_id>0):直接复用原记录,避免按 sys:ack: 前缀另建一条记录—— // 那样会让原记录(如 sys:notice:* 系统通知)状态永远停留在失败/待推送,且每次重推都新建记录 // 声明在 try 之外:异常兜底回写失败状态时仍需定位到该记录 let outboundId = reuseMessageId > 0 ? reuseMessageId : 0; try { if (!outboundId) { const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, }); if (existAck) { outboundId = existAck.id; } else { const created = await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, store_id: Number(data.store_id) || ctx.inboxContext?.store_id || null, direction: 'outbound', parent_id: parentId || null, source_type: 'system', source_extra: null, target_type: 'api', group_id: groupId, user_id: isSystem ? null : userId, group_name: groupName, user_name: isSystem ? null : userName, content: replyContent, ext_data: outboundExtData, extend_props: extendProps || null, flags: {}, }); outboundId = created.id; } } // 重推兜底:复用已有记录(定时补发送/手动重推)时,若调用方未传 extend_props, // 从原记录回读,保证定时补发送报文一定带 extend_props(如开门指令等空文案回执) let finalExtendProps = extendProps && typeof extendProps === 'object' && !Array.isArray(extendProps) ? extendProps : null; if (!finalExtendProps && outboundId > 0) { try { const existed = await InboxMessage.findOne({ where: { id: outboundId }, attributes: [ 'extend_props' ], raw: true, }); if (existed && existed.extend_props && typeof existed.extend_props === 'object' && !Array.isArray(existed.extend_props)) { finalExtendProps = existed.extend_props; } } catch (e) { ctx.logger.warn(`[inbox processor] 回读 extend_props 失败: ${e.message}`); } } const hasCallbackConfigs = callbackConfigs.length > 0; if (hasCallbackConfigs) { const method = 'notify.reply'; const notifyBody = { code: 200, data: { // rule_reply(关键词规则引擎回执)与 ai_reply 同属机器人自动回复,映射为 ai 类型 type: isSystem ? 'system' : (source === 'ai_reply' || source === 'rule_reply') ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error', content: replyContent, ext_data: outboundExtData, ...(finalExtendProps ? { extend_props: finalExtendProps } : {}), ext_id: String(outboundId), group_id: groupId, ...(isSystem ? {} : { user_id: userId, user_name: userName }), group_name: groupName, timestamp: Math.floor(Date.now() / 1000), }, }; // 逐个候选尝试:第一个成功即止;全部失败回写失败状态且不改动接口配置 for (const callbackConfig of callbackConfigs) { const attempt = await this.pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody }); if (attempt.pushOk) { await InboxMessage.update( { push_status: 2, push_response: { http_status: attempt.httpStatus, body: attempt.response || null }, pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { where: { id: outboundId } } ); // 同步更新原入站消息的推送状态 if (parentId) { await InboxMessage.update( { push_status: 2, pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { where: { id: parentId } } ); } return true; } } // 全部候选尝试失败:回写状态和原因 await InboxMessage.update( { push_status: 3, push_response: { error: `全部 ${callbackConfigs.length} 个回调应用尝试失败`, }, }, { where: { id: outboundId } } ); return false; } // 无应用承接该回调:回写状态 await InboxMessage.update( { push_status: 3, push_response: { error: '无应用承接该回调(callback_functions 未勾选或应用未启用)' }, }, { where: { id: outboundId } } ); ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 无应用承接回调 notify.reply,回写失败状态 ext_id=${extId}`); return false; } catch (error) { ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`); // 推送异常时更新状态 + 写日志 try { await InboxMessage.update( { push_status: 3, push_response: { error: error.message } }, { where: { id: outboundId } } ); } catch (updateErr) { ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message); } try { const { WarehouseLog } = ctx.model; const crypto = require('crypto'); await WarehouseLog.create({ log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), app_key: (await this.getApiAppCallbackConfig(warehouseId)).appKey || null, method: 'notify.reply', warehouse_id: warehouseId || null, http_status: null, body: '', result: 'Error: ' + error.message, use_time: null, created_at: new Date(), }); } catch (logErr) { ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message); } return false; } } /** * 判断当前消息所在群是否为仓库内部群(wms_inbox_group.group_type='warehouse')。 * 优先使用已加载的群信息(ctx.inboxContext.group_type),避免重复查库; * 未加载时按 (group_id, warehouse_id) 查库,查库异常按「非仓库群」处理(屏蔽照常生效,安全默认)。 * * @param {string} groupId 外部群ID。 * @param {number} warehouseId 仓库ID。 * @return {Promise} 是否仓库群。 */ async isWarehouseGroup(groupId, warehouseId) { const { ctx } = this; const cachedGroupType = String(ctx.inboxContext?.group_type || '').trim(); if (cachedGroupType) return cachedGroupType === 'warehouse'; if (!groupId) return false; try { const group = await ctx.model.InboxGroup.findOne({ attributes: [ 'group_type' ], where: { group_id: groupId, warehouse_id: warehouseId }, raw: true, }); return String((group && group.group_type) || '').trim() === 'warehouse'; } catch (error) { ctx.logger.warn(`[inbox processor] 查询群类型失败: ${error.message}`); return false; } } /** * 加载当前仓库的屏蔽用户ID集合(供 AI 判断真人接管)。 * 口径与 isBlocked() 一致:仓库群忽略不带群ID的屏蔽记录(仅带 group_id 的记录才算命中), * 避免货主群/快递群等场景的用户级屏蔽连带把仓库群用户标记为「已屏蔽」。 * * @param {number} warehouseId 仓库ID。 * @return {Promise>} 屏蔽用户ID集合。 */ async loadBlockedUserIds(warehouseId) { const { ctx } = this; const isWarehouseGroup = String(ctx.inboxContext?.group_type || '').trim() === 'warehouse'; const { InboxBlock } = ctx.model; const rows = await InboxBlock.findAll({ attributes: [ 'group_id', 'user_id' ], where: { warehouse_id: warehouseId }, raw: true, }); return new Set( rows .filter(r => !(isWarehouseGroup && !String(r.group_id || '').trim())) .map(r => String(r.user_id || '').trim()) .filter(Boolean) ); } /** * 检查当前消息的群/用户是否在屏蔽列表中。 * * 口径: * - 带群ID的屏蔽记录(`群:用户` / `群:*`)在对应群内始终生效; * - 仅带 user_id 的全局用户屏蔽(`*:用户`)在仓库群内不生效——仓库群是内部群, * 此类屏蔽多来自货主群/快递群等外部场景,不应连带跳过仓库群消息; * 仓库群内由机器人发起的屏蔽([屏蔽] 指令)会写入当前群 group_id,故仍按带群ID记录生效。 * - 无群ID的消息(如私聊)不受此例外影响。 * * @return {Promise} 是否已屏蔽。 */ async isBlocked() { const { ctx } = this; const app = ctx.app; const groupId = String(ctx.inboxContext?.group_id || '').trim(); const userId = String(ctx.inboxContext?.user_id || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); if (!groupId && !userId) return false; try { // 1. 尝试从缓存读取屏蔽列表 const cacheKey = `inbox:block:${warehouseId}`; let blockedSet = await app.getCacheAsync(cacheKey); if (!blockedSet || !(blockedSet instanceof Set)) { // 2. 缓存未命中,查库并填入缓存 const { InboxBlock } = ctx.model; const rows = await InboxBlock.findAll({ attributes: [ 'group_id', 'user_id' ], where: { warehouse_id: warehouseId }, raw: true, }); blockedSet = new Set(); for (const row of rows) { const g = String(row.group_id || '').trim(); const u = String(row.user_id || '').trim(); if (g && u) blockedSet.add(`${g}:${u}`); if (g && !u) blockedSet.add(`${g}:*`); if (!g && u) blockedSet.add(`*:${u}`); } // TTL 5 分钟 await app.setCacheAsync(cacheKey, blockedSet, 300); } // 3. 检查当前消息是否命中屏蔽规则 if (groupId && userId && blockedSet.has(`${groupId}:${userId}`)) return true; if (groupId && blockedSet.has(`${groupId}:*`)) return true; if (userId && blockedSet.has(`*:${userId}`)) { // 仓库群忽略不带群ID的用户级屏蔽(见方法注释) if (groupId && await this.isWarehouseGroup(groupId, warehouseId)) { ctx.logger.info(`[inbox processor] 仓库群忽略不带群ID的用户屏蔽 group_id=${groupId} user_id=${userId}`); return false; } return true; } return false; } catch (error) { ctx.logger.warn(`[inbox processor] 屏蔽检查异常: ${error.message}`); return false; } } /** * 失效屏蔽缓存,在新增屏蔽记录后调用。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 无返回值。 */ async invalidateBlockCache(warehouseId) { const { ctx } = this; try { await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0); } catch (error) { ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`); } } /** * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 * 兼容旧调用:默认取承接 notify.reply 的首个应用。 * * @param {number} warehouseId 仓库ID。 * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。 */ async getApiAppCallbackConfig(warehouseId) { return await this.getApiAppCallbackConfigByMethod(warehouseId, 'notify.reply'); } /** * 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。 * * @param {number} warehouseId 仓库ID。 * @param {string} method 出站 method。 * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。 */ async getApiAppCallbackConfigByMethod(warehouseId, method) { const list = await this.listApiAppCallbackConfigs(warehouseId, method); const first = list[0] || {}; return { url: first.url || null, appKey: first.appKey || null, appSecret: first.appSecret || null, }; } /** * 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。 * callback_functions 为空/未勾选的应用不承接任何回调(不放行)。 * * @param {number} warehouseId 仓库ID。 * @param {string} method 出站 method。 * @return {Promise>} 候选列表。 */ async listApiAppCallbackConfigs(warehouseId, method) { const { ctx } = this; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { return []; } const apiAppModel = ctx.model && ctx.model.ApiApp; if (!apiAppModel || typeof apiAppModel.findAll !== 'function') { return []; } try { const rows = await apiAppModel.findAll({ attributes: [ 'id', 'callback_url', 'self_app_key', 'self_app_secret', 'callback_functions' ], where: { warehouse_id: warehouseId, interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, is_enabled: 1, }, order: [[ 'id', 'ASC' ]], raw: true, }); const methodStr = String(method || '').trim(); return rows .filter(row => { let list = row.callback_functions; if (typeof list === 'string') { try { list = JSON.parse(list); } catch (error) { list = null; } } return Array.isArray(list) && list.map(item => String(item || '').trim()).includes(methodStr); }) .map(row => ({ appId: Number(row.id), url: row.callback_url || null, appKey: row.self_app_key || null, appSecret: row.self_app_secret || null, })); } catch (error) { ctx.logger.warn(`[inbox processor] 查询回调配置列表失败: ${error.message}`); return []; } } /** * 从来源记录中提取仓库级 API 应用的 AppKey。 * 仅 source_type='api' 时 source_extra 才是 appKey(IM 来源存的是平台标识)。 * @param {Object|null} row 入站消息或群记录。 * @return {string|null} 来源应用 AppKey。 */ pickApiSourceAppKey(row) { if (!row || String(row.source_type || '') !== 'api') return null; const appKey = String(row.source_extra || '').trim(); return appKey || null; } /** * 解析回执应发往的来源应用 AppKey。 * 优先级:群创建来源(wms_inbox_group 为准)→ 入站消息来源 → ext_id(api:{appKey}:{requestId})兜底。 * 群是站内信的会话归属中心,内部通知与回执都从群配置出发,优先按群来源收敛候选。 * @param {Object} options 解析参数。 * @param {number} [options.parentId] 入站消息记录 ID。 * @param {string} [options.groupId] 外部群 ID。 * @param {number} [options.warehouseId] 仓库 ID。 * @param {string} [options.extId] 入站消息 ext_id。 * @return {Promise} 来源应用 AppKey。 */ async resolveReplySourceAppKey({ parentId, groupId, warehouseId, extId } = {}) { const { ctx } = this; const groupIdStr = String(groupId || '').trim(); if (groupIdStr && Number(warehouseId) > 0) { try { const group = await ctx.model.InboxGroup.findOne({ attributes: [ 'source_type', 'source_extra' ], where: { group_id: groupIdStr, warehouse_id: Number(warehouseId) }, raw: true, }); const appKey = this.pickApiSourceAppKey(group); if (appKey) return appKey; } catch (error) { ctx.logger.warn(`[inbox processor] 查询群来源失败: ${error.message}`); } } const inboundId = Number(parentId) || 0; if (inboundId > 0) { try { const row = await ctx.model.InboxMessage.findOne({ attributes: [ 'source_type', 'source_extra' ], where: { id: inboundId, warehouse_id: Number(warehouseId) || 0 }, raw: true, }); const appKey = this.pickApiSourceAppKey(row); if (appKey) return appKey; } catch (error) { ctx.logger.warn(`[inbox processor] 查询入站消息来源失败: ${error.message}`); } } // ext_id 约定:api:{appKey}:{requestId} const matched = /^api:([^:]+):/.exec(String(extId || '')); return matched ? matched[1] : null; } /** * 按来源应用收敛回执候选:来源应用承接时只发给它,避免多应用错投; * 来源缺失或未承接时保持原有候选顺序(兼容旧行为)并记录告警。 * @param {Array} candidates 候选应用列表(含 appKey)。 * @param {string|null} sourceAppKey 来源应用 AppKey。 * @param {Object} [context] 日志上下文。 * @param {number} [context.warehouseId] 仓库 ID。 * @param {string} [context.extId] 消息 ext_id。 * @return {Array} 收敛后的候选列表。 */ orderCallbackConfigsBySource(candidates, sourceAppKey, { warehouseId, extId } = {}) { const list = Array.isArray(candidates) ? candidates : []; if (list.length <= 1) return list; const sourceKey = String(sourceAppKey || '').trim(); if (!sourceKey) { this.ctx.logger.warn( `[inbox processor] 无法确定回执来源应用,按候选顺序尝试 warehouse=${warehouseId} ext_id=${extId} candidates=${list.length}` ); return list; } const matched = list.filter(item => String(item.appKey || '').trim() === sourceKey); if (matched.length > 0) return matched; this.ctx.logger.warn( `[inbox processor] 来源应用未承接 notify.reply,按候选顺序兜底 warehouse=${warehouseId} source_app=${sourceKey} ext_id=${extId} candidates=${list.length}` ); return list; } /** * 单次回执推送尝试(回执专用协议:MD5(appSecret+timestamp+bodyJson) + POST)。 * 每次尝试均写 wms_warehouse_log,失败不改动接口配置。 * * @param {Object} options 尝试参数。 * @param {Object} options.callbackConfig 候选应用 { appId, url, appKey, appSecret }。 * @param {number} options.warehouseId 仓库ID。 * @param {string} options.method 出站 method。 * @param {Object} options.notifyBody 推送体(已组装)。 * @return {Promise} { pushOk, httpStatus, response, error }。 */ async pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody }) { const { ctx } = this; const crypto = require('crypto'); const callbackUrl = callbackConfig.url; const bodyJson = JSON.stringify(notifyBody); const timestamp = Math.floor(Date.now() / 1000); const appKey = callbackConfig.appKey || ''; const appSecret = callbackConfig.appSecret || ''; // MD5 签名:MD5(appSecret + timestamp + bodyJson) const sign = appSecret ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') : ''; const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`; const startTime = Date.now(); let curlResult = null; let error = null; try { curlResult = await ctx.curl(urlWithSign, { method: 'POST', dataType: 'json', contentType: 'json', data: notifyBody, headers: { 'Content-Type': 'application/json' }, timeout: 10000, }); } catch (curlError) { error = curlError; } // HTTP 200 且 body.code=200 → 推送成功 const pushOk = !!curlResult && curlResult.status === 200 && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); // 记录出站通知日志到 wms_warehouse_log(每次尝试均记录) try { const { WarehouseLog } = ctx.model; await WarehouseLog.create({ log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), app_key: appKey || null, method, warehouse_id: warehouseId || null, url: urlWithSign || null, http_status: curlResult ? curlResult.status : null, body: bodyJson.substring(0, 65535), result: curlResult ? JSON.stringify(curlResult.data || {}).substring(0, 65535) : 'Error: ' + (error ? error.message : ''), use_time: Date.now() - startTime, created_at: new Date(), }); } catch (logErr) { ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message); } return { pushOk, httpStatus: curlResult ? curlResult.status : null, response: curlResult ? (curlResult.data || null) : null, error: error ? error.message : (pushOk ? null : '回调返回非200或code非200'), }; } /** * 获取仓库 ApiApp 回调地址(兼容旧调用)。 * @param {number} warehouseId 仓库ID。 * @return {Promise} 回调 URL。 */ async getApiAppCallbackUrl(warehouseId) { const config = await this.getApiAppCallbackConfig(warehouseId); return config.url; } /** * 系统通知异步推送:仅 POST 回调,不写 inbox_message。 * @param {Object} data 通知数据。 * @param {number} data.warehouse_id 仓库ID。 * @param {string} data.group_id 目标群ID。 * @param {string} data.group_name 目标群名称。 * @param {string} data.content 通知内容。 * @param {Object} [data.ext_data] 群扩展数据(渠道信息)。 * @param {number} [data.store_id] 目标货主ID(用于写入回信记录的 store_id)。 * @return {void} 无返回值,异步写入与推送。 */ pushSystemNotification(data = {}) { const { ctx } = this; const warehouseId = Number(data.warehouse_id); const groupId = String(data.group_id || '').trim(); const groupName = String(data.group_name || '').trim(); const content = String(data.content || '').trim(); const extData = data.ext_data || null; const storeId = Number(data.store_id) || null; if (!warehouseId || !groupId || !content) return; // 构造 data 对象,复用 writeOutboundReply const replyData = { warehouse_id: warehouseId, ext_id: `sys:notify:${warehouseId}:${groupId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`, parent_id: null, ext_data: extData, group_id: groupId, user_id: '', group_name: groupName, user_name: '', store_id: storeId, }; // 写库 + POST,异步不阻塞 setImmediate(() => { this.writeOutboundReply(replyData, content, 'system').catch(err => { ctx.logger.warn(`[pushNotify] 推送异常 group=${groupName}: ${err.message}`); }); }); } /** * 尝试从消息正文中提取仓库ID。 * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 * * @param {string} content 消息正文。 * @return {number|null} 仓库ID,无法解析时返回 null。 */ extractWarehouseId(content) { // 默认不解析,由业务方覆盖 void content; return null; } /** * 尝试从消息正文中提取货主ID。 * 子类或业务方可覆盖此方法以实现自定义解析逻辑。 * * @param {string} content 消息正文。 * @return {number|null} 货主ID,无法解析时返回 null。 */ extractStoreId(content) { // 默认不解析,由业务方覆盖 void content; return null; } /** * 从 Egg.js 请求上下文中获取仓库ID。 * * @return {number|null} 仓库ID。 */ getWarehouseIdFromContext() { const { ctx } = this; const user = ctx.user || ctx.state?.user || {}; const warehouseId = Number(user.store_id || user.warehouse_id) || null; return Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : null; } /** * 从 Egg.js 请求上下文中获取货主ID。 * * @return {number|null} 货主ID。 */ getStoreIdFromContext() { const { ctx } = this; const user = ctx.user || ctx.state?.user || {}; const storeId = Number(user.store_id) || null; return Number.isFinite(storeId) && storeId > 0 ? storeId : null; } } module.exports = InboxProcessorService;