62 lines
1.6 KiB
C#
62 lines
1.6 KiB
C#
|
|
namespace FrontOffice.Main.Utilities;
|
||
|
|
|
||
|
|
public record CartItem(long ProductId, string Title, string ImageUrl, long UnitPrice, int Quantity)
|
||
|
|
{
|
||
|
|
public long LineTotal => UnitPrice * Quantity;
|
||
|
|
}
|
||
|
|
|
||
|
|
public class CartService
|
||
|
|
{
|
||
|
|
private readonly List<CartItem> _items = new();
|
||
|
|
public event Action? OnChange;
|
||
|
|
|
||
|
|
public IReadOnlyList<CartItem> Items => _items.AsReadOnly();
|
||
|
|
public long Total => _items.Sum(i => i.LineTotal);
|
||
|
|
public int Count => _items.Sum(i => i.Quantity);
|
||
|
|
|
||
|
|
public void Add(Product product, int quantity = 1)
|
||
|
|
{
|
||
|
|
if (quantity <= 0) return;
|
||
|
|
var existing = _items.FirstOrDefault(i => i.ProductId == product.Id);
|
||
|
|
if (existing is null)
|
||
|
|
{
|
||
|
|
_items.Add(new CartItem(product.Id, product.Title, product.ImageUrl, product.Price, quantity));
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
var idx = _items.IndexOf(existing);
|
||
|
|
_items[idx] = existing with { Quantity = existing.Quantity + quantity };
|
||
|
|
}
|
||
|
|
Notify();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void UpdateQuantity(long productId, int quantity)
|
||
|
|
{
|
||
|
|
var existing = _items.FirstOrDefault(i => i.ProductId == productId);
|
||
|
|
if (existing is null) return;
|
||
|
|
if (quantity <= 0)
|
||
|
|
{
|
||
|
|
Remove(productId);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
var idx = _items.IndexOf(existing);
|
||
|
|
_items[idx] = existing with { Quantity = quantity };
|
||
|
|
Notify();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Remove(long productId)
|
||
|
|
{
|
||
|
|
_items.RemoveAll(i => i.ProductId == productId);
|
||
|
|
Notify();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Clear()
|
||
|
|
{
|
||
|
|
_items.Clear();
|
||
|
|
Notify();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Notify() => OnChange?.Invoke();
|
||
|
|
}
|
||
|
|
|