using Indotalent.Infrastructure.Database; using MediatR; using Microsoft.EntityFrameworkCore; namespace Indotalent.Features.Setting.SystemUser.Cqrs; public class GetSystemUserListResponse { public string? Id { get; set; } public string? FullName { get; set; } public string? AvatarFile { get; set; } public string? Email { get; set; } public string? SsoIdFirebase { get; set; } public string? SsoIdKeycloak { get; set; } public bool IsActive { get; set; } public List UserRoles { get; set; } = new(); } public record GetSystemUserListQuery() : IRequest>; public class GetSystemUserListHandler : IRequestHandler> { private readonly AppDbContext _context; public GetSystemUserListHandler(AppDbContext context) => _context = context; public async Task> Handle(GetSystemUserListQuery request, CancellationToken cancellationToken) { var users = await _context.Users .AsNoTracking() .OrderByDescending(x => x.CreatedAt) .Select(x => new GetSystemUserListResponse { Id = x.Id, FullName = x.FullName, Email = x.Email, SsoIdFirebase = x.SsoIdFirebase, SsoIdKeycloak = x.SsoIdKeycloak, IsActive = x.IsActive, AvatarFile = x.AvatarFile, }) .ToListAsync(cancellationToken); var userIds = users.Select(u => u.Id).ToList(); var userRolesMap = await (from ur in _context.UserRoles join r in _context.Roles on ur.RoleId equals r.Id where userIds.Contains(ur.UserId) select new { ur.UserId, r.Name }) .ToListAsync(cancellationToken); foreach (var user in users) { user.UserRoles = userRolesMap .Where(x => x.UserId == user.Id) .Select(x => x.Name!) .ToList(); } return users; } }