Beispiel #1
0
        public ActionResult ChangeCartItem(RequestParamsToCart param)
        {
            ModelState.Clear();
            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            if (WishList.Cart.GetAllLineItems().FirstOrDefault(x => x.Code == param.Code) == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.NoContent, productName + " is not exist in the wishlist."));
            }

            _cartService.ChangeCartItem(WishList.Cart, 0, param.Code, param.Quantity, param.Size, param.NewSize);
            _orderRepository.Save(WishList.Cart);
            _trackingService.TrackWishlist(HttpContext);
            var          referencePages = _settingsService.GetSiteSettings <ReferencePageSettings>();
            WishListPage wishlistPage   = null;

            if (!referencePages?.WishlistPage.IsNullOrEmpty() ?? false)
            {
                wishlistPage = _contentLoader.Get <WishListPage>(referencePages.WishlistPage);
            }

            if (param.RequestFrom.Equals("axios", StringComparison.OrdinalIgnoreCase))
            {
                var viewModel = _cartViewModelFactory.CreateWishListViewModel(WishList.Cart, wishlistPage);
                return(PartialView("_WishlistListItem", viewModel));
            }

            return(Redirect(_urlResolver.GetUrl(wishlistPage)));
        }
Beispiel #2
0
        public async Task <JsonResult> RemoveWishlistItem(RequestParamsToCart param) // only use Code
        {
            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            if (WishList.Cart.GetAllLineItems().FirstOrDefault(x => x.Code == param.Code) == null)
            {
                return(Json(new ChangeCartJsonResult {
                    StatusCode = 0, Message = productName + " is not exist in the wishlist."
                }));
            }

            var result = _cartService.ChangeCartItem(WishList.Cart, 0, param.Code, 0, null, null);

            _orderRepository.Save(WishList.Cart);
            await _trackingService.TrackWishlist(HttpContext);

            if (result.Count > 0)
            {
                return(Json(new ChangeCartJsonResult {
                    StatusCode = 0, Message = "Remove " + productName + " error.", CountItems = (int)WishList.Cart.GetAllLineItems().Sum(x => x.Quantity)
                }));
            }

            return(Json(new ChangeCartJsonResult {
                StatusCode = 1, Message = productName + " has removed from the wishlist.", CountItems = (int)WishList.Cart.GetAllLineItems().Sum(x => x.Quantity)
            }));
        }
Beispiel #3
0
        public ActionResult AddToCart(RequestParamsToCart param)
        {
            ModelState.Clear();

            if (SharedCart.Cart == null)
            {
                _sharedCart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultSharedCartName, OrganizationId),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            param.Store = "delivery";
            var result = _cartService.AddToCart(SharedCart.Cart, param);

            if (result.EntriesAddedToCart)
            {
                _orderRepository.Save(SharedCart.Cart);
                var productName = "";
                var entryLink   = _referenceConverter.GetContentLink(param.Code);
                productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 1,
                    CountItems = (int)SharedCart.Cart.GetAllLineItems().Sum(x => x.Quantity),
                    Message = productName + " is added to the shared cart  successfully."
                }));
            }

            return(Json(new ChangeCartJsonResult {
                StatusCode = -1, Message = result.GetComposedValidationMessage()
            }));
        }
        public AddToCartResult AddToCart(ICart cart, RequestParamsToCart requestParams)
        {
            var contentLink  = _referenceConverter.GetContentLink(requestParams.Code);
            var entryContent = _contentLoader.Get <EntryContentBase>(contentLink);

            return(AddToCart(cart, entryContent, requestParams.Quantity, requestParams.Store, requestParams.SelectedStore, requestParams.DynamicCodes));
        }
