public async Task <ProductSearchResult> SearchProducts([FromQuery] ProductSearchCriteria criteria)
 {
     return(await _productQueryService.SearchAsync(criteria));
 }
        protected virtual IList <KeyValuePair <string, IFilter> > GetRemovableFilters(ProductSearchCriteria criteria, IList <IFilter> permanentFilters)
        {
            var result = new List <KeyValuePair <string, IFilter> >();

            var terms = criteria.GetTerms();

            if (terms.Any())
            {
                var browseFilters = GetBrowseFilters(criteria);

                var filtersAndValues = browseFilters
                                       ?.Select(x => new { Filter = x, Values = x.GetValues() })
                                       .ToList();

                foreach (var term in terms)
                {
                    var browseFilter = browseFilters?.SingleOrDefault(x => x.Key.EqualsInvariant(term.Key));

                    // Handle special filter term with a key = "tags", it contains just values and we need to determine which filter to use
                    if (browseFilter == null && term.Key == "tags")
                    {
                        foreach (var termValue in term.Values)
                        {
                            // Try to find filter by value
                            var filterAndValues = filtersAndValues?.FirstOrDefault(x => x.Values.Any(y => y.Id.Equals(termValue)));
                            if (filterAndValues != null)
                            {
                                var filter = ConvertBrowseFilter(filterAndValues.Filter, term.Values, criteria);
                                permanentFilters.Add(filter);
                            }
                            else
                            {
                                // Unknown term values should produce empty result
                                permanentFilters.Add(new IdsFilter {
                                    Values = new[] { string.Empty }
                                });
                            }
                        }
                    }
                    else if (browseFilter != null) // Predefined filter
                    {
                        var filter = ConvertBrowseFilter(browseFilter, term.Values, criteria);
                        result.Add(new KeyValuePair <string, IFilter>(browseFilter.Key, filter));
                    }
                    else // Custom term
                    {
                        var filter = FiltersHelper.CreateTermFilter(term.Key, term.Values);
                        permanentFilters.Add(filter);
                    }
                }
            }

            return(result);
        }
        protected virtual IFilter ConvertPriceRangeFilter(PriceRangeFilter priceRangeFilter, IList <string> valueIds, ProductSearchCriteria criteria)
        {
            IFilter result = null;

            if (string.IsNullOrEmpty(criteria.Currency) || priceRangeFilter.Currency.EqualsInvariant(criteria.Currency))
            {
                var knownValues = priceRangeFilter.Values
                                  ?.Where(v => valueIds.Contains(v.Id, StringComparer.OrdinalIgnoreCase))
                                  .ToArray();

                if (knownValues != null && knownValues.Any())
                {
                    var filters = knownValues
                                  .Select(v => FiltersHelper.CreatePriceRangeFilter(priceRangeFilter.Currency, criteria.Pricelists, v.Lower, v.Upper, v.IncludeLower, v.IncludeUpper))
                                  .Where(f => f != null)
                                  .ToList();

                    result = filters.Or();
                }
                else
                {
                    // Unknown term values should produce empty result
                    result = new IdsFilter {
                        Values = new[] { string.Empty }
                    };
                }
            }

            return(result);
        }
Exemple #4
0
        private void BuildGoogleFeed()
        {
            //
            // the majority of the code to follow is based upon the excellent blog below:
            // http://blog.codenamed.nl/2015/05/14/creating-a-google-shopping-feed-with-c/
            //

            // get an instance of the store application
            var HccApp = HotcakesApplication.Current;

            var totalProducts = 0;
            var feed          = new FeedInfo();

            // get the store URL based upon SSL
            var storeUrl = Request.IsSecureConnection ? HccApp.CurrentStore.RootUrlSecure() : HccApp.CurrentStore.RootUrl();
            // used to get currency code
            var regionInfo = new RegionInfo(System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);

            feed.Link    = storeUrl;
            feed.Title   = HccApp.CurrentStore.StoreName;
            feed.Updated = DateTime.Now;
            feed.Entries = new List <EntryInfo>();

            // find all products in the store that are active
            var searchCriteria = new ProductSearchCriteria
            {
                DisplayInactiveProducts = false
            };

            // using the search instead of querying the Products directly to use cache
            var products = HccApp.CatalogServices.Products.FindByCriteria(searchCriteria, 1, int.MaxValue, ref totalProducts);

            // non-shipping
            var shippingInfo = new ShippingInfo {
                Price = Constants.HARDCODED_PRICE_ZERO
            };
            // not taxable (e.g., software)
            var taxInfo = new TaxInfo {
                Rate = Constants.HARDCODED_PRICE_ZERO
            };

            // iterate through each product and add it to the feed
            foreach (var product in products)
            {
                var productUrl = UrlRewriter.BuildUrlForProduct(product);

                var productEntry = new EntryInfo
                {
                    Availablity           = GetStockMessage(product),            // OPTIONS: preorder, in stock, out of stock
                    Condition             = Constants.CONDITION_NEW,             // OPTIONS: new, refurbished, used
                    Description           = product.LongDescription,
                    GoogleProductCategory = Constants.HARDCODED_GOOGLE_CATEGORY, // hard-coded for this example project (see property attributes)
                    Id          = product.Sku,
                    ImageLink   = DiskStorage.ProductImageUrlMedium(HccApp, product.Bvin, product.ImageFileMedium, Request.IsSecureConnection),
                    Link        = productUrl,
                    MobileLink  = productUrl,
                    Price       = string.Format(Constants.CURRENCY_TEXT_FORMAT, product.SitePrice.ToString(Constants.CURRENCY_FORMAT), regionInfo.ISOCurrencySymbol),
                    ProductType = GetFirstAvailableCategory(HccApp, product.Bvin), // put your preferred site category here
                    Title       = product.ProductName,
                    MPN         = product.Sku,                                     // this should be replaced with real data
                    Brand       = product.VendorId,                                // this should be replaced with real data
                    Color       = string.Empty,
                    Gender      = Constants.GENDER_UNISEX,                         // OPTIONS: male, female, unisex
                    AgeGroup    = Constants.AGE_GROUP_ADULT,                       // OPTIONS: newborn, infant, toddler, kids, adult
                    GTIN        = GenerateGTIN()                                   // this should be replaced with real data
                };

                // this could and should be iterated on to show shipping options for up to 100 locations
                productEntry.Shipping = new List <ShippingInfo>();
                productEntry.Shipping.Add(shippingInfo);

                // this could and should be iterated on to show taxes for up to 100 locations
                productEntry.Tax = new List <TaxInfo>();
                productEntry.Tax.Add(taxInfo);

                feed.Entries.Add(productEntry);
            }

            // simply done to display the feed in the textbox
            // alternatives could be to send this through a web service or other means
            txtGoogleFeed.Text = feed.SerializeObject();
        }
Exemple #5
0
        /// <summary>
        /// Async search products by given criteria
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public virtual async Task <CatalogSearchResult> SearchProductsAsync(ProductSearchCriteria criteria)
        {
            var workContext = _workContextAccessor.WorkContext;

            return(await InnerSearchProductsAsync(criteria, workContext));
        }
 public static searchDto.ProductSearch ToProductSearchDto(this ProductSearchCriteria criteria, WorkContext workContext)
 {
     return(CatalogConverterInstance.ToProductSearchDto(criteria, workContext));
 }
        static void Main(string[] args)
        {
            // CreateOrderTest();

            ContextFactory contextFactory = new ContextFactory();
            ShopContext    context        = contextFactory.CreateDbContext(args);

            context.Database.Migrate();

            if (!context.Products.Any())
            {
                CreateSampleData(context);
            }

            for (int i = 2; i < 10; i++)
            {
                CreateOrder(context, $"ZA {i}");
            }


            var updateproducts = context.Products.OrderBy(p => p.Id).Take(10).ToList();

            context.Products.RemoveRange(updateproducts);
            context.SaveChanges();

            var product = context.Products.First();

            Console.WriteLine(context.Entry(product).State);

            product.UnitPrice = 400.00m;
            product.Color     = "red";

            Console.WriteLine(context.Entry(product).State);

            product.UnitPrice = 300.00m;

            Console.WriteLine(context.Entry(product).State);

            Console.WriteLine(context.Entry(product).Property(p => p.UnitPrice).OriginalValue);

            context.SaveChanges();

            Console.WriteLine(context.Entry(product).State);


            //  context.Products.Remove(product);
            Console.WriteLine(context.Entry(product).State);

            context.Entry(product).State = EntityState.Unchanged;

            context.SaveChanges();


            IProductsService productsService = new DbProductsService(context);

            productsService.Remove(20);

            ProductSearchCriteria searchCriteria = new ProductSearchCriteria
            {
            };

            var colorProducts = productsService.Get(searchCriteria);

            if (colorProducts.Any())
            {
            }

            //  context.Database.EnsureDeleted();
            // context.Database.EnsureCreated();

            context.Database.Migrate();

            var customers = context.Customers.ToList();

            var products = context.Products
                           .Where(p => p.UnitPrice > 100)
                           .Where(p => p.Name.StartsWith("N"))
                           .OrderBy(p => p.Name)
                           .ThenBy(p => p.Color)
                           .Select(p => new { p.Name, p.Color })
                           .ToList();


            var productsByColor = context.Products
                                  .GroupBy(p => p.Color)
                                  .ToList();

            var productsQtyByColor = context.Products
                                     .GroupBy(p => p.Color)
                                     .Select(g => new { Color = g.Key, Qty = g.Count() })
                                     .ToList();

            //var productsOver100 = new List<Product>();

            //foreach (var product in context.Products)
            //{
            //    if (product.UnitPrice > 100)
            //    {
            //        productsOver100.Add(product);
            //    }
            //}



            // string customers = configuration["Generator:Customers"];

            // Generowanie danych
            // CreateSampleData(context);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();

            var tuple = GetTuple2();
        }
        protected virtual async Task HandleNonAssetRequest(IOwinContext context, WorkContext workContext)
        {
            await InitializeShoppingCart(context, workContext);

            if (workContext.CurrentStore.QuotesEnabled)
            {
                var quoteRequestBuilder = Container.Resolve <IQuoteRequestBuilder>();
                await quoteRequestBuilder.GetOrCreateNewTransientQuoteRequestAsync(workContext.CurrentStore, workContext.CurrentCustomer, workContext.CurrentLanguage, workContext.CurrentCurrency);

                workContext.CurrentQuoteRequest = quoteRequestBuilder.QuoteRequest;
            }

            var linkListService = Container.Resolve <IMenuLinkListService>();
            var linkLists       = await CacheManager.GetAsync("GetAllStoreLinkLists-" + workContext.CurrentStore.Id, "ApiRegion", async() => await linkListService.LoadAllStoreLinkListsAsync(workContext.CurrentStore.Id));

            workContext.CurrentLinkLists = linkLists.GroupBy(x => x.Name).Select(x => x.FindWithLanguage(workContext.CurrentLanguage)).Where(x => x != null).ToList();

            // load all static content
            var staticContents = CacheManager.Get(string.Join(":", "AllStoreStaticContent", workContext.CurrentStore.Id), "ContentRegion", () =>
            {
                var staticContentService = Container.Resolve <IStaticContentService>();
                var allContentItems      = staticContentService.LoadStoreStaticContent(workContext.CurrentStore).ToList();
                var blogs             = allContentItems.OfType <Blog>().ToArray();
                var blogArticlesGroup = allContentItems.OfType <BlogArticle>().GroupBy(x => x.BlogName, x => x).ToList();

                foreach (var blog in blogs)
                {
                    var blogArticles = blogArticlesGroup.FirstOrDefault(x => string.Equals(x.Key, blog.Name, StringComparison.OrdinalIgnoreCase));
                    if (blogArticles != null)
                    {
                        blog.Articles = new MutablePagedList <BlogArticle>(blogArticles);
                    }
                }

                return(new { Pages = allContentItems, Blogs = blogs });
            });

            workContext.Pages = new MutablePagedList <ContentItem>(staticContents.Pages.Where(x => x.Language.IsInvariant || x.Language == workContext.CurrentLanguage));
            workContext.Blogs = new MutablePagedList <Blog>(staticContents.Blogs.Where(x => x.Language.IsInvariant || x.Language == workContext.CurrentLanguage));

            // Initialize blogs search criteria
            workContext.CurrentBlogSearchCritera = new BlogSearchCriteria(workContext.QueryString);

            //Pricelists
            var pricelistCacheKey = string.Join("-", "EvaluatePriceLists", workContext.CurrentStore.Id, workContext.CurrentCustomer.Id);

            workContext.CurrentPricelists = await CacheManager.GetAsync(pricelistCacheKey, "ApiRegion", async() =>
            {
                var evalContext      = workContext.ToPriceEvaluationContextDto();
                var pricingModuleApi = Container.Resolve <IPricingModuleApiClient>();
                var pricingResult    = await pricingModuleApi.PricingModule.EvaluatePriceListsAsync(evalContext);
                return(pricingResult.Select(p => p.ToPricelist(workContext.AllCurrencies, workContext.CurrentLanguage)).ToList());
            });

            // Vendors with their products
            workContext.Vendors = new MutablePagedList <Vendor>((pageNumber, pageSize, sortInfos) =>
            {
                var catalogSearchService = Container.Resolve <ICatalogSearchService>();
                var customerService      = Container.Resolve <ICustomerService>();
                var vendors = customerService.SearchVendors(null, pageNumber, pageSize, sortInfos);

                foreach (var vendor in vendors)
                {
                    vendor.Products = new MutablePagedList <Product>((pageNumber2, pageSize2, sortInfos2) =>
                    {
                        var criteria = new ProductSearchCriteria
                        {
                            VendorId      = vendor.Id,
                            PageNumber    = pageNumber2,
                            PageSize      = pageSize2,
                            ResponseGroup = workContext.CurrentProductSearchCriteria.ResponseGroup & ~ItemResponseGroup.ItemWithVendor,
                            SortBy        = SortInfo.ToString(sortInfos2),
                        };
                        var searchResult = catalogSearchService.SearchProducts(criteria);
                        return(searchResult.Products);
                    }, 1, ProductSearchCriteria.DefaultPageSize);
                }

                return(vendors);
            }, 1, VendorSearchCriteria.DefaultPageSize);
        }
            /// <summary>
            /// Return View with optional search criteria added.
            /// </summary>
            /// <param name="categoryId">Required: Category id to show products for.</param>
            /// <param name="filterBrands">List of brands to show (comma separated).</param>
            /// <param name="filterCategories">List of categories to show (comma separated).</param>
            /// <returns>View of Products.</returns>
            public async Task <ActionResult> Index(string categoryId = "", string[] filterBrands = null, string[] filterCategories = null)
            {
                EcommerceContext         ecommerceContext         = ServiceUtilities.GetEcommerceContext(this.HttpContext);
                OrgUnitOperationsHandler orgUnitOperationsHandler = new OrgUnitOperationsHandler(ecommerceContext);

                PagedResult <Category> categories = await orgUnitOperationsHandler.GetNavigationalHierarchyCategories(Utilities.DefaultQuerySettings);

                IEnumerable <long> rawCategoryIds = categories.Select(c => c.RecordId);

                // determine what category to load products for, if null, load all products
                ObservableCollection <long> categoryIds;

                if (string.IsNullOrEmpty(categoryId))
                {
                    categoryIds = new ObservableCollection <long>(rawCategoryIds);
                }
                else
                {
                    categoryIds = new ObservableCollection <long>();
                    categoryIds.Add(long.Parse(categoryId));
                }

                // Category Id to Name Mapping
                Dictionary <long, string> mapping = new Dictionary <long, string>();

                foreach (Category category in categories)
                {
                    mapping.Add(category.RecordId, category.Name);
                }

                // Retrieving Products - make sure we include products from descendant categories too
                ProductSearchCriteria searchCriteria = new ProductSearchCriteria
                {
                    DataLevelValue = 4,
                    CategoryIds    = categoryIds,
                    IncludeProductsFromDescendantCategories = true
                };

                // try and get product information
                ProductOperationsHandler productOperationsHandler = new ProductOperationsHandler(ecommerceContext);

                PagedResult <ProductCatalog> productCatalogs = await productOperationsHandler.GetProductCatalogs(Utilities.DefaultQuerySettings);

                IEnumerable <long> activeCatalogIds = productCatalogs.Results.Select(pc => pc.RecordId);

                PagedResult <Product> products = await productOperationsHandler.SearchProducts(searchCriteria, activeCatalogIds, Utilities.DefaultQuerySettings);

                // Breadcrumb Navigation Links
                Collection <CustomLink> breadcrumbNavLinks = new Collection <CustomLink>();
                Category currentCategory = this.GetCategoryById(long.Parse(categoryId), categories);

                while (!currentCategory.ParentCategory.Equals((long?)0))
                {
                    breadcrumbNavLinks.Add(new CustomLink("/ProductGallery?categoryId=" + currentCategory.RecordId, currentCategory.Name));
                    currentCategory = this.GetCategoryById(currentCategory.ParentCategory, categories);
                }

                breadcrumbNavLinks.Add(new CustomLink("/", "Home"));

                // Filter Mapping
                Dictionary <string, string[]> filters = new Dictionary <string, string[]>();

                filters.Add("brand", filterBrands);
                filters.Add("categories", filterCategories);

                IEnumerable <Product> productList = await ProductDetailsController.PopulateViewSpecificProductInfo(products.Results, ecommerceContext);

                // create a new product gallery model for the view
                ProductGalleryModel productGalleryModel = new ProductGalleryModel(long.Parse(categoryId), productList, breadcrumbNavLinks, mapping, filters);

                return(this.View(ProductGalleryController.ProductGalleryViewName, productGalleryModel));
            }
Exemple #10
0
        protected virtual IList <SortingField> GetSorting(ProductSearchCriteria criteria)
        {
            var result = new List <SortingField>();
            //For sorting by relevance have to keep sortInfo clear
            var needClearSortInfo = false;

            var priorityFields = criteria.GetPriorityFields();

            foreach (SortInfo sortInfo in criteria.SortInfos)
            {
                var sortingField = new SortingField();
                if (sortInfo is GeoSortInfo geoSortInfo)
                {
                    sortingField = new GeoDistanceSortingField
                    {
                        Location = geoSortInfo.GeoPoint
                    };
                }
                sortingField.FieldName    = sortInfo.SortColumn.ToLowerInvariant();
                sortingField.IsDescending = sortInfo.SortDirection == SortDirection.Descending;

                switch (sortingField.FieldName)
                {
                case "relevance":
                    needClearSortInfo = true;
                    break;

                case "price":
                    if (criteria.Pricelists != null)
                    {
                        result.AddRange(
                            criteria.Pricelists.Select(priceList => new SortingField($"price_{criteria.Currency}_{priceList}".ToLowerInvariant(), sortingField.IsDescending)));
                    }
                    break;

                case "priority":
                    result.AddRange(priorityFields.Select(priorityField => new SortingField(priorityField, sortingField.IsDescending)));
                    break;

                case "name":
                case "title":
                    result.Add(new SortingField("name", sortingField.IsDescending));
                    break;

                default:
                    result.Add(sortingField);
                    break;
                }
            }

            if (!result.Any())
            {
                result.AddRange(priorityFields.Select(priorityField => new SortingField(priorityField, true)));
                result.Add(new SortingField("__sort"));
            }

            if (needClearSortInfo)
            {
                result.Clear();
            }

            return(result);
        }
        protected virtual async Task HandleStorefrontRequest(IOwinContext context)
        {
            var workContext = Container.Resolve <WorkContext>();

            // Initialize common properties
            var qs = HttpUtility.ParseQueryString(context.Request.Uri.Query);

            workContext.RequestUrl   = context.Request.Uri;
            workContext.QueryString  = qs;
            workContext.AllCountries = AllCountries;
            workContext.AllStores    = await CacheManager.GetAsync("GetAllStores", "ApiRegion", async() => await GetAllStoresAsync(), cacheNullValue : false);

            if (workContext.AllStores != null && workContext.AllStores.Any())
            {
                // Initialize request specific properties
                workContext.CurrentStore    = GetStore(context, workContext.AllStores);
                workContext.CurrentLanguage = GetLanguage(context, workContext.AllStores, workContext.CurrentStore);

                if (!IsStaticAssetRequest(context.Request))
                {
                    var commerceApi = Container.Resolve <ICoreModuleApiClient>();
                    workContext.AllCurrencies = await CacheManager.GetAsync("GetAllCurrencies-" + workContext.CurrentLanguage.CultureName, "ApiRegion", async() => { return((await commerceApi.Commerce.GetAllCurrenciesAsync()).Select(x => x.ToCurrency(workContext.CurrentLanguage)).ToArray()); });

                    //Sync store currencies with avail in system
                    foreach (var store in workContext.AllStores)
                    {
                        store.SyncCurrencies(workContext.AllCurrencies, workContext.CurrentLanguage);
                        store.CurrentSeoInfo = store.SeoInfos.FirstOrDefault(x => x.Language == workContext.CurrentLanguage);
                    }

                    //Set current currency
                    workContext.CurrentCurrency = GetCurrency(context, workContext.CurrentStore);

                    //Initialize catalog search criteria
                    workContext.CurrentProductSearchCriteria = new ProductSearchCriteria(workContext.CurrentLanguage, workContext.CurrentCurrency, qs);

                    //Initialize product response group. Exclude properties meta-information for performance reason (property values will be returned)
                    workContext.CurrentProductResponseGroup = EnumUtility.SafeParse(qs.Get("resp_group"), ItemResponseGroup.ItemLarge & ~ItemResponseGroup.ItemProperties);

                    workContext.PageNumber = qs.Get("page").ToNullableInt();
                    workContext.PageSize   = qs.Get("count").ToNullableInt() ?? qs.Get("page_size").ToNullableInt();

                    var catalogSearchService = Container.Resolve <ICatalogSearchService>();

                    //This line make delay categories loading initialization (categories can be evaluated on view rendering time)
                    workContext.Categories = new MutablePagedList <Category>((pageNumber, pageSize, sortInfos) =>
                    {
                        var criteria = new CategorySearchCriteria(workContext.CurrentLanguage)
                        {
                            PageNumber    = pageNumber,
                            PageSize      = pageSize,
                            ResponseGroup = CategoryResponseGroup.Small
                        };

                        if (string.IsNullOrEmpty(criteria.SortBy) && !sortInfos.IsNullOrEmpty())
                        {
                            criteria.SortBy = SortInfo.ToString(sortInfos);
                        }
                        var result = catalogSearchService.SearchCategories(criteria);
                        foreach (var category in result)
                        {
                            category.Products = new MutablePagedList <Product>((pageNumber2, pageSize2, sortInfos2) =>
                            {
                                var productSearchCriteria = new ProductSearchCriteria(workContext.CurrentLanguage, workContext.CurrentCurrency)
                                {
                                    PageNumber    = pageNumber2,
                                    PageSize      = pageSize2,
                                    Outline       = category.Outline,
                                    ResponseGroup = workContext.CurrentProductSearchCriteria.ResponseGroup
                                };

                                //criteria.CategoryId = category.Id;
                                if (string.IsNullOrEmpty(criteria.SortBy) && !sortInfos2.IsNullOrEmpty())
                                {
                                    productSearchCriteria.SortBy = SortInfo.ToString(sortInfos2);
                                }

                                var searchResult = catalogSearchService.SearchProducts(productSearchCriteria);

                                //Because catalog search products returns also aggregations we can use it to populate workContext using C# closure
                                //now workContext.Aggregation will be contains preloaded aggregations for current category
                                workContext.Aggregations = new MutablePagedList <Aggregation>(searchResult.Aggregations);
                                return(searchResult.Products);
                            }, 1, ProductSearchCriteria.DefaultPageSize);
                        }
                        return(result);
                    }, 1, CategorySearchCriteria.DefaultPageSize);

                    //This line make delay products loading initialization (products can be evaluated on view rendering time)
                    workContext.Products = new MutablePagedList <Product>((pageNumber, pageSize, sortInfos) =>
                    {
                        var criteria        = workContext.CurrentProductSearchCriteria.Clone();
                        criteria.PageNumber = pageNumber;
                        criteria.PageSize   = pageSize;
                        if (string.IsNullOrEmpty(criteria.SortBy) && !sortInfos.IsNullOrEmpty())
                        {
                            criteria.SortBy = SortInfo.ToString(sortInfos);
                        }
                        var result = catalogSearchService.SearchProducts(criteria);
                        //Prevent double api request for get aggregations
                        //Because catalog search products returns also aggregations we can use it to populate workContext using C# closure
                        //now workContext.Aggregation will be contains preloaded aggregations for current search criteria
                        workContext.Aggregations = new MutablePagedList <Aggregation>(result.Aggregations);
                        return(result.Products);
                    }, 1, ProductSearchCriteria.DefaultPageSize);

                    //This line make delay aggregation loading initialization (aggregation can be evaluated on view rendering time)
                    workContext.Aggregations = new MutablePagedList <Aggregation>((pageNumber, pageSize, sortInfos) =>
                    {
                        var criteria        = workContext.CurrentProductSearchCriteria.Clone();
                        criteria.PageNumber = pageNumber;
                        criteria.PageSize   = pageSize;
                        if (string.IsNullOrEmpty(criteria.SortBy) && !sortInfos.IsNullOrEmpty())
                        {
                            criteria.SortBy = SortInfo.ToString(sortInfos);
                        }
                        //Force to load products and its also populate workContext.Aggregations by preloaded values
                        workContext.Products.Slice(pageNumber, pageSize, sortInfos);
                        return(workContext.Aggregations);
                    }, 1, ProductSearchCriteria.DefaultPageSize);

                    workContext.CurrentOrderSearchCriteria = new Model.Order.OrderSearchCriteria(qs);
                    workContext.CurrentQuoteSearchCriteria = new Model.Quote.QuoteSearchCriteria(qs);

                    //Get current customer
                    workContext.CurrentCustomer = await GetCustomerAsync(context);

                    //Validate that current customer has to store access
                    ValidateUserStoreLogin(context, workContext.CurrentCustomer, workContext.CurrentStore);
                    MaintainAnonymousCustomerCookie(context, workContext);

                    // Gets the collection of external login providers
                    var externalAuthTypes = context.Authentication.GetExternalAuthenticationTypes();

                    workContext.ExternalLoginProviders = externalAuthTypes.Select(at => new LoginProvider
                    {
                        AuthenticationType = at.AuthenticationType,
                        Caption            = at.Caption,
                        Properties         = at.Properties
                    }).ToList();

                    workContext.ApplicationSettings = GetApplicationSettings();

                    //Do not load shopping cart and other for resource requests
                    if (!IsAssetRequest(context.Request))
                    {
                        await HandleNonAssetRequest(context, workContext);
                    }
                }
            }
        }
Exemple #12
0
 public List <ProductInventoryListViewModel> GetInventoryBySearch(ProductSearchCriteria searchCriteriaObject)
 {
     return(_productRepository.GetInventoryBySearch(searchCriteriaObject));
 }
Exemple #13
0
 public List <Product> GetProductsBySearch(ProductSearchCriteria searchCriteriaObject)
 {
     return(_productRepository.GetProductsBySearch(searchCriteriaObject));
 }
Exemple #14
0
        private void RouteProductCall(Operation op, ProductEntity entry)
        {
            const string ReviewType = "FullReview";

            if (op == Operation.Publish) // publish
            {
                var product = GetCatalogProduct(entry, out bool isNew);
                product.IsActive = true;

                if (entry.Content != null)
                {
                    var list = new List <EditorialReview>();
                    foreach (var lang in entry.Content.Keys)
                    {
                        var review = new EditorialReview()
                        {
                            Content      = entry.Content[lang],
                            ReviewType   = ReviewType,
                            LanguageCode = lang
                        };

                        list.Add(review);
                    }

                    // add new reviews or update existing ones
                    if (product.Reviews == null)
                    {
                        product.Reviews = list.ToArray();
                    }
                    else
                    {
                        foreach (var review in list)
                        {
                            var existingReview = product.Reviews.Where(x => x.ReviewType == ReviewType && x.LanguageCode == review.LanguageCode).SingleOrDefault();
                            if (existingReview == null)
                            {
                                product.Reviews.Add(review);
                            }
                            else
                            {
                                existingReview.Content = review.Content;
                            }
                        }
                    }
                }

                // now add all the properties
                if (entry.Properties != null)
                {
                    var propValuesList = new List <PropertyValue>();
                    foreach (var key in entry.Properties.Keys)
                    {
                        var prop = entry.Properties[key];

                        foreach (var lang in prop.Keys)
                        {
                            var proValue = new PropertyValue()
                            {
                                LanguageCode = lang,
                                PropertyName = key,
                                Value        = prop[lang]
                            };

                            propValuesList.Add(proValue);
                        }
                    }

                    propValuesList.Add(new PropertyValue()
                    {
                        PropertyName = "contentfulid", Value = entry.Id
                    });

                    // add new properties or update existing ones
                    if (product.PropertyValues == null)
                    {
                        product.PropertyValues = propValuesList.ToArray();
                    }
                    else
                    {
                        foreach (var propertyValue in propValuesList)
                        {
                            var existingPropertyValue = product.PropertyValues.Where(x => x.PropertyName == propertyValue.PropertyName && x.LanguageCode == propertyValue.LanguageCode).SingleOrDefault();
                            if (existingPropertyValue == null)
                            {
                                product.PropertyValues.Add(propertyValue);
                            }
                            else
                            {
                                existingPropertyValue.Value = propertyValue.Value;
                            }
                        }
                    }
                }

                if (isNew)
                {
                    _itemService.Create(product);
                }
                else
                {
                    _itemService.Update(new[] { product });
                }
            }
            else if (op == Operation.Unpublish || op == Operation.Delete) // unpublish
            {
                var criteria = new ProductSearchCriteria();
                criteria.Terms = new[] { string.Format("contentfulid:{0}", entry.Id) };
                var result = _productSearchService.SearchAsync(criteria).Result;

                if (result.TotalCount > 0)
                {
                    var product = _itemService.GetById(result.Items[0].Id, ItemResponseGroup.ItemLarge); // reload complete product now
                    product.IsActive = false;
                    _itemService.Update(new[] { product });
                }
            }
        }
Exemple #15
0
 public IEnumerable <Product> Get(ProductSearchCriteria searchCriteria)
 {
     throw new NotImplementedException();
 }
Exemple #16
0
 public Task <PagedResult <ProductRefiner> > GetRefiners(ProductSearchCriteria productSearchCriteria, QueryResultSettings queryResultSettings)
 {
     return(Task.Run(() => Runtime.Client.ProductManager.Create(CommerceRuntimeManager.Runtime).GetRefiners(productSearchCriteria)));
 }
Exemple #17
0
 /// <summary>
 /// Search products by given criteria
 /// </summary>
 /// <param name="criteria"></param>
 /// <returns></returns>
 public virtual CatalogSearchResult SearchProducts(ProductSearchCriteria criteria)
 {
     return(SearchProductsAsync(criteria).GetAwaiter().GetResult());
 }
Exemple #18
0
 public Task <PagedResult <Product> > Search(ProductSearchCriteria productSearchCriteria, QueryResultSettings queryResultSettings)
 {
     return(Task.Run(() => Runtime.Client.ProductManager.Create(CommerceRuntimeManager.Runtime).SearchProducts(productSearchCriteria, queryResultSettings).Results.ToCRTPagedResult()));
 }
        public IEnumerable <Product> Get([FromQuery] ProductSearchCriteria searchCriteria)
        {
            var products = productService.Get(searchCriteria);

            return(products);
        }
Exemple #20
0
            /// <summary>
            /// Executes the workflow to retrieve the prices and calculated discount amount for the given product identifiers.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <returns>The response.</returns>
            protected override GetIndependentProductPriceDiscountResponse Process(GetIndependentProductPriceDiscountRequest request)
            {
                ThrowIf.Null(request, "request");

                ProductSearchCriteria productSearchCriteria = new ProductSearchCriteria(
                    request.Context.ChannelId.GetValueOrDefault(),
                    request.Context.CatalogId.GetValueOrDefault())
                {
                    DataLevel = CommerceEntityDataLevel.Standard,
                    Ids       = request.ProductIds.ToList()
                };

                ProductSearchResultContainer productSearchResult = request.RequestContext.Runtime.Execute <ProductSearchServiceResponse>(
                    new ProductSearchServiceRequest(productSearchCriteria, request.QueryResultSettings), request.RequestContext).ProductSearchResult;

                List <ProductPrice> productPrices = new List <ProductPrice>(request.ProductIds.Count());

                // Create sales line for every product id there is in the request.
                List <SalesLine> salesLines = new List <SalesLine>(request.ProductIds.Count());

                foreach (var product in productSearchResult.Results)
                {
                    if (product.IsMasterProduct)
                    {
                        foreach (var variant in product.GetVariants())
                        {
                            if (request.ProductIds.Contains(variant.DistinctProductVariantId))
                            {
                                salesLines.Add(new SalesLine
                                {
                                    ItemId  = product.ItemId,
                                    Variant = variant,
                                    InventoryDimensionId    = variant.InventoryDimensionId,
                                    SalesOrderUnitOfMeasure = product.Rules.DefaultUnitOfMeasure,
                                    LineId    = System.Guid.NewGuid().ToString("N"),
                                    Quantity  = 1,
                                    ProductId = variant.DistinctProductVariantId,
                                    CatalogId = request.Context.CatalogId.GetValueOrDefault()
                                });
                            }
                        }
                    }
                    else
                    {
                        salesLines.Add(new SalesLine
                        {
                            ItemId = product.ItemId,
                            SalesOrderUnitOfMeasure = product.Rules.DefaultUnitOfMeasure,
                            LineId    = System.Guid.NewGuid().ToString("N"),
                            Quantity  = 1,
                            ProductId = product.RecordId,
                            CatalogId = request.Context.CatalogId.GetValueOrDefault()
                        });
                    }
                }

                // Set the catalog ids on the sales lines.
                if (request.Context.CatalogId != null)
                {
                    if (request.Context.CatalogId.Value > 0)
                    {
                        // If a specific catalogId is set on the context, add it to the catalogIds on the sales lines.
                        foreach (var sl in salesLines)
                        {
                            sl.CatalogIds.Add(request.Context.CatalogId.Value);
                        }
                    }
                    else
                    {
                        GetProductCatalogAssociationsDataRequest productCatalogAssociationRequest = new GetProductCatalogAssociationsDataRequest(salesLines.Select(p => p.ProductId))
                        {
                            QueryResultSettings = QueryResultSettings.AllRecords
                        };
                        ReadOnlyCollection <ProductCatalogAssociation> productCatalogs = request.RequestContext.Runtime.Execute <GetProductCatalogAssociationsDataResponse>(
                            productCatalogAssociationRequest,
                            request.RequestContext).CatalogAssociations;

                        // If catalogId is 0, add all independent catalogs to the catalogIds on the sales lines.
                        foreach (var sl in salesLines)
                        {
                            sl.CatalogIds.UnionWith(productCatalogs.Where(pc => pc.ProductRecordId == sl.ProductId).Select(pc => pc.CatalogRecordId));
                        }
                    }
                }

                Collection <SalesAffiliationLoyaltyTier> affiliations = null;

                if (request.AffiliationLoyaltyTiers != null)
                {
                    affiliations = new Collection <SalesAffiliationLoyaltyTier>((from alt in request.AffiliationLoyaltyTiers
                                                                                 select new SalesAffiliationLoyaltyTier
                    {
                        AffiliationId = alt.AffiliationId,
                        AffiliationType = alt.AffiliationType,
                        LoyaltyTierId = alt.LoyaltyTierId,
                        ReasonCodeLines = alt.ReasonCodeLines,
                        CustomerId = alt.CustomerId,
                        ChannelId = request.Context.ChannelId.GetValueOrDefault()
                    }).ToList());
                }

                SalesTransaction transaction = new SalesTransaction
                {
                    SalesLines = new Collection <SalesLine>(salesLines),
                    CustomerId = request.CustomerAccountNumber,
                    AffiliationLoyaltyTierLines = affiliations
                };

                // Calculate prices and discounts for sales lines
                GetIndependentPriceDiscountServiceRequest itemPriceDiscountServiceRequest = new GetIndependentPriceDiscountServiceRequest(transaction);
                GetPriceServiceResponse      itemPriceServiceResponse = this.Context.Execute <GetPriceServiceResponse>(itemPriceDiscountServiceRequest);
                Dictionary <long, SalesLine> salesLineDictionary      = itemPriceServiceResponse.Transaction.SalesLines.ToDictionary(sl => sl.ProductId);

                foreach (long productId in request.ProductIds)
                {
                    SalesLine salesLine;

                    if (!salesLineDictionary.TryGetValue(productId, out salesLine))
                    {
                        salesLine = new SalesLine();
                    }

                    ProductPrice productPrice = new ProductPrice
                    {
                        UnitOfMeasure        = salesLine.SalesOrderUnitOfMeasure,
                        ItemId               = salesLine.ItemId,
                        InventoryDimensionId = salesLine.InventoryDimensionId,
                        BasePrice            = salesLine.BasePrice,
                        TradeAgreementPrice  = salesLine.AgreementPrice,
                        AdjustedPrice        = salesLine.AdjustedPrice,
                        DiscountAmount       = salesLine.DiscountAmount,
                        ProductId            = productId,
                        ChannelId            = request.Context.ChannelId.GetValueOrDefault(),
                        CatalogId            = request.Context.CatalogId.GetValueOrDefault()
                    };

                    productPrices.Add(productPrice);
                }

                return(new GetIndependentProductPriceDiscountResponse(productPrices.AsPagedResult()));
            }
        protected virtual IQueryable <ItemEntity> BuildQuery(ICatalogRepository repository, ProductSearchCriteria criteria)
        {
            var query = repository.Items;

            if (!string.IsNullOrEmpty(criteria.Keyword))
            {
                query = query.Where(x => x.Name.Contains(criteria.Keyword));
            }

            if (!criteria.CategoryIds.IsNullOrEmpty())
            {
                var searchCategoryIds = criteria.CategoryIds;

                if (criteria.SearchInChildren)
                {
                    searchCategoryIds = searchCategoryIds.Concat(repository.GetAllChildrenCategoriesIdsAsync(searchCategoryIds).GetAwaiter().GetResult()).ToArray();
                }

                query = query.Where(x => searchCategoryIds.Contains(x.CategoryId) || x.CategoryLinks.Any(link => searchCategoryIds.Contains(link.CategoryId)));
            }

            if (!criteria.CatalogIds.IsNullOrEmpty())
            {
                query = query.Where(x => criteria.CatalogIds.Contains(x.CatalogId));
            }

            if (!criteria.Skus.IsNullOrEmpty())
            {
                query = query.Where(x => criteria.Skus.Contains(x.Code));
            }
            if (!string.IsNullOrEmpty(criteria.MainProductId))
            {
                query = query.Where(x => x.ParentId == criteria.MainProductId);
            }
            else if (!criteria.SearchInVariations)
            {
                query = query.Where(x => x.ParentId == null);
            }

            return(query);
        }
Exemple #22
0
            /// <summary>
            /// Get the Details for a particular product.
            /// </summary>
            /// <param name="productId">The product id you need the details for.</param>
            /// <returns>The View for that product.</returns>
            public async Task <ActionResult> Index(string productId = "")
            {
                EcommerceContext         ecommerceContext         = ServiceUtilities.GetEcommerceContext(this.HttpContext);
                OrgUnitOperationsHandler orgUnitOperationsHandler = new OrgUnitOperationsHandler(ecommerceContext);

                PagedResult <Category> categories = await orgUnitOperationsHandler.GetNavigationalHierarchyCategories(Utilities.DefaultQuerySettings);

                IEnumerable <long> rawCategoryIds = categories.Select(c => c.RecordId);

                ObservableCollection <long> productIds = null;
                Product prod = null;
                Collection <CustomLink> breadcrumbNavLinks = new Collection <CustomLink>();
                long productIdentifier;

                if (string.IsNullOrEmpty(productId) || !long.TryParse(productId, out productIdentifier))
                {
                    RetailLogger.Log.OnlineStoreInvalidProductIdProvided(productId);
                    return(this.RedirectToAction(HomeController.DefaultActionName, HomeController.ControllerName));
                }
                else
                {
                    // add productId to an ObservableCollection
                    productIds = new ObservableCollection <long>();
                    productIds.Add(productIdentifier);

                    ProductSearchCriteria searchCriteria = new ProductSearchCriteria
                    {
                        DataLevelValue = 4,
                        Ids            = productIds
                    };

                    // try and get product information
                    ProductOperationsHandler     productOperationsHandler = new ProductOperationsHandler(ecommerceContext);
                    PagedResult <ProductCatalog> productCatalogs          = await productOperationsHandler.GetProductCatalogs(Utilities.DefaultQuerySettings);

                    IEnumerable <long> activeCatalogIds = productCatalogs.Results.Select(pc => pc.RecordId);

                    PagedResult <Product> products = await productOperationsHandler.SearchProducts(searchCriteria, activeCatalogIds, Utilities.DefaultQuerySettings);

                    if (!products.Results.Any())
                    {
                        var message = string.Format("ProductIds: {0}.", string.Join(",", productIds));
                        RetailLogger.Log.OnlineStoreNoProductsFound(message);
                        return(this.RedirectToAction(HomeController.DefaultActionName, HomeController.ControllerName));
                    }

                    prod = products.Results.First <Product>();

                    // Breadcrumb Navigation Links
                    // add current item
                    breadcrumbNavLinks.Add(new CustomLink("/ProductDetails?productId=" + prod.RecordId, prod.ProductName));

                    Category currentCategory = this.GetCategoryById(prod.CategoryIds.First(), categories);

                    while (currentCategory.ParentCategory != 0)
                    {
                        breadcrumbNavLinks.Add(new CustomLink("/ProductGallery?categoryId=" + currentCategory.RecordId, currentCategory.Name));
                        currentCategory = this.GetCategoryById(currentCategory.ParentCategory, categories);
                    }

                    breadcrumbNavLinks.Add(new CustomLink("/", "Home"));
                }

                prod = (await ProductDetailsController.PopulateViewSpecificProductInfo(new Product[] { prod }, ecommerceContext)).FirstOrDefault();

                return(this.View(ProductDetailsController.ProductDetailsViewName, new ProductDetailsModel(prod, breadcrumbNavLinks)));
            }
Exemple #23
0
        public virtual Aggregation[] ConvertAggregations(IList <AggregationResponse> aggregationResponses, ProductSearchCriteria criteria)
        {
            var result = new List <Aggregation>();

            var browseFilters = _browseFilterService.GetBrowseFilters(criteria);

            if (browseFilters != null && aggregationResponses?.Any() == true)
            {
                foreach (var filter in browseFilters)
                {
                    Aggregation aggregation = null;

                    var attributeFilter  = filter as AttributeFilter;
                    var rangeFilter      = filter as RangeFilter;
                    var priceRangeFilter = filter as PriceRangeFilter;

                    if (attributeFilter != null)
                    {
                        aggregation = GetAttributeAggregation(attributeFilter, aggregationResponses);
                    }
                    else if (rangeFilter != null)
                    {
                        aggregation = GetRangeAggregation(rangeFilter, aggregationResponses);
                    }
                    else if (priceRangeFilter != null)
                    {
                        aggregation = GetPriceRangeAggregation(priceRangeFilter, aggregationResponses);
                    }

                    if (aggregation?.Items?.Any() == true)
                    {
                        result.Add(aggregation);
                    }
                }
            }

            // Add localized labels for names and values
            if (result.Any())
            {
                AddLabels(result, criteria.CatalogId);
            }

            return(result.ToArray());
        }
        protected virtual async Task <catalogDto.ProductIndexedSearchResult> SearchProductsAsync(ProductSearchCriteria criteria, WorkContext workContext)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchProductsAsync), criteria.GetCacheKey(), workContext.CurrentStore.Id, workContext.CurrentLanguage.CultureName, workContext.CurrentCurrency.Code);

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                criteria = criteria.Clone() as ProductSearchCriteria;

                var searchCriteria = criteria.ToProductSearchCriteriaDto(workContext);
                return await _searchApi.SearchProductsAsync(searchCriteria);
            }));
        }
Exemple #25
0
        /// <summary>
        /// Search products by given criteria
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public virtual CatalogSearchResult SearchProducts(ProductSearchCriteria criteria)
        {
            var workContext = _workContextAccessor.WorkContext;

            return(Task.Factory.StartNew(() => InnerSearchProductsAsync(criteria, workContext), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
        }
            /// <summary>
            /// Processes the specified request.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <returns>
            /// Available quantities of specified listings at the requested warehouse.
            /// </returns>
            protected override GetListingAvailableQuantitiesResponse Process(GetListingAvailableQuantitiesRequest request)
            {
                ThrowIf.Null(request, "request");
                ThrowIf.NullOrEmpty(request.ProductIds, "No Ids have been provided");

                QueryResultSettings settings = QueryResultSettings.AllRecords;
                var productIds = request.ProductIds.Distinct().ToList();
                ProductSearchCriteria queryCriteria = new ProductSearchCriteria(this.Context.GetPrincipal().ChannelId)
                {
                    Ids       = productIds,
                    DataLevel = CommerceEntityDataLevel.Identity,
                };

                var productSearchResult = request.RequestContext.Runtime.Execute <ProductSearchServiceResponse>(
                    new ProductSearchServiceRequest(queryCriteria, settings), request.RequestContext).ProductSearchResult;

                if (productSearchResult.Results.IsNullOrEmpty())
                {
                    string nonResolvedProductIdsInfo = string.Join(" ", productIds);
                    //// This is a valid situtation for cross channel scenarios, wish lists for example.
                    NetTracer.Warning("None of the specified product ids were found on the current channel {0}. ProductIds = {1}", this.Context.GetPrincipal().ChannelId, nonResolvedProductIdsInfo);
                    return(new GetListingAvailableQuantitiesResponse());
                }

                var productMap = productSearchResult.Results.ToDictionary(p => p.RecordId, p => p);
                var items      = this.GetItemAndInventDimId(productIds, productSearchResult, productMap);

                settings = new QueryResultSettings(new PagingInfo(items.Count(), 0));
                var itemAvailabilities = new HashSet <ItemAvailability>();
                var itemUnits          = new HashSet <ItemUnit>();

                if (request.ChannelId == 0)
                {
                    var itemVariantInventoryDimensions = new HashSet <ItemVariantInventoryDimension>();
                    foreach (var item in items)
                    {
                        itemVariantInventoryDimensions.Add(new ItemVariantInventoryDimension(item.Item1, item.Item2));
                    }

                    var itemAvailableQuantitiesRequest  = new GetItemAvailableQuantitiesByItemsServiceRequest(settings, itemVariantInventoryDimensions, string.Empty);
                    var itemAvailableQuantitiesResponse = this.Context.Execute <GetItemAvailableQuantitiesByItemsServiceResponse>(itemAvailableQuantitiesRequest);
                    foreach (var quantity in itemAvailableQuantitiesResponse.ItemAvailableQuantities.Results)
                    {
                        if (quantity != null)
                        {
                            var productAvailableQuantity = new ItemAvailability
                            {
                                ItemId = quantity.ItemId,
                                VariantInventoryDimensionId = quantity.VariantInventoryDimensionId,
                                AvailableQuantity           = quantity.AvailableQuantity,
                                UnitOfMeasure = quantity.UnitOfMeasure
                            };

                            itemAvailabilities.Add(productAvailableQuantity);

                            var itemUnit = new ItemUnit
                            {
                                ItemId = quantity.ItemId,
                                VariantInventoryDimensionId = quantity.VariantInventoryDimensionId,
                                UnitOfMeasure = items.Where(i => i.Item1.Equals(quantity.ItemId) && i.Item2.Equals(quantity.VariantInventoryDimensionId)).SingleOrDefault().Item3
                            };

                            itemUnits.Add(itemUnit);
                        }
                    }
                }
                else
                {
                    var itemWarehouses = new HashSet <ItemWarehouse>();
                    foreach (var item in items)
                    {
                        var itemWarehouse = new ItemWarehouse()
                        {
                            ItemId = item.Item1,
                            VariantInventoryDimensionId = item.Item2,
                            InventoryLocationId         = this.Context.GetChannelConfiguration().InventLocation
                        };
                        itemWarehouses.Add(itemWarehouse);
                    }

                    var warehouseRequest  = new GetItemAvailabilitiesByItemWarehousesServiceRequest(settings, itemWarehouses);
                    var warehouseResponse = this.Context.Execute <GetItemAvailabilitiesByItemWarehousesServiceResponse>(warehouseRequest);
                    foreach (var quantity in warehouseResponse.ItemAvailabilities.Results)
                    {
                        if (quantity != null)
                        {
                            itemAvailabilities.Add(quantity);

                            var itemUnit = new ItemUnit
                            {
                                ItemId = quantity.ItemId,
                                VariantInventoryDimensionId = quantity.VariantInventoryDimensionId,
                                UnitOfMeasure = items.Where(i => i.Item1.Equals(quantity.ItemId) && i.Item2.Equals(quantity.VariantInventoryDimensionId)).SingleOrDefault().Item3
                            };

                            itemUnits.Add(itemUnit);
                        }
                    }
                }

                var itemAvailabilitiesList  = ChannelAvailabilityHelper.ConvertUnitOfMeasure(this.Context, itemAvailabilities.ToList(), itemUnits.ToList());
                var processedAvailabilities = this.ProcessItemAvailabilities(itemAvailabilitiesList, productIds, productSearchResult, productMap);

                return(new GetListingAvailableQuantitiesResponse(processedAvailabilities.AsPagedResult()));
            }
        protected virtual IFilter ConvertBrowseFilter(IBrowseFilter filter, IList <string> valueIds, ProductSearchCriteria criteria)
        {
            IFilter result = null;

            if (filter != null && valueIds != null)
            {
                var attributeFilter  = filter as AttributeFilter;
                var rangeFilter      = filter as BrowseFilters.RangeFilter;
                var priceRangeFilter = filter as PriceRangeFilter;

                if (attributeFilter != null)
                {
                    result = ConvertAttributeFilter(attributeFilter, valueIds);
                }
                else if (rangeFilter != null)
                {
                    result = ConvertRangeFilter(rangeFilter, valueIds);
                }
                else if (priceRangeFilter != null)
                {
                    result = ConvertPriceRangeFilter(priceRangeFilter, valueIds, criteria);
                }
            }

            return(result);
        }
        public IActionResult Get([FromQuery] ProductSearchCriteria criteria)
        {
            var products = productsService.Get(criteria);

            return(Ok(products));
        }
        protected virtual IList <AggregationRequest> GetPriceRangeFilterAggregationRequests(PriceRangeFilter priceRangeFilter, ProductSearchCriteria criteria, IList <IFilter> existingFilters)
        {
            var result = priceRangeFilter.Values.Select(v => GetPriceRangeFilterValueAggregationRequest(priceRangeFilter, v, existingFilters, criteria.Pricelists)).ToList();

            return(result);
        }
        public Task <IEnumerable <Product> > GetAsync(ProductSearchCriteria criteria)
        {
            // return Task.FromResult(Get(criteria));

            return(Task.Run(() => Get(criteria)));
        }