/// <summary> /// Gets all the products under a specific category /// </summary> /// <param name="categoryId">The category name</param> /// <param name="searchOptions">The paging options for this query</param> /// <returns>A list of child products</returns> public static SearchResponse GetCategoryProducts(ID categoryId, CommerceSearchOptions searchOptions) { var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchIndex = searchManager.GetIndex(); using (var context = searchIndex.CreateSearchContext()) { var searchResults = context.GetQueryable <CommerceProductSearchResultItem>() .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product) .Where(item => item.Language == CurrentLanguageName) .Where(item => item.CommerceAncestorIds.Contains(categoryId)) .Select(p => new CommerceProductSearchResultItem() { ItemId = p.ItemId, Uri = p.Uri }); searchResults = searchManager.AddSearchOptionsToQuery <CommerceProductSearchResultItem>(searchResults, searchOptions); var results = searchResults.GetResults(); var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results); return(response); } }
/// <summary> /// Gets a product based on its product id /// </summary> /// <param name="productId">The product's id</param> /// <param name="catalogName">The name of the catalog containing the product</param> /// <returns>The found product item, or null if not found</returns> public static Item GetProduct(string productId, string catalogName) { Sitecore.Diagnostics.Assert.ArgumentNotNullOrEmpty(catalogName, "catalogName"); Item result = null; var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchIndex = searchManager.GetIndex(catalogName); using (var context = searchIndex.CreateSearchContext()) { var productQuery = context.GetQueryable <CommerceProductSearchResultItem>() .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product) .Where(item => item.CatalogName == catalogName) .Where(item => item.Language == CurrentLanguageName) .Where(item => item.CatalogItemId == productId.ToLowerInvariant()) .Select(p => new CommerceProductSearchResultItem() { ItemId = p.ItemId, Uri = p.Uri }) .Take(1); var foundSearchItem = productQuery.FirstOrDefault(); if (foundSearchItem != null) { result = foundSearchItem.GetItem(); } } return(result); }
/// <summary> /// _s the navigate. /// </summary> /// <param name="endResponse">if set to <c>true</c> [end response].</param> private void _Navigate(bool endResponse) { string uri = this.ToString(); var siteContext = CommerceTypeLoader.CreateInstance <ISiteContext>(); siteContext.CurrentContext.Response.Redirect(uri, endResponse); }
/// <summary> /// Initializes this object based on the data contained in the provided cart. /// </summary> /// <param name="cart">The cart used to initialize this object.</param> public virtual void Initialize(Cart cart) { this.Lines = new List <CartLineBaseJsonResult>(); this.Adjustments = new List <CartAdjustmentBaseJsonResult>(); this.PromoCodes = new List <string>(); if (cart == null) { return; } foreach (var line in (cart.Lines ?? Enumerable.Empty <CartLine>())) { var cartLine = CommerceTypeLoader.CreateInstance <CartLineBaseJsonResult>(line); this.Lines.Add(cartLine); } foreach (var adjustment in (cart.Adjustments ?? Enumerable.Empty <CartAdjustment>())) { this.Adjustments.Add(new CartAdjustmentBaseJsonResult(adjustment)); } var commerceTotal = (CommerceTotal)cart.Total; this.Subtotal = commerceTotal.Subtotal.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode); this.TaxTotal = cart.Total.TaxTotal.Amount.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode); this.Total = cart.Total.Amount.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode); this.TotalAmount = cart.Total.Amount; this.Discount = commerceTotal.OrderLevelDiscountAmount.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode); this.ShippingTotal = commerceTotal.ShippingTotal.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode); }
/// <summary> /// Reorders one or more items from an existing order. /// </summary> /// <param name="storefront">The storefront context.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="inputModel">The reorder input model.</param> /// <returns>The result of the operation.</returns> public ManagerResponse <CartResult, CommerceCart> Reorder([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, ReorderInputModel inputModel) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNull(inputModel, "inputModel"); Assert.ArgumentNotNullOrEmpty(inputModel.OrderId, "inputModel.OrderId"); var request = new ReorderByCartNameRequest() { CustomerId = visitorContext.GetCustomerId(), OrderId = inputModel.OrderId, ReorderLineExternalIds = inputModel.ReorderLineExternalIds, CartName = storefront.DefaultCartName, OrderShippingPreferenceType = ShippingOptionType.ShipToAddress, }; var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>(); cartCache.InvalidateCartCache(visitorContext.GetCustomerId()); var result = this.OrderServiceProvider.Reorder(request); if (result.Success && result.Cart != null) { cartCache.AddCartToCache(result.Cart as CommerceCart); } Helpers.LogSystemMessages(result.SystemMessages, result); return(new ManagerResponse <CartResult, CommerceCart>(result, result.Cart as CommerceCart)); }
/// <summary> /// Searches for catalog items based on keyword /// </summary> /// <param name="keyword">The keyword to search for.</param> /// <param name="catalogName">The name of the catalog containing the keyword</param> /// <param name="searchOptions">The paging options for this query</param> /// <returns>A list of child products</returns> public static SearchResponse SearchCatalogItemsByKeyword(string keyword, string catalogName, CommerceSearchOptions searchOptions) { Sitecore.Diagnostics.Assert.ArgumentNotNullOrEmpty(catalogName, "catalogName"); var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchIndex = searchManager.GetIndex(catalogName); using (var context = searchIndex.CreateSearchContext()) { var searchResults = context.GetQueryable <CommerceProductSearchResultItem>() .Where(item => item.Name.Equals(keyword) || item["_displayname"].Equals(keyword) || item.Content.Contains(keyword)) .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product || item.CommerceSearchItemType == CommerceSearchResultItemType.Category) .Where(item => item.CatalogName == catalogName) .Where(item => item.Language == CurrentLanguageName) .Select(p => new CommerceProductSearchResultItem() { ItemId = p.ItemId, Uri = p.Uri }); searchResults = searchManager.AddSearchOptionsToQuery <CommerceProductSearchResultItem>(searchResults, searchOptions); var results = searchResults.GetResults(); var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results); return(response); } }
private SearchInfo GetSearchInfo(string searchKeyword, int?pageNumber, string facetValues, string sortField, int?pageSize, CommerceConstants.SortDirection?sortDirection) { if (this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] != null) { return((SearchInfo)this.CurrentSiteContext.Items[CurrentSearchInfoKeyName]); } var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchInfo = new SearchInfo { SearchKeyword = searchKeyword ?? string.Empty, RequiredFacets = searchManager.GetFacetFieldsForItem(this.Item), SortFields = searchManager.GetSortFieldsForItem(this.Item), Catalog = StorefrontManager.CurrentStorefront.DefaultCatalog, ItemsPerPage = pageSize ?? searchManager.GetItemsPerPageForItem(this.Item) }; if (searchInfo.ItemsPerPage == 0) { searchInfo.ItemsPerPage = StorefrontConstants.Settings.DefaultItemsPerPage; } var productSearchOptions = new CommerceSearchOptions(searchInfo.ItemsPerPage, pageNumber.GetValueOrDefault(0)); this.UpdateOptionsWithFacets(searchInfo.RequiredFacets, facetValues, productSearchOptions); this.UpdateOptionsWithSorting(sortField, sortDirection, productSearchOptions); searchInfo.SearchOptions = productSearchOptions; this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] = searchInfo; return(searchInfo); }
/// <summary> /// Updates the cart currency. /// </summary> /// <param name="storefront">The storefront.</param> /// <param name="visitorContext">The visitor context.</param> /// <param name="currencyCode">The currency code.</param> /// <returns>The manager response.</returns> public virtual ManagerResponse <CartResult, bool> UpdateCartCurrency([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] string currencyCode) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNullOrEmpty(currencyCode, "currencyCode"); var result = this.GetCurrentCart(storefront, visitorContext); if (!result.ServiceProviderResult.Success) { return(new ManagerResponse <CartResult, bool>(new CartResult { Success = false }, false)); } var cart = result.Result; var changes = new CommerceCart() { CurrencyCode = currencyCode }; var updateCartResult = this.UpdateCart(storefront, visitorContext, cart, changes); if (updateCartResult.ServiceProviderResult.Success) { var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>(); string customerId = visitorContext.GetCustomerId(); cartCache.InvalidateCartCache(customerId); } return(new ManagerResponse <CartResult, bool>(updateCartResult.ServiceProviderResult, updateCartResult.ServiceProviderResult.Success)); }
/// <summary> /// Processes the specified arguments. /// </summary> /// <param name="args">The arguments.</param> public override void Process(Commerce.Pipelines.ServicePipelineArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(args.Request, "args.request"); Assert.ArgumentCondition(args.Request is RefSFArgs.GetSupportedCurrenciesRequest, "args.Request", "args.Request is RefSFArgs.GetSupportedCurrenciesRequest"); Assert.ArgumentCondition(args.Result is GetSupportedCurrenciesResult, "args.Result", "args.Result is GetSupportedCurrenciesResult"); var request = (RefSFArgs.GetSupportedCurrenciesRequest)args.Request; var result = (GetSupportedCurrenciesResult)args.Result; Assert.ArgumentNotNullOrEmpty(request.CatalogName, "request.CatalogName"); ICatalogRepository catalogRepository = CommerceTypeLoader.CreateInstance <ICatalogRepository>(); var catalog = catalogRepository.GetCatalogReadOnly(request.CatalogName); List <string> currencyList = new List <string>(); currencyList.Add(catalog["Currency"].ToString()); if (this._currenciesToInject.Count > 0) { currencyList.AddRange(this._currenciesToInject); } result.Currencies = new System.Collections.ObjectModel.ReadOnlyCollection <string>(currencyList); }
/// <summary> /// Initializes the line item shipping options. /// </summary> /// <param name="lineItemShippingOptionList">The line item shipping option list.</param> public virtual void InitializeLineItemShippingOptions(IEnumerable <LineShippingOption> lineItemShippingOptionList) { if (lineItemShippingOptionList != null && lineItemShippingOptionList.Any()) { var lineShippingOptionList = new List <LineShippingOptionBaseJsonResult>(); foreach (var lineShippingOption in lineItemShippingOptionList) { var jsonResult = CommerceTypeLoader.CreateInstance <LineShippingOptionBaseJsonResult>(); jsonResult.Initialize(lineShippingOption); lineShippingOptionList.Add(jsonResult); } this.LineShippingOptions = lineShippingOptionList; foreach (var line in this.Cart.Lines) { var lineShippingOption = lineItemShippingOptionList.FirstOrDefault(l => l.LineId.Equals(line.ExternalCartLineId, StringComparison.OrdinalIgnoreCase)); if (lineShippingOption != null) { line.SetShippingOptions(lineShippingOption.ShippingOptions); } } } }
/// <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> /// Gets the cache provider /// </summary> /// <returns>the cahce provider</returns> protected virtual ICacheProvider GetCacheProvider() { var cacheProvider = CommerceTypeLoader.GetCacheProvider(CommerceConstants.KnownCacheNames.CommerceCartCache); Assert.IsNotNull(cacheProvider, "Could not retrieve the cache provider '{0}'.", CommerceConstants.KnownCacheNames.CommerceCartCache); return(cacheProvider); }
private static ICacheProvider GetCacheProvider() { var cacheProvider = CommerceTypeLoader.GetCacheProvider(CommerceConstants.KnownCacheNames.CommerceCartCache); Assert.IsNotNull(cacheProvider, "cacheProvider"); return(cacheProvider); }
public SearchSettingsProvider(ICatalogContext catalogContext) { Assert.ArgumentNotNull(catalogContext, nameof(catalogContext)); this.catalogContext = catalogContext; this.commerceSearchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); Assert.ArgumentNotNull(this.commerceSearchManager, nameof(this.commerceSearchManager)); }
/// <summary> /// Gets the profile repository. /// </summary> /// <returns>An instance of the profile respository.</returns> protected virtual ICommerceProfileRepository GetProfileRepository() { if (this._profileRepository == null) { this._profileRepository = CommerceTypeLoader.CreateInstance <ICommerceProfileRepository>(); } return(this._profileRepository); }
/// <summary> /// Initializes the specified order headers. /// </summary> /// <param name="orderHeaders">The order headers.</param> public virtual void Initialize(IEnumerable <OrderHeader> orderHeaders) { Assert.ArgumentNotNull(orderHeaders, "orderHeaders"); foreach (var orderHeader in orderHeaders) { var headerItem = CommerceTypeLoader.CreateInstance <OrderHeaderItemBaseJsonResult>(orderHeader); this._orders.Add(headerItem); } }
/// <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)); }
/// <summary> /// Gets the product id from the incomming request /// </summary> /// <returns>The product id if found</returns> public virtual CatalogRouteData GetCatalogItemFromIncomingRequest() { var siteContext = CommerceTypeLoader.CreateInstance <ISiteContext>(); var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(siteContext.CurrentContext)); if (routeData != null) { var data = this.GetRouteDataValue(routeData); return(data); } return(null); }
/// <summary> /// Gets the child variants read only. /// </summary> /// <param name="itemId">The item identifier.</param> /// <param name="language">The language.</param> /// <returns>Product variant collection.</returns> private Category GetCategoryReadOnly(ID itemId, string language) { Category category = null; var catalogRepository = CommerceTypeLoader.CreateInstance <ICatalogRepository>(); var externalInfo = catalogRepository.GetExternalIdInformation(itemId.Guid); if (externalInfo != null && externalInfo.CommerceItemType == CommerceItemType.Category) { var culture = CommerceUtility.ConvertLanguageToCulture(language); category = catalogRepository.GetCategoryReadOnly(externalInfo.CatalogName, externalInfo.CategoryName, culture) as Category; } return(category); }
/// <summary> /// Gets the tags. /// </summary> /// <returns>The Html metadata tags if necessary.</returns> public static HtmlString GetTags() { var siteContext = CommerceTypeLoader.CreateInstance <ISiteContext>(); if (siteContext.IsCategory) { return(new HtmlString(GetCategoryTags(siteContext.CurrentCatalogItem))); } else if (siteContext.IsProduct) { return(new HtmlString(GetProductTags(siteContext.CurrentCatalogItem))); } return(new HtmlString(string.Empty)); }
/// <summary> /// Sets the shipping methods. /// </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 <AddShippingInfoResult, CommerceCart> SetShippingMethods([NotNull] CommerceStorefront storefront, [NotNull] VisitorContext visitorContext, [NotNull] SetShippingMethodsInputModel inputModel) { Assert.ArgumentNotNull(storefront, "storefront"); Assert.ArgumentNotNull(visitorContext, "visitorContext"); Assert.ArgumentNotNull(inputModel, "inputModel"); var result = new AddShippingInfoResult { Success = false }; var response = this.GetCurrentCart(storefront, visitorContext, true); if (!response.ServiceProviderResult.Success || response.Result == null) { return(new ManagerResponse <AddShippingInfoResult, CommerceCart>(result, response.Result)); } var cart = (CommerceCart)response.ServiceProviderResult.Cart; if (inputModel.ShippingAddresses != null && inputModel.ShippingAddresses.Any()) { var cartParties = cart.Parties.ToList(); cartParties.AddRange(inputModel.ShippingAddresses.ToParties()); cart.Parties = cartParties.AsReadOnly(); } var internalShippingList = inputModel.ShippingMethods.ToShippingInfoList(); var orderPreferenceType = InputModelExtension.GetShippingOptionType(inputModel.OrderShippingPreferenceType); if (orderPreferenceType != ShippingOptionType.DeliverItemsIndividually) { foreach (var shipping in internalShippingList) { shipping.LineIDs = (from CommerceCartLine lineItem in cart.Lines select lineItem.ExternalCartLineId).ToList().AsReadOnly(); } } var cartCache = CommerceTypeLoader.CreateInstance <CartCacheHelper>(); cartCache.InvalidateCartCache(visitorContext.GetCustomerId()); result = this.AddShippingInfoToCart(cart, orderPreferenceType, internalShippingList); if (result.Success && result.Cart != null) { cartCache.AddCartToCache(result.Cart as CommerceCart); } return(new ManagerResponse <AddShippingInfoResult, CommerceCart>(result, result.Cart as CommerceCart)); }
private IQueryable <CommerceSellableItemSearchResultItem> GetBaseQueryable(string catalogName, string searchItemType) { Assert.ArgumentNotNullOrEmpty(catalogName, nameof(catalogName)); Assert.ArgumentNotNullOrEmpty(searchItemType, nameof(searchItemType)); var commerceSearchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); using (var searchContext = commerceSearchManager.GetIndex(catalogName).CreateSearchContext()) { var searchResultItems = searchContext.GetQueryable <CommerceSellableItemSearchResultItem>() .Where(item => item.CommerceSearchItemType == searchItemType) .Where(item => item.Language == Context.Language.Name); return(searchResultItems); } }
/// <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> /// 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)); }
public static SearchResponse GetNavigationCategories(string navigationDataSource, CommerceSearchOptions searchOptions) { ID navigationId; var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchIndex = searchManager.GetIndex(); if (navigationDataSource.IsGuid()) { navigationId = ID.Parse(navigationDataSource); } else { using (var context = searchIndex.CreateSearchContext()) { var query = LinqHelper.CreateQuery <Sitecore.ContentSearch.SearchTypes.SitecoreUISearchResultItem>(context, SearchStringModel.ParseDatasourceString(navigationDataSource)) .Select(result => result.GetItem().ID); if (query != null & query.Any()) { navigationId = query.First(); } else { return(new SearchResponse()); } } } using (var context = searchIndex.CreateSearchContext()) { var searchResults = context.GetQueryable <CommerceBaseCatalogSearchResultItem>() .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category) .Where(item => item.Language == CurrentLanguageName) .Where(item => item.CommerceAncestorIds.Contains(navigationId)) .Select(p => new CommerceBaseCatalogSearchResultItem() { ItemId = p.ItemId, Uri = p.Uri }); searchResults = searchManager.AddSearchOptionsToQuery <CommerceBaseCatalogSearchResultItem>(searchResults, searchOptions); var results = searchResults.GetResults(); var response = SearchResponse.CreateFromSearchResultsItems(searchOptions, results); return(response); } }
/// <summary> /// Gets the child variants read only. /// </summary> /// <param name="itemId">The item identifier.</param> /// <param name="language">The language.</param> /// <returns>Product variant collection.</returns> private IEnumerable <Variant> GetChildVariantsReadOnly(ID itemId, string language) { var catalogRepository = CommerceTypeLoader.CreateInstance <ICatalogRepository>(); var externalInfo = catalogRepository.GetExternalIdInformation(itemId.Guid); if (externalInfo != null && externalInfo.CommerceItemType == CommerceItemType.ProductFamily) { var culture = CommerceUtility.ConvertLanguageToCulture(language); var productFamily = catalogRepository.GetProductReadOnly(externalInfo.CatalogName, externalInfo.ProductId, culture) as ProductFamily; if (productFamily != null && productFamily.Variants.Count > 0) { return(productFamily.Variants); } } return(new List <Variant>()); }
/// <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)); }
/// <summary> /// Determines whether this instance [can line item be emailed] the specified line item. /// </summary> /// <param name="lineItem">The line item.</param> /// <returns>True if the line item can be emailed; otherwise false.</returns> protected virtual bool CanLineItemBeEmailed(CommerceCartLine lineItem) { bool lineItemCanBeEmailed = true; var product = (CommerceCartProduct)lineItem.Product; var repository = CommerceTypeLoader.CreateInstance <ICatalogRepository>(); CSCatalog.Product commerceProduct = repository.GetProduct(product.ProductCatalog, product.ProductId); if (commerceProduct != null) { if (!commerceProduct.DefinitionName.Equals("GiftCard", StringComparison.OrdinalIgnoreCase)) { lineItemCanBeEmailed = false; } } return(lineItemCanBeEmailed); }
private IEnumerable <Sitecore.Data.Items.Item> GetChildCategories(ID categorySitecoreId) { var searchManager = CommerceTypeLoader.CreateInstance <ICommerceSearchManager>(); var searchIndex = searchManager.GetIndex(); // TODO: I replicated this from the SXA storefront code. // Seems a strange way to get the child categories to me. // Why not use ParentCategoryList to query in the index, need to investigate. using (var context = searchIndex.CreateSearchContext()) { var category = context.GetQueryable <CommerceCategorySearchResultItem>() .Where(x => x.ItemId == categorySitecoreId) .Where(x => x.Language == Sitecore.Context.Language.Name) .ToList(); if (category.Count() == 0) { return(null); } var childrenCategories = String.Empty; try { childrenCategories = category[0]["childrencategorylist"]; } catch (KeyNotFoundException) { Sitecore.Diagnostics.Log.Info($"No children categories found for {category[0].DisplayName}", this); } if (string.IsNullOrEmpty(childrenCategories)) { return(null); } var childrenCategoryIds = childrenCategories.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); return(childrenCategoryIds .Select(x => Sitecore.Context.Database.GetItem(new ID(x)))); } }