'use strict'; const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); /** 权限范围:1集团全部 2所在公司 */ const SCOPES = { 1: { suffix: 'group', label: '集团全部' }, 2: { suffix: 'company', label: '所在公司' } }; /** * @controller PermissionController 权限管理 * 权限以「菜单」作为分类(menus 顶级菜单),每个菜单下两种权限子类:集团全部 / 所在公司。 */ class PermissionController extends Controller { /** * @summary 权限列表 * @description 分页查询权限,按菜单分类返回;支持按菜单、权限范围、状态与关键词过滤 * @router get /api/permissions * @apikey * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 * @request query integer menu_id 菜单(权限分类)ID * @request query integer scope 权限范围:1集团全部 2所在公司 * @request query integer status 状态:1启用 0禁用 * @request query string keyword 关键词,匹配权限名称 / 标识 * @response 200 permissionListResponse success */ async index() { const { ctx } = this; const Op = this.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { menu_id: menuId, scope, status } = ctx.query; const where = {}; if (menuId) where.menu_id = Number(menuId); if (scope !== undefined && scope !== '') where.scope = Number(scope); if (status !== undefined && status !== '') where.status = Number(status); 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.Permission.findAndCountAll({ where, offset, limit, order: [[{ model: ctx.model.Menu, as: 'menu' }, 'sort', 'DESC' ], [ 'scope', 'ASC' ], [ 'id', 'ASC' ]], include: [ { model: ctx.model.Menu, as: 'menu', attributes: [ 'id', 'name', 'icon', 'path' ], required: false }, ], }); ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; } /** * @summary 权限分类(菜单下拉) * @description 返回可作为权限分类的顶级菜单 * @router get /api/permissions/menus * @apikey * @response 200 baseResponse success */ async menus() { const { ctx } = this; const rows = await ctx.model.Menu.findAll({ where: { parent_id: 0 }, attributes: [ 'id', 'name', 'icon', 'path', 'sort' ], order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]], raw: true, }); ctx.body = { code: 0, message: 'success', data: rows }; } /** * @summary 权限详情 * @router get /api/permissions/{id} * @apikey * @request path integer *id 权限主键ID * @response 200 baseResponse success */ async show() { const { ctx } = this; const item = await ctx.model.Permission.findByPk(ctx.params.id, { include: [ { model: ctx.model.Menu, as: 'menu', attributes: [ 'id', 'name', 'icon', 'path' ], required: false }, ], }); if (!item) { ctx.status = 404; ctx.body = { code: 404, message: '权限不存在' }; return; } ctx.body = { code: 0, message: 'success', data: item }; } /** * @summary 新增权限 * @description 同一菜单 + 同一权限范围唯一;未传名称/标识时按菜单与范围自动生成 * @router post /api/permissions * @apikey * @request body createPermissionRequest *body * @response 200 baseResponse success */ async create() { const { ctx } = this; const body = ctx.request.body || {}; const menuId = Number(body.menu_id); const scope = Number(body.scope); if (!menuId) { ctx.status = 400; ctx.body = { code: 400, message: '请选择权限分类(菜单)' }; return; } const scopeMeta = SCOPES[scope]; if (!scopeMeta) { ctx.status = 400; ctx.body = { code: 400, message: '权限范围只能为:1集团全部 2所在公司' }; return; } const menu = await ctx.model.Menu.findByPk(menuId); if (!menu) { ctx.status = 404; ctx.body = { code: 404, message: '菜单不存在' }; return; } const exist = await ctx.model.Permission.findOne({ where: { menu_id: menuId, scope } }); if (exist) { ctx.status = 400; ctx.body = { code: 400, message: `「${menu.name}」下已存在${scopeMeta.label}权限` }; return; } const name = String(body.name || '').trim() || `${menu.name}(${scopeMeta.label})`; const code = String(body.code || '').trim() || `menu_${menuId}_${scopeMeta.suffix}`; const codeExist = await ctx.model.Permission.findOne({ where: { code } }); if (codeExist) { ctx.status = 400; ctx.body = { code: 400, message: '权限标识已存在' }; return; } const item = await ctx.model.Permission.create({ menu_id: menuId, scope, name, code, status: body.status === undefined ? 1 : Number(body.status) === 0 ? 0 : 1, remark: body.remark == null ? null : String(body.remark).trim(), }); ctx.body = { code: 0, message: 'success', data: { id: item.id } }; } /** * @summary 更新权限 * @description 未传入的字段保持原值;菜单 + 范围唯一 * @router put /api/permissions/{id} * @apikey * @request path integer *id 权限主键ID * @request body updatePermissionRequest *body * @response 200 baseResponse success */ async update() { const { ctx } = this; const item = await ctx.model.Permission.findByPk(ctx.params.id); if (!item) { ctx.status = 404; ctx.body = { code: 404, message: '权限不存在' }; return; } const body = ctx.request.body || {}; const patch = {}; for (const key of [ 'menu_id', 'name', 'status', 'remark' ]) { if (body[key] !== undefined) patch[key] = body[key]; } if (patch.menu_id !== undefined) { const menu = await ctx.model.Menu.findByPk(Number(patch.menu_id)); if (!menu) { ctx.status = 404; ctx.body = { code: 404, message: '菜单不存在' }; return; } patch.menu_id = Number(patch.menu_id); } if (patch.name !== undefined) { const name = String(patch.name || '').trim(); if (!name) { ctx.status = 400; ctx.body = { code: 400, message: '权限名称不能为空' }; return; } patch.name = name; } if (patch.status !== undefined) patch.status = Number(patch.status) === 0 ? 0 : 1; if (patch.remark !== undefined) { patch.remark = patch.remark == null || String(patch.remark).trim() === '' ? null : String(patch.remark).trim(); } const menuId = patch.menu_id === undefined ? Number(item.menu_id) : patch.menu_id; if (patch.menu_id !== undefined) { const exist = await ctx.model.Permission.findOne({ where: { menu_id: menuId, scope: item.scope } }); if (exist && Number(exist.id) !== Number(item.id)) { ctx.status = 400; ctx.body = { code: 400, message: '该菜单下已存在相同范围的权限' }; return; } } await item.update(patch); ctx.body = { code: 0, message: 'success', data: { id: item.id } }; } /** * @summary 删除权限 * @description 被系统预设角色使用的权限不可删除(可改为禁用);删除时同时解除自定义角色的绑定 * @router delete /api/permissions/{id} * @apikey * @request path integer *id 权限主键ID * @response 200 baseResponse success */ async destroy() { const { ctx } = this; const item = await ctx.model.Permission.findByPk(ctx.params.id); if (!item) { ctx.status = 404; ctx.body = { code: 404, message: '权限不存在' }; return; } // 系统预设角色(系统管理员 / 货主权限)的权限集合固定,禁止删除其占用的权限 const boundRows = await ctx.model.RolePermission.findAll({ where: { permission_id: item.id }, attributes: [ 'role_id' ], raw: true, }); const boundSystem = boundRows.length ? await ctx.model.Role.count({ where: { id: boundRows.map(row => row.role_id), is_system: 1 } }) : 0; if (boundSystem > 0) { ctx.status = 400; ctx.body = { code: 400, message: '该权限已被系统预设角色使用,无法删除;如需停用请改为禁用' }; return; } await ctx.model.RolePermission.destroy({ where: { permission_id: item.id } }); await item.destroy(); ctx.body = { code: 0, message: 'success', data: { id: Number(item.id) } }; } /** * @summary 同步菜单权限 * @description 为每个顶级菜单补齐「集团全部 / 所在公司」两种权限,已存在的跳过;新菜单上线后可手动同步 * @router post /api/permissions/sync * @apikey * @response 200 baseResponse success */ async sync() { const { ctx } = this; const menus = await ctx.model.Menu.findAll({ where: { parent_id: 0 }, attributes: [ 'id', 'name' ], order: [[ 'sort', 'DESC' ], [ 'id', 'ASC' ]], }); const existRows = await ctx.model.Permission.findAll({ attributes: [ 'menu_id', 'scope' ], raw: true }); const existKeys = new Set(existRows.map(row => `${Number(row.menu_id)}:${Number(row.scope)}`)); let created = 0; for (const menu of menus) { for (const scope of [ 1, 2 ]) { const scopeMeta = SCOPES[scope]; if (existKeys.has(`${Number(menu.id)}:${scope}`)) continue; await ctx.model.Permission.create({ menu_id: menu.id, scope, name: `${menu.name}(${scopeMeta.label})`, code: `menu_${menu.id}_${scopeMeta.suffix}`, status: 1, remark: `菜单「${menu.name}」的${scopeMeta.label}权限`, }); created++; } } ctx.body = { code: 0, message: 'success', data: { created } }; } } module.exports = PermissionController;