Exemplo n.º 1
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] IVisitorContext 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
                });
            }

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

            return(new ManagerResponse <UpdatePasswordResult, bool>(result, result.Success));
        }
        /// <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] IVisitorContext 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 = ContextTypeLoader.CreateInstance <CartCacheHelper>();
                cartCache.InvalidateCartCache(visitorContext.GetCustomerId());
            }

            //Helpers.LogSystemMessages(errorResult.SystemMessages, errorResult);
            return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, errorResult.Order as CommerceOrder));
        }
Exemplo n.º 3
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] IVisitorContext 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
                });
            }

            //Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <UpdateUserResult, CommerceUser>(result, result.CommerceUser));
        }
        /// <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] IVisitorContext 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 = 10;//(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 = new JoinLoyaltyProgramResult();//this.LoyaltyProgramServiceProvider.JoinLoyaltyProgram(request);

            Helpers.LogSystemMessages(result.SystemMessages, result);
            return(new ManagerResponse <JoinLoyaltyProgramResult, LoyaltyCard>(result, result.LoyaltyCard));
        }
Exemplo n.º 5
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));
        }
        /// <summary>
        /// Builds a catalog item link.
        /// </summary>
        /// <param name="itemName">The catalog item name.</param>
        /// <param name="itemFriendlyName">The catalog item friendy / display name.</param>
        /// <param name="catalogName">The name of the catalog that includes the catalog item.</param>
        /// <param name="root">The root catalog item path.</param>
        /// <returns>The catalog item link.</returns>
        public static string BuildUrl(string itemName, string itemFriendlyName, string catalogName, string root)
        {
            Assert.ArgumentNotNullOrEmpty(itemName, "itemName");

            var route = new StringBuilder("/");

            if (IncludeLanguage)
            {
                route.Append(Sitecore.Context.Language.Name);
                route.Append("/");
            }

            var isGiftCard = (itemName == StorefrontManager.CurrentStorefront.GiftCardProductId);

            if (isGiftCard)
            {
                route.Append(ProductItemResolver.LandingUrlRoute);
                route.Append("/");
                route.Append(ProductItemResolver.BuyGiftCardUrlRoute);
            }
            else
            {
                if (!string.IsNullOrEmpty(catalogName))
                {
                    route.Append(EncodeUrlToken(catalogName, true));
                    route.Append("/");
                }

                route.Append(root);
                route.Append("/");

                if (!string.IsNullOrEmpty(itemFriendlyName))
                {
                    route.Append(EncodeUrlToken(itemFriendlyName, true));
                    route.Append(_urlTokenDelimiter);
                }

                route.Append(EncodeUrlToken(itemName, false));
            }

            var url = StorefrontManager.StorefrontUri(route.ToString());

            return(url);
        }
Exemplo n.º 7
0
        /// <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>
        /// 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] IVisitorContext visitorContext, string catalogName, IEnumerable <string> productIds, params string[] priceTypeIds)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

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

            var request = new Requests.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>
        /// 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 <Sitecore.Commerce.Services.Prices.GetProductPricesResult, IDictionary <string, Price> > GetProductPrices([NotNull] CommerceStorefront storefront, [NotNull] IVisitorContext visitorContext, string catalogName, string productId, bool includeVariants, params string[] priceTypeIds)
        {
            Assert.ArgumentNotNull(storefront, "storefront");

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

            var request = new Requests.GetProductPricesRequest(catalogName, productId, priceTypeIds);

            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 <Sitecore.Commerce.Services.Prices.GetProductPricesResult, IDictionary <string, Price> >(result, result.Prices == null ? new Dictionary <string, Price>() : result.Prices));
        }
Exemplo n.º 10
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));
            }
        }
        /// <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);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Groups the provided relationships by name, and converts them into a list of <see cref="CategoryViewModel" /> objects.
        /// </summary>
        /// <param name="storefront">The storefront.</param>
        /// <param name="visitorContext">The visitor context.</param>
        /// <param name="field">The relationship field.</param>
        /// <param name="relationshipNames">The names of the relationships to retrieve.</param>
        /// <param name="productRelationshipInfoList">The list of rerlationships to group and convert.</param>
        /// <param name="rendering">The rendering.</param>
        /// <returns>The grouped relationships converted into a list of <see cref="CategoryViewModel" /> objects.</returns>
        protected IEnumerable <CategoryViewModel> GroupRelationshipsByDescription([NotNull] CommerceStorefront storefront, [NotNull] IVisitorContext visitorContext, RelationshipField field, IEnumerable <string> relationshipNames, IEnumerable <CatalogRelationshipInformation> productRelationshipInfoList, Rendering rendering)
        {
            var 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 = string.IsNullOrWhiteSpace(relationshipInfo.RelationshipDescription) ? StorefrontManager.GetRelationshipName(relationshipInfo.RelationshipName, out lookupItem) : relationshipInfo.RelationshipDescription;
                        CategoryViewModel categoryModel;
                        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);

                        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);
        }