feat(apiApp): 出站回调按 method 路由(callback_functions 注册表 + 多候选逐个尝试推送)
This commit is contained in:
parent
8c27cd08ed
commit
cbd8d5bb78
26
app/lib/callback_functions.js
Normal file
26
app/lib/callback_functions.js
Normal file
@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 出站回调 method 注册表(代码注册,管理端多选列表经拉取接口透出)。
|
||||
*
|
||||
* method 即出站路由键:wms_api_app.callback_functions 勾选后,
|
||||
* 出站回调按 warehouse_id + method 自动路由到承接该 method 的应用;
|
||||
* callback_functions 为空/未勾选 = 不承接任何回调。
|
||||
*
|
||||
* 新增出站回调能力时在此登记 method,管理端接口自动可见。
|
||||
*/
|
||||
const CALLBACK_FUNCTIONS = [
|
||||
{
|
||||
method: 'notify.reply',
|
||||
name: '站内信通知回执',
|
||||
description: '站内信/系统通知/回执出站推送(warehouseNotify 与 inbox 回执共用)',
|
||||
},
|
||||
];
|
||||
|
||||
/** method 合法值集合(供管理端 create/update 校验) */
|
||||
const CALLBACK_METHOD_SET = new Set(CALLBACK_FUNCTIONS.map(item => item.method));
|
||||
|
||||
module.exports = {
|
||||
CALLBACK_FUNCTIONS,
|
||||
CALLBACK_METHOD_SET,
|
||||
};
|
||||
@ -70,6 +70,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: 'API回调通知URL',
|
||||
},
|
||||
callback_functions: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)',
|
||||
},
|
||||
qimen_app_key: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
|
||||
@ -527,7 +527,8 @@ class InboxProcessorService extends Service {
|
||||
}
|
||||
|
||||
const ackExtId = `sys:ack:${extId}`;
|
||||
const callbackConfig = await this.getApiAppCallbackConfig(warehouseId);
|
||||
// 多候选路由:按 method 查询全部承接应用(id 升序),逐个尝试直到成功
|
||||
const callbackConfigs = await this.listApiAppCallbackConfigs(warehouseId, 'notify.reply');
|
||||
// 重推(reuse_message_id>0):直接复用原记录,避免按 sys:ack: 前缀另建一条记录——
|
||||
// 那样会让原记录(如 sys:notice:* 系统通知)状态永远停留在失败/待推送,且每次重推都新建记录
|
||||
// 声明在 try 之外:异常兜底回写失败状态时仍需定位到该记录
|
||||
@ -578,9 +579,8 @@ class InboxProcessorService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
const callbackUrl = callbackConfig.url;
|
||||
if (callbackUrl) {
|
||||
const crypto = require('crypto');
|
||||
const hasCallbackConfigs = callbackConfigs.length > 0;
|
||||
if (hasCallbackConfigs) {
|
||||
const method = 'notify.reply';
|
||||
const notifyBody = {
|
||||
code: 200,
|
||||
@ -600,92 +600,53 @@ class InboxProcessorService extends Service {
|
||||
},
|
||||
};
|
||||
|
||||
const bodyJson = JSON.stringify(notifyBody);
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const appKey = callbackConfig.appKey || '';
|
||||
const appSecret = callbackConfig.appSecret || '';
|
||||
|
||||
// MD5 签名:MD5(appSecret + timestamp + bodyJson)
|
||||
const sign = appSecret
|
||||
? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex')
|
||||
: '';
|
||||
|
||||
const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
|
||||
|
||||
const curlResult = await ctx.curl(urlWithSign, {
|
||||
method: 'POST', dataType: 'json', contentType: 'json',
|
||||
data: notifyBody,
|
||||
headers: { 'Content-Type': 'application/json' }, timeout: 10000,
|
||||
});
|
||||
|
||||
// HTTP 200 且 body.code=200 → 推送成功
|
||||
const pushOk = curlResult && curlResult.status === 200
|
||||
&& (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200);
|
||||
|
||||
// 记录出站通知日志到 wms_warehouse_log
|
||||
try {
|
||||
const { WarehouseLog } = ctx.model;
|
||||
await WarehouseLog.create({
|
||||
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
|
||||
app_key: appKey || null,
|
||||
method,
|
||||
warehouse_id: warehouseId || null,
|
||||
url: urlWithSign || null,
|
||||
http_status: curlResult ? curlResult.status : null,
|
||||
body: JSON.stringify(notifyBody).substring(0, 65535),
|
||||
result: curlResult ? JSON.stringify(curlResult.data || {}).substring(0, 65535) : '',
|
||||
use_time: Date.now() - timestamp * 1000,
|
||||
created_at: new Date(),
|
||||
});
|
||||
} catch (logErr) {
|
||||
ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message);
|
||||
}
|
||||
|
||||
if (pushOk) {
|
||||
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: { id: outboundId } }
|
||||
);
|
||||
|
||||
// 同步更新原入站消息的推送状态
|
||||
if (parentId) {
|
||||
// 逐个候选尝试:第一个成功即止;全部失败回写失败状态且不改动接口配置
|
||||
for (const callbackConfig of callbackConfigs) {
|
||||
const attempt = await this.pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody });
|
||||
if (attempt.pushOk) {
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: 2,
|
||||
push_response: { http_status: attempt.httpStatus, body: attempt.response || null },
|
||||
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
{ where: { id: parentId } }
|
||||
{ where: { id: outboundId } }
|
||||
);
|
||||
|
||||
// 同步更新原入站消息的推送状态
|
||||
if (parentId) {
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: 2,
|
||||
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
{ where: { id: parentId } }
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// 推送失败:回写状态和原因
|
||||
// 全部候选尝试失败:回写状态和原因
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: 3,
|
||||
push_response: {
|
||||
http_status: curlResult ? curlResult.status : null,
|
||||
body: curlResult ? (curlResult.data || null) : null,
|
||||
error: curlResult ? '回调返回非200或code非200' : '回调无响应',
|
||||
error: `全部 ${callbackConfigs.length} 个回调应用尝试失败`,
|
||||
},
|
||||
},
|
||||
{ where: { id: outboundId } }
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// 未配置回调地址:回写状态
|
||||
// 无应用承接该回调:回写状态
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: 3,
|
||||
push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' },
|
||||
push_response: { error: '无应用承接该回调(callback_functions 未勾选或应用未启用)' },
|
||||
},
|
||||
{ where: { id: outboundId } }
|
||||
);
|
||||
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`);
|
||||
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 无应用承接回调 notify.reply,回写失败状态 ext_id=${extId}`);
|
||||
return false;
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`);
|
||||
@ -859,38 +820,162 @@ class InboxProcessorService extends Service {
|
||||
|
||||
/**
|
||||
* 获取仓库 ApiApp 回调配置(URL + 签名凭证)。
|
||||
* 兼容旧调用:默认取承接 notify.reply 的首个应用。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。
|
||||
*/
|
||||
async getApiAppCallbackConfig(warehouseId) {
|
||||
return await this.getApiAppCallbackConfigByMethod(warehouseId, 'notify.reply');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 method 获取仓库 ApiApp 回调配置(取候选列表中首个应用)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} method 出站 method。
|
||||
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。
|
||||
*/
|
||||
async getApiAppCallbackConfigByMethod(warehouseId, method) {
|
||||
const list = await this.listApiAppCallbackConfigs(warehouseId, method);
|
||||
const first = list[0] || {};
|
||||
return {
|
||||
url: first.url || null,
|
||||
appKey: first.appKey || null,
|
||||
appSecret: first.appSecret || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询仓库下承接指定 method 的全部回调候选应用(按 id 升序)。
|
||||
* callback_functions 为空/未勾选的应用不承接任何回调(不放行)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @param {string} method 出站 method。
|
||||
* @return {Promise<Array<{appId: number, url: string|null, appKey: string|null, appSecret: string|null}>>} 候选列表。
|
||||
*/
|
||||
async listApiAppCallbackConfigs(warehouseId, method) {
|
||||
const { ctx } = this;
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
return { url: null, appKey: null, appSecret: null };
|
||||
return [];
|
||||
}
|
||||
|
||||
const apiAppModel = ctx.model && ctx.model.ApiApp;
|
||||
if (!apiAppModel || typeof apiAppModel.findAll !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const apiApp = await ctx.model.ApiApp.findOne({
|
||||
attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ],
|
||||
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 {
|
||||
url: (apiApp && apiApp.callback_url) || null,
|
||||
appKey: (apiApp && apiApp.self_app_key) || null,
|
||||
appSecret: (apiApp && apiApp.self_app_secret) || null,
|
||||
};
|
||||
const methodStr = String(method || '').trim();
|
||||
return rows
|
||||
.filter(row => {
|
||||
let list = row.callback_functions;
|
||||
if (typeof list === 'string') {
|
||||
try {
|
||||
list = JSON.parse(list);
|
||||
} catch (error) {
|
||||
list = null;
|
||||
}
|
||||
}
|
||||
return Array.isArray(list)
|
||||
&& list.map(item => String(item || '').trim()).includes(methodStr);
|
||||
})
|
||||
.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(`[inbox processor] 查询回调配置失败: ${error.message}`);
|
||||
return { url: null, appKey: null, appSecret: null };
|
||||
ctx.logger.warn(`[inbox processor] 查询回调配置列表失败: ${error.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 单次回执推送尝试(回执专用协议:MD5(appSecret+timestamp+bodyJson) + POST)。
|
||||
* 每次尝试均写 wms_warehouse_log,失败不改动接口配置。
|
||||
*
|
||||
* @param {Object} options 尝试参数。
|
||||
* @param {Object} options.callbackConfig 候选应用 { appId, url, appKey, appSecret }。
|
||||
* @param {number} options.warehouseId 仓库ID。
|
||||
* @param {string} options.method 出站 method。
|
||||
* @param {Object} options.notifyBody 推送体(已组装)。
|
||||
* @return {Promise<Object>} { pushOk, httpStatus, response, error }。
|
||||
*/
|
||||
async pushReplyOnce({ callbackConfig, warehouseId, method, notifyBody }) {
|
||||
const { ctx } = this;
|
||||
const crypto = require('crypto');
|
||||
const callbackUrl = callbackConfig.url;
|
||||
const bodyJson = JSON.stringify(notifyBody);
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const appKey = callbackConfig.appKey || '';
|
||||
const appSecret = callbackConfig.appSecret || '';
|
||||
|
||||
// MD5 签名:MD5(appSecret + timestamp + bodyJson)
|
||||
const sign = appSecret
|
||||
? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex')
|
||||
: '';
|
||||
|
||||
const urlWithSign = `${callbackUrl}?app_key=${encodeURIComponent(appKey)}&method=${encodeURIComponent(method)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
|
||||
const startTime = Date.now();
|
||||
|
||||
let curlResult = null;
|
||||
let error = null;
|
||||
try {
|
||||
curlResult = await ctx.curl(urlWithSign, {
|
||||
method: 'POST', dataType: 'json', contentType: 'json',
|
||||
data: notifyBody,
|
||||
headers: { 'Content-Type': 'application/json' }, timeout: 10000,
|
||||
});
|
||||
} catch (curlError) {
|
||||
error = curlError;
|
||||
}
|
||||
|
||||
// HTTP 200 且 body.code=200 → 推送成功
|
||||
const pushOk = !!curlResult && curlResult.status === 200
|
||||
&& (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200);
|
||||
|
||||
// 记录出站通知日志到 wms_warehouse_log(每次尝试均记录)
|
||||
try {
|
||||
const { WarehouseLog } = ctx.model;
|
||||
await WarehouseLog.create({
|
||||
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
|
||||
app_key: appKey || null,
|
||||
method,
|
||||
warehouse_id: warehouseId || null,
|
||||
url: urlWithSign || null,
|
||||
http_status: curlResult ? curlResult.status : null,
|
||||
body: bodyJson.substring(0, 65535),
|
||||
result: curlResult
|
||||
? JSON.stringify(curlResult.data || {}).substring(0, 65535)
|
||||
: 'Error: ' + (error ? error.message : ''),
|
||||
use_time: Date.now() - startTime,
|
||||
created_at: new Date(),
|
||||
});
|
||||
} catch (logErr) {
|
||||
ctx.logger.error('[notify-log] 日志写入失败: ' + logErr.message);
|
||||
}
|
||||
|
||||
return {
|
||||
pushOk,
|
||||
httpStatus: curlResult ? curlResult.status : null,
|
||||
response: curlResult ? (curlResult.data || null) : null,
|
||||
error: error ? error.message : (pushOk ? null : '回调返回非200或code非200'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库 ApiApp 回调地址(兼容旧调用)。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
|
||||
@ -45,7 +45,7 @@ class ApiAppService extends MainService {
|
||||
const record = await ctx.model.ApiApp.findOne({
|
||||
attributes: [
|
||||
'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret',
|
||||
'self_ip_whitelist', 'callback_url', 'interface_type_id',
|
||||
'self_ip_whitelist', 'callback_url', 'callback_functions', 'interface_type_id',
|
||||
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
|
||||
],
|
||||
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: defaultTypeId },
|
||||
@ -112,6 +112,17 @@ class ApiAppService extends MainService {
|
||||
return this.success('重新生成成功', result);
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取出站回调 method 注册表(管理端多选列表)。
|
||||
* @return {Promise<Object>} { list: [{method,name,description}], total }。
|
||||
*/
|
||||
async listCallbackFunctions() {
|
||||
try {
|
||||
const result = this.service.systems.apiApp.listCallbackFunctions();
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) { return this.fail(e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ApiAppService;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
const { randomBytes } = require('node:crypto');
|
||||
const { Service } = require('egg');
|
||||
const { CALLBACK_FUNCTIONS, CALLBACK_METHOD_SET } = require('../../lib/callback_functions');
|
||||
|
||||
class ApiAppService extends Service {
|
||||
/**
|
||||
@ -75,7 +76,7 @@ class ApiAppService extends Service {
|
||||
const list = await ctx.model.ApiApp.findAll({
|
||||
attributes: [
|
||||
'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret',
|
||||
'self_ip_whitelist', 'callback_url', 'interface_type_id',
|
||||
'self_ip_whitelist', 'callback_url', 'callback_functions', 'interface_type_id',
|
||||
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
|
||||
],
|
||||
where,
|
||||
@ -148,6 +149,7 @@ class ApiAppService extends Service {
|
||||
self_app_secret: appSecret,
|
||||
self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null,
|
||||
callback_url: String(data.callback_url || '').trim() || null,
|
||||
callback_functions: this.normalizeCallbackFunctions(data.callback_functions),
|
||||
rate_limit: Number(data.rate_limit) || 1000,
|
||||
sign_method: 'md5',
|
||||
is_enabled: 1,
|
||||
@ -171,6 +173,7 @@ class ApiAppService extends Service {
|
||||
self_app_secret: record.self_app_secret,
|
||||
self_ip_whitelist: record.self_ip_whitelist,
|
||||
callback_url: record.callback_url,
|
||||
callback_functions: record.callback_functions,
|
||||
rate_limit: record.rate_limit,
|
||||
sign_method: record.sign_method,
|
||||
is_enabled: record.is_enabled,
|
||||
@ -179,6 +182,34 @@ class ApiAppService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并规范化 callback_functions:
|
||||
* 仅允许代码注册表中的 method,去重去空;
|
||||
* 非数组入参视为 null(不承接任何回调)。
|
||||
* @param {*} value 入参值。
|
||||
* @return {Array<string>|null} 规范化后的 method 数组(可为空数组)。
|
||||
*/
|
||||
normalizeCallbackFunctions(value) {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const functions = [ ...new Set(value.map(item => String(item || '').trim()).filter(Boolean)) ];
|
||||
const invalid = functions.filter(method => !CALLBACK_METHOD_SET.has(method));
|
||||
if (invalid.length > 0) {
|
||||
throw new Error(`存在未注册的回调方法: ${invalid.join(', ')}`);
|
||||
}
|
||||
return functions;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取出站回调 method 注册表(管理端多选列表)。
|
||||
* @return {Object} { list: [{method,name,description}], total }。
|
||||
*/
|
||||
listCallbackFunctions() {
|
||||
return {
|
||||
list: CALLBACK_FUNCTIONS.map(item => ({ ...item })),
|
||||
total: CALLBACK_FUNCTIONS.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新仓库 API 应用。
|
||||
* @param {number|string} id 应用 ID。
|
||||
@ -203,11 +234,13 @@ class ApiAppService extends Service {
|
||||
throw new Error('API应用不存在或不属于当前仓库');
|
||||
}
|
||||
|
||||
const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'rate_limit', 'sign_method', 'is_enabled' ];
|
||||
const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'callback_functions', 'rate_limit', 'sign_method', 'is_enabled' ];
|
||||
for (const field of updatableFields) {
|
||||
if (data[field] !== undefined && data[field] !== null) {
|
||||
if (field === 'sign_method') {
|
||||
throw new Error('签名方法当前仅支持 md5,不允许修改');
|
||||
} else if (field === 'callback_functions') {
|
||||
record[field] = this.normalizeCallbackFunctions(data[field]);
|
||||
} else if (field === 'is_enabled') {
|
||||
record[field] = Number(data[field]);
|
||||
} else if (field === 'rate_limit') {
|
||||
@ -242,6 +275,7 @@ class ApiAppService extends Service {
|
||||
: '',
|
||||
self_ip_whitelist: record.self_ip_whitelist,
|
||||
callback_url: record.callback_url,
|
||||
callback_functions: record.callback_functions,
|
||||
rate_limit: record.rate_limit,
|
||||
sign_method: record.sign_method,
|
||||
is_enabled: record.is_enabled,
|
||||
|
||||
@ -32,34 +32,91 @@ class WarehouseNotifyService extends Service {
|
||||
|
||||
/**
|
||||
* 获取仓库 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<Array<{appId: number, url: string|null, appKey: string|null, appSecret: string|null}>>} 候选列表。
|
||||
*/
|
||||
async listCallbackConfigs(warehouseId, method) {
|
||||
const { ctx } = this;
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
return { url: null, appKey: null, appSecret: null };
|
||||
return [];
|
||||
}
|
||||
|
||||
const apiAppModel = ctx.model && ctx.model.ApiApp;
|
||||
if (!apiAppModel || typeof apiAppModel.findAll !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const apiApp = await ctx.model.ApiApp.findOne({
|
||||
attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ],
|
||||
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 {
|
||||
url: (apiApp && apiApp.callback_url) || null,
|
||||
appKey: (apiApp && apiApp.self_app_key) || null,
|
||||
appSecret: (apiApp && apiApp.self_app_secret) || null,
|
||||
};
|
||||
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 { url: null, appKey: null, appSecret: null };
|
||||
ctx.logger.warn(`[warehouseNotify] 查询回调配置列表失败: ${error.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@ -125,29 +182,16 @@ class WarehouseNotifyService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。
|
||||
* @param {Object} options 推送参数。
|
||||
* 单次回调推送尝试(复用 MD5 签名 + POST 协议,成功/失败均写日志)。
|
||||
* @param {Object} options 尝试参数。
|
||||
* @param {Object} options.config 候选应用 { appId, url, appKey, appSecret }。
|
||||
* @param {number} options.warehouseId 仓库 ID。
|
||||
* @param {string} [options.method='notify.reply'] 出站 method。
|
||||
* @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。
|
||||
* @return {Promise<Object>} 推送结果。
|
||||
* @param {string} options.method 出站 method。
|
||||
* @param {Object} options.body 请求体。
|
||||
* @return {Promise<Object>} 单次结果 { success, appId, httpStatus, response, error }。
|
||||
*/
|
||||
async push({ warehouseId, method = 'notify.reply', data = {} } = {}) {
|
||||
async pushOnce({ config, warehouseId, method, body }) {
|
||||
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({
|
||||
@ -193,9 +237,7 @@ class WarehouseNotifyService extends Service {
|
||||
|
||||
return {
|
||||
success: pushOk,
|
||||
skipped: false,
|
||||
warehouseId,
|
||||
method,
|
||||
appId: config.appId,
|
||||
httpStatus: curlResult ? curlResult.status : null,
|
||||
response: curlResult ? (curlResult.data || null) : null,
|
||||
error: pushOk ? null : '回调返回非200或code非200',
|
||||
@ -214,9 +256,7 @@ class WarehouseNotifyService extends Service {
|
||||
|
||||
return {
|
||||
success: false,
|
||||
skipped: false,
|
||||
warehouseId,
|
||||
method,
|
||||
appId: config.appId,
|
||||
httpStatus: null,
|
||||
response: null,
|
||||
error: error.message,
|
||||
@ -224,6 +264,63 @@ class WarehouseNotifyService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向仓库 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<Object>} 推送结果(含 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 内容,推送体仅保留协议必需字段:
|
||||
|
||||
@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_api_app 新增 callback_functions 字段(出站回调 method 路由)。
|
||||
*
|
||||
* 语义:应用承接的出站回调 method 列表(JSON 数组)。
|
||||
* 为空/未勾选 = 不承接任何回调;出站回调按 warehouse_id + method 自动路由到
|
||||
* 勾选了该 method 的应用,多个应用按 id 升序逐个尝试,全部失败不改配置。
|
||||
*
|
||||
* A 方案存量回填:仓库接口类型(OPEN_API_WAREHOUSE)下启用的应用
|
||||
* 默认承接 notify.reply,升级后站内信推送不受影响。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { sequelize } = queryInterface;
|
||||
|
||||
// 幂等:列已存在则跳过
|
||||
const [ columns ] = await sequelize.query(
|
||||
"SHOW COLUMNS FROM `wms_api_app` LIKE 'callback_functions'"
|
||||
);
|
||||
if (columns.length === 0) {
|
||||
await queryInterface.addColumn('wms_api_app', 'callback_functions', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)',
|
||||
});
|
||||
}
|
||||
|
||||
// 存量回填:按 interface_code 查仓库接口类型 ID(避免硬编码数字漂移)
|
||||
const [ interfaceRows ] = await sequelize.query(
|
||||
"SELECT id FROM wms_interface_type WHERE interface_code = 'OPEN_API_WAREHOUSE' LIMIT 1"
|
||||
);
|
||||
const interfaceTypeId = interfaceRows && interfaceRows.length
|
||||
? Number(interfaceRows[0].id)
|
||||
: 3;
|
||||
|
||||
await sequelize.query(
|
||||
'UPDATE wms_api_app SET callback_functions = JSON_ARRAY(\'notify.reply\') ' +
|
||||
'WHERE interface_type_id = :interfaceTypeId AND is_enabled = 1 ' +
|
||||
'AND (callback_functions IS NULL OR JSON_LENGTH(callback_functions) = 0)',
|
||||
{ replacements: { interfaceTypeId } }
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const { sequelize } = queryInterface;
|
||||
|
||||
const [ columns ] = await sequelize.query(
|
||||
"SHOW COLUMNS FROM `wms_api_app` LIKE 'callback_functions'"
|
||||
);
|
||||
if (columns.length > 0) {
|
||||
await queryInterface.removeColumn('wms_api_app', 'callback_functions');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* apiApp.listCallbackFunctions(出站回调 method 注册表拉取)API 权限记录迁移。
|
||||
*
|
||||
* 权限明细(固定 ID 636,当前迁移内最大已用 ID=635):
|
||||
* 636 — apiApp.listCallbackFunctions API:出站回调方法注册表
|
||||
*
|
||||
* 角色授权:与同组 apiApp 权限(465-470)口径一致——该组权限仅对
|
||||
* permissions='*' 的通配角色(超管/经理/仓库管理员)开放,
|
||||
* 无任何非通配角色持有,因此本迁移仅插入权限记录,不做角色注入。
|
||||
*
|
||||
* 幂等:INSERT IGNORE 创建权限记录。
|
||||
*/
|
||||
|
||||
const TABLE = 'wms_permission';
|
||||
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
|
||||
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const apis = [
|
||||
[ 636, 'apiApp.listCallbackFunctions', 'API:出站回调方法注册表' ],
|
||||
];
|
||||
|
||||
for (const [ id, path, metaTitle ] of apis) {
|
||||
await queryInterface.sequelize.query(
|
||||
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] }
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM \`${TABLE}\` WHERE id = 636 AND path = 'apiApp.listCallbackFunctions'`
|
||||
);
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user