Browse Source

Merge branch 'order-processflow-redesign' of https://github.com/dotnet-architecture/eShopOnContainers into order-processflow-redesign

# Conflicts:
#	src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs
pull/223/head
Christian Arenas 7 years ago
parent
commit
09a2ab4058
45 changed files with 589 additions and 268 deletions
  1. +5
    -5
      src/BuildingBlocks/EventBus/EventBus.Tests/InMemory_SubscriptionManager_Tests.cs
  2. +2
    -2
      src/BuildingBlocks/EventBus/EventBus/Abstractions/IEventBus.cs
  3. +2
    -2
      src/BuildingBlocks/EventBus/EventBus/IEventBusSubscriptionsManager.cs
  4. +19
    -19
      src/BuildingBlocks/EventBus/EventBus/InMemoryEventBusSubscriptionsManager.cs
  5. +7
    -7
      src/BuildingBlocks/EventBus/EventBus/SubscriptionInfo.cs
  6. +31
    -24
      src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.cs
  7. +1
    -0
      src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj
  8. +1
    -0
      src/Services/Basket/Basket.API/Basket.API.csproj
  9. +10
    -6
      src/Services/Basket/Basket.API/Controllers/BasketController.cs
  10. +0
    -21
      src/Services/Basket/Basket.API/IntegrationEvents/Events/UserCheckoutAccepted.cs
  11. +64
    -0
      src/Services/Basket/Basket.API/IntegrationEvents/Events/UserCheckoutAcceptedIntegrationEvent.cs
  12. +35
    -0
      src/Services/Basket/Basket.API/Model/BasketCheckout.cs
  13. +9
    -6
      src/Services/Basket/Basket.API/Startup.cs
  14. +1
    -0
      src/Services/Catalog/Catalog.API/Catalog.API.csproj
  15. +7
    -1
      src/Services/Catalog/Catalog.API/Startup.cs
  16. +1
    -0
      src/Services/Identity/Identity.API/Identity.API.csproj
  17. +8
    -2
      src/Services/Identity/Identity.API/Startup.cs
  18. +19
    -11
      src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommand.cs
  19. +1
    -1
      src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs
  20. +0
    -14
      src/Services/Ordering/Ordering.API/Application/IntegrationCommands/Commands/SubmitOrderCommandMsg.cs
  21. +40
    -5
      src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs
  22. +62
    -0
      src/Services/Ordering/Ordering.API/Application/IntegrationEvents/Events/UserCheckoutAcceptedIntegrationEvent.cs
  23. +1
    -0
      src/Services/Ordering/Ordering.API/Application/IntegrationEvents/OrderingIntegrationEventService.cs
  24. +18
    -0
      src/Services/Ordering/Ordering.API/Application/Models/BasketItem.cs
  25. +19
    -0
      src/Services/Ordering/Ordering.API/Application/Models/CustomerBasket.cs
  26. +2
    -24
      src/Services/Ordering/Ordering.API/Application/Sagas/OrderProcessSaga.cs
  27. +6
    -11
      src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs
  28. +7
    -8
      src/Services/Ordering/Ordering.API/Startup.cs
  29. +1
    -1
      src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs
  30. +3
    -0
      src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs
  31. +1
    -0
      src/Services/Payment/Payment.API/Payment.API.csproj
  32. +9
    -2
      src/Services/Payment/Payment.API/Startup.cs
  33. +6
    -1
      src/Services/SagaManager/SagaManager/Program.cs
  34. +1
    -0
      src/Services/SagaManager/SagaManager/SagaManager.csproj
  35. +19
    -2
      src/Web/WebMVC/Controllers/OrderController.cs
  36. +10
    -0
      src/Web/WebMVC/Infrastructure/API.cs
  37. +37
    -0
      src/Web/WebMVC/Models/BasketDTO.cs
  38. +11
    -0
      src/Web/WebMVC/Services/BasketService.cs
  39. +2
    -0
      src/Web/WebMVC/Services/IBasketService.cs
  40. +3
    -1
      src/Web/WebMVC/Services/IOrderingService.cs
  41. +26
    -11
      src/Web/WebMVC/Services/OrderingService.cs
  42. +1
    -1
      src/Web/WebMVC/Views/Order/Create.cshtml
  43. +6
    -5
      test/Services/UnitTest/Basket/Application/BasketWebApiTest.cs
  44. +45
    -45
      test/Services/UnitTest/Ordering/Application/OrderControllerTest.cs
  45. +30
    -30
      test/Services/UnitTest/Ordering/Application/OrdersWebApiTest.cs

+ 5
- 5
src/BuildingBlocks/EventBus/EventBus.Tests/InMemory_SubscriptionManager_Tests.cs View File

@ -18,7 +18,7 @@ namespace EventBus.Tests
public void After_One_Event_Subscription_Should_Contain_The_Event()
{
var manager = new InMemoryEventBusSubscriptionsManager();
manager.AddSubscription<TestIntegrationEvent,TestIntegrationEventHandler>(() => new TestIntegrationEventHandler());
manager.AddSubscription<TestIntegrationEvent,TestIntegrationEventHandler>();
Assert.True(manager.HasSubscriptionsForEvent<TestIntegrationEvent>());
}
@ -26,7 +26,7 @@ namespace EventBus.Tests
public void After_All_Subscriptions_Are_Deleted_Event_Should_No_Longer_Exists()
{
var manager = new InMemoryEventBusSubscriptionsManager();
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(() => new TestIntegrationEventHandler());
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>();
manager.RemoveSubscription<TestIntegrationEvent, TestIntegrationEventHandler>();
Assert.False(manager.HasSubscriptionsForEvent<TestIntegrationEvent>());
}
@ -37,7 +37,7 @@ namespace EventBus.Tests
bool raised = false;
var manager = new InMemoryEventBusSubscriptionsManager();
manager.OnEventRemoved += (o, e) => raised = true;
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(() => new TestIntegrationEventHandler());
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>();
manager.RemoveSubscription<TestIntegrationEvent, TestIntegrationEventHandler>();
Assert.True(raised);
}
@ -46,8 +46,8 @@ namespace EventBus.Tests
public void Get_Handlers_For_Event_Should_Return_All_Handlers()
{
var manager = new InMemoryEventBusSubscriptionsManager();
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>(() => new TestIntegrationEventHandler());
manager.AddSubscription<TestIntegrationEvent, TestIntegrationOtherEventHandler>(() => new TestIntegrationOtherEventHandler());
manager.AddSubscription<TestIntegrationEvent, TestIntegrationEventHandler>();
manager.AddSubscription<TestIntegrationEvent, TestIntegrationOtherEventHandler>();
var handlers = manager.GetHandlersForEvent<TestIntegrationEvent>();
Assert.Equal(2, handlers.Count());
}


