//protected virtual void IndexReviews(ref ResultDocument doc, CatalogProduct item)
        //{
        //	var reviews = ReviewRepository.Reviews.Where(r => r.ItemId == item.ItemId).ToArray();
        //	var count = reviews.Count();
        //	var avg = count > 0 ? Math.Round(reviews.Average(r => r.OverallRating), 2) : 0;
        //	doc.Add(new DocumentField("__reviewstotal", count, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
        //	doc.Add(new DocumentField("__reviewsavg", avg, new[] { IndexStore.YES, IndexType.NOT_ANALYZED }));
        //}


        private IEnumerable <Partition> GetPartitionsForAllProducts()
        {
            var partitions = new List <Partition>();

            var criteria = new SearchCriteria
            {
                ResponseGroup = ResponseGroup.WithProducts,
                Count         = 0
            };

            var result = _catalogSearchService.Search(criteria);

            for (var start = 0; start < result.TotalCount; start += _partitionSizeCount)
            {
                criteria.Start = start;
                criteria.Count = _partitionSizeCount;

                // TODO: Need optimize search to return only product ids
                result = _catalogSearchService.Search(criteria);

                var productIds = result.Products.Select(p => p.Id).ToArray();
                partitions.Add(new Partition(OperationType.Index, productIds));
            }

            return(partitions);
        }
        public IHttpActionResult GetProductByCode(string store, [FromUri] string code, [FromUri] coreModel.ItemResponseGroup responseGroup = coreModel.ItemResponseGroup.ItemLarge, string language = "en-us")
        {
            var fullLoadedStore = GetStoreById(store);

            if (fullLoadedStore == null)
            {
                throw new NullReferenceException(store + " not found");
            }

            var searchCriteria = new SearchCriteria
            {
                ResponseGroup = ResponseGroup.WithProducts | ResponseGroup.WithVariations,
                Code          = code,
                //CatalogId = fullLoadedStore.Catalog
            };

            var result = _searchService.Search(searchCriteria);

            if (result.Products != null && result.Products.Any())
            {
                var products = InnerGetProductsByIds(fullLoadedStore, new [] { result.Products.First().Id }, responseGroup);
                var retVal   = products.FirstOrDefault();
                if (retVal != null)
                {
                    return(Ok(retVal));
                }
            }

            return(NotFound());
        }
Пример #3
0
        protected virtual IEnumerable <Partition> GetPartitionsForAllProducts()
        {
            var partitions = new ConcurrentBag <Partition>();

            var result = _catalogSearchService.Search(new SearchCriteria {
                Take = 0, ResponseGroup = SearchResponseGroup.WithProducts, WithHidden = true
            });
            var parts           = result.ProductsTotalCount / PartitionSize + 1;
            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 5
            };

            Parallel.For(0, parts, parallelOptions, (index) =>
            {
                var criteria = new SearchCriteria
                {
                    Skip          = index * PartitionSize,
                    Take          = PartitionSize,
                    ResponseGroup = SearchResponseGroup.WithProducts,
                    WithHidden    = true
                };

                // TODO: Need optimize search to return only product ids
                result = _catalogSearchService.Search(criteria);

                var productIds = result.Products.Select(p => p.Id).ToArray();
                partitions.Add(new Partition(OperationType.Index, productIds));
            });

            return(partitions);
        }
        private void ExportCategories(JsonTextWriter writer, JsonSerializer serializer, PlatformExportManifest manifest, ExportImportProgressInfo progressInfo, Action <ExportImportProgressInfo> progressCallback)
        {
            //Categories
            progressInfo.Description = string.Format("Categories exporting...");
            progressCallback(progressInfo);

            var categorySearchCriteria = new SearchCriteria {
                WithHidden = true, Skip = 0, Take = 0, ResponseGroup = SearchResponseGroup.WithCategories
            };
            var categoriesSearchResult = _catalogSearchService.Search(categorySearchCriteria);
            var categories             = _categoryService.GetByIds(categoriesSearchResult.Categories.Select(x => x.Id).ToArray(), CategoryResponseGroup.Full);

            if (manifest.HandleBinaryData)
            {
                LoadImages(categories);
            }

            writer.WritePropertyName("Categories");
            writer.WriteStartArray();
            //reset some properties to decrease resultin JSON size
            foreach (var category in categories)
            {
                ResetRedundantReferences(category);
                serializer.Serialize(writer, category);
            }
            writer.WriteEndArray();

            progressInfo.Description = $"{ categoriesSearchResult.Categories.Count } categories exported";
            progressCallback(progressInfo);
        }
