feat(inbox): 站内信分组快速列表与多群成员聚合,支持 groupIds 数组入参

This commit is contained in:
liufumingren 2026-08-30 07:28:05 +08:00
parent 3100bddce1
commit 0a54f8028b
4 changed files with 413 additions and 2 deletions

View File

@ -9,11 +9,13 @@ const MainService = require('../main');
class InboxSystemService extends MainService {
/**
* 群管理子入口,供 /system dispatcher 按 inbox.group.* 路径访问。
* @return {{list: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}}
* @return {{list: Function, quickList: Function, members: Function, disable: Function, update: Function, reset: Function, messages: Function, checkAuth: Function}} 群管理子入口方法集合。
*/
get group() {
return {
list: data => this.groupList(data),
quickList: data => this.groupQuickList(data),
members: data => this.groupMembers(data),
disable: data => this.groupDisable(data),
update: data => this.groupUpdate(data),
reset: data => this.groupReset(data),
@ -24,7 +26,7 @@ class InboxSystemService extends MainService {
/**
* 消息管理子入口,供 /system dispatcher 按 inbox.message.* 路径访问。
* @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}}
* @return {{list: Function, detail: Function, thread: Function, reply: Function, stats: Function, checkAuth: Function}} 消息管理子入口方法集合。
*/
get message() {
const { ctx } = this;
@ -100,6 +102,61 @@ class InboxSystemService extends MainService {
});
}
/**
* 群快速查询(下拉选择用,不分页)。
* 双维度可选过滤,均不传时返回所有仓库/货主的群:
* - store_id:货主维度,透传为底层参数 storeId;
* - warehouse_id:仓库维度,透传为底层参数 warehouseId;
* - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。
*
* @param {Object} data 请求数据。
* @param {string} [data.keyword] 关键词,模糊匹配群名称与外部群ID。
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
* @param {number} [data.limit=20] 返回条数上限,最大 100。
* @param {number|string} [data.store_id] 货主ID(可选,对应 wms_inbox_group.store_id 列)。
* @param {number|string} [data.warehouse_id] 仓库ID(可选,对应 wms_inbox_group.warehouse_id 列)。
* @return {Promise<Object>} { list: 群快速列表 }。
*/
async groupQuickList(data = {}) {
const { ctx } = this;
const {
keyword, groupType, limit,
store_id: storeId,
warehouse_id: warehouseId,
} = data;
return await ctx.service.systems.inbox.group.quickList({
storeId,
warehouseId,
keyword,
groupType,
limit,
});
}
/**
* 查询一个或多个群的成员列表(下拉选择用,多群聚合)。
* warehouseId 从 ctx.user.store_id 自动注入,不信任前端传值。
*
* @param {Object} data 请求数据。
* @param {Array<number|string>} data.groupIds 群内部主键ID数组(必填,非空且每个元素为正整数)。
* @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。
* @param {number} [data.limit=20] 返回条数上限,最大 100。
* @return {Promise<Object>} { list: 群成员列表 }。
*/
async groupMembers(data = {}) {
const { ctx } = this;
const { groupIds, keyword, limit } = data;
const warehouseId = Number(ctx.user?.store_id || 0);
return await ctx.service.systems.inbox.group.members({
groupIds,
warehouseId,
keyword,
limit,
});
}
/**
* 禁用 / 解禁群。
* warehouseId 从 ctx.user.store_id 自动注入。

View File

@ -193,6 +193,180 @@ class InboxGroupService extends Service {
return { total: count, list };
}
/**
* 群快速查询(下拉选择用,不分页)。
* 关键词同时模糊匹配群名称与外部群ID,按创建时间倒序返回轻量字段,
* 软删除记录由 paranoid 自动排除。
* 双维度可选过滤,均不传时 where 不含这两列、返回所有仓库/货主的群:
* - store_id(货主维度)↔ wms_inbox_group.store_id 列;
* - warehouse_id(仓库维度)↔ wms_inbox_group.warehouse_id 列;
* - 两者可同时传(AND 关系),也可都不传(不加对应过滤条件)。
*
* @param {Object} data 请求数据。
* @param {number|string} [data.storeId] 货主ID(可选,来自 API 入参 store_id,映射到 wms_inbox_group.store_id 列;
* 传入时须为可解析的正整数,否则抛错「store_id 无效」;不传或为空时不加货主过滤)。
* @param {number|string} [data.warehouseId] 仓库ID(可选,来自 API 入参 warehouse_id,映射到 wms_inbox_group.warehouse_id 列;
* 传入时须为可解析的正整数,否则抛错「warehouse_id 无效」;不传或为空时不加仓库过滤)。
* @param {string} [data.keyword] 关键词,模糊匹配 group_name / group_id。
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
* @param {number} [data.limit=20] 返回条数上限,最大 100。
* @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number}>}>} 群快速列表。
*/
async quickList(data = {}) {
const { ctx } = this;
const { InboxGroup } = ctx.model;
const { Op } = ctx.app.Sequelize;
const keyword = String(data.keyword || '').trim();
const groupType = String(data.groupType || '').trim();
const limit = Math.min(100, Math.max(1, Number(data.limit) || 20));
const where = {};
// store_id(货主维度,对应 wms_inbox_group.store_id 列)可选:
// 传入时校验为可解析的正整数,设置 where.store_id;不传或为空串时不加货主过滤
const storeIdRaw = String(data.storeId ?? '').trim();
if (storeIdRaw) {
const storeId = Number(storeIdRaw);
if (!Number.isInteger(storeId) || storeId <= 0) throw new Error('store_id 无效');
where.store_id = storeId;
}
// warehouse_id(仓库维度,对应 wms_inbox_group.warehouse_id 列)可选:
// 传入时校验为可解析的正整数,设置 where.warehouse_id;不传或为空串时不加仓库过滤
const warehouseIdRaw = String(data.warehouseId ?? '').trim();
if (warehouseIdRaw) {
const warehouseId = Number(warehouseIdRaw);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) throw new Error('warehouse_id 无效');
where.warehouse_id = warehouseId;
}
if (groupType) where.group_type = groupType;
if (keyword) {
where[Op.or] = [
{ group_name: { [Op.like]: `%${keyword}%` } },
{ group_id: { [Op.like]: `%${keyword}%` } },
];
}
const rows = await InboxGroup.findAll({
attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked' ],
where,
order: [[ 'created_at', 'DESC' ]],
limit,
raw: true,
});
return { list: rows };
}
/**
* 查询一个或多个群的成员列表(下拉选择用,多群聚合)。
* 先用内部主键数组 + 仓库批量校验群存在(软删自动排除,attributes 只取 id/group_id,
* 找不到任何匹配群抛「群不存在或无权限操作」),再收集所有群的外部群ID(去重、剔除空值),
* 按外部群ID集合在消息表中聚合去重成员:取每个 user_id 最新一条消息的 user_name
* (消息按 id 倒序,首次出现的即最新),关键词在聚合后对 user_name / user_id 做包含匹配,
* 最后截断到 limit 条。外部群ID集合为空时直接返回空列表。
* 局限说明:多群共享同一聚合池,最多取最近 500 条消息,更早消息中的成员不会出现在结果中;
* user_id 为 NULL / 空串的消息被排除;关键词匹配大小写不敏感。
*
* @param {Object} data 请求数据。
* @param {Array<number|string>} data.groupIds wms_inbox_group 内部主键ID数组(必填,非空且每个元素为正整数)。
* @param {number} data.warehouseId 仓库ID(必填,由 controller 注入)。
* @param {string} [data.keyword] 关键词,模糊匹配 user_name / user_id。
* @param {number} [data.limit=20] 返回条数上限,最大 100。
* @return {Promise<{list: Array<{user_id: string, user_name: string}>}>} 群成员列表。
*/
async members(data = {}) {
const { ctx } = this;
const { InboxGroup, InboxMessage } = ctx.model;
const { Op } = ctx.app.Sequelize;
const warehouseId = Number(data.warehouseId);
if (!warehouseId) throw new Error('warehouseId 无效');
// groupIds 校验:非空数组且每个元素为数字或可解析数字字符串的正整数
const rawGroupIds = data.groupIds;
if (!Array.isArray(rawGroupIds) || rawGroupIds.length === 0) {
throw new Error('groupIds 无效');
}
const groupIds = rawGroupIds.map(item => {
if (typeof item !== 'number' && typeof item !== 'string') return NaN;
return Number(item);
});
if (groupIds.some(id => !Number.isInteger(id) || id <= 0)) {
throw new Error('groupIds 无效');
}
// 批量校验群存在(软删自动排除),attributes 只取 id / group_id
const groups = await InboxGroup.findAll({
attributes: [ 'id', 'group_id' ],
where: { id: { [Op.in]: groupIds }, warehouse_id: warehouseId },
raw: true,
});
if (!groups || groups.length === 0) {
throw new Error('群不存在或无权限操作');
}
// 收集所有群的外部群ID(去重、剔除空值),全部为空则没有可关联的消息成员
const externalGroupIds = [ ...new Set(
groups.map(g => String(g.group_id || '').trim()).filter(Boolean)
) ];
if (externalGroupIds.length === 0) {
return { list: [] };
}
const keyword = String(data.keyword || '').trim();
const limit = Math.min(100, Math.max(1, Number(data.limit) || 20));
// 拉取多群最近消息集合(软删除由 paranoid 自动排除),共享同一聚合池。
// 局限说明:聚合池最多取最近 500 条消息,更早消息中的成员不会出现在结果中。
// user_id 同时排除 NULL 与空串(用字段级 Op.and 避免同名键覆盖),
// 防止脏数据进入聚合池并输出 "null"/"" 成员。
const messages = await InboxMessage.findAll({
attributes: [ 'id', 'user_id', 'user_name' ],
where: {
warehouse_id: warehouseId,
group_id: { [Op.in]: externalGroupIds },
user_id: {
[Op.and]: [
{ [Op.ne]: null },
{ [Op.ne]: '' },
],
},
},
order: [[ 'id', 'DESC' ]],
limit: 500,
raw: true,
});
// 按 user_id 去重:消息已按 id 倒序,首次出现即该用户最新消息。
// JS 层兜底:跳过 null/undefined user_id,防止 String(null) 变成 "null" 输出。
const memberMap = new Map();
for (const msg of messages) {
if (msg.user_id === null || msg.user_id === undefined) continue;
const userId = String(msg.user_id).trim();
if (!userId || memberMap.has(userId)) continue;
memberMap.set(userId, String(msg.user_name || '').trim());
}
let list = Array.from(memberMap.entries())
.map(([ user_id, user_name ]) => ({ user_id, user_name }));
// 关键词在聚合结果上过滤 user_name / user_id:
// 统一转小写后做包含匹配,与 quickList 的 SQL LIKE(MySQL 默认大小写不敏感)语义一致
if (keyword) {
const lowerKeyword = keyword.toLowerCase();
list = list.filter(item => {
const userName = String(item.user_name || '').toLowerCase();
const userId = String(item.user_id || '').toLowerCase();
return userName.includes(lowerKeyword) || userId.includes(lowerKeyword);
});
}
return { list: list.slice(0, limit) };
}
/**
* 禁用 / 解禁群。
*

View File

@ -0,0 +1,121 @@
'use strict';
/**
* 为群选择 / 群成员选择下拉接口创建 API 权限记录并授权。
*
* 权限明细(固定 ID,当前迁移内 max_id=565):
* 566 — inbox.group.quickList API:群快速查询
* 567 — inbox.group.members API:群成员列表
*
* 角色授权(客服组-主管及以上):
* 26(仓库组-主管) → 28(客服组-主管) → 29(生产组-主管) → 8(经理)
* 超级管理员(7)/仓库管理员(2) 已持有 * 通配符,自动拥有,无需处理
*
* 幂等:INSERT IGNORE 创建权限记录;角色权限数组追加后去重排序,已存在跳过。
*/
const TABLE = 'wms_permission';
const ROLE_TABLE = 'wms_role';
const COLUMNS = 'id, path, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, type, sort, status, created_at, update_at';
/** 权限ID → 授权角色ID列表(不含通配符角色) */
const PERMISSION_ROLES = {
566: [ 26, 28, 29, 8 ],
567: [ 26, 28, 29, 8 ],
};
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
// ── 1. 创建 API 权限记录(固定 ID)──
const apis = [
[ 566, 'inbox.group.quickList', 'API:群快速查询' ],
[ 567, 'inbox.group.members', 'API:群成员列表' ],
];
for (const [ id, path, metaTitle ] of apis) {
await queryInterface.sequelize.query(
`INSERT IGNORE INTO \`${TABLE}\` (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
{ replacements: [ id, path, null, path, null, metaTitle, null, 0, 0, null, 'api', 0, 1 ] }
);
}
// ── 2. 角色授权注入 ──
for (const permId of Object.keys(PERMISSION_ROLES).map(Number)) {
for (const roleId of PERMISSION_ROLES[permId]) {
const rows = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
);
const record = Array.isArray(rows) ? rows[0] : null;
if (!record) {
continue;
}
// 通配符角色跳过
if (record.permissions === '*') {
continue;
}
let perms;
try {
perms = typeof record.permissions === 'string'
? JSON.parse(record.permissions)
: record.permissions;
} catch (e) {
perms = null;
}
if (!Array.isArray(perms)) {
continue;
}
if (!perms.includes(permId)) {
perms.push(permId);
perms.sort((a, b) => Number(a) - Number(b));
await queryInterface.sequelize.query(
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
{ replacements: [ JSON.stringify(perms), roleId ] }
);
}
}
}
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.sequelize.query(
'DELETE FROM `wms_permission` WHERE id IN (566, 567)'
);
const permIds = [ 566, 567 ];
for (const roleId of Object.values(PERMISSION_ROLES).flat()) {
const rows = await queryInterface.sequelize.query(
`SELECT id, permissions FROM \`${ROLE_TABLE}\` WHERE id = ?`,
{ replacements: [ roleId ], type: queryInterface.sequelize.QueryTypes.SELECT }
);
const record = Array.isArray(rows) ? rows[0] : null;
if (!record || record.permissions === '*') {
continue;
}
let perms;
try {
perms = typeof record.permissions === 'string'
? JSON.parse(record.permissions)
: record.permissions;
} catch (e) {
perms = null;
}
if (!Array.isArray(perms) || !perms.some(p => permIds.includes(p))) {
continue;
}
perms = perms.filter(p => !permIds.includes(p));
await queryInterface.sequelize.query(
`UPDATE \`${ROLE_TABLE}\` SET permissions = ? WHERE id = ?`,
{ replacements: [ JSON.stringify(perms), roleId ] }
);
}
},
};

