|
| 1 | +using BookStore.ApiService.Infrastructure; |
| 2 | +using BookStore.ApiService.Projections; |
| 3 | +using BookStore.Shared.Models; |
| 4 | +using Marten; |
| 5 | +using Microsoft.AspNetCore.Mvc; |
| 6 | +using Microsoft.Extensions.Options; |
| 7 | + |
| 8 | +namespace BookStore.ApiService.Endpoints; |
| 9 | + |
| 10 | +public static class SalesEndpoints |
| 11 | +{ |
| 12 | + public static RouteGroupBuilder MapSalesEndpoints(this RouteGroupBuilder group) |
| 13 | + { |
| 14 | + _ = group.MapGet("/", GetSales) |
| 15 | + .WithName("GetSales") |
| 16 | + .WithSummary("Get all scheduled book sales"); |
| 17 | + |
| 18 | + return group.RequireAuthorization("Admin"); |
| 19 | + } |
| 20 | + |
| 21 | + static async Task<IResult> GetSales( |
| 22 | + [FromServices] IQuerySession session, |
| 23 | + [FromServices] IOptions<PaginationOptions> paginationOptions, |
| 24 | + [AsParameters] PagedRequest request, |
| 25 | + CancellationToken cancellationToken) |
| 26 | + { |
| 27 | + var paging = request.Normalize(paginationOptions.Value); |
| 28 | + var now = DateTimeOffset.UtcNow; |
| 29 | + |
| 30 | + var books = await session.Query<BookSearchProjection>() |
| 31 | + .Where(b => !b.Deleted) |
| 32 | + .ToListAsync(cancellationToken); |
| 33 | + |
| 34 | + var allSales = books |
| 35 | + .Where(b => b.Sales.Count > 0) |
| 36 | + .SelectMany(b => b.Sales.Select(sale => new SaleDto |
| 37 | + { |
| 38 | + Id = b.Id, |
| 39 | + BookTitle = b.Title, |
| 40 | + BuyerName = string.Empty, |
| 41 | + Date = sale.Start, |
| 42 | + EndDate = sale.End, |
| 43 | + Amount = sale.Percentage, |
| 44 | + Status = now >= sale.Start && now < sale.End ? "Active" |
| 45 | + : now < sale.Start ? "Upcoming" |
| 46 | + : "Expired", |
| 47 | + ETag = ETagHelper.GenerateETag(b.Version) |
| 48 | + })) |
| 49 | + .OrderByDescending(s => s.Date) |
| 50 | + .ToList(); |
| 51 | + |
| 52 | + var totalCount = allSales.Count; |
| 53 | + var page = paging.Page!.Value; |
| 54 | + var pageSize = paging.PageSize!.Value; |
| 55 | + var items = allSales.Skip((page - 1) * pageSize).Take(pageSize).ToList(); |
| 56 | + |
| 57 | + return Results.Ok(new PagedListDto<SaleDto>(items, page, pageSize, totalCount)); |
| 58 | + } |
| 59 | +} |
0 commit comments