366 lines
10 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;
const crypto = require('crypto');
/**
* 站内信查询/管理服务。
* 提供消息列表、详情、对话链、回复、重推、统计等管理功能。
*/
class InboxService extends Service {
/**
* 消息列表(按仓库/状态/方向筛选,分页)。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {string} [params.direction] 消息方向筛选:inbound / outbound。
* @param {number} [params.pushStatus] 推送状态筛选:0/1/2/3。
* @param {string} [params.targetChannel] 目标渠道筛选。
* @param {string} [params.keyword] 关键词搜索(ext_id / ref_code)。
* @param {number} [params.page=1] 页码。
* @param {number} [params.pageSize=20] 每页数量。
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
*/
async list(params = {}) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
const page = Math.max(1, Number(params.page) || 1);
const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20));
const where = {
warehouse_id: warehouseId,
deleted_at: null,
};
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') {
const status = Number(params.pushStatus);
if ([ 0, 1, 2, 3 ].includes(status)) {
where.push_status = status;
}
}
if (params.targetChannel && typeof params.targetChannel === 'string') {
where.target_channel = params.targetChannel.trim();
}
if (params.keyword && typeof params.keyword === 'string') {
const keyword = `%${params.keyword.trim()}%`;
where[Op.or] = [
{ ext_id: { [Op.like]: keyword } },
];
}
const { count: total, rows } = await InboxMessage.findAndCountAll({
attributes: {
exclude: [ 'ext_data', 'push_response' ],
},
where,
order: [[ 'created_at', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: pageSize,
});
return {
list: rows,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
hasPrevious: page > 1,
hasNext: page * pageSize < total,
},
};
}
/**
* 消息详情(含 push_response)。
* @param {Object} params 查询参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} 消息详情。
*/
async detail(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId, 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;
}
/**
* 系统回信:写入 outbound 记录 + 异步推送。
* @param {Object} data 回信数据。
* @param {number} data.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {number} data.parentId 原消息ID。
* @param {string} data.targetChannel 目标渠道。
* @param {string} data.targetUrl 推送目标URL。
* @param {string} [data.refCode] 引用编码。
* @param {Object} [data.extData] 透传数据。
* @param {Object} [data.flags] 处理标记。
* @return {Promise<Object>} 回信结果。
*/
async reply(data = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(data.warehouseId);
const parentId = Number(data.parentId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(parentId) || parentId <= 0) {
throw new Error('parentId 无效');
}
// 查找原消息
const parent = await InboxMessage.findOne({
where: { id: parentId, warehouse_id: warehouseId, deleted_at: null },
});
if (!parent) {
throw new Error('原消息不存在或无权访问');
}
const extId = `sys:${crypto.randomUUID()}`;
const result = await ctx.service.inbox.receiver.receive({
ext_id: extId,
warehouse_id: warehouseId,
store_id: parent.store_id,
direction: 'outbound',
parent_id: parentId,
source_type: 'system',
source_extra: null,
target_type: data.targetType || parent.target_type,
target_channel: data.targetChannel,
target_url: data.targetUrl,
ref_code: data.refCode || parent.ref_code,
ext_data: data.extData || parent.ext_data,
flags: data.flags || {},
});
return result;
}
/**
* 手动重推。
* @param {Object} params 重推参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {number} params.id 消息ID。
* @return {Promise<Object>} 重推结果。
*/
async retry(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const warehouseId = Number(params.warehouseId);
const id = Number(params.id);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
if (!Number.isFinite(id) || id <= 0) {
throw new Error('消息ID无效');
}
const record = await InboxMessage.findOne({
where: { id, warehouse_id: warehouseId },
});
if (!record) {
throw new Error('消息不存在或无权访问');
}
if (![ 3 ].includes(record.push_status)) {
throw new Error('仅失败状态的消息可以手动重推');
}
// 重置为待推送状态,由异步推送接管
await record.update({
push_status: 0,
push_started_at: null,
});
// 触发异步推送
setImmediate(() => {
ctx.service.inbox.receiver.asyncPush(record, 0).catch(err => {
ctx.logger.error(`[inbox] 手动重推异常 ext_id=${record.ext_id}: ${err.message}`);
});
});
return {
ok: true,
id: record.id,
ext_id: record.ext_id,
message: '已触发重推',
};
}
/**
* 推送统计(按仓库 + 状态汇总)。
* @param {Object} params 统计参数。
* @param {number} params.warehouseId 仓库ID(必填)。
* @param {string} [params.direction] 消息方向筛选。
* @return {Promise<Object>} 统计结果。
*/
async stats(params = {}) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(params.warehouseId);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw new Error('warehouseId 无效');
}
const where = {
warehouse_id: warehouseId,
};
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
where.direction = params.direction;
}
// 按方向统计
const directionStats = await InboxMessage.findAll({
attributes: [
'direction',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
],
where,
group: [ 'direction' ],
raw: true,
});
// 按推送状态统计
const statusStats = await InboxMessage.findAll({
attributes: [
'push_status',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
],
where,
group: [ 'push_status' ],
raw: true,
});
// 最近24小时统计
const recentWhere = {
...where,
created_at: {
[Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000),
},
};
const recentCount = await InboxMessage.count({ where: recentWhere });
return {
total_by_direction: directionStats,
total_by_status: statusStats,
recent_24h_count: recentCount,
};
}
}
module.exports = InboxService;