'use strict'; const { Service } = require('egg'); const crypto = require('crypto'); /** 仓库接口类型 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 + 签名凭证)。 * @param {number} warehouseId 仓库 ID。 * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。 */ async getCallbackConfig(warehouseId) { const { ctx } = this; if (!Number.isFinite(warehouseId) || warehouseId <= 0) { return { url: null, appKey: null, appSecret: null }; } try { const apiApp = await ctx.model.ApiApp.findOne({ attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ], where: { warehouse_id: warehouseId, interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID, is_enabled: 1, }, raw: true, }); return { url: (apiApp && apiApp.callback_url) || null, appKey: (apiApp && apiApp.self_app_key) || null, appSecret: (apiApp && apiApp.self_app_secret) || null, }; } catch (error) { ctx.logger.warn(`[warehouseNotify] 查询回调配置失败: ${error.message}`); return { url: null, appKey: null, appSecret: null }; } } /** * 计算 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); } } /** * 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。 * @param {Object} options 推送参数。 * @param {number} options.warehouseId 仓库 ID。 * @param {string} [options.method='notify.reply'] 出站 method。 * @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。 * @return {Promise} 推送结果。 */ async push({ warehouseId, method = 'notify.reply', data = {} } = {}) { const { ctx } = this; const config = await this.getCallbackConfig(warehouseId); if (!config.url) { ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 未配置回调地址,跳过推送 method=${method}`); return { success: false, skipped: true, reason: '未配置回调地址(wms_api_app.callback_url 为空)', warehouseId, method, }; } const body = { code: 200, data }; 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, skipped: false, warehouseId, method, 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, skipped: false, warehouseId, method, httpStatus: null, response: null, error: error.message, }; } } /** * 向指定群(可选)与成员(可选)推送系统级业务通知(复用 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。 * * 向后兼容:不传 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规范化:仅接受字符串数组,去重并过滤空值(向后兼容:旧调用不传时为空数组) 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' ], paranoid: false, }); if (existing) { messageId = Number(existing.id); } 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: extData || null, 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: extData || null, 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;