View File

@ -0,0 +1,59 @@
'use strict';
/**
* 为站内信群表补充货主维度查询索引。
*
* 背景:inbox.group.quickList 接口支持双维度过滤:
* - store_id(货主维度)→ wms_inbox_group.store_id 列
* - warehouse_id(仓库维度)→ wms_inbox_group.warehouse_id 列
* 两者可单独或同时(AND)过滤。store_id 列此前无索引,
* 单独按货主过滤或与仓库 AND 过滤时会走全表扫描。
*
* wms_inbox_group:
* - idx_store_id: (store_id)
* 用于按货主维度过滤群列表。warehouse_id 维度已由唯一索引
* uk_warehouse_group_id(warehouse_id, group_id) 的前导列覆盖,无需新增仓库单列索引;
* 双条件 AND 场景由 idx_store_id 与 uk_warehouse_group_id 组合命中,
* 群表数据量小,单列索引已足够,不引入复合索引以控制索引维护成本。
*/
const TABLE_NAME = 'wms_inbox_group';
const INDEX_NAME = 'idx_store_id';
async function indexExists(queryInterface, tableName, indexName) {
const indexes = await queryInterface.showIndex(tableName);
return (indexes || []).some(i => (typeof i === 'string' ? i : i.name) === indexName);
}
async function addIndexIfNotExists(queryInterface, tableName, indexName, options = {}) {
if (await indexExists(queryInterface, tableName, indexName)) {
console.log(`[idx] ${tableName}.${indexName} 已存在,跳过`);
return;
}
await queryInterface.addIndex(tableName, options.fields, {
name: indexName,
unique: !!options.unique,
});
console.log(`[idx] ${tableName}.${indexName} 已创建`);
}
async function dropIndexIfExists(queryInterface, tableName, indexName) {
if (await indexExists(queryInterface, tableName, indexName)) {
await queryInterface.removeIndex(tableName, indexName);
console.log(`[idx] ${tableName}.${indexName} 已删除`);
}
}
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
await addIndexIfNotExists(queryInterface, TABLE_NAME, INDEX_NAME, {
fields: [ 'store_id' ],
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await dropIndexIfExists(queryInterface, TABLE_NAME, INDEX_NAME);
},
};