Пример #5
0
        public IHttpActionResult ListItemsSearch(webModel.SearchCriteria criteria)
        {
            var coreModelCriteria = criteria.ToCoreModel();

            ApplyRestrictionsForCurrentUser(coreModelCriteria);

            coreModelCriteria.WithHidden = true;
            //Need search in children categories if user specify keyword
            if (!string.IsNullOrEmpty(coreModelCriteria.Keyword))
            {
                coreModelCriteria.SearchInChildren   = true;
                coreModelCriteria.SearchInVariations = true;
            }

            var retVal = new webModel.ListEntrySearchResult();

            int categorySkip = 0;
            int categoryTake = 0;

            //Because products and categories represent in search result as two separated collections for handle paging request
            //we should join two resulting collection artificially
            //search categories
            if ((coreModelCriteria.ResponseGroup & coreModel.SearchResponseGroup.WithCategories) == coreModel.SearchResponseGroup.WithCategories)
            {
                coreModelCriteria.ResponseGroup = coreModelCriteria.ResponseGroup & ~coreModel.SearchResponseGroup.WithProducts;
                var categoriesSearchResult = _searchService.Search(coreModelCriteria);
                var categoriesTotalCount   = categoriesSearchResult.Categories.Count();

                categorySkip = Math.Min(categoriesTotalCount, coreModelCriteria.Skip);
                categoryTake = Math.Min(coreModelCriteria.Take, Math.Max(0, categoriesTotalCount - coreModelCriteria.Skip));
                var categories = categoriesSearchResult.Categories.Skip(categorySkip).Take(categoryTake).Select(x => new webModel.ListEntryCategory(x.ToWebModel(_blobUrlResolver))).ToList();

                retVal.TotalCount = categoriesTotalCount;
                retVal.ListEntries.AddRange(categories);

                coreModelCriteria.ResponseGroup = coreModelCriteria.ResponseGroup | coreModel.SearchResponseGroup.WithProducts;
            }

            //search products
            if ((coreModelCriteria.ResponseGroup & coreModel.SearchResponseGroup.WithProducts) == coreModel.SearchResponseGroup.WithProducts)
            {
                coreModelCriteria.ResponseGroup = coreModelCriteria.ResponseGroup & ~coreModel.SearchResponseGroup.WithCategories;
                coreModelCriteria.Skip          = coreModelCriteria.Skip - categorySkip;
                coreModelCriteria.Take          = coreModelCriteria.Take - categoryTake;
                var productsSearchResult = _searchService.Search(coreModelCriteria);

                var products = productsSearchResult.Products.Select(x => new webModel.ListEntryProduct(x.ToWebModel(_blobUrlResolver)));

                retVal.TotalCount += productsSearchResult.ProductsTotalCount;
                retVal.ListEntries.AddRange(products);
            }


            return(Ok(retVal));
        }
Пример #6
0
        /// <summary>
        /// Get product by Code from given catalog
        /// </summary>
        private CatalogProduct GetProductByCode(string code, string catalogId)
        {
            var responseGroup = SearchResponseGroup.WithProducts | SearchResponseGroup.WithVariations;

            var criteria = new SearchCriteria {
                Take = 1, Skip = 0, ResponseGroup = responseGroup, Code = code, CatalogId = catalogId, SearchInChildren = true, WithHidden = true
            };
            var searchResponse = _searchService.Search(criteria);

            return(searchResponse.Products.FirstOrDefault());
        }
        public ActionResult InstantSearch(CatalogSearchQuery query)
        {
            if (string.IsNullOrWhiteSpace(query.Term) || query.Term.Length < _searchSettings.InstantSearchTermMinLength)
            {
                return(Content(string.Empty));
            }

            query
            .BuildFacetMap(false)
            .Slice(0, Math.Min(16, _searchSettings.InstantSearchNumberOfProducts))
            .SortBy(ProductSortingEnum.Relevance);

            var result = _catalogSearchService.Search(query);

            var model = new SearchResultModel(query)
            {
                SearchResult       = result,
                Term               = query.Term,
                TotalProductsCount = result.TotalHitsCount
            };

            var mappingSettings = _catalogHelper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Mini, x =>
            {
                x.MapPrices            = false;
                x.MapShortDescription  = true;
                x.MapPictures          = _searchSettings.ShowProductImagesInInstantSearch;
                x.ThumbnailSize        = _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage;
                x.PrefetchTranslations = true;
                x.PrefetchUrlSlugs     = true;
            });

            using (_urlRecordService.BeginScope(false))
                using (_localizedEntityService.BeginScope(false))
                {
                    // InstantSearch should be REALLY very fast! No time for smart caching stuff.
                    if (result.Hits.Count > 0)
                    {
                        _localizedEntityService.PrefetchLocalizedProperties(
                            nameof(Product),
                            Services.WorkContext.WorkingLanguage.Id,
                            result.Hits.Select(x => x.Id).ToArray());
                    }

                    // Add product hits.
                    model.TopProducts = _catalogHelper.MapProductSummaryModel(result.Hits, mappingSettings);

                    // Add spell checker suggestions (if any).
                    model.AddSpellCheckerSuggestions(result.SpellCheckerSuggestions, T, x => Url.RouteUrl("Search", new { q = x }));
                }

            return(PartialView(model));
        }
        protected override ExportableSearchResult FetchData(CategoryExportSearchCriteria searchCriteria)
        {
            var categorySearchCriteria = searchCriteria.ToCatalogSearchCriteria();

            categorySearchCriteria.ResponseGroup = SearchResponseGroup.WithCategories;

            var searchResult = _catalogSearchService.Search(categorySearchCriteria);
            var categoryIds  = searchResult.Categories
                               .Skip(categorySearchCriteria.Skip)
                               .Take(categorySearchCriteria.Take)
                               .Select(x => x.Id)
                               .ToArray();

            var categories = _categoryService.GetByIds(categoryIds, CategoryResponseGroup.Full);

            categories.LoadImages(_blobStorageProvider);

            foreach (var category in categories)
            {
                category.ResetRedundantReferences();
            }

            return(new ExportableSearchResult
            {
                TotalCount = searchResult.CategoriesTotalCount,
                Results = categories.Select(x => AbstractTypeFactory <ExportableCategory> .TryCreateInstance().FromModel(x)).Cast <IExportable>().ToList(),
            });
        }
