dotnet-digital-ops/DigitalOps.CQRS/Queries/Project/ProjectQuery.cs

72 lines
2.2 KiB
C#

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