using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Data; using AsbCloudApp.Services; using AsbCloudDb.Model; using AsbCloudInfrastructure.Services.Cache; using Mapster; namespace AsbCloudInfrastructure.Services { public class UserRoleService : IUserRoleService { private readonly IAsbCloudDbContext db; private readonly CacheTable cacheUserRoles; private readonly CacheTable cachePermissions; private readonly CacheTable cacheUserRolesPermissions; public UserRoleService(IAsbCloudDbContext db, CacheDb cacheDb) { this.db = db; cacheUserRoles = cacheDb.GetCachedTable((AsbCloudDbContext)db); cachePermissions = cacheDb.GetCachedTable((AsbCloudDbContext)db); cacheUserRolesPermissions = cacheDb.GetCachedTable((AsbCloudDbContext)db); } public async Task> GetAllAsync(CancellationToken token) { var rolesDtos = (await cacheUserRoles.WhereAsync(token).ConfigureAwait(false)) .Adapt(); return rolesDtos.Select(FillUserRoleWithPermissions); } public async Task GetAsync(int id, CancellationToken token) { var roleDto = (await cacheUserRoles.FirstOrDefaultAsync(r => r.Id == id, token) .ConfigureAwait(false)).Adapt(); return roleDto is null ? null : FillUserRoleWithPermissions(roleDto); } public async Task InsertAsync(UserRoleDto dto, CancellationToken token = default) { var newRole = dto.Adapt(); db.UserRoles.Add(newRole); var result = await db.SaveChangesAsync(token); if (dto.PermissionIds == default) return result; foreach (var pId in dto.PermissionIds) { var relation = new RelationUserRolePermission() { IdUserRole = newRole.Id, IdPermission = pId }; db.RelationUserRolesPermissions.Add(relation); } return await db.SaveChangesAsync(token); } public async Task UpdateAsync(UserRoleDto dto, CancellationToken token = default) { var entity = dto.Adapt(); db.UserRoles.Update(entity); await db.SaveChangesAsync(token); if (dto.PermissionIds != default) { await cacheUserRolesPermissions.RemoveAsync(r => r.IdUserRole == dto.Id, token) .ConfigureAwait(false); var newRelations = dto.PermissionIds.Select(p => new RelationUserRolePermission() { IdUserRole = dto.Id, IdPermission = p }); await cacheUserRolesPermissions.InsertAsync(newRelations, token); } } public async Task DeleteAsync(IEnumerable ids, CancellationToken token) { var entities = cacheUserRoles.Where(e => ids.Contains(e.Id)); if (entities == default) return 0; db.UserRoles.RemoveRange(entities); return await db.SaveChangesAsync(token); } 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(); return roleDto; } } }