protected IEnumerable <CategoryViewModel> GroupRelationshipsByDescription([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, RelationshipField field, IEnumerable <string> relationshipNames, IEnumerable <CatalogRelationshipInformation> productRelationshipInfoList, Rendering rendering)
        {
            Dictionary <string, CategoryViewModel> relationshipGroups = new Dictionary <string, CategoryViewModel>(StringComparer.OrdinalIgnoreCase);

            if (field != null && productRelationshipInfoList != null)
            {
                foreach (var relationshipInfo in productRelationshipInfoList)
                {
                    if (!relationshipNames.Any() || relationshipNames.Contains(relationshipInfo.RelationshipName, StringComparer.OrdinalIgnoreCase))
                    {
                        Item lookupItem                 = null;
                        bool usingRelationshipName      = string.IsNullOrWhiteSpace(relationshipInfo.RelationshipDescription);
                        var  relationshipDescription    = usingRelationshipName ? StorefrontManager.GetRelationshipName(relationshipInfo.RelationshipName, out lookupItem) : relationshipInfo.RelationshipDescription;
                        CategoryViewModel categoryModel = null;
                        if (!relationshipGroups.TryGetValue(relationshipDescription, out categoryModel))
                        {
                            categoryModel = new CategoryViewModel
                            {
                                ChildProducts           = new List <ProductViewModel>(),
                                RelationshipName        = relationshipInfo.RelationshipName,
                                RelationshipDescription = relationshipDescription,
                                LookupRelationshipItem  = (usingRelationshipName) ? lookupItem : null
                            };
                            relationshipGroups[relationshipDescription] = categoryModel;
                        }

                        var targetItemId = ID.Parse(relationshipInfo.ToItemExternalId);
                        var targetItem   = field.InnerField.Database.GetItem(targetItemId);
                        var productModel = new ProductViewModel(targetItem);
                        productModel.Initialize(rendering);
                        productModel.CustomerAverageRating = this.GetProductRating(targetItem);

                        categoryModel.ChildProducts.Add(productModel);
                    }
                }
            }

            if (relationshipGroups.Count > 0)
            {
                List <ProductViewModel> productViewModelList = new List <ProductViewModel>();

                foreach (string key in relationshipGroups.Keys)
                {
                    CategoryViewModel viewModel = relationshipGroups[key];
                    var childProducts           = viewModel.ChildProducts;
                    if (childProducts != null && childProducts.Count > 0)
                    {
                        productViewModelList.AddRange(childProducts);
                    }
                }

                if (productViewModelList.Count > 0)
                {
                    this.GetProductBulkPrices(visitorContext, productViewModelList);
                    this.InventoryManager.GetProductsStockStatusForList(storefront, productViewModelList);
                }
            }

            return(relationshipGroups.Values);
        }
Exemple #2
0
        /// <summary>
        /// Updates the user password.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>The manager response.</returns>
        public virtual ManagerResponse <UpdatePasswordResult, bool> UpdateUserPassword([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, ChangePasswordInputModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(inputModel, "inputModel");
            Assert.ArgumentNotNullOrEmpty(inputModel.OldPassword, "inputModel.OldPassword");
            Assert.ArgumentNotNullOrEmpty(inputModel.NewPassword, "inputModel.NewPassword");

            var userName = visitorContext.UserName;

            var request = new UpdatePasswordRequest(userName, inputModel.OldPassword, inputModel.NewPassword);
            var result  = this.CustomerServiceProvider.UpdatePassword(request);

            if (!result.Success && !result.SystemMessages.Any())
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.PasswordCouldNotBeReset);
                result.SystemMessages.Add(new SystemMessage {
                    Message = message
                });

                Helpers.LogSystemMessages(result.SystemMessages, result);
            }

            return(new ManagerResponse <UpdatePasswordResult, bool>(result, result.Success));
        }
        /// <summary>
        /// Gets the product prices.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="catalogName">Name of the catalog.</param>
        /// <param name="productId">The product identifier.</param>
        /// <param name="includeVariants">if set to <c>true</c> [include variants].</param>
        /// <param name="priceTypeIds">The price type ids.</param>
        /// <returns>The manager response with the list of prices in the Result.</returns>
        public virtual ManagerResponse <GetProductPricesResult, IDictionary <string, Price> > GetProductPrices([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string catalogName, string productId, bool includeVariants, params string[] priceTypeIds)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

            if (priceTypeIds == null)
            {
                priceTypeIds = DefaultPriceTypeIds;
            }

            var request = new Sitecore.Commerce.Engine.Connect.Services.Prices.GetProductPricesRequest(catalogName, productId, priceTypeIds)
            {
                DateTime = this.GetCurrentDate()
            };

            if (Sitecore.Context.User.IsAuthenticated)
            {
                request.UserId = visitorContext.GetCustomerId();
            }

            request.IncludeVariantPrices = includeVariants;
            request.CurrencyCode         = StorefrontManager.GetCustomerCurrency();
            var result = this.PricingServiceProvider.GetProductPrices(request);

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <GetProductPricesResult, IDictionary <string, Price> >(result, result.Prices ?? new Dictionary <string, Price>()));
        }
        /// <summary>
        /// Adds the promo code to cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="promoCode">The promo code.</param>
        /// <returns>
        /// The manager response where the modified CommerceCart is returned in the Result.
        /// </returns>
        public virtual ManagerResponse <AddPromoCodeResult, CommerceCart> AddPromoCodeToCart([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string promoCode)
        {
            Assert.ArgumentNotNullOrEmpty(promoCode, "promoCode");

            AddPromoCodeResult result = new AddPromoCodeResult {
                Success = false
            };
            var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, visitorContext.UserId);

            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError);
                cartResult.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
                return(new ManagerResponse <AddPromoCodeResult, CommerceCart>(result, cartResult.Cart as CommerceCart));
            }

            var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();

            cartCache.InvalidateCartCache(visitorContext.GetCustomerId());

            var cart    = cartResult.Cart as CommerceCart;
            var request = new AddPromoCodeRequest(cart, promoCode);

            request.RefreshCart(true);
            result = ((CommerceCartServiceProvider)this.CartServiceProvider).AddPromoCode(request);
            if (result.Success && result.Cart != null)
            {
                cartCache.AddCartToCache(result.Cart as CommerceCart);
            }

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <AddPromoCodeResult, CommerceCart>(result, result.Cart as CommerceCart));
        }
        /// <summary>
        /// Adds the line item to cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModelList">The input model.</param>
        /// <returns>
        /// The manager response where the result is retuned indicating the success or failure of the operation.
        /// </returns>
        public virtual ManagerResponse <CartResult, bool> AddLineItemsToCart([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, IEnumerable <AddCartLineInputModel> inputModelList)
        {
            Assert.ArgumentNotNull(inputModelList, "inputModelList");

            var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, visitorContext.UserId, false);

            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError);
                cartResult.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
                return(new ManagerResponse <CartResult, bool>(cartResult, cartResult.Success));
            }

            var lines = new List <CartLine>();

            foreach (var inputModel in inputModelList)
            {
                Assert.ArgumentNotNullOrEmpty(inputModel.ProductId, "inputModel.ProductId");
                Assert.ArgumentNotNullOrEmpty(inputModel.CatalogName, "inputModel.CatalogName");
                Assert.ArgumentNotNull(inputModel.Quantity, "inputModel.Quantity");

                var quantity = (uint)inputModel.Quantity;

                //// Special handling for a Gift Card
                if (inputModel.ProductId.Equals(storefront.GiftCardProductId, StringComparison.OrdinalIgnoreCase))
                {
                    inputModel.VariantId = inputModel.GiftCardAmount.Value.ToString("000", CultureInfo.InvariantCulture);
                }

                var cartLine = new CommerceCartLine(inputModel.CatalogName, inputModel.ProductId, inputModel.VariantId == "-1" ? null : inputModel.VariantId, quantity);
                cartLine.Properties["ProductUrl"] = inputModel.ProductUrl;
                cartLine.Properties["ImageUrl"]   = inputModel.ImageUrl;
                //// UpdateStockInformation(storefront, visitorContext, cartLine, inputModel.CatalogName);

                lines.Add(cartLine);
            }

            var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();

            cartCache.InvalidateCartCache(visitorContext.GetCustomerId());

            var cart            = cartResult.Cart as CommerceCart;
            var addLinesRequest = new AddCartLinesRequest(cart, lines);

            addLinesRequest.RefreshCart(true);
            var addLinesResult = this.CartServiceProvider.AddCartLines(addLinesRequest);

            if (addLinesResult.Success && addLinesResult.Cart != null)
            {
                cartCache.AddCartToCache(addLinesResult.Cart as CommerceCart);
            }

            this.AddBasketErrorsToResult(addLinesResult.Cart as CommerceCart, addLinesResult);

            Helpers.LogSystemMessages(addLinesResult.SystemMessages, addLinesResult);
            return(new ManagerResponse <CartResult, bool>(addLinesResult, addLinesResult.Success));
        }
        /// <summary>
        /// Resets the user password.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>The manager response.</returns>
        public virtual ManagerResponse <UpdatePasswordResult, bool> ResetUserPassword([NotNull] CommerceStorefront storefront, ForgotPasswordInputModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(inputModel, "inputModel");
            Assert.ArgumentNotNullOrEmpty(inputModel.Email, "inputModel.Email");

            var result = new UpdatePasswordResult {
                Success = true
            };

            var getUserResponse = this.GetUser(inputModel.Email);

            if (!getUserResponse.ServiceProviderResult.Success || getUserResponse.Result == null)
            {
                result.Success = false;
                foreach (var systemMessage in getUserResponse.ServiceProviderResult.SystemMessages)
                {
                    result.SystemMessages.Add(systemMessage);
                }
            }
            else
            {
                try
                {
                    var    userIpAddress       = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : string.Empty;
                    string provisionalPassword = Membership.Provider.ResetPassword(getUserResponse.Result.UserName, string.Empty);

                    var mailUtil     = new MailUtil();
                    var wasEmailSent = mailUtil.SendMail("ForgotPassword", inputModel.Email, storefront.SenderEmailAddress, new object(), new object[] { userIpAddress, provisionalPassword });
                    if (!wasEmailSent)
                    {
                        var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CouldNotSentEmailError);
                        result.Success = false;
                        result.SystemMessages.Add(new SystemMessage {
                            Message = message
                        });
                    }
                }
                catch (Exception e)
                {
                    result.Success = false;
                    result.SystemMessages.Add(new SystemMessage {
                        Message = e.Message
                    });
                }

                if (!result.Success)
                {
                    Helpers.LogSystemMessages(result.SystemMessages, result);
                }
            }

            return(new ManagerResponse <UpdatePasswordResult, bool>(result, result.Success));
        }