Beispiel #5
0
        public ActionResult RemoveCartItem(RequestParamsToCart param)
        {
            ModelState.Clear();
            var organizationId = param.OrganizationId;

            if (string.IsNullOrEmpty(organizationId))
            {
                organizationId = OrganizationId.ToString();
            }

            var userWishCart = _cartService.LoadSharedCardByCustomerId(new Guid(organizationId));

            if (userWishCart.GetAllLineItems().Count() == 1)
            {
                _orderRepository.Delete(userWishCart.OrderLink);
            }
            else
            {
                _cartService.ChangeQuantity(userWishCart, -1, param.Code, 0);
                _orderRepository.Save(userWishCart);
            }

            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            return(Json(new ChangeCartJsonResult
            {
                StatusCode = 1,
                CountItems = (int)SharedCart.Cart.GetAllLineItems().Sum(x => x.Quantity),
                Message = productName + " is removed from the shared cart successfully."
            }));
        }
Beispiel #6
0
        public async Task <ActionResult> Subscription(RequestParamsToCart param)
        {
            var warningMessage = string.Empty;

            ModelState.Clear();

            if (CartWithValidationIssues.Cart == null)
            {
                _cart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultCartName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var result = _cartService.AddToCart(CartWithValidationIssues.Cart, param);

            if (result.EntriesAddedToCart)
            {
                var item = CartWithValidationIssues.Cart.GetAllLineItems().FirstOrDefault(x => x.Code.Equals(param.Code));
                var subscriptionPrice = PriceCalculationService.GetSubscriptionPrice(param.Code, CartWithValidationIssues.Cart.MarketId, CartWithValidationIssues.Cart.Currency);
                if (subscriptionPrice != null)
                {
                    item.Properties["SubscriptionPrice"] = subscriptionPrice.UnitPrice.Amount;
                    item.PlacedPrice = subscriptionPrice.UnitPrice.Amount;
                }

                _orderRepository.Save(CartWithValidationIssues.Cart);
                await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

                return(MiniCartDetails());
            }

            return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
        }
Beispiel #7
0
        public ActionResult AddToSharedCart(RequestParamsToCart param)
        {
            ModelState.Clear();
            var currentPage = _contentRouteHelper.Content as CartPage;

            if (SharedCardWithValidationIssues.Cart == null)
            {
                _sharedcart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultSharedCartName, _customerService.GetCurrentContact().FoundationOrganization?.OrganizationId.ToString()),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var items = new Dictionary <int, string>();

            foreach (var shipment in CartWithValidationIssues.Cart.Forms.SelectMany(x => x.Shipments))
            {
                foreach (var lineItem in shipment.LineItems)
                {
                    if (!lineItem.Code.Equals(param.Code))
                    {
                        continue;
                    }
                    items.Add(shipment.ShipmentId, param.Code);
                }
            }
            foreach (var key in items.Keys)
            {
                _cartService.ChangeCartItem(CartWithValidationIssues.Cart, key, items[key], 0, "", "");
            }
            _orderRepository.Save(CartWithValidationIssues.Cart);

            if (SharedCardWithValidationIssues.Cart.GetAllLineItems().Any(item => item.Code.Equals(param.Code, StringComparison.OrdinalIgnoreCase)))
            {
                return(View("LargeCart", _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, currentPage)));
            }

            var result = _cartService.AddToCart(SharedCardWithValidationIssues.Cart,
                                                new RequestParamsToCart {
                Code = param.Code, Quantity = 1, Store = "delivery", SelectedStore = ""
            });

            if (!result.EntriesAddedToCart)
            {
                return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
            }

            _orderRepository.Save(SharedCardWithValidationIssues.Cart);

            var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, currentPage);

            return(View("LargeCart", viewModel));
        }
        public async Task <ActionResult> RemoveCartItem(RequestParamsToCart param) // only use ShipmentId, Code (variant Code)
        {
            ModelState.Clear();
            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            var result = _cartService.ChangeCartItem(CartWithValidationIssues.Cart, param.ShipmentId, param.Code, 0, null, null);

            _orderRepository.Save(CartWithValidationIssues.Cart);
            await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

            if (result.Count > 0)
            {
                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 0,
                    Message = "Remove " + productName + " error.",
                    CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                    SubTotal = CartWithValidationIssues.Cart.GetSubTotal()
                }));
            }

            if (param.RequestFrom == "large-cart")
            {
                var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, null);
                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 1,
                    Message = productName + " has removed from the cart.",
                    CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                    SubTotal = viewModel.Subtotal,
                    Total = viewModel.Total,
                    ShippingTotal = viewModel.ShippingTotal,
                    TaxTotal = viewModel.TaxTotal,
                    TotalDiscount = viewModel.TotalDiscount
                }));
            }

            return(Json(new ChangeCartJsonResult
            {
                StatusCode = 1,
                Message = productName + " has removed from the cart.",
                CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                SubTotal = CartWithValidationIssues.Cart.GetSubTotal()
            }));
        }
