DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/UserRoleService.cs

91 lines
3.3 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
using Mapster;
namespace AsbCloudInfrastructure.Services
{
public class UserRoleService : CrudServiceBase<UserRoleDto, UserRole>
{
private readonly CacheTable<UserRole> cacheUserRoles;
private readonly CacheTable<Permission> cachePermissions;
private readonly CacheTable<RelationUserRolePermission> cacheUserRolesPermissions;
public UserRoleService(IAsbCloudDbContext context, CacheDb cacheDb) : base(context)
{
cacheUserRoles = cacheDb.GetCachedTable<UserRole>((AsbCloudDbContext)context);
cachePermissions = cacheDb.GetCachedTable<Permission>((AsbCloudDbContext)context);
cacheUserRolesPermissions =
cacheDb.GetCachedTable<RelationUserRolePermission>((AsbCloudDbContext)context);
}
public override async Task<IEnumerable<UserRoleDto>> GetAllAsync(CancellationToken token = default)
{
var rolesDtos = await base.GetAllAsync(token);
return rolesDtos.Select(FillUserRoleWithPermissions);
}
public override async Task<UserRoleDto> GetAsync(int id, CancellationToken token = default)
{
var roleDto = await base.GetAsync(id,token);
return roleDto is null ? null : FillUserRoleWithPermissions(roleDto);
}
public override async Task<int> InsertAsync(UserRoleDto dto, CancellationToken token = default)
{
var newRoleId = await base.InsertAsync(dto, token);
if (dto.PermissionIds == default)
return newRoleId;
foreach (var pId in dto.PermissionIds)
{
var relation = new RelationUserRolePermission()
{
IdUserRole = newRoleId,
IdPermission = pId
};
context.RelationUserRolesPermissions.Add(relation);
}
return await context.SaveChangesAsync(token);
}
public override async Task<int> UpdateAsync(int id, UserRoleDto item, CancellationToken token = default)
{
var result = await base.UpdateAsync(id, item, token);
if (item.PermissionIds == default)
return result;
await cacheUserRolesPermissions.RemoveAsync(r => r.IdUserRole == item.Id, token)
.ConfigureAwait(false);
var newRelations = item.PermissionIds.Select(p => new RelationUserRolePermission()
{
IdUserRole = item.Id,
IdPermission = p
});
await cacheUserRolesPermissions.InsertAsync(newRelations, token);
return result;
}
private UserRoleDto FillUserRoleWithPermissions(UserRoleDto roleDto)
{
var rolePermissionIds = cacheUserRolesPermissions.Where(c =>
c.IdUserRole == roleDto.Id).Select(p => p.IdPermission);
roleDto.Permissions = cachePermissions.Where(permission => rolePermissionIds.Contains(permission.Id))
.Adapt<PermissionDto>();
return roleDto;
}
}
}