Exemple #7
0
        /// <summary>
        /// Updates the user.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>
        /// The manager response where the user is returned.
        /// </returns>
        public virtual ManagerResponse <UpdateUserResult, CommerceUser> UpdateUser([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, ProfileModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(inputModel, "inputModel");

            UpdateUserResult result;

            var userName     = visitorContext.UserName;
            var commerceUser = this.GetUser(userName).Result;

            if (commerceUser != null)
            {
                commerceUser.FirstName = inputModel.FirstName;
                commerceUser.LastName  = inputModel.LastName;
                commerceUser.Email     = inputModel.Email;
                commerceUser.SetPropertyValue("Phone", inputModel.TelephoneNumber);

                try
                {
                    var request = new UpdateUserRequest(commerceUser);
                    result = this.CustomerServiceProvider.UpdateUser(request);
                }
                catch (Exception ex)
                {
                    result = new UpdateUserResult {
                        Success = false
                    };
                    result.SystemMessages.Add(new Sitecore.Commerce.Services.SystemMessage {
                        Message = ex.Message + "/" + ex.StackTrace
                    });
                }
            }
            else
            {
                // user is authenticated, but not in the CommerceUsers domain - probably here because we are in edit or preview mode
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UpdateUserProfileError);
                message = string.Format(CultureInfo.InvariantCulture, message, Context.User.LocalName);
                result  = new UpdateUserResult {
                    Success = false
                };

                result.SystemMessages.Add(new Commerce.Services.SystemMessage {
                    Message = message
                });
            }

            if (!result.Success)
            {
                Helpers.LogSystemMessages(result.SystemMessages, result);
            }

            return(new ManagerResponse <UpdateUserResult, CommerceUser>(result, result.CommerceUser));
        }
