using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using WebApp.Common.Exceptions.ClientSide; using WebApp.Common.Resources; using WebApp.Data; using WebApp.Data.Entities; using WebApp.Models; using WebApp.Models.MappingExtensions; using WebApp.Models.Request.Users; using WebApp.Models.Response.Roles; using WebApp.Models.Response.Users; using WebApp.Services.Interfaces; namespace WebApp.Services.Implementations; public class UserService : IUserService { private readonly UserManager _userManager; private readonly ApplicationContext _context; private readonly ILogger _logger; public UserService(UserManager userManager, ApplicationContext context, ILogger logger) { _userManager = userManager; _context = context; _logger = logger; } public async Task GetByIdAsync(Guid userId) { ApplicationUser? user = await _userManager.FindByIdAsync(userId.ToString()); if (user is null) { _logger.LogError("Not found user with ID: {userId}", userId); throw new NotFoundUserException(Messages.UserNotFound); } return user; } public async Task GetDetailsByIdAsync(Guid userId) { ApplicationUser? user = await _context.Users.Include(x => x.Roles).FirstOrDefaultAsync(x => x.Id == userId); if (user is null) { _logger.LogError("Not found user with ID: {userId}", userId); throw new NotFoundUserException(Messages.UserNotFound); } IList userRoles = await GetUserRolesAsync(user); IReadOnlyList userRolesResponse = userRoles.Select(x => x.ToRoleResponseModel()).ToList(); return user.ToUserResponseModel(userRolesResponse); } public async Task> GetAllUsersAsync(UsersFilter usersFilter) { IQueryable usersQuery = _userManager.Users.Include(x => x.Roles); usersQuery = await ApplyUserFilterAsync(usersQuery, usersFilter); int totalCount = await usersQuery.CountAsync(); int pagesCount = (int)Math.Ceiling((double)totalCount / usersFilter.ItemsPerPage!.Value); usersQuery = usersQuery .Skip(usersFilter.SkipCount) .Take(usersFilter.ItemsPerPage!.Value); IReadOnlyList usersResponses = await usersQuery .Select(x => x.ToUserResponseModel(new List())) .ToListAsync(); return new PaginationResponseModel { Items = usersResponses, TotalItems = totalCount, PageNumber = usersFilter.PageNumber!.Value, ItemsPerPage = usersFilter.ItemsPerPage!.Value, PagesCount = pagesCount, }; } private async Task> GetUserRolesAsync(ApplicationUser user) { IList userRoles = new List(); foreach (var userRole in user.Roles) { var role = await _context.Roles.FirstOrDefaultAsync(x => x.Id == userRole.RoleId); userRoles.Add(role!); } return userRoles; } private async Task> ApplyUserFilterAsync(IQueryable users, UsersFilter usersFilter) { if (usersFilter.SearchTerm is not null) { users = users.Where(x => x.Email!.Contains(usersFilter.SearchTerm)); } return users.OrderByDescending(x => x.CreatedOn); } }