Пример #9
0
        public ProductsCustomBatchRequest GetCatalogProductsBatchRequest(string catalogId, string categoryId = "")
        {
            var retVal = new ProductsCustomBatchRequest
            {
                Entries = new List <ProductsCustomBatchRequestEntry>()
            };

            var searchCriteria = new SearchCriteria
            {
                CatalogId     = catalogId,
                CategoryId    = categoryId,
                ResponseGroup = SearchResponseGroup.WithProducts | SearchResponseGroup.WithVariations
            };
            var result = _catalogSearchService.Search(searchCriteria);

            foreach (var product in result.Products.Select((value, index) => new { Value = value, Index = index }))
            {
                var converted = product.Value.ToGoogleModel(_assetUrlResolver);
                if (!TryGetProductPrice(converted.Id, out var productPrice))
                {
                    continue;
                }

                converted.Price = productPrice;

                var val = converted.ToBatchEntryModel();
                val.BatchId = product.Index + 1;
                retVal.Entries.Add(val);
            }
            ;
            return(retVal);
        }
Пример #10
0
        public IHttpActionResult ListItemsSearch([ModelBinder(typeof(ListEntrySearchCriteriaBinder))] webModel.ListEntrySearchCriteria criteria)
        {
            var searchCriteria = criteria.ToCoreModel();

            ApplyRestrictionsForCurrentUser(searchCriteria);

            var serviceResult = _searchService.Search(searchCriteria);

            var retVal = new webModel.ListEntrySearchResult();

            var start = criteria.Start;
            var count = criteria.Count;

            // all categories
            var categories = serviceResult.Categories.Select(x => new webModel.ListEntryCategory(x.ToWebModel(_blobUrlResolver))).ToList();
            var products   = serviceResult.Products.Select(x => new webModel.ListEntryProduct(x.ToWebModel(_blobUrlResolver)));

            retVal.TotalCount = categories.Count() + serviceResult.ProductsTotalCount;
            retVal.ListEntries.AddRange(categories.Skip(start).Take(count));

            count -= categories.Count();

            retVal.ListEntries.AddRange(products.Take(count));

            return(Ok(retVal));
        }
        public SearchResult Search(SearchCriteria criteria)
        {
            var retVal = _catalogSearchService.Search(criteria);

            if (!string.IsNullOrEmpty(criteria.CatalogId))
            {
                var catalog = base.AllCachedCatalogs.FirstOrDefault(x => x.Id.EqualsInvariant(criteria.CatalogId));
                if (catalog != null && !catalog.Virtual)
                {
                    criteria.WithHidden = false;
                }
            }
            var extCatalogs = GetExternalCatalogs();

            if (!string.IsNullOrEmpty(criteria.CatalogId))
            {
                extCatalogs = extCatalogs.Where(x => x.Id.EqualsInvariant(criteria.CatalogId));
            }
            var vcSearchCriteria = new External.CatalogModule.Web.CatalogModuleApi.Models.SearchCriteria();

            vcSearchCriteria.InjectFrom(criteria);
            vcSearchCriteria.Skip             = criteria.Skip;
            vcSearchCriteria.Take             = criteria.Take;
            vcSearchCriteria.Sort             = criteria.Sort;
            vcSearchCriteria.WithHidden       = false;
            vcSearchCriteria.SearchInChildren = vcSearchCriteria.CatalogId.IsNullOrEmpty() ? true : criteria.SearchInChildren;
            vcSearchCriteria.ResponseGroup    = criteria.ResponseGroup.ToString();

            foreach (var extCatalog in extCatalogs)
            {
                var apiUrl = extCatalog.PropertyValues.FirstOrDefault(x => x.PropertyName.EqualsInvariant("apiUrl")).Value.ToString();
                if (criteria.Take >= 0)
                {
                    vcSearchCriteria.CatalogId = extCatalog.Id;
                    var result = _vcCatalogClientFactory(apiUrl).CatalogModuleSearch.Search(vcSearchCriteria);

                    retVal.ProductsTotalCount += result.ProductsTotalCount.Value;
                    vcSearchCriteria.Skip      = Math.Max(0, criteria.Skip - retVal.ProductsTotalCount);
                    vcSearchCriteria.Take      = Math.Max(0, criteria.Take - retVal.Products.Count());
                    foreach (var dtoCategory in result.Categories)
                    {
                        if (!retVal.Categories.Any(x => x.Id.EqualsInvariant(dtoCategory.Id)))
                        {
                            var cat = new Category();
                            cat.InjectFrom(dtoCategory);
                            retVal.Categories.Add(cat);
                        }
                    }
                    foreach (var dtoProduct in result.Products)
                    {
                        if (!retVal.Products.Any(x => x.Id.EqualsInvariant(dtoProduct.Id)))
                        {
                            var prod = ConvertToProduct(dtoProduct);
                            retVal.Products.Add(prod);
                        }
                    }
                }
            }
            return(retVal);
        }
        public IHttpActionResult ListItemsSearch(coreModel.SearchCriteria searchCriteria)
        {
            ApplyRestrictionsForCurrentUser(searchCriteria);

            searchCriteria.WithHidden = true;
            //Need search in children categories if user specify keyword
            if (!string.IsNullOrEmpty(searchCriteria.Keyword))
            {
                searchCriteria.SearchInChildren   = true;
                searchCriteria.SearchInVariations = true;
            }
            var serviceResult = _searchService.Search(searchCriteria);

            var retVal = new webModel.ListEntrySearchResult();

            var start = searchCriteria.Skip;
            var count = searchCriteria.Take;

            // all categories
            var categories = serviceResult.Categories.Select(x => new webModel.ListEntryCategory(x.ToWebModel(_blobUrlResolver))).ToList();
            var products   = serviceResult.Products.Select(x => new webModel.ListEntryProduct(x.ToWebModel(_blobUrlResolver)));

            retVal.TotalCount = categories.Count() + serviceResult.ProductsTotalCount;
            retVal.ListEntries.AddRange(categories.Skip(start).Take(count));

            count -= categories.Count();

            retVal.ListEntries.AddRange(products.Take(count));

            return(Ok(retVal));
        }
        private ICollection <CatalogProduct> LoadProducts(Store store, Catalog catalog)
        {
            // TODO: Implement product count restriction from Catalog.MaximumNumber setting
            var retVal = new List <CatalogProduct>();

            var productsIds = _catalogSearchService.Search(new SearchCriteria
            {
                CatalogId        = catalog.Id,
                SearchInChildren = true,
                Skip             = 0,
                Take             = int.MaxValue,
                ResponseGroup    = SearchResponseGroup.WithProducts
            }).Products.Select(x => x.Id).ToArray();
            var products = _productService.GetByIds(productsIds.Distinct().ToArray(), ItemResponseGroup.ItemInfo | ItemResponseGroup.Variations);

            foreach (var product in products)
            {
                retVal.Add(product);
                if (product.Variations != null)
                {
                    retVal.AddRange(product.Variations);
                }
            }

            return(retVal);
        }
        public SearchResult Search(SearchCriteria criteria)
        {
            SearchResult result;

            var useIndexedSearch = _settingsManager.GetValue("VirtoCommerce.SearchApi.UseCatalogIndexedSearchInManager", true);
            var searchProducts   = criteria.ResponseGroup.HasFlag(SearchResponseGroup.WithProducts);

            if (useIndexedSearch && searchProducts && !string.IsNullOrEmpty(criteria.Keyword))
            {
                result = new SearchResult();

                // TODO: create outline for category
                // TODO: implement sorting

                var serviceCriteria = new CatalogItemSearchCriteria()
                {
                    SearchPhrase      = criteria.Keyword,
                    Catalog           = criteria.CatalogId,
                    StartingRecord    = criteria.Skip,
                    RecordsToRetrieve = criteria.Take,
                    WithHidden        = criteria.WithHidden,
                    Locale            = "*",
                };

                SearchItems(_searchConnection.Scope, result, serviceCriteria, ItemResponseGroup.ItemInfo | ItemResponseGroup.Outlines);
            }
            else
            {
                // use original impl. from catalog module
                result = _catalogSearchService.Search(criteria);
            }

            return(result);
        }
