Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,22 @@ public class CreateOrderCommandHandler
private readonly IMediator _mediator;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;
private readonly ILogger<CreateOrderCommandHandler> _logger;
private readonly ICatalogPrices _catalogPrices;

// Using DI to inject infrastructure persistence Repositories
public CreateOrderCommandHandler(IMediator mediator,
IOrderingIntegrationEventService orderingIntegrationEventService,
IOrderRepository orderRepository,
IIdentityService identityService,
ILogger<CreateOrderCommandHandler> logger)
ILogger<CreateOrderCommandHandler> logger,
ICatalogPrices catalogPrices)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_identityService = identityService ?? throw new ArgumentNullException(nameof(identityService));
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentNullException(nameof(orderingIntegrationEventService));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_catalogPrices = catalogPrices ?? throw new ArgumentNullException(nameof(catalogPrices));
}

public async Task<bool> Handle(CreateOrderCommand message, CancellationToken cancellationToken)
Expand All @@ -39,9 +42,12 @@ public async Task<bool> Handle(CreateOrderCommand message, CancellationToken can
var address = new Address(message.Street, message.City, message.State, message.Country, message.ZipCode);
var order = new Order(message.UserId, message.UserName, address, message.CardTypeId, message.CardNumber, message.CardSecurityNumber, message.CardHolderName, message.CardExpiration);

// Price each line from the catalog, so a client cannot submit its own unit price.
var prices = await _catalogPrices.GetPricesAsync(message.OrderItems.Select(item => item.ProductId), cancellationToken);
foreach (var item in message.OrderItems)
{
order.AddOrderItem(item.ProductId, item.ProductName, item.UnitPrice, item.Discount, item.PictureUrl, item.Units);
var unitPrice = prices.TryGetValue(item.ProductId, out var current) ? current : item.UnitPrice;
order.AddOrderItem(item.ProductId, item.ProductName, unitPrice, item.Discount, item.PictureUrl, item.Units);
}

_logger.LogInformation("Creating Order - Order: {@Order}", order);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@
using eShop.Ordering.Domain.AggregatesModel.OrderAggregate;

// Regular CommandHandler
public class CreateOrderDraftCommandHandler
public class CreateOrderDraftCommandHandler(ICatalogPrices catalogPrices)
: IRequestHandler<CreateOrderDraftCommand, OrderDraftDTO>
{
public Task<OrderDraftDTO> Handle(CreateOrderDraftCommand message, CancellationToken cancellationToken)
public async Task<OrderDraftDTO> Handle(CreateOrderDraftCommand message, CancellationToken cancellationToken)
{
var order = Order.NewDraft();
var orderItems = message.Items.Select(i => i.ToOrderItemDTO());
var orderItems = message.Items.Select(i => i.ToOrderItemDTO()).ToList();
var prices = await catalogPrices.GetPricesAsync(orderItems.Select(item => item.ProductId), cancellationToken);
foreach (var item in orderItems)
{
order.AddOrderItem(item.ProductId, item.ProductName, item.UnitPrice, item.Discount, item.PictureUrl, item.Units);
var unitPrice = prices.TryGetValue(item.ProductId, out var current) ? current : item.UnitPrice;
order.AddOrderItem(item.ProductId, item.ProductName, unitPrice, item.Discount, item.PictureUrl, item.Units);
}

return Task.FromResult(OrderDraftDTO.FromOrder(order));
return OrderDraftDTO.FromOrder(order);
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/Ordering.API/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ public static void AddApplicationServices(this IHostApplicationBuilder builder)
});
builder.EnrichNpgsqlDbContext<OrderingContext>();

// Orders are priced from the catalog's current prices, not from what the client sends.
builder.AddKeyedNpgsqlDataSource("catalogdb");
services.AddScoped<ICatalogPrices, CatalogPrices>();

services.AddMigration<OrderingContext, OrderingContextSeed>();

// Add the integration services that consume the DbContext
Expand Down
35 changes: 35 additions & 0 deletions src/Ordering.API/Infrastructure/Services/CatalogPrices.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Npgsql;

namespace eShop.Ordering.API.Infrastructure.Services;

/// <summary>
/// The catalog's current price for each product, so an order is priced by the catalog
/// rather than by the unit prices the client sends.
/// </summary>
public interface ICatalogPrices
{
Task<IReadOnlyDictionary<int, decimal>> GetPricesAsync(IEnumerable<int> productIds, CancellationToken cancellationToken = default);
}

public class CatalogPrices([FromKeyedServices("catalogdb")] NpgsqlDataSource catalogDb) : ICatalogPrices
{
public async Task<IReadOnlyDictionary<int, decimal>> GetPricesAsync(IEnumerable<int> productIds, CancellationToken cancellationToken = default)
{
var ids = productIds.Distinct().ToArray();
var prices = new Dictionary<int, decimal>();
if (ids.Length == 0)
{
return prices;
}

await using var command = catalogDb.CreateCommand("""SELECT "Id", "Price" FROM "Catalog" WHERE "Id" = ANY($1)""");
command.Parameters.Add(new NpgsqlParameter { Value = ids });
await using var reader = await command.ExecuteReaderAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
prices[reader.GetInt32(0)] = reader.GetDecimal(1);
}

return prices;
}
}
1 change: 1 addition & 0 deletions src/Ordering.API/Ordering.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

<ItemGroup>
<PackageReference Include="Asp.Versioning.Http" />
<PackageReference Include="Aspire.Npgsql" />
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" />
<PackageReference Include="FluentValidation" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" />
Expand Down
1 change: 1 addition & 0 deletions src/eShop.AppHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
.WithReference(catalogDb);

var orderingApi = builder.AddProject<Projects.Ordering_API>("ordering-api")
.WithReference(catalogDb)
.WithReference(rabbitMq).WaitFor(rabbitMq)
.WithReference(orderDb).WaitFor(orderDb)
.WithHttpHealthCheck("/health")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ public async Task Handle_return_false_if_order_is_not_persisted()

var LoggerMock = Substitute.For<ILogger<CreateOrderCommandHandler>>();
//Act
var handler = new CreateOrderCommandHandler(_mediator, _orderingIntegrationEventService, _orderRepositoryMock, _identityServiceMock, LoggerMock);
var catalogPrices = Substitute.For<ICatalogPrices>();
catalogPrices.GetPricesAsync(Arg.Any<IEnumerable<int>>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<int, decimal>());
var handler = new CreateOrderCommandHandler(_mediator, _orderingIntegrationEventService, _orderRepositoryMock, _identityServiceMock, LoggerMock, catalogPrices);
var cltToken = new CancellationToken();
var result = await handler.Handle(fakeOrderCmd, cltToken);

Expand Down
Loading