feat(inbox): 站内信模块完整实现 - AI智能助手、群管理、消息列表增强、灰度开关
新增功能: - AI智能助手: DeepSeek多轮推理、函数调用(searchStock/createOrder等) - silent动作: AI识别无需回复的消息(好的/谢谢/再见)自动跳过回执 - ai_enabled灰度开关: 群级别控制AI启停,支持逐群放量 - 消息列表增强: storeId/groupId/groupName/userName/content/sourceType多条件筛选,时间格式化 代码优化: - processWithAI: 多轮推理循环(MAX_ROUNDS=5)、对话历史不含[#N]前缀防AI污染 - 回执记录补齐group_id/user_id/group_name/user_name上下文 - 移除未使用的target_channel字段及迁移 - bindCode文档修正: store_warehouse → store 接口文档: - system.json v0.3.18→0.3.19: 新增aiEnabled参数、消息列表响应扩充 - changes/system.json: 新增bindCode变更记录 杂项: - store_warehouse.js JSDoc补全 - wave.js waveBatchSource修复
This commit is contained in:
parent
c25dffe884
commit
e61efbb66a
@ -1,127 +0,0 @@
|
||||
'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;
|
||||
45
app/model/inbox_block.js
Normal file
45
app/model/inbox_block.js
Normal file
@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 站内信屏蔽表 Model。
|
||||
* 记录被屏蔽的群/用户,后续来自该群+用户的消息不再触发 AI 回信。
|
||||
* group_name 和 user_name 均为 NULL 时表示全局屏蔽(预留)。
|
||||
*
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const InboxBlock = app.model.define('inbox_block', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
group_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '群名称',
|
||||
},
|
||||
user_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '用户名称',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_inbox_block',
|
||||
timestamps: false,
|
||||
comment: '站内信屏蔽表',
|
||||
});
|
||||
|
||||
return InboxBlock;
|
||||
};
|
||||
106
app/model/inbox_group.js
Normal file
106
app/model/inbox_group.js
Normal file
@ -0,0 +1,106 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 站内信群表 Model。
|
||||
* 记录与 WMS 交互的群信息,支持按仓库屏蔽。
|
||||
*
|
||||
* @param {Object} app Egg.js Application 实例。
|
||||
* @return {Object} Sequelize Model 定义。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const InboxGroup = app.model.define('inbox_group', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
group_name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '群名称',
|
||||
},
|
||||
group_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部群ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联货主ID',
|
||||
},
|
||||
group_type: {
|
||||
type: app.Sequelize.ENUM('store', 'warehouse', 'express'),
|
||||
allowNull: true,
|
||||
comment: '群类型: store=货主 warehouse=仓库 express=快递',
|
||||
},
|
||||
sub_type: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '群子类型: 货主(售后/财务/收货) 仓库(收货/普通/生产) 快递(揽收/售后)',
|
||||
},
|
||||
source_type: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '来源类型:im / api / system',
|
||||
},
|
||||
source_extra: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '来源附加信息',
|
||||
},
|
||||
is_blocked: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否屏蔽 0=否 1=是',
|
||||
},
|
||||
ai_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用AI自动回复: 0=关闭 1=开启',
|
||||
},
|
||||
express_interfaces: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)',
|
||||
},
|
||||
system_express_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '系统快递编码(仅群类型为 express 时必填)',
|
||||
},
|
||||
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: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_inbox_group',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
deletedAt: 'deleted_at',
|
||||
paranoid: true,
|
||||
comment: '站内信群表',
|
||||
});
|
||||
|
||||
return InboxGroup;
|
||||
};
|
||||
@ -77,34 +77,30 @@ module.exports = app => {
|
||||
},
|
||||
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: {
|
||||
group_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部引用编码,推送/回执时原样携带',
|
||||
comment: '群名称(外部传入)',
|
||||
},
|
||||
user_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '用户名称(外部传入)',
|
||||
},
|
||||
group_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部群ID',
|
||||
},
|
||||
user_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部用户ID',
|
||||
},
|
||||
content: {
|
||||
type: app.Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '消息正文/摘要,用于列表展示和关键词搜索',
|
||||
},
|
||||
ext_data: {
|
||||
type: JSON_TYPE,
|
||||
@ -116,6 +112,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '处理标记,外部传入控制WMS处理行为',
|
||||
},
|
||||
ai_thoughts: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]',
|
||||
},
|
||||
push_status: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
|
||||
@ -734,7 +734,14 @@ module.exports = app => {
|
||||
return normalizePolicyConfig(value, options);
|
||||
};
|
||||
|
||||
// 统一构造复合键语义的 where 条件,避免 service 侧重复散落。
|
||||
/**
|
||||
* 统一构造复合键语义的 where 条件,避免 service 侧重复散落。
|
||||
* @param {Object} options 配置项
|
||||
* @param {number} [options.warehouseId] 仓库ID
|
||||
* @param {number} [options.storeId] 货主ID
|
||||
* @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约
|
||||
* @return {Object} 组装后的 where 条件对象
|
||||
*/
|
||||
StoreWarehouse.buildScopedWhere = function(options = {}) {
|
||||
const {
|
||||
warehouseId,
|
||||
@ -757,7 +764,16 @@ module.exports = app => {
|
||||
return where;
|
||||
};
|
||||
|
||||
// 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。
|
||||
/**
|
||||
* 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。
|
||||
* @param {Object} options 配置项
|
||||
* @param {number} [options.warehouseId] 仓库ID
|
||||
* @param {number} [options.storeId] 货主ID
|
||||
* @param {boolean} [options.required=false] 是否使用 INNER JOIN
|
||||
* @param {number} [options.warehouseUseStatus=1] 仓库侧使用状态过滤,默认仅查可用合约
|
||||
* @param {Array<string>} [options.attributes] 需要查询的字段
|
||||
* @return {Object} Sequelize include 对象
|
||||
*/
|
||||
StoreWarehouse.buildStoreStockInclude = function(options = {}) {
|
||||
const {
|
||||
warehouseId,
|
||||
|
||||
@ -67,7 +67,4 @@ module.exports = app => {
|
||||
router.get('/testSendData', controller.home.testSendData);
|
||||
// IM交互入口
|
||||
router.post('/im', controller.im.index);
|
||||
|
||||
// 站内信内部管理接口
|
||||
router.post('/inbox', controller.inbox.index);
|
||||
};
|
||||
|
||||
@ -1,118 +0,0 @@
|
||||
'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;
|
||||
@ -1,35 +0,0 @@
|
||||
'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;
|
||||
@ -1,60 +0,0 @@
|
||||
'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;
|
||||
@ -1,44 +0,0 @@
|
||||
'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;
|
||||
@ -1,33 +0,0 @@
|
||||
'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;
|
||||
1060
app/service/inbox/functions.js
Normal file
1060
app/service/inbox/functions.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -9,13 +9,14 @@ const crypto = require('crypto');
|
||||
*/
|
||||
class InboxService extends Service {
|
||||
/**
|
||||
* 消息列表(按仓库/状态/方向筛选,分页)。
|
||||
* 消息列表(按仓库/状态/方向/群筛选,分页)。
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
|
||||
* @param {string} [params.groupId] 按群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 {string} [params.keyword] 关键词搜索(ext_id / content)。
|
||||
* @param {number} [params.page=1] 页码。
|
||||
* @param {number} [params.pageSize=20] 每页数量。
|
||||
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
|
||||
@ -38,6 +39,12 @@ class InboxService extends Service {
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
// 按群ID筛选
|
||||
if (params.groupId && typeof params.groupId === 'string') {
|
||||
const gid = params.groupId.trim();
|
||||
if (gid) where.group_id = gid;
|
||||
}
|
||||
|
||||
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
|
||||
where.direction = params.direction;
|
||||
}
|
||||
@ -49,15 +56,11 @@ class InboxService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
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 } },
|
||||
|
||||
{ content: { [Op.like]: keyword } },
|
||||
];
|
||||
}
|
||||
|
||||
@ -188,13 +191,11 @@ class InboxService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统回信:写入 outbound 记录 + 异步推送。
|
||||
* 系统回信:写入 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 {string} [data.content] 消息正文。
|
||||
* @param {Object} [data.extData] 透传数据。
|
||||
* @param {Object} [data.flags] 处理标记。
|
||||
* @return {Promise<Object>} 回信结果。
|
||||
@ -232,10 +233,7 @@ class InboxService extends Service {
|
||||
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,
|
||||
content: data.content || null,
|
||||
ext_data: data.extData || parent.ext_data,
|
||||
flags: data.flags || {},
|
||||
});
|
||||
@ -244,61 +242,7 @@ class InboxService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动重推。
|
||||
* @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] 消息方向筛选。
|
||||
|
||||
335
app/service/inbox/message.js
Normal file
335
app/service/inbox/message.js
Normal file
@ -0,0 +1,335 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 站内信消息查询/管理服务。
|
||||
* 提供消息列表、详情、对话链、回复、统计等管理功能。
|
||||
*/
|
||||
class InboxMessageService extends Service {
|
||||
/**
|
||||
* 消息列表(多条件筛选,分页)。
|
||||
* 时间字段使用 app.formatDate 统一格式化输出。
|
||||
*
|
||||
* @param {Object} params 查询参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
|
||||
* @param {string|string[]} [params.storeId] 货主ID筛选,支持逗号分隔字符串或数组。
|
||||
* @param {string|string[]} [params.groupId] 群ID筛选,支持逗号分隔字符串或数组。
|
||||
* @param {string} [params.groupName] 群名称模糊搜索。
|
||||
* @param {string} [params.userName] 用户名模糊搜索。
|
||||
* @param {string} [params.content] 正文模糊搜索。
|
||||
* @param {string} [params.sourceType] 来源类型:im / api / system。
|
||||
* @param {string} [params.direction] 消息方向筛选:inbound / outbound。
|
||||
* @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。
|
||||
* @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,
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
// 货主ID:支持多选(逗号分隔字符串或数组)
|
||||
const storeIds = this._normalizeIds(params.storeId);
|
||||
if (storeIds.length > 0) {
|
||||
where.store_id = { [Op.in]: storeIds };
|
||||
}
|
||||
|
||||
// 群ID:支持多选(逗号分隔字符串或数组)
|
||||
const groupIds = this._normalizeStrings(params.groupId);
|
||||
if (groupIds.length > 0) {
|
||||
where.group_id = { [Op.in]: groupIds };
|
||||
}
|
||||
|
||||
// 群名称模糊搜索
|
||||
const groupName = String(params.groupName || '').trim();
|
||||
if (groupName) {
|
||||
where.group_name = { [Op.like]: `%${groupName}%` };
|
||||
}
|
||||
|
||||
// 用户名模糊搜索
|
||||
const userName = String(params.userName || '').trim();
|
||||
if (userName) {
|
||||
where.user_name = { [Op.like]: `%${userName}%` };
|
||||
}
|
||||
|
||||
// 正文模糊搜索
|
||||
const content = String(params.content || '').trim();
|
||||
if (content) {
|
||||
where.content = { [Op.like]: `%${content}%` };
|
||||
}
|
||||
|
||||
// 来源类型筛选
|
||||
const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ];
|
||||
const sourceType = String(params.sourceType || '').trim();
|
||||
if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) {
|
||||
where.source_type = sourceType;
|
||||
}
|
||||
|
||||
// 方向筛选
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
const { count: total, rows } = await InboxMessage.findAndCountAll({
|
||||
attributes: {
|
||||
exclude: [ 'ext_data', 'push_response', 'target_channel' ],
|
||||
},
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
});
|
||||
|
||||
// 批量查货主名称
|
||||
const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ];
|
||||
const storeNameMap = {};
|
||||
if (storeIdsInResult.length > 0) {
|
||||
const stores = await ctx.model.Store.findAll({
|
||||
attributes: [ 'id', 'company_name' ],
|
||||
where: { id: { [Op.in]: storeIdsInResult } },
|
||||
raw: true,
|
||||
});
|
||||
for (const s of stores) {
|
||||
storeNameMap[s.id] = s.company_name || '';
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = ctx.app.formatDate;
|
||||
const list = rows.map(row => {
|
||||
const obj = row && typeof row.toJSON === 'function' ? row.toJSON() : row;
|
||||
return {
|
||||
...obj,
|
||||
store_name: storeNameMap[obj.store_id] || '',
|
||||
created_at: obj.created_at ? formatDate(obj.created_at) : '',
|
||||
updated_at: obj.updated_at ? formatDate(obj.updated_at) : '',
|
||||
pushed_at: obj.pushed_at ? formatDate(obj.pushed_at) : '',
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
totalPages: Math.ceil(total / pageSize),
|
||||
hasPrevious: page > 1,
|
||||
hasNext: page * pageSize < total,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将入参统一为数字ID数组。
|
||||
* 支持逗号分隔字符串 "1,2,3" 或数组 [1,2,3]。
|
||||
* @param {string|string[]|number[]|undefined} val 入参。
|
||||
* @return {number[]} 去重后的数字数组。
|
||||
*/
|
||||
_normalizeIds(val) {
|
||||
if (val === undefined || val === null) return [];
|
||||
const arr = Array.isArray(val) ? val : String(val).split(',');
|
||||
return [ ...new Set(arr.map(Number).filter(v => Number.isFinite(v) && v > 0)) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 将入参统一为字符串数组(去重去空)。
|
||||
* @param {string|string[]|undefined} val 入参。
|
||||
* @return {string[]} 去重后的非空字符串数组。
|
||||
*/
|
||||
_normalizeStrings(val) {
|
||||
if (val === undefined || val === null) return [];
|
||||
const arr = Array.isArray(val) ? val : String(val).split(',');
|
||||
return [ ...new Set(arr.map(String).map(s => s.trim()).filter(Boolean)) ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息详情(含 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, deleted_at: null },
|
||||
});
|
||||
|
||||
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 MAX_THREAD_DEPTH = 50;
|
||||
const thread = [ root ];
|
||||
const visited = new Set([ root.id ]);
|
||||
|
||||
// 查找所有回信(以 root.id 为 parent_id)
|
||||
const replies = await InboxMessage.findAll({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
parent_id: root.id,
|
||||
deleted_at: null,
|
||||
},
|
||||
order: [[ 'created_at', 'ASC' ]],
|
||||
});
|
||||
|
||||
for (const reply of replies) {
|
||||
if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) {
|
||||
visited.add(reply.id);
|
||||
thread.push(reply);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果当前消息不是根(有 parent_id),也向上查找原消息
|
||||
if (root.parent_id) {
|
||||
const parent = await InboxMessage.findOne({
|
||||
where: {
|
||||
id: root.parent_id,
|
||||
warehouse_id: warehouseId,
|
||||
deleted_at: null,
|
||||
},
|
||||
});
|
||||
|
||||
if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) {
|
||||
visited.add(parent.id);
|
||||
thread.unshift(parent);
|
||||
}
|
||||
}
|
||||
|
||||
return thread;
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送统计(按仓库 + 方向汇总)。
|
||||
* @param {Object} params 统计参数。
|
||||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||||
* @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 = InboxMessageService;
|
||||
570
app/service/inbox/processor.js
Normal file
570
app/service/inbox/processor.js
Normal file
@ -0,0 +1,570 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||
const CALLBACK_TIMEOUT_MS = 10000; // 回执超时 10s
|
||||
|
||||
/**
|
||||
* 站内信内容处理器。
|
||||
* 负责解析入站消息正文,按 source_type 分流处理,
|
||||
* 将 warehouse_id 和 store_id 挂载到 ctx 上下文供下游使用。
|
||||
*/
|
||||
class InboxProcessorService extends Service {
|
||||
/**
|
||||
* 处理入站消息内容。
|
||||
* 解析 content 后将 warehouse_id 和 store_id 写入 ctx 上下文。
|
||||
*
|
||||
* @param {Object} data 入站消息数据。
|
||||
* @param {string} data.content 消息正文。
|
||||
* @param {number} [data.warehouse_id] 仓库ID(优先使用显式传入值)。
|
||||
* @param {number} [data.store_id] 货主ID(优先使用显式传入值)。
|
||||
* @return {Promise<{warehouse_id: number|null, store_id: number|null, content: string}>} 处理结果。
|
||||
*/
|
||||
async process(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const content = String(data.content || '').trim();
|
||||
if (!content) {
|
||||
throw new Error('消息正文 content 不能为空');
|
||||
}
|
||||
|
||||
// warehouse_id:优先取显式传入,否则尝试从 content 中解析
|
||||
let warehouseId = data.warehouse_id != null ? Number(data.warehouse_id) : null;
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
warehouseId = this.extractWarehouseId(content) || this.getWarehouseIdFromContext();
|
||||
}
|
||||
|
||||
// store_id:优先取显式传入,否则尝试从 content 中解析
|
||||
let storeId = data.store_id != null ? Number(data.store_id) : null;
|
||||
if (!Number.isFinite(storeId) || storeId <= 0) {
|
||||
storeId = this.extractStoreId(content) || this.getStoreIdFromContext();
|
||||
}
|
||||
|
||||
// 写入 ctx 上下文,供下游使用
|
||||
if (!ctx.inboxContext) {
|
||||
ctx.inboxContext = {};
|
||||
}
|
||||
ctx.inboxContext.warehouse_id = warehouseId || null;
|
||||
ctx.inboxContext.store_id = storeId || null;
|
||||
ctx.inboxContext.group_name = data.group_name || null;
|
||||
ctx.inboxContext.user_name = data.user_name || null;
|
||||
ctx.inboxContext.group_id = data.group_id || null;
|
||||
ctx.inboxContext.user_id = data.user_id || null;
|
||||
|
||||
ctx.logger.info(
|
||||
'[inbox processor] 内容处理完成 ' +
|
||||
`warehouse_id=${ctx.inboxContext.warehouse_id} ` +
|
||||
`store_id=${ctx.inboxContext.store_id} ` +
|
||||
`content_length=${content.length}`
|
||||
);
|
||||
|
||||
return {
|
||||
warehouse_id: ctx.inboxContext.warehouse_id,
|
||||
store_id: ctx.inboxContext.store_id,
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* API 来源消息异步回执。
|
||||
* 处理消息正文后,向仓库 ApiApp 回调地址 POST 确认回执。
|
||||
* 回执内容为"收到",ext_data 原路带回。
|
||||
* 异步执行,不阻塞入站响应。
|
||||
*
|
||||
* @param {Object} data 入站消息数据。
|
||||
* @param {number} data.warehouse_id 仓库ID。
|
||||
* @param {number} [data.store_id] 货主ID。
|
||||
* @param {number} [data.parent_id] 入站消息记录ID(回执的 parent_id)。
|
||||
* @param {Object} [data.ext_data] 原始透传数据。
|
||||
* @param {string} [data.ext_id] 外部消息ID。
|
||||
* @param {string} [data.content] 消息正文。
|
||||
* @return {Promise<void>} 无返回值,异常仅记日志不抛出。
|
||||
*/
|
||||
async handleApiMessage(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(data.warehouse_id) || 0;
|
||||
const extId = String(data.ext_id || '');
|
||||
const parentId = Number(data.parent_id) || null;
|
||||
|
||||
try {
|
||||
// 1. 处理消息正文,挂载上下文
|
||||
await this.process(data);
|
||||
|
||||
// 2. 屏蔽检查
|
||||
const isBlocked = await this.isBlocked();
|
||||
if (isBlocked) {
|
||||
ctx.logger.info(`[inbox processor] 已屏蔽,跳过回执 ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. 绑群码识别:消息匹配"授权:CODE"时执行绑群
|
||||
const bindHandled = await this.tryBindGroup(data);
|
||||
if (bindHandled) return;
|
||||
|
||||
// 4. 群未绑定货主则跳过 AI 解析
|
||||
const storeId = Number(ctx.inboxContext?.store_id || 0);
|
||||
if (!storeId) {
|
||||
ctx.logger.info(`[inbox processor] 群未绑定货主,跳过 AI ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 4.1 注入群的 group_type / sub_type / ai_enabled 到上下文
|
||||
if (!ctx.inboxContext.group_type || !ctx.inboxContext.sub_type || ctx.inboxContext.ai_enabled === undefined) {
|
||||
try {
|
||||
const groupId = String(ctx.inboxContext.group_id || '').trim();
|
||||
if (groupId) {
|
||||
const group = await ctx.model.InboxGroup.findOne({
|
||||
attributes: [ 'group_type', 'sub_type', 'ai_enabled' ],
|
||||
where: { group_id: groupId, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
if (group) {
|
||||
ctx.inboxContext.group_type = group.group_type || '';
|
||||
ctx.inboxContext.sub_type = group.sub_type || '';
|
||||
ctx.inboxContext.ai_enabled = group.ai_enabled;
|
||||
ctx.logger.info(
|
||||
`[inbox processor] 注入群分组信息 group_type=${ctx.inboxContext.group_type} sub_type=${ctx.inboxContext.sub_type} ai_enabled=${ctx.inboxContext.ai_enabled}`
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[inbox processor] 查询群分组信息失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 4.2 群未启用AI → 跳过 AI 解析(灰度开关)
|
||||
if (ctx.inboxContext.ai_enabled === 0) {
|
||||
ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 5. DeepSeek 两步交互
|
||||
const aiResult = await ctx.service.inbox.functions.processWithAI({
|
||||
content: data.content || '',
|
||||
ext_data: data.ext_data || null,
|
||||
parentId: data.parent_id || null,
|
||||
});
|
||||
|
||||
// 无回复且无函数调用 → 跳过,节约资源
|
||||
// AI 显式指示跳过(silent 动作)→ 同上
|
||||
if (aiResult.skip || (!aiResult.reply && (!aiResult.functionName || aiResult.functionName === 'none'))) {
|
||||
ctx.logger.info(`[inbox processor] 无回复且未匹配函数,跳过回执 ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const replyContent = aiResult.reply || '已处理完成';
|
||||
ctx.logger.info(
|
||||
`[inbox processor] AI 处理完成 ext_id=${extId} ` +
|
||||
`function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}`
|
||||
);
|
||||
|
||||
// 6. 写入 outbound 回执记录
|
||||
const ackExtId = `sys:ack:${extId}`;
|
||||
|
||||
try {
|
||||
const existAck = await InboxMessage.findOne({
|
||||
where: { ext_id: ackExtId },
|
||||
attributes: [ 'id' ],
|
||||
paranoid: false,
|
||||
});
|
||||
|
||||
if (!existAck) {
|
||||
await InboxMessage.create({
|
||||
ext_id: ackExtId,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: data.store_id || null,
|
||||
direction: 'outbound',
|
||||
parent_id: parentId,
|
||||
source_type: 'system',
|
||||
source_extra: null,
|
||||
target_type: 'api',
|
||||
group_id: ctx.inboxContext?.group_id || data.group_id || null,
|
||||
user_id: ctx.inboxContext?.user_id || data.user_id || null,
|
||||
group_name: ctx.inboxContext?.group_name || data.group_name || null,
|
||||
user_name: ctx.inboxContext?.user_name || data.user_name || null,
|
||||
content: replyContent,
|
||||
ext_data: data.ext_data || null,
|
||||
ai_thoughts: aiResult.thoughts || null,
|
||||
flags: {},
|
||||
});
|
||||
|
||||
ctx.logger.info(`[inbox processor] 回执记录写入成功 parent_id=${parentId}`);
|
||||
}
|
||||
} catch (writeError) {
|
||||
ctx.logger.warn(`[inbox processor] 回执记录写入失败: ${writeError.message}`);
|
||||
}
|
||||
|
||||
// 7. 查回调地址并发送
|
||||
const callbackUrl = await this.getApiAppCallbackUrl(warehouseId);
|
||||
if (!callbackUrl) {
|
||||
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,跳过回执 ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const ackBody = {
|
||||
content: replyContent,
|
||||
ext_data: data.ext_data || null,
|
||||
ext_id: extId || null,
|
||||
};
|
||||
|
||||
ctx.logger.info(`[inbox processor] 发送 API 回执 ext_id=${extId} url=${callbackUrl}`);
|
||||
|
||||
const response = await ctx.curl(callbackUrl, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
contentType: 'json',
|
||||
data: ackBody,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
timeout: CALLBACK_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
ctx.logger.info(
|
||||
`[inbox processor] API 回执完成 ext_id=${extId} ` +
|
||||
`http_status=${response.status}`
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.error(
|
||||
`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试识别并执行绑群操作。
|
||||
* 匹配"授权:CODE",从缓存读取绑群信息并绑定货主到群。
|
||||
*
|
||||
* @param {Object} data 消息数据。
|
||||
* @return {Promise<boolean>} 是否已处理绑群。
|
||||
*/
|
||||
async tryBindGroup(data = {}) {
|
||||
const { ctx } = this;
|
||||
const content = String(data.content || '').trim();
|
||||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||||
const groupId = String(ctx.inboxContext?.group_id || '').trim();
|
||||
|
||||
const bindMatch = content.match(/授权[::]\s*([A-Z0-9]{6,20})/i);
|
||||
if (!bindMatch || !groupId || !warehouseId) return false;
|
||||
|
||||
const code = bindMatch[1].toUpperCase();
|
||||
|
||||
// 查群是否已绑定(直接查 DB,避免 ctx 上下文被仓库ID污染)
|
||||
try {
|
||||
const existingGroup = await ctx.model.InboxGroup.findOne({
|
||||
attributes: [ 'store_id' ],
|
||||
where: { group_id: groupId, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
if (existingGroup && existingGroup.store_id) {
|
||||
await this.writeOutboundReply(data, '已在绑定状态,无需重复操作');
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[inbox processor] 查群绑定状态异常: ${e.message}`);
|
||||
}
|
||||
|
||||
const cacheKey = `chat:bind:${warehouseId}:${code}`;
|
||||
|
||||
try {
|
||||
const cacheValue = await ctx.app.getCacheAsync(cacheKey);
|
||||
if (!cacheValue || !cacheValue.store_id) {
|
||||
await this.writeOutboundReply(data, '绑群码无效或已过期,请重新生成');
|
||||
return true;
|
||||
}
|
||||
|
||||
let storeName = `货主${cacheValue.store_id}`;
|
||||
try {
|
||||
const store = await ctx.model.Store.findOne({
|
||||
attributes: [ 'store_name' ],
|
||||
where: { id: cacheValue.store_id },
|
||||
raw: true,
|
||||
});
|
||||
if (store && store.store_name) storeName = store.store_name;
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
await ctx.model.InboxGroup.update(
|
||||
{
|
||||
store_id: cacheValue.store_id,
|
||||
group_type: cacheValue.group_type || 'store',
|
||||
sub_type: cacheValue.sub_type || null,
|
||||
},
|
||||
{ where: { group_id: groupId, warehouse_id: warehouseId } }
|
||||
);
|
||||
|
||||
ctx.inboxContext.store_id = cacheValue.store_id;
|
||||
ctx.inboxContext.group_type = cacheValue.group_type || 'store';
|
||||
ctx.inboxContext.sub_type = cacheValue.sub_type || null;
|
||||
await ctx.app.setCacheAsync(cacheKey, null, 0);
|
||||
|
||||
ctx.logger.info(
|
||||
`[inbox processor] 绑群成功 group_id=${groupId} store=${storeName}`
|
||||
);
|
||||
|
||||
await this.writeOutboundReply(data, `绑定「${storeName}」成功`);
|
||||
|
||||
// 绑定成功后自动查询面单余额
|
||||
try {
|
||||
const balanceResult = await ctx.service.inbox.functions.callFunction('queryPrintBalance', {});
|
||||
const balanceMsg = balanceResult?.success
|
||||
? `面单余额:总量 ${balanceResult.data.print_quantity},已锁定 ${balanceResult.data.print_quantity_locked},可用 ${balanceResult.data.available}`
|
||||
: `面单余额查询失败:${balanceResult?.error || '未知错误'}`;
|
||||
// 使用独立 ext_id 避免与绑定成功回执冲突
|
||||
await this.writeOutboundReply({ ...data, ext_id: `${data.ext_id}:balance` }, balanceMsg);
|
||||
} catch (balanceErr) {
|
||||
ctx.logger.warn(`[inbox processor] 绑群后面单余额查询异常: ${balanceErr.message}`);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[inbox processor] 绑群异常: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入 outbound 回执并发送 HTTP 回调。
|
||||
* group_id / user_id / group_name / user_name 为强制入参,
|
||||
* 缺失任一将抛出异常。
|
||||
*
|
||||
* @param {Object} data 消息数据。
|
||||
* @param {string} data.group_id 群ID(必填)。
|
||||
* @param {string} data.user_id 用户ID(必填)。
|
||||
* @param {string} data.group_name 群名称(必填)。
|
||||
* @param {string} data.user_name 用户名称(必填)。
|
||||
* @param {string} replyContent 回复内容。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async writeOutboundReply(data, replyContent) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
|
||||
const warehouseId = Number(data.warehouse_id || 0);
|
||||
const extId = String(data.ext_id || '');
|
||||
const parentId = Number(data.parent_id || 0);
|
||||
|
||||
// 强制入参校验
|
||||
const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim();
|
||||
const userId = String(data.user_id || ctx.inboxContext?.user_id || '').trim();
|
||||
const groupName = String(data.group_name || ctx.inboxContext?.group_name || '').trim();
|
||||
const userName = String(data.user_name || ctx.inboxContext?.user_name || '').trim();
|
||||
|
||||
if (!groupId || !userId || !groupName || !userName) {
|
||||
throw new Error(
|
||||
`回执缺少必填字段: group_id=${groupId || '?'}, user_id=${userId || '?'}, ` +
|
||||
`group_name=${groupName || '?'}, user_name=${userName || '?'}`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const ackExtId = `sys:ack:${extId}`;
|
||||
const existAck = await InboxMessage.findOne({
|
||||
where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false,
|
||||
});
|
||||
if (!existAck) {
|
||||
await InboxMessage.create({
|
||||
ext_id: ackExtId, warehouse_id: warehouseId,
|
||||
store_id: ctx.inboxContext?.store_id || null,
|
||||
direction: 'outbound', parent_id: parentId || null,
|
||||
source_type: 'system', source_extra: null,
|
||||
target_type: 'api',
|
||||
group_id: groupId,
|
||||
user_id: userId,
|
||||
group_name: groupName,
|
||||
user_name: userName,
|
||||
content: replyContent,
|
||||
ext_data: data.ext_data || null, flags: {},
|
||||
});
|
||||
}
|
||||
|
||||
const callbackUrl = await this.getApiAppCallbackUrl(warehouseId);
|
||||
if (callbackUrl) {
|
||||
const curlResult = await ctx.curl(callbackUrl, {
|
||||
method: 'POST', dataType: 'json', contentType: 'json',
|
||||
data: {
|
||||
content: replyContent,
|
||||
ext_data: data.ext_data || null,
|
||||
ext_id: extId,
|
||||
group_id: groupId,
|
||||
user_id: userId,
|
||||
group_name: groupName,
|
||||
user_name: userName,
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' }, timeout: 10000,
|
||||
});
|
||||
|
||||
// HTTP 200 → 更新回执消息推送状态为已送达
|
||||
if (curlResult && curlResult.status === 200) {
|
||||
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: { ext_id: ackExtId } }
|
||||
);
|
||||
|
||||
// 同步更新原入站消息的推送状态
|
||||
if (parentId) {
|
||||
await InboxMessage.update(
|
||||
{
|
||||
push_status: 2,
|
||||
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
},
|
||||
{ where: { id: parentId } }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查当前消息的群/用户是否在屏蔽列表中。
|
||||
*
|
||||
* @return {Promise<boolean>} 是否已屏蔽。
|
||||
*/
|
||||
async isBlocked() {
|
||||
const { ctx } = this;
|
||||
const app = ctx.app;
|
||||
const groupName = String(ctx.inboxContext?.group_name || '').trim();
|
||||
const userName = String(ctx.inboxContext?.user_name || '').trim();
|
||||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||||
|
||||
if (!groupName && !userName) return false;
|
||||
|
||||
try {
|
||||
// 1. 尝试从缓存读取屏蔽列表
|
||||
const cacheKey = `inbox:block:${warehouseId}`;
|
||||
let blockedSet = await app.getCacheAsync(cacheKey);
|
||||
|
||||
if (!blockedSet || !(blockedSet instanceof Set)) {
|
||||
// 2. 缓存未命中,查库并填入缓存
|
||||
const { InboxBlock } = ctx.model;
|
||||
const rows = await InboxBlock.findAll({ attributes: [ 'group_name', 'user_name' ], raw: true });
|
||||
|
||||
blockedSet = new Set();
|
||||
for (const row of rows) {
|
||||
const g = String(row.group_name || '').trim();
|
||||
const u = String(row.user_name || '').trim();
|
||||
if (g && u) blockedSet.add(`${g}:${u}`);
|
||||
if (g) blockedSet.add(`${g}:*`);
|
||||
if (u) blockedSet.add(`*:${u}`);
|
||||
}
|
||||
|
||||
// TTL 5 分钟
|
||||
await app.setCacheAsync(cacheKey, blockedSet, 300);
|
||||
}
|
||||
|
||||
// 3. 检查当前消息是否命中屏蔽规则
|
||||
if (groupName && userName && blockedSet.has(`${groupName}:${userName}`)) return true;
|
||||
if (groupName && blockedSet.has(`${groupName}:*`)) return true;
|
||||
if (userName && blockedSet.has(`*:${userName}`)) return true;
|
||||
|
||||
return false;
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox processor] 屏蔽检查异常: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 失效屏蔽缓存,在新增屏蔽记录后调用。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async invalidateBlockCache(warehouseId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
await ctx.app.setCacheAsync(`inbox:block:${warehouseId}`, null, 0);
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox processor] 失效屏蔽缓存失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取仓库 ApiApp 回调地址。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<string|null>} 回调 URL,未配置时返回 null。
|
||||
*/
|
||||
async getApiAppCallbackUrl(warehouseId) {
|
||||
const { ctx } = this;
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const apiApp = await ctx.model.ApiApp.findOne({
|
||||
attributes: [ 'callback_url' ],
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
|
||||
is_enabled: 1,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return (apiApp && apiApp.callback_url) || null;
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`[inbox processor] 查询回调地址失败: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试从消息正文中提取仓库ID。
|
||||
* 子类或业务方可覆盖此方法以实现自定义解析逻辑。
|
||||
*
|
||||
* @param {string} content 消息正文。
|
||||
* @return {number|null} 仓库ID,无法解析时返回 null。
|
||||
*/
|
||||
extractWarehouseId(content) {
|
||||
// 默认不解析,由业务方覆盖
|
||||
void content;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试从消息正文中提取货主ID。
|
||||
* 子类或业务方可覆盖此方法以实现自定义解析逻辑。
|
||||
*
|
||||
* @param {string} content 消息正文。
|
||||
* @return {number|null} 货主ID,无法解析时返回 null。
|
||||
*/
|
||||
extractStoreId(content) {
|
||||
// 默认不解析,由业务方覆盖
|
||||
void content;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Egg.js 请求上下文中获取仓库ID。
|
||||
*
|
||||
* @return {number|null} 仓库ID。
|
||||
*/
|
||||
getWarehouseIdFromContext() {
|
||||
const { ctx } = this;
|
||||
const user = ctx.user || ctx.state?.user || {};
|
||||
const warehouseId = Number(user.store_id || user.warehouse_id) || null;
|
||||
return Number.isFinite(warehouseId) && warehouseId > 0 ? warehouseId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Egg.js 请求上下文中获取货主ID。
|
||||
*
|
||||
* @return {number|null} 货主ID。
|
||||
*/
|
||||
getStoreIdFromContext() {
|
||||
const { ctx } = this;
|
||||
const user = ctx.user || ctx.state?.user || {};
|
||||
const storeId = Number(user.store_id) || null;
|
||||
return Number.isFinite(storeId) && storeId > 0 ? storeId : null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxProcessorService;
|
||||
@ -2,157 +2,45 @@
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const { URL } = require('url');
|
||||
const { networkInterfaces } = require('os');
|
||||
|
||||
/** 推<>?body 大小上限<E4B88A>?4KB */
|
||||
const MAX_PUSH_BODY_SIZE = 64 * 1024;
|
||||
/** 最大重试次<E8AF95>?*/
|
||||
const MAX_RETRY_COUNT = 3;
|
||||
/** 僵尸恢复阈值:5分钟 */
|
||||
const ZOMBIE_RECOVERY_MINUTES = 5;
|
||||
/** 消息体大小上限 64KB */
|
||||
const MAX_BODY_SIZE = 64 * 1024;
|
||||
|
||||
/**
|
||||
* 收集本机所有内<EFBFBD>?IPv4 地址<EFBFBD>?
|
||||
* @return {string[]} 内网IP地址列表<EFBFBD>?
|
||||
*/
|
||||
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<EFBFBD>?
|
||||
* @param {string} ip IP地址<EFBFBD>?
|
||||
* @return {boolean} 是否为内网IP<EFBFBD>?
|
||||
*/
|
||||
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 安全性:仅允<EFBFBD>?https://,禁止内网IP<49>?
|
||||
* @param {string} urlStr 目标URL<EFBFBD>?
|
||||
* @throws {Error} URL 不合法时抛出<EFBFBD>?
|
||||
*/
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
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 格式不合<E4B88D>? ${urlStr}`);
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'https:') {
|
||||
throw new Error('target_url 仅允<E4BB85>?https:// 协议');
|
||||
}
|
||||
|
||||
const hostname = parsed.hostname || '';
|
||||
if (isInternalIp(hostname)) {
|
||||
throw new Error('target_url 不允许指向内网地址');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 站内信接收服务<EFBFBD>?
|
||||
* 统一处理消息入站:幂等去重、写库、异步推送、指数退避重试、僵尸恢复<EFBFBD>?
|
||||
* 站内信接收服务。
|
||||
* 统一处理消息入站:幂等去重、写库。
|
||||
* 暂不包含出站转发逻辑,纯入库管理。
|
||||
*/
|
||||
class InboxReceiverService extends Service {
|
||||
/**
|
||||
* 获取支持的目标渠道集合<EFBFBD>?
|
||||
* @return {Set<string>} 支持的目标渠道<EFBFBD>?
|
||||
*/
|
||||
static get SUPPORTED_CHANNELS() {
|
||||
return new Set([
|
||||
'webhook',
|
||||
'wecom',
|
||||
'dingtalk',
|
||||
'feishu',
|
||||
'warehouse_api',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化时执行僵尸恢复<EFBFBD>?
|
||||
* @param {Object} ctx Egg.js 上下文<EFBFBD>?
|
||||
*/
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// 异步执行僵尸恢复,不阻塞服务启动
|
||||
setImmediate(() => {
|
||||
this.recoverZombieMessages().catch(err => {
|
||||
ctx.logger.error(`[inbox] 僵尸恢复失败: ${err.message}`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一接收入口:幂等去重、写库、异步推送<EFBFBD>?
|
||||
* @param {Object} data 消息数据<EFBFBD>?
|
||||
* @param {string} data.ext_id 外部唯一消息主键<EFBFBD>?
|
||||
* @param {number} data.warehouse_id 所属仓库ID(服务端上下文注入,禁止外部传入)<EFBFBD>?
|
||||
* @param {number} [data.store_id] 关联货主ID<EFBFBD>?
|
||||
* @param {string} [data.direction='inbound'] 消息方向<EFBFBD>?
|
||||
* @param {number} [data.parent_id] 关联消息ID(回信时指向原消息)<EFBFBD>?
|
||||
* @param {string} data.source_type 来源类型:im / api / system<EFBFBD>?
|
||||
* @param {string} [data.source_extra] 来源附加信息<EFBFBD>?
|
||||
* @param {string} data.target_type 目标类型:im / api / webhook<EFBFBD>?
|
||||
* @param {string} data.target_channel 目标渠道<EFBFBD>?
|
||||
* @param {string} data.target_url 推送目标URL<EFBFBD>?
|
||||
* @param {string} [data.ref_code] 引用编码<EFBFBD>?
|
||||
* @param {Object} [data.ext_data] 透传数据<EFBFBD>?
|
||||
* @param {Object} [data.flags] 处理标记<EFBFBD>?
|
||||
* @return {Promise<{ok: boolean, id: number, ext_id: string}>} 接收结果<EFBFBD>?
|
||||
* 统一接收入口:幂等去重、写库。
|
||||
* @param {Object} data 消息数据。
|
||||
* @param {string} data.ext_id 外部唯一消息主键。
|
||||
* @param {number} data.warehouse_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.group_name] 群名称(外部传入)。
|
||||
* @param {string} [data.user_name] 用户名称(外部传入)。
|
||||
* @param {string} [data.group_id] 外部群ID。
|
||||
* @param {string} [data.user_id] 外部用户ID。
|
||||
* @param {string} [data.content] 消息正文/摘要。
|
||||
* @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;
|
||||
|
||||
// 安全边界:校<EFBFBD>?ext_id 不能为空
|
||||
// 安全边界:校验 ext_id 不能为空
|
||||
const extId = String(data.ext_id || '').trim();
|
||||
if (!extId) {
|
||||
throw new Error('ext_id 不能为空');
|
||||
}
|
||||
|
||||
// 安全边界:warehouse_id 必须由服务端上下文提<EFBFBD>?
|
||||
// 安全边界:warehouse_id 必须由服务端上下文提供
|
||||
const warehouseId = Number(data.warehouse_id);
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('warehouse_id 无效');
|
||||
@ -182,19 +70,10 @@ class InboxReceiverService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 校验 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(', ')}`);
|
||||
}
|
||||
|
||||
// 安全边界:校<EFBC9A>?target_url
|
||||
|
||||
// 幂等检查:ext_id 已存在则直接返回
|
||||
const exist = await InboxMessage.findOne({
|
||||
where: { ext_id: extId },
|
||||
attributes: [ 'id', 'ext_id', 'push_status' ],
|
||||
attributes: [ 'id', 'ext_id' ],
|
||||
paranoid: false,
|
||||
});
|
||||
|
||||
@ -207,69 +86,92 @@ class InboxReceiverService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 推<>?body 大小限制(序列化后检查)
|
||||
const pushBody = {
|
||||
// 消息体大小限制
|
||||
const checkBody = {
|
||||
content: data.content || null,
|
||||
ext_data: data.ext_data || null,
|
||||
};
|
||||
const bodySize = Buffer.byteLength(JSON.stringify(pushBody), 'utf8');
|
||||
if (bodySize > MAX_PUSH_BODY_SIZE) {
|
||||
throw new Error(`推<EFBFBD>?body 超过 64KB 限制(当<EFBC88>?${Math.round(bodySize / 1024)}KB)`);
|
||||
const bodySize = Buffer.byteLength(JSON.stringify(checkBody), 'utf8');
|
||||
if (bodySize > MAX_BODY_SIZE) {
|
||||
throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`);
|
||||
}
|
||||
|
||||
// 写库
|
||||
|
||||
// store_id 签约校验,若传入 store_id,必须存在有效合约关系
|
||||
const storeId = data.store_id ? Number(data.store_id) : null;
|
||||
if (storeId && Number.isFinite(storeId) && storeId > 0) {
|
||||
const contract = await ctx.model.StoreWarehouse.findOne({
|
||||
where: {
|
||||
store_id: storeId,
|
||||
warehouse_id: warehouseId,
|
||||
auth_status: 2,
|
||||
warehouse_use_status: 1,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
if (!contract) {
|
||||
throw new Error(`store_id=${storeId} 与仓库 ${warehouseId} 无有效签约关系`);
|
||||
// 从群绑定查询货主ID(外部不再直接传入 store_id)
|
||||
let storeId = null;
|
||||
const extGroupId = String(data.group_id || '').trim();
|
||||
if (extGroupId && warehouseId) {
|
||||
try {
|
||||
const group = await ctx.model.InboxGroup.findOne({
|
||||
attributes: [ 'store_id' ],
|
||||
where: { group_id: extGroupId, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
if (group && group.store_id) {
|
||||
storeId = Number(group.store_id);
|
||||
}
|
||||
} catch (groupErr) {
|
||||
ctx.logger.warn(`[inbox] 查找群货主失败: ${groupErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 写库(暂不触发异步转发)
|
||||
const record = await InboxMessage.create({
|
||||
ext_id: extId,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: data.store_id || null,
|
||||
store_id: storeId || null,
|
||||
direction,
|
||||
parent_id: parentId,
|
||||
source_type: sourceType,
|
||||
source_extra: data.source_extra || null,
|
||||
target_type: targetType,
|
||||
target_channel: targetChannel,
|
||||
group_name: data.group_name || null,
|
||||
user_name: data.user_name || null,
|
||||
group_id: data.group_id || null,
|
||||
user_id: data.user_id || null,
|
||||
content: data.content || 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 异步推送异<E98081>?ext_id=${extId}: ${err.message}`);
|
||||
// 异常已由 asyncPush 内部 try/catch,这里作为兜<E4B8BA>?
|
||||
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] 兜底更新推送状态失<E68081>?ext_id=${extId}: ${updateErr.message}`);
|
||||
}
|
||||
// 自动登记群(幂等 upsert)
|
||||
const groupName = String(data.group_name || '').trim();
|
||||
if (groupName) {
|
||||
try {
|
||||
await ctx.model.InboxGroup.findOrCreate({
|
||||
where: { group_name: groupName, warehouse_id: warehouseId },
|
||||
defaults: {
|
||||
group_id: extGroupId,
|
||||
store_id: storeId || null,
|
||||
source_type: sourceType,
|
||||
source_extra: data.source_extra || null,
|
||||
},
|
||||
});
|
||||
} catch (groupErr) {
|
||||
ctx.logger.warn(`[inbox] 群登记失败: ${groupErr.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// source_type 分流:API 来源异步回执
|
||||
if (sourceType === 'api') {
|
||||
setImmediate(() => {
|
||||
ctx.service.inbox.processor.handleApiMessage({
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
parent_id: record.id,
|
||||
ext_data: data.ext_data || null,
|
||||
ext_id: extId,
|
||||
content: data.content || '',
|
||||
group_name: data.group_name || null,
|
||||
user_name: data.user_name || null,
|
||||
group_id: data.group_id || null,
|
||||
user_id: data.user_id || null,
|
||||
}).catch(err => {
|
||||
ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
@ -277,133 +179,6 @@ class InboxReceiverService extends Service {
|
||||
ext_id: extId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步推<EFBFBD>?+ 指数退避重试<EFBFBD>?
|
||||
* @param {Object} record 消息记录(Sequelize Model 实例)<EFBFBD>?
|
||||
* @param {number} [attempt=0] 当前重试次数<EFBFBD>?
|
||||
* @return {Promise<void>} 推送结果<EFBFBD>?
|
||||
*/
|
||||
async asyncPush(record, attempt = 0) {
|
||||
const { ctx } = this;
|
||||
const { InboxMessage } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
try {
|
||||
// 乐观锁:<E99481>?push_status=0 或(重试<E9878D>?push_status=3)时可取<E58FAF>?
|
||||
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] 消息已被其他进程取走,跳过推<E8BF87>?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 <20>?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} 未实现`);
|
||||
}
|
||||
|
||||
// 执行推<E8A18C>?
|
||||
const response = await dispatchService.push(record);
|
||||
|
||||
// 推送成<E98081>?
|
||||
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] 推送成<E98081>?ext_id=${record.ext_id} channel=${channel}`);
|
||||
} catch (error) {
|
||||
const next = attempt + 1;
|
||||
ctx.logger.warn(`[inbox] 推送失<E98081>?ext_id=${record.ext_id} attempt=${next} error=${error.message}`);
|
||||
|
||||
// 更新失败状<E8B4A5>?
|
||||
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 <20>?60s <20>?120s
|
||||
if (next < MAX_RETRY_COUNT) {
|
||||
const delay = 30000 * Math.pow(2, attempt);
|
||||
ctx.logger.info(`[inbox] 将在 ${delay / 1000}s 后重<E5908E>?ext_id=${record.ext_id} attempt=${next}`);
|
||||
setTimeout(() => {
|
||||
this.asyncPush(record, next).catch(err => {
|
||||
ctx.logger.error(`[inbox] 重试推送异<E98081>?ext_id=${record.ext_id}: ${err.message}`);
|
||||
});
|
||||
}, delay);
|
||||
} else {
|
||||
ctx.logger.error(`[inbox] 推送达到最大重试次数,标记为终态失<E68081>?ext_id=${record.ext_id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 僵尸恢复:重置卡<EFBFBD>?推送中"超过5分钟的消息为"待推<EFBFBD>?<EFBFBD>?
|
||||
* 在服务启动时及定时任务中调用<EFBFBD>?
|
||||
* @return {Promise<number>} 恢复的消息数量<EFBFBD>?
|
||||
*/
|
||||
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] 僵尸恢复完成,重<EFBC8C>?${updatedCount} 条消息为待推送`);
|
||||
}
|
||||
|
||||
return updatedCount;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxReceiverService;
|
||||
|
||||
189
app/service/systemMethods/inbox.js
Normal file
189
app/service/systemMethods/inbox.js
Normal file
@ -0,0 +1,189 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 站内信系统方法层。
|
||||
* 提供需要用户权限的内部管理接口。
|
||||
*/
|
||||
class InboxSystemService extends MainService {
|
||||
/**
|
||||
* 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。
|
||||
* @return {{list: Function, disable: Function, update: Function, messages: Function, checkAuth: Function}}
|
||||
*/
|
||||
get group() {
|
||||
return {
|
||||
list: data => this.groupList(data),
|
||||
disable: data => this.groupDisable(data),
|
||||
update: data => this.groupUpdate(data),
|
||||
messages: data => this.groupMessages(data),
|
||||
checkAuth: (...args) => this.checkAuth(...args),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。
|
||||
* @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}}
|
||||
*/
|
||||
get message() {
|
||||
const { ctx } = this;
|
||||
return {
|
||||
list: data => {
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
return ctx.service.inbox.message.list({ warehouseId, ...data });
|
||||
},
|
||||
detail: data => {
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
return ctx.service.inbox.message.detail({ warehouseId, id: data.id });
|
||||
},
|
||||
thread: data => {
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
return ctx.service.inbox.message.thread({ warehouseId, id: data.id });
|
||||
},
|
||||
stats: data => {
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
return ctx.service.inbox.message.stats({ warehouseId, direction: data.direction });
|
||||
},
|
||||
checkAuth: (...args) => this.checkAuth(...args),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成货主绑群码。
|
||||
* 委托给 systems.store.bindCode 执行:校验 StoreWarehouse 合约 → 生成12位随机码 → 缓存300秒。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入,绑群码缓存 key 为 chat:bind:{warehouseId}:{code}。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.storeId 货主ID。
|
||||
* @param {string} [data.subType] 群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)。
|
||||
* @return {Promise<Object>} { code: 绑群码 }。
|
||||
*/
|
||||
async bindCode(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { storeId, subType } = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
return await ctx.service.systems.store.bindCode({
|
||||
storeId,
|
||||
warehouseId,
|
||||
subType,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取当前仓库的群列表。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
|
||||
* @param {string} [data.keyword] 群名称模糊搜索。
|
||||
* @param {number} [data.page] 页码。
|
||||
* @param {number} [data.pageSize] 每页条数。
|
||||
* @return {Promise<Object>} { total, list }。
|
||||
*/
|
||||
async groupList(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { groupType, keyword, page, pageSize } = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
return await ctx.service.systems.inbox.group.list({
|
||||
warehouseId,
|
||||
groupType,
|
||||
keyword,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用 / 解禁群。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.id 群记录主键ID(必填)。
|
||||
* @param {number} [data.isBlocked=1] 是否禁用 1=是 0=否。
|
||||
* @return {Promise<Object>} { message: 操作结果 }。
|
||||
*/
|
||||
async groupDisable(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { id, isBlocked } = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
await ctx.service.systems.inbox.group.disable({
|
||||
id,
|
||||
warehouseId,
|
||||
isBlocked: isBlocked === 0 ? 0 : 1,
|
||||
});
|
||||
|
||||
return { message: isBlocked === 0 ? '群已启用' : '群已禁用' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改群信息。
|
||||
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.id 群记录主键ID(必填)。
|
||||
* @param {string} [data.groupType] 群类型:store / warehouse / express。
|
||||
* @param {string} [data.subType] 群子类型。
|
||||
* @param {number} [data.storeId] 关联货主ID。
|
||||
* @param {number[]} [data.expressInterfaces] 快递接口ID数组(仅 express 生效)。
|
||||
* @param {string} [data.systemExpressCode] 系统快递编码(express 时必填)。
|
||||
* @return {Promise<Object>} { message: 操作结果 }。
|
||||
*/
|
||||
async groupUpdate(data = {}) {
|
||||
const { ctx } = this;
|
||||
const {
|
||||
id, groupType, subType, storeId,
|
||||
expressInterfaces, systemExpressCode, aiEnabled,
|
||||
} = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
await ctx.service.systems.inbox.group.update({
|
||||
id,
|
||||
warehouseId,
|
||||
groupType,
|
||||
subType,
|
||||
storeId,
|
||||
expressInterfaces,
|
||||
systemExpressCode,
|
||||
aiEnabled,
|
||||
});
|
||||
|
||||
return { message: '群信息修改成功' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取指定群的消息列表。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {string} data.groupId 群ID(必填)。
|
||||
* @param {string} [data.direction] 消息方向筛选:inbound / outbound。
|
||||
* @param {string} [data.keyword] 关键词搜索(ext_id / content)。
|
||||
* @param {number} [data.page] 页码。
|
||||
* @param {number} [data.pageSize] 每页条数。
|
||||
* @return {Promise<Object>} { list, pagination }。
|
||||
*/
|
||||
async groupMessages(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { groupId, direction, keyword, page, pageSize } = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
if (!groupId || typeof groupId !== 'string' || !groupId.trim()) {
|
||||
throw new Error('groupId 不能为空');
|
||||
}
|
||||
|
||||
return await ctx.service.inbox.message.list({
|
||||
warehouseId,
|
||||
groupId: groupId.trim(),
|
||||
direction,
|
||||
keyword,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxSystemService;
|
||||
@ -12732,7 +12732,7 @@ class WaveService extends OrderBaseService {
|
||||
try {
|
||||
const directFetchResult = await this.executeWaveStrategyDirectFetch({
|
||||
plan,
|
||||
waveBatchSource: 1,
|
||||
waveBatchSource: 0,
|
||||
});
|
||||
|
||||
this.ctx.logger.info('[wave.waveStrategyFetchAdmin] 建波成功', {
|
||||
|
||||
250
app/service/systems/inbox/group.js
Normal file
250
app/service/systems/inbox/group.js
Normal file
@ -0,0 +1,250 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* 站内信群管理业务逻辑层。
|
||||
* 提供群列表查询、禁用、修改等核心能力。
|
||||
*/
|
||||
class InboxGroupService extends Service {
|
||||
/**
|
||||
* 拉取当前仓库的群列表。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
|
||||
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
|
||||
* @param {string} [data.keyword] 按群名称模糊搜索。
|
||||
* @param {number} [data.page=1] 页码。
|
||||
* @param {number} [data.pageSize=20] 每页条数。
|
||||
* @return {Promise<Object>} { total, list }。
|
||||
*/
|
||||
async list(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxGroup } = ctx.model;
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
|
||||
const warehouseId = Number(data.warehouseId);
|
||||
const groupType = String(data.groupType || '').trim();
|
||||
const keyword = String(data.keyword || '').trim();
|
||||
const page = Math.max(1, Number(data.page) || 1);
|
||||
const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20));
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
if (!warehouseId) throw new Error('warehouseId 无效');
|
||||
|
||||
const where = { warehouse_id: warehouseId };
|
||||
if (groupType) where.group_type = groupType;
|
||||
if (keyword) where.group_name = { [Op.like]: `%${keyword}%` };
|
||||
|
||||
const { count, rows } = await InboxGroup.findAndCountAll({
|
||||
attributes: [
|
||||
'id', 'group_name', 'group_id', 'warehouse_id', 'store_id',
|
||||
'group_type', 'sub_type', 'source_type', 'source_extra',
|
||||
'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code',
|
||||
'created_at', 'updated_at',
|
||||
],
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
limit: pageSize,
|
||||
offset,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// express_interfaces 输出为数组
|
||||
const list = rows.map(row => ({
|
||||
...row,
|
||||
express_interfaces: row.express_interfaces
|
||||
? row.express_interfaces.split(',').map(Number).filter(Boolean)
|
||||
: [],
|
||||
}));
|
||||
|
||||
return { total: count, list };
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用 / 解禁群。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.id 群记录主键ID(必填)。
|
||||
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
|
||||
* @param {number} data.isBlocked 是否屏蔽 1=禁用 0=启用。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async disable(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxGroup } = ctx.model;
|
||||
|
||||
const id = Number(data.id);
|
||||
const warehouseId = Number(data.warehouseId);
|
||||
const isBlocked = data.isBlocked === 1 ? 1 : 0;
|
||||
|
||||
if (!id) throw new Error('群ID无效');
|
||||
if (!warehouseId) throw new Error('warehouseId 无效');
|
||||
|
||||
const [ affected ] = await InboxGroup.update(
|
||||
{ is_blocked: isBlocked },
|
||||
{ where: { id, warehouse_id: warehouseId } }
|
||||
);
|
||||
|
||||
if (!affected) {
|
||||
throw new Error('群不存在或无权限操作');
|
||||
}
|
||||
|
||||
ctx.logger.info(
|
||||
`[inbox group] ${isBlocked ? '禁用' : '启用'}群 id=${id} warehouse_id=${warehouseId}`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改群信息。
|
||||
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
|
||||
* 群类型切为 express 时 system_express_code 必填,
|
||||
* express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.id 群记录主键ID(必填)。
|
||||
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
|
||||
* @param {string} [data.groupType] 群类型:store / warehouse / express。
|
||||
* @param {string} [data.subType] 群子类型。
|
||||
* @param {number} [data.storeId] 关联货主ID。
|
||||
* @param {number[]} [data.expressInterfaces] 快递接口ID数组。
|
||||
* @param {string} [data.systemExpressCode] 系统快递编码。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async update(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { InboxGroup } = ctx.model;
|
||||
|
||||
const id = Number(data.id);
|
||||
const warehouseId = Number(data.warehouseId);
|
||||
|
||||
if (!id) throw new Error('群ID无效');
|
||||
if (!warehouseId) throw new Error('warehouseId 无效');
|
||||
|
||||
// 查群是否存在
|
||||
const group = await InboxGroup.findOne({
|
||||
attributes: [ 'id', 'group_type', 'group_id', 'warehouse_id' ],
|
||||
where: { id, warehouse_id: warehouseId },
|
||||
raw: true,
|
||||
});
|
||||
if (!group) throw new Error('群不存在或无权限操作');
|
||||
|
||||
// 目标群类型(优先新值,否则保留原值)
|
||||
const targetGroupType = data.groupType !== undefined
|
||||
? String(data.groupType).trim()
|
||||
: group.group_type || '';
|
||||
const isExpress = targetGroupType === 'express';
|
||||
|
||||
// express_interfaces 处理
|
||||
let expressInterfaces = null;
|
||||
if (data.expressInterfaces !== undefined) {
|
||||
if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length > 0) {
|
||||
// 校验快递接口ID有效性
|
||||
await this.validateExpressInterfaces(data.expressInterfaces);
|
||||
expressInterfaces = data.expressInterfaces.join(',');
|
||||
} else if (Array.isArray(data.expressInterfaces) && data.expressInterfaces.length === 0) {
|
||||
// 空数组 = 清空 = 表示全部快递类型
|
||||
expressInterfaces = '';
|
||||
} else {
|
||||
expressInterfaces = null; // 未传入 = 不修改
|
||||
}
|
||||
}
|
||||
|
||||
// system_express_code 校验
|
||||
let systemExpressCode;
|
||||
if (data.systemExpressCode !== undefined) {
|
||||
const code = String(data.systemExpressCode).trim();
|
||||
if (code) {
|
||||
await this.validateSystemExpressCode(code);
|
||||
systemExpressCode = code;
|
||||
} else {
|
||||
systemExpressCode = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 切换为 express 类型时 system_express_code 不能为空
|
||||
if (isExpress && data.groupType !== undefined) {
|
||||
const finalCode = systemExpressCode !== undefined ? systemExpressCode : group.system_express_code;
|
||||
if (!finalCode) {
|
||||
throw new Error('群类型为快递群时,系统快递编码不能为空');
|
||||
}
|
||||
}
|
||||
|
||||
// 构建更新字段
|
||||
const updateData = {};
|
||||
if (data.groupType !== undefined) updateData.group_type = targetGroupType || null;
|
||||
if (data.subType !== undefined) updateData.sub_type = String(data.subType || '').trim() || null;
|
||||
if (data.storeId !== undefined) {
|
||||
updateData.store_id = Number.isFinite(Number(data.storeId)) && Number(data.storeId) > 0
|
||||
? Number(data.storeId) : null;
|
||||
}
|
||||
// 非 express 群类型时忽略 express 相关字段
|
||||
if (isExpress && expressInterfaces !== null) {
|
||||
updateData.express_interfaces = expressInterfaces || null;
|
||||
}
|
||||
if (isExpress && systemExpressCode !== undefined) {
|
||||
updateData.system_express_code = systemExpressCode || null;
|
||||
}
|
||||
// AI 开关(所有群类型均支持)
|
||||
if (data.aiEnabled !== undefined) {
|
||||
updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0;
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
throw new Error('未提供任何需要修改的字段');
|
||||
}
|
||||
|
||||
await InboxGroup.update(updateData, { where: { id, warehouse_id: warehouseId } });
|
||||
ctx.logger.info(
|
||||
`[inbox group] 修改群 id=${id} fields=${Object.keys(updateData).join(',')}`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验快递接口ID数组的有效性。
|
||||
* 所有ID必须在 wms_express_interface 表中存在。
|
||||
*
|
||||
* @param {number[]} ids 快递接口ID数组。
|
||||
* @return {Promise<void>} 无效时抛出异常。
|
||||
*/
|
||||
async validateExpressInterfaces(ids) {
|
||||
const { ctx } = this;
|
||||
if (!Array.isArray(ids) || ids.length === 0) return;
|
||||
|
||||
const numericIds = ids.map(Number).filter(id => Number.isFinite(id) && id > 0);
|
||||
if (numericIds.length !== ids.length) {
|
||||
throw new Error('快递接口ID包含无效值');
|
||||
}
|
||||
|
||||
const count = await ctx.model.ExpressInterface.count({
|
||||
where: { id: { [ctx.app.Sequelize.Op.in]: numericIds } },
|
||||
});
|
||||
|
||||
if (count !== numericIds.length) {
|
||||
throw new Error('部分快递接口ID不存在');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验系统快递编码有效性。
|
||||
* 必须在 wms_express 表中存在对应的 code。
|
||||
*
|
||||
* @param {string} code 系统快递编码。
|
||||
* @return {Promise<void>} 无效时抛出异常。
|
||||
*/
|
||||
async validateSystemExpressCode(code) {
|
||||
const { ctx } = this;
|
||||
const trimmed = String(code).trim();
|
||||
if (!trimmed) throw new Error('系统快递编码不能为空');
|
||||
|
||||
const exists = await ctx.model.Express.count({
|
||||
where: { code: trimmed },
|
||||
});
|
||||
|
||||
if (!exists) {
|
||||
throw new Error(`系统快递编码 "${trimmed}" 不存在`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxGroupService;
|
||||
@ -1004,6 +1004,73 @@ class StoreService extends Service {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成货主绑群码。
|
||||
* 查询货主与仓库的有效合约,生成 12 位随机码并存入缓存(5分钟有效)。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.storeId 货主ID(必填)。
|
||||
* @param {number} data.warehouseId 仓库ID(必填,由 systemMethods 层注入)。
|
||||
* @param {string} [data.subType] 群子类型:after_sales / finance / receiving。
|
||||
* @return {Promise<Object>} { code: 绑群码 }。
|
||||
*/
|
||||
async bindCode(data = {}) {
|
||||
const { ctx } = this;
|
||||
const storeId = Number(data.storeId);
|
||||
const warehouseId = Number(data.warehouseId);
|
||||
|
||||
if (!Number.isFinite(storeId) || storeId <= 0) {
|
||||
throw new Error('storeId 无效');
|
||||
}
|
||||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||
throw new Error('缺少仓库信息,请确认已登录并选择了仓库');
|
||||
}
|
||||
|
||||
const contract = await ctx.model.StoreWarehouse.findOne({
|
||||
attributes: [ 'id', 'store_id', 'warehouse_id', 'initiator_subject_id' ],
|
||||
where: {
|
||||
store_id: storeId,
|
||||
warehouse_id: warehouseId,
|
||||
auth_status: 2,
|
||||
warehouse_use_status: 1,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!contract) {
|
||||
throw new Error(`货主 ${storeId} 在仓库 ${warehouseId} 无有效合约`);
|
||||
}
|
||||
|
||||
const subType = String(data.subType || '').trim();
|
||||
const VALID_SUB_TYPES = [ 'after_sales', 'finance', 'receiving' ];
|
||||
if (subType && !VALID_SUB_TYPES.includes(subType)) {
|
||||
throw new Error(`无效的子类型: ${subType},可选值: ${VALID_SUB_TYPES.join(' / ')}`);
|
||||
}
|
||||
|
||||
const code = Math.random().toString(36).slice(2, 8)
|
||||
.toUpperCase()
|
||||
+ Math.random().toString(36).slice(2, 8)
|
||||
.toUpperCase();
|
||||
const cacheKey = `chat:bind:${warehouseId}:${code}`;
|
||||
|
||||
const cacheValue = {
|
||||
store_id: contract.store_id,
|
||||
initiator_subject_id: contract.initiator_subject_id || null,
|
||||
warehouse_id: contract.warehouse_id,
|
||||
group_type: 'store',
|
||||
sub_type: subType || null,
|
||||
};
|
||||
|
||||
await ctx.app.setCacheAsync(cacheKey, cacheValue, 300);
|
||||
|
||||
ctx.logger.info(
|
||||
`[store bindCode] 生成绑群码 code=${code} ` +
|
||||
`store_id=${contract.store_id} warehouse_id=${warehouseId}`
|
||||
);
|
||||
|
||||
return { code };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = StoreService;
|
||||
|
||||
@ -29,10 +29,6 @@ class WarehouseInboxService extends MainService {
|
||||
throw new Error('requestId 不能为空');
|
||||
}
|
||||
|
||||
if (!body.targetChannel || !String(body.targetChannel).trim()) {
|
||||
throw new Error('targetChannel 不能为空');
|
||||
}
|
||||
|
||||
// 构造 ext_id
|
||||
const extId = `api:${String(appKey || 'unknown')}:${String(body.requestId).trim()}`;
|
||||
|
||||
@ -40,13 +36,16 @@ class WarehouseInboxService extends MainService {
|
||||
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,
|
||||
group_name: body.groupName || null,
|
||||
user_name: body.userName || null,
|
||||
group_id: body.groupId || null,
|
||||
user_id: body.userId || null,
|
||||
content: body.content || null,
|
||||
ext_data: body.extData || null,
|
||||
flags: body.flags || {},
|
||||
});
|
||||
|
||||
@ -65,18 +65,33 @@ module.exports = {
|
||||
},
|
||||
target_channel: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
|
||||
allowNull: true,
|
||||
comment: '目标渠道(仅供参考,出站路由由外部系统负责)',
|
||||
},
|
||||
target_url: {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: false,
|
||||
comment: '推送目标URL(IM Bot webhook 地址 / API 回调地址)',
|
||||
},
|
||||
ref_code: {
|
||||
group_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部引用编码,推送/回执时原样携带',
|
||||
comment: '群名称(外部传入)',
|
||||
},
|
||||
user_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '用户名称(外部传入)',
|
||||
},
|
||||
group_id: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部群ID',
|
||||
},
|
||||
user_id: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部用户ID',
|
||||
},
|
||||
content: {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '消息正文/摘要,用于列表展示和关键词搜索',
|
||||
},
|
||||
ext_data: {
|
||||
type: Sequelize.JSON,
|
||||
|
||||
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_message';
|
||||
const COLUMN_NAME = 'content';
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 为站内信消息表添加消息正文字段。
|
||||
* @param {Object} queryInterface Sequelize QueryInterface 实例。
|
||||
* @param {Object} Sequelize Sequelize 类。
|
||||
* @return {Promise<void>} 迁移执行结果。
|
||||
*/
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (columns[COLUMN_NAME]) return;
|
||||
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '消息正文/摘要,用于列表展示和关键词搜索',
|
||||
after: 'target_channel',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚:移除消息正文字段。
|
||||
* @param {Object} queryInterface Sequelize QueryInterface 实例。
|
||||
* @return {Promise<void>} 迁移回滚结果。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
},
|
||||
};
|
||||
57
database/migrations/20260804130000-create-inbox-block.js
Normal file
57
database/migrations/20260804130000-create-inbox-block.js
Normal file
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_block';
|
||||
|
||||
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: '主键',
|
||||
},
|
||||
group_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '群名称',
|
||||
},
|
||||
user_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '用户名称',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
});
|
||||
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'group_name', 'user_name' ], {
|
||||
unique: true,
|
||||
name: 'uk_group_user',
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚:删除站内信屏蔽表。
|
||||
* @param {Object} queryInterface Sequelize QueryInterface 实例。
|
||||
* @return {Promise<void>} 迁移回滚结果。
|
||||
*/
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
92
database/migrations/20260804140000-create-inbox-group.js
Normal file
92
database/migrations/20260804140000-create-inbox-group.js
Normal file
@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_group';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tables = await queryInterface.showAllTables();
|
||||
if (tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME)) return;
|
||||
|
||||
await queryInterface.createTable(TABLE_NAME, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
group_name: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: false,
|
||||
comment: '群名称',
|
||||
},
|
||||
group_id: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '外部群ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联货主ID',
|
||||
},
|
||||
group_type: {
|
||||
type: Sequelize.ENUM('store', 'warehouse', 'express'),
|
||||
allowNull: true,
|
||||
comment: '群类型: store=货主 warehouse=仓库 express=快递',
|
||||
},
|
||||
sub_type: {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: true,
|
||||
comment: '群子类型',
|
||||
},
|
||||
source_type: {
|
||||
type: Sequelize.STRING(20),
|
||||
allowNull: true,
|
||||
comment: '来源类型:im / api / system',
|
||||
},
|
||||
source_extra: {
|
||||
type: Sequelize.STRING(100),
|
||||
allowNull: true,
|
||||
comment: '来源附加信息',
|
||||
},
|
||||
is_blocked: {
|
||||
type: Sequelize.TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否屏蔽 0=否 1=是',
|
||||
},
|
||||
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, [ 'group_name', 'warehouse_id' ], {
|
||||
unique: true,
|
||||
name: 'uk_group_warehouse',
|
||||
});
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.dropTable(TABLE_NAME);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为 wms_inbox_group 添加快递相关字段:
|
||||
* - express_interfaces:快递接口ID列表(逗号分隔)
|
||||
* - system_express_code:系统快递编码
|
||||
*/
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const { STRING } = Sequelize;
|
||||
|
||||
// 检查列是否已存在
|
||||
const tableInfo = await queryInterface.describeTable('wms_inbox_group');
|
||||
|
||||
if (!tableInfo.express_interfaces) {
|
||||
await queryInterface.addColumn('wms_inbox_group', 'express_interfaces', {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '快递接口ID列表,逗号分隔(仅群类型为 express 时生效)',
|
||||
});
|
||||
}
|
||||
|
||||
if (!tableInfo.system_express_code) {
|
||||
await queryInterface.addColumn('wms_inbox_group', 'system_express_code', {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '系统快递编码(仅群类型为 express 时必填)',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
down: async (queryInterface) => {
|
||||
const tableInfo = await queryInterface.describeTable('wms_inbox_group');
|
||||
|
||||
if (tableInfo.express_interfaces) {
|
||||
await queryInterface.removeColumn('wms_inbox_group', 'express_interfaces');
|
||||
}
|
||||
if (tableInfo.system_express_code) {
|
||||
await queryInterface.removeColumn('wms_inbox_group', 'system_express_code');
|
||||
}
|
||||
},
|
||||
};
|
||||
73
database/migrations/20260805140000-add-inbox-indexes.js
Normal file
73
database/migrations/20260805140000-add-inbox-indexes.js
Normal file
@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为站内信消息表和群表补充查询索引。
|
||||
*
|
||||
* wms_inbox_message:
|
||||
* - idx_warehouse_group_created: (warehouse_id, group_id, created_at)
|
||||
* 用于按群拉取消息列表(最常用查询)。
|
||||
*
|
||||
* wms_inbox_group:
|
||||
* - idx_group_id: (group_id)
|
||||
* 用于 receiver/processor 中按 group_id 查找群。
|
||||
* - idx_warehouse_group_id: (warehouse_id, group_id)
|
||||
* 用于按仓库+群ID定位群。
|
||||
*/
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
// ── wms_inbox_message 索引 ──
|
||||
const msgTableInfo = await queryInterface.describeTable('wms_inbox_message');
|
||||
|
||||
// 检查已有索引(通过尝试添加,重复则忽略)
|
||||
try {
|
||||
await queryInterface.addIndex('wms_inbox_message', {
|
||||
fields: ['warehouse_id', 'group_id', 'created_at'],
|
||||
name: 'idx_warehouse_group_created',
|
||||
});
|
||||
console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已创建');
|
||||
} catch (e) {
|
||||
if (e.message && e.message.includes('Duplicate')) {
|
||||
console.log('[idx] wms_inbox_message.idx_warehouse_group_created 已存在,跳过');
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// ── wms_inbox_group 索引 ──
|
||||
try {
|
||||
await queryInterface.addIndex('wms_inbox_group', {
|
||||
fields: ['group_id'],
|
||||
name: 'idx_group_id',
|
||||
});
|
||||
console.log('[idx] wms_inbox_group.idx_group_id 已创建');
|
||||
} catch (e) {
|
||||
if (e.message && e.message.includes('Duplicate')) {
|
||||
console.log('[idx] wms_inbox_group.idx_group_id 已存在,跳过');
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await queryInterface.addIndex('wms_inbox_group', {
|
||||
fields: ['warehouse_id', 'group_id'],
|
||||
name: 'idx_warehouse_group_id',
|
||||
});
|
||||
console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已创建');
|
||||
} catch (e) {
|
||||
if (e.message && e.message.includes('Duplicate')) {
|
||||
console.log('[idx] wms_inbox_group.idx_warehouse_group_id 已存在,跳过');
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.removeIndex('wms_inbox_message', 'idx_warehouse_group_created');
|
||||
await queryInterface.removeIndex('wms_inbox_group', 'idx_group_id');
|
||||
await queryInterface.removeIndex('wms_inbox_group', 'idx_warehouse_group_id');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为 inbox.group.* 方法创建 API 权限记录。
|
||||
*
|
||||
* 固定 ID(当前 max_id=494):
|
||||
* 495 — inbox.group.list
|
||||
* 496 — inbox.group.disable
|
||||
* 497 — inbox.group.update
|
||||
* 498 — inbox.group.messages
|
||||
*/
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async up(queryInterface, Sequelize) {
|
||||
const methods = [
|
||||
[495, 'inbox.group.list'],
|
||||
[496, 'inbox.group.disable'],
|
||||
[497, 'inbox.group.update'],
|
||||
[498, 'inbox.group.messages'],
|
||||
];
|
||||
|
||||
for (const [id, method] of methods) {
|
||||
await queryInterface.sequelize.query(`
|
||||
INSERT INTO wms_permission (id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at)
|
||||
VALUES (${id}, '${method}', NULL, '${method}', NULL, 'API:${method}', NULL, 0, 0, NULL, 'api', 0, 1, NOW(), NOW())
|
||||
ON DUPLICATE KEY UPDATE path='${method}', meta_title='API:${method}', type='api'
|
||||
`);
|
||||
}
|
||||
|
||||
// 授权给客服组-主管及以上角色
|
||||
const newIdSuffix = ', 495, 496, 497, 498';
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = CONCAT(LEFT(permissions, LENGTH(permissions) - 1), '${newIdSuffix}]')
|
||||
WHERE id IN (8, 26, 28, 29)
|
||||
AND permissions != '*'
|
||||
AND permissions IS NOT NULL
|
||||
AND LENGTH(permissions) > 2
|
||||
`);
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
'DELETE FROM wms_permission WHERE id IN (495, 496, 497, 498)'
|
||||
);
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_role
|
||||
SET permissions = REPLACE(permissions, ', 495, 496, 497, 498', '')
|
||||
WHERE id IN (8, 26, 28, 29)
|
||||
`);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为 wms_inbox_message 新增 ai_thoughts 字段。
|
||||
* 存储 AI 多轮推理的思考过程数组。
|
||||
*/
|
||||
module.exports = {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const tableInfo = await queryInterface.describeTable('wms_inbox_message');
|
||||
if (!tableInfo.ai_thoughts) {
|
||||
await queryInterface.addColumn('wms_inbox_message', 'ai_thoughts', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: 'AI 多轮推理思考过程 [{round,action,function,params,reason,functionResult}]',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
down: async (queryInterface) => {
|
||||
const tableInfo = await queryInterface.describeTable('wms_inbox_message');
|
||||
if (tableInfo.ai_thoughts) {
|
||||
await queryInterface.removeColumn('wms_inbox_message', 'ai_thoughts');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_group';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (columns.ai_enabled) return;
|
||||
|
||||
await queryInterface.addColumn(TABLE_NAME, 'ai_enabled', {
|
||||
type: Sequelize.TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用AI自动回复: 0=关闭 1=开启',
|
||||
});
|
||||
},
|
||||
|
||||
down: async queryInterface => {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'ai_enabled');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_inbox_message';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
const columns = await queryInterface.describeTable(TABLE_NAME);
|
||||
if (!columns.target_channel) return;
|
||||
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'target_channel');
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'target_channel', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '目标渠道:wecom / dingtalk / feishu / warehouse_api / webhook',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -1,4 +1,21 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.06-inbox-bindCode",
|
||||
"date": "2026-08-06",
|
||||
"type": "added",
|
||||
"summary": "新增货主绑群码生成接口。校验 StoreWarehouse 合约有效性后生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。实现位于 systems/store.js → bindCode(),由 systemMethods/inbox.js → bindCode() 委托调用。",
|
||||
"methods": [
|
||||
"inbox.bindCode"
|
||||
],
|
||||
"notes": [
|
||||
"调用链:/system → systemMethods/inbox.bindCode → systems/store.bindCode。",
|
||||
"前置校验:StoreWarehouse 合约 auth_status=2 AND warehouse_use_status=1,不满足则返回500。",
|
||||
"缓存策略:app.setCacheAsync('chat:bind:{warehouseId}:{code}', { store_id, initiator_subject_id, warehouse_id, group_type, sub_type }, 300)。",
|
||||
"绑定时消费:processor.tryBindGroup 匹配 '授权:CODE' 模式,读取缓存执行绑定,成功即清缓存。",
|
||||
"warehouseId:从 ctx.user.store_id 自动注入,前端无需传递。"
|
||||
],
|
||||
"module": "inbox"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.05-inbox-group",
|
||||
"date": "2026-08-05",
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.18",
|
||||
"version": "0.3.19",
|
||||
"updatedAt": "2026-08-05",
|
||||
"headers": [
|
||||
{
|
||||
@ -31879,8 +31879,8 @@
|
||||
"module": "inbox",
|
||||
"list": [
|
||||
{
|
||||
"method": "inbox.list",
|
||||
"description": "站内信消息列表,按仓库/方向/状态/渠道筛选,支持关键词搜索(ext_id / ref_code),分页返回(默认20条/页,最大200条)",
|
||||
"method": "inbox.message.list",
|
||||
"description": "站内信消息列表,支持货主/群/用户名/正文/来源等多条件筛选,时间字段使用统一格式化输出,分页返回(默认20条/页,最大200条)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -31892,6 +31892,48 @@
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "storeId",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "货主ID筛选,支持逗号分隔多选,如 \"1000000,1000001\""
|
||||
},
|
||||
{
|
||||
"name": "groupId",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "群ID筛选,支持逗号分隔多选"
|
||||
},
|
||||
{
|
||||
"name": "groupName",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "群名称模糊搜索"
|
||||
},
|
||||
{
|
||||
"name": "userName",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "用户名模糊搜索"
|
||||
},
|
||||
{
|
||||
"name": "content",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "正文模糊搜索"
|
||||
},
|
||||
{
|
||||
"name": "sourceType",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "来源类型筛选:im / api / system"
|
||||
},
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
@ -31906,20 +31948,6 @@
|
||||
"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",
|
||||
@ -31942,7 +31970,7 @@
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "消息列表(不含 ext_data 和 push_response 大字段)",
|
||||
"description": "消息列表(不含 ext_data、push_response、target_channel 字段,时间已格式化)",
|
||||
"children": [
|
||||
{
|
||||
"name": "id",
|
||||
@ -31962,6 +31990,18 @@
|
||||
"required": true,
|
||||
"description": "所属仓库ID"
|
||||
},
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "关联货主ID"
|
||||
},
|
||||
{
|
||||
"name": "store_name",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "货主名称(批量回填)"
|
||||
},
|
||||
{
|
||||
"name": "direction",
|
||||
"type": "string",
|
||||
@ -31981,10 +32021,34 @@
|
||||
"description": "目标类型:im / api / webhook"
|
||||
},
|
||||
{
|
||||
"name": "target_channel",
|
||||
"name": "group_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "目标渠道"
|
||||
"required": false,
|
||||
"description": "外部群ID"
|
||||
},
|
||||
{
|
||||
"name": "group_name",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "群名称"
|
||||
},
|
||||
{
|
||||
"name": "user_id",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "外部用户ID"
|
||||
},
|
||||
{
|
||||
"name": "user_name",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "用户名称"
|
||||
},
|
||||
{
|
||||
"name": "content",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "消息正文/摘要"
|
||||
},
|
||||
{
|
||||
"name": "push_status",
|
||||
@ -32002,7 +32066,19 @@
|
||||
"name": "created_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "创建时间"
|
||||
"description": "创建时间(YYYY-MM-DD HH:mm:ss 格式化)"
|
||||
},
|
||||
{
|
||||
"name": "updated_at",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "更新时间(YYYY-MM-DD HH:mm:ss 格式化)"
|
||||
},
|
||||
{
|
||||
"name": "pushed_at",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "推送完成时间(YYYY-MM-DD HH:mm:ss 格式化)"
|
||||
}
|
||||
]
|
||||
},
|
||||
@ -32063,7 +32139,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.detail",
|
||||
"method": "inbox.message.detail",
|
||||
"description": "站内信消息详情,含完整 push_response 推送响应信息",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
@ -32186,7 +32262,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.thread",
|
||||
"method": "inbox.message.thread",
|
||||
"description": "站内信对话链查询,返回原消息 + 所有回信(按 parent_id 递归),按时间升序排列",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
@ -32231,7 +32307,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.reply",
|
||||
"method": "inbox.message.reply",
|
||||
"description": "系统回信:写入 outbound 记录 + 异步推送到目标渠道。自动继承原消息的 ext_data、ref_code 等字段",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
@ -32316,7 +32392,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.retry",
|
||||
"method": "inbox.message.retry",
|
||||
"description": "手动重推失败(push_status=3)的站内信消息,重置为待推送状态并触发异步推送",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
@ -32379,7 +32455,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "inbox.stats",
|
||||
"method": "inbox.message.stats",
|
||||
"description": "站内信推送统计:按方向汇总、按推送状态汇总、最近24小时新增数量",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
@ -32461,7 +32537,7 @@
|
||||
},
|
||||
{
|
||||
"method": "inbox.bindCode",
|
||||
"description": "生成货主绑群码。传入货主ID和子类型,生成5分钟有效12位随机码存入缓存",
|
||||
"description": "生成货主绑群码。校验 StoreWarehouse 合约有效后,生成12位随机码(大写字母+数字),缓存 key 为 chat:bind:{warehouseId}:{code},TTL 300秒。warehouseId 从 token 自动注入",
|
||||
"isNeedAuth": true,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -32478,14 +32554,14 @@
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "货主ID"
|
||||
"description": "货主ID(需在目标仓库有有效合约 auth_status=2 warehouse_use_status=1)"
|
||||
},
|
||||
{
|
||||
"name": "subType",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "群子类型编码:after_sales(售后) / finance(财务) / receiving(收货)"
|
||||
"description": "群子类型:after_sales(售后) / finance(财务) / receiving(收货)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -32493,13 +32569,13 @@
|
||||
"name": "code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "12位绑群随机码,5分钟有效"
|
||||
"description": "12位绑群随机码(大写字母+数字),5分钟有效"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "400",
|
||||
"message": "storeId 无效 / 缺少仓库信息"
|
||||
"message": "storeId 无效 / 缺少仓库信息 / 子类型无效"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
@ -32561,7 +32637,7 @@
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/express_interfaces(数组)/system_express_code/created_at"
|
||||
"description": "群记录列表,含id/group_name/group_id/store_id/group_type/sub_type/is_blocked/ai_enabled/express_interfaces(数组)/system_express_code/created_at"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
@ -32621,7 +32697,7 @@
|
||||
},
|
||||
{
|
||||
"method": "inbox.group.update",
|
||||
"description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码。切换为express类型时systemExpressCode必填,expressInterfaces仅express类型生效",
|
||||
"description": "修改群信息:群类型/子类型/货主/快递接口/系统快递编码/AI开关。aiEnabled支持灰度控制,切换为express类型时systemExpressCode必填",
|
||||
"isNeedAuth": true,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
@ -32674,6 +32750,13 @@
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "系统快递编码,groupType=express时必填。需校验wms_express.code存在"
|
||||
},
|
||||
{
|
||||
"name": "aiEnabled",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "是否启用AI自动回复: 0=关闭 1=开启,默认1(所有群类型均支持,用于灰度测试)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
|
||||
87
script/tmp-check-pending-migrations.cjs
Normal file
87
script/tmp-check-pending-migrations.cjs
Normal file
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations');
|
||||
|
||||
async function main() {
|
||||
// 1. 收集本地所有迁移文件
|
||||
const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort();
|
||||
console.log(`[本地] 迁移文件总数: ${allFiles.length}`);
|
||||
|
||||
// 2. 连接生产数据库
|
||||
const dbConfig = {
|
||||
host: '112.124.21.102',
|
||||
port: 3306,
|
||||
user: 'wms',
|
||||
password: 'P6j3YTHTpirepYWz',
|
||||
database: 'wms',
|
||||
};
|
||||
|
||||
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
dialect: 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
console.log('[DB] 生产数据库连接成功');
|
||||
} catch (e) {
|
||||
console.error('[DB] 生产数据库连接失败:', e.message);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// 3. 检查 SequelizeMeta 表是否存在
|
||||
let appliedNames = [];
|
||||
try {
|
||||
const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name');
|
||||
appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean);
|
||||
} catch (e) {
|
||||
console.error('[DB] 读取 SequelizeMeta 失败:', e.message);
|
||||
await sequelize.close();
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`);
|
||||
|
||||
// 4. 找出未执行的迁移
|
||||
const appliedSet = new Set(appliedNames);
|
||||
const pending = allFiles.filter(f => !appliedSet.has(f));
|
||||
const archived = allFiles.filter(f => f.startsWith('archive/'));
|
||||
|
||||
console.log(`\n========== 结果汇总 ==========`);
|
||||
console.log(`本地迁移文件总数: ${allFiles.length}`);
|
||||
console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`);
|
||||
console.log(`未执行 (pending): ${pending.length}`);
|
||||
console.log(`===============================\n`);
|
||||
|
||||
if (pending.length === 0) {
|
||||
console.log('✅ 所有迁移脚本均已执行,无 pending migration。');
|
||||
} else {
|
||||
console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`);
|
||||
pending.forEach((f, i) => {
|
||||
console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`);
|
||||
});
|
||||
|
||||
// 额外检查:有没有本地没有但 DB 已记录的(可能被删除了)
|
||||
const localSet = new Set(allFiles);
|
||||
const orphanInDb = appliedNames.filter(n => !localSet.has(n));
|
||||
if (orphanInDb.length > 0) {
|
||||
console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`);
|
||||
orphanInDb.forEach(n => console.log(` - ${n}`));
|
||||
}
|
||||
}
|
||||
|
||||
await sequelize.close();
|
||||
console.log('\n[DONE] 检查完成');
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('脚本执行异常:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user