using DigitalOps.Authority.Services; using DigitalOps.Dal; using Microsoft.EntityFrameworkCore; using OpenHarbor.CQRS.DynamicQuery.Abstractions; namespace DigitalOps.CQRS.Queries.Client; public class ClientParams { public long OrganizationId { get; set; } } public class ClientItem { public long Id { get; set; } public IEnumerable OrganizationIds { get; set; } public required string Name { get; set; } public DateTime CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } } public class ClientQueryableProvider(MainDbContext dbContext, UserIdentityService userIdentityService): IQueryableProviderOverride { public async Task> GetQueryableAsync(object query, CancellationToken cancellationToken = default) { long? organizationId = null; if (query is IDynamicQueryParams dynamicQuery) { var queryParams = dynamicQuery.GetParams(); organizationId = queryParams?.OrganizationId; } if (organizationId is null) { // don't bother to call the database if organizationId is not set return Enumerable.Empty().AsQueryable(); } var user = await userIdentityService.GetUserOrDefaultAsync(cancellationToken); var queryable = dbContext.Clients .AsNoTracking(); var result = dbContext.Clients .AsNoTracking() .Where(client => client.OrganizationClients.Any(organizationClient => organizationClient.OrganizationId == organizationId)) .Where(client => client.OrganizationClients.Any(organizationClient => organizationClient.Organization.OrganizationUsers.Any(organizationUser => organizationUser.UserId == user!.Id))) .Select(client => new ClientItem { Id = client.Id, OrganizationIds = client.OrganizationClients.Select(organizationClient => organizationClient.OrganizationId), Name = client.Name, CreatedAt = client.CreatedAt, UpdatedAt = client.UpdatedAt }); return result; } }