115 lines
2.4 KiB
C#
115 lines
2.4 KiB
C#
using System.Text.Json;
|
|
|
|
using TechnoWorld.Data;
|
|
using TechnoWorld.Models;
|
|
|
|
namespace TechnoWorld.Services;
|
|
|
|
public class CartService
|
|
{
|
|
private const string SessionKey = "CartItems";
|
|
private readonly IHttpContextAccessor _http;
|
|
|
|
public CartService(IHttpContextAccessor http)
|
|
{
|
|
_http = http;
|
|
}
|
|
|
|
public List<CartItem> GetItems()
|
|
{
|
|
var ids = GetIds();
|
|
var items = new List<CartItem>();
|
|
|
|
foreach (var (productId, quantity) in ids)
|
|
{
|
|
var product = ProductStore.Products.FirstOrDefault(p => p.Id == productId);
|
|
if (product == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
items.Add(new CartItem { ProductId = productId, Product = product, Quantity = quantity });
|
|
}
|
|
|
|
return items;
|
|
}
|
|
|
|
public int GetCount()
|
|
{
|
|
return GetIds().Values.Sum();
|
|
}
|
|
|
|
public decimal GetTotal()
|
|
{
|
|
return GetItems().Sum(i => i.Subtotal);
|
|
}
|
|
|
|
public void Add(int productId, int quantity = 1)
|
|
{
|
|
var ids = GetIds();
|
|
ids[productId] = ids.GetValueOrDefault(productId) + quantity;
|
|
Save(ids);
|
|
}
|
|
|
|
public void SetQuantity(int productId, int quantity)
|
|
{
|
|
var ids = GetIds();
|
|
if (quantity <= 0)
|
|
{
|
|
ids.Remove(productId);
|
|
}
|
|
else
|
|
{
|
|
ids[productId] = quantity;
|
|
}
|
|
|
|
Save(ids);
|
|
}
|
|
|
|
public void Remove(int productId)
|
|
{
|
|
var ids = GetIds();
|
|
ids.Remove(productId);
|
|
Save(ids);
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
_http.HttpContext?.Session.Remove(SessionKey);
|
|
}
|
|
|
|
private Dictionary<int, int> GetIds()
|
|
{
|
|
var session = _http.HttpContext?.Session;
|
|
if (session == null)
|
|
{
|
|
return new Dictionary<int, int>();
|
|
}
|
|
|
|
var json = session.GetString(SessionKey);
|
|
if (string.IsNullOrEmpty(json))
|
|
{
|
|
return new Dictionary<int, int>();
|
|
}
|
|
|
|
try
|
|
{
|
|
return JsonSerializer.Deserialize<Dictionary<int, int>>(json) ?? new Dictionary<int, int>();
|
|
}
|
|
catch
|
|
{
|
|
return new Dictionary<int, int>();
|
|
}
|
|
}
|
|
|
|
private void Save(Dictionary<int, int> ids)
|
|
{
|
|
var session = _http.HttpContext?.Session;
|
|
if (session == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
session.SetString(SessionKey, JsonSerializer.Serialize(ids));
|
|
}
|
|
} |