<commit_before>﻿namespace MvcProject.Web.Areas.Public.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Data.Models.Catalog;
    using ViewModels.Products;
    using Services.Data;
    using ViewModels.Orders;
    using Common.GlobalConstants;
    using Infrastructure.Authorization;
    using Data.Models.Orders;
    using Infrastructure.Extensions;

    [AuthorizeRoles(IdentityRoles.Customer, IdentityRoles.Seller)]
    public class OrdersController : BasePublicController
    {
        private readonly IUsersService usersService;
        private readonly IProductsService productsService;
        private readonly IOrdersService ordersService;
        private readonly IOrderItemsService orderItemsService;

        public OrdersController(
            IUsersService usersService,
            IProductsService productsService,
            IOrdersService ordersService,
            IOrderItemsService orderItemsService)
        {
            this.usersService = usersService;
            this.productsService = productsService;
            this.ordersService = ordersService;
            this.orderItemsService = orderItemsService;
        }

        [HttpGet]
        public ActionResult ShoppingCart(/*ShoppingCartViewModel shoppingCart*/)
        {
            //var viewModel = new ShoppingCartViewModel()
            //{
            //    UserName = this.HttpContext.User.Identity.Name,

            //};

            var shoppingCart = new ShoppingCartViewModel();
            var userName = this.HttpContext.User.Identity.Name;
            var sessionKey = string.Format("{0}-{1}", userName, "ShoppingCart");

            if (this.HttpContext.Session.IsNewSession)
            {
                var user = this.usersService.GetByUserName(userName);
                //var sessionKey = string.Format("{0}-{1}", userId, "ShoppingCart");
                shoppingCart.UserId = user.Id;
                shoppingCart.UserName = userName;
                this.Session[sessionKey] = shoppingCart;
            }
            else
            {
                shoppingCart = (ShoppingCartViewModel)this.Session[sessionKey];
            }

            //shoppingCart.UserId = this.usersService.GetByUserName(shoppingCart.UserName).Id;

            return this.View(/*viewModel*/shoppingCart);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateShoppingCart(ShoppingCartViewModel shoppingCart)
        {
            if (shoppingCart != null && this.ModelState.IsValid)
            {
                shoppingCart.CartItems = shoppingCart.CartItems.Where(ci => ci.ToDelete == false).ToList();

                var sessionKey = string.Format("{0}-{1}", shoppingCart.UserName, "ShoppingCart");
                this.Session[sessionKey] = shoppingCart;
                return this.PartialView("ShoppingCartPartial", shoppingCart);
            }

            throw new HttpException(400, "Invalid shopping cart state.");
        }
        
        public ActionResult AddToCart(int productId)
        {
            if (this.ModelState.IsValid)
            {
                var userName = this.User.Identity.Name;
                var sessionKey = string.Format("{0}-{1}", userName, "ShoppingCart");
                var shoppingCart = (ShoppingCartViewModel)this.Session[sessionKey];

                if (shoppingCart == null)
                {
                    shoppingCart = new ShoppingCartViewModel() { UserName = userName, UserId = this.usersService.GetByUserName(userName).Id };
                }

                var cartItem = shoppingCart.CartItems.FirstOrDefault(ci => ci.Product.Id == productId);
                if (cartItem != null)
                {
                    cartItem.ProductQuantity += 1;
                }
                else
                {
                    cartItem = new ShoppingCartItem();
                    cartItem.Product = PopulateProductForCartItem(this.productsService.GetById(productId));
                    cartItem.ProductQuantity = 1;
                    cartItem.ToDelete = false;
                    shoppingCart.CartItems.Add(cartItem);
                }

                this.Session[sessionKey] = shoppingCart;
            }

            return this.RedirectToAction("ShoppingCart");
        }

        public ActionResult Checkout()
        {
            var userName = this.User.Identity.Name;
            var sessionKey = string.Format("{0}-{1}", userName, "ShoppingCart");
            var shoppingCart = (ShoppingCartViewModel)this.Session[sessionKey];

            var order = new Order();
            PopulateOrder(order, shoppingCart);
            this.ordersService.Insert(order);
            var orderId = order.Id;
            PopulateOrderItems(order, shoppingCart.CartItems);
            this.ordersService.Update(order);

            //order.OrderItems = shoppingCart.CartItems.AsQueryable().To<OrderItem>().ToList();

            return this.View("CheckoutSuccess");
        }

        private void PopulateOrderItems(/*ICollection<OrderItem> orderItems*/Order order, ICollection<ShoppingCartItem> cartItems)
        {
            var orderItems = cartItems.AsQueryable().To<OrderItem>();
            foreach (var item in orderItems)
            {
                item.Product = this.productsService.GetById(item.ProductId);
                item.OrderId = order.Id;
                item.Order = this.ordersService.GetById(item.OrderId);
                item.IsDeleted = false;
                item.ModifiedOn = null;
                this.orderItemsService.Insert(item);
            }
        }

        private void PopulateOrder(Order order, ShoppingCartViewModel shoppingCart)
        {
            order.TotalCost = shoppingCart.TotalCost;
            order.UserId = shoppingCart.UserId;
            order.IsDeleted = false;
            order.ModifiedOn = null;
        }

        #region Helpers
        private ProductForShoppingCart PopulateProductForCartItem(Product product)
        {<commit_msg>clearing shopping cart on checkout fixed<commit_after>﻿namespace MvcProject.Web.Areas.Public.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Data.Models.Catalog;
    using ViewModels.Products;
    using Services.Data;
    using ViewModels.Orders;
    using Common.GlobalConstants;
    using Infrastructure.Authorization;
    using Data.Models.Orders;
    using Infrastructure.Extensions;

    [AuthorizeRoles(IdentityRoles.Customer, IdentityRoles.Seller)]
    public class OrdersController : BasePublicController
    {
        private readonly IUsersService usersService;
        private readonly IProductsService productsService;
        private readonly IOrdersService ordersService;
        private readonly IOrderItemsService orderItemsService;

        public OrdersController(
            IUsersService usersService,
            IProductsService productsService,
            IOrdersService ordersService,
            IOrderItemsService orderItemsService)
        {
            this.usersService = usersService;
            this.productsService = productsService;
            this.ordersService = ordersService;
            this.orderItemsService = orderItemsService;
        }

        [HttpGet]
        public ActionResult ShoppingCart()
        {
            var shoppingCart = new ShoppingCartViewModel();
            var userName = this.HttpContext.User.Identity.Name;
            var sessionKey = string.Format("{0}-{1}", userName, "ShoppingCart");

            if (/*this.HttpContext.Session.IsNewSession*/this.Session[sessionKey] == null)
            {
                var user = this.usersService.GetByUserName(userName);
                shoppingCart.UserId = user.Id;
                shoppingCart.UserName = userName;
                this.Session[sessionKey] = shoppingCart;
            }
            else
            {
                shoppingCart = (ShoppingCartViewModel)this.Session[sessionKey];
            }

            return this.View(shoppingCart);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UpdateShoppingCart(ShoppingCartViewModel shoppingCart)
        {
            if (shoppingCart != null && this.ModelState.IsValid)
            {
                shoppingCart.CartItems = shoppingCart.CartItems.Where(ci => ci.ToDelete == false).ToList();

                var sessionKey = string.Format("{0}-{1}", shoppingCart.UserName, "ShoppingCart");
                this.Session[sessionKey] = shoppingCart;
                return this.PartialView("ShoppingCartPartial", shoppingCart);
            }

            throw new HttpException(400, "Invalid shopping cart state.");
        }
        
        public ActionResult AddToCart(int productId)
        {
            if (this.ModelState.IsValid)
            {
                var userName = this.User.Identity.Name;
                var sessionKey = string.Format("{0}-{1}", userName, "ShoppingCart");
                var shoppingCart = (ShoppingCartViewModel)this.Session[sessionKey];

                if (shoppingCart == null)
                {
                    shoppingCart = new ShoppingCartViewModel() { UserName = userName, UserId = this.usersService.GetByUserName(userName).Id };
                }

                var cartItem = shoppingCart.CartItems.FirstOrDefault(ci => ci.Product.Id == productId);
                if (cartItem != null)
                {
                    cartItem.ProductQuantity += 1;
                }
                else
                {
                    cartItem = new ShoppingCartItem();
                    cartItem.Product = PopulateProductForCartItem(this.productsService.GetById(productId));
                    cartItem.ProductQuantity = 1;
                    cartItem.ToDelete = false;
                    shoppingCart.CartItems.Add(cartItem);
                }

                this.Session[sessionKey] = shoppingCart;
            }

            return this.RedirectToAction("ShoppingCart");
        }

        public ActionResult Checkout()
        {
            if (this.ModelState.IsValid)
            {
                var userName = this.User.Identity.Name;
                var sessionKey = string.Format("{0}-{1}", userName, "ShoppingCart");
                var shoppingCart = (ShoppingCartViewModel)this.Session[sessionKey];

                if (shoppingCart == null)
                {
                    return this.RedirectToAction("ShoppingCart");
                }

                if (!shoppingCart.CartItems.Any())
                {
                    return this.RedirectToAction("ShoppingCart");
                }

                var order = new Order();
                PopulateOrder(order, shoppingCart);
                this.ordersService.Insert(order);
                var orderId = order.Id;
                PopulateOrderItems(order, shoppingCart.CartItems);
                this.ordersService.Update(order);
                this.Session[sessionKey] = null;

                return this.View("CheckoutSuccess");
            }

            throw new HttpException(400, "Invalid checkout request.");
        }

        private void PopulateOrderItems(Order order, ICollection<ShoppingCartItem> cartItems)
        {
            var orderItems = cartItems.AsQueryable().To<OrderItem>();
            foreach (var item in orderItems)
            {
                item.Product = this.productsService.GetById(item.ProductId);
                item.OrderId = order.Id;
                item.Order = this.ordersService.GetById(item.OrderId);
                item.IsDeleted = false;
                item.ModifiedOn = null;
                this.orderItemsService.Insert(item);
            }
        }

        private void PopulateOrder(Order order, ShoppingCartViewModel shoppingCart)
        {
            order.TotalCost = shoppingCart.TotalCost;
            order.UserId = shoppingCart.UserId;
            order.IsDeleted = false;
            order.ModifiedOn = null;
        }

        #region Helpers
        private ProductForShoppingCart PopulateProductForCartItem(Product product)
        {
{'fraction_non_alphanumeric': 0.08652516874034318, 'fraction_numerical': 0.0025209400666829306, 'mean_word_length': 1.856678281068525, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5326599', 'n_tokens_mistral': 3101, 'n_tokens_neox': 2976, 'n_words': 556}