-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCartHelper.cs
89 lines (79 loc) · 3.32 KB
/
CartHelper.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using littlebreadloaf.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace littlebreadloaf
{
public static class CartHelper
{
public const string CartCookieName = "LittleBreadLoaf.CartID";
public const string PreOrderCookie = "LittleBreadLoaf.PreOrderMode";
public static async Task<ObjectResult> AddToCart(ProductContext context,
Guid productID,
ClaimsPrincipal user,
HttpContext http)
{
Data.Cart cart = null;
Data.CartItem item = null;
var cookie = http.Request.Cookies[CartCookieName];
bool invalidCookieDetected = false;
if(!string.IsNullOrEmpty(cookie) && !Guid.TryParse(cookie, out Guid parsedCookie))
{
http.Response.Cookies.Delete(CartCookieName);
invalidCookieDetected = true;
}
if (http.Request.Cookies[CartCookieName] == null || invalidCookieDetected)
{
cart = new Data.Cart()
{
CartID = Guid.NewGuid(),
Created = DateTime.Now,
CheckedOut = new DateTime(9999, 12, 31)
};
context.Cart.Add(cart);
var cookieOptions = new CookieOptions
{
IsEssential = true //Prevents the "accept cookies" dialog from preventing this cookie from being sent
};
http.Response.Cookies.Append(CartCookieName, cart.CartID.ToString(), cookieOptions);
}
else
{
var cartID = http.Request.Cookies[CartCookieName];
var parsedCartId = Guid.Parse(cartID);
cart = context.Cart.FirstOrDefault(m => m.CartID == parsedCartId);
item = context.CartItem.FirstOrDefault(m => m.CartID == parsedCartId && m.ProductID == productID);
}
if (item != null)
{
item.Quantity++;
context.CartItem.Update(item);
await context.SaveChangesAsync();
}
else
{
var product = context.Product.FirstOrDefault(m => m.ProductID == productID);
item = new CartItem()
{
CartItemID = Guid.NewGuid(),
CartID = cart.CartID,
ProductID = productID,
Quantity = 1,
Price = product.Price,
Created = DateTime.Now
};
context.CartItem.Add(item);
await context.SaveChangesAsync();
}
//Get product name and cart count
int? cartCount = await context.CartItem.Where(c => c.CartID == cart.CartID).SumAsync(s => s.Quantity);
string productName = context.Product.FirstOrDefault(p => p.ProductID == productID).Name;
return new OkObjectResult(new { CartCount=cartCount, ProductName=productName });
}
}
}