129 lines
3.1 KiB
C#
129 lines
3.1 KiB
C#
using LiteCharms.Features.Abstractions;
|
|
using LiteCharms.Features.MidrandBooks.Orders.Models;
|
|
using LiteCharms.Features.MidrandBooks.Products.Models;
|
|
|
|
namespace LiteCharms.Features.MidrandBooks.Orders;
|
|
|
|
public sealed class CartService : IService
|
|
{
|
|
private Cart cart = new();
|
|
|
|
public Cart GetCart() => cart;
|
|
|
|
public void LoadCart(Cart savedCart) => cart = savedCart;
|
|
|
|
public void AddItem(ProductPrice productPrice)
|
|
{
|
|
var itemExists = false;
|
|
|
|
for (var i = 0; i < cart.Items.Count; i++)
|
|
{
|
|
if (cart.Items[i].Price!.Id == productPrice.Id)
|
|
{
|
|
cart.Items[i].Quantity++;
|
|
cart.Items[i].Amount += productPrice.Amount;
|
|
|
|
itemExists = true;
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!itemExists)
|
|
cart.Items.Add(new CartItem
|
|
{
|
|
Price = productPrice,
|
|
Amount = productPrice.Amount,
|
|
Quantity = 1,
|
|
});
|
|
|
|
CalculateTotalPrice();
|
|
}
|
|
|
|
public void UpdateQuantity(long productPriceId, int newQuantity)
|
|
{
|
|
if (newQuantity <= 0)
|
|
{
|
|
RemoveAllSameItem(productPriceId);
|
|
|
|
return;
|
|
}
|
|
|
|
for (var i = 0; i < cart.Items.Count; i++)
|
|
{
|
|
if (cart.Items[i].Price!.Id == productPriceId)
|
|
{
|
|
var oldQuantity = cart.Items[i].Quantity;
|
|
var pricePerUnit = cart.Items[i].Price!.Amount;
|
|
|
|
cart.Items[i].Quantity = newQuantity;
|
|
cart.Items[i].Amount = pricePerUnit * newQuantity;
|
|
break;
|
|
}
|
|
}
|
|
|
|
CalculateTotalPrice();
|
|
}
|
|
|
|
public void RemoveOneItem(long productPriceId)
|
|
{
|
|
for (var i = 0; i < cart.Items.Count; i++)
|
|
{
|
|
if (cart.Items[i].Price!.Id == productPriceId)
|
|
{
|
|
if (cart.Items[i].Quantity <= 1)
|
|
{
|
|
cart.Items.RemoveAt(i);
|
|
}
|
|
else
|
|
{
|
|
cart.Items[i].Quantity--;
|
|
cart.Items[i].Amount -= cart.Items[i].Price!.Amount;
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
|
|
CalculateTotalPrice();
|
|
}
|
|
|
|
public void RemoveAllSameItem(long productPriceId)
|
|
{
|
|
if (cart.Items.Count == 0) return;
|
|
|
|
var item = cart.Items.FirstOrDefault(i => i.Price?.Id == productPriceId);
|
|
|
|
if (item is not null) cart.Items.Remove(item);
|
|
|
|
CalculateTotalPrice();
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
if(cart.CustomerId is not null || cart.OrderId is not null)
|
|
{
|
|
cart.TotalPrice = 0;
|
|
cart.TotalVat = 0;
|
|
cart.Items.Clear();
|
|
|
|
return;
|
|
}
|
|
|
|
cart = new Cart();
|
|
}
|
|
|
|
public decimal CalculateTotalPrice()
|
|
{
|
|
if (cart.Items.Count == 0) return 0;
|
|
|
|
var gross = cart.Items.Sum(i => i.Amount);
|
|
|
|
if (!cart.IsVatInclusive) cart.TotalVat = gross * cart.VatRate;
|
|
|
|
cart.TotalPrice = gross + cart.TotalVat;
|
|
|
|
return cart.TotalPrice;
|
|
}
|
|
}
|