Beispiel #9
0
        public ActionResult ChangeCartItem(RequestParamsToCart param)
        {
            ModelState.Clear();

            _cartService.ChangeCartItem(SharedCart.Cart, 0, param.Code, param.Quantity, param.Size, param.NewSize);
            _orderRepository.Save(SharedCart.Cart);

            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            return(Json(new ChangeCartJsonResult
            {
                StatusCode = 1,
                CountItems = (int)SharedCart.Cart.GetAllLineItems().Sum(x => x.Quantity),
                Message = productName + " is added to the shared cart successfully."
            }));
        }
        public ActionResult SeparateShipment(CheckoutPage currentPage, RequestParamsToCart param)
        {
            var result = _cartService.SeparateShipment(CartWithValidationIssues.Cart, param.Code, (int)param.Quantity, param.ShipmentId, param.ToShipmentId, param.DeliveryMethodId, param.SelectedStore);

            if (result.EntriesAddedToCart)
            {
                var model = CreateCheckoutViewModel(currentPage);
                foreach (var payment in model.Payments)
                {
                    var paymentViewmodel = new CheckoutViewModel();
                    paymentViewmodel.Payment = payment;
                    _checkoutService.RemovePaymentFromCart(CartWithValidationIssues.Cart, paymentViewmodel);
                }
                _orderRepository.Save(CartWithValidationIssues.Cart);

                return(Json(new { Status = true, RedirectUrl = Url.Action("Index") }));
            }

            return(Json(new { Status = false, Message = string.Join(", ", result.ValidationMessages) }));
        }
