Esempio n. 1
0
        public IActionResult UpdateCart([FromBody] CartUpdate cu)
        {
            int   cartCount;
            float subTotal;
            float total = 0;

            try
            {
                int productId; int qty;
                productId = cu.ProductId; qty = cu.Qty;
                Debug.WriteLine($"Prod ID:{productId}, Qty: {qty}");
                if (qty <= 0)
                {
                    return(Json(new
                    {
                        success = false
                    }));
                }

                // if user is not logged in, update cart data in Session State as a Jsonified dict
                if (!User.Identity.IsAuthenticated)
                {
                    var cartList = HttpContext.Session.GetJson <CartListViewModel>("cart");

                    // check if "cart" exists in Session data
                    if (cartList != null)
                    {
                        // update cart item qty if cart item exists, otherwise add new cart item
                        cartList.UpdateCart(new Cart {
                            ProductId = productId, Qty = qty
                        });
                    }
                    // create new cratList Dict if there isn't one in session
                    else
                    {
                        cartList = new CartListViewModel();
                        cartList.UpdateCart(new Cart {
                            ProductId = productId, Qty = qty
                        });
                    }

                    // update "cart" Session data
                    HttpContext.Session.SetJson("cart", cartList);

                    // get latest "cartCount" and set to Session data
                    cartCount = cartList.CartCount;
                    HttpContext.Session.SetInt32("cartCount", cartCount);

                    // for debugging, to delete
                    foreach (Cart c in cartList.List)
                    {
                        Debug.WriteLine($"Prod: {c.ProductId} - {c.Qty}");
                    }
                    Debug.WriteLine("Cart count: " + cartCount);

                    var prod = db.Products.FirstOrDefault(p => p.Id == productId);

                    subTotal = (prod.UnitPrice * qty) * (1 - prod.Discount);

                    foreach (Cart c in cartList.List)
                    {
                        var currProd  = db.Products.FirstOrDefault(p => p.Id == c.ProductId);
                        var unitPrice = currProd.UnitPrice;
                        var discount  = currProd.Discount;
                        total += unitPrice * c.Qty * (1 - discount);
                    }
                }
                // else user is logged in, update cart data in SQL db Cart table
                else
                {
                    string userId = User.FindFirst("userId").Value;
                    var    cart   = db.Carts.FirstOrDefault(c => c.ProductId == productId && c.UserId == userId);

                    // update cart item's qty if exists, otherwise add new Cart object
                    if (cart != null)
                    {
                        cart.Qty = qty;
                    }
                    else
                    {
                        cart = new Cart()
                        {
                            UserId = userId, ProductId = productId, Qty = qty
                        };
                        db.Carts.Add(cart);
                    }
                    db.SaveChanges();

                    // get latest "cartCount" and set to Session data
                    cartCount = db.Users.FirstOrDefault(u => u.Id == userId).Carts.Sum(c => c.Qty);
                    HttpContext.Session.SetInt32("cartCount", cartCount);

                    // for debugging, to delete
                    //foreach (Cart c in db.Users.FirstOrDefault(u => u.Id == userId).Carts)
                    //{
                    //    Debug.WriteLine($"Prod: {c.ProductId} - {c.Qty}");
                    //}
                    //Debug.WriteLine("Cart count: " + cartCount);

                    subTotal = cart.Product.UnitPrice * qty * (1 - cart.Product.Discount);

                    foreach (Cart c in db.Users.FirstOrDefault(u => u.Id == userId).Carts)
                    {
                        total += c.Product.UnitPrice * c.Qty * (1 - c.Product.Discount);
                    }
                }

                HttpContext.Session.SetInt32("cartCount", cartCount);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                _logger.LogError(ex, $"Error updating cart for {cu}");
                return(Json(new
                {
                    success = false
                }));
            }

            return(Json(new
            {
                success = true,
                cartCount = cartCount,
                subTotal = subTotal.ToString("S$ 0.00"),
                total = total.ToString("S$ 0.00")
            }));
        }