+ 2
- 2
src/BuildingBlocks/EventBus/EventBus/Abstractions/IEventBus.cs View File

@ -5,10 +5,10 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions
{
public interface IEventBus
{
void Subscribe<T, TH>(Func<TH> handler)
void Subscribe<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>;
void SubscribeDynamic<TH>(string eventName, Func<TH> handler)
void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler;
void UnsubscribeDynamic<TH>(string eventName)


+ 2
- 2
src/BuildingBlocks/EventBus/EventBus/IEventBusSubscriptionsManager.cs View File

@ -10,10 +10,10 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus
{
bool IsEmpty { get; }
event EventHandler<string> OnEventRemoved;
void AddDynamicSubscription<TH>(string eventName, Func<TH> handler)
void AddDynamicSubscription<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler;
void AddSubscription<T, TH>(Func<TH> handler)
void AddSubscription<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>;


+ 19
- 19
src/BuildingBlocks/EventBus/EventBus/InMemoryEventBusSubscriptionsManager.cs View File

@ -26,34 +26,41 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus
public bool IsEmpty => !_handlers.Keys.Any();
public void Clear() => _handlers.Clear();
public void AddDynamicSubscription<TH>(string eventName, Func<TH> handler)
public void AddDynamicSubscription<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
DoAddSubscription(handler, eventName, isDynamic: true);
DoAddSubscription(typeof(TH), eventName, isDynamic: true);
}
public void AddSubscription<T, TH>(Func<TH> handler)
public void AddSubscription<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>
{
var eventName = GetEventKey<T>();
DoAddSubscription(handler, eventName, isDynamic: false);
DoAddSubscription(typeof(TH), eventName, isDynamic: false);
_eventTypes.Add(typeof(T));
}
private void DoAddSubscription(Delegate handler, string eventName, bool isDynamic)
private void DoAddSubscription(Type handlerType, string eventName, bool isDynamic)
{
if (!HasSubscriptionsForEvent(eventName))
{
_handlers.Add(eventName, new List<SubscriptionInfo>());
}
if (_handlers[eventName].Any(s => s.HandlerType == handlerType))
{
throw new ArgumentException(
$"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType));
}
if (isDynamic)
{
_handlers[eventName].Add(SubscriptionInfo.Dynamic(handler));
_handlers[eventName].Add(SubscriptionInfo.Dynamic(handlerType));
}
else
{
_handlers[eventName].Add(SubscriptionInfo.Typed(handler));
_handlers[eventName].Add(SubscriptionInfo.Typed(handlerType));
}
}
@ -115,7 +122,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus
private SubscriptionInfo FindDynamicSubscriptionToRemove<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
return DoFindHandlerToRemove(eventName, typeof(TH));
return DoFindSubscriptionToRemove(eventName, typeof(TH));
}
@ -124,25 +131,18 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus
where TH : IIntegrationEventHandler<T>
{
var eventName = GetEventKey<T>();
return DoFindHandlerToRemove(eventName, typeof(TH));
return DoFindSubscriptionToRemove(eventName, typeof(TH));
}
private SubscriptionInfo DoFindHandlerToRemove(string eventName, Type handlerType)
private SubscriptionInfo DoFindSubscriptionToRemove(string eventName, Type handlerType)
{
if (!HasSubscriptionsForEvent(eventName))
{
return null;
}
foreach (var subscription in _handlers[eventName])
{
var genericArgs = subscription.Factory.GetType().GetGenericArguments();
if (genericArgs.SingleOrDefault() == handlerType)
{
return subscription;
}
}
return null;
return _handlers[eventName].SingleOrDefault(s => s.HandlerType == handlerType);
}
public bool HasSubscriptionsForEvent<T>() where T : IntegrationEvent


+ 7
- 7
src/BuildingBlocks/EventBus/EventBus/SubscriptionInfo.cs View File

@ -7,21 +7,21 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus
public class SubscriptionInfo
{
public bool IsDynamic { get; }
public Delegate Factory { get; }
public Type HandlerType{ get; }
private SubscriptionInfo(bool isDynamic, Delegate factory)
private SubscriptionInfo(bool isDynamic, Type handlerType)
{
IsDynamic = isDynamic;
Factory = factory;
HandlerType = handlerType;
}
public static SubscriptionInfo Dynamic(Delegate factory)
public static SubscriptionInfo Dynamic(Type handlerType)
{
return new SubscriptionInfo(true, factory);
return new SubscriptionInfo(true, handlerType);
}
public static SubscriptionInfo Typed(Delegate factory)
public static SubscriptionInfo Typed(Type handlerType)
{
return new SubscriptionInfo(false, factory);
return new SubscriptionInfo(false, handlerType);
}
}
}


+ 31
- 24
src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.cs View File

@ -1,4 +1,5 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Autofac;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.Extensions.Logging;
@ -26,17 +27,20 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
private readonly IRabbitMQPersistentConnection _persistentConnection;
private readonly ILogger<EventBusRabbitMQ> _logger;
private readonly IEventBusSubscriptionsManager _subsManager;
private readonly ILifetimeScope _autofac;
private readonly string AUTOFAC_SCOPE_NAME = "eshop_event_bus";
private IModel _consumerChannel;
private string _queueName;
public EventBusRabbitMQ(IRabbitMQPersistentConnection persistentConnection, ILogger<EventBusRabbitMQ> logger, IEventBusSubscriptionsManager subsManager)
public EventBusRabbitMQ(IRabbitMQPersistentConnection persistentConnection, ILogger<EventBusRabbitMQ> logger,
ILifetimeScope autofac, IEventBusSubscriptionsManager subsManager)
{
_persistentConnection = persistentConnection ?? throw new ArgumentNullException(nameof(persistentConnection));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager();
_consumerChannel = CreateConsumerChannel();
_autofac = autofac;
_subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
}
@ -97,20 +101,20 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
}
}
public void SubscribeDynamic<TH>(string eventName, Func<TH> handler)
where TH: IDynamicIntegrationEventHandler
public void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler
{
DoInternalSubscription(eventName);
_subsManager.AddDynamicSubscription<TH>(eventName,handler);
_subsManager.AddDynamicSubscription<TH>(eventName);
}
public void Subscribe<T, TH>(Func<TH> handler)
public void Subscribe<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>
{
var eventName = _subsManager.GetEventKey<T>();
DoInternalSubscription(eventName);
_subsManager.AddSubscription<T, TH>(handler);
_subsManager.AddSubscription<T, TH>();
}
private void DoInternalSubscription(string eventName)
@ -140,7 +144,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
}
public void UnsubscribeDynamic<TH>(string eventName)
where TH: IDynamicIntegrationEventHandler
where TH : IDynamicIntegrationEventHandler
{
_subsManager.RemoveDynamicSubscription<TH>(eventName);
}
@ -195,25 +199,28 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
private async Task ProcessEvent(string eventName, string message)
{
if (_subsManager.HasSubscriptionsForEvent(eventName))
{
var subscriptions = _subsManager.GetHandlersForEvent(eventName);
foreach (var subscription in subscriptions)
using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME))
{
if (subscription.IsDynamic)
{
var handler = subscription.Factory.DynamicInvoke() as IDynamicIntegrationEventHandler;
dynamic eventData = JObject.Parse(message);
await handler.Handle(eventData);
}
else
var subscriptions = _subsManager.GetHandlersForEvent(eventName);
foreach (var subscription in subscriptions)
{
var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var handler = subscription.Factory.DynamicInvoke();
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
if (subscription.IsDynamic)
{
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
dynamic eventData = JObject.Parse(message);
await handler.Handle(eventData);
}
else
{
var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var handler = scope.ResolveOptional(subscription.HandlerType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
}
}
}
}


