WMS_MAIN/app/service/inbox/receiver.js
liufumingren 3c0c7634c5 fix(inbox): notify.reply 按群/消息来源应用路由回执
同一仓库存在多个仓库级 API 应用且都勾选 notify.reply 时,回执按 id 升序逐个尝试,
可能被首个返回 200 的其它适配器接走,导致错投且被记为已送达。

- receiver: 群已存在时补写空白的 source_type/source_extra,来源不一致仅告警不覆盖
- processor: 回执来源优先级改为 群(wms_inbox_group) → 入站消息 → ext_id 解析,
  来源应用承接时只发给它;来源缺失或未承接时保持原候选顺序并告警
- warehouseNotify: push 支持 preferredAppKey,系统通知按群来源应用发送

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-10 02:42:25 +08:00

250 lines
9.1 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] 处理标记。
* @param {number} [data.send_time] 消息原始发送时间(毫秒时间戳,可选,用于历史消息过滤)。
* @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)`);
}
// flags 合并:消息发送时间统一存入 flags.send_time(毫秒),供 AI 历史消息过滤
const flags = { ...(data.flags || {}) };
if (!flags.send_time && data.send_time != null) {
const sendTime = Number(data.send_time);
if (Number.isFinite(sendTime) && sendTime > 0) {
flags.send_time = Math.floor(sendTime);
}
}
// 从群绑定查询货主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,
});
ctx.logger.info(`[inbox] 消息入库成功 ext_id=${extId} id=${record.id}`);
// 自动登记群:优先按 (group_id, warehouse_id) 幂等 upsert。
// 群ID不变、仅名称变化时只更新名称,不重复建群。
const groupName = String(data.group_name || '').trim();
if (groupName) {
try {
if (extGroupId) {
const group = await ctx.model.InboxGroup.findOne({
where: { group_id: extGroupId, warehouse_id: warehouseId },
});
if (group) {
// 群已存在:名称变化时更新名称,不新建。
// 来源字段为空时补写(用于出站 notify.reply 按来源应用路由);
// 已有来源且与本次不一致时不覆盖,避免多应用共用群时归属被反复改写。
const patch = {};
const oldName = group.group_name;
if (oldName !== groupName) {
patch.group_name = groupName;
}
if (!group.source_type && sourceType) {
patch.source_type = sourceType;
}
if (!group.source_extra && data.source_extra) {
patch.source_extra = data.source_extra;
}
if (Object.keys(patch).length > 0) {
await group.update(patch);
}
if (patch.group_name) {
ctx.logger.info(
`[inbox] 群名称已更新 group_id=${extGroupId}: ${oldName} → ${groupName}`
);
}
if (group.source_extra && data.source_extra
&& String(group.source_extra) !== String(data.source_extra)) {
ctx.logger.warn(
`[inbox] 群来源不一致 group_id=${extGroupId} existing=${group.source_extra} incoming=${data.source_extra}`
);
}
} else {
// 群ID不存在:按群ID直接新建(群以ID为准,不按名称匹配既有群)
await ctx.model.InboxGroup.create({
group_name: groupName,
group_id: extGroupId,
warehouse_id: warehouseId,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
});
ctx.logger.info(
`[inbox] 新建群记录 group_id=${extGroupId} name=${groupName}`
);
}
} else {
// 无群ID:按 (group_name, warehouse_id) 幂等登记(向后兼容)
await ctx.model.InboxGroup.findOrCreate({
where: { group_name: groupName, warehouse_id: warehouseId },
defaults: {
group_id: null,
store_id: storeId || null,
source_type: sourceType,
source_extra: data.source_extra || null,
ai_enabled: 0,
},
});
}
} 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,
flags,
}).catch(err => {
ctx.logger.error(`[inbox] API 异步回执异常 ext_id=${extId}: ${err.message}`);
});
});
}
return {
ok: true,
id: record.id,
ext_id: extId,
};
}
}
module.exports = InboxReceiverService;