Пример #15
0
        public IHttpActionResult Search([FromUri] SearchCriteria criteria)
        {
            ApplyRestrictionsForCurrentUser(criteria);
            var serviceResult = _searchService.Search(criteria);

            return(Ok(serviceResult.ToWebModel(_blobUrlResolver)));
        }
Пример #16
0
        public CatalogSearchResult Search(SearchFilterExpression[] filters, int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var searchQuery = new CatalogSearchQuery()
                              .OriginatesFrom("Rule/Search")
                              .WithLanguage(_services.WorkContext.WorkingLanguage)
                              .WithCurrency(_services.WorkContext.WorkingCurrency)
                              .BuildFacetMap(false)
                              .CheckSpelling(0)
                              .Slice(pageIndex * pageSize, pageSize)
                              .SortBy(ProductSortingEnum.CreatedOn);

            if ((filters?.Length ?? 0) == 0)
            {
                return(new CatalogSearchResult(searchQuery));
            }

            SearchFilterExpressionGroup group;

            if (filters.Length == 1 && filters[0] is SearchFilterExpressionGroup group2)
            {
                group = group2;
            }
            else
            {
                group = new SearchFilterExpressionGroup();
                group.AddExpressions(filters);
            }

            searchQuery = group.ApplyFilters(searchQuery);

            var searchResult = _catalogSearchService.Search(searchQuery);

            return(searchResult);
        }
