feat(inbox): 站内信模块完整实现 — 统一消息收件箱
This commit is contained in:
parent
b5b631f20d
commit
4374ad01e3
127
app/controller/inbox.js
Normal file
127
app/controller/inbox.js
Normal file
@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
/**
|
||||
* 站内信内部管理接口控制器。
|
||||
* 提供消息列表、详情、对话链、回信、重推、统计等管理功能。
|
||||
*/
|
||||
class InboxController extends Controller {
|
||||
/**
|
||||
* 获取当前仓库上下文。
|
||||
* @return {{ warehouseId: number }} 仓库上下文。
|
||||
*/
|
||||
getWarehouseContext() {
|
||||
const { ctx } = this;
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('缺少仓库信息');
|
||||
}
|
||||
|
||||
return { warehouseId };
|
||||
}
|
||||
|
||||
/**
|
||||
* 内部管理统一入口,分发到对应 service 方法。
|
||||
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const method = String(ctx.request.body && ctx.request.body.method || '').trim();
|
||||
if (!method || !method.startsWith('inbox.')) {
|
||||
ctx.status = 400;
|
||||
ctx.body = toFailure({ message: 'method 参数无效' });
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
const action = method.replace('inbox.', '');
|
||||
const data = (ctx.request.body && ctx.request.body.data) || {};
|
||||
|
||||
let result;
|
||||
|
||||
switch (action) {
|
||||
case 'list': {
|
||||
const { warehouseId } = this.getWarehouseContext();
|
||||
result = await ctx.service.inbox.index.list({
|
||||
warehouseId,
|
||||
...data,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'detail': {
|
||||
const { warehouseId } = this.getWarehouseContext();
|
||||
result = await ctx.service.inbox.index.detail({
|
||||
warehouseId,
|
||||
id: data.id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'thread': {
|
||||
const { warehouseId } = this.getWarehouseContext();
|
||||
result = await ctx.service.inbox.index.thread({
|
||||
warehouseId,
|
||||
id: data.id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'reply': {
|
||||
const { warehouseId } = this.getWarehouseContext();
|
||||
result = await ctx.service.inbox.index.reply({
|
||||
warehouseId,
|
||||
parentId: data.parentId,
|
||||
targetChannel: data.targetChannel,
|
||||
targetUrl: data.targetUrl,
|
||||
targetType: data.targetType,
|
||||
refCode: data.refCode,
|
||||
extData: data.extData,
|
||||
flags: data.flags,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'retry': {
|
||||
const { warehouseId } = this.getWarehouseContext();
|
||||
result = await ctx.service.inbox.index.retry({
|
||||
warehouseId,
|
||||
id: data.id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'stats': {
|
||||
const { warehouseId } = this.getWarehouseContext();
|
||||
result = await ctx.service.inbox.index.stats({
|
||||
warehouseId,
|
||||
direction: data.direction,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
ctx.status = 400;
|
||||
ctx.body = toFailure({ message: `不支持的 inbox 方法: ${action}` });
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.status = 200;
|
||||
ctx.body = toSuccess(result, 'ok');
|
||||
ctx.type = 'application/json';
|
||||
} catch (error) {
|
||||
const message = String(error && error.message || '请求失败');
|
||||
ctx.status = 500;
|
||||
ctx.body = toFailure({ message: `站内信错误: ${message}` });
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxController;
|
||||
190
app/model/inbox_message.js
Normal file
190
app/model/inbox_message.js
Normal file
@ -0,0 +1,190 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 站内信消息 Model。
|
||||
* 统一管理消息推送状态追踪:谁发来的、要推到哪、推送状态。
|
||||
* inbound(外部→WMS)与 outbound(WMS→外部)共表,direction + parent_id 形成对话链。
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE, INTEGER, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const InboxMessage = app.model.define('inbox_message', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
ext_id: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联货主ID',
|
||||
},
|
||||
direction: {
|
||||
type: STRING(10),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbound',
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 'inbound', 'outbound' ]],
|
||||
msg: 'direction 必须是 inbound 或 outbound',
|
||||
},
|
||||
},
|
||||
comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信',
|
||||
},
|
||||
parent_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联消息ID(回信时指向原消息,形成对话链)',
|
||||
},
|
||||
source_type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 'im', 'api', 'system' ]],
|
||||
msg: 'source_type 必须是 im、api 或 system',
|
||||
},
|
||||
},
|
||||
comment: '来源类型:im / api / system',
|
||||
},
|
||||
source_extra: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '来源附加信息(IM 平台 / API app_id)',
|
||||
},
|
||||
target_type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 'im', 'api', 'webhook' ]],
|
||||
msg: 'target_type 必须是 im、api 或 webhook',
|
||||
},
|
||||
},
|
||||
comment: '目标类型:im / api / webhook',
|
||||
},
|
||||
target_channel: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
notEmpty: {
|
||||
msg: 'target_channel 不能为空',
|
||||
},
|
||||
},
|
||||
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
|
||||
},
|
||||
target_url: {
|
||||
type: STRING(500),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
notEmpty: {
|
||||
msg: 'target_url 不能为空',
|
||||
},
|
||||
len: {
|
||||
args: [ 1, 500 ],
|
||||
msg: 'target_url 长度应在1-500个字符之间',
|
||||
},
|
||||
},
|
||||
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
|
||||
},
|
||||
ref_code: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部引用编码,推送/回执时原样携带',
|
||||
},
|
||||
ext_data: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回',
|
||||
},
|
||||
flags: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '处理标记,外部传入控制WMS处理行为',
|
||||
},
|
||||
push_status: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 0, 1, 2, 3 ]],
|
||||
msg: 'push_status 必须是 0(待推送)、1(推送中)、2(已送达)、3(失败)',
|
||||
},
|
||||
},
|
||||
comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败',
|
||||
},
|
||||
push_started_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)',
|
||||
},
|
||||
retry_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '已重试次数',
|
||||
},
|
||||
push_response: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: '目标响应(http_status, body, error)',
|
||||
},
|
||||
pushed_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '推送完成时间',
|
||||
},
|
||||
work_order_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联工单ID(预留)',
|
||||
},
|
||||
work_order_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '工单号(预留)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_inbox_message',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
deletedAt: 'deleted_at',
|
||||
paranoid: true,
|
||||
comment: '站内信消息推送状态追踪表',
|
||||
});
|
||||
|
||||
return InboxMessage;
|
||||
};
|
||||
@ -67,4 +67,7 @@ module.exports = app => {
|
||||
router.get('/testSendData', controller.home.testSendData);
|
||||
// IM交互入口
|
||||
router.post('/im', controller.im.index);
|
||||
|
||||
// 站内信内部管理接口
|
||||
router.post('/inbox', controller.inbox.index);
|
||||
};
|
||||
|
||||
118
app/service/inbox/dispatch/base.js
Normal file
118
app/service/inbox/dispatch/base.js
Normal file
@ -0,0 +1,118 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const apiSignLib = require('../../../lib/api_sign');
|
||||
|
||||
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||
const DISPATCH_TIMEOUT_MS = 10000; // 10s 超时
|
||||
|
||||
/**
|
||||
* 统一出站基类,所有渠道 dispatch 继承此类。
|
||||
* 统一处理:查密钥、签名、发 HTTP。
|
||||
* 子类只需实现 push(record) 方法,关注消息格式转换。
|
||||
*/
|
||||
class OutboundBase extends Service {
|
||||
/**
|
||||
* 获取仓库 ApiApp 密钥配置(IM 渠道无需签名,返回 null)。
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<Object|null>} ApiApp 配置对象,含 appKey / selfAppSecret / warehouseId。
|
||||
*/
|
||||
async getApiApp(warehouseId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
// 通过仓库ID查找该仓库的 warehouse 类型 ApiApp
|
||||
const apiApp = await ctx.model.ApiApp.findOne({
|
||||
attributes: [ 'id', 'self_app_key', 'self_app_secret', 'is_enabled', 'interface_type_id', 'warehouse_id' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
|
||||
is_enabled: 1,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!apiApp || !apiApp.self_app_secret) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
appKey: apiApp.self_app_key,
|
||||
selfAppSecret: apiApp.self_app_secret,
|
||||
warehouseId: Number(apiApp.warehouse_id),
|
||||
};
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox dispatch] 获取仓库 ApiApp 失败: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 MD5 签名,返回带签名后的完整 URL。
|
||||
* @param {string} url 原始目标URL。
|
||||
* @param {*} body 请求体。
|
||||
* @param {Object} secret ApiApp 密钥对象,含 appKey / selfAppSecret。
|
||||
* @return {string} 带签名的完整URL。
|
||||
*/
|
||||
signRequest(url, body, secret) {
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const query = {
|
||||
app_key: secret.appKey,
|
||||
timestamp,
|
||||
};
|
||||
|
||||
const { sign } = apiSignLib.signRequest({
|
||||
query,
|
||||
body,
|
||||
selfAppSecret: secret.selfAppSecret,
|
||||
});
|
||||
|
||||
const separator = url.includes('?') ? '&' : '?';
|
||||
return `${url}${separator}app_key=${encodeURIComponent(query.app_key)}×tamp=${timestamp}&sign=${encodeURIComponent(sign)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一 HTTP POST 发送。
|
||||
* @param {string} url 目标URL。
|
||||
* @param {*} body 请求体。
|
||||
* @param {Object} [options] 额外选项。
|
||||
* @param {Object} [options.headers] 自定义请求头。
|
||||
* @return {Promise<{status: number, data: *}>} 响应结果。
|
||||
*/
|
||||
async post(url, body, options = {}) {
|
||||
const { ctx } = this;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...(options.headers || {}),
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
contentType: 'json',
|
||||
data: body,
|
||||
headers,
|
||||
timeout: DISPATCH_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
return {
|
||||
status: response.status,
|
||||
data: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`HTTP 推送失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 子类必须实现的推送方法。
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例),子类按需使用。
|
||||
* @throws {Error} 子类未实现时抛出。
|
||||
*/
|
||||
async push(record) {
|
||||
const id = record && record.id;
|
||||
throw new Error(`子类必须实现 push(record) 方法,当前消息ID: ${id || '未知'}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OutboundBase;
|
||||
35
app/service/inbox/dispatch/dingtalk.js
Normal file
35
app/service/inbox/dispatch/dingtalk.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
const OutboundBase = require('./base');
|
||||
|
||||
/**
|
||||
* 钉钉 Bot 渠道出站实现。
|
||||
* 推送 Markdown 消息到钉钉机器人 webhook。
|
||||
*/
|
||||
class DingtalkDispatch extends OutboundBase {
|
||||
/**
|
||||
* 通过钉钉 Bot 推送消息。
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例)。
|
||||
* @return {Promise<{status: number, data: *}>} 推送响应。
|
||||
*/
|
||||
async push(record) {
|
||||
const { ctx } = this;
|
||||
|
||||
const extData = record.ext_data || {};
|
||||
const title = extData.title || '新消息通知';
|
||||
const text = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`;
|
||||
|
||||
const body = {
|
||||
msgtype: 'markdown',
|
||||
markdown: {
|
||||
title,
|
||||
text: typeof text === 'string' ? text : JSON.stringify(text),
|
||||
},
|
||||
};
|
||||
|
||||
ctx.logger.info(`[inbox dingtalk] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
|
||||
return await this.post(record.target_url, body);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DingtalkDispatch;
|
||||
60
app/service/inbox/dispatch/feishu.js
Normal file
60
app/service/inbox/dispatch/feishu.js
Normal file
@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
const OutboundBase = require('./base');
|
||||
|
||||
/**
|
||||
* 飞书 Bot 渠道出站实现。
|
||||
* 推送交互式卡片消息到飞书机器人 webhook。
|
||||
*/
|
||||
class FeishuDispatch extends OutboundBase {
|
||||
/**
|
||||
* 通过飞书 Bot 推送消息。
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例)。
|
||||
* @return {Promise<{status: number, data: *}>} 推送响应。
|
||||
*/
|
||||
async push(record) {
|
||||
const { ctx } = this;
|
||||
|
||||
const extData = record.ext_data || {};
|
||||
const title = extData.title || '新消息通知';
|
||||
const content = extData.content || extData.text || `消息:${record.ref_code || record.ext_id}`;
|
||||
|
||||
const body = {
|
||||
msg_type: 'interactive',
|
||||
card: {
|
||||
header: {
|
||||
title: {
|
||||
tag: 'plain_text',
|
||||
content: title,
|
||||
},
|
||||
},
|
||||
elements: [
|
||||
{
|
||||
tag: 'div',
|
||||
text: {
|
||||
tag: 'lark_md',
|
||||
content: typeof content === 'string' ? content : JSON.stringify(content),
|
||||
},
|
||||
},
|
||||
{
|
||||
tag: 'hr',
|
||||
},
|
||||
{
|
||||
tag: 'note',
|
||||
elements: [
|
||||
{
|
||||
tag: 'plain_text',
|
||||
content: `编号: ${record.ref_code || record.ext_id}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
ctx.logger.info(`[inbox feishu] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
|
||||
return await this.post(record.target_url, body);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FeishuDispatch;
|
||||
44
app/service/inbox/dispatch/webhook.js
Normal file
44
app/service/inbox/dispatch/webhook.js
Normal file
@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
const OutboundBase = require('./base');
|
||||
|
||||
/**
|
||||
* Webhook 渠道出站实现。
|
||||
* 直接 HTTP POST 推送 JSON 到目标 webhook URL。
|
||||
*/
|
||||
class WebhookDispatch extends OutboundBase {
|
||||
/**
|
||||
* 通过 webhook 渠道推送消息。
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例)。
|
||||
* @return {Promise<{status: number, data: *}>} 推送响应。
|
||||
*/
|
||||
async push(record) {
|
||||
const { ctx } = this;
|
||||
|
||||
const body = {
|
||||
ref_code: record.ref_code,
|
||||
ext_data: record.ext_data,
|
||||
message_id: record.ext_id,
|
||||
direction: record.direction,
|
||||
source_type: record.source_type,
|
||||
created_at: record.created_at,
|
||||
};
|
||||
|
||||
let targetUrl = record.target_url;
|
||||
|
||||
// API 类型需要签名
|
||||
if (record.target_type === 'api') {
|
||||
const apiApp = await this.getApiApp(record.warehouse_id);
|
||||
if (apiApp) {
|
||||
targetUrl = this.signRequest(targetUrl, body, apiApp);
|
||||
} else {
|
||||
ctx.logger.warn(`[inbox webhook] 仓库 ${record.warehouse_id} 没有可用 ApiApp,跳过签名`);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.logger.info(`[inbox webhook] 推送消息 ext_id=${record.ext_id} url=${targetUrl}`);
|
||||
return await this.post(targetUrl, body);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebhookDispatch;
|
||||
33
app/service/inbox/dispatch/wecom.js
Normal file
33
app/service/inbox/dispatch/wecom.js
Normal file
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
const OutboundBase = require('./base');
|
||||
|
||||
/**
|
||||
* 企微 Bot 渠道出站实现。
|
||||
* 推送 Markdown 消息到企业微信机器人 webhook。
|
||||
*/
|
||||
class WecomDispatch extends OutboundBase {
|
||||
/**
|
||||
* 通过企微 Bot 推送消息。
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例)。
|
||||
* @return {Promise<{status: number, data: *}>} 推送响应。
|
||||
*/
|
||||
async push(record) {
|
||||
const { ctx } = this;
|
||||
|
||||
const extData = record.ext_data || {};
|
||||
const content = extData.content || extData.text || `新消息通知:${record.ref_code || record.ext_id}`;
|
||||
|
||||
const body = {
|
||||
msgtype: 'markdown',
|
||||
markdown: {
|
||||
content: typeof content === 'string' ? content : JSON.stringify(content),
|
||||
},
|
||||
};
|
||||
|
||||
ctx.logger.info(`[inbox wecom] 推送消息 ext_id=${record.ext_id} url=${record.target_url}`);
|
||||
return await this.post(record.target_url, body);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WecomDispatch;
|
||||
354
app/service/inbox/index.js
Normal file
354
app/service/inbox/index.js
Normal file
@ -0,0 +1,354 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const crypto = require('crypto');
|
||||
|
||||
/**
|
||||
* 站内信查询/管理服务。
|
||||
* 提供消息列表、详情、对话链、回复、重推、统计等管理功能。
|
||||
*/
|
||||
class InboxService extends Service {
|
||||
/**
|
||||
* 消息列表(按仓库/状态/方向筛选,分页)。
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
|
||||
* @param {string} [params.direction] 消息方向筛选:inbound / outbound。
|
||||
* @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。
|
||||
* @param {string} [params.targetChannel] 目标渠道筛选。
|
||||
* @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。
|
||||
* @param {number} [params.page=1] 页码。
|
||||
* @param {number} [params.pageSize=20] 每页数量。
|
||||
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
|
||||
*/
|
||||
async list(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(params.warehouseId);
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouseId 无效');
|
||||
}
|
||||
|
||||
const page = Math.max(1, Number(params.page) || 1);
|
||||
const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20));
|
||||
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
|
||||
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
|
||||
where.direction = params.direction;
|
||||
}
|
||||
|
||||
if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') {
|
||||
const status = Number(params.pushStatus);
|
||||
if ([ 0, 1, 2, 3 ].includes(status)) {
|
||||
where.push_status = status;
|
||||
}
|
||||
}
|
||||
|
||||
if (params.targetChannel && typeof params.targetChannel === 'string') {
|
||||
where.target_channel = params.targetChannel.trim();
|
||||
}
|
||||
|
||||
if (params.keyword && typeof params.keyword === 'string') {
|
||||
const keyword = `%${params.keyword.trim()}%`;
|
||||
where[Op.or] = [
|
||||
{ ext_id: { [Op.like]: keyword } },
|
||||
{ ref_code: { [Op.like]: keyword } },
|
||||
];
|
||||
}
|
||||
|
||||
const { count: total, rows } = await InboxMessage.findAndCountAll({
|
||||
attributes: {
|
||||
exclude: [ 'ext_data', 'push_response' ],
|
||||
},
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
return {
|
||||
list: rows,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page * pageSize < total,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息详情(含 push_response)。
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||||
* @param {number} params.id 消息ID。
|
||||
* @return {Promise<Object>} 消息详情。
|
||||
*/
|
||||
async detail(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(params.warehouseId);
|
||||
const id = Number(params.id);
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouseId 无效');
|
||||
}
|
||||
if (!Number.isFinite(id) || id <= 0) {
|
||||
throw new Error('消息ID无效');
|
||||
}
|
||||
|
||||
const record = await InboxMessage.findOne({
|
||||
where: { id, warehouse_id: warehouseId },
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
throw new Error('消息不存在或无权访问');
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对话链查询(原消息 + 所有回信),按 parent_id 递归。
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||||
* @param {number} params.id 消息ID。
|
||||
* @return {Promise<Array>} 对话链列表。
|
||||
*/
|
||||
async thread(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(params.warehouseId);
|
||||
const id = Number(params.id);
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouseId 无效');
|
||||
}
|
||||
if (!Number.isFinite(id) || id <= 0) {
|
||||
throw new Error('消息ID无效');
|
||||
}
|
||||
|
||||
// 查找根消息
|
||||
const root = await InboxMessage.findOne({
|
||||
where: { id, warehouse_id: warehouseId },
|
||||
});
|
||||
|
||||
if (!root) {
|
||||
throw new Error('消息不存在或无权访问');
|
||||
}
|
||||
|
||||
// 收集对话链:从根到叶
|
||||
const thread = [ root ];
|
||||
|
||||
// 查找所有回信(以 root.id 为 parent_id)
|
||||
const replies = await InboxMessage.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
parent_id: root.id,
|
||||
},
|
||||
order: [[ 'created_at', 'ASC' ]],
|
||||
});
|
||||
|
||||
thread.push(...replies);
|
||||
|
||||
// 如果当前消息不是根(有 parent_id),也向上查找原消息
|
||||
if (root.parent_id) {
|
||||
const parent = await InboxMessage.findOne({
|
||||
where: {
|
||||
id: root.parent_id,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
});
|
||||
|
||||
if (parent) {
|
||||
thread.unshift(parent);
|
||||
}
|
||||
}
|
||||
|
||||
return thread;
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统回信:写入 outbound 记录 + 异步推送。
|
||||
* @param {Object} data 回信数据。
|
||||
* @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。
|
||||
* @param {number} data.parentId 原消息ID。
|
||||
* @param {string} data.targetChannel 目标渠道。
|
||||
* @param {string} data.targetUrl 推送目标URL。
|
||||
* @param {string} [data.refCode] 引用编码。
|
||||
* @param {Object} [data.extData] 透传数据。
|
||||
* @param {Object} [data.flags] 处理标记。
|
||||
* @return {Promise<Object>} 回信结果。
|
||||
*/
|
||||
async reply(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(data.warehouseId);
|
||||
const parentId = Number(data.parentId);
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouseId 无效');
|
||||
}
|
||||
if (!Number.isFinite(parentId) || parentId <= 0) {
|
||||
throw new Error('parentId 无效');
|
||||
}
|
||||
|
||||
// 查找原消息
|
||||
const parent = await InboxMessage.findOne({
|
||||
where: { id: parentId, warehouse_id: warehouseId },
|
||||
});
|
||||
|
||||
if (!parent) {
|
||||
throw new Error('原消息不存在或无权访问');
|
||||
}
|
||||
|
||||
const extId = `sys:${crypto.randomUUID()}`;
|
||||
|
||||
const result = await ctx.service.inbox.receiver.receive({
|
||||
ext_id: extId,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: parent.store_id,
|
||||
direction: 'outbound',
|
||||
parent_id: parentId,
|
||||
source_type: 'system',
|
||||
source_extra: null,
|
||||
target_type: data.targetType || parent.target_type,
|
||||
target_channel: data.targetChannel,
|
||||
target_url: data.targetUrl,
|
||||
ref_code: data.refCode || parent.ref_code,
|
||||
ext_data: data.extData || parent.ext_data,
|
||||
flags: data.flags || {},
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动重推。
|
||||
* @param {Object} params 重推参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||||
* @param {number} params.id 消息ID。
|
||||
* @return {Promise<Object>} 重推结果。
|
||||
*/
|
||||
async retry(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(params.warehouseId);
|
||||
const id = Number(params.id);
|
||||
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouseId 无效');
|
||||
}
|
||||
if (!Number.isFinite(id) || id <= 0) {
|
||||
throw new Error('消息ID无效');
|
||||
}
|
||||
|
||||
const record = await InboxMessage.findOne({
|
||||
where: { id, warehouse_id: warehouseId },
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
throw new Error('消息不存在或无权访问');
|
||||
}
|
||||
|
||||
if (![ 3 ].includes(record.push_status)) {
|
||||
throw new Error('仅失败状态的消息可以手动重推');
|
||||
}
|
||||
|
||||
// 重置为待推送状态,由异步推送接管
|
||||
await record.update({
|
||||
push_status: 0,
|
||||
push_started_at: null,
|
||||
});
|
||||
|
||||
// 触发异步推送
|
||||
setImmediate(() => {
|
||||
ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => {
|
||||
ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`);
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
id: record.id,
|
||||
ext_id: record.ext_id,
|
||||
message: '已触发重推',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送统计(按仓库 + 状态汇总)。
|
||||
* @param {Object} params 统计参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||||
* @param {string} [params.direction] 消息方向筛选。
|
||||
* @return {Promise<Object>} 统计结果。
|
||||
*/
|
||||
async stats(params = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const warehouseId = Number(params.warehouseId);
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouseId 无效');
|
||||
}
|
||||
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
};
|
||||
|
||||
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
|
||||
where.direction = params.direction;
|
||||
}
|
||||
|
||||
// 按方向统计
|
||||
const directionStats = await InboxMessage.findAll({
|
||||
attributes: [
|
||||
'direction',
|
||||
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
|
||||
],
|
||||
where,
|
||||
group: [ 'direction' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 按推送状态统计
|
||||
const statusStats = await InboxMessage.findAll({
|
||||
attributes: [
|
||||
'push_status',
|
||||
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
|
||||
],
|
||||
where,
|
||||
group: [ 'push_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 最近24小时统计
|
||||
const recentWhere = {
|
||||
...where,
|
||||
created_at: {
|
||||
[Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000),
|
||||
},
|
||||
};
|
||||
|
||||
const recentCount = await InboxMessage.count({ where: recentWhere });
|
||||
|
||||
return {
|
||||
total_by_direction: directionStats,
|
||||
total_by_status: statusStats,
|
||||
recent_24h_count: recentCount,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxService;
|
||||
370
app/service/inbox/receiver.js
Normal file
370
app/service/inbox/receiver.js
Normal file
@ -0,0 +1,370 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const { URL } = require('url');
|
||||
const { networkInterfaces } = require('os');
|
||||
|
||||
/** 推送 body 大小上限:64KB */
|
||||
const MAX_PUSH_BODY_SIZE = 64 * 1024;
|
||||
/** 最大重试次数 */
|
||||
const MAX_RETRY_COUNT = 3;
|
||||
/** 僵尸恢复阈值:5分钟 */
|
||||
const ZOMBIE_RECOVERY_MINUTES = 5;
|
||||
|
||||
/**
|
||||
* 收集本机所有内网 IPv4 地址。
|
||||
* @return {string[]} 内网IP地址列表。
|
||||
*/
|
||||
function getLocalInternalIps() {
|
||||
const ips = new Set();
|
||||
const nets = networkInterfaces();
|
||||
for (const interfaces of Object.values(nets)) {
|
||||
for (const iface of interfaces) {
|
||||
if (iface.family === 'IPv4' && !iface.internal) {
|
||||
ips.add(iface.address);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(ips);
|
||||
}
|
||||
|
||||
/** 内网 IP 前缀集合 */
|
||||
const INTERNAL_IP_PREFIXES = [
|
||||
'127.',
|
||||
'10.',
|
||||
'192.168.',
|
||||
'0.',
|
||||
];
|
||||
|
||||
/**
|
||||
* 判断给定 IP 是否属于本机内网IP。
|
||||
* @param {string} ip IP地址。
|
||||
* @return {boolean} 是否为内网IP。
|
||||
*/
|
||||
function isInternalIp(ip) {
|
||||
if (!ip || ip === 'localhost') return true;
|
||||
|
||||
// 检查已知内网前缀
|
||||
for (const prefix of INTERNAL_IP_PREFIXES) {
|
||||
if (ip.startsWith(prefix)) return true;
|
||||
}
|
||||
|
||||
// 检查 172.16.0.0 ~ 172.31.255.255
|
||||
const parts = ip.split('.').map(Number);
|
||||
if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查本机实际内网IP
|
||||
const localIps = getLocalInternalIps();
|
||||
if (localIps.includes(ip)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 target_url 安全性:仅允许 https://,禁止内网IP。
|
||||
* @param {string} urlStr 目标URL。
|
||||
* @throws {Error} URL 不合法时抛出。
|
||||
*/
|
||||
function validateTargetUrl(urlStr) {
|
||||
if (!urlStr || typeof urlStr !== 'string') {
|
||||
throw new Error('target_url 不能为空');
|
||||
}
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(urlStr);
|
||||
} catch (e) {
|
||||
throw new Error(`target_url 格式不合法: ${urlStr}`);
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'https:') {
|
||||
throw new Error('target_url 仅允许 https:// 协议');
|
||||
}
|
||||
|
||||
const hostname = parsed.hostname || '';
|
||||
if (isInternalIp(hostname)) {
|
||||
throw new Error('target_url 不允许指向内网地址');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 站内信接收服务。
|
||||
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复。
|
||||
*/
|
||||
class InboxReceiverService extends Service {
|
||||
/**
|
||||
* 获取支持的目标渠道集合。
|
||||
* @return {Set<string>} 支持的目标渠道。
|
||||
*/
|
||||
static get SUPPORTED_CHANNELS() {
|
||||
return new Set([
|
||||
'webhook',
|
||||
'wecom',
|
||||
'dingtalk',
|
||||
'feishu',
|
||||
'warehouse_api',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化时执行僵尸恢复。
|
||||
* @param {Object} ctx Egg.js 上下文。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// 异步执行僵尸恢复,不阻塞服务启动
|
||||
setImmediate(() => {
|
||||
this.recoverZombieMessages().catch(err => {
|
||||
ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一接收入口:幂等去重、写库、异步推送。
|
||||
* @param {Object} data 消息数据。
|
||||
* @param {string} data.ext_id 外部唯一消息主键。
|
||||
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)。
|
||||
* @param {number} [data.store_id] 关联货主ID。
|
||||
* @param {string} [data.direction='inbound'] 消息方向。
|
||||
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)。
|
||||
* @param {string} data.source_type 来源类型:im / api / system。
|
||||
* @param {string} [data.source_extra] 来源附加信息。
|
||||
* @param {string} data.target_type 目标类型:im / api / webhook。
|
||||
* @param {string} data.target_channel 目标渠道。
|
||||
* @param {string} data.target_url 推送目标URL。
|
||||
* @param {string} [data.ref_code] 引用编码。
|
||||
* @param {Object} [data.ext_data] 透传数据。
|
||||
* @param {Object} [data.flags] 处理标记。
|
||||
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果。
|
||||
*/
|
||||
async receive(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
// 安全边界:校验 ext_id 不能为空
|
||||
const extId = String(data.ext_id || '').trim();
|
||||
if (!extId) {
|
||||
throw new Error('ext_id 不能为空');
|
||||
}
|
||||
|
||||
// 安全边界:warehouse_id 必须由服务端上下文提供
|
||||
const warehouseId = Number(data.warehouse_id);
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouse_id 无效');
|
||||
}
|
||||
|
||||
// 校验 target_channel 是否存在
|
||||
const targetChannel = String(data.target_channel || '').trim();
|
||||
if (!targetChannel || !InboxReceiverService.SUPPORTED_CHANNELS.has(targetChannel)) {
|
||||
throw new Error(`不支持的目标渠道: ${targetChannel},支持的渠道: ${Array.from(InboxReceiverService.SUPPORTED_CHANNELS).join(', ')}`);
|
||||
}
|
||||
|
||||
// 安全边界:校验 target_url
|
||||
validateTargetUrl(data.target_url);
|
||||
|
||||
// 幂等检查:ext_id 已存在则直接返回
|
||||
const exist = await InboxMessage.findOne({
|
||||
where: { ext_id: extId },
|
||||
attributes: [ 'id', 'ext_id', 'push_status' ],
|
||||
paranoid: false,
|
||||
});
|
||||
|
||||
if (exist) {
|
||||
ctx.logger.info(`[inbox] 消息已存在,跳过入库 ext_id=${extId} id=${exist.id}`);
|
||||
return {
|
||||
ok: true,
|
||||
id: exist.id,
|
||||
ext_id: extId,
|
||||
};
|
||||
}
|
||||
|
||||
// 推送 body 大小限制(序列化后检查)
|
||||
const pushBody = {
|
||||
ref_code: data.ref_code || null,
|
||||
ext_data: data.ext_data || null,
|
||||
};
|
||||
const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8');
|
||||
if (bodySize > MAX_PUSH_BODY_SIZE) {
|
||||
throw new Error(`推送 body 超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`);
|
||||
}
|
||||
|
||||
// 写库
|
||||
const record = await InboxMessage.create({
|
||||
ext_id: extId,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: data.store_id || null,
|
||||
direction: data.direction || 'inbound',
|
||||
parent_id: data.parent_id || null,
|
||||
source_type: data.source_type || 'api',
|
||||
source_extra: data.source_extra || null,
|
||||
target_type: data.target_type,
|
||||
target_channel: targetChannel,
|
||||
target_url: data.target_url,
|
||||
ref_code: data.ref_code || null,
|
||||
ext_data: data.ext_data || null,
|
||||
flags: data.flags || {},
|
||||
push_status: 0,
|
||||
});
|
||||
|
||||
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
|
||||
|
||||
// 异步后台推送(不阻塞响应)
|
||||
setImmediate(() => {
|
||||
this.asyncPush(record).catch(err => {
|
||||
ctx.logger.error(`[inbox] setImmediate 异步推送异常 ext_id=${extId}: ${err.message}`);
|
||||
// 异常已由 asyncPush 内部 try/catch,这里作为兜底
|
||||
try {
|
||||
InboxMessage.update(
|
||||
{
|
||||
push_status: 3,
|
||||
push_response: { error: `setImmediate 异常: ${err.message}` },
|
||||
pushed_at: new Date(),
|
||||
},
|
||||
{ where: { id: record.id, push_status: { [this.ctx.app.Sequelize.Op.in]: [ 0, 1 ] } } }
|
||||
);
|
||||
} catch (updateErr) {
|
||||
ctx.logger.error(`[inbox] 兜底更新推送状态失败 ext_id=${extId}: ${updateErr.message}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
id: record.id,
|
||||
ext_id: extId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步推送 + 指数退避重试。
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例)。
|
||||
* @param {number} [attempt=0] 当前重试次数。
|
||||
* @return {Promise<void>} 推送结果。
|
||||
*/
|
||||
async asyncPush(record, attempt = 0) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
try {
|
||||
// 乐观锁:仅 push_status=0 或(重试时 push_status=3)时可取走
|
||||
const allowedStatuses = attempt === 0 ? [ 0 ] : [ 3 ];
|
||||
const [ updatedCount ] = await InboxMessage.update(
|
||||
{
|
||||
push_status: 1,
|
||||
push_started_at: new Date(),
|
||||
},
|
||||
{
|
||||
where: {
|
||||
id: record.id,
|
||||
push_status: { [Op.in]: allowedStatuses },
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (updatedCount === 0) {
|
||||
ctx.logger.info(`[inbox] 消息已被其他进程取走,跳过推送 ext_id=${record.ext_id} id=${record.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取 dispatch 服务
|
||||
const channel = record.target_channel;
|
||||
if (!InboxReceiverService.SUPPORTED_CHANNELS.has(channel)) {
|
||||
throw new Error(`不支持的目标渠道: ${channel}`);
|
||||
}
|
||||
|
||||
// 统一渠道映射:warehouse_api → webhook
|
||||
const dispatchChannel = channel === 'warehouse_api' ? 'webhook' : channel;
|
||||
const dispatchService = ctx.service.inbox.dispatch[dispatchChannel];
|
||||
|
||||
if (!dispatchService || typeof dispatchService.push !== 'function') {
|
||||
throw new Error(`dispatch 渠道 ${dispatchChannel} 未实现`);
|
||||
}
|
||||
|
||||
// 执行推送
|
||||
const response = await dispatchService.push(record);
|
||||
|
||||
// 推送成功
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: 2,
|
||||
push_response: {
|
||||
http_status: response.status,
|
||||
body: response.data,
|
||||
},
|
||||
pushed_at: new Date(),
|
||||
},
|
||||
{ where: { id: record.id, push_status: 1 } }
|
||||
);
|
||||
|
||||
ctx.logger.info(`[inbox] 推送成功 ext_id=${record.ext_id} channel=${channel}`);
|
||||
} catch (error) {
|
||||
const next = attempt + 1;
|
||||
ctx.logger.warn(`[inbox] 推送失败 ext_id=${record.ext_id} attempt=${next} error=${error.message}`);
|
||||
|
||||
// 更新失败状态
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: next >= MAX_RETRY_COUNT ? 3 : 3,
|
||||
retry_count: next,
|
||||
push_response: { error: error.message },
|
||||
...(next >= MAX_RETRY_COUNT ? { pushed_at: new Date() } : {}),
|
||||
},
|
||||
{ where: { id: record.id, push_status: 1 } }
|
||||
);
|
||||
|
||||
// 指数退避重试:30s → 60s → 120s
|
||||
if (next < MAX_RETRY_COUNT) {
|
||||
const delay = 30000 * Math.pow(2, attempt);
|
||||
ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重试 ext_id=${record.ext_id} attempt=${next}`);
|
||||
setTimeout(() => {
|
||||
this.asyncPush(record, next).catch(err => {
|
||||
ctx.logger.error(`[inbox] 重试推送异常 ext_id=${record.ext_id}: ${err.message}`);
|
||||
});
|
||||
}, delay);
|
||||
} else {
|
||||
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失败 ext_id=${record.ext_id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 僵尸恢复:重置卡在"推送中"超过5分钟的消息为"待推送"。
|
||||
* 在服务启动时及定时任务中调用。
|
||||
* @return {Promise<number>} 恢复的消息数量。
|
||||
*/
|
||||
async recoverZombieMessages() {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const threshold = new Date(Date.now() - ZOMBIE_RECOVERY_MINUTES * 60 * 1000);
|
||||
|
||||
const [ updatedCount ] = await InboxMessage.update(
|
||||
{
|
||||
push_status: 0,
|
||||
push_started_at: null,
|
||||
},
|
||||
{
|
||||
where: {
|
||||
push_status: 1,
|
||||
push_started_at: {
|
||||
[Op.lt]: threshold,
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (updatedCount > 0) {
|
||||
ctx.logger.info(`[inbox] 僵尸恢复完成,重置 ${updatedCount} 条消息为待推送`);
|
||||
}
|
||||
|
||||
return updatedCount;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxReceiverService;
|
||||
64
app/service/warehouseMethods/inbox.js
Normal file
64
app/service/warehouseMethods/inbox.js
Normal file
@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 仓库开放 API — 站内信模块处理器。
|
||||
* 接收仓库级外部适配器推送的 inbox.push 请求,
|
||||
* 统一委托 app/service/inbox/receiver.receive 处理写库与异步推送。
|
||||
*/
|
||||
class WarehouseInboxService extends MainService {
|
||||
/**
|
||||
* 仓库 API 消息入站入口。
|
||||
* warehouse_id 从验签后上下文注入,禁止外部传入。
|
||||
* @param {Object} options 请求参数。
|
||||
* @param {Object} options.body 请求体。
|
||||
* @return {Promise<Object>} 入站结果。
|
||||
*/
|
||||
async push({ body = {} } = {}) {
|
||||
const { ctx } = this;
|
||||
const { warehouseId, appKey } = this.getInfo();
|
||||
|
||||
// 安全边界:warehouse_id 一律从验签后上下文获取
|
||||
if (!warehouseId) {
|
||||
throw new Error('缺少仓库信息');
|
||||
}
|
||||
|
||||
// 安全边界:校验必填参数
|
||||
if (!body.requestId || !String(body.requestId).trim()) {
|
||||
throw new Error('requestId 不能为空');
|
||||
}
|
||||
|
||||
if (!body.targetChannel || !String(body.targetChannel).trim()) {
|
||||
throw new Error('targetChannel 不能为空');
|
||||
}
|
||||
|
||||
if (!body.targetUrl || !String(body.targetUrl).trim()) {
|
||||
throw new Error('targetUrl 不能为空');
|
||||
}
|
||||
|
||||
// 构造 ext_id
|
||||
const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`;
|
||||
|
||||
// 构造入站数据并委托给 inbox receiver
|
||||
const result = await ctx.service.inbox.receiver.receive({
|
||||
ext_id: extId,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: body.storeId || null,
|
||||
direction: 'inbound',
|
||||
parent_id: body.parentId || null,
|
||||
source_type: body.sourceType || 'api',
|
||||
source_extra: String(appKey || ''),
|
||||
target_type: body.targetType || 'im',
|
||||
target_channel: body.targetChannel,
|
||||
target_url: body.targetUrl,
|
||||
ref_code: body.refCode || null,
|
||||
ext_data: body.extData || null,
|
||||
flags: body.flags || {},
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseInboxService;
|
||||
441
database/designs/inbox-message-module-design.md
Normal file
441
database/designs/inbox-message-module-design.md
Normal file
@ -0,0 +1,441 @@
|
||||
# 站内信(Inbox)模块设计方案
|
||||
|
||||
> **状态**: 📋 设计中
|
||||
> **设计日期**: 2026-08-03
|
||||
> **设计人**: wms-test-agent
|
||||
> **模块**: `app/service/inbox/`,独立文件模块
|
||||
> **表**: 1 张 — `wms_inbox_message`
|
||||
|
||||
---
|
||||
|
||||
## 一、概念
|
||||
|
||||
消息推送状态追踪表。不重复存储消息内容(消息体由 IM 回调 / API 请求各自管理),只记录**谁发来的、要推到哪、推送状态**。收件(inbound)和回信(outbound)共表,`direction` + `parent_id` 形成对话链。
|
||||
|
||||
```
|
||||
inbound(外部 → WMS) outbound(WMS → 外部)
|
||||
┌──────────────────────┐ ┌──────────────────────┐
|
||||
│ IM 回调 / API push │ │ 系统回信 / 工单通知 │
|
||||
└──────────┬───────────┘ └──────────┬───────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────────────────────────────┐
|
||||
│ wms_inbox_message(同一张表) │
|
||||
│ │
|
||||
│ direction: inbound │ outbound │
|
||||
│ parent_id: NULL │ parent_id: 原消息ID │
|
||||
│ │
|
||||
│ "IM msg_001 → API app_10 → success" │
|
||||
│ "WMS 回复 → 企微 Bot → success" │
|
||||
└─────────────────────────────────────────┘
|
||||
│
|
||||
▼ setImmediate async push
|
||||
dispatch → HTTP POST / Bot API
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、数据库表
|
||||
|
||||
### `wms_inbox_message`
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|
||||
|------|------|------|--------|------|
|
||||
| `id` | `BIGINT UNSIGNED` | ✅ | AUTO | 主键 |
|
||||
| `ext_id` | `VARCHAR(128)` | ✅ | — | **外部唯一消息主键**(IM msgId / API requestId 等),唯一索引,幂等去重 |
|
||||
| `warehouse_id` | `BIGINT UNSIGNED` | ✅ | — | 所属仓库 |
|
||||
| `store_id` | `BIGINT UNSIGNED` | — | NULL | 关联货主 |
|
||||
| `direction` | `VARCHAR(10)` | ✅ | `inbound` | `inbound`=外部→WMS 收件 / `outbound`=WMS→外部 回信 |
|
||||
| `parent_id` | `BIGINT UNSIGNED` | — | NULL | 关联消息 ID(回信时指向原消息,形成对话链) |
|
||||
|
||||
#### 来源 / 目标
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `source_type` | `VARCHAR(20)` | ✅ | `im` / `api` |
|
||||
| `source_extra` | `VARCHAR(100)` | — | 附加信息(IM 平台 / API app_id) |
|
||||
| `target_type` | `VARCHAR(20)` | ✅ | `im` / `api` |
|
||||
| `target_channel` | `VARCHAR(50)` | ✅ | 目标渠道:`wecom` / `dingtalk` / `feishu` / `warehouse_api` / `webhook` |
|
||||
| `target_url` | `VARCHAR(500)` | ✅ | 推送目标 URL(IM Bot webhook 地址 / API 回调地址) |
|
||||
|
||||
> **安全设计**:
|
||||
> - `target_url` 不含 secret。IM Bot URL 中 token 已内嵌,API 推送时 secret 从 `ApiApp.self_app_secret` 查。
|
||||
> - **出站签名**:推送到仓库开放 API 时,使用与该仓库 ApiApp 相同的 MD5 签名算法(`canonicalQuery + self_app_secret + bodySign`),接收方用同一 `app_key` 验证。IM 通道则使用各自 Bot 的原生鉴权。
|
||||
|
||||
> **inbound vs outbound 的 source/target 语义**:
|
||||
> ```
|
||||
> inbound(外部→WMS):source=外部来源 target=WMS 内部要转发到的渠道
|
||||
> outbound(WMS→外部):source=WMS 内部 target=要推送到的外部渠道
|
||||
> ```
|
||||
| `ref_code` | `VARCHAR(100)` | — | 外部引用编码,推送/回执时原样携带 |
|
||||
| `ext_data` | `JSON` | — | **外部透传数据**,外部传入任意 JSON,WMS 不解析,回信时原样返回 |
|
||||
| `flags` | `JSON` | — | **处理标记**,外部传入控制 WMS 处理行为,见下表 |
|
||||
|
||||
> **`flags` 支持的标记**:
|
||||
> ```json
|
||||
> {
|
||||
> "skip_ai_parse": true, // 跳过智能解析(内部员工发信时设为 true)
|
||||
> "skip_auto_reply": true, // 跳过自动回复
|
||||
> "skip_forward": true // 仅存档,不转发
|
||||
> }
|
||||
> ```
|
||||
> 外部不传 → 默认全部开启(智能解析 + 自动回复 + 转发)。内部系统调用 `inbox.push` 时按需关闭特定行为。
|
||||
|
||||
#### 推送状态
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|
||||
|------|------|------|--------|------|
|
||||
| `push_status` | `TINYINT(4)` | ✅ | 0 | 0=待推送 1=推送中 2=已送达 3=失败 |
|
||||
| `push_started_at` | `DATETIME` | — | NULL | 开始推送时间(僵尸检测:超 5 分钟仍为 1 → 重置为 0) |
|
||||
| `retry_count` | `INT(11)` | ✅ | 0 | 已重试次数 |
|
||||
| `push_response` | `JSON` | — | NULL | 目标响应(http_status, body, error) |
|
||||
| `pushed_at` | `DATETIME` | — | NULL | 推送完成时间 |
|
||||
|
||||
> **防重机制**:`push_status` 字段本身即状态流转,不需要额外流转表。使用乐观锁 `UPDATE SET push_status=1 WHERE push_status=0` 保证单条消息不会被重复取走。`push_started_at` 用于进程崩溃后的僵尸恢复。
|
||||
|
||||
#### 关联(后续)
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `work_order_id` | `BIGINT UNSIGNED` | — | 🔮 关联工单 |
|
||||
| `work_order_no` | `VARCHAR(50)` | — | 🔮 工单号 |
|
||||
|
||||
#### 时间
|
||||
|
||||
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|
||||
|------|------|------|--------|------|
|
||||
| `created_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP | |
|
||||
| `updated_at` | `DATETIME` | ✅ | CURRENT_TIMESTAMP ON UPDATE | |
|
||||
| `deleted_at` | `DATETIME` | — | NULL | 软删除 |
|
||||
|
||||
### 索引
|
||||
|
||||
| 索引名 | 字段 | 用途 |
|
||||
|--------|------|------|
|
||||
| `PRIMARY` | `id` | — |
|
||||
| `uk_ext_id` | `ext_id` UNIQUE | 外部幂等去重 |
|
||||
| `idx_warehouse_status` | `warehouse_id, push_status` | 按仓库+状态查询 |
|
||||
| `idx_warehouse_direction` | `warehouse_id, direction, created_at` | 收件/回信列表 |
|
||||
| `idx_parent` | `parent_id` | 对话链查询 |
|
||||
| `idx_created_at` | `created_at` | 时间范围 |
|
||||
|
||||
> **`ext_id` 唯一键防碰撞**:不同来源的消息 ID 可能重复(IM msgId 与 API requestId 撞车)。入库时按来源加前缀:
|
||||
> ```
|
||||
> IM 消息: ext_id = `im:wecom:${msg.msgId}`
|
||||
> API 消息: ext_id = `api:${apiAppId}:${body.requestId}`
|
||||
> 系统回信: ext_id = `sys:${uuid}`
|
||||
> ```
|
||||
> 前缀保证不同来源的消息不会因 ID 相同而误判为重复。
|
||||
|
||||
> **容量规划**:`BIGINT UNSIGNED` 主键容量无限。单表 InnoDB 建议 ≤ 5000 万行。以 100 仓 × 日均 5000 条 = 日 50 万条计,达到上限需 ~100 天。届时加 `PARTITION BY HASH(warehouse_id) PARTITIONS 16` 即可水平扩展,无需分库分表,代码零改动。
|
||||
|
||||
### 安全边界(强制)
|
||||
|
||||
| 边界 | 规则 |
|
||||
|------|------|
|
||||
| **warehouse_id 归属** | 禁止外部传入。IM 路径从回调解析获取,API 路径从验签后 `ctx.warehouseId` 获取 |
|
||||
| **ext_id 前缀** | `im:{platform}:{msgId}` / `api:{appId}:{requestId}` / `sys:{uuid}`,receiver 入站时统一格式 |
|
||||
| **target_url SSRF** | 仅允许 `https://`,禁止内网 IP(127.0.0.1/10.x/172.16-31.x/192.168.x) |
|
||||
| **dispatch 超时** | HTTP 请求超时 10s,超时视为失败进入重试 |
|
||||
| **setImmediate 异常** | `try/catch` 包裹,异常写入 `push_response.error`,`push_status=3` |
|
||||
| **target_channel 校验** | `dispatch[channel]` 不存在时返回明确错误,不静默丢弃 |
|
||||
| **僵尸恢复** | 启动时 + 每 5 分钟定时执行 `UPDATE push_status=0 WHERE push_status=1 AND push_started_at < NOW()-5MIN` |
|
||||
| **推送 body 大小** | 限制 64KB,超限拒绝写入 |
|
||||
|
||||
---
|
||||
|
||||
## 三、推送流程
|
||||
|
||||
```
|
||||
receiver.receive()
|
||||
│
|
||||
├─ 1. 幂等检查(ext_id 已存在 → 直接返回)
|
||||
├─ 2. INSERT(push_status=0)
|
||||
└─ 3. setImmediate(() => asyncPush(record))
|
||||
│
|
||||
├─ UPDATE push_status=1(推送中)
|
||||
├─ dispatch(target_channel, target_url)
|
||||
│ ├─ 成功 → UPDATE push_status=2, pushed_at=NOW()
|
||||
│ └─ 失败 → retry_count++
|
||||
│ ├─ < 3 次 → setTimeout(delay, asyncPush) 指数退避重试
|
||||
│ └─ ≥ 3 次 → UPDATE push_status=3(终态)
|
||||
└─ 返回
|
||||
```
|
||||
|
||||
**指数退避**:30s → 60s → 120s,最多重试 3 次。
|
||||
|
||||
**关键**:不依赖定时任务轮询,利用 Node.js 事件循环的 `setImmediate` + `setTimeout` 在同一个进程内异步完成推送与重试。
|
||||
|
||||
---
|
||||
|
||||
## 四、两个接收入口
|
||||
|
||||
### IM 消息入站
|
||||
|
||||
```
|
||||
企微/钉钉/飞书 Bot 回调 → receiver.receive({
|
||||
// warehouse_id 由 IM 回调解析 / 签名验证后从上下文获取,不外部传入
|
||||
source_type: 'im',
|
||||
ext_id: `im:wecom:${msg.msgId}`,
|
||||
source_extra: 'wecom',
|
||||
|
||||
target_type: 'api',
|
||||
target_channel: 'warehouse_api',
|
||||
target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
|
||||
ref_code: msg.userId,
|
||||
ext_data: { conversation_id: msg.conversationId },
|
||||
flags: {},
|
||||
|
||||
warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入
|
||||
})
|
||||
```
|
||||
|
||||
### 仓库 API 消息入站
|
||||
|
||||
```
|
||||
POST /warehouse?method=inbox.push → receiver.receive({
|
||||
// warehouse_id 由仓库 API 验签后从 ApiApp 解析,不外部传入
|
||||
source_type: 'api',
|
||||
ext_id: `api:${ctx.apiAppId}:${body.requestId}`,
|
||||
source_extra: String(ctx.apiAppId),
|
||||
|
||||
target_type: 'im',
|
||||
target_channel: body.targetChannel || 'wecom',
|
||||
target_url: body.targetUrl,
|
||||
ref_code: body.refCode,
|
||||
ext_data: body.extData,
|
||||
flags: body.flags || {},
|
||||
|
||||
warehouse_id: ctx.warehouseId, // ← 来自鉴权上下文,非外部传入
|
||||
})
|
||||
```
|
||||
|
||||
### 系统回信(outbound)
|
||||
|
||||
```
|
||||
WMS 内部(工单通知/状态更新)→ receiver.reply({
|
||||
parent_id: 1, // 原消息 ID
|
||||
target_type: 'im',
|
||||
target_channel: 'wecom',
|
||||
target_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx',
|
||||
ref_code: 'TICKET-001',
|
||||
ext_data: { ... }, // 继承原消息 ext_data
|
||||
|
||||
warehouse_id: ctx.warehouseId, // ← WMS 内部上下文
|
||||
})
|
||||
// 自动写入 direction=outbound, parent_id=1
|
||||
// 推送成功后,可通过 inbox.thread 查完整对话链
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、API
|
||||
|
||||
### 5.1 内部管理 (`inbox.*`)
|
||||
|
||||
| method | 说明 |
|
||||
|--------|------|
|
||||
| `inbox.list` | 消息列表(`direction` 区分收件/回信) |
|
||||
| `inbox.detail` | 消息详情(含 push_response) |
|
||||
| `inbox.thread` | 对话链(原消息 + 所有回信) |
|
||||
| `inbox.reply` | 系统回信(写入 outbound 记录 + 异步推送) |
|
||||
| `inbox.retry` | 手动重推 |
|
||||
| `inbox.stats` | 推送统计 |
|
||||
|
||||
### 5.2 仓库 API (`inbox.push`)
|
||||
|
||||
`POST /warehouse?method=inbox.push`
|
||||
|
||||
| 参数 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `body.sourceType` | `string` | ✅ | 来源类型:`im` / `api` |
|
||||
| `body.sourceChannel` | `string` | — | 来源渠道(IM 平台 / API 标识) |
|
||||
| `body.requestId` | `string` | ✅ | 来源请求 ID(组成 ext_id) |
|
||||
| `body.targetChannel` | `string` | ✅ | 目标渠道 |
|
||||
| `body.targetUrl` | `string` | ✅ | 推送目标 URL |
|
||||
| `body.refCode` | `string` | — | 引用编码 |
|
||||
| `body.extData` | `object` | — | 透传数据 |
|
||||
| `body.flags` | `object` | — | 处理标记 `{ skip_ai_parse, skip_auto_reply, skip_forward }` |
|
||||
| `body.storeId` | `number` | — | 关联货主 |
|
||||
|
||||
---
|
||||
|
||||
## 六、异步推送实现
|
||||
|
||||
不启动独立 consumer,利用 Egg.js / Node.js 原生异步能力:
|
||||
|
||||
```javascript
|
||||
// receiver.js
|
||||
async receive(data) {
|
||||
// 1. 幂等检查
|
||||
const exist = await this.ctx.model.InboxMessage.findOne({
|
||||
where: { ext_id: data.ext_id },
|
||||
});
|
||||
if (exist) return { ok: true, id: exist.id, ext_id: data.ext_id };
|
||||
|
||||
// 2. 写入记录
|
||||
const record = await this.ctx.model.InboxMessage.create({
|
||||
ext_id: data.ext_id,
|
||||
warehouse_id: data.warehouse_id,
|
||||
source_type: data.source_type,
|
||||
source_extra: data.source_extra,
|
||||
target_type: data.target_type,
|
||||
target_channel: data.target_channel,
|
||||
target_url: data.target_url,
|
||||
ref_code: data.ref_code,
|
||||
ext_data: data.ext_data,
|
||||
flags: data.flags || {},
|
||||
push_status: 0,
|
||||
});
|
||||
|
||||
// 3. 异步后台推送(不阻塞响应)
|
||||
setImmediate(() => this.asyncPush(record));
|
||||
|
||||
return { ok: true, id: record.id, ext_id: data.ext_id };
|
||||
}
|
||||
|
||||
async asyncPush(record, attempt = 0) {
|
||||
// 乐观锁:仅 push_status=0 时可取走,防重
|
||||
const [ updated ] = await InboxMessage.update(
|
||||
{ push_status: 1, push_started_at: new Date() },
|
||||
{ where: { id: record.id, push_status: attempt === 0 ? 0 : 3 } }
|
||||
);
|
||||
if (!updated) return; // 已被其他进程取走
|
||||
|
||||
try {
|
||||
// API 渠道:用仓库 ApiApp 生成 MD5 签名,接收方同密钥验证
|
||||
const payload = { ref_code: record.ref_code, ext_data: record.ext_data };
|
||||
const signedUrl = record.target_type === 'api'
|
||||
? await this.signRequest(record, payload)
|
||||
: record.target_url;
|
||||
|
||||
const res = await this.ctx.service.inbox.dispatch[record.target_channel].push(
|
||||
signedUrl, payload
|
||||
);
|
||||
await record.update({
|
||||
push_status: 2,
|
||||
push_response: { http_status: res.status, body: res.data },
|
||||
pushed_at: new Date(),
|
||||
});
|
||||
} catch (err) {
|
||||
const next = attempt + 1;
|
||||
await record.update({ push_status: 3, retry_count: next, push_response: { error: err.message } });
|
||||
|
||||
if (next < 3) {
|
||||
const delay = 30000 * Math.pow(2, attempt); // 30s → 60s → 120s
|
||||
setTimeout(() => this.asyncPush(record, next), delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**不需要**:定时任务、消息队列、独立 worker 进程。
|
||||
|
||||
> **僵尸恢复**:进程崩溃导致 `push_status=1` 的记录卡死时,启动时执行 `UPDATE SET push_status=0 WHERE push_status=1 AND push_started_at < NOW() - INTERVAL 5 MINUTE` 即可复活。
|
||||
|
||||
> **出站签名**:推送到 `target_type=api` 时,使用仓库 ApiApp 的 `self_app_secret` 生成 MD5 签名附加到 URL query:
|
||||
> ```
|
||||
> signedUrl = target_url
|
||||
> + '?app_key=' + apiApp.self_app_key
|
||||
> + '×tamp=' + now
|
||||
> + '&sign=' + md5(queryString + self_app_secret + md5(body))
|
||||
> ```
|
||||
> 接收方(仓库开放侧)可用同一 `app_key` 调用 `apiSignLib.verifyRequestSign()` 验证。IM 通道(wecom/dingtalk/feishu)使用各自 Bot 原生鉴权,不走此签名。
|
||||
|
||||
---
|
||||
|
||||
## 七、模块结构
|
||||
|
||||
**分层原则**:API 入口只做校验与签名,统一委托 `app/service/inbox/` 处理写库与推送逻辑。`methods/` 仅放接口定义,不放业务代码。
|
||||
|
||||
```
|
||||
入口层(校验 + 签名) 统一处理层(写库 + 推送) 数据层
|
||||
────────────────────────── ────────────────────────── ──────
|
||||
app/controller/ app/service/inbox/ app/model/
|
||||
im.js ─────────────┐ ┌─ receiver.js inbox_message.js
|
||||
warehouse.js ──────┤ │ 统一接收(幂等去重) ↑
|
||||
├──调用──→ │ 写库(INSERT) │
|
||||
app/service/im.js ─┘ │ 异步推送(setImmediate) │
|
||||
│ │ 重试(setTimeout 指数退避) │
|
||||
│ │ │
|
||||
│ ├─ index.js │
|
||||
│ │ 列表/详情/重推/统计 │
|
||||
│ │ │
|
||||
│ └─ dispatch/ │
|
||||
│ base.js ← 统一出站:查 ApiApp、取密钥、签名、发 HTTP │
|
||||
│ webhook.js ← 继承 base,HTTP POST │
|
||||
│ wecom.js ← 继承 base,企微 Bot │
|
||||
│ dingtalk.js ← 继承 base,钉钉 Bot │
|
||||
│ feishu.js ← 继承 base,飞书 Bot │
|
||||
│ │
|
||||
methods/ (仅接口定义,不放逻辑) │
|
||||
warehouse.json ← inbox.push 参数声明 │
|
||||
system.json ← inbox.* 参数声明 │
|
||||
```
|
||||
|
||||
> **关键**:`app/service/inbox/` 是独立的统一处理目录,所有写库、推送、重试逻辑集中在此。后续新增渠道只需在 `dispatch/` 下加一个文件,不影响其他层。
|
||||
|
||||
### 统一出站基类 `dispatch/base.js`
|
||||
|
||||
所有渠道 dispatch 继承此基类,统一处理查密钥、签名、发 HTTP:
|
||||
|
||||
```javascript
|
||||
// dispatch/base.js
|
||||
class OutboundBase {
|
||||
constructor(ctx) { this.ctx = ctx; }
|
||||
|
||||
// 获取仓库 ApiApp 密钥(IM 渠道无需签名,返回 null)
|
||||
async getApiApp(warehouseId) {
|
||||
return await this.ctx.service.systems.apiSign.getApiAppConfigByAppKey(
|
||||
/* appKey from warehouse */, WAREHOUSE_INTERFACE_TYPE_ID
|
||||
);
|
||||
}
|
||||
|
||||
// 生成 MD5 签名(复用 apiSignLib)
|
||||
signRequest(url, body, secret) {
|
||||
const query = { app_key: secret.appKey, timestamp: Math.floor(Date.now() / 1000) };
|
||||
const { sign } = apiSignLib.signRequest({ query, body, selfAppSecret: secret.selfAppSecret });
|
||||
return `${url}?app_key=${query.app_key}×tamp=${query.timestamp}&sign=${sign}`;
|
||||
}
|
||||
|
||||
// 统一发送(子类可覆盖签名逻辑)
|
||||
async post(url, body) { /* axios/post */ }
|
||||
|
||||
// 子类必须实现
|
||||
async push(record) { throw new Error('子类实现'); }
|
||||
}
|
||||
```
|
||||
|
||||
> **调用链**:`receiver.asyncPush()` → `dispatch[channel].push(record)` → 基类 `signRequest()` + `post()` → 外部。各渠道只关注消息格式转换,签名和 HTTP 由基类统一处理。
|
||||
|
||||
### 与现有系统集成
|
||||
|
||||
```
|
||||
app/controller/im.js(已有)
|
||||
→ IM 回调签名校验后 → ctx.service.inbox.receiver.receive({ source_type: 'im', ... })
|
||||
|
||||
app/controller/warehouse.js(已有)
|
||||
→ method=inbox.push → ctx.service.inbox.receiver.receive({ source_type: 'api', ... })
|
||||
|
||||
methods/warehouse.json(修改)
|
||||
→ 新增 inbox.push 方法定义,注册到 warehouse 开放接口方法列表
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 八、文件变更清单
|
||||
|
||||
| 文件 | 操作 |
|
||||
|------|------|
|
||||
| `database/migrations/{ts}-create-inbox-message.js` | 新增 DDL |
|
||||
| `app/model/inbox_message.js` | 新增 |
|
||||
| `app/service/inbox/index.js` | 新增 |
|
||||
| `app/service/inbox/receiver.js` | 新增(统一接收 + 写库 + 异步推送入口) |
|
||||
| `app/service/inbox/dispatch/base.js` | 新增(统一出站:查密钥 + 签名 + HTTP) |
|
||||
| `app/service/inbox/dispatch/webhook.js` | 新增(HTTP POST 推送) |
|
||||
| `app/service/inbox/dispatch/wecom.js` | 新增(企微 Bot) |
|
||||
| `app/service/inbox/dispatch/dingtalk.js` | 新增(钉钉 Bot) |
|
||||
| `app/service/inbox/dispatch/feishu.js` | 新增(飞书 Bot) |
|
||||
| `app/controller/inbox.js` | 新增 |
|
||||
| `methods/warehouse.json` | 新增 `inbox.push` |
|
||||
| `methods/system.json` | 新增 `inbox.*` |
|
||||
182
database/migrations/20260803120000-create-inbox-message.js
Normal file
182
database/migrations/20260803120000-create-inbox-message.js
Normal file
@ -0,0 +1,182 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_message';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 创建站内信消息表。
|
||||
* @param {Object} queryInterface Sequelize QueryInterface 实例。
|
||||
* @param {Object} Sequelize Sequelize 类。
|
||||
* @return {Promise<void>} 迁移执行结果。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME);
|
||||
if (exists) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
ext_id: {
|
||||
type: Sequelize.STRING(128),
|
||||
allowNull: false,
|
||||
comment: '外部唯一消息主键(IM msgId / API requestId 等),用于幂等去重',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联货主ID',
|
||||
},
|
||||
direction: {
|
||||
type: Sequelize.STRING(10),
|
||||
allowNull: false,
|
||||
defaultValue: 'inbound',
|
||||
comment: '消息方向:inbound=外部→WMS收件 / outbound=WMS→外部回信',
|
||||
},
|
||||
parent_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联消息ID(回信时指向原消息,形成对话链)',
|
||||
},
|
||||
source_type: {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
comment: '来源类型:im / api',
|
||||
},
|
||||
source_extra: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '来源附加信息(IM 平台 / API app_id)',
|
||||
},
|
||||
target_type: {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: false,
|
||||
comment: '目标类型:im / api',
|
||||
},
|
||||
target_channel: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
|
||||
},
|
||||
target_url: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: false,
|
||||
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
|
||||
},
|
||||
ref_code: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部引用编码,推送/回执时原样携带',
|
||||
},
|
||||
ext_data: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回',
|
||||
},
|
||||
flags: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '处理标记,外部传入控制WMS处理行为',
|
||||
},
|
||||
push_status: {
|
||||
type: Sequelize.TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '推送状态:0=待推送 1=推送中 2=已送达 3=失败',
|
||||
},
|
||||
push_started_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '开始推送时间(僵尸检测:超5分钟仍为1则重置为0)',
|
||||
},
|
||||
retry_count: {
|
||||
type: Sequelize.INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '已重试次数',
|
||||
},
|
||||
push_response: {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '目标响应(http_status, body, error)',
|
||||
},
|
||||
pushed_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '推送完成时间',
|
||||
},
|
||||
work_order_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联工单ID(预留)',
|
||||
},
|
||||
work_order_no: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '工单号(预留)',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
});
|
||||
|
||||
// 唯一索引 — 外部幂等去重
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'ext_id' ], {
|
||||
unique: true,
|
||||
name: 'uk_ext_id',
|
||||
});
|
||||
|
||||
// 仓库+状态查询
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'push_status' ], {
|
||||
name: 'idx_warehouse_status',
|
||||
});
|
||||
|
||||
// 仓库+方向+时间
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'direction', 'created_at' ], {
|
||||
name: 'idx_warehouse_direction',
|
||||
});
|
||||
|
||||
// 对话链查询
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'parent_id' ], {
|
||||
name: 'idx_parent',
|
||||
});
|
||||
|
||||
// 时间范围查询
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'created_at' ], {
|
||||
name: 'idx_created_at',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚站内信消息表。
|
||||
* @param {Object} queryInterface Sequelize QueryInterface 实例。
|
||||
* @return {Promise<void>} 迁移回滚结果。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,22 +1,41 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.01-warehouse-01",
|
||||
"date": "2026-08-01",
|
||||
"type": "added",
|
||||
"summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表",
|
||||
"methods": [
|
||||
"index.ping",
|
||||
"store.list"
|
||||
],
|
||||
"notes": [
|
||||
"POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。",
|
||||
"签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。",
|
||||
"时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。",
|
||||
"无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。",
|
||||
"index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。",
|
||||
"store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。",
|
||||
"api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。"
|
||||
],
|
||||
"module": "warehouse"
|
||||
}
|
||||
{
|
||||
"version": "2026.08.01-warehouse-01",
|
||||
"date": "2026-08-01",
|
||||
"type": "added",
|
||||
"summary": "新增 /warehouse 仓库开放 API 入口,支持仓库级外部适配器 HMAC-SHA256 签名鉴权调用,首批上线 index.ping 心跳 + store.list 货主列表",
|
||||
"methods": [
|
||||
"index.ping",
|
||||
"store.list"
|
||||
],
|
||||
"notes": [
|
||||
"POST /warehouse 为新增入口,独立于 /openapi(货主级),鉴权使用 interface_type_id=3 的仓库 API 应用(由 apiApp 模块管理)。",
|
||||
"签名算法与 /openapi 完全一致:query 参数字典序 + body 拼接 → HMAC-SHA256 → hex。",
|
||||
"时间戳 ±10 分钟有效期,Redis 缓存 API 应用配置 300 秒(缓存前缀 warehouse:api-app)。",
|
||||
"无需 StoreWarehouse 合约关联,直接通过 api_app.warehouse_id 确定仓库上下文。",
|
||||
"index.ping:无需 body 参数,返回 warehouse_id / app_key / server_time / status。",
|
||||
"store.list:分页查询当前仓库下已授权的货主,通过 wms_store_warehouse 关联 wms_store,仅返回 auth_status=2 + store.status=1 + warehouse_use_status=1 的记录。",
|
||||
"api_sign.js 改造:getApiAppConfigByAppKey 新增 interfaceTypeId 参数(默认 2 保持向后兼容),warehouse 入口传 3,查询增加 interface_type_id 条件并返回 warehouse_id。"
|
||||
],
|
||||
"module": "warehouse"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.03-warehouse-01",
|
||||
"date": "2026-08-03",
|
||||
"type": "added",
|
||||
"summary": "新增仓库开放 API 站内信模块 inbox.push,支持外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道(IM/API/webhook)",
|
||||
"methods": [
|
||||
"inbox.push"
|
||||
],
|
||||
"notes": [
|
||||
"POST /warehouse?method=inbox.push,interface_type_id=3(仓库侧),使用 MD5 签名鉴权",
|
||||
"warehouse_id 由验签后上下文注入,禁止外部传入(安全边界)",
|
||||
"ext_id 格式:api:{appKey}:{requestId},用于幂等去重",
|
||||
"target_url 仅允许 https://,禁止内网 IP(SSRF 防护)",
|
||||
"推送 body 大小限制 64KB",
|
||||
"异步推送使用 setImmediate,不阻塞响应;失败指数退避重试(30s→60s→120s,最多3次)",
|
||||
"路由到 app/service/warehouseMethods/inbox.push → app/service/inbox/receiver.receive"
|
||||
],
|
||||
"module": "inbox"
|
||||
}
|
||||
]
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.9",
|
||||
"updatedAt": "2026-07-30",
|
||||
"updatedAt": "2026-08-03",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -31595,6 +31595,607 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"groupName": "站内信模块",
|
||||
"module": "inbox",
|
||||
"list": [
|
||||
{
|
||||
"method": "inbox.list",
|
||||
"description": "站内信消息列表,按仓库/方向/状态/渠道筛选,支持关键词搜索(ext_id / ref_code),分页返回(默认20条/页,最大200条)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "消息方向筛选:inbound(收件)/ outbound(回信)"
|
||||
},
|
||||
{
|
||||
"name": "pushStatus",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "推送状态筛选:0=待推送 1=推送中 2=已送达 3=失败"
|
||||
},
|
||||
{
|
||||
"name": "targetChannel",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "目标渠道筛选:wecom / dingtalk / feishu / warehouse_api / webhook"
|
||||
},
|
||||
{
|
||||
"name": "keyword",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "关键词搜索,模糊匹配 ext_id 和 ref_code"
|
||||
},
|
||||
{
|
||||
"name": "page",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "页码,默认 1",
|
||||
"defaultValue": 1
|
||||
},
|
||||
{
|
||||
"name": "pageSize",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "每页数量,默认 20,最大 200",
|
||||
"defaultValue": 20
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "消息列表(不含 ext_data 和 push_response 大字段)",
|
||||
"children": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "消息ID"
|
||||
},
|
||||
{
|
||||
"name": "ext_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "外部唯一消息主键"
|
||||
},
|
||||
{
|
||||
"name": "warehouse_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "所属仓库ID"
|
||||
},
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "消息方向:inbound / outbound"
|
||||
},
|
||||
{
|
||||
"name": "source_type",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "来源类型:im / api / system"
|
||||
},
|
||||
{
|
||||
"name": "target_type",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "目标类型:im / api / webhook"
|
||||
},
|
||||
{
|
||||
"name": "target_channel",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "目标渠道"
|
||||
},
|
||||
{
|
||||
"name": "push_status",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "推送状态:0=待推送 1=推送中 2=已送达 3=失败"
|
||||
},
|
||||
{
|
||||
"name": "retry_count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "已重试次数"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "创建时间"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "pagination",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "分页信息",
|
||||
"children": [
|
||||
{
|
||||
"name": "page",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "当前页码"
|
||||
},
|
||||
{
|
||||
"name": "pageSize",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "每页数量"
|
||||
},
|
||||
{
|
||||
"name": "total",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "总记录数"
|
||||
},
|
||||
{
|
||||
"name": "totalPages",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "总页数"
|
||||
},
|
||||
{
|
||||
"name": "hasPrevious",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否有上一页"
|
||||
},
|
||||
{
|
||||
"name": "hasNext",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "是否有下一页"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "method 参数无效"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "warehouseId 无效"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.detail",
|
||||
"description": "站内信消息详情,含完整 push_response 推送响应信息",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "消息ID"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "消息ID"
|
||||
},
|
||||
{
|
||||
"name": "ext_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "外部唯一消息主键"
|
||||
},
|
||||
{
|
||||
"name": "warehouse_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "所属仓库ID"
|
||||
},
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "消息方向"
|
||||
},
|
||||
{
|
||||
"name": "source_type",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "来源类型"
|
||||
},
|
||||
{
|
||||
"name": "target_type",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "目标类型"
|
||||
},
|
||||
{
|
||||
"name": "target_channel",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "目标渠道"
|
||||
},
|
||||
{
|
||||
"name": "target_url",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "推送目标URL"
|
||||
},
|
||||
{
|
||||
"name": "push_status",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "推送状态"
|
||||
},
|
||||
{
|
||||
"name": "retry_count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "已重试次数"
|
||||
},
|
||||
{
|
||||
"name": "push_response",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "推送目标响应(http_status, body, error)"
|
||||
},
|
||||
{
|
||||
"name": "ext_data",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "外部透传数据"
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "创建时间"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "更新时间"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "method 参数无效"
|
||||
},
|
||||
{
|
||||
"code": "404",
|
||||
"message": "消息不存在或无权访问"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "消息ID无效 / warehouseId 无效"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.thread",
|
||||
"description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "消息ID(可为对话链中任意一条消息,自动向上查找根消息并收集所有回信)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "thread",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "对话链消息数组,按时间升序排列,首元素为根消息,后续为回信"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "method 参数无效"
|
||||
},
|
||||
{
|
||||
"code": "404",
|
||||
"message": "消息不存在或无权访问"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "消息ID无效 / warehouseId 无效"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.reply",
|
||||
"description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "parentId",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "原消息ID(回信指向的原消息)"
|
||||
},
|
||||
{
|
||||
"name": "targetChannel",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook"
|
||||
},
|
||||
{
|
||||
"name": "targetUrl",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "推送目标 URL"
|
||||
},
|
||||
{
|
||||
"name": "targetType",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "目标类型:im / api / webhook,默认继承原消息的 target_type"
|
||||
},
|
||||
{
|
||||
"name": "refCode",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "引用编码,默认继承原消息的 ref_code"
|
||||
},
|
||||
{
|
||||
"name": "extData",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "透传数据,默认继承原消息的 ext_data"
|
||||
},
|
||||
{
|
||||
"name": "flags",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "处理标记"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "ok",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "操作是否成功"
|
||||
},
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "回信记录 ID"
|
||||
},
|
||||
{
|
||||
"name": "ext_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "回信唯一标识(sys:{uuid})"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "method 参数无效 / parentId 无效 / targetChannel 不能为空 / targetUrl 不能为空"
|
||||
},
|
||||
{
|
||||
"code": "404",
|
||||
"message": "原消息不存在或无权访问"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "warehouseId 无效 / 回信失败"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.retry",
|
||||
"description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "消息ID"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "ok",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "操作是否成功"
|
||||
},
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "消息ID"
|
||||
},
|
||||
{
|
||||
"name": "ext_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "外部唯一消息主键"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "操作结果描述"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "method 参数无效 / 仅失败状态的消息可以手动重推"
|
||||
},
|
||||
{
|
||||
"code": "404",
|
||||
"message": "消息不存在或无权访问"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "消息ID无效 / warehouseId 无效"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.stats",
|
||||
"description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token(从中解析 warehouseId 仓库上下文)"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "可选:按方向筛选统计(inbound / outbound),不传则统计全部"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "total_by_direction",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "按方向汇总统计",
|
||||
"children": [
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "消息方向"
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "消息数量"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "total_by_status",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "按推送状态汇总统计",
|
||||
"children": [
|
||||
{
|
||||
"name": "push_status",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "推送状态:0/1/2/3"
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "消息数量"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "recent_24h_count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "最近24小时新增消息数量"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "method 参数无效"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "warehouseId 无效"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
"module": "warehouse",
|
||||
"description": "仓库开放 API 统一入口,供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)",
|
||||
"version": "1.0.0",
|
||||
"updatedAt": "2026-08-01",
|
||||
"updatedAt": "2026-08-03",
|
||||
"http": {
|
||||
"path": "/warehouse",
|
||||
"method": "POST"
|
||||
@ -197,6 +197,148 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"groupName": "站内信模块",
|
||||
"module": "inbox",
|
||||
"list": [
|
||||
{
|
||||
"method": "inbox.push",
|
||||
"description": "外部系统将消息推入仓库站内信,WMS 异步转发到目标渠道。warehouse_id 由验签后上下文注入,禁止外部传入。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [
|
||||
{
|
||||
"name": "sourceType",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "来源类型:im / api,默认 api"
|
||||
},
|
||||
{
|
||||
"name": "sourceChannel",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "来源渠道标识(IM 平台名称 / API 标识),将写入 source_extra"
|
||||
},
|
||||
{
|
||||
"name": "requestId",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "来源请求唯一 ID,与 appKey 组合为 ext_id(api:{appKey}:{requestId}),用于幂等去重"
|
||||
},
|
||||
{
|
||||
"name": "targetType",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "目标类型:im / api / webhook,默认 im"
|
||||
},
|
||||
{
|
||||
"name": "targetChannel",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook"
|
||||
},
|
||||
{
|
||||
"name": "targetUrl",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "推送目标 URL(IM Bot webhook 地址 / API 回调地址),仅允许 https://,禁止内网 IP"
|
||||
},
|
||||
{
|
||||
"name": "refCode",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "外部引用编码,推送/回执时原样携带"
|
||||
},
|
||||
{
|
||||
"name": "extData",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "外部透传数据,任意 JSON,WMS 不解析,回信时原样返回"
|
||||
},
|
||||
{
|
||||
"name": "flags",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "处理标记,可选:skip_ai_parse(跳过智能解析)、skip_auto_reply(跳过自动回复)、skip_forward(仅存档不转发)"
|
||||
},
|
||||
{
|
||||
"name": "storeId",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "关联货主 ID"
|
||||
},
|
||||
{
|
||||
"name": "parentId",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "关联消息 ID(回信时指向原消息,形成对话链)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "ok",
|
||||
"type": "boolean",
|
||||
"required": true,
|
||||
"description": "操作是否成功"
|
||||
},
|
||||
{
|
||||
"name": "id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "站内信记录 ID"
|
||||
},
|
||||
{
|
||||
"name": "ext_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "外部唯一消息主键"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "requestId 不能为空"
|
||||
},
|
||||
{
|
||||
"code": "400",
|
||||
"message": "targetChannel 不能为空"
|
||||
},
|
||||
{
|
||||
"code": "400",
|
||||
"message": "targetUrl 不能为空"
|
||||
},
|
||||
{
|
||||
"code": "400",
|
||||
"message": "缺少仓库信息"
|
||||
},
|
||||
{
|
||||
"code": "400",
|
||||
"message": "target_url 仅允许 https:// 协议"
|
||||
},
|
||||
{
|
||||
"code": "400",
|
||||
"message": "target_url 不允许指向内网地址"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "站内信入站失败"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user