WMS_MAIN/app/service/systems/warehouseNotify.js
liufumingren 7ad08e488d feat(notice): 统一通知仓库接口通道与订单同步通知去抖
- warehouseNotify: 按固定群订阅经 wms_api_app 回调推送(MD5 验签),消息表登记+失败重试
- notice: 货主群缺失时降级发仓库异常群(前缀标记失败),合约停用/已解除货主不发货主群也不降级
- order_async: 订单同步通知 3 分钟去抖合并,Redis 队列+定时冲刷+失败重试
- receiving: 收货完成/驳回/审核通知走仓库通道,仓库/货主侧文案分离
- storage/inventory: 移除移库完成群通知(事件码保留,库存余量提醒仍复用)
- 新增 debug:warehouse:push-receiver 调试接收服务与文档/变更记录
2026-08-17 02:03:34 +08:00

343 lines
11 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 }。
* @param {string} [options.content=''] 通知正文。
* @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。
* @return {Promise<Object>} 推送结果(含 messageId)。
*/
async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = 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)}`);
const uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`;
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: 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,
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;