Пример #17
0
        protected override ExportableSearchResult FetchData(ProductExportSearchCriteria searchCriteria)
        {
            var result     = Array.Empty <CatalogProduct>();
            int totalCount = 0;

            var responseGroup = BuildResponseGroup();
            var productIds    = searchCriteria.ObjectIds?.ToArray() ?? Array.Empty <string>();

            if (productIds.IsNullOrEmpty())
            {
                var catalogSearchCriteria = searchCriteria.ToCatalogSearchCriteria();

                var productSearchResult = _catalogSearchService.Search(catalogSearchCriteria);
                productIds = productSearchResult.Products.Select(x => x.Id).ToArray();
                totalCount = productSearchResult.ProductsTotalCount;
            }

            if (!productIds.IsNullOrEmpty())
            {
                result     = _itemService.GetByIds(productIds, responseGroup);
                totalCount = result.Length;
            }

            if (DataQuery.LoadImageBinaries == true || DataQuery.IncludedProperties.Any(x => x.FullName.Contains("Images.BinaryData")))
            {
                result.LoadImages(_blobStorageProvider);
            }

            return(new ExportableSearchResult()
            {
                Results = ToExportable(result).ToList(),
                TotalCount = totalCount
            });
        }
Пример #18
0
        public ProductsCustomBatchRequest GetCatalogProductsBatchRequest(string catalogId, string categoryId = "")
        {
            var result = _catalogSearchService.Search(new SearchCriteria {
                CatalogId = catalogId, CategoryId = categoryId, ResponseGroup = SearchResponseGroup.WithProducts | SearchResponseGroup.WithVariations
            });
            var retVal = new ProductsCustomBatchRequest();

            foreach (var product in result.Products.Select((value, index) => new { Value = value, Index = index }))
            {
                var converted = product.Value.ToGoogleModel(_assetUrlResolver);
                var prices    = _pricingService.EvaluateProductPrices(new PriceEvaluationContext {
                    ProductIds = new string[] { converted.Id }
                });
                if (prices != null)
                {
                    converted.Price = prices.First(x => x.Currency == "USD").ToGoogleModel();
                    if (retVal.Entries == null)
                    {
                        retVal.Entries = new List <ProductsCustomBatchRequestEntry>();
                    }
                    var val = converted.ToBatchEntryModel();
                    val.BatchId = product.Index + 1;
                    retVal.Entries.Add(val);
                }
            }
            ;
            return(retVal);
        }