Esempio n. 2
0
        public async Task <IActionResult> Checkout()
        {
            List <Order>       newOrderList        = new List <Order>();
            List <OrderDetail> newOrderDetailsList = new List <OrderDetail>();
            int i = 0;

            //generate orderId
            //Add order and orderdetal data into database after purchase.
            var newOrderId = ShortGuid.Shorten(Guid.NewGuid());

            List <Cart> userCart = new List <Cart>();
            string      userId   = User.FindFirst("userId").Value;

            userCart = db.Users.FirstOrDefault(u => u.Id == userId).Carts.ToList();

            //While we are adding order and orderdetail data into the database, we will populate the view data as well for the reciept

            List <CheckOutViewModel> recieptList = new List <CheckOutViewModel>();

            Order newOrder = new Order()
            {
                UserId    = userId,
                Id        = newOrderId,
                Timestamp = DateTime.Now
            };

            db.Orders.Add(newOrder);
            db.SaveChanges();

            //Debug.WriteLine(newOrder.Id);
            //Debug.WriteLine(newOrder);

            foreach (var cartItem in userCart)
            {
                while (i < cartItem.Qty)
                {
                    //Populate OrderDetail & add to database
                    OrderDetail newOrderDetail = new OrderDetail()
                    {
                        ActivationCode = Guid.NewGuid().ToString(),
                        OrderId        = newOrderId,
                        ProductId      = cartItem.ProductId
                    };

                    db.OrderDetails.Add(newOrderDetail);
                    db.SaveChanges();

                    //Debug.WriteLine(newOrderDetail);
                    //Debug.WriteLine(newOrderDetail.ActivationCode);

                    //populate the checkoutviewmodel
                    CheckOutViewModel reciept = new CheckOutViewModel()
                    {
                        ImgURL         = cartItem.Product.ImgURL,
                        ProductName    = cartItem.Product.ProductName,
                        ProductDesc    = cartItem.Product.ProductDesc,
                        ActivationCode = newOrderDetail.ActivationCode,
                        Qty            = cartItem.Qty,
                        UnitPrice      = cartItem.Product.UnitPrice,
                        Discount       = cartItem.Product.Discount
                    };

                    recieptList.Add(reciept);
                    i++;
                }
                i = 0;
            }

            var receiptView = recieptList.GroupBy(o => o.ProductName);

            //mapping the orderviewmodel into to the view using viewdata
            ViewData["RecieptView"] = receiptView;

            // create Receipt model and pass it to EmailReceipt.SendReceipt
            var receipt = new Receipt
            {
                OrderId = newOrderId
            };

            foreach (var group in receiptView)
            {
                List <string> activationCodes = group.Select(g => g.ActivationCode).ToList();

                receipt.ReceiptItems.Add(new ReceiptItem
                {
                    ProductName     = group.First().ProductName,
                    ActivationCodes = activationCodes,
                    UnitPrice       = group.First().UnitPrice,
                    Qty             = group.First().Qty,
                    Discount        = group.First().Discount
                });
            }

            var emailStatus = await EmailReceipt.SendReceipt(db.Users.FirstOrDefault(u => u.Id == userId).Email, receipt);

            if (!emailStatus.IsSuccessful)
            {
                //Debug.WriteLine("Email receipt unsuccessful");
            }

            //Clearing the Cart table in database after purchase
            foreach (var cartDelete in userCart)
            {
                db.Carts.Remove(cartDelete);
            }
            db.SaveChanges();

            //Remove cart session data
            HttpContext.Session.Remove("cart");
            HttpContext.Session.Remove("cartCount");

            return(View());
        }
Esempio n. 3
0
        public async Task <IActionResult> Login([FromForm] LoginDetails login, string returnUrl)
        {
            // find user by email
            var user = db.Users.FirstOrDefault(u => u.Email == login.Email);

            if (user != null)
            {
                // check password hash if matched
                string pwdHash = PasswordHasher.Hash(login.Password, user.Salt);
                if (pwdHash == user.PasswordHash)
                {
                    try
                    {
                        // declare claims
                        var claims = new List <Claim>
                        {
                            new Claim("email", user.Email),
                            new Claim("role", "Member"),
                            new Claim("fullName", user.FirstName + " " + user.LastName),
                            new Claim("userId", user.Id.ToString())
                        };

                        // configure authentication
                        var authProperties = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            AllowRefresh = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(20) // authentication ticket expiry
                        };

                        // sign in with new Identity, authentication name: "Cookies", User.Identity.Name is "fullName"
                        await HttpContext.SignInAsync(new ClaimsPrincipal(
                                                          new ClaimsIdentity(claims, "Cookies", "fullName", "role")),
                                                      authProperties);

                        // transfer cart data in session into User's cart
                        var cartList = HttpContext.Session.GetJson <CartListViewModel>("cart");

                        // if cart in Session not empty, override db Cart data
                        if (cartList != null)
                        {
                            // remove existing db Cart data
                            foreach (Cart c in user.Carts)
                            {
                                db.Carts.Remove(c);
                            }

                            // populate new Cart data from Session into db
                            foreach (Cart c in cartList.List)
                            {
                                c.UserId = user.Id;
                                db.Carts.Add(c);
                            }

                            db.SaveChanges();
                        }

                        // get cartCount and save in Session
                        int cartCount = user.Carts.Sum(c => c.Qty);
                        HttpContext.Session.SetInt32("cartCount", cartCount);

                        return(Redirect(returnUrl == null ? "/" : returnUrl));
                    }
                    catch (Exception ex)
                    {
                        //Debug.WriteLine("Error occured during login: "******"Error occured during login");

                        TempData["error"] = "Something went wrong";
                        return(RedirectToAction("Login", new { returnUrl = returnUrl }));
                    }
                }
                else
                {
                    TempData["error"] = "Invalid password";
                    return(RedirectToAction("Login", new { returnUrl = returnUrl }));
                }
            }
            else
            {
                TempData["error"] = "Invalid account";
                return(RedirectToAction("Login", new { returnUrl = returnUrl }));
            }
        }