新增功能: - 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修复
336 lines
10 KiB
JavaScript
336 lines
10 KiB
JavaScript
'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;
|