using FoodLabeling.Application.Contracts.Dtos.RbacRoleMenu;
using FoodLabeling.Application.Contracts.IServices;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Uow;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace FoodLabeling.Application.Services;
///
/// 角色-权限关联(食品标签-美国版对外)
///
public class RbacRoleMenuAppService : ApplicationService, IRbacRoleMenuAppService
{
private readonly ISqlSugarRepository _roleRepository;
private readonly ISqlSugarRepository _menuRepository;
private readonly ISqlSugarRepository _roleMenuRepository;
public RbacRoleMenuAppService(
ISqlSugarRepository roleRepository,
ISqlSugarRepository menuRepository,
ISqlSugarRepository roleMenuRepository)
{
_roleRepository = roleRepository;
_menuRepository = menuRepository;
_roleMenuRepository = roleMenuRepository;
}
///
[UnitOfWork]
public async Task SetAsync([FromBody] RbacRoleMenuSetInputVo input)
{
var role = await _roleRepository.GetSingleAsync(x => x.Id == input.RoleId && x.IsDeleted == false);
if (role is null)
{
throw new UserFriendlyException("角色不存在");
}
var menuIds = input.MenuIds?.Distinct().ToList() ?? new List();
if (menuIds.Count == 0)
{
// 覆盖式:传空表示清空
await _roleMenuRepository.DeleteAsync(x => x.RoleId == input.RoleId);
return;
}
// 只允许分配未删除的菜单
var existMenuIds = await _menuRepository._DbQueryable
.Where(x => x.IsDeleted == false)
.Where(x => menuIds.Contains(x.Id))
.Select(x => x.Id)
.ToListAsync();
await _roleMenuRepository.DeleteAsync(x => x.RoleId == input.RoleId);
var entities = existMenuIds.Select(menuId =>
{
var entity = new RoleMenuEntity
{
RoleId = input.RoleId,
MenuId = menuId
};
EntityHelper.TrySetId(entity, () => GuidGenerator.Create());
return entity;
}).ToList();
if (entities.Count > 0)
{
await _roleMenuRepository.InsertRangeAsync(entities);
}
}
///
public async Task> GetMenuIdsAsync([FromQuery] Guid roleId)
{
return await _roleMenuRepository._DbQueryable
.Where(x => x.RoleId == roleId)
.Select(x => x.MenuId)
.ToListAsync();
}
///
[UnitOfWork]
public async Task RemoveAsync([FromBody] RbacRoleMenuRemoveInputVo input)
{
var role = await _roleRepository.GetSingleAsync(x => x.Id == input.RoleId && x.IsDeleted == false);
if (role is null)
{
throw new UserFriendlyException("角色不存在");
}
var menuIds = input.MenuIds?.Distinct().ToList() ?? new List();
if (menuIds.Count == 0)
{
return;
}
await _roleMenuRepository._Db.Deleteable()
.Where(x => x.RoleId == input.RoleId)
.WhereIF(menuIds.Count > 0, x => menuIds.Contains(x.MenuId))
.ExecuteCommandAsync();
}
}