Exemple #8
0
        /// <summary>
        /// Submits the visitor order.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>
        /// The manager response where the new CommerceOrder is returned in the Result.
        /// </returns>
        public ManagerResponse <SubmitVisitorOrderResult, CommerceOrder> SubmitVisitorOrder([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] SubmitOrderInputModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(inputModel, "inputModel");

            SubmitVisitorOrderResult errorResult = new SubmitVisitorOrderResult {
                Success = false
            };

            var response = this.CartManager.GetCurrentCart(storefront, visitorContext, true);

            if (!response.ServiceProviderResult.Success || response.Result == null)
            {
                response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m));
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null));
            }

            var cart = (CommerceCart)response.ServiceProviderResult.Cart;

            if (cart.Lines.Count == 0)
            {
                errorResult.SystemMessages.Add(new SystemMessage {
                    Message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.SubmitOrderHasEmptyCart)
                });
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null));
            }

            var cartChanges = new CommerceCart();

            cartChanges.Properties["Email"] = inputModel.UserEmail;

            var updateCartResult = this.CartManager.UpdateCart(storefront, visitorContext, cart, cartChanges);

            if (!updateCartResult.ServiceProviderResult.Success)
            {
                response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m));
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null));
            }

            var request = new SubmitVisitorOrderRequest(cart);

            request.RefreshCart(true);
            errorResult = this.OrderServiceProvider.SubmitVisitorOrder(request);
            if (errorResult.Success && errorResult.Order != null && errorResult.CartWithErrors == null)
            {
                var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();
                cartCache.InvalidateCartCache(visitorContext.GetCustomerId());
            }

            Helpers.LogSystemMessages(errorResult.SystemMessages, errorResult);
            return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, errorResult.Order as CommerceOrder));
        }
Exemple #9
0
        /// <summary>
        /// Gets the product bulk prices.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="catalogName">Name of the catalog.</param>
        /// <param name="productIds">The product ids.</param>
        /// <returns>
        /// The manager response with the list of prices in the Result.
        /// </returns>
        public virtual ManagerResponse <GetProductBulkPricesResult, IDictionary <string, Price> > GetProductBulkPrices([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string catalogName, IEnumerable <string> productIds)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

            var request = new Sitecore.Reference.Storefront.Connect.Pipelines.Arguments.GetProductBulkPricesRequest(catalogName, productIds);

            request.CurrencyCode = StorefrontManager.GetCustomerCurrency();

            var result = this.PricingServiceProvider.GetProductBulkPrices(request);

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <GetProductBulkPricesResult, IDictionary <string, Price> >(result, result.Prices ?? new Dictionary <string, Price>()));
        }
