'use strict'; const Service = require('egg').Service; class SettingPermissionService extends Service { createError(message, code = 500) { const error = new Error(message); error.code = code; return error; } getCurrentStoreId() { const storeId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isFinite(storeId) || storeId <= 0) { throw this.createError('未识别到当前主体,无法操作权限', 400); } return storeId; } getCurrentEmployeeId() { const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); if (!Number.isFinite(employeeId) || employeeId <= 0) { return null; } return employeeId; } toPositiveNumber(value, fieldName) { const num = Number(value); if (!Number.isFinite(num) || num <= 0) { throw this.createError(`${fieldName} 参数不能为空`, 400); } return num; } async getRole(roleId) { const { ctx, app } = this; const { Op } = app.Sequelize; const storeId = this.getCurrentStoreId(); const role = await ctx.model.Role.findOne({ where: { id: roleId, [Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null }, ], }, }); if (!role) { throw this.createError('角色不存在或无权限操作', 404); } return role; } async getPermission(permissionId, includeDisabled = false) { const { ctx } = this; const where = { id: permissionId }; if (!includeDisabled) { where.status = 1; } const permission = await ctx.model.Permission.findOne({ where }); if (!permission) { throw this.createError('权限不存在或已禁用', 404); } return permission; } /** * 规范化并校验权限类型 * @param {string} type 权限类型 * @return {string} 规范化后的权限类型 */ normalizePermissionType(type) { const normalized = typeof type === 'string' ? type.trim() : ''; if (!normalized) { throw this.createError('type 参数不能为空', 400); } const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'workerstation_pages', 'block' ]); if (!allowedTypes.has(normalized)) { throw this.createError('type 参数不合法', 400); } return normalized; } normalizeOptionalString(value, fieldName, maxLength = 255) { if (value === undefined || value === null) { return null; } const normalized = String(value).trim(); if (!normalized) { return ''; } if (normalized.length > maxLength) { throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); } return normalized; } normalizeParentId(value) { if (value === undefined || value === null || value === '' || Number(value) === 0) { return null; } const num = Number(value); if (!Number.isFinite(num) || num <= 0) { throw this.createError('parent_id 参数不合法', 400); } return num; } normalizeSort(value) { if (value === undefined || value === null || value === '') { return 0; } const num = Number(value); if (!Number.isFinite(num) || num < 0) { throw this.createError('sort 参数不合法', 400); } return Math.floor(num); } normalizeStatus(value) { if (value === undefined || value === null || value === '') { return 1; } const num = Number(value); if (num === 0 || num === 1) { return num; } throw this.createError('status 参数不合法', 400); } normalizeBooleanFlag(value, fieldName) { if (value === undefined || value === null || value === '') { return 0; } const num = Number(value); if (num === 0 || num === 1) { return num; } throw this.createError(`${fieldName} 参数不合法`, 400); } async getAvailablePermissionIdSet({ includeDisabled = false } = {}) { const rows = await this.resolveVisiblePermissionRows({ includeDisabled, type: null, keyword: '', }); return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); } async ensureParentPermissionExists(parentId) { if (!parentId) { return; } await this.getPermission(parentId, false); } async ensurePermissionsExist(permissionIds) { const { ctx } = this; const targetRows = await ctx.model.Permission.findAll({ where: { id: permissionIds, }, attributes: [ 'id' ], raw: true, }); if (targetRows.length !== permissionIds.length) { const found = new Set(targetRows.map(item => Number(item.id))); const missing = permissionIds.filter(id => !found.has(Number(id))); throw this.createError(`权限不存在:${missing.join(',')}`, 404); } return targetRows; } normalizePermissionIds(inputPermissionIds) { if (!Array.isArray(inputPermissionIds)) { throw this.createError('permission_ids 参数不能为空', 400); } const permissionIds = []; for (const permissionId of inputPermissionIds) { const normalized = Number(permissionId); if (!Number.isFinite(normalized) || normalized <= 0) { throw this.createError('permission_ids 必须是正整数数组', 400); } permissionIds.push(normalized); } return Array.from(new Set(permissionIds)); } normalizeIds(inputIds, fieldName = 'ids') { if (!Array.isArray(inputIds)) { throw this.createError(`${fieldName} 参数不能为空`, 400); } const ids = []; for (const item of inputIds) { const normalized = Number(item); if (!Number.isFinite(normalized) || normalized <= 0) { throw this.createError(`${fieldName} 必须是正整数数组`, 400); } ids.push(normalized); } if (ids.length === 0) { throw this.createError(`${fieldName} 参数不能为空`, 400); } return Array.from(new Set(ids)); } async validatePermissions(permissionIds) { const { ctx } = this; if (permissionIds.length === 0) { return []; } const permissions = await ctx.model.Permission.findAll({ where: { id: permissionIds, status: 1, }, attributes: [ 'id' ], }); if (permissions.length !== permissionIds.length) { const foundIds = permissions.map(item => Number(item.id)); const missingIds = permissionIds.filter(item => !foundIds.includes(item)); throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400); } return permissions; } async clearRoleUsersCache(roleId) { const { ctx, service } = this; const storeId = this.getCurrentStoreId(); const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ where: { role_id: roleId, }, include: [ { model: ctx.model.AccountStoreEmployee, as: 'employee', attributes: [ 'account_id' ], where: { store_id: storeId, status: 1, }, required: true, }, ], raw: false, }); const accountIds = Array.from(new Set(employeeRoleRows .map(item => Number(item.employee && item.employee.account_id)) .filter(id => Number.isFinite(id) && id > 0))); for (const accountId of accountIds) { await service.systems.auth.user.clearUserCache(accountId); } } async getCurrentEmployeePermissionIds() { const { ctx } = this; const currentEmployeeId = this.getCurrentEmployeeId(); if (!currentEmployeeId) { return []; } const employeeRoles = await ctx.model.EmployeeRole.findAll({ attributes: [ 'role_id' ], where: { employee_id: currentEmployeeId, }, include: [ { model: ctx.model.Role, as: 'role', attributes: [], where: { status: 1, }, required: true, }, ], raw: true, }); const roleIds = Array.from(new Set(employeeRoles .map(item => Number(item.role_id)) .filter(id => Number.isFinite(id) && id > 0))); if (roleIds.length === 0) { return []; } return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { includeDisabled: false, }); } async getCurrentRoleId() { const { ctx } = this; const currentEmployeeId = this.getCurrentEmployeeId(); if (!currentEmployeeId) { return null; } const row = await ctx.model.EmployeeRole.findOne({ attributes: [ 'role_id' ], where: { employee_id: currentEmployeeId, }, include: [ { model: ctx.model.Role, as: 'role', attributes: [], where: { status: 1, }, required: true, }, ], order: [[ 'id', 'ASC' ]], raw: true, }); const roleId = Number(row && row.role_id); if (!Number.isFinite(roleId) || roleId <= 0) { return null; } return roleId; } async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; const where = { status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, }; if (scopeMode !== 'all') { const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); if (currentPermissionIds.length === 0) { return []; } where.id = { [Op.in]: currentPermissionIds, }; } if (type) { where.type = type; } if (keyword) { where[Op.or] = [ { path: { [Op.like]: `%${keyword}%` } }, { name: { [Op.like]: `%${keyword}%` } }, { meta_title: { [Op.like]: `%${keyword}%` } }, ]; } const permissionRows = await ctx.model.Permission.findAll({ where, attributes: [ 'id', 'path', 'name', 'type', 'status', 'parent_id', 'sort', 'component', 'redirect', 'meta_title', 'meta_icon', 'hidden', 'always_show', ], order: [ [ 'sort', 'ASC' ], [ 'id', 'ASC' ], ], }); return permissionRows; } async list(data = {}) { const { ctx } = this; const includeDisabled = data.includeDisabled === true; const roleIdRaw = data.role_id || data.roleId; const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null; const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; let role = null; let targetRoleId = roleIdRaw; if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') { targetRoleId = await this.getCurrentRoleId(); } if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') { const roleId = this.toPositiveNumber(targetRoleId, 'role_id'); role = await this.getRole(roleId); } // 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。 const permissionRows = await this.resolveVisiblePermissionRows({ includeDisabled, type, keyword, scopeMode: 'all', }); let selectedPermissionSet = new Set(); let selectAllPermissions = false; if (role) { const directPermissionIds = ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions); if (directPermissionIds.includes('*')) { selectAllPermissions = true; } else if (directPermissionIds.length > 0) { selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item))); } } const permissions = permissionRows.map(item => ({ permission_id: Number(item.id), path: item.path || '', name: item.name || '', type: item.type || '', status: Number(item.status), parent_id: item.parent_id === null ? null : Number(item.parent_id), sort: Number(item.sort || 0), component: item.component || '', redirect: item.redirect || '', meta_title: item.meta_title || '', meta_icon: item.meta_icon || '', hidden: Number(item.hidden || 0), always_show: Number(item.always_show || 0), selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false, })); return { code: 200, data: { role_id: role ? Number(role.id) : null, permissions, }, }; } async add(data = {}) { const { ctx } = this; const path = this.normalizeOptionalString(data.path, 'path', 255); if (!path) { throw this.createError('path 参数不能为空', 400); } const permissionData = { path, type: this.normalizePermissionType(data.type), name: this.normalizeOptionalString(data.name, 'name', 100) || '', component: this.normalizeOptionalString(data.component, 'component', 255), redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255), meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100), meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50), parent_id: this.normalizeParentId(data.parent_id), sort: this.normalizeSort(data.sort), hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'), always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'), status: this.normalizeStatus(data.status), }; await this.ensureParentPermissionExists(permissionData.parent_id); let created = null; try { created = await ctx.model.Permission.create(permissionData); } catch (error) { throw error; } return { code: 200, data: { permission_id: Number(created.id), path: created.path || '', type: created.type || '', parent_id: created.parent_id === null ? null : Number(created.parent_id), status: Number(created.status), }, }; } async delete(data = {}) { const { ctx } = this; const permissionIds = this.normalizeIds(data.ids, 'ids'); await this.ensurePermissionsExist(permissionIds); const permissions = await ctx.model.Permission.findAll({ where: { id: permissionIds, }, attributes: [ 'id', 'status' ], raw: true, }); const deletedIds = []; const alreadyDeletedIds = []; for (const permission of permissions) { if (Number(permission.status) === 0) { alreadyDeletedIds.push(Number(permission.id)); } else { deletedIds.push(Number(permission.id)); } } const transaction = await ctx.model.transaction(); try { if (deletedIds.length > 0) { await ctx.model.Permission.update({ status: 0, }, { where: { id: deletedIds, }, transaction, }); await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, { transaction, }); } await transaction.commit(); } catch (error) { await transaction.rollback(); throw error; } return { code: 200, data: { ids: permissionIds, deleted_ids: deletedIds, already_deleted_ids: alreadyDeletedIds, status: 'deleted', }, }; } async update(data = {}) { const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); await this.ensurePermissionsExist([ permissionId ]); const permission = await this.getPermission(permissionId, true); const hasPath = Object.prototype.hasOwnProperty.call(data, 'path'); const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); const hasType = Object.prototype.hasOwnProperty.call(data, 'type'); const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component'); const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect'); const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title'); const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon'); const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id'); const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort'); const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden'); const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show'); const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect && !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort && !hasHidden && !hasAlwaysShow && !hasStatus) { throw this.createError('至少需要提供一个可更新字段', 400); } const updates = {}; if (hasPath) { const path = this.normalizeOptionalString(data.path, 'path', 255); if (!path) { throw this.createError('path 参数不能为空', 400); } updates.path = path; } if (hasName) { updates.name = this.normalizeOptionalString(data.name, 'name', 100) || ''; } if (hasType) { updates.type = this.normalizePermissionType(data.type); } if (hasComponent) { updates.component = this.normalizeOptionalString(data.component, 'component', 255); } if (hasRedirect) { updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255); } if (hasMetaTitle) { updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100); } if (hasMetaIcon) { updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50); } if (hasParentId) { const parentId = this.normalizeParentId(data.parent_id); if (parentId && parentId === permissionId) { throw this.createError('parent_id 不能等于 permission_id', 400); } await this.ensureParentPermissionExists(parentId); updates.parent_id = parentId; } if (hasSort) { updates.sort = this.normalizeSort(data.sort); } if (hasHidden) { updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden'); } if (hasAlwaysShow) { updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show'); } if (hasStatus) { updates.status = this.normalizeStatus(data.status); } await permission.update(updates); return { code: 200, data: { permission_id: Number(permission.id), path: permission.path || '', type: permission.type || '', parent_id: permission.parent_id === null ? null : Number(permission.parent_id), status: Number(permission.status), }, }; } } module.exports = SettingPermissionService;