Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

Add order completed feature #1940

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
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
8 changes: 6 additions & 2 deletions src/Services/Identity/Identity.API/Identity.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,12 @@
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.18" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="6.0.0" />
<PackageReference Include="Microsoft.TypeScript.MSBuild" Version="4.7.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.11.1" />
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.1.113" />
<PackageReference Include="Microsoft.Web.LibraryManager.Build" Version="2.1.175" />
<PackageReference Include="Polly" Version="7.2.2" />
<PackageReference Include="Serilog.AspNetCore" Version="4.1.1-dev-00229" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.1-dev-00787" />
Expand All @@ -50,7 +54,7 @@
<PackageReference Include="Serilog.Sinks.Seq" Version="5.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.2.1" />
<PackageReference Include="System.Data.SqlClient" version="4.8.2"/>
<PackageReference Include="System.Data.SqlClient" version="4.8.2" />
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.2.1" />
<PackageReference Include="Azure.Identity" Version="1.4.0" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ public IdentifiedCommand(T command, Guid id)
Command = command;
Id = id;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;

public class SetCompletedOrderStatusCommand : IRequest<bool>
{

[DataMember]
public int OrderNumber { get; private set; }

public SetCompletedOrderStatusCommand(int orderNumber)
{
OrderNumber = orderNumber;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;

// Regular CommandHandler
public class SetCompletedOrderStatusCommandHandler : IRequestHandler<SetCompletedOrderStatusCommand, bool>
{
private readonly IOrderRepository _orderRepository;

public SetCompletedOrderStatusCommandHandler(IOrderRepository orderRepository)
{
_orderRepository = orderRepository;
}

/// <summary>
/// Handler which processes the command when
/// Completed the order
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public async Task<bool> Handle(SetCompletedOrderStatusCommand command, CancellationToken cancellationToken)
{
// Simulate a work time for validating the completed
await Task.Delay(10000, cancellationToken);

var orderToUpdate = await _orderRepository.GetAsync(command.OrderNumber);
if (orderToUpdate == null)
{
return false;
}

orderToUpdate.SetCompletedStatus();
return await _orderRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
}
}


// Use for Idempotency in Command process
public class SetCompletedIdentifiedOrderStatusCommandHandler : IdentifiedCommandHandler<SetCompletedOrderStatusCommand, bool>
{
public SetCompletedIdentifiedOrderStatusCommandHandler(
IMediator mediator,
IRequestManager requestManager,
ILogger<IdentifiedCommandHandler<SetCompletedOrderStatusCommand, bool>> logger)
: base(mediator, requestManager, logger)
{
}

protected override bool CreateResultForDuplicateRequest()
{
return true; // Ignore duplicate requests for processing order.
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.DomainEventHandlers.OrderCompleted;

public class OrderStatusChangedToCompletedDomainEventHandler
: INotificationHandler<OrderStatusChangedToCompletedDomainEvent>
{
private readonly IOrderRepository _orderRepository;
private readonly ILoggerFactory _logger;
private readonly IBuyerRepository _buyerRepository;
private readonly IOrderingIntegrationEventService _orderingIntegrationEventService;


public OrderStatusChangedToCompletedDomainEventHandler(
IOrderRepository orderRepository, ILoggerFactory logger,
IBuyerRepository buyerRepository,
IOrderingIntegrationEventService orderingIntegrationEventService
)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_buyerRepository = buyerRepository ?? throw new ArgumentNullException(nameof(buyerRepository));
_orderingIntegrationEventService = orderingIntegrationEventService ?? throw new ArgumentNullException(nameof(orderingIntegrationEventService));
}

public async Task Handle(OrderStatusChangedToCompletedDomainEvent orderStatusChangedToCompletedDomainEvent, CancellationToken cancellationToken)
{
_logger.CreateLogger<OrderStatusChangedToCompletedDomainEventHandler>()
.LogTrace("Order with Id: {OrderId} has been successfully updated to status {Status} ({Id})",
orderStatusChangedToCompletedDomainEvent.OrderId, nameof(OrderStatus.Complete), OrderStatus.Complete.Id);

var order = await _orderRepository.GetAsync(orderStatusChangedToCompletedDomainEvent.OrderId);
var buyer = await _buyerRepository.FindByIdAsync(order.GetBuyerId.Value.ToString());

var orderStockList = orderStatusChangedToCompletedDomainEvent.OrderItems
.Select(orderItem => new OrderStockItem(orderItem.ProductId, orderItem.GetUnits()));

var orderStatusChangedToCompletedIntegrationEvent = new OrderStatusChangedToCompletedIntegrationEvent(
orderStatusChangedToCompletedDomainEvent.OrderId,
order.OrderStatus.Name,
buyer.Name,
orderStockList);

await _orderingIntegrationEventService.AddAndSaveEventAsync(orderStatusChangedToCompletedIntegrationEvent);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.IntegrationEvents.EventHandling;

public class OrderCompletedFailedIntegrationEventHandler :
IIntegrationEventHandler<OrderCompletedFailedIntegrationEvent>
{
private readonly IMediator _mediator;
private readonly ILogger<OrderCompletedFailedIntegrationEventHandler> _logger;

public OrderCompletedFailedIntegrationEventHandler(
IMediator mediator,
ILogger<OrderCompletedFailedIntegrationEventHandler> logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public async Task Handle(OrderCompletedFailedIntegrationEvent @event)
{
using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}"))
{
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event);

var command = new CancelOrderCommand(@event.OrderId);

_logger.LogInformation(
"----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})",
command.GetGenericTypeName(),
nameof(command.OrderNumber),
command.OrderNumber,
command);

await _mediator.Send(command);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.IntegrationEvents.EventHandling;

public class OrderCompletedSucceededIntegrationEventHandler :
IIntegrationEventHandler<OrderCompletedSucceededIntegrationEvent>
{
private readonly IMediator _mediator;
private readonly ILogger<OrderCompletedSucceededIntegrationEventHandler> _logger;

public OrderCompletedSucceededIntegrationEventHandler(
IMediator mediator,
ILogger<OrderCompletedSucceededIntegrationEventHandler> logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public async Task Handle(OrderCompletedSucceededIntegrationEvent @event)
{
using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}"))
{
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event);

var command = new SetCompletedOrderStatusCommand(@event.OrderId);

_logger.LogInformation(
"----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})",
command.GetGenericTypeName(),
nameof(command.OrderNumber),
command.OrderNumber,
command);

await _mediator.Send(command);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.IntegrationEvents.Events;

public record OrderCompletedFailedIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }

public OrderCompletedFailedIntegrationEvent(int orderId) => OrderId = orderId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.IntegrationEvents.Events;

public record OrderCompletedSucceededIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }

public OrderCompletedSucceededIntegrationEvent(int orderId) => OrderId = orderId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.IntegrationEvents.Events;

public record OrderStatusChangedToCompletedIntegrationEvent : IntegrationEvent
{
public int OrderId { get; }
public string OrderStatus { get; }
public string BuyerName { get; }
public IEnumerable<OrderStockItem> OrderStockItems { get; }

public OrderStatusChangedToCompletedIntegrationEvent(int orderId,
string orderStatus,
string buyerName,
IEnumerable<OrderStockItem> orderStockItems)
{
OrderId = orderId;
OrderStockItems = orderStockItems;
OrderStatus = orderStatus;
BuyerName = buyerName;
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Validations;

public class CompletedOrderCommandValidator : AbstractValidator<SetCompletedOrderStatusCommand>
{
public CompletedOrderCommandValidator(ILogger<CompletedOrderCommandValidator> logger)
{
RuleFor(order => order.OrderNumber).NotEmpty().WithMessage("No orderId found");

logger.LogTrace("----- INSTANCE CREATED - {ClassName}", GetType().Name);
}
}
25 changes: 25 additions & 0 deletions src/Services/Ordering/Ordering.API/Controllers/OrdersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,29 @@ public async Task<ActionResult<OrderDraftDTO>> CreateOrderDraftFromBasketDataAsy

return await _mediator.Send(createOrderDraftCommand);
}


[Route("completed")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> CompletedOrderAsync([FromBody] SetCompletedOrderStatusCommand setCompletedOrderStatusCommand, [FromHeader(Name = "x-requestid")] string requestId)
{
bool commandResult = false;
_logger.LogInformation(
"----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})",
setCompletedOrderStatusCommand.GetGenericTypeName(),
nameof(setCompletedOrderStatusCommand.OrderNumber),
setCompletedOrderStatusCommand.OrderNumber,
setCompletedOrderStatusCommand);
commandResult = await _mediator.Send(setCompletedOrderStatusCommand);
if (!commandResult)
{
return BadRequest();
}


return Ok();

}
}
2 changes: 2 additions & 0 deletions src/Services/Ordering/Ordering.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ private void ConfigureEventBus(IApplicationBuilder app)
eventBus.Subscribe<OrderStockConfirmedIntegrationEvent, IIntegrationEventHandler<OrderStockConfirmedIntegrationEvent>>();
eventBus.Subscribe<OrderStockRejectedIntegrationEvent, IIntegrationEventHandler<OrderStockRejectedIntegrationEvent>>();
eventBus.Subscribe<OrderPaymentFailedIntegrationEvent, IIntegrationEventHandler<OrderPaymentFailedIntegrationEvent>>();
eventBus.Subscribe<OrderCompletedFailedIntegrationEvent, IIntegrationEventHandler<OrderCompletedFailedIntegrationEvent>>();
eventBus.Subscribe<OrderPaymentSucceededIntegrationEvent, IIntegrationEventHandler<OrderPaymentSucceededIntegrationEvent>>();
eventBus.Subscribe<OrderCompletedSucceededIntegrationEvent, IIntegrationEventHandler<OrderCompletedSucceededIntegrationEvent>>();
}

protected virtual void ConfigureAuth(IApplicationBuilder app)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,16 @@ public void SetPaidStatus()
_description = "The payment was performed at a simulated \"American Bank checking bank account ending on XX35071\"";
}
}
public void SetCompletedStatus()
{
if (_orderStatusId == OrderStatus.Paid.Id)
{
AddDomainEvent(new OrderStatusChangedToCompletedDomainEvent(Id, OrderItems));

_orderStatusId = OrderStatus.Complete.Id;
_description = "completed \"Yurt içi cargo ending on XX35071\"";
}
}

public void SetShippedStatus()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ public class OrderStatus
public static OrderStatus Paid = new OrderStatus(4, nameof(Paid).ToLowerInvariant());
public static OrderStatus Shipped = new OrderStatus(5, nameof(Shipped).ToLowerInvariant());
public static OrderStatus Cancelled = new OrderStatus(6, nameof(Cancelled).ToLowerInvariant());
public static OrderStatus Complete = new OrderStatus(7, nameof(Complete).ToLowerInvariant());

public OrderStatus(int id, string name)
: base(id, name)
{
}

public static IEnumerable<OrderStatus> List() =>
new[] { Submitted, AwaitingValidation, StockConfirmed, Paid, Shipped, Cancelled };
new[] { Submitted, AwaitingValidation, StockConfirmed, Paid, Shipped, Cancelled, Complete };

public static OrderStatus FromName(string name)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.Events;

/// <summary>
/// Event used when the order is completed
/// </summary>
public class OrderStatusChangedToCompletedDomainEvent
: INotification
{
public int OrderId { get; }
public IEnumerable<OrderItem> OrderItems { get; }

public OrderStatusChangedToCompletedDomainEvent(int orderId,
IEnumerable<OrderItem> orderItems)
{
OrderId = orderId;
OrderItems = orderItems;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace Microsoft.eShopOnContainers.Services.Ordering.SignalrHub.IntegrationEvents.EventHandling;

public class OrderStatusChangedToCompletedIntegrationEventHandler : IIntegrationEventHandler<OrderStatusChangedToCompletedIntegrationEvent>
{
private readonly IHubContext<NotificationsHub> _hubContext;
private readonly ILogger<OrderStatusChangedToCompletedIntegrationEventHandler> _logger;

public OrderStatusChangedToCompletedIntegrationEventHandler(
IHubContext<NotificationsHub> hubContext,
ILogger<OrderStatusChangedToCompletedIntegrationEventHandler> logger)
{
_hubContext = hubContext ?? throw new ArgumentNullException(nameof(hubContext));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}


public async Task Handle(OrderStatusChangedToCompletedIntegrationEvent @event)
{
using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}"))
{
_logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event);

await _hubContext.Clients
.Group(@event.BuyerName)
.SendAsync("UpdatedOrderState", new { OrderId = @event.OrderId, Status = @event.OrderStatus });
}
}
}
Loading