Exemple #10
0
        /// <summary>
        /// Activates the loyalty account for the current user cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <returns>
        /// The manager response where the loyalty card is returned in the Result.
        /// </returns>
        public virtual ManagerResponse <JoinLoyaltyProgramResult, LoyaltyCard> ActivateAccount([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext)
        {
            var result = new JoinLoyaltyProgramResult {
                Success = false
            };
            var cartResult = this.CartManager.GetCurrentCart(storefront, visitorContext, false);

            if (!cartResult.ServiceProviderResult.Success || cartResult.Result == null)
            {
                result.SystemMessages.ToList().AddRange(cartResult.ServiceProviderResult.SystemMessages);
                return(new ManagerResponse <JoinLoyaltyProgramResult, LoyaltyCard>(result, null));
            }

            var errorResult = new JoinLoyaltyProgramResult()
            {
                Success = false
            };

            // Limit the number of loyalty programs a user may join.
            var currentLoyaltyProgramResult = this.GetLoyaltyCards(storefront, visitorContext.UserId);

            if (!currentLoyaltyProgramResult.ServiceProviderResult.Success)
            {
                currentLoyaltyProgramResult.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m));
                return(new ManagerResponse <JoinLoyaltyProgramResult, LoyaltyCard>(errorResult, null));
            }

            int maxLoyaltyProgramsToJoin = ((DynamicsStorefront)StorefrontManager.CurrentStorefront).MaxNumberOfLoyaltyProgramsToJoin;

            if (currentLoyaltyProgramResult.Result.Count() >= maxLoyaltyProgramsToJoin)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.MaxLoyaltyProgramsToJoinReached);
                message = string.Format(CultureInfo.InvariantCulture, message, maxLoyaltyProgramsToJoin);
                errorResult.SystemMessages.Add(new Commerce.Services.SystemMessage()
                {
                    Message = message
                });
                return(new ManagerResponse <JoinLoyaltyProgramResult, LoyaltyCard>(errorResult, null));
            }

            var cart    = (CommerceCart)cartResult.ServiceProviderResult.Cart;
            var request = new Sitecore.Commerce.Connect.DynamicsRetail.Services.LoyaltyPrograms.JoinLoyaltyProgramRequest(visitorContext.UserId, storefront.ShopName)
            {
                CartId = cart.ExternalId
            };

            result = this.LoyaltyProgramServiceProvider.JoinLoyaltyProgram(request);

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <JoinLoyaltyProgramResult, LoyaltyCard>(result, result.LoyaltyCard));
        }
        /// <summary>
        /// Merges the carts.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="anonymousVisitorId">The anonymous visitor identifier.</param>
        /// <param name="anonymousVisitorCart">The anonymous visitor cart.</param>
        /// <returns>
        /// The manager response where the merged cart is returned in the result.
        /// </returns>
        public virtual ManagerResponse <CartResult, CommerceCart> MergeCarts([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string anonymousVisitorId, Cart anonymousVisitorCart)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNullOrEmpty(anonymousVisitorId, "anonymousVisitorId");

            var userId     = visitorContext.UserId;
            var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, userId, true);

            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError);
                cartResult.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
                return(new ManagerResponse <CartResult, CommerceCart>(cartResult, cartResult.Cart as CommerceCart));
            }

            CommerceCart currentCart = (CommerceCart)cartResult.Cart;
            var          result      = new CartResult {
                Cart = currentCart, Success = true
            };

            if (userId != anonymousVisitorId)
            {
                var anonymousCartHasPromocodes = (anonymousVisitorCart is CommerceCart) &&
                                                 ((CommerceCart)anonymousVisitorCart).OrderForms.Any(of => of.PromoCodes.Any());

                if (anonymousVisitorCart != null && (anonymousVisitorCart.Lines.Any() || anonymousCartHasPromocodes))
                {
                    if ((currentCart.ShopName == anonymousVisitorCart.ShopName) || (currentCart.ExternalId != anonymousVisitorCart.ExternalId))
                    {
                        var mergeCartRequest = new MergeCartRequest(anonymousVisitorCart, currentCart);
                        result = this.CartServiceProvider.MergeCart(mergeCartRequest);
                    }
                }
            }

            if (result.Success && result.Cart != null)
            {
                var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();
                cartCache.InvalidateCartCache(anonymousVisitorId);
                cartCache.AddCartToCache(result.Cart as CommerceCart);
            }

            return(new ManagerResponse <CartResult, CommerceCart>(result, result.Cart as CommerceCart));
        }
        /// <summary>
        /// Changes the line quantity.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>
        /// The manager response where the modified CommerceCart is returned in the Result.
        /// </returns>
        public virtual ManagerResponse <CartResult, CommerceCart> ChangeLineQuantity([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] UpdateCartLineInputModel inputModel)
        {
            Assert.ArgumentNotNull(inputModel, "inputModel");
            Assert.ArgumentNotNullOrEmpty(inputModel.ExternalCartLineId, "inputModel.ExternalCartLineId");

            var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, visitorContext.UserId);

            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError);
                cartResult.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
                return(new ManagerResponse <CartResult, CommerceCart>(cartResult, cartResult.Cart as CommerceCart));
            }

            var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();

            cartCache.InvalidateCartCache(visitorContext.GetCustomerId());

            var cart   = cartResult.Cart;
            var result = new CartResult {
                Cart = cart, Success = true
            };
            var cartLineToChange = cart.Lines.SingleOrDefault(cl => cl.Product != null && cl.ExternalCartLineId == inputModel.ExternalCartLineId);

            if (inputModel.Quantity == 0 && cartLineToChange != null)
            {
                result = this.RemoveCartLines(cart, new[] { cartLineToChange }, true);
            }
            else if (cartLineToChange != null)
            {
                cartLineToChange.Quantity = inputModel.Quantity;
                var request = new UpdateCartLinesRequest(cart, new[] { cartLineToChange });
                request.RefreshCart(true);
                result = this.CartServiceProvider.UpdateCartLines(request);
            }

            if (result.Success && result.Cart != null)
            {
                cartCache.AddCartToCache(result.Cart as CommerceCart);
            }

            this.AddBasketErrorsToResult(result.Cart as CommerceCart, result);

            return(new ManagerResponse <CartResult, CommerceCart>(result, result.Cart as CommerceCart));
        }
        /// <summary>
        /// Removes the line item from cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="externalCartLineId">The external cart line identifier.</param>
        /// <returns>
        /// The manager response where the modified CommerceCart is returned in the Result.
        /// </returns>
        public virtual ManagerResponse <CartResult, CommerceCart> RemoveLineItemFromCart([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] string externalCartLineId)
        {
            Assert.ArgumentNotNullOrEmpty(externalCartLineId, "externalCartLineId");

            var cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, visitorContext.UserId, false);

            if (!cartResult.Success || cartResult.Cart == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError);
                cartResult.SystemMessages.Add(new SystemMessage
                {
                    Message = message
                });
                return(new ManagerResponse <CartResult, CommerceCart>(cartResult, cartResult.Cart as CommerceCart));
            }

            var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();

            cartCache.InvalidateCartCache(visitorContext.GetCustomerId());

            CommerceCart cart         = cartResult.Cart as CommerceCart;
            var          lineToRemove = cart.Lines.SingleOrDefault(cl => cl.ExternalCartLineId == externalCartLineId);

            if (lineToRemove == null)
            {
                return(new ManagerResponse <CartResult, CommerceCart>(new CartResult {
                    Success = true
                }, cart));
            }

            var removeLinesRequest = new RemoveCartLinesRequest(cart, new[] { new CartLine {
                                                                                  ExternalCartLineId = externalCartLineId, Quantity = lineToRemove.Quantity, Product = lineToRemove.Product
                                                                              } });

            removeLinesRequest.RefreshCart(true);
            var removeLinesResult = this.CartServiceProvider.RemoveCartLines(removeLinesRequest);

            if (removeLinesResult.Success && removeLinesResult.Cart != null)
            {
                cartCache.AddCartToCache(removeLinesResult.Cart as CommerceCart);
            }

            Helpers.LogSystemMessages(removeLinesResult.SystemMessages, removeLinesResult);
            return(new ManagerResponse <CartResult, CommerceCart>(removeLinesResult, removeLinesResult.Cart as CommerceCart));
        }
