'use strict'; const { Service } = require('egg'); const crypto = require('crypto'); const { normalizeExtDataSource } = require('../../lib/inbox_channel'); /** 仓库接口类型 ID(interface_type_id=3) */ const WAREHOUSE_INTERFACE_TYPE_ID = 3; /** 请求超时(毫秒) */ const REQUEST_TIMEOUT_MS = 10000; /** 日志内容长度上限 */ const LOG_BODY_MAX = 65535; /** * 仓库接口消息推送服务(出站方向:WMS → 外部系统)。 * 复用仓库开放接口出站协议(MD5 签名 + ApiApp.callback_url), * 供统一通知服务与 inbox 回执复用同一套发送与日志链路。 */ class WarehouseNotifyService extends Service { /** * 截断日志内容到上限长度。 * @param {*} value 原始值。 * @return {string} 截断后的字符串。 */ truncateLogBody(value) { const str = typeof value === 'string' ? value : JSON.stringify(value || ''); if (str.length > LOG_BODY_MAX) { return str.substring(0, LOG_BODY_MAX); } return str; } /** * 获取仓库 ApiApp 回调配置(URL + 签名凭证)。 * 兼容旧调用:默认取承接 notify.reply 的首个应用。 * @param {number} warehouseId 仓库 ID。 * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。 */ async getCallbackConfig(warehouseId) { return await this.getCallbackConfigByMethod(warehouseId, 'notify.reply'); } /** * 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。 * @param {number} warehouseId 仓库 ID。 * @param {string} method 出站 method(如 notify.reply)。 * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。 */ async getCallbackConfigByMethod(warehouseId, method) { const list = await this.listCallbackConfigs(warehouseId, method); const first = list[0] || {}; return { url: first.url || null, appKey: first.appKey || null, appSecret: first.appSecret || null, }; } /** * 判断应用的 callback_functions 是否承接指定 method(兼容 JSON 字符串形式)。 * @param {*} callbackFunctions 应用承接的 method 列表(数组或 JSON 字符串)。 * @param {string} method 目标 method。 * @return {boolean} 是否承接。 */ containsCallbackMethod(callbackFunctions, method) { let list = callbackFunctions; if (typeof list === 'string') { try { list = JSON.parse(list); } catch (error) { list = null; } } if (!Array.isArray(list)) return false; const methodStr = String(method || '').trim(); return list.map(item => String(item || '').trim()).includes(methodStr); } /** * 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。 * callback_functions 为空/未勾选的应用不承接任何回调(不放行)。 * @param {number} warehouseId 仓库 ID。 * @param {string} method 出站 method。 * @return {Promise>} 候选列表。 */ async listCallbackConfigs(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, }); return rows .filter(row => this.containsCallbackMethod(row.callback_functions, method)) .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(`[warehouseNotify] 查询回调配置列表失败: ${error.message}`); return []; } } /** * 计算 MD5 签名:MD5(appSecret + timestamp + bodyJson)。 * @param {Object} options 签名参数。 * @param {string} options.appSecret 应用密钥。 * @param {number} options.timestamp Unix 秒时间戳。 * @param {string} options.bodyJson 请求体 JSON 字符串。 * @return {string} 签名 hex。 */ buildSignature({ appSecret, timestamp, bodyJson }) { return appSecret ? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex') : ''; } /** * 写入仓库接口日志(失败仅记日志不抛出)。 * @param {Object} options 日志参数。 * @param {string} [options.appKey] API 应用 AppKey。 * @param {string} [options.method] 请求方法名。 * @param {number} [options.warehouseId] 仓库 ID。 * @param {string} [options.url] 请求 URL。 * @param {number} [options.httpStatus] HTTP 状态码。 * @param {*} [options.body] 请求体。 * @param {*} [options.result] 响应体。 * @param {number} [options.useTime] 耗时(毫秒)。 * @return {Promise} */ async writeLog({ appKey, method, warehouseId, url, httpStatus, body, result, useTime, } = {}) { const { ctx } = this; const logModel = ctx.model && ctx.model.WarehouseLog; if (!logModel || typeof logModel.create !== 'function') { return; } try { await logModel.create({ log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'), app_key: appKey || null, method, warehouse_id: warehouseId || null, url: url || null, http_status: httpStatus || null, body: this.truncateLogBody(body), result: this.truncateLogBody(result), use_time: useTime || null, created_at: new Date(), }); } catch (logErr) { ctx.logger.error('[warehouseNotify] 日志写入失败: ' + logErr.message); } } /** * 单次回调推送尝试(复用 MD5 签名 + POST 协议,成功/失败均写日志)。 * @param {Object} options 尝试参数。 * @param {Object} options.config 候选应用 { appId, url, appKey, appSecret }。 * @param {number} options.warehouseId 仓库 ID。 * @param {string} options.method 出站 method。 * @param {Object} options.body 请求体。 * @return {Promise} 单次结果 { success, appId, httpStatus, response, error }。 */ async pushOnce({ config, warehouseId, method, body }) { const { ctx } = this; const bodyJson = JSON.stringify(body); const timestamp = Math.floor(Date.now() / 1000); const sign = this.buildSignature({ appSecret: config.appSecret, timestamp, bodyJson, }); const queryString = [ `app_key=${encodeURIComponent(config.appKey || '')}`, `method=${encodeURIComponent(method)}`, `timestamp=${timestamp}`, `sign=${encodeURIComponent(sign)}`, ].join('&'); const separator = config.url.includes('?') ? '&' : '?'; const url = `${config.url}${separator}${queryString}`; const startTime = Date.now(); try { const curlResult = await ctx.curl(url, { method: 'POST', dataType: 'json', contentType: 'json', data: body, headers: { 'Content-Type': 'application/json' }, timeout: REQUEST_TIMEOUT_MS, }); // HTTP 200 且 body.code=200(或未返回 code)→ 推送成功 const pushOk = curlResult && curlResult.status === 200 && (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200); await this.writeLog({ appKey: config.appKey, method, warehouseId, url, httpStatus: curlResult ? curlResult.status : null, body: bodyJson, result: curlResult ? curlResult.data || {} : {}, useTime: Date.now() - startTime, }); return { success: pushOk, appId: config.appId, httpStatus: curlResult ? curlResult.status : null, response: curlResult ? (curlResult.data || null) : null, error: pushOk ? null : '回调返回非200或code非200', }; } catch (error) { await this.writeLog({ appKey: config.appKey, method, warehouseId, url, httpStatus: null, body: bodyJson, result: 'Error: ' + error.message, useTime: Date.now() - startTime, }); return { success: false, appId: config.appId, httpStatus: null, response: null, error: error.message, }; } } /** * 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。 * 路由规则:查承接该 method 的全部候选应用(按 id 升序)逐个尝试, * 第一个成功即返回;全部失败返回失败且不改动任何接口配置。 * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {string} [options.method='notify.reply'] 出站 method。 * @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。 * @return {Promise} 推送结果(含 attempts 明细)。 */ async push({ warehouseId, method = 'notify.reply', data = {} } = {}) { const { ctx } = this; const methodStr = String(method || '').trim() || 'notify.reply'; const candidates = await this.listCallbackConfigs(warehouseId, methodStr); if (candidates.length === 0) { ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 无应用承接回调 method=${methodStr},跳过推送`); return { success: false, skipped: true, reason: '无应用承接该回调 method(callback_functions 未勾选或应用未启用)', warehouseId, method: methodStr, attempts: [], }; } const body = { code: 200, data }; const attempts = []; for (const config of candidates) { const attempt = await this.pushOnce({ config, warehouseId, method: methodStr, body }); attempts.push(attempt); if (attempt.success) { return { success: true, skipped: false, warehouseId, method: methodStr, appId: config.appId, httpStatus: attempt.httpStatus, response: attempt.response, attempts, }; } } ctx.logger.warn(`[warehouseNotify] 仓库 ${warehouseId} method=${methodStr} 全部 ${candidates.length} 个候选应用尝试失败`); return { success: false, skipped: false, warehouseId, method: methodStr, attempts, error: `全部 ${candidates.length} 个回调应用尝试失败`, }; } /** * 向指定群(可选)与成员(可选)推送系统级业务通知(复用 notify.reply,type=system)。 * 对方接口只处理 content 内容,推送体仅保留协议必需字段: * type / content / ext_id / group_id / group_name / user_id / timestamp。 * 推送前写入 wms_inbox_message(direction=outbound,source_type=system), * 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。 * 幂等去重:同 ext_id 的消息已送达(push_status=2)时直接跳过推送, * 避免定时任务宽限窗口重复执行/多实例并发导致同一群重复收到相同通知; * 未送达(0/1/3)时复用同一消息记录重推。 * * 向后兼容:不传 userIds 且传入 group 时,行为与旧版本完全一致 * (校验、幂等 ext_id、落库字段、推送体均不变)。 * * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {number} [options.storeId] 货主 ID。 * @param {Object|null} [options.group=null] 目标群 { group_id, group_name, ext_data } * (新增允许为 null:仅成员推送场景)。 * @param {Array|null} [options.userIds=null] 目标成员外部 IM 用户 ID 数组 * (新增,目标侧协议支持 user_id 数组:整体透传不循环拆发)。 * @param {string} [options.content=''] 通知正文。 * @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。 * @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。 * @return {Promise} 推送结果(含 messageId)。 */ async pushSystemMessage({ warehouseId, storeId = null, group = null, userIds = null, content = '', extId = null, extData = null, } = {}) { const { ctx } = this; const groupId = String((group && group.group_id) || '').trim(); const groupName = String((group && group.group_name) || '').trim(); // 按群ID格式校正渠道来源(@chatroom→wx / 纯数字→qiwe),避免通知投递到错误渠道 const normalizedExtData = normalizeExtDataSource(groupId, extData); // 成员ID规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组) const normalizedUserIds = Array.isArray(userIds) ? [ ...new Set(userIds.map(item => String(item || '').trim()).filter(Boolean)) ] : []; // 向后兼容:无群且无成员时保持旧版 skip 语义(原判断 !groupId || !groupName) if (!groupId && normalizedUserIds.length === 0) { return { success: false, skipped: true, reason: '目标群缺少 group_id 或 group_name', warehouseId, }; } // 指定了群但缺群名:与旧版一致返回 skip(群维度协议要求 group_name) if (groupId && !groupName) { return { success: false, skipped: true, reason: '目标群缺少 group_id 或 group_name', warehouseId, }; } // 幂等 ext_id:业务单号 + 事件 + 目标维度(群优先、仅成员时按成员集合), // 网络重推时复用同一条消息记录;超长时降级哈希兜底 const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`); const memberKey = normalizedUserIds.length > 0 ? `members:${normalizedUserIds.join(',')}` : ''; const targetKey = groupId || memberKey; let uniqueExtId = `sys:notice:${sourceExtId}:${targetKey}`; if (uniqueExtId.length > 128) { const digest = crypto.createHash('md5') .update(uniqueExtId) .digest('hex') .slice(0, 12); uniqueExtId = `sys:notice:${sourceExtId.slice(0, 100)}:${digest}`; } const InboxMessage = ctx.model && ctx.model.InboxMessage; const normalizedContent = String(content || '').trim() || '系统通知'; let messageId = null; if (InboxMessage) { try { const existing = await InboxMessage.findOne({ where: { ext_id: uniqueExtId }, attributes: [ 'id', 'push_status' ], paranoid: false, }); if (existing) { messageId = Number(existing.id); // 幂等去重:同 ext_id 消息已送达(push_status=2)时跳过推送, // 防止重复轮次/多实例并发导致同一群重复收到相同通知; // 未送达(0/1/3)时保留重推机会(复用同一消息记录回写推送结果) if (Number(existing.push_status) === 2) { return { success: true, skipped: true, reason: '消息已送达,跳过重复推送', warehouseId, method: 'notify.reply', messageId, }; } } else { const created = await InboxMessage.create({ ext_id: uniqueExtId, warehouse_id: Number(warehouseId || 0), store_id: Number(storeId || 0) > 0 ? Number(storeId) : null, direction: 'outbound', parent_id: null, source_type: 'system', source_extra: 'notice', target_type: 'api', group_id: groupId || null, // 成员数组仅随推送体 user_id 透传并记录在 report_delivery_log.notify_targets 快照中, // 消息表 user_id 列(STRING(100))不承载数组,避免超长截断 user_id: null, group_name: groupName || null, user_name: null, content: normalizedContent, ext_data: normalizedExtData, flags: {}, push_status: 1, push_started_at: new Date(), }); messageId = Number(created.id); } } catch (messageErr) { ctx.logger.warn('[warehouseNotify] 写消息表失败: ' + messageErr.message); } } // 推送体:群字段仅指定群时携带;成员 user_id 直接传数组(目标侧协议支持),不循环拆发 const pushData = { type: 'system', content: normalizedContent, ext_id: sourceExtId, ext_data: normalizedExtData, timestamp: Math.floor(Date.now() / 1000), }; if (groupId) { pushData.group_id = groupId; pushData.group_name = groupName; } if (normalizedUserIds.length > 0) { pushData.user_id = normalizedUserIds; } const result = await this.push({ warehouseId, method: 'notify.reply', data: pushData, }); // 回写推送状态(失败仅记日志,不影响业务) if (InboxMessage && messageId) { try { if (result.success) { await InboxMessage.update({ push_status: 2, push_response: { http_status: result.httpStatus, body: result.response || null, }, pushed_at: new Date(), }, { where: { id: messageId } }); } else { await InboxMessage.update({ push_status: 3, push_response: { http_status: result.httpStatus, body: result.response || null, error: result.error || result.reason || '推送失败', }, }, { where: { id: messageId } }); } } catch (updateErr) { ctx.logger.warn('[warehouseNotify] 回写推送状态失败: ' + updateErr.message); } } return { ...result, messageId }; } } module.exports = WarehouseNotifyService;