using YBEE.EQM.Core;
namespace YBEE.EQM.Application
{
///
/// 角色菜单服务
///
public class SysRoleMenuService : ISysRoleMenuService, ITransient
{
private readonly IRepository _roleMenuRep;
private readonly IRepository _menuRep;
private readonly ICacheService _cacheService;
public SysRoleMenuService(IRepository roleMenuRep, IRepository menuRep, ICacheService cacheService)
{
_roleMenuRep = roleMenuRep;
_menuRep = menuRep;
_cacheService = cacheService;
}
///
/// 授权角色菜单
///
///
///
public async Task GrantRoleMenu(GrantSysRoleMenuInput input)
{
var roleMenus = await _roleMenuRep.DetachedEntities.Where(u => u.SysRoleId == input.RoleId).ToListAsync();
await _roleMenuRep.DeleteAsync(roleMenus);
// 确保对按钮菜单的父级菜单能正确的授权,发现前端构造的数据会丢弃了按钮菜单的父级菜单
var roleMenuPidsList = await _menuRep.DetachedEntities.Where(u => input.RoleMenuScopeList.Select(t => t.MenuId).Contains(u.Id))
.Select(u => u.Pids).ToListAsync();
var roleMenuSplitPids = roleMenuPidsList
.SelectMany(u => u.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(v => int.Parse(v[1..^1]))
.Where(v => v != 0))
.Union(input.RoleMenuScopeList.Select(t => t.MenuId));
var menus = roleMenuSplitPids.Select(u => new SysRoleMenu
{
SysRoleId = input.RoleId,
SysMenuId = u,
DataScopeType = input.RoleMenuScopeList.FirstOrDefault(t => t.MenuId == u)?.DataScopeType ?? DataScopeType.SELF
}).ToList();
await _roleMenuRep.InsertAsync(menus);
// 清除缓存
await _cacheService.DelByPatternAsync(CommonConst.CACHE_KEY_MENU);
await _cacheService.DelByPatternAsync(CommonConst.CACHE_KEY_PERMISSION);
}
///
/// 根据菜单Id集合删除对应的角色-菜单表信息
///
///
///
public async Task DeleteRoleMenuListByMenuIdList(List menuIdList)
{
var roleMenus = await _roleMenuRep.DetachedEntities.Where(u => menuIdList.Contains(u.SysMenuId)).ToListAsync();
await _roleMenuRep.DeleteAsync(roleMenus);
}
///
/// 根据角色Id删除对应的角色-菜单表关联信息
///
///
///
public async Task DeleteRoleMenuListByRoleId(int roleId)
{
var roleMenus = await _roleMenuRep.DetachedEntities.Where(u => u.SysRoleId == roleId).ToListAsync();
await _roleMenuRep.DeleteAsync(roleMenus);
}
///
/// 获取角色的菜单Id集合
///
///
///
public async Task> GetRoleMenuIdList(List roleIdList)
{
return await _roleMenuRep.DetachedEntities
.Where(u => roleIdList.Contains(u.SysRoleId))
.Select(u => u.SysMenuId).ToListAsync();
}
///
/// 获取角色对象菜单列表
///
///
///
public async Task> GetRoleMenuList(int roleId)
{
return await _roleMenuRep.DetachedEntities.Include(t => t.SysMenu).Where(t => t.SysRoleId == roleId).ProjectToType().ToListAsync();
}
///
/// 获取指定权限标识的角色ID列表
///
///
///
public async Task> GetRoleIdListByMenuPermissionCode(string permissionCode)
{
return await _roleMenuRep.DetachedEntities.Where(t => t.SysMenu.Permission == permissionCode).Select(t => t.SysRoleId).Distinct().ToListAsync();
}
}
}