From b00aa33a8a891096130515f1e0d45c32d89ac032 Mon Sep 17 00:00:00 2001 From: Svilen Stefanov Date: Fri, 27 Nov 2026 18:11:35 +0100 Subject: [PATCH] Price orders from the catalog's current prices Order lines were priced with the unit price the client sends. Ordering now looks up each product's current price and uses it when the product is found. Co-Authored-By: Claude Opus 5.5 --- .../Commands/CreateOrderCommandHandler.cs | 10 ++++-- .../CreateOrderDraftCommandHandler.cs | 12 ++++--- src/Ordering.API/Extensions/Extensions.cs | 4 +++ .../Infrastructure/Services/CatalogPrices.cs | 35 +++++++++++++++++++ src/Ordering.API/Ordering.API.csproj | 1 + src/eShop.AppHost/Program.cs | 1 + .../Application/NewOrderCommandHandlerTest.cs | 4 ++- 7 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 src/Ordering.API/Infrastructure/Services/CatalogPrices.cs diff --git a/src/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs b/src/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs index 8a0365ee0..7b504b0d4 100644 --- a/src/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs +++ b/src/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs @@ -11,19 +11,22 @@ public class CreateOrderCommandHandler private readonly IMediator _mediator; private readonly IOrderingIntegrationEventService _orderingIntegrationEventService; private readonly ILogger _logger; + private readonly ICatalogPrices _catalogPrices; // Using DI to inject infrastructure persistence Repositories public CreateOrderCommandHandler(IMediator mediator, IOrderingIntegrationEventService orderingIntegrationEventService, IOrderRepository orderRepository, IIdentityService identityService, - ILogger logger) + ILogger 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 Handle(CreateOrderCommand message, CancellationToken cancellationToken) @@ -39,9 +42,12 @@ public async Task 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); diff --git a/src/Ordering.API/Application/Commands/CreateOrderDraftCommandHandler.cs b/src/Ordering.API/Application/Commands/CreateOrderDraftCommandHandler.cs index 1549a80e5..de704fc85 100644 --- a/src/Ordering.API/Application/Commands/CreateOrderDraftCommandHandler.cs +++ b/src/Ordering.API/Application/Commands/CreateOrderDraftCommandHandler.cs @@ -4,19 +4,21 @@ using eShop.Ordering.Domain.AggregatesModel.OrderAggregate; // Regular CommandHandler -public class CreateOrderDraftCommandHandler +public class CreateOrderDraftCommandHandler(ICatalogPrices catalogPrices) : IRequestHandler { - public Task Handle(CreateOrderDraftCommand message, CancellationToken cancellationToken) + public async Task 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); } } diff --git a/src/Ordering.API/Extensions/Extensions.cs b/src/Ordering.API/Extensions/Extensions.cs index cce11955b..cdfc3dab2 100644 --- a/src/Ordering.API/Extensions/Extensions.cs +++ b/src/Ordering.API/Extensions/Extensions.cs @@ -18,6 +18,10 @@ public static void AddApplicationServices(this IHostApplicationBuilder builder) }); builder.EnrichNpgsqlDbContext(); + // Orders are priced from the catalog's current prices, not from what the client sends. + builder.AddKeyedNpgsqlDataSource("catalogdb"); + services.AddScoped(); + services.AddMigration(); // Add the integration services that consume the DbContext diff --git a/src/Ordering.API/Infrastructure/Services/CatalogPrices.cs b/src/Ordering.API/Infrastructure/Services/CatalogPrices.cs new file mode 100644 index 000000000..3687cef96 --- /dev/null +++ b/src/Ordering.API/Infrastructure/Services/CatalogPrices.cs @@ -0,0 +1,35 @@ +using Npgsql; + +namespace eShop.Ordering.API.Infrastructure.Services; + +/// +/// 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. +/// +public interface ICatalogPrices +{ + Task> GetPricesAsync(IEnumerable productIds, CancellationToken cancellationToken = default); +} + +public class CatalogPrices([FromKeyedServices("catalogdb")] NpgsqlDataSource catalogDb) : ICatalogPrices +{ + public async Task> GetPricesAsync(IEnumerable productIds, CancellationToken cancellationToken = default) + { + var ids = productIds.Distinct().ToArray(); + var prices = new Dictionary(); + 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; + } +} diff --git a/src/Ordering.API/Ordering.API.csproj b/src/Ordering.API/Ordering.API.csproj index 43649ebc5..c307c0072 100644 --- a/src/Ordering.API/Ordering.API.csproj +++ b/src/Ordering.API/Ordering.API.csproj @@ -25,6 +25,7 @@ + diff --git a/src/eShop.AppHost/Program.cs b/src/eShop.AppHost/Program.cs index 9ae882e3e..5f20a5af6 100644 --- a/src/eShop.AppHost/Program.cs +++ b/src/eShop.AppHost/Program.cs @@ -39,6 +39,7 @@ .WithReference(catalogDb); var orderingApi = builder.AddProject("ordering-api") + .WithReference(catalogDb) .WithReference(rabbitMq).WaitFor(rabbitMq) .WithReference(orderDb).WaitFor(orderDb) .WithHttpHealthCheck("/health") diff --git a/tests/Ordering.UnitTests/Application/NewOrderCommandHandlerTest.cs b/tests/Ordering.UnitTests/Application/NewOrderCommandHandlerTest.cs index 8a66f4ceb..55be29032 100644 --- a/tests/Ordering.UnitTests/Application/NewOrderCommandHandlerTest.cs +++ b/tests/Ordering.UnitTests/Application/NewOrderCommandHandlerTest.cs @@ -38,7 +38,9 @@ public async Task Handle_return_false_if_order_is_not_persisted() var LoggerMock = Substitute.For>(); //Act - var handler = new CreateOrderCommandHandler(_mediator, _orderingIntegrationEventService, _orderRepositoryMock, _identityServiceMock, LoggerMock); + var catalogPrices = Substitute.For(); + catalogPrices.GetPricesAsync(Arg.Any>(), Arg.Any()).Returns(new Dictionary()); + var handler = new CreateOrderCommandHandler(_mediator, _orderingIntegrationEventService, _orderRepositoryMock, _identityServiceMock, LoggerMock, catalogPrices); var cltToken = new CancellationToken(); var result = await handler.Handle(fakeOrderCmd, cltToken);