+ 1
- 0
src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj View File

@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="4.5.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="Polly" Version="5.0.6" />


+ 1
- 0
src/Services/Basket/Basket.API/Basket.API.csproj View File

@ -22,6 +22,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.0.0" />
<PackageReference Include="System.Threading" Version="4.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />


+ 10
- 6
src/Services/Basket/Basket.API/Controllers/BasketController.cs View File

@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Basket.API.IntegrationEvents.Events;
using Microsoft.eShopOnContainers.Services.Basket.API.Services;
using Basket.API.Model;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers
{
@ -50,20 +51,23 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers
return Ok(basket);
}
[Route("checkouts")]
[HttpPost]
public async Task<IActionResult> Checkout()
[Route("checkout")]
[HttpPut]
public async Task<IActionResult> Checkout([FromBody]BasketCheckout value)
{
var userId = _identitySvc.GetUserIdentity();
var basket = await _repository.GetBasketAsync(userId);
_eventBus.Publish(new UserCheckoutAccepted(userId, basket));
var eventMessage = new UserCheckoutAcceptedIntegrationEvent(userId, value.City, value.Street,
value.State, value.Country, value.ZipCode, value.CardNumber, value.CardHolderName,
value.CardExpiration, value.CardSecurityNumber, value.CardTypeId, value.Buyer, value.RequestId, basket);
_eventBus.Publish(eventMessage);
if (basket == null)
{
return BadRequest();
}
return Accepted();
}


+ 0
- 21
src/Services/Basket/Basket.API/IntegrationEvents/Events/UserCheckoutAccepted.cs View File

@ -1,21 +0,0 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Basket.API.IntegrationEvents.Events
{
public class UserCheckoutAccepted : IntegrationEvent
{
public string UserId {get; }
CustomerBasket Basket { get; }
public UserCheckoutAccepted(string userId, CustomerBasket basket)
{
UserId = userId;
Basket = basket;
}
}
}

+ 64
- 0
src/Services/Basket/Basket.API/IntegrationEvents/Events/UserCheckoutAcceptedIntegrationEvent.cs View File

