'use strict'; const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); /** * @controller RoleController 角色组(权限管理) * 角色组维护「权限集合」,账号通过 principal_users.role_id 关联角色组。 * is_system=1 的系统预设角色(系统管理员 / 货主权限)只读,不可修改/删除。 */ class RoleController extends Controller { /** * @summary 角色组列表 * @description 分页查询角色组,带出已绑定的权限;支持关键词、系统预设与状态过滤 * @router get /api/roles * @apikey * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query string keyword 关键词,匹配角色名称 / 标识 * @request query integer is_system 是否系统预设:1是 0否 * @request query integer status 状态:1启用 0禁用 * @response 200 roleListResponse success */ async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { is_system: isSystem, status } = ctx.query; const where = {}; if (isSystem !== undefined && isSystem !== '') where.is_system = Number(isSystem) === 1 ? 1 : 0; if (status !== undefined && status !== '') where.status = Number(status) === 0 ? 0 : 1; const text = String(ctx.query.keyword || '').trim(); if (text) { where[Op.or] = [ { name: { [Op.like]: `%${text}%` } }, { code: { [Op.like]: `%${text}%` } }, ]; } const { count, rows } = await ctx.model.Role.findAndCountAll({ where, offset, limit, // 角色与权限是一对多 join,需去重计数,否则总数按权限条数统计 distinct: true, order: [[ 'is_system', 'DESC' ], [ 'id', 'ASC' ]], include: [ { model: ctx.model.Permission, as: 'permissions', attributes: [ 'id', 'menu_id', 'name', 'code', 'scope', 'status' ], through: { attributes: [] }, required: false, }, ], }); const list = rows.map(row => { const plain = row.toJSON(); plain.permission_ids = (plain.permissions || []).map(item => Number(item.id)); plain.permission_count = plain.permission_ids.length; return plain; }); ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } /** * @summary 角色组下拉 * @description 返回启用的角色组,供「员工档案」页面分配角色组使用; * mine=1 时对「所在公司」权限的账号只返回不含集团权限的角色组,避免越权分配 * @router get /api/roles/options * @apikey * @request query integer mine 是否按当前账号权限收窄:1是 * @response 200 baseResponse success */ async options() { const { ctx } = this; const rows = await ctx.model.Role.findAll({ where: { status: 1 }, attributes: [ 'id', 'name', 'code', 'is_system' ], order: [[ 'is_system', 'DESC' ], [ 'id', 'ASC' ]], raw: true, }); let list = rows; if (String(ctx.query.mine || '') === '1' && ctx.query.principal_id) { const access = await ctx.service.access.resolve(ctx.userId, ctx.query.principal_id); if (!access.isGroup) { const groupPermissions = await ctx.model.Permission.findAll({ where: { scope: 1, status: 1 }, attributes: [ 'id' ], include: [{ model: ctx.model.Role, as: 'roles', attributes: [ 'id' ], through: { attributes: [] }, required: true, }], }); const blocked = new Set( groupPermissions.flatMap(item => (item.roles || []).map(role => Number(role.id))) ); list = rows.filter(row => !blocked.has(Number(row.id))); } } ctx.body = { code: 0, message: 'success', data: list }; } /** * @summary 角色组详情 * @router get /api/roles/{id} * @apikey * @request path integer *id 角色组主键ID * @response 200 baseResponse success */ async show() { const { ctx } = this; const role = await ctx.model.Role.findByPk(ctx.params.id, { include: [ { model: ctx.model.Permission, as: 'permissions', attributes: [ 'id', 'menu_id', 'name', 'code', 'scope', 'status' ], through: { attributes: [] }, required: false, }, ], }); if (!role) { ctx.status = 404; ctx.body = { code: 404, message: '角色组不存在' }; return; } ctx.body = { code: 0, message: 'success', data: role }; } /** * @summary 新增角色组 * @description 名称与标识全局唯一;permission_ids 为要绑定的权限ID列表 * @router post /api/roles * @apikey * @request body createRoleRequest *body * @response 200 baseResponse success */ async create() { const { ctx } = this; const body = ctx.request.body || {}; const name = String(body.name || '').trim(); if (!name) { ctx.status = 400; ctx.body = { code: 400, message: '角色名称不能为空' }; return; } const nameExist = await ctx.model.Role.findOne({ where: { name } }); if (nameExist) { ctx.status = 400; ctx.body = { code: 400, message: '角色名称已存在' }; return; } const code = String(body.code || '').trim() || `role_${Date.now().toString(36)}`; const codeExist = await ctx.model.Role.findOne({ where: { code } }); if (codeExist) { ctx.status = 400; ctx.body = { code: 400, message: '角色标识已存在' }; return; } const permissionIds = await this.resolvePermissionIds(body.permission_ids); const role = await ctx.model.Role.create({ name, code, is_system: 0, status: body.status === undefined ? 1 : Number(body.status) === 0 ? 0 : 1, remark: body.remark == null ? null : String(body.remark).trim(), }); await this.syncPermissions(role.id, permissionIds); ctx.body = { code: 0, message: 'success', data: { id: role.id } }; } /** * @summary 更新角色组 * @description 系统预设角色只读;未传入的字段保持原值 * @router put /api/roles/{id} * @apikey * @request path integer *id 角色组主键ID * @request body updateRoleRequest *body * @response 200 baseResponse success */ async update() { const { ctx } = this; const role = await ctx.model.Role.findByPk(ctx.params.id); if (!role) { ctx.status = 404; ctx.body = { code: 404, message: '角色组不存在' }; return; } if (Number(role.is_system) === 1) { ctx.status = 400; ctx.body = { code: 400, message: '系统预设角色不可修改' }; return; } const body = ctx.request.body || {}; const patch = {}; if (body.name !== undefined) { const name = String(body.name || '').trim(); if (!name) { ctx.status = 400; ctx.body = { code: 400, message: '角色名称不能为空' }; return; } const exist = await ctx.model.Role.findOne({ where: { name } }); if (exist && Number(exist.id) !== Number(role.id)) { ctx.status = 400; ctx.body = { code: 400, message: '角色名称已存在' }; return; } patch.name = name; } if (body.code !== undefined) { const code = String(body.code || '').trim(); if (!code) { ctx.status = 400; ctx.body = { code: 400, message: '角色标识不能为空' }; return; } const exist = await ctx.model.Role.findOne({ where: { code } }); if (exist && Number(exist.id) !== Number(role.id)) { ctx.status = 400; ctx.body = { code: 400, message: '角色标识已存在' }; return; } patch.code = code; } if (body.status !== undefined) patch.status = Number(body.status) === 0 ? 0 : 1; if (body.remark !== undefined) { patch.remark = body.remark == null || String(body.remark).trim() === '' ? null : String(body.remark).trim(); } await role.update(patch); if (body.permission_ids !== undefined) { const permissionIds = await this.resolvePermissionIds(body.permission_ids); await this.syncPermissions(role.id, permissionIds); } ctx.body = { code: 0, message: 'success', data: { id: role.id } }; } /** * @summary 删除角色组 * @description 系统预设角色不可删除;删除后账号的角色组置空 * @router delete /api/roles/{id} * @apikey * @request path integer *id 角色组主键ID * @response 200 baseResponse success */ async destroy() { const { ctx } = this; const role = await ctx.model.Role.findByPk(ctx.params.id); if (!role) { ctx.status = 404; ctx.body = { code: 404, message: '角色组不存在' }; return; } if (Number(role.is_system) === 1) { ctx.status = 400; ctx.body = { code: 400, message: '系统预设角色不可删除' }; return; } await ctx.model.PrincipalUser.update({ role_id: null }, { where: { role_id: role.id } }); await ctx.model.RolePermission.destroy({ where: { role_id: role.id } }); await role.destroy(); ctx.body = { code: 0, message: 'success', data: { id: Number(role.id) } }; } /** * 校验并去重权限ID(忽略不存在的ID) * @param {Array} input 权限ID列表 * @return {Promise>} 有效权限ID */ async resolvePermissionIds(input) { const ids = Array.isArray(input) ? [ ...new Set(input.map(Number).filter(id => id > 0)) ] : []; if (!ids.length) return []; const rows = await this.ctx.model.Permission.findAll({ where: { id: ids }, attributes: [ 'id' ], raw: true }); return rows.map(row => Number(row.id)); } /** * 覆盖式同步角色权限 * @param {number} roleId 角色ID * @param {Array} permissionIds 权限ID列表 * @return {Promise} 无返回值 */ async syncPermissions(roleId, permissionIds) { const { ctx } = this; await ctx.model.RolePermission.destroy({ where: { role_id: roleId } }); if (!permissionIds.length) return; await ctx.model.RolePermission.bulkCreate(permissionIds.map(permissionId => ({ role_id: roleId, permission_id: permissionId }))); } } module.exports = RoleController;