34 lines
1.3 KiB
C#
34 lines
1.3 KiB
C#
using LiteCharms.Extensions;
|
|
using LiteCharms.Infrastructure.Database;
|
|
using LiteCharms.Models;
|
|
|
|
namespace LiteCharms.Features.Customers.Queries.Handlers;
|
|
|
|
public class GetCustomersQueryHandler(IDbContextFactory<LeadGeneratorDbContext> contextFactory) : IRequestHandler<GetCustomersQuery, Result<Customer[]>>
|
|
{
|
|
public async ValueTask<Result<Customer[]>> Handle(GetCustomersQuery request, CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
var fromDate = request.From.ToDateTime(TimeOnly.MinValue);
|
|
var toDate = request.To.ToDateTime(TimeOnly.MaxValue);
|
|
|
|
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
var customers = await context.Customers.AsNoTracking()
|
|
.OrderByDescending(o => o.CreatedAt)
|
|
.Where(c => c.CreatedAt >= fromDate && c.CreatedAt <= toDate)
|
|
.Take(request.MaxRecords)
|
|
.ToArrayAsync(cancellationToken);
|
|
|
|
return customers?.Length > 0
|
|
? Result.Ok(customers.Select(c => c.ToModel()).ToArray())
|
|
: Result.Fail<Customer[]>(new Error("No customers found in the specified date range."));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return Result.Fail<Customer[]>(new Error(ex.Message).CausedBy(ex));
|
|
}
|
|
}
|
|
}
|