Repository navigation
Expand file tree
/
Copy pathCreateOrderDraftCommandHandler.cs
More file actions
61 lines (50 loc) · 1.91 KB
/
Copy pathCreateOrderDraftCommandHandler.cs
File metadata and controls
61 lines (50 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
namespace eShop.Ordering.API.Application.Commands;
using eShop.Ordering.API.Extensions;
using eShop.Ordering.Domain.AggregatesModel.OrderAggregate;
// Regular CommandHandler
public class CreateOrderDraftCommandHandler(ICatalogPrices catalogPrices)
: IRequestHandler<CreateOrderDraftCommand, OrderDraftDTO>
{
public async Task<OrderDraftDTO> Handle(CreateOrderDraftCommand message, CancellationToken cancellationToken)
{
var order = Order.NewDraft();
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)
{
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 OrderDraftDTO.FromOrder(order);
}
}
public record OrderDraftDTO
{
public IEnumerable<OrderItemDTO> OrderItems { get; init; }
public decimal Total { get; init; }
public static OrderDraftDTO FromOrder(Order order)
{
return new OrderDraftDTO()
{
OrderItems = order.OrderItems.Select(oi => new OrderItemDTO
{
Discount = oi.Discount,
ProductId = oi.ProductId,
UnitPrice = oi.UnitPrice,
PictureUrl = oi.PictureUrl,
Units = oi.Units,
ProductName = oi.ProductName
}),
Total = order.GetTotal()
};
}
}
public record OrderItemDTO
{
public int ProductId { get; init; }
public string ProductName { get; init; }
public decimal UnitPrice { get; init; }
public decimal Discount { get; init; }
public int Units { get; init; }
public string PictureUrl { get; init; }
}