WMS_MAIN/app/service/inbox/receiver.js
liufumingren e61efbb66a 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修复
2026-08-06 17:40:36 +08:00

185 lines
6.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

'use strict';
const Service = require('egg').Service;
/** 消息体大小上限 64KB */
const MAX_BODY_SIZE = 64 * 1024;
/**
* 站内信接收服务。
* 统一处理消息入站:幂等去重、写库。
* 暂不包含出站转发逻辑,纯入库管理。
*/
class InboxReceiverService extends Service {
/**
* 统一接收入口:幂等去重、写库。
* @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;
// 安全边界:校验 ext_id 不能为空
const extId = String(data.ext_id || '').trim();
if (!extId) {
throw new Error('ext_id 不能为空');
}
// 安全边界:warehouse_id 必须由服务端上下文提供
const warehouseId = Number(data.warehouse_id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouse_id 无效');
}
// 枚举校验:direction
const VALID_DIRECTIONS = [ 'inbound', 'outbound' ];
const direction = VALID_DIRECTIONS.includes(data.direction) ? data.direction : 'inbound';
// 枚举校验:source_type
const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ];
const sourceType = VALID_SOURCE_TYPES.includes(data.source_type) ? data.source_type : (data.source_type || 'api');
// 枚举校验:target_type
const VALID_TARGET_TYPES = [ 'im', 'api', 'webhook' ];
const targetType = VALID_TARGET_TYPES.includes(data.target_type) ? data.target_type : (data.target_type || 'im');
// parent_id 存在性校验
const parentId = data.parent_id ? Number(data.parent_id) : null;
if (parentId) {
const parentExists = await InboxMessage.findOne({
where: { id: parentId, warehouse_id: warehouseId },
attributes: [ 'id' ],
});
if (!parentExists) {
throw new Error(`parent_id=${parentId} 对应的消息不存在`);
}
}
// 幂等检查:ext_id 已存在则直接返回
const exist = await InboxMessage.findOne({
where: { ext_id: extId },
attributes: [ 'id', 'ext_id' ],
paranoid: false,
});
if (exist) {
ctx.logger.info(`[inbox] 消息已存在,跳过入库 ext_id=${extId} id=${exist.id}`);
return {
ok: true,
id: exist.id,
ext_id: extId,
};
}
// 消息体大小限制
const checkBody = {
content: data.content || null,
ext_data: data.ext_data || null,
};
const bodySize = Buffer.byteLength(JSON.stringify(checkBody), 'utf8');
if (bodySize > MAX_BODY_SIZE) {
throw new Error(`消息体超过 64KB 限制(当前 ${Math.round(bodySize / 1024)}KB)`);
}
// 从群绑定查询货主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: storeId || null,
direction,
parent_id: parentId,
source_type: sourceType,
source_extra: data.source_extra || null,
target_type: targetType,
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 || {},
});
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
// 自动登记群(幂等 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,
id: record.id,
ext_id: extId,
};
}
}
module.exports = InboxReceiverService;