@ -0,0 +1,64 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Basket.API.IntegrationEvents.Events
{
public class UserCheckoutAcceptedIntegrationEvent : IntegrationEvent
{
public string UserId { get; }
public int OrderNumber { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public string CardNumber { get; set; }
public string CardHolderName { get; set; }
public DateTime CardExpiration { get; set; }
public string CardSecurityNumber { get; set; }
public int CardTypeId { get; set; }
public string Buyer { get; set; }
public Guid RequestId { get; set; }
public CustomerBasket Basket { get; }
public UserCheckoutAcceptedIntegrationEvent(string userId, string city, string street,
string state, string country, string zipCode, string cardNumber, string cardHolderName,
DateTime cardExpiration, string cardSecurityNumber, int cardTypeId, string buyer, Guid requestId,
CustomerBasket basket)
{
UserId = userId;
City = city;
Street = street;
State = state;
Country = country;
ZipCode = zipCode;
CardNumber = cardNumber;
CardHolderName = cardHolderName;
CardExpiration = cardExpiration;
CardSecurityNumber = cardSecurityNumber;
CardTypeId = cardTypeId;
Buyer = buyer;
Basket = basket;
RequestId = requestId;
}
}
}

+ 35
- 0
src/Services/Basket/Basket.API/Model/BasketCheckout.cs View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Basket.API.Model
{
public class BasketCheckout
{
public string City { get; set; }
public string Street { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public string CardNumber { get; set; }
public string CardHolderName { get; set; }
public DateTime CardExpiration { get; set; }
public string CardSecurityNumber { get; set; }
public int CardTypeId { get; set; }
public string Buyer { get; set; }
public Guid RequestId { get; set; }
}
}

+ 9
- 6
src/Services/Basket/Basket.API/Startup.cs View File

@ -23,6 +23,8 @@ using System.Threading.Tasks;
using System;
using Microsoft.eShopOnContainers.Services.Basket.API.Services;
using Microsoft.AspNetCore.Http;
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace Microsoft.eShopOnContainers.Services.Basket.API
{
@ -41,7 +43,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks(checks =>
@ -112,6 +114,10 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
services.AddTransient<IBasketRepository, RedisBasketRepository>();
services.AddTransient<IIdentityService, IdentityService>();
RegisterServiceBus(services);
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
private void RegisterServiceBus(IServiceCollection services)
@ -167,11 +173,8 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>
(() => app.ApplicationServices.GetRequiredService<ProductPriceChangedIntegrationEventHandler>());
eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>
(() => app.ApplicationServices.GetRequiredService<OrderStartedIntegrationEventHandler>());
eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>();
eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>();
}
}
}

+ 1
- 0
src/Services/Catalog/Catalog.API/Catalog.API.csproj View File

@ -29,6 +29,7 @@
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.Abstractions" Version="1.1.1" />


+ 7
- 1
src/Services/Catalog/Catalog.API/Startup.cs View File

@ -1,5 +1,7 @@
namespace Microsoft.eShopOnContainers.Services.Catalog.API
{
using Autofac;
using Autofac.Extensions.DependencyInjection;
using global::Catalog.API.Infrastructure.Filters;
using global::Catalog.API.IntegrationEvents;
using Microsoft.AspNetCore.Builder;
@ -44,7 +46,7 @@
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
@ -118,6 +120,10 @@
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddSingleton<IEventBus, EventBusRabbitMQ>();
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)


+ 1
- 0
src/Services/Identity/Identity.API/Identity.API.csproj View File

@ -14,6 +14,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.0" />


+ 8
- 2
src/Services/Identity/Identity.API/Startup.cs View File

@ -19,6 +19,8 @@ using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.HealthChecks;
using Identity.API.Certificate;
using Autofac.Extensions.DependencyInjection;
using Autofac;
namespace eShopOnContainers.Identity
{
@ -44,7 +46,7 @@ namespace eShopOnContainers.Identity
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
@ -87,7 +89,11 @@ namespace eShopOnContainers.Identity
.AddInMemoryIdentityResources(Config.GetResources())
.AddInMemoryClients(Config.GetClients(clientUrls))
.AddAspNetIdentity<ApplicationUser>()
.Services.AddTransient<IProfileService, ProfileService>();
.Services.AddTransient<IProfileService, ProfileService>();
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.


+ 19
- 11
src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommand.cs View File

@ -3,6 +3,7 @@ using MediatR;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Collections;
using Ordering.API.Application.Models;
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands
{
@ -52,12 +53,6 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands
[DataMember]
public int CardTypeId { get; private set; }
[DataMember]
public int PaymentId { get; private set; }
[DataMember]
public int BuyerId { get; private set; }
[DataMember]
public IEnumerable<OrderItemDTO> OrderItems => _orderItems;
@ -66,11 +61,11 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands
_orderItems = new List<OrderItemDTO>();
}
public CreateOrderCommand(List<OrderItemDTO> orderItems, string city, string street, string state, string country, string zipcode,
public CreateOrderCommand(List<BasketItem> basketItems, string city, string street, string state, string country, string zipcode,
string cardNumber, string cardHolderName, DateTime cardExpiration,
string cardSecurityNumber, int cardTypeId, int paymentId, int buyerId) : this()
string cardSecurityNumber, int cardTypeId) : this()
{
_orderItems = orderItems;
_orderItems = MapToOrderItems(basketItems);
City = city;
Street = street;
State = state;
@ -82,8 +77,21 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands
CardSecurityNumber = cardSecurityNumber;
CardTypeId = cardTypeId;
CardExpiration = cardExpiration;
PaymentId = paymentId;
BuyerId = buyerId;
}
private List<OrderItemDTO> MapToOrderItems(List<BasketItem> basketItems)
{
var result = new List<OrderItemDTO>();
basketItems.ForEach((item) => {
result.Add(new OrderItemDTO() {
ProductId = int.TryParse(item.Id, out int id) ? id : -1,
ProductName = item.ProductName,
PictureUrl = item.PictureUrl,
UnitPrice = item.UnitPrice,
Units = item.Quantity
});
});
return result;
}
public class OrderItemDTO


+ 1
- 1
src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs View File

@ -43,7 +43,7 @@
// make sure that consistency is preserved across the whole aggregate
var address = new Address(message.Street, message.City, message.State, message.Country, message.ZipCode);
var order = new Order(address , message.CardTypeId, message.CardNumber, message.CardSecurityNumber, message.CardHolderName, message.CardExpiration);
order.SetOrderStatusId(OrderStatus.Submited.Id);
foreach (var item in message.OrderItems)
{
order.AddOrderItem(item.ProductId, item.ProductName, item.UnitPrice, item.Discount, item.PictureUrl, item.Units);


+ 0
- 14
src/Services/Ordering/Ordering.API/Application/IntegrationCommands/Commands/SubmitOrderCommandMsg.cs View File

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
namespace Ordering.API.Application.IntegrationCommands.Commands
{
public class SubmitOrderCommandMsg : IntegrationEvent
{
public int OrderNumber { get; private set; }
//TODO: message should change to Integration command type once command bus is implemented
}
}

+ 40
- 5
src/Services/Ordering/Ordering.API/Application/IntegrationEvents/EventHandling/UserCheckoutAcceptedIntegrationEventHandler.cs View File

@ -1,13 +1,48 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using MediatR;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using System.Threading.Tasks;
namespace Ordering.API.Application.IntegrationEvents.EventHandling
{
public class UserCheckoutAcceptedIntegrationEventHandler : IDynamicIntegrationEventHandler
public class UserCheckoutAcceptedIntegrationEventHandler : IIntegrationEventHandler<UserCheckoutAcceptedIntegrationEvent>
{
public async Task Handle(dynamic eventData)
private readonly IMediator _mediator;
private readonly ILoggerFactory _logger;
public UserCheckoutAcceptedIntegrationEventHandler(IMediator mediator,
IOrderingIntegrationEventService orderingIntegrationEventService,
ILoggerFactory logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// Integration event handler which starts the create order process
/// </summary>
/// <param name="eventMsg">
/// Integration event message which is sent by the
/// basket.api once it has successfully process the
/// order items.
/// </param>
/// <returns></returns>
public async Task Handle(UserCheckoutAcceptedIntegrationEvent eventMsg)
{
int i = 0;
var result = false;
if (eventMsg.RequestId != Guid.Empty)
{
var createOrderCommand = new CreateOrderCommand(eventMsg.Basket.Items, eventMsg.City, eventMsg.Street,
eventMsg.State, eventMsg.Country, eventMsg.ZipCode,
eventMsg.CardNumber, eventMsg.CardHolderName, eventMsg.CardExpiration,
eventMsg.CardSecurityNumber, eventMsg.CardTypeId);
var requestCreateOrder = new IdentifiedCommand<CreateOrderCommand, bool>(createOrderCommand, eventMsg.RequestId);
result = await _mediator.SendAsync(requestCreateOrder);
}
_logger.CreateLogger(nameof(UserCheckoutAcceptedIntegrationEventHandler))
.LogTrace(result ? $"UserCheckoutAccepted integration event has been received and a create new order process is started with requestId: {eventMsg.RequestId}" :
$"UserCheckoutAccepted integration event has been received but a new order process has failed with requestId: {eventMsg.RequestId}");
}
}
}
}

+ 62
- 0
src/Services/Ordering/Ordering.API/Application/IntegrationEvents/Events/UserCheckoutAcceptedIntegrationEvent.cs View File

@ -0,0 +1,62 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Ordering.API.Application.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ordering.API.Application.IntegrationEvents.Events
{
public class UserCheckoutAcceptedIntegrationEvent : IntegrationEvent
{
public string UserId { get; }
public string City { get; set; }
public string Street { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public string CardNumber { get; set; }
public string CardHolderName { get; set; }
public DateTime CardExpiration { get; set; }
public string CardSecurityNumber { get; set; }
public int CardTypeId { get; set; }
public string Buyer { get; set; }
public Guid RequestId { get; set; }
public CustomerBasket Basket { get; }
public UserCheckoutAcceptedIntegrationEvent(string userId, string city, string street,
string state, string country, string zipCode, string cardNumber, string cardHolderName,
DateTime cardExpiration, string cardSecurityNumber, int cardTypeId, string buyer, Guid requestId,
CustomerBasket basket)
{
UserId = userId;
City = city;
Street = street;
State = state;
Country = country;
ZipCode = zipCode;
CardNumber = cardNumber;
CardHolderName = cardHolderName;
CardExpiration = cardExpiration;
CardSecurityNumber = cardSecurityNumber;
CardTypeId = cardTypeId;
Buyer = buyer;
Basket = basket;
RequestId = requestId;
}
}
}

+ 1
- 0
src/Services/Ordering/Ordering.API/Application/IntegrationEvents/OrderingIntegrationEventService.cs View File

@ -7,6 +7,7 @@ using Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF.Utilities
using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure;
using System;
using System.Data.Common;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Ordering.API.Application.IntegrationEvents


+ 18
- 0
src/Services/Ordering/Ordering.API/Application/Models/BasketItem.cs View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ordering.API.Application.Models
{
public class BasketItem
{
public string Id { get; set; }
public string ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
public decimal OldUnitPrice { get; set; }
public int Quantity { get; set; }
public string PictureUrl { get; set; }
}
}

+ 19
- 0
src/Services/Ordering/Ordering.API/Application/Models/CustomerBasket.cs View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Ordering.API.Application.Models
{
public class CustomerBasket
{
public string BuyerId { get; set; }
public List<BasketItem> Items { get; set; }
public CustomerBasket(string customerId)
{
BuyerId = customerId;
Items = new List<BasketItem>();
}
}
}

+ 2
- 24
src/Services/Ordering/Ordering.API/Application/Sagas/OrderProcessSaga.cs View File

@ -7,6 +7,7 @@ using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure;
using Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Idempotency;
using Ordering.API.Application.Commands;
using Ordering.API.Application.IntegrationCommands.Commands;
using Ordering.API.Application.IntegrationEvents.Events;
using Ordering.Domain.Exceptions;
using System;
using System.Collections.Generic;
@ -27,7 +28,6 @@ namespace Ordering.API.Application.Sagas
/// with the validations.
/// </summary>
public class OrderProcessSaga : Saga<Order>,
IIntegrationEventHandler<SubmitOrderCommandMsg>,
IIntegrationEventHandler<ConfirmGracePeriodCommandMsg>,
IAsyncRequestHandler<CancelOrderCommand, bool>
{
@ -43,29 +43,7 @@ namespace Ordering.API.Application.Sagas
_dbContextFactory = dbContextFactory;
_mediator = mediator;
_orderingIntegrationEventService = orderingIntegrationEventService;
}
/// <summary>
/// Command handler which starts the create order process
/// and initializes the saga
/// </summary>
/// <param name="command">
/// Integration command message which is sent by the
/// basket.api once it has successfully process the
/// order items.
/// </param>
/// <returns></returns>
public async Task Handle(SubmitOrderCommandMsg command)
{
var orderSaga = FindSagaById(command.OrderNumber);
CheckValidSagaId(orderSaga);
// TODO: This handler should change to Integration command handler type once command bus is implemented
// TODO: Send createOrder Command
// TODO: Set saga timeout
}
}
/// <summary>
/// Command handler which confirms that the grace period


+ 6
- 11
src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs View File

@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Queries;
using Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.Services;
using Ordering.API.Application.Commands;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
@ -26,23 +27,17 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.API.Controllers
_identityService = identityService ?? throw new ArgumentNullException(nameof(identityService));
}
[Route("new")]
[Route("cancel")]
[HttpPost]
public async Task<IActionResult> CreateOrder([FromBody]CreateOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
public async Task<IActionResult> CancelOrder([FromBody]CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
{
bool commandResult = false;
if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
{
var requestCreateOrder = new IdentifiedCommand<CreateOrderCommand, bool>(command, guid);
commandResult = await _mediator.SendAsync(requestCreateOrder);
var requestCancelOrder = new IdentifiedCommand<CancelOrderCommand, bool>(command, guid);
commandResult = await _mediator.SendAsync(requestCancelOrder);
}
else
{
// If no x-requestid header is found we process the order anyway. This is just temporary to not break existing clients
// that aren't still updated. When all clients were updated this could be removed.
commandResult = await _mediator.SendAsync(command);
}
return commandResult ? (IActionResult)Ok() : (IActionResult)BadRequest();
}


+ 7
- 8
src/Services/Ordering/Ordering.API/Startup.cs View File

@ -4,7 +4,7 @@
using Autofac;
using Autofac.Extensions.DependencyInjection;
using global::Ordering.API.Application.IntegrationEvents;
using global::Ordering.API.Application.IntegrationEvents.EventHandling;
using global::Ordering.API.Application.IntegrationEvents.Events;
using global::Ordering.API.Infrastructure.Middlewares;
using global::Ordering.API.Application.IntegrationCommands.Commands;
using global::Ordering.API.Application.IntegrationEvents.Events;
@ -31,6 +31,7 @@
using System;
using System.Data.Common;
using System.Reflection;
using global::Ordering.API.Application.IntegrationEvents.EventHandling;
public class Startup
{
@ -127,8 +128,7 @@
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddSingleton<IEventBus, EventBusRabbitMQ>();
services.AddTransient<UserCheckoutAcceptedIntegrationEventHandler>();
services.AddTransient<IIntegrationEventHandler, UserCheckoutAcceptedIntegrationEventHandler>();
services.AddTransient<IIntegrationEventHandler<ConfirmGracePeriodCommandMsg>, OrderProcessSaga>();
services.AddTransient<OrderStockConfirmedIntegrationEventHandler>();
services.AddTransient<OrderStockNotConfirmedIntegrationEventHandler>();
@ -156,14 +156,13 @@
app.UseFailingMiddleware();
ConfigureAuth(app);
ConfigureEventBus(app);
app.UseMvcWithDefaultRoute();
app.UseSwagger()
.UseSwaggerUi();
OrderingContextSeed.SeedAsync(app).Wait();
ConfigureEventBus(app);
var integrationEventLogContext = new IntegrationEventLogContext(
new DbContextOptionsBuilder<IntegrationEventLogContext>()
@ -176,9 +175,9 @@
private void ConfigureEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.SubscribeDynamic(
"UserCheckoutAccepted",
() => app.ApplicationServices.GetRequiredService<UserCheckoutAcceptedIntegrationEventHandler>());
eventBus.Subscribe<UserCheckoutAcceptedIntegrationEvent,IIntegrationEventHandler<UserCheckoutAcceptedIntegrationEvent>>(
() => app.ApplicationServices.GetRequiredService<IIntegrationEventHandler<UserCheckoutAcceptedIntegrationEvent>>());
eventBus.Subscribe<ConfirmGracePeriodCommandMsg, IIntegrationEventHandler<ConfirmGracePeriodCommandMsg>>
(() => app.ApplicationServices.GetRequiredService<IIntegrationEventHandler<ConfirmGracePeriodCommandMsg>>());


+ 1
- 1
src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs View File

@ -37,7 +37,7 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.O
private int? _paymentMethodId;
protected Order() { }
protected Order() { _orderItems = new List<OrderItem>(); }
public Order(Address address, int cardTypeId, string cardNumber, string cardSecurityNumber,
string cardHolderName, DateTime cardExpiration, int? buyerId = null, int? paymentMethodId = null)


+ 3
- 0
src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs View File

@ -36,6 +36,9 @@ namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure
public OrderingContext(DbContextOptions options, IMediator mediator) : base(options)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
System.Diagnostics.Debug.WriteLine("OrderingContext::ctor ->" + this.GetHashCode());
}
protected override void OnModelCreating(ModelBuilder modelBuilder)


+ 1
- 0
src/Services/Payment/Payment.API/Payment.API.csproj View File

@ -10,6 +10,7 @@
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.0.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />


+ 9
- 2
src/Services/Payment/Payment.API/Startup.cs View File

@ -1,8 +1,11 @@
using Microsoft.AspNetCore.Builder;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
namespace Payment.API
{
@ -21,7 +24,7 @@ namespace Payment.API
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
@ -38,6 +41,10 @@ namespace Payment.API
TermsOfService = "Terms Of Service"
});
});
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.


+ 6
- 1
src/Services/SagaManager/SagaManager/Program.cs View File

@ -16,7 +16,8 @@ namespace SagaManager
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using Services;
using Autofac.Extensions.DependencyInjection;
using Autofac;
public class Program
{
@ -76,6 +77,10 @@ namespace SagaManager
RegisterServiceBus(services);
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
return services.BuildServiceProvider();
}


+ 1
- 0
src/Services/SagaManager/SagaManager/SagaManager.csproj View File

@ -6,6 +6,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.0.0" />
<PackageReference Include="Dapper" Version="1.50.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="1.1.1" />


+ 19
- 2
src/Web/WebMVC/Controllers/OrderController.cs View File

@ -8,6 +8,7 @@ using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.AspNetCore.Authorization;
using System.Net.Http;
using Polly.CircuitBreaker;
using WebMVC.Models;
namespace Microsoft.eShopOnContainers.WebMVC.Controllers
{
@ -36,14 +37,16 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers
}
[HttpPost]
public async Task<IActionResult> Create(Order model, string action)
public async Task<IActionResult> Checkout(Order model)
{
try
{
if (ModelState.IsValid)
{
var user = _appUserParser.Parse(HttpContext.User);
await _orderSvc.CreateOrder(model);
var basket = _orderSvc.MapOrderToBasket(model);
await _basketSvc.Checkout(basket);
//Redirect to historic list.
return RedirectToAction("Index");
@ -56,6 +59,20 @@ namespace Microsoft.eShopOnContainers.WebMVC.Controllers
return View(model);
}
[HttpPut]
public async Task<IActionResult> Cancel(Order model)
{
if (ModelState.IsValid)
{
var user = _appUserParser.Parse(HttpContext.User);
await _orderSvc.CancelOrder(model);
//Redirect to historic list.
return RedirectToAction("Index");
}
return View(model);
}
public async Task<IActionResult> Detail(string orderId)
{
var user = _appUserParser.Parse(HttpContext.User);


+ 10
- 0
src/Web/WebMVC/Infrastructure/API.cs View File

@ -14,6 +14,11 @@
return baseUri;
}
public static string CheckoutBasket(string baseUri)
{
return $"{baseUri}/checkout";
}
public static string CleanBasket(string baseUri, string basketId)
{
return $"{baseUri}/{basketId}";
@ -36,6 +41,11 @@
{
return $"{baseUri}/new";
}
public static string CancelOrder(string baseUri)
{
return $"{baseUri}/cancel";
}
}
public static class Catalog


+ 37
- 0
src/Web/WebMVC/Models/BasketDTO.cs View File

@ -0,0 +1,37 @@
using System;
using System.ComponentModel.DataAnnotations;
namespace WebMVC.Models
{
public class BasketDTO
{
[Required]
public string City { get; set; }
[Required]
public string Street { get; set; }
[Required]
public string State { get; set; }
[Required]
public string Country { get; set; }
public string ZipCode { get; set; }
[Required]
public string CardNumber { get; set; }
[Required]
public string CardHolderName { get; set; }
[Required]
public DateTime CardExpiration { get; set; }
[Required]
public string CardSecurityNumber { get; set; }
public int CardTypeId { get; set; }
public string Buyer { get; set; }
[Required]
public Guid RequestId { get; set; }
}
}

+ 11
- 0
src/Web/WebMVC/Services/BasketService.cs View File

@ -7,6 +7,7 @@ using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using WebMVC.Models;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -54,6 +55,16 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
return basket;
}
public async Task Checkout(BasketDTO basket)
{
var token = await GetUserTokenAsync();
var updateBasketUri = API.Basket.CheckoutBasket(_remoteServiceBaseUrl);
var response = await _apiClient.PutAsync(updateBasketUri, basket, token);
response.EnsureSuccessStatusCode();
}
public async Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities)
{
var basket = await GetBasket(user);


+ 2
- 0
src/Web/WebMVC/Services/IBasketService.cs View File

@ -3,6 +3,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebMVC.Models;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -11,6 +12,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
Task<Basket> GetBasket(ApplicationUser user);
Task AddItemToBasket(ApplicationUser user, BasketItem product);
Task<Basket> UpdateBasket(Basket basket);
Task Checkout(BasketDTO basket);
Task<Basket> SetQuantities(ApplicationUser user, Dictionary<string, int> quantities);
Order MapBasketToOrder(Basket basket);
Task CleanBasket(ApplicationUser user);


+ 3
- 1
src/Web/WebMVC/Services/IOrderingService.cs View File

@ -3,6 +3,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebMVC.Models;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -10,8 +11,9 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
{
Task<List<Order>> GetMyOrders(ApplicationUser user);
Task<Order> GetOrder(ApplicationUser user, string orderId);
Task CreateOrder(Order order);
Task CancelOrder(Order order);
Order MapUserInfoIntoOrder(ApplicationUser user, Order order);
BasketDTO MapOrderToBasket(Order order);
void OverrideUserInfoIntoOrder(Order original, Order destination);
}
}

+ 26
- 11
src/Web/WebMVC/Services/OrderingService.cs View File

@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using WebMVC.Models;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -65,22 +66,17 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
return order;
}
async public Task CreateOrder(Order order)
async public Task CancelOrder(Order order)
{
var token = await GetUserTokenAsync();
var requestId = order.RequestId.ToString();
var addNewOrderUri = API.Order.AddNewOrder(_remoteServiceBaseUrl);
order.CardTypeId = 1;
order.CardExpirationApiFormat();
SetFakeIdToProducts(order);
var response = await _apiClient.PostAsync(addNewOrderUri, order, token, requestId);
var cancelOrderUri = API.Order.CancelOrder(_remoteServiceBaseUrl);
var response = await _apiClient.PutAsync(cancelOrderUri, order, token, requestId);
if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new Exception("Error creating order, try later.");
throw new Exception("Error cancelling order, try later.");
}
response.EnsureSuccessStatusCode();
@ -100,6 +96,25 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
destination.CardSecurityNumber = original.CardSecurityNumber;
}
public BasketDTO MapOrderToBasket(Order order)
{
return new BasketDTO()
{
City = order.City,
Street = order.Street,
State = order.State,
Country = order.Country,
ZipCode = order.ZipCode,
CardNumber = order.CardNumber,
CardHolderName = order.CardHolderName,
CardExpiration = order.CardExpiration,
CardSecurityNumber = order.CardSecurityNumber,
CardTypeId = order.CardTypeId,
Buyer = order.Buyer,
RequestId = order.RequestId
};
}
void SetFakeIdToProducts(Order order)
{
var id = 1;
@ -111,6 +126,6 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var context = _httpContextAccesor.HttpContext;
return await context.Authentication.GetTokenAsync("access_token");
}
}
}
}