Пример #19
0
        public SearchResult Search(SearchCriteria criteria)
        {
            var cacheKey = GetCacheKey("CatalogSearchService.Search", criteria.GetCacheKey());
            var retVal   = _cacheManager.Get(cacheKey, RegionName, () => _searchService.Search(criteria));

            return(retVal);
        }
Пример #20
0
        public SearchResult Search(SearchCriteria criteria)
        {
            SearchResult retVal;

            if (!string.IsNullOrEmpty(criteria.Keyword) && _settingsManager.GetValue("VirtoCommerce.SearchApi.UseCatalogIndexedSearchInManager", true))
            {
                // use indexed search
                retVal = new SearchResult();

                // TODO: create outline for category
                // TODO: implement sorting

                var serviceCriteria = new SimpleCatalogItemSearchCriteria()
                {
                    RawQuery          = criteria.Keyword,
                    Catalog           = criteria.CatalogId,
                    StartingRecord    = criteria.Skip,
                    RecordsToRetrieve = criteria.Take,
                    WithHidden        = true
                };

                SearchItems(_searchConnection.Scope, retVal, serviceCriteria, ItemResponseGroup.ItemInfo | ItemResponseGroup.Outlines);
            }
            else
            {
                // use original impl. from catalog module
                retVal = _catalogSearchService.Search(criteria);
            }

            return(retVal);
        }
        public ListEntrySearchResult Search(SearchCriteria criteria)
        {
            var result = new ListEntrySearchResult();
            var skip   = 0;
            var take   = 0;

            // because products and categories represent in search result as two separated collections for handle paging request
            // we should join two resulting collection artificially

            // search categories
            var responseGroupCopy = criteria.ResponseGroup;

            if (criteria.ResponseGroup.HasFlag(Flags.WithCategories))
            {
                criteria.ResponseGroup &= ~Flags.WithProducts;

                var searchResult = _searchService.Search(criteria);
                var totalCount   = searchResult.Categories.Count;
                skip = GetSkip(criteria, totalCount);
                take = GetTake(criteria, totalCount);
                var pagedCategories = searchResult.Categories.Skip(skip).Take(take);
                var categories      = pagedCategories.Select(
                    category => new ListEntryCategory(category.ToWebModel(_blobUrlResolver)));
                result.TotalCount = totalCount;

                result.ListEntries.AddRange(categories);
            }

            criteria.ResponseGroup = responseGroupCopy;

            // search products
            if (criteria.ResponseGroup.HasFlag(Flags.WithProducts))
            {
                criteria.ResponseGroup &= ~Flags.WithCategories;

                criteria.Skip -= skip;
                criteria.Take -= take;
                var searchResult = _searchService.Search(criteria);
                var products     = searchResult.Products.Select(
                    product => new ListEntryProduct(product.ToWebModel(_blobUrlResolver)));
                result.TotalCount += searchResult.ProductsTotalCount;

                result.ListEntries.AddRange(products);
            }

            return(result);
        }
