77 lines
2.3 KiB
C#
77 lines
2.3 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using System.Text.Json;
|
|
|
|
namespace WebVentaCoche.Helpers
|
|
{
|
|
public static class CartSessionHelper
|
|
{
|
|
private const string CartSessionKey = "CartItems";
|
|
|
|
//Obtiene el diccionario: ProductId -> Quantity
|
|
public static Dictionary<int, int> GetCartItems(ISession session)
|
|
{
|
|
var json = session.GetString(CartSessionKey);
|
|
if (string.IsNullOrEmpty(json))
|
|
return new Dictionary<int, int>();
|
|
|
|
return JsonSerializer.Deserialize<Dictionary<int, int>>(json)
|
|
?? new Dictionary<int, int>();
|
|
}
|
|
|
|
//Guarda el diccionario en la sesión
|
|
private static void SaveCartItems(ISession session, Dictionary<int, int> items)
|
|
{
|
|
var json = JsonSerializer.Serialize(items);
|
|
session.SetString(CartSessionKey, json);
|
|
}
|
|
|
|
//Añade un producto al carrito
|
|
public static void AddToCart(ISession session, int productId)
|
|
{
|
|
var items = GetCartItems(session);
|
|
|
|
if (items.ContainsKey(productId))
|
|
items[productId]++;
|
|
else
|
|
items[productId] = 1;
|
|
|
|
SaveCartItems(session, items);
|
|
}
|
|
|
|
//Actualiza la cantidad de un producto. Si la cantidad es 0 o menor, lo elimina
|
|
public static void UpdateQuantity(ISession session, int productId, int quantity)
|
|
{
|
|
var items = GetCartItems(session);
|
|
if (items.ContainsKey(productId))
|
|
{
|
|
if (quantity <= 0)
|
|
{
|
|
items.Remove(productId);
|
|
}
|
|
else
|
|
{
|
|
items[productId] = quantity;
|
|
}
|
|
SaveCartItems(session, items);
|
|
}
|
|
}
|
|
|
|
//Elimina un producto del carrito
|
|
public static void RemoveFromCart(ISession session, int productId)
|
|
{
|
|
var items = GetCartItems(session);
|
|
if (items.ContainsKey(productId))
|
|
{
|
|
items.Remove(productId);
|
|
}
|
|
SaveCartItems(session, items);
|
|
}
|
|
|
|
//Vacía el carrito entero
|
|
public static void ClearCart(ISession session)
|
|
{
|
|
session.Remove(CartSessionKey);
|
|
}
|
|
}
|
|
}
|