+ 1
- 1
src/Web/WebMVC/Views/Order/Create.cshtml View File

@ -9,7 +9,7 @@
@Html.Partial("_Header", new Header() { Controller = "Cart", Text = "Back to cart" })
<div class="container">
<form method="post" asp-controller="Order" asp-action="Create">
<form method="post" asp-controller="Order" asp-action="Checkout">
<section class="esh-orders_new-section">
<div class="row">
@foreach (var error in ViewData.ModelState.Values.SelectMany(err => err.Errors)) {


+ 6
- 5
test/Services/UnitTest/Basket/Application/BasketWebApiTest.cs View File

@ -1,4 +1,5 @@
using Basket.API.IntegrationEvents.Events;
using Basket.API.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.Services.Basket.API.Controllers;
@ -35,7 +36,7 @@ namespace UnitTest.Basket.Application
.Returns(Task.FromResult(fakeCustomerBasket));
_identityServiceMock.Setup(x => x.GetUserIdentity()).Returns(fakeCustomerId);
_serviceBusMock.Setup(x => x.Publish(It.IsAny<UserCheckoutAccepted>()));
_serviceBusMock.Setup(x => x.Publish(It.IsAny<UserCheckoutAcceptedIntegrationEvent>()));
//Act
var basketController = new BasketController(
_basketRepositoryMock.Object, _identityServiceMock.Object, _serviceBusMock.Object);
@ -56,7 +57,7 @@ namespace UnitTest.Basket.Application
_basketRepositoryMock.Setup(x => x.UpdateBasketAsync(It.IsAny<CustomerBasket>()))
.Returns(Task.FromResult(fakeCustomerBasket));
_identityServiceMock.Setup(x => x.GetUserIdentity()).Returns(fakeCustomerId);
_serviceBusMock.Setup(x => x.Publish(It.IsAny<UserCheckoutAccepted>()));
_serviceBusMock.Setup(x => x.Publish(It.IsAny<UserCheckoutAcceptedIntegrationEvent>()));
//Act
var basketController = new BasketController(
_basketRepositoryMock.Object, _identityServiceMock.Object, _serviceBusMock.Object);
@ -79,7 +80,7 @@ namespace UnitTest.Basket.Application
var basketController = new BasketController(
_basketRepositoryMock.Object, _identityServiceMock.Object, _serviceBusMock.Object);
var result = await basketController.Checkout() as BadRequestResult;
var result = await basketController.Checkout(new BasketCheckout()) as BadRequestResult;
Assert.NotNull(result);
}
@ -95,8 +96,8 @@ namespace UnitTest.Basket.Application
var basketController = new BasketController(
_basketRepositoryMock.Object, _identityServiceMock.Object, _serviceBusMock.Object);
var result = await basketController.Checkout() as AcceptedResult;
_serviceBusMock.Verify(mock => mock.Publish(It.IsAny<UserCheckoutAccepted>()), Times.Once);
var result = await basketController.Checkout(new BasketCheckout()) as AcceptedResult;
_serviceBusMock.Verify(mock => mock.Publish(It.IsAny<UserCheckoutAcceptedIntegrationEvent>()), Times.Once);
Assert.NotNull(result);
}