Beispiel #11
0
        public async Task <JsonResult> AddToCart(RequestParamsToCart param) // only use Code
        {
            if (WishList.Cart == null)
            {
                _wishlist = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultWishListName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            // return 0 if the variant already exist in wishlist
            // return 1 if added susscessfully
            var result       = new AddToCartResult();
            var allLineItems = WishList.Cart.GetAllLineItems();
            var contentLink  = _referenceConverter.GetContentLink(param.Code);
            var message      = "";
            var productName  = "";
            var entryLink    = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            if (_contentLoader.Get <EntryContentBase>(contentLink) is GenericBundle bundle) // Add bundle
            {
                var variantCodes = _contentLoader
                                   .GetItems(bundle.GetEntries(_relationRepository), _languageResolver.GetPreferredCulture())
                                   .OfType <VariationContent>()
                                   .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v))
                                   .Select(x => x.Code);
                var allLineItemCodes = allLineItems.Select(x => x.Code);
                var allNewCodes      = variantCodes.Where(x => !allLineItemCodes.Contains(x));
                if (!allNewCodes.Any())
                {
                    return(Json(new ChangeCartJsonResult {
                        StatusCode = 0, Message = productName + " already exist in the wishlist."
                    }));
                }
                else
                {
                    foreach (var v in allNewCodes)
                    {
                        result = _cartService.AddToCart(WishList.Cart, new RequestParamsToCart {
                            Code = v, Quantity = 1, Store = "delivery", SelectedStore = ""
                        });
                        if (result.ValidationMessages.Count > 0)
                        {
                            message += string.Join("\n", result.ValidationMessages);
                        }
                    }
                }
            }
            else // Add variant
            {
                if (allLineItems.Any(item => item.Code.Equals(param.Code, StringComparison.OrdinalIgnoreCase)))
                {
                    return(Json(new ChangeCartJsonResult {
                        StatusCode = 0, Message = productName + " already exist in the wishlist."
                    }));
                }

                result = _cartService.AddToCart(WishList.Cart,
                                                new RequestParamsToCart {
                    Code = param.Code, Quantity = 1, Store = "delivery", SelectedStore = ""
                });
            }

            if (result.EntriesAddedToCart)
            {
                _orderRepository.Save(WishList.Cart);
                await _trackingService.TrackWishlist(HttpContext);

                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 1,
                    CountItems = (int)WishList.Cart.GetAllLineItems().Sum(x => x.Quantity),
                    Message = productName + " is added to the wishlist successfully.\n" + message
                }));
            }
            return(Json(new ChangeCartJsonResult {
                StatusCode = -1, Message = result.GetComposedValidationMessage()
            }));
        }
        public async Task <ActionResult> ChangeCartItem(RequestParamsToCart param) // change quantity
        {
            ModelState.Clear();

            var validationIssues = _cartService.ChangeCartItem(CartWithValidationIssues.Cart, param.ShipmentId, param.Code, param.Quantity, param.Size, param.NewSize);

            _orderRepository.Save(CartWithValidationIssues.Cart);
            var model = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, null);

            if (validationIssues.Any())
            {
                foreach (var item in validationIssues.Keys)
                {
                    model.Message += GetValidationMessages(item, validationIssues);
                }
            }
            var trackingResponse = await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

            //model.Recommendations = trackingResponse.GetCartRecommendations(_referenceConverter);
            var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, null);

            if (param.RequestFrom == "changeSizeItem")
            {
                var preferredCulture = _languageResolver.GetPreferredCulture();
                var newCode          = _productService.GetSiblingVariantCodeBySize(param.Code, param.NewSize);
                var shipment         = CartWithValidationIssues.Cart.GetFirstForm().Shipments.FirstOrDefault(x => x.ShipmentId == param.ShipmentId);
                var lineItem         = shipment.LineItems.FirstOrDefault(x => x.Code == newCode);
                var entries          = _contentLoader.GetItems(shipment.LineItems.Select(x => _referenceConverter.GetContentLink(x.Code)),
                                                               preferredCulture).OfType <EntryContentBase>();
                var entry            = entries.FirstOrDefault(x => x.Code == lineItem.Code);
                var newItemViewModel = _cartItemViewModelFactory.CreateCartItemViewModel(CartWithValidationIssues.Cart, lineItem, entry);
                ViewData["ShipmentId"] = param.ShipmentId;
                return(PartialView("_ItemTemplate", newItemViewModel));
            }

            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            var result = new ChangeCartJsonResult
            {
                CountItems    = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                SubTotal      = viewModel.Subtotal,
                Total         = viewModel.Total,
                ShippingTotal = viewModel.ShippingTotal,
                TaxTotal      = viewModel.TaxTotal,
                TotalDiscount = viewModel.TotalDiscount
            };

            if (validationIssues.Count > 0)
            {
                result.StatusCode = 0;
                result.Message    = string.Join("\n", validationIssues.Select(x => string.Join("\n", x.Value.Select(v => v.ToString()))));
            }
            else
            {
                result.StatusCode = 1;
                result.Message    = productName + " has changed from the cart.";
            }

            return(Json(result));
        }
        public ActionResult MoveToWishlist(RequestParamsToCart param)
        {
            ModelState.Clear();
            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            var currentPage = _contentRouteHelper.Content as CartPage;

            if (WishListWithValidationIssues.Cart == null)
            {
                _wishlist = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultWishListName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var items = new Dictionary <int, string>();

            foreach (var shipment in CartWithValidationIssues.Cart.Forms.SelectMany(x => x.Shipments))
            {
                foreach (var lineItem in shipment.LineItems)
                {
                    if (!lineItem.Code.Equals(param.Code))
                    {
                        continue;
                    }
                    items.Add(shipment.ShipmentId, param.Code);
                }
            }

            if (WishListWithValidationIssues.Cart.GetAllLineItems().Any(item => item.Code.Equals(param.Code, StringComparison.OrdinalIgnoreCase)))
            {
                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 0,
                    Message = productName + " already existed in the wishlist.",
                }));
            }

            foreach (var key in items.Keys)
            {
                _cartService.ChangeCartItem(CartWithValidationIssues.Cart, key, items[key], 0, "", "");
            }
            _orderRepository.Save(CartWithValidationIssues.Cart);

            var result = _cartService.AddToCart(WishListWithValidationIssues.Cart, param.Code, 1, "delivery", "");

            if (!result.EntriesAddedToCart)
            {
                return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
            }

            _orderRepository.Save(WishListWithValidationIssues.Cart);

            var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, currentPage);

            return(Json(new ChangeCartJsonResult
            {
                StatusCode = 1,
                Message = productName + " has moved to the wishlist.",
                CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                SubTotal = viewModel.Subtotal,
                Total = viewModel.Total,
                ShippingTotal = viewModel.ShippingTotal,
                TaxTotal = viewModel.TaxTotal,
                TotalDiscount = viewModel.TotalDiscount
            }));
        }
        public async Task <ActionResult> BuyNow(RequestParamsToCart param)
        {
            var warningMessage = string.Empty;

            ModelState.Clear();

            if (CartWithValidationIssues.Cart == null)
            {
                _cart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultCartName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var result = _cartService.AddToCart(CartWithValidationIssues.Cart, param.Code, param.Quantity, param.Store, param.SelectedStore);

            if (!result.EntriesAddedToCart)
            {
                return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
            }
            var contact = PrincipalInfo.CurrentPrincipal.GetCustomerContact();

            if (contact == null)
            {
                return(RedirectToCart("The contact is invalid"));
            }

            var creditCard = contact.ContactCreditCards.FirstOrDefault();

            if (creditCard == null)
            {
                return(RedirectToCart("There is not any credit card"));
            }

            var shipment = CartWithValidationIssues.Cart.GetFirstShipment();

            if (shipment == null)
            {
                return(RedirectToCart("The shopping cart is not exist"));
            }

            var shippingAddress = (contact.PreferredShippingAddress ?? contact.ContactAddresses.FirstOrDefault())?.ConvertToOrderAddress(CartWithValidationIssues.Cart);

            if (shippingAddress == null)
            {
                return(RedirectToCart("The shipping address is not exist"));
            }

            shipment.ShippingAddress = shippingAddress;

            var shippingMethodViewModels = _shipmentViewModelFactory.CreateShipmentsViewModel(CartWithValidationIssues.Cart).SelectMany(x => x.ShippingMethods);
            var shippingMethodViewModel  = shippingMethodViewModels.Where(x => x.Price != 0)
                                           .OrderBy(x => x.Price)
                                           .FirstOrDefault();

            //If product is virtual set shipping method is Free
            if (shipment.LineItems.FirstOrDefault().IsVirtualVariant())
            {
                shippingMethodViewModel = shippingMethodViewModels.Where(x => x.Price == 0).FirstOrDefault();
            }

            if (shippingMethodViewModel == null)
            {
                return(RedirectToCart("The shipping method is invalid"));
            }

            shipment.ShippingMethodId = shippingMethodViewModel.Id;

            var paymentAddress = (contact.PreferredBillingAddress ?? contact.ContactAddresses.FirstOrDefault())?.ConvertToOrderAddress(CartWithValidationIssues.Cart);

            if (paymentAddress == null)
            {
                return(RedirectToCart("The billing address is not exist"));
            }

            var totals = _orderGroupCalculator.GetOrderGroupTotals(CartWithValidationIssues.Cart);

            var payment = CartWithValidationIssues.Cart.CreateCardPayment();

            payment.BillingAddress         = paymentAddress;
            payment.CardType               = "Credit card";
            payment.PaymentMethodId        = new Guid("B1DA37A6-CF19-40D5-915B-B863D74D8799");
            payment.PaymentMethodName      = "GenericCreditCard";
            payment.Amount                 = CartWithValidationIssues.Cart.GetTotal().Amount;
            payment.CreditCardNumber       = creditCard.CreditCardNumber;
            payment.CreditCardSecurityCode = creditCard.SecurityCode;
            payment.ExpirationMonth        = creditCard.ExpirationMonth ?? 1;
            payment.ExpirationYear         = creditCard.ExpirationYear ?? DateTime.Now.Year;
            payment.Status                 = PaymentStatus.Pending.ToString();
            payment.CustomerName           = contact.FullName;
            payment.TransactionType        = TransactionType.Authorization.ToString();
            CartWithValidationIssues.Cart.GetFirstForm().Payments.Add(payment);

            var issues = _cartService.ValidateCart(CartWithValidationIssues.Cart);

            if (issues.Keys.Any(x => issues.HasItemBeenRemoved(x)))
            {
                return(RedirectToCart("The product is invalid"));
            }
            var order = _checkoutService.PlaceOrder(CartWithValidationIssues.Cart, new ModelStateDictionary(), new CheckoutViewModel());

            //await _checkoutService.CreateOrUpdateBoughtProductsProfileStore(CartWithValidationIssues.Cart);
            //await _checkoutService.CreateBoughtProductsSegments(CartWithValidationIssues.Cart);
            await _recommendationService.TrackOrder(HttpContext, order);

            var homePage = _contentLoader.Get <PageData>(ContentReference.StartPage) as CommerceHomePage;

            if (homePage?.OrderConfirmationPage != null)
            {
                var orderConfirmationPage = _contentLoader.Get <OrderConfirmationPage>(homePage.OrderConfirmationPage);
                var queryCollection       = new NameValueCollection
                {
                    { "contactId", contact.PrimaryKeyId?.ToString() },
                    { "orderNumber", order.OrderLink.OrderGroupId.ToString() }
                };
                var urlRedirect = new UrlBuilder(orderConfirmationPage.StaticLinkURL)
                {
                    QueryCollection = queryCollection
                };
                return(Json(new { Redirect = urlRedirect.ToString() }));
            }

            return(RedirectToCart("Something went wrong"));
        }
        public async Task <ActionResult> AddToCart(RequestParamsToCart param)
        {
            var warningMessage = string.Empty;

            ModelState.Clear();

            if (CartWithValidationIssues.Cart == null)
            {
                _cart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultCartName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var result = _cartService.AddToCart(CartWithValidationIssues.Cart, param.Code, param.Quantity, param.Store, param.SelectedStore);

            if (result.EntriesAddedToCart)
            {
                _orderRepository.Save(CartWithValidationIssues.Cart);
                await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

                if (string.Equals(param.RequestFrom, "axios", StringComparison.OrdinalIgnoreCase))
                {
                    var product   = "";
                    var entryLink = _referenceConverter.GetContentLink(param.Code);
                    var entry     = _contentLoader.Get <EntryContentBase>(entryLink);
                    if (entry is BundleContent || entry is PackageContent)
                    {
                        product = entry.DisplayName;
                    }
                    else
                    {
                        var parentProduct = _contentLoader.Get <EntryContentBase>(entry.GetParentProducts().FirstOrDefault());
                        product = parentProduct?.DisplayName;
                    }

                    if (result.ValidationMessages.Count > 0)
                    {
                        return(Json(new ChangeCartJsonResult
                        {
                            StatusCode = 1,
                            CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                            Message = product + " is added to the cart successfully.\n" + result.GetComposedValidationMessage(),
                            SubTotal = CartWithValidationIssues.Cart.GetSubTotal()
                        }));
                    }

                    return(Json(new ChangeCartJsonResult
                    {
                        StatusCode = 1,
                        CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                        Message = product + " is added to the cart successfully.",
                        SubTotal = CartWithValidationIssues.Cart.GetSubTotal()
                    }));
                }

                return(MiniCartDetails());
            }

            return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
        }