WMS_MAIN/app/service/systems/warehouseNotify.js

353 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'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<void>}
*/
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<Object>} 推送结果。
*/
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 / timestamp。
* 推送前写入 wms_inbox_message(direction=outbound,source_type=system),
* 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。
* @param {Object} options 推送参数。
* @param {number} options.warehouseId 仓库 ID。
* @param {number} [options.storeId] 货主 ID。
* @param {Object} options.group 目标群 { group_id, group_name, ext_data }。
* @param {string} [options.content=''] 通知正文。
* @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。
* @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。
* @return {Promise<Object>} 推送结果(含 messageId)。
*/
async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null, extData = null } = {}) {
const { ctx } = this;
const groupId = String((group && group.group_id) || '').trim();
const groupName = String((group && group.group_name) || '').trim();
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)}`);
let uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`;
if (uniqueExtId.length > 128) {
const crypto = require('crypto');
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,
user_id: null,
group_name: groupName,
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);
}
}
const result = await this.push({
warehouseId,
method: 'notify.reply',
data: {
type: 'system',
content: normalizedContent,
ext_id: sourceExtId,
ext_data: extData || null,
group_id: groupId,
group_name: groupName,
timestamp: Math.floor(Date.now() / 1000),
},
});
// 回写推送状态(失败仅记日志,不影响业务)
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;