コード例 #1
0
        private async Task CapturePayment(OrderItemRemovedFromStockIntegrationEvent message)
        {
            using var scope = _serviceProvider.CreateScope();
            var paymentService = scope.ServiceProvider.GetRequiredService <IPaymentService>();
            var response       = await paymentService.CapturePayment(message.OrderId);

            if (!response.ValidResult.IsValid)
            {
                throw new DomainException($"Error to process the payment for the order {message.OrderId}");
            }

            //will be captured by the Order API
            await _messageBus.PublishAsync(new OrderPaidIntegrationEvent(message.CustomerId, message.OrderId));
        }
コード例 #2
0
        private async Task RemoveFromStock(OrderAuthorizedIntegrationEvent message)
        {
            using var scope = _serviceProvider.CreateScope();

            var productsAvailable = new List <Product>();
            var productRepository = scope.ServiceProvider.GetRequiredService <IProductRepository>();
            var productIds        = string.Join(",", message.Items.Select(i => i.Key));
            var products          = await productRepository.GetProductsById(productIds);

            if (products.Count != message.Items.Count)
            {
                CancelOrderWithoutStock(message);
                return;
            }

            foreach (var product in products)
            {
                var qty = message.Items.FirstOrDefault(p => p.Key == product.Id).Value;

                if (product.IsAvailable(qty))
                {
                    product.RemoveStock(qty);
                    productsAvailable.Add(product);
                }
            }

            if (productsAvailable.Count != message.Items.Count)
            {
                CancelOrderWithoutStock(message);
                return;
            }

            foreach (var product in productsAvailable)
            {
                productRepository.Update(product);
            }

            if (!await productRepository.UnitOfWork.Commit())
            {
                //this exception will not be market as completed and it will return to the queue to be managed later.
                //This needs to be checked, depends on the situation is not better to throw an exception, but manage this in a log process, etc.
                throw new DomainException($"Error to update the stock of the order {message.OrderId}");
            }

            var orderItemRemovedStock = new OrderItemRemovedFromStockIntegrationEvent(message.CustomerId, message.OrderId);
            await _messageBus.PublishAsync(orderItemRemovedStock); //Payment API will subscribe this event
        }