+ 45
- 45
test/Services/UnitTest/Ordering/Application/OrderControllerTest.cs View File

@ -95,51 +95,51 @@ namespace UnitTest.Ordering.Application
Assert.IsAssignableFrom<Order>(viewResult.ViewData.Model);
}
[Fact]
public async Task Post_create_order_success()
{
//Arrange
var fakeOrder = GetFakeOrder();
_basketServiceMock.Setup(x => x.CleanBasket(It.IsAny<ApplicationUser>()))
.Returns(Task.FromResult(1));
_orderServiceMock.Setup(x => x.CreateOrder(It.IsAny<Order>()))
.Returns(Task.FromResult(1));
//Act
var orderController = new OrderController(_orderServiceMock.Object, _basketServiceMock.Object, _identityParserMock.Object);
orderController.ControllerContext.HttpContext = _contextMock.Object;
var actionResult = await orderController.Create(fakeOrder, "fakeAction");
//Assert
var redirectToActionResult = Assert.IsType<RedirectToActionResult>(actionResult);
Assert.Null(redirectToActionResult.ControllerName);
Assert.Equal("Index", redirectToActionResult.ActionName);
}
[Fact]
public async Task Post_create_order_fail()
{
//Arrange
var fakeOrder = GetFakeOrder();
_basketServiceMock.Setup(x => x.CleanBasket(It.IsAny<ApplicationUser>()))
.Returns(Task.FromResult(1));
_orderServiceMock.Setup(x => x.CreateOrder(It.IsAny<Order>()))
.Returns(Task.FromResult(1));
//Act
var orderController = new OrderController(_orderServiceMock.Object, _basketServiceMock.Object, _identityParserMock.Object);
orderController.ControllerContext.HttpContext = _contextMock.Object;
orderController.ModelState.AddModelError("fakeError", "fakeError");
var actionResult = await orderController.Create(fakeOrder, "action");
//Assert
var viewResult = Assert.IsType<ViewResult>(actionResult);
Assert.IsAssignableFrom<Order>(viewResult.ViewData.Model);
}
//[Fact]
//public async Task Post_create_order_success()
//{
// //Arrange
// var fakeOrder = GetFakeOrder();
// _basketServiceMock.Setup(x => x.CleanBasket(It.IsAny<ApplicationUser>()))
// .Returns(Task.FromResult(1));
// _orderServiceMock.Setup(x => x.CreateOrder(It.IsAny<Order>()))
// .Returns(Task.FromResult(1));
// //Act
// var orderController = new OrderController(_orderServiceMock.Object, _basketServiceMock.Object, _identityParserMock.Object);
// orderController.ControllerContext.HttpContext = _contextMock.Object;
// var actionResult = await orderController.Create(fakeOrder, "fakeAction");
// //Assert
// var redirectToActionResult = Assert.IsType<RedirectToActionResult>(actionResult);
// Assert.Null(redirectToActionResult.ControllerName);
// Assert.Equal("Index", redirectToActionResult.ActionName);
//}
//[Fact]
//public async Task Post_create_order_fail()
//{
// //Arrange
// var fakeOrder = GetFakeOrder();
// _basketServiceMock.Setup(x => x.CleanBasket(It.IsAny<ApplicationUser>()))
// .Returns(Task.FromResult(1));
// _orderServiceMock.Setup(x => x.CreateOrder(It.IsAny<Order>()))
// .Returns(Task.FromResult(1));
// //Act
// var orderController = new OrderController(_orderServiceMock.Object, _basketServiceMock.Object, _identityParserMock.Object);
// orderController.ControllerContext.HttpContext = _contextMock.Object;
// orderController.ModelState.AddModelError("fakeError", "fakeError");
// var actionResult = await orderController.Create(fakeOrder, "action");
// //Assert
// var viewResult = Assert.IsType<ViewResult>(actionResult);
// Assert.IsAssignableFrom<Order>(viewResult.ViewData.Model);
//}
private BasketModel GetFakeBasket(string buyerId)
{


+ 30
- 30
test/Services/UnitTest/Ordering/Application/OrdersWebApiTest.cs View File

@ -25,36 +25,36 @@ namespace UnitTest.Ordering.Application
_identityServiceMock = new Mock<IIdentityService>();
}
[Fact]
public async Task Create_order_with_requestId_success()
{
//Arrange
_mediatorMock.Setup(x => x.SendAsync(It.IsAny<IdentifiedCommand<CreateOrderCommand, bool>>()))
.Returns(Task.FromResult(true));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.CreateOrder(new CreateOrderCommand(), Guid.NewGuid().ToString()) as OkResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
}
[Fact]
public async Task Create_order_bad_request()
{
//Arrange
_mediatorMock.Setup(x => x.SendAsync(It.IsAny<IdentifiedCommand<CreateOrderCommand, bool>>()))
.Returns(Task.FromResult(true));
//Act
var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
var actionResult = await orderController.CreateOrder(new CreateOrderCommand(), String.Empty) as BadRequestResult;
//Assert
Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.BadRequest);
}
//[Fact]
//public async Task Create_order_with_requestId_success()
//{
// //Arrange
// _mediatorMock.Setup(x => x.SendAsync(It.IsAny<IdentifiedCommand<CreateOrderCommand, bool>>()))
// .Returns(Task.FromResult(true));
// //Act
// var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
// var actionResult = await orderController.CreateOrder(new CreateOrderCommand(), Guid.NewGuid().ToString()) as OkResult;
// //Assert
// Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.OK);
//}
//[Fact]
//public async Task Create_order_bad_request()
//{
// //Arrange
// _mediatorMock.Setup(x => x.SendAsync(It.IsAny<IdentifiedCommand<CreateOrderCommand, bool>>()))
// .Returns(Task.FromResult(true));
// //Act
// var orderController = new OrdersController(_mediatorMock.Object, _orderQueriesMock.Object, _identityServiceMock.Object);
// var actionResult = await orderController.CreateOrder(new CreateOrderCommand(), String.Empty) as BadRequestResult;
// //Assert
// Assert.Equal(actionResult.StatusCode, (int)System.Net.HttpStatusCode.BadRequest);
//}
[Fact]
public async Task Get_orders_success()


Loading…
Cancel
Save