/// <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 = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); 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> /// Navigates the specified end response. /// </summary> /// <param name="endResponse">if set to <c>true</c> [end response].</param> private void NavigateInternal(bool endResponse) { string uri = this.ToString(); var siteContext = ContextTypeLoader.CreateInstance <ISiteContext>(); siteContext.CurrentContext.Response.Redirect(uri, endResponse); }
/// <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 Foundation.CommerceServer.Requests.GetSupportedCurrenciesRequest, "args.Request", "args.Request is RefSFArgs.GetSupportedCurrenciesRequest"); Assert.ArgumentCondition(args.Result is GetSupportedCurrenciesResult, "args.Result", "args.Result is GetSupportedCurrenciesResult"); var request = (Foundation.CommerceServer.Requests.GetSupportedCurrenciesRequest)args.Request; var result = (GetSupportedCurrenciesResult)args.Result; Assert.ArgumentNotNullOrEmpty(request.CatalogName, "request.CatalogName"); ICatalogRepository catalogRepository = ContextTypeLoader.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> /// 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 Search.SearchResponse GetCategoryProducts(ID categoryId, Search.Models.CommerceSearchOptions searchOptions) { var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); 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(searchResults, searchOptions.ConnectSearchOptions); var results = searchResults.GetResults(); var response = Search.SearchResponse.CreateFromSearchResultsItems(searchOptions, results); return(response); } }
/// <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 Search.SearchResponse SearchCatalogItemsByKeyword(string keyword, string catalogName, Search.Models.CommerceSearchOptions searchOptions) { Sitecore.Diagnostics.Assert.ArgumentNotNullOrEmpty(catalogName, "catalogName"); var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); 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(searchResults, searchOptions.ConnectSearchOptions); var results = searchResults.GetResults(); var response = Search.SearchResponse.CreateFromSearchResultsItems(searchOptions, results); return(response); } }
/// <summary> /// Gets the profile repository. /// </summary> /// <returns>An instance of the profile respository.</returns> protected virtual ICommerceProfileRepository GetProfileRepository() { if (this._profileRepository == null) { this._profileRepository = ContextTypeLoader.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 = ContextTypeLoader.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] 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)); }
/// <summary> /// Gets the product id from the incomming request /// </summary> /// <returns>The product id if found</returns> public virtual CatalogRouteData GetCatalogItemFromIncomingRequest() { var siteContext = ContextTypeLoader.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 = ContextTypeLoader.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 = ContextTypeLoader.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> /// Returns the navigation categories based on a root navigation ID identified by a Data Source string. /// </summary> /// <param name="navigationDataSource">A Sitecore Item ID or query that identifies the root navigation ID.</param> /// <param name="searchOptions">The paging options for this query.</param> /// <returns>A list of category items.</returns> /// TODO:remove unused public static Search.SearchResponse GetNavigationCategories(string navigationDataSource, Search.Models.CommerceSearchOptions searchOptions) { ID navigationId; var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); var searchIndex = searchManager.GetIndex(); if (navigationDataSource.IsGuid()) { navigationId = ID.Parse(navigationDataSource); } else { using (var context = searchIndex.CreateSearchContext()) { var query = LinqHelper.CreateQuery <SitecoreUISearchResultItem>(context, SearchStringModel.ParseDatasourceString(navigationDataSource)) .Select(result => result.GetItem().ID); if (query.Any()) { navigationId = query.First(); } else { return(new Search.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(searchResults, searchOptions.ConnectSearchOptions); var results = searchResults.GetResults(); var response = Search.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 = ContextTypeLoader.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> /// 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 = ContextTypeLoader.CreateInstance <ICatalogRepository>(); Product commerceProduct = repository.GetProduct(product.ProductCatalog, product.ProductId); if (commerceProduct != null) { if (!commerceProduct.DefinitionName.Equals("GiftCard", StringComparison.OrdinalIgnoreCase)) { lineItemCanBeEmailed = false; } } return(lineItemCanBeEmailed); }
/// <summary> /// Adds the party. /// </summary> /// <param name="party">The party.</param> /// <param name="entityName">Name of the entity.</param> /// <param name="cartContext">The cart context.</param> /// <returns> /// The commerce party that was added. /// </returns> protected virtual ConnectOrderModels.CommerceParty AddParty(Party party, string entityName, CartPipelineContext cartContext) { OrderAddress destinationAddress = ContextTypeLoader.CreateInstance <OrderAddress>(this.GetPartyName(party), party.ExternalId); TranslateEntityToOrderAddressRequest translateRequest = new TranslateEntityToOrderAddressRequest(party, destinationAddress); var translateResult = PipelineUtility.RunCommerceConnectPipeline <TranslateEntityToOrderAddressRequest, TranslateEntityToOrderAddressResult>(PipelineNames.TranslateEntityToOrderAddress, translateRequest); OrderAddress newOrderAddress = translateResult.Address; cartContext.Basket.Addresses.Add(newOrderAddress); ConnectOrderModels.CommerceParty translatedParty = this.EntityFactory.Create <ConnectOrderModels.CommerceParty>(entityName); Assert.ArgumentNotNull(translatedParty, "translatedParty"); TranslateOrderAddressToEntityRequest translateOrderAddressRequest = new TranslateOrderAddressToEntityRequest(newOrderAddress, translatedParty); PipelineUtility.RunCommerceConnectPipeline <TranslateOrderAddressToEntityRequest, CommerceResult>(PipelineNames.TranslateOrderAddressToEntity, translateOrderAddressRequest); return(translatedParty); }
/// <summary> /// Gets the product information from the index file. /// </summary> /// <param name="catalogName">Name of the catalog.</param> /// <param name="productIdList">The product identifier list.</param> /// <returns> /// The found product document instance; Otherwise null. /// </returns> protected virtual List <PriceSearchResultItem> GetProductsFromIndex(String catalogName, IEnumerable <string> productIdList) { var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); var searchIndex = searchManager.GetIndex(); var productPredicate = this.BuildProductIdListPredicate(productIdList); using (var context = searchIndex.CreateSearchContext()) { var searchResults = context.GetQueryable <PriceSearchResultItem>() .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product) .Where(item => item.CatalogName == catalogName) .Where(item => item.Language == Sitecore.Context.Language.Name) .Where(productPredicate) .Select(p => new PriceSearchResultItem { OtherFields = p.Fields, ListPrice = p.ListPrice, BasePrice = p.BasePrice, VariantInfo = p.VariantInfo, Name = p.Name }); return(searchResults.ToList()); } }
/// <summary> /// Executes a search in a bucket to retrieve catalog items. /// </summary> /// <param name="defaultBucketQuery">The search default bucket query value.</param> /// <param name="persistentBucketFilter">The search persistent bucket filter value.</param> /// <returns>A list of catalog items.</returns> /// TODO:remove unused public static Search.SearchResponse SearchBucketForCatalogItems(string defaultBucketQuery, string persistentBucketFilter) { var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); var searchIndex = searchManager.GetIndex(); var defaultQuery = defaultBucketQuery.Replace("&", ";"); var persistentQuery = persistentBucketFilter.Replace("&", ";"); var combinedQuery = CombineQueries(persistentQuery, defaultQuery); var searchStringModel = SearchStringModel.ParseDatasourceString(combinedQuery); using (var context = searchIndex.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck)) { var query = LinqHelper.CreateQuery <SitecoreUISearchResultItem>(context, searchStringModel) .Where(item => item.Language == SearchNavigation.CurrentLanguageName); var results = query.GetResults(); var response = Search.SearchResponse.CreateFromUISearchResultsItems(new Search.Models.CommerceSearchOptions(), results); return(response); } }
public SearchInfo GetSearchInfo( Item datasource, 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 = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); var searchInfo = new SearchInfo { SearchKeyword = searchKeyword ?? string.Empty, RequiredFacets = searchManager.GetFacetFieldsForItem(datasource), SortFields = searchManager.GetSortFieldsForItem(datasource), Catalog = StorefrontManager.CurrentStorefront.DefaultCatalog, ItemsPerPage = pageSize ?? searchManager.GetItemsPerPageForItem(datasource) }; if (searchInfo.ItemsPerPage == 0) { searchInfo.ItemsPerPage = StorefrontConstants.Settings.DefaultItemsPerPage; } var productSearchOptions = new CommerceSearchOptions(searchInfo.ItemsPerPage, pageNumber.GetValueOrDefault(0)); UpdateOptionsWithFacets(searchInfo.RequiredFacets, facetValues, productSearchOptions); UpdateOptionsWithSorting(sortField, sortDirection, productSearchOptions); searchInfo.SearchOptions = productSearchOptions; this.CurrentSiteContext.Items[CurrentSearchInfoKeyName] = searchInfo; return(searchInfo); }
/// <summary> /// Runs the processor. /// </summary> /// <param name="args">The args.</param> public virtual void Process(PipelineArgs args) { if (Context.Item != null) { return; } var routeData = this.GetCatalogItemFromIncomingRequest(); if (routeData != null) { var siteContext = ContextTypeLoader.CreateInstance <ISiteContext>(); Context.Item = ResolveCatalogItem(routeData.Id, routeData.Catalog, routeData.IsProduct); siteContext.CurrentCatalogItem = Context.Item; if (Context.Item == null) { WebUtil.Redirect("~/"); } } }
/// <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> /// <param name="productResolver"></param> public virtual void Initialize(Cart cart, IProductResolver productResolver) { this.Lines = new List <CartLineBaseJsonResult>(); this.Adjustments = new List <CartAdjustmentBaseJsonResult>(); this.PromoCodes = new List <string>(); var currencyCode = StorefrontManager.GetCustomerCurrency(); this.Subtotal = 0.0M.ToCurrency(currencyCode); this.TaxTotal = 0.0M.ToCurrency(currencyCode); this.Total = 0.0M.ToCurrency(currencyCode); this.TotalAmount = 0.0M; this.Discount = 0.0M.ToCurrency(currencyCode); this.ShippingTotal = 0.0M.ToCurrency(currencyCode); if (cart == null) { return; } foreach (var line in (cart.Lines ?? Enumerable.Empty <CartLine>())) { var cartLine = ContextTypeLoader.CreateInstance <CartLineBaseJsonResult>(line, productResolver); 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(currencyCode); this.TaxTotal = cart.Total.TaxTotal.Amount.ToCurrency(currencyCode); this.Total = cart.Total.Amount.ToCurrency(currencyCode); this.TotalAmount = cart.Total.Amount; this.Discount = commerceTotal.OrderLevelDiscountAmount.ToCurrency(currencyCode); this.ShippingTotal = commerceTotal.ShippingTotal.ToCurrency(currencyCode); }
/// <summary> /// Gets all the products under a specific category /// </summary> /// <param name="categoryId">The parent category id</param> /// <param name="searchOptions">The paging options for this query</param> /// <returns>A list of child products</returns> public static CategorySearchResults GetCategoryChildCategories(ID categoryId, Search.Models.CommerceSearchOptions searchOptions) { var childCategoryList = new List <Item>(); var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); var searchIndex = searchManager.GetIndex(); using (var context = searchIndex.CreateSearchContext()) { var searchResults = context.GetQueryable <CommerceBaseCatalogSearchResultItem>() .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Category) .Where(item => item.Language == CurrentLanguageName) .Where(item => item.ItemId == categoryId) .Select(p => p); var list = searchResults.ToList(); if (list.Count > 0) { if (list[0].Fields.ContainsKey(StorefrontConstants.KnownIndexFields.ChildCategoriesSequence)) { var childCategoryDelimitedString = list[0][StorefrontConstants.KnownIndexFields.ChildCategoriesSequence]; string[] categoryIdArray = childCategoryDelimitedString.Split('|'); foreach (var childCategoryId in categoryIdArray) { var childCategoryItem = Sitecore.Context.Database.GetItem(ID.Parse(childCategoryId)); if (childCategoryItem != null) { childCategoryList.Add(childCategoryItem); } } } } } return(new CategorySearchResults(childCategoryList, childCategoryList.Count, 1, 1, new List <FacetCategory>())); }
/// <summary> /// Adds the user profile address. /// </summary> /// <param name="party">The party.</param> /// <param name="cartContext">The cart context.</param> /// <returns>The commerce party that was added.</returns> protected virtual ConnectOrderModels.CommerceParty AddUserProfileAddress(ConnectOrderModels.CommerceParty party, CartPipelineContext cartContext) { Assert.IsTrue(party.UserProfileAddressId != Guid.Empty, "party.UserProfileAddressId != Guid.Empty"); Assert.IsNotNullOrEmpty(party.Name, "party.Name"); var repository = this.GetProfileRepository(); Profile addressProfile = repository.GetProfile("Address", party.UserProfileAddressId.ToString("B")); Assert.IsNotNull(addressProfile, string.Format(CultureInfo.InvariantCulture, "An invalid address profile was provided: {0}", party.UserProfileAddressId.ToString("B"))); OrderAddress newOrderAddress = ContextTypeLoader.CreateInstance <OrderAddress>(party.Name, addressProfile); cartContext.Basket.Addresses.Add(newOrderAddress); ConnectOrderModels.CommerceParty translatedParty = this.EntityFactory.Create <ConnectOrderModels.CommerceParty>("Party"); Assert.ArgumentNotNull(translatedParty, "translatedParty"); var translateOrderAddressRequest = new TranslateOrderAddressToEntityRequest(newOrderAddress, translatedParty); PipelineUtility.RunCommerceConnectPipeline <TranslateOrderAddressToEntityRequest, CommerceResult>(PipelineNames.TranslateOrderAddressToEntity, translateOrderAddressRequest); return(translatedParty); }
public CatalogSearchManager() { _connectSearchManager = ContextTypeLoader.CreateInstance <ICommerceSearchManager>(); }
/// <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 GetProductBulkPricesRequest, "args.Request", "args.Request is GetProductBulkPricesRequest"); Assert.ArgumentCondition(args.Result is Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult, "args.Result", "args.Result is GetProductBulkPricesResult"); GetProductBulkPricesRequest request = (GetProductBulkPricesRequest)args.Request; Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult result = (Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult)args.Result; Assert.ArgumentNotNull(request.ProductCatalogName, "request.ProductCatalogName"); Assert.ArgumentNotNull(request.ProductIds, "request.ProductIds"); Assert.ArgumentNotNull(request.PriceType, "request.PriceType"); ICatalogRepository catalogRepository = ContextTypeLoader.CreateInstance <ICatalogRepository>(); bool isList = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.List, StringComparison.OrdinalIgnoreCase)) != null; bool isAdjusted = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.Adjusted, StringComparison.OrdinalIgnoreCase)) != null; bool isLowestPriceVariantSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.LowestPricedVariant, StringComparison.OrdinalIgnoreCase)) != null; bool isLowestPriceVariantListPriceSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.LowestPricedVariantListPrice, StringComparison.OrdinalIgnoreCase)) != null; bool isHighestPriceVariantSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.HighestPricedVariant, StringComparison.OrdinalIgnoreCase)) != null; var uniqueIds = request.ProductIds.ToList().Distinct(); foreach (var requestedProductId in uniqueIds) { try { var product = catalogRepository.GetProductReadOnly(request.ProductCatalogName, requestedProductId); ExtendedCommercePrice extendedPrice = this.EntityFactory.Create <ExtendedCommercePrice>("Price"); // BasePrice is a List price and ListPrice is Adjusted price if (isList) { if (product.HasProperty("BasePrice") && product["BasePrice"] != null) { extendedPrice.Amount = (product["BasePrice"] as decimal?).Value; } else { // No base price is defined, the List price is set to the actual ListPrice define in the catalog extendedPrice.Amount = product.ListPrice; } } if (isAdjusted && !product.IsListPriceNull()) { extendedPrice.ListPrice = product.ListPrice; } if ((isLowestPriceVariantSpecified || isLowestPriceVariantListPriceSpecified || isHighestPriceVariantSpecified) && product is ProductFamily) { this.SetVariantPrices(product as ProductFamily, extendedPrice, isLowestPriceVariantSpecified, isLowestPriceVariantListPriceSpecified, isHighestPriceVariantSpecified); } result.Prices.Add(requestedProductId, extendedPrice); } catch (EntityDoesNotExistException e) { result.Success = false; result.SystemMessages.Add(new SystemMessage { Message = e.Message }); continue; } } }
/// <summary> /// Gets the index of the product stock status from. /// </summary> /// <param name="viewModelList">The view model list.</param> public static void GetProductStockStatusFromIndex(List <ProductViewModel> viewModelList) { if (viewModelList == null || viewModelList.Count == 0) { return; } var searchManager = ContextTypeLoader.CreateInstance <ICatalogSearchManager>(); var searchIndex = searchManager.GetIndex(); using (var context = searchIndex.CreateSearchContext()) { var predicate = PredicateBuilder.Create <InventorySearchResultItem>(item => item[StorefrontConstants.KnownIndexFields.InStockLocations].Contains("Default")); predicate = predicate.Or(item => item[StorefrontConstants.KnownIndexFields.OutOfStockLocations].Contains("Default")); predicate = predicate.Or(item => item[StorefrontConstants.KnownIndexFields.OrderableLocations].Contains("Default")); predicate = predicate.Or(item => item[StorefrontConstants.KnownIndexFields.PreOrderable].Contains("0")); var searchResults = context.GetQueryable <InventorySearchResultItem>() .Where(item => item.CommerceSearchItemType == CommerceSearchResultItemType.Product) .Where(item => item.Language == SearchNavigation.CurrentLanguageName) .Where(BuildProductIdListPredicate(viewModelList)) .Where(predicate) .Select(x => new { x.OutOfStockLocations, x.OrderableLocations, x.PreOrderable, x.InStockLocations, x.Fields, x.Name }); var results = searchResults.GetResults(); if (results.TotalSearchResults == 0) { return; } foreach (var result in results) { var resultDocument = result.Document; if (resultDocument == null) { continue; } StockStatus status; var isInStock = resultDocument.Fields.ContainsKey(StorefrontConstants.KnownIndexFields.InStockLocations) && resultDocument.Fields[StorefrontConstants.KnownIndexFields.InStockLocations] != null; if (isInStock) { status = StockStatus.InStock; } else { var isPreOrderable = resultDocument.Fields.ContainsKey(StorefrontConstants.KnownIndexFields.PreOrderable) && result.Document.PreOrderable != null && (result.Document.PreOrderable.Equals("1", StringComparison.OrdinalIgnoreCase) || result.Document.PreOrderable.Equals("true", StringComparison.OrdinalIgnoreCase)); if (isPreOrderable) { status = StockStatus.PreOrderable; } else { var isOutOfStock = resultDocument.Fields.ContainsKey(StorefrontConstants.KnownIndexFields.OutOfStockLocations) && result.Document.OutOfStockLocations != null; var isBackOrderable = resultDocument.Fields.ContainsKey(StorefrontConstants.KnownIndexFields.OrderableLocations) && result.Document.OrderableLocations != null; if (isOutOfStock && isBackOrderable) { status = StockStatus.BackOrderable; } else { status = isOutOfStock ? StockStatus.OutOfStock : null; } } } var foundModel = viewModelList.Find(x => x.ProductId == result.Document.Name); if (foundModel != null) { foundModel.StockStatus = status; foundModel.StockStatusName = StorefrontManager.GetProductStockStatusName(foundModel.StockStatus); } } } }
public CartCacheService() { _cartCacheHelper = ContextTypeLoader.CreateInstance <CartCacheHelper>(); }
/// <summary> /// returns a QueryStringCollection object based on the current querystring of the request /// </summary> /// <returns>the QueryStringCollection object </returns> public QueryStringCollection FromCurrent() { var siteContext = ContextTypeLoader.CreateInstance <ISiteContext>(); return(new QueryStringCollection(siteContext.CurrentContext.Request.Url.ToString())); }
/// <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 GetProductPricesRequest, "args.Request", "args.Request is GetProductPricesRequest"); Assert.ArgumentCondition(args.Result is Sitecore.Commerce.Services.Prices.GetProductPricesResult, "args.Result", "args.Result is GetProductPricesResult"); GetProductPricesRequest request = (GetProductPricesRequest)args.Request; Sitecore.Commerce.Services.Prices.GetProductPricesResult result = (Sitecore.Commerce.Services.Prices.GetProductPricesResult)args.Result; Assert.ArgumentNotNull(request.ProductCatalogName, "request.ProductCatalogName"); Assert.ArgumentNotNull(request.ProductId, "request.ProductId"); Assert.ArgumentNotNull(request.PriceTypeIds, "request.PriceTypeIds"); ICatalogRepository catalogRepository = ContextTypeLoader.CreateInstance <ICatalogRepository>(); bool isList = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.List, StringComparison.OrdinalIgnoreCase)) != null; bool isAdjusted = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.Adjusted, StringComparison.OrdinalIgnoreCase)) != null; try { var product = catalogRepository.GetProductReadOnly(request.ProductCatalogName, request.ProductId); ExtendedCommercePrice extendedPrice = this.EntityFactory.Create <ExtendedCommercePrice>("Price"); // BasePrice is a List price and ListPrice is Adjusted price if (isList) { if (product.HasProperty("BasePrice") && product["BasePrice"] != null) { extendedPrice.Amount = (product["BasePrice"] as decimal?).Value; } else { // No base price is defined, the List price is set to the actual ListPrice define in the catalog extendedPrice.Amount = product.ListPrice; } } if (isAdjusted && !product.IsListPriceNull()) { extendedPrice.ListPrice = product.ListPrice; } result.Prices.Add(request.ProductId, extendedPrice); if (request.IncludeVariantPrices && product is ProductFamily) { foreach (Variant variant in ((ProductFamily)product).Variants) { ExtendedCommercePrice variantExtendedPrice = this.EntityFactory.Create <ExtendedCommercePrice>("Price"); bool hasBasePrice = product.HasProperty("BasePrice"); if (hasBasePrice && variant["BasePriceVariant"] != null) { variantExtendedPrice.Amount = (variant["BasePriceVariant"] as decimal?).Value; } if (!variant.IsListPriceNull()) { variantExtendedPrice.ListPrice = variant.ListPrice; if (!hasBasePrice) { variantExtendedPrice.Amount = variant.ListPrice; } } result.Prices.Add(variant.VariantId.Trim(), variantExtendedPrice); } } } catch (EntityDoesNotExistException e) { result.Success = false; result.SystemMessages.Add(new SystemMessage { Message = e.Message }); } }
/// <summary> /// This method returns the Route data value /// </summary> /// <param name="routeData">The route</param> /// <returns>The value if found, empty string if route is found but not value, null if route invalid</returns> public virtual CatalogRouteData GetRouteDataValue(RouteData routeData) { var data = new CatalogRouteData(); if (routeData.Values.ContainsKey(ItemTypeField)) { if (routeData.Values[ItemTypeField].ToString() == CatalogItemType) { var currentStorefront = StorefrontManager.CurrentStorefront; Item productCatalogItem = currentStorefront.HomeItem.Axes.GetDescendant(NavigationItemName + "/" + routeData.Values["pathElements"].ToString()); if (productCatalogItem != null) { data.IsProduct = (productCatalogItem.ItemType() == StorefrontConstants.ItemTypes.Product); data.Id = productCatalogItem.Name; } } else { data.IsProduct = routeData.Values[ItemTypeField].ToString() == ProductItemType ? true : false; } } else { return(null); } if (routeData.Values.ContainsKey(IdField)) { data.Id = CatalogUrlManager.ExtractItemId(routeData.Values[IdField].ToString()); } else { if (string.IsNullOrWhiteSpace(data.Id)) { return(null); } } if (routeData.Values.ContainsKey(CatalogField)) { data.Catalog = routeData.Values[CatalogField].ToString(); } if (string.IsNullOrEmpty(data.Catalog)) { var defaultCatalog = StorefrontManager.CurrentStorefront.DefaultCatalog; if (defaultCatalog != null) { data.Catalog = defaultCatalog.Name; } } if (routeData.Values.ContainsKey(CategoryField)) { var siteContext = ContextTypeLoader.CreateInstance <ISiteContext>(); siteContext.UrlContainsCategory = true; } return(data); }