Exemple #14
0
        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <param name="userName">The username.</param>
        /// <returns>
        /// The manager response where the user is returned in the response.
        /// </returns>
        public virtual ManagerResponse <GetUserResult, CommerceUser> GetUser(string userName)
        {
            Assert.ArgumentNotNullOrEmpty(userName, "userName");

            var request = new GetUserRequest(userName);
            var result  = this.CustomerServiceProvider.GetUser(request);

            if (!result.Success || result.CommerceUser == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserNotFoundError);
                result.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
            }

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <GetUserResult, CommerceUser>(result, result.CommerceUser));
        }
Exemple #15
0
        /// <summary>
        /// Gets the product prices.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="productId">The product identifier.</param>
        /// <param name="priceTypeIds">The price type ids.</param>
        /// <returns>
        /// The manager response with the list of prices in the Result.
        /// </returns>
        public virtual ManagerResponse <GetProductPricesResult, IDictionary <string, Price> > GetProductPrices([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string productId, params string[] priceTypeIds)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

            var request = new GetProductPricesRequest(productId, priceTypeIds);

            if (Sitecore.Context.User.IsAuthenticated)
            {
                request.UserId = visitorContext.GetCustomerId();
            }

            request.CurrencyCode = StorefrontManager.GetCustomerCurrency();

            var result = this.PricingServiceProvider.GetProductPrices(request);

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <GetProductPricesResult, IDictionary <string, Price> >(result, result.Prices ?? new Dictionary <string, Price>()));
        }
        /// <summary>
        /// Adds the lines to wish list.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="wishListId">The wish list identifier.</param>
        /// <param name="lines">The lines.</param>
        /// <returns>The manager response with the wish list as the result.</returns>
        public virtual ManagerResponse <AddLinesToWishListResult, WishList> AddLinesToWishList([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string wishListId, IEnumerable <WishListLine> lines)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(lines, "lines");
            Assert.ArgumentNotNullOrEmpty(wishListId, "wishListId");

            var errorResult = new AddLinesToWishListResult()
            {
                Success = false
            };

            // Limit the number of wish list lines that can get created.
            var wishListResult = this.GetWishList(storefront, visitorContext, wishListId);

            if (!wishListResult.ServiceProviderResult.Success)
            {
                wishListResult.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m));
                return(new ManagerResponse <AddLinesToWishListResult, WishList>(errorResult, null));
            }

            if (wishListResult.Result.Lines.Count() >= StorefrontManager.CurrentStorefront.MaxNumberOfWishListItems)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.MaxWishListLineLimitReached);
                message = string.Format(CultureInfo.InvariantCulture, message, StorefrontManager.CurrentStorefront.MaxNumberOfWishLists);
                errorResult.SystemMessages.Add(new Commerce.Services.SystemMessage()
                {
                    Message = message
                });
                return(new ManagerResponse <AddLinesToWishListResult, WishList>(errorResult, null));
            }

            var request = new AddLinesToWishListRequest(new WishList {
                UserId = visitorContext.UserId, CustomerId = visitorContext.UserId, ExternalId = wishListId, ShopName = storefront.ShopName
            }, lines);
            var result = this.WishListServiceProvider.AddLinesToWishList(request);

            if (!result.Success)
            {
                Helpers.LogSystemMessages(result.SystemMessages, result);
            }

            return(new ManagerResponse <AddLinesToWishListResult, WishList>(result, result.WishList));
        }
Exemple #17
0
        /// <summary>
        /// Gets the product bulk prices.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="catalogName">Name of the catalog.</param>
        /// <param name="productIds">The product ids.</param>
        /// <param name="priceTypeIds">The price type ids.</param>
        /// <returns>
        /// The manager response with the list of prices in the Result.
        /// </returns>
        public virtual ManagerResponse <Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult, IDictionary <string, Price> > GetProductBulkPrices([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, string catalogName, IEnumerable <string> productIds, params string[] priceTypeIds)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

            if (priceTypeIds == null)
            {
                priceTypeIds = defaultPriceTypeIds;
            }

            var request = new RefSFArgs.GetProductBulkPricesRequest(catalogName, productIds, priceTypeIds);

            request.CurrencyCode = StorefrontManager.GetCustomerCurrency();

            var result = this.PricingServiceProvider.GetProductBulkPrices(request);

            // Currently, both Categories and Products are passed in and are waiting for a fix to filter the categories out.  Until then, this code is commented
            // out as it generates an unecessary Error event indicating the product cannot be found.
            // Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult, IDictionary <string, Price> >(result, result.Prices == null ? new Dictionary <string, Price>() : result.Prices));
        }
        /// <summary>
        /// Creates the wish list.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="wishListName">Name of the wish list.</param>
        /// <returns>The manager response with the wish list as the result.</returns>
        public virtual ManagerResponse <CreateWishListResult, WishList> CreateWishList([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] string wishListName)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNullOrEmpty(wishListName, "wishListName");

            CreateWishListResult errorResult = new CreateWishListResult()
            {
                Success = false
            };

            // Limit the number of wish list that can get created.
            var wishListResponse = this.GetWishLists(storefront, visitorContext);

            if (!wishListResponse.ServiceProviderResult.Success)
            {
                wishListResponse.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m));
                return(new ManagerResponse <CreateWishListResult, WishList>(errorResult, null));
            }

            if (wishListResponse.Result.Count() >= StorefrontManager.CurrentStorefront.MaxNumberOfWishLists)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.MaxWishListLimitReached);
                message = string.Format(CultureInfo.InvariantCulture, message, StorefrontManager.CurrentStorefront.MaxNumberOfWishLists);
                errorResult.SystemMessages.Add(new Commerce.Services.SystemMessage()
                {
                    Message = message
                });
                return(new ManagerResponse <CreateWishListResult, WishList>(errorResult, null));
            }

            var request = new CreateWishListRequest(visitorContext.UserId, wishListName, storefront.ShopName);
            var result  = this.WishListServiceProvider.CreateWishList(request);

            if (!result.Success)
            {
                Helpers.LogSystemMessages(result.SystemMessages, result);
            }

            return(new ManagerResponse <CreateWishListResult, WishList>(result, result.WishList));
        }
Exemple #19
0
        /// <summary>
        /// Gets the users.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="userName">The username.</param>
        /// <returns>
        /// The manager response where a list of users is returned in the response.
        /// </returns>
        public virtual ManagerResponse <GetUsersResult, IList <CommerceUser> > GetUsers([NotNull] CommerceStorefront storefront, string userName)
        {
            Assert.ArgumentNotNullOrEmpty(userName, "userName");

            var criteria = new UserSearchCriteria {
                UserName = userName, ShopName = storefront.ShopName
            };
            var request = new GetUsersRequest(criteria);
            var result  = this.CustomerServiceProvider.GetUsers(request);

            if (!result.Success || result.CommerceUsers == null)
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserNotFoundError);
                result.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
            }

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <GetUsersResult, IList <CommerceUser> >(result, result.CommerceUsers));
        }
        /// <summary>
        /// Registers the user.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="inputModel">The input model.</param>
        /// <returns>
        /// The manager result where the user is returned as the Result.
        /// </returns>
        public virtual ManagerResponse <CreateUserResult, CommerceUser> RegisterUser([NotNull] CommerceStorefront storefront, RegisterUserInputModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(inputModel, "inputModel");
            Assert.ArgumentNotNullOrEmpty(inputModel.UserName, "inputModel.UserName");
            Assert.ArgumentNotNullOrEmpty(inputModel.Password, "inputModel.Password");

            CreateUserResult result;

            // Attempt to register the user
            try
            {
                var request = new CreateUserRequest(inputModel.UserName, inputModel.Password, inputModel.UserName, storefront.ShopName);
                result = this.CustomerServiceProvider.CreateUser(request);
                if (!result.Success)
                {
                    Helpers.LogSystemMessages(result.SystemMessages, result);
                }
                else if (result.Success && result.CommerceUser == null && result.SystemMessages.Count() == 0)
                {
                    // Connect bug:  This is a work around to a Connect bug.  When the user already exists,connect simply aborts the pipeline but
                    // does not set the success flag nor does it return an error message.
                    result.Success = false;
                    result.SystemMessages.Add(new SystemMessage {
                        Message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserAlreadyExists)
                    });
                }
            }
            catch (MembershipCreateUserException e)
            {
                result = new CreateUserResult {
                    Success = false
                };
                result.SystemMessages.Add(new Commerce.Services.SystemMessage {
                    Message = ErrorCodeToString(e.StatusCode)
                });
            }

            return(new ManagerResponse <CreateUserResult, CommerceUser>(result, result.CommerceUser));
        }
        /// <summary>
        /// Returns the current user cart.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="customerId">The customer identifier.</param>
        /// <param name="refresh">if set to <c>true</c> [refresh].</param>
        /// <returns>
        /// The manager response where the modified CommerceCart is returned in the Result.
        /// </returns>
        public virtual ManagerResponse <CartResult, CommerceCart> GetCurrentCart([NotNull] CommerceStorefront storefront, [NotNull] string customerId, bool refresh = false)
        {
            var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();

            if (refresh)
            {
                cartCache.InvalidateCartCache(customerId);
            }

            var cart = cartCache.GetCart(customerId);

            if (cart != null)
            {
                var result = new CartResult {
                    Cart = cart
                };
                this.AddBasketErrorsToResult(result.Cart as CommerceCart, result);
                return(new ManagerResponse <CartResult, CommerceCart>(result, cart));
            }

            CartResult cartResult = this.LoadCartByName(storefront.ShopName, storefront.DefaultCartName, customerId, refresh);

            if (cartResult.Success && cartResult.Cart != null)
            {
                cart            = cartResult.Cart as CommerceCart;
                cartResult.Cart = cart;
                cartCache.AddCartToCache(cart);
            }
            else
            {
                var message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.CartNotFoundError);
                cartResult.SystemMessages.Add(new SystemMessage {
                    Message = message
                });
            }

            this.AddBasketErrorsToResult(cartResult.Cart as CommerceCart, cartResult);

            return(new ManagerResponse <CartResult, CommerceCart>(cartResult, cart));
        }
Exemple #22
0
        /// <summary>
        /// Errors the code to string.
        /// </summary>
        /// <param name="createStatus">The create status.</param>
        /// <returns>The membership error status.</returns>
        protected virtual string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
            case MembershipCreateStatus.DuplicateUserName:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserAlreadyExists));

            case MembershipCreateStatus.DuplicateEmail:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserNameForEmailExists));

            case MembershipCreateStatus.InvalidPassword:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.InvalidPasswordError));

            case MembershipCreateStatus.InvalidEmail:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.InvalidEmailError));

            case MembershipCreateStatus.InvalidAnswer:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.PasswordRetrievalAnswerInvalid));

            case MembershipCreateStatus.InvalidQuestion:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.PasswordRetrievalQuestionInvalid));

            case MembershipCreateStatus.InvalidUserName:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserNameInvalid));

            case MembershipCreateStatus.ProviderError:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.AuthenticationProviderError));

            case MembershipCreateStatus.UserRejected:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UserRejectedError));

            default:
                return(StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.UnknownMembershipProviderError));
            }
        }
        public ManagerResponse <SubmitVisitorOrderResult, CommerceOrder> SubmitVisitorOrder([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] SubmitOrderInputModel inputModel)
        {
            Assert.ArgumentNotNull(storefront, "storefront");
            Assert.ArgumentNotNull(visitorContext, "visitorContext");
            Assert.ArgumentNotNull(inputModel, "inputModel");

            SubmitVisitorOrderResult result = new SubmitVisitorOrderResult {
                Success = false
            };
            var response = this.CartManager.GetCurrentCart(storefront, visitorContext, true);

            if (!response.ServiceProviderResult.Success || response.Result == null)
            {
                result.SystemMessages.ToList().AddRange(response.ServiceProviderResult.SystemMessages);
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(result, null));
            }

            var cart = (CommerceCart)response.ServiceProviderResult.Cart;

            if (cart.Lines.Count == 0)
            {
                result.SystemMessages.Add(new SystemMessage {
                    Message = StorefrontManager.GetSystemMessage(StorefrontConstants.SystemMessages.SubmitOrderHasEmptyCart)
                });
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(result, null));
            }

            // payments and billing address will be save as part of submit order
            var payments = new List <PaymentInfo>();

            if (inputModel.CreditCardPayment != null && !string.IsNullOrEmpty(inputModel.CreditCardPayment.PaymentMethodID) && inputModel.BillingAddress != null)
            {
                payments.Add(inputModel.CreditCardPayment.ToCreditCardPaymentInfo());
                List <Party> parties = cart.Parties.ToList();
                parties.Add(inputModel.BillingAddress.ToParty());
                cart.Parties = parties.AsSafeReadOnly();
            }

            if (inputModel.GiftCardPayment != null && !string.IsNullOrEmpty(inputModel.GiftCardPayment.PaymentMethodID))
            {
                payments.Add(inputModel.GiftCardPayment.ToGiftCardPaymentInfo());
            }

            if (inputModel.LoyaltyCardPayment != null && !string.IsNullOrEmpty(inputModel.LoyaltyCardPayment.PaymentMethodID))
            {
                payments.Add(inputModel.LoyaltyCardPayment.ToLoyaltyCardPaymentInfo());
            }

            cart.Payment = payments.ToList().AsReadOnly();

            var request = new Sitecore.Commerce.Connect.DynamicsRetail.Services.Orders.SubmitVisitorOrderRequest(cart, inputModel.UserEmail);

            request.RefreshCart(true);
            result = this.OrderServiceProvider.SubmitVisitorOrder(request);
            if (result.Success && result.Order != null && result.CartWithErrors == null)
            {
                var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>();
                cartCache.InvalidateCartCache(visitorContext.GetCustomerId());
            }

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(result, result.Order as CommerceOrder));
        }
        /// <summary>
        /// Gets the product stock status.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="productViewModels">The product view models.</param>
        public virtual void GetProductsStockStatus([NotNull] CommerceStorefront storefront, List <ProductViewModel> productViewModels)
        {
            if (productViewModels == null || !productViewModels.Any())
            {
                return;
            }

            var products = new List <CommerceInventoryProduct>();

            foreach (var viewModel in productViewModels)
            {
                if (viewModel.Variants != null && viewModel.Variants.Any())
                {
                    foreach (var variant in viewModel.Variants)
                    {
                        products.Add(new CommerceInventoryProduct
                        {
                            ProductId   = viewModel.ProductId,
                            CatalogName = viewModel.CatalogName,
                            VariantId   = variant.VariantId
                        });
                    }
                }
                else
                {
                    products.Add(new CommerceInventoryProduct {
                        ProductId = viewModel.ProductId, CatalogName = viewModel.CatalogName
                    });
                }
            }

            if (products.Any())
            {
                var response = this.GetStockInformation(storefront, products, StockDetailsLevel.All);
                if (response.Result != null)
                {
                    var stockInfoList = response.Result.ToList();

                    foreach (var viewModel in productViewModels)
                    {
                        StockInformation foundItem = null;
                        if (viewModel.Variants != null && viewModel.Variants.Any())
                        {
                            foreach (var variant in viewModel.Variants)
                            {
                                foundItem = stockInfoList.Find(p => p.Product.ProductId == viewModel.ProductId && ((CommerceInventoryProduct)p.Product).VariantId == variant.VariantId);
                            }
                        }
                        else
                        {
                            foundItem = stockInfoList.Find(p => p.Product.ProductId == viewModel.ProductId);
                        }

                        if (foundItem != null)
                        {
                            viewModel.StockStatus     = foundItem.Status;
                            viewModel.StockStatusName = StorefrontManager.GetProductStockStatusName(foundItem.Status);
                        }
                    }
                }
            }
        }