Пример #22
0
        private IEnumerable <CatalogProduct> LoadProducts(string catalogId, string[] exportedCategories, string[] exportedProducts)
        {
            var retVal = new List <CatalogProduct>();

            var productIds = new List <string>();

            if (exportedProducts != null)
            {
                productIds = exportedProducts.ToList();
            }
            if (exportedCategories != null && exportedCategories.Any())
            {
                foreach (var categoryId in exportedCategories)
                {
                    var result = _searchService.Search(new SearchCriteria {
                        CatalogId = catalogId, CategoryId = categoryId, Start = 0, Count = int.MaxValue, ResponseGroup = ResponseGroup.WithProducts | ResponseGroup.WithCategories
                    });
                    productIds.AddRange(result.Products.Select(x => x.Id));
                    if (result.Categories != null && result.Categories.Any())
                    {
                        retVal.AddRange(LoadProducts(catalogId, result.Categories.Select(x => x.Id).ToArray(), null));
                    }
                }
            }

            if ((exportedCategories == null || !exportedCategories.Any()) && (exportedProducts == null || !exportedProducts.Any()))
            {
                var result = _searchService.Search(new SearchCriteria {
                    CatalogId = catalogId, GetAllCategories = true, Start = 0, Count = int.MaxValue, ResponseGroup = ResponseGroup.WithProducts
                });
                productIds = result.Products.Select(x => x.Id).ToList();
            }

            var products = _productService.GetByIds(productIds.Distinct().ToArray(), ItemResponseGroup.ItemLarge);

            foreach (var product in products)
            {
                retVal.Add(product);
                if (product.Variations != null)
                {
                    retVal.AddRange(product.Variations);
                }
            }

            return(retVal);
        }
        public IHttpActionResult BulkCreateLinks(webModel.BulkLinkCreationRequest creationRequest)
        {
            if (creationRequest.CatalogId.IsNullOrEmpty())
            {
                throw new ArgumentException("Target catalog identifier should be specified.");
            }

            var  coreModelCriteria = creationRequest.SearchCriteria.ToCoreModel();
            bool haveProducts;

            do
            {
                var links = new List <webModel.ListEntryLink>();

                var searchResult = _searchService.Search(coreModelCriteria);

                var productLinks = searchResult
                                   .Products
                                   .Select(x => new webModel.ListEntryLink
                {
                    CatalogId     = creationRequest.CatalogId,
                    ListEntryType = webModel.ListEntryProduct.TypeName,
                    ListEntryId   = x.Id,
                    CategoryId    = creationRequest.CategoryId
                })
                                   .ToList();

                links.AddRange(productLinks);

                if (coreModelCriteria.ResponseGroup.HasFlag(coreModel.SearchResponseGroup.WithCategories))
                {
                    coreModelCriteria.ResponseGroup = coreModelCriteria.ResponseGroup & ~coreModel.SearchResponseGroup.WithCategories;

                    var categoryLinks = searchResult
                                        .Categories
                                        .Select(c => new webModel.ListEntryLink
                    {
                        CatalogId     = creationRequest.CatalogId,
                        ListEntryType = webModel.ListEntryCategory.TypeName,
                        ListEntryId   = c.Id,
                        CategoryId    = creationRequest.CategoryId
                    })
                                        .ToList();

                    links.AddRange(categoryLinks);
                }

                haveProducts = productLinks.Any();

                coreModelCriteria.Skip += coreModelCriteria.Take;

                CheckCurrentUserHasPermissionForObjects(CatalogPredefinedPermissions.Create, links.ToArray());

                InnerUpdateLinks(links.ToArray(), (x, y) => x.Links.Add(y));
            } while (haveProducts);

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public IHttpActionResult Search(SearchCriteria criteria)
        {
            var coreModelCriteria = criteria.ToCoreModel();

            ApplyRestrictionsForCurrentUser(coreModelCriteria);
            var serviceResult = _searchService.Search(coreModelCriteria);

            return(Ok(serviceResult.ToWebModel(_blobUrlResolver)));
        }
Пример #25
0
        private void SaveCategoryTree(coreModel.Catalog catalog, IEnumerable <CsvProduct> csvProducts, ExportImportProgressInfo progressInfo, Action <ExportImportProgressInfo> progressCallback)
        {
            var categories = new List <coreModel.Category>();

            progressInfo.ProcessedCount = 0;
            var cachedCategoryMap = new Dictionary <string, Category>();

            foreach (var csvProduct in csvProducts.Where(x => x.Category != null && !String.IsNullOrEmpty(x.Category.Path)))
            {
                var    outline = "";
                var    productCategoryNames = csvProduct.Category.Path.Split(_categoryDelimiters);
                string parentCategoryId     = null;
                foreach (var categoryName in productCategoryNames)
                {
                    outline += "\\" + categoryName;
                    Category category;
                    if (!cachedCategoryMap.TryGetValue(outline, out category))
                    {
                        var searchCriteria = new SearchCriteria
                        {
                            CatalogId     = catalog.Id,
                            CategoryId    = parentCategoryId,
                            ResponseGroup = SearchResponseGroup.WithCategories
                        };
                        category = _searchService.Search(searchCriteria).Categories.FirstOrDefault(x => x.Name == categoryName);
                    }

                    if (category == null)
                    {
                        category = _categoryService.Create(new coreModel.Category()
                        {
                            Name = categoryName, Code = categoryName.GenerateSlug(), CatalogId = catalog.Id, ParentId = parentCategoryId
                        });
                        //Raise notification each notifyCategorySizeLimit category
                        progressInfo.Description = string.Format("Creating categories: {0} created", ++progressInfo.ProcessedCount);
                        progressCallback(progressInfo);
                    }
                    csvProduct.CategoryId      = category.Id;
                    csvProduct.Category        = category;
                    parentCategoryId           = category.Id;
                    cachedCategoryMap[outline] = category;
                }
            }
        }
Пример #26
0
        public override void ResolveElementCounts(TreeNode <MenuItem> curNode, bool deep = false)
        {
            try
            {
                using (Services.Chronometer.Step("SiteMap.ResolveElementsCount() for {0}".FormatInvariant(curNode.Value.Text.EmptyNull())))
                {
                    // Perf: only resolve counts for categories in the current path.
                    while (curNode != null)
                    {
                        if (curNode.Children.Any(x => !x.Value.ElementsCount.HasValue))
                        {
                            lock (s_lock)
                            {
                                if (curNode.Children.Any(x => !x.Value.ElementsCount.HasValue))
                                {
                                    var nodes = deep ? curNode.SelectNodes(x => true, false) : curNode.Children.AsEnumerable();

                                    foreach (var node in nodes)
                                    {
                                        var categoryIds = new List <int>();

                                        if (_catalogSettings.ShowCategoryProductNumberIncludingSubcategories)
                                        {
                                            // Include subcategories
                                            node.Traverse(x =>
                                            {
                                                categoryIds.Add(x.Value.EntityId);
                                            }, true);
                                        }
                                        else
                                        {
                                            categoryIds.Add(node.Value.EntityId);
                                        }

                                        var context = new CatalogSearchQuery()
                                                      .VisibleOnly()
                                                      .VisibleIndividuallyOnly(true)
                                                      .WithCategoryIds(null, categoryIds.ToArray())
                                                      .HasStoreId(Services.StoreContext.CurrentStoreIdIfMultiStoreMode)
                                                      .BuildHits(false);

                                        node.Value.ElementsCount = _catalogSearchService.Search(context).TotalHitsCount;
                                    }
                                }
                            }
                        }

                        curNode = curNode.Parent;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
        public IHttpActionResult GetCatalogs()
        {
            var criteria = new moduleModel.SearchCriteria
            {
                ResponseGroup = moduleModel.ResponseGroup.WithCatalogs
            };
            var serviceResult = _searchService.Search(criteria);
            var retVal        = serviceResult.Catalogs.Select(x => x.ToWebModel()).ToArray();

            return(Ok(retVal));
        }
        public ActionResult InstantSearch(CatalogSearchQuery query)
        {
            if (string.IsNullOrWhiteSpace(query.Term) || query.Term.Length < _searchSettings.InstantSearchTermMinLength)
            {
                return(Content(string.Empty));
            }

            query
            .BuildFacetMap(false)
            .Slice(0, Math.Min(16, _searchSettings.InstantSearchNumberOfProducts))
            .SortBy(ProductSortingEnum.Relevance);

            var result = _catalogSearchService.Search(query);

            var model = new SearchResultModel(query)
            {
                SearchResult       = result,
                Term               = query.Term,
                TotalProductsCount = result.TotalHitsCount
            };

            var mappingSettings = _catalogHelper.GetBestFitProductSummaryMappingSettings(ProductSummaryViewMode.Mini, x =>
            {
                x.MapPrices           = false;
                x.MapShortDescription = true;
            });

            mappingSettings.MapPictures   = _searchSettings.ShowProductImagesInInstantSearch;
            mappingSettings.ThumbnailSize = _mediaSettings.ProductThumbPictureSizeOnProductDetailsPage;

            var summaryModel = _catalogHelper.MapProductSummaryModel(result.Hits, mappingSettings);

            // Add product hits
            model.TopProducts = summaryModel;

            // Add spell checker suggestions (if any)
            AddSpellCheckerSuggestionsToModel(result.SpellCheckerSuggestions, model);

            return(PartialView(model));
        }
Пример #29
0
        public IHttpActionResult GetProductByCode(string store, [FromUri] string code, [FromUri] coreModel.ItemResponseGroup responseGroup = coreModel.ItemResponseGroup.ItemLarge, string language = "en-us")
        {
            var searchCriteria = new SearchCriteria
            {
                ResponseGroup = ResponseGroup.WithProducts | ResponseGroup.WithVariations,
                Code          = code,
            };

            var result = _searchService.Search(searchCriteria);

            if (result.Products != null && result.Products.Any())
            {
                var products = InnerGetProductsByIds(new string[] { result.Products.First().Id }, responseGroup);
                var retVal   = products.FirstOrDefault();
                if (retVal != null)
                {
                    return(Ok(retVal));
                }
            }

            return(NotFound());
        }
Пример #30
0
        public IHttpActionResult GetCategoryByCode(string store, [FromUri] string code, string language = "en-us")
        {
            var catalog        = _storeService.GetById(store).Catalog;
            var searchCriteria = new SearchCriteria
            {
                ResponseGroup = ResponseGroup.WithCategories,
                Code          = code,
                CatalogId     = catalog
            };

            var result = _searchService.Search(searchCriteria);

            if (result.Categories != null && result.Categories.Any())
            {
                var category = _categoryService.GetById(result.Categories.First().Id);
                if (category != null)
                {
                    return(Ok(category.ToWebModel()));
                }
            }

            return(NotFound());
        }