/
ShoppingCartDetails.cs
121 lines (95 loc) · 3.09 KB
/
ShoppingCartDetails.cs
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using Carts.ShoppingCarts.AddingProduct;
using Carts.ShoppingCarts.CancelingCart;
using Carts.ShoppingCarts.ConfirmingCart;
using Carts.ShoppingCarts.OpeningCart;
using Carts.ShoppingCarts.Products;
using Carts.ShoppingCarts.RemovingProduct;
using Core.Extensions;
using Core.Projections;
namespace Carts.ShoppingCarts.GettingCartById;
public class ShoppingCartDetails: IVersionedProjection
{
public Guid Id { get; set; }
public Guid ClientId { get; set; }
public ShoppingCartStatus Status { get; set; }
public IList<PricedProductItem> ProductItems { get; set; } = default!;
public decimal TotalPrice => ProductItems.Sum(pi => pi.TotalPrice);
public long Version { get; set; }
public void Evolve(object @event)
{
switch (@event)
{
case ShoppingCartOpened cartOpened:
Apply(cartOpened);
return;
case ProductAdded cartOpened:
Apply(cartOpened);
return;
case ProductRemoved cartOpened:
Apply(cartOpened);
return;
case ShoppingCartConfirmed cartOpened:
Apply(cartOpened);
return;
case ShoppingCartCanceled cartCanceled:
Apply(cartCanceled);
return;
}
}
public void Apply(ShoppingCartOpened @event)
{
Id = @event.CartId;
ClientId = @event.ClientId;
ProductItems = new List<PricedProductItem>();
Status = @event.ShoppingCartStatus;
Version = 0;
}
public void Apply(ProductAdded @event)
{
Version++;
var newProductItem = @event.ProductItem;
var existingProductItem = FindProductItemMatchingWith(newProductItem);
if (existingProductItem is null)
{
ProductItems.Add(newProductItem);
return;
}
ProductItems.Replace(
existingProductItem,
existingProductItem.MergeWith(newProductItem)
);
}
public void Apply(ProductRemoved @event)
{
Version++;
var productItemToBeRemoved = @event.ProductItem;
var existingProductItem = FindProductItemMatchingWith(@event.ProductItem);
if (existingProductItem == null)
return;
if (existingProductItem.HasTheSameQuantity(productItemToBeRemoved))
{
ProductItems.Remove(existingProductItem);
return;
}
ProductItems.Replace(
existingProductItem,
existingProductItem.Substract(productItemToBeRemoved)
);
}
public void Apply(ShoppingCartConfirmed @event)
{
Version++;
Status = ShoppingCartStatus.Confirmed;
}
public void Apply(ShoppingCartCanceled @event)
{
Version++;
Status = ShoppingCartStatus.Canceled;
}
private PricedProductItem? FindProductItemMatchingWith(PricedProductItem productItem)
{
return ProductItems
.SingleOrDefault(pi => pi.MatchesProductAndPrice(productItem));
}
public ulong LastProcessedPosition { get; set; }
}