'use strict'; const Service = require('egg').Service; const WAREHOUSE_INTERFACE_TYPE_ID = 3; const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s /** * 站内信内容处理器。 * 负责解析入站消息正文,按 source_type 分流处理, * 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。 */ class InboxProcessorService extends Service { /** * 处理入站消息内容。 * 解析 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; } // 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群 const bindHandled = await this.tryBindGroup(data); if (bindHandled) return; // 4. 群未绑定货主则跳过 AI 解析 const storeId = Number(ctx.inboxContext?.store_id || 0); if (!storeId) { ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`); return; } // 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文 if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || ctx.inboxContext.ai_enabled === undefined) { try { const groupId = String(ctx.inboxContext.group_id || '').trim(); if (groupId) { const group = await ctx.model.InboxGroup.findOne({ attributes: [ 'group_type', 'sub_type', 'ai_enabled' ], where: { group_id: groupId, warehouse_id: warehouseId }, raw: true, }); if (group) { ctx.inboxContext.group_type = group.group_type || ''; ctx.inboxContext.sub_type = group.sub_type || ''; ctx.inboxContext.ai_enabled = group.ai_enabled; ctx.logger.info( `[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}` ); } } } catch (e) { ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`); } } // 4.2 群未启用AI → 跳过 AI 解析(灰度开关) if (ctx.inboxContext.ai_enabled === 0) { ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`); return; } // 5. DeepSeek 两步交互 const aiResult = await ctx.service.inbox.functions.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}`); return; } const replyContent = aiResult.reply || '已处理完成'; ctx.logger.info( `[inbox processor] AI 处理完成 ext_id=${extId} ` + `function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}` ); // 6. 写入 outbound 回执记录 const ackExtId = `sys:ack:${extId}`; try { const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, }); if (!existAck) { await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, store_id: data.store_id || null, direction: 'outbound', parent_id: parentId, source_type: 'system', source_extra: null, target_type: 'api', 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, content: replyContent, ext_data: data.ext_data || null, ai_thoughts: aiResult.thoughts || null, flags: {}, }); ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`); } } catch (writeError) { ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`); } // 7. 查回调地址并发送 const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); if (!callbackUrl) { ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`); return; } const ackBody = { content: replyContent, ext_data: data.ext_data || null, ext_id: extId || null, }; ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`); const response = await ctx.curl(callbackUrl, { method: 'POST', dataType: 'json', contentType: 'json', data: ackBody, headers: { 'Content-Type': 'application/json' }, timeout: CALLBACK_TIMEOUT_MS, }); ctx.logger.info( `[inbox processor] API 回执完成 ext_id=${extId} ` + `http_status=${response.status}` ); } catch (error) { ctx.logger.error( `[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, '已在绑定状态,无需重复操作'); 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, '绑群码无效或已过期,请重新生成'); 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}」成功`); // 绑定成功后自动查询面单余额 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); } 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 {string} replyContent 回复内容。 * @return {Promise} */ async writeOutboundReply(data, replyContent) { 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 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 || !userId || !groupName || !userName) { throw new Error( `回执缺少必填字段: group_id=${groupId || '?'}, user_id=${userId || '?'}, ` + `group_name=${groupName || '?'}, user_name=${userName || '?'}` ); } try { const ackExtId = `sys:ack:${extId}`; const existAck = await InboxMessage.findOne({ where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false, }); if (!existAck) { await InboxMessage.create({ ext_id: ackExtId, warehouse_id: warehouseId, 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: userId, group_name: groupName, user_name: userName, content: replyContent, ext_data: data.ext_data || null, flags: {}, }); } const callbackUrl = await this.getApiAppCallbackUrl(warehouseId); if (callbackUrl) { const curlResult = await ctx.curl(callbackUrl, { method: 'POST', dataType: 'json', contentType: 'json', data: { content: replyContent, ext_data: data.ext_data || null, ext_id: extId, group_id: groupId, user_id: userId, group_name: groupName, user_name: userName, }, headers: { 'Content-Type': 'application/json' }, timeout: 10000, }); // HTTP 200 → 更新回执消息推送状态为已送达 if (curlResult && curlResult.status === 200) { await InboxMessage.update( { push_status: 2, push_response: { http_status: curlResult.status, body: curlResult.data || null }, pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { where: { ext_id: ackExtId } } ); // 同步更新原入站消息的推送状态 if (parentId) { await InboxMessage.update( { push_status: 2, pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'), }, { where: { id: parentId } } ); } } } } catch (error) { ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`); } } /** * 检查当前消息的群/用户是否在屏蔽列表中。 * * @return {Promise} 是否已屏蔽。 */ async isBlocked() { const { ctx } = this; const app = ctx.app; const groupName = String(ctx.inboxContext?.group_name || '').trim(); const userName = String(ctx.inboxContext?.user_name || '').trim(); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); if (!groupName && !userName) 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_name', 'user_name' ], raw: true }); blockedSet = new Set(); for (const row of rows) { const g = String(row.group_name || '').trim(); const u = String(row.user_name || '').trim(); if (g && u) blockedSet.add(`${g}:${u}`); if (g) blockedSet.add(`${g}:*`); if (u) blockedSet.add(`*:${u}`); } // TTL 5 分钟 await app.setCacheAsync(cacheKey, blockedSet, 300); } // 3. 检查当前消息是否命中屏蔽规则 if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true; if (groupName && blockedSet.has(`${groupName}:*`)) return true; if (userName && blockedSet.has(`*:${userName}`)) 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 回调地址。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 回调 URL,未配置时返回 null。 */ async getApiAppCallbackUrl(warehouseId) { const { ctx } = this; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { return null; } try { const apiApp = await ctx.model.ApiApp.findOne({ attributes: [ 'callback_url' ], where: { warehouse_id: warehouseId, interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, is_enabled: 1, }, raw: true, }); return (apiApp && apiApp.callback_url) || null; } catch (error) { ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`); return null; } } /** * 尝试从消息正文中提取仓库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;