private Facet(Models.Facet item) { FacetField = item.FacetField; Name = item.FacetField; FacetResults = FacetField == "area" ? FacetValue.OrganizationCreateFromList(item.FacetResults) : FacetValue.CreateFromList(item.FacetResults); NameTranslated = UI.ResourceManager.GetString("Facet_" + item.FacetField); }
public virtual async Task <IHttpActionResult> SuggestCategories(AutoCompleteSearchViewModel request, int limit = MAXIMUM_CATEGORIES_SUGGESTIONS) { string language = ComposerContext.CultureInfo.Name; string searchTerm = request.Query.Trim().ToLower(); List <Category> categories = await SearchViewService.GetAllCategories(); List <Facet> categoryCounts = await SearchViewService.GetCategoryProductCounts(language); List <CategorySuggestionViewModel> categorySuggestionList = new List <CategorySuggestionViewModel>(); foreach (var category in categories) { if (!category.DisplayName.TryGetValue(language, out string displayName)) { continue; } // Find the parents of the category List <Category> parents = new List <Category>(); Category currentNode = category; while (!string.IsNullOrWhiteSpace(currentNode.PrimaryParentCategoryId) && currentNode.PrimaryParentCategoryId != RootCategoryId) { Category parent = categories.Single((cat) => cat.Id == currentNode.PrimaryParentCategoryId); parents.Add(parent); currentNode = parent; } parents.Reverse(); FacetValue categoryCount = categoryCounts .Where((facet) => int.TryParse(CategoryFieldName.Match(facet.FieldName).Groups[1].Value, out int n) && parents.Count == n - 1) .FirstOrDefault()? .Values .Where((facetValue) => facetValue.Value == category.DisplayName[language]).SingleOrDefault(); if (categoryCount != null) { categorySuggestionList.Add(new CategorySuggestionViewModel { DisplayName = displayName, Parents = parents.Select((parent) => parent.DisplayName[language]).ToList(), Quantity = categoryCount.Count }); } } ; List <CategorySuggestionViewModel> finalSuggestions = categorySuggestionList .OrderByDescending((category) => category.Quantity) .Where((suggestion) => suggestion.DisplayName.ToLower().Contains(searchTerm)) .Take(limit) .ToList(); CategorySuggestionsViewModel vm = new CategorySuggestionsViewModel { Suggestions = finalSuggestions }; return(Ok(vm)); }
private void ApplyFacetValueHit(FacetValue facetValue, Facet value, int docId, ParsedRange parsedRange, IndexReader indexReader) { facetValue.Hits++; if ( IndexQuery.IsDistinct == false && (value.Aggregation == FacetAggregation.Count || value.Aggregation == FacetAggregation.None) ) { return; } FacetValueState set; if (matches.TryGetValue(facetValue, out set) == false) { matches[facetValue] = set = new FacetValueState { Docs = new HashSet <int>(), Facet = value, Range = parsedRange }; } if (IndexQuery.IsDistinct) { if (IndexQuery.FieldsToFetch.Length == 0) { throw new InvalidOperationException("Cannot process distinct facet query without specifying which fields to distinct upon."); } if (set.AlreadySeen == null) { set.AlreadySeen = new HashSet <StringCollectionValue>(); } var document = indexReader.Document(docId); var fields = new List <string>(); foreach (var fieldName in IndexQuery.FieldsToFetch) { foreach (var field in document.GetFields(fieldName)) { if (field.StringValue == null) { continue; } fields.Add(field.StringValue); } } if (fields.Count == 0) { throw new InvalidOperationException("Cannot apply distinct facet on [" + string.Join(", ", IndexQuery.FieldsToFetch) + "], did you forget to store them in the index? "); } if (set.AlreadySeen.Add(new StringCollectionValue(fields)) == false) { facetValue.Hits--; // already seen, cancel this return; } } set.Docs.Add(docId); }
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell(RefineCell.Key, indexPath) as RefineCell; PresentationFacetResult facets = _presentationFacetResultList[(int)indexPath.Section]; FacetValue aFacetValue = facets.ListFacetValues[(int)indexPath.Row]; cell.label.Text = aFacetValue.ValueName + "(" + aFacetValue.ValueCount + ")"; // If ValueUnChecked is not null that means filter is selected. if (string.IsNullOrEmpty(aFacetValue.ValueChecked) || aFacetValue.isSelected) { //cell.imageView.Image = UIImage.FromBundle("arrow-down-icon.png"); cell.label.TextColor = UIColor.Red; cell.checkBoxButton.SetImage(UIImage.FromBundle("check.png"), UIControlState.Normal); } else { //cell.imageView.Image = UIImage.FromBundle("arrow-down.png"); cell.label.TextColor = UIColor.DarkGray; cell.checkBoxButton.SetImage(UIImage.FromBundle("uncheck.png"), UIControlState.Normal); } return(cell); }
public void Initialize(FacetValue queryFacet) { Assert.ArgumentNotNull(queryFacet, nameof(queryFacet)); this.Name = queryFacet.Name; this.AggregateCount = queryFacet.AggregateCount; }
private static List <Models.API.FacetResult> BuildFacets(ISearchResults searchResult, Tab tab) { var facetResults = new List <Models.API.FacetResult>(); foreach (var facetConfiguration in tab.Facets) { ISearchResultFacet facet = searchResult.Facets.Where(x => x.Definition.FieldName == facetConfiguration.FieldName).FirstOrDefault(); if (facet != null) { FacetResult facetResult = new FacetResult(); facetResult.Values = new List <FacetValue>(); facetResult.Name = facetConfiguration.Name; facetResult.FieldName = facetConfiguration.FieldName; foreach (var facetValue in facet.Values) { FacetValue facetResultValue = new FacetValue(); facetResultValue.Count = facetValue.Count; facetResultValue.Name = facetValue.Value.ToString(); facetResultValue.Selected = facetValue.Selected; facetResultValue.Value = facetValue.Value.ToString(); facetResult.Values.Add(facetResultValue); } facetResult = SortFacetValues(facetConfiguration, facetResult); facetResults.Add(facetResult); } } return(facetResults); }
public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) { var cell = tableView.CellAt(indexPath) as RefineCell; PresentationFacetResult facets = _presentationFacetResultList[(int)indexPath.Section]; FacetValue aFacetValue = facets.ListFacetValues[(int)indexPath.Row]; string filterUrl = (!string.IsNullOrEmpty(aFacetValue.ValueChecked)) ? aFacetValue.ValueChecked : aFacetValue.ValueUnChecked; bool isSelected = !aFacetValue.isSelected; if (isSelected) { //filterUrl = aFacetValue.ValueChecked; cell.checkBoxButton.SetImage(UIImage.FromBundle("check.png"), UIControlState.Normal); cell.label.TextColor = UIColor.Red; } else { //filterUrl = aFacetValue.ValueUnChecked; cell.checkBoxButton.SetImage(UIImage.FromBundle("uncheck.png"), UIControlState.Normal); cell.label.TextColor = UIColor.DarkGray; } Constants.FilterURL = Constants.JobBaseAddress + filterUrl; tableView.DeselectRow(indexPath, true); aFacetValue.isSelected = isSelected; _refineViewController.GetJobSearchData(); }
public FacetValueViewModel(FacetValue facetValue) { FacetName = facetValue.FacetName; ValueName = facetValue.ValueName; Value = facetValue.Value; Count = facetValue.Count; }
public virtual IList <FacetValue> ProcessFacetValues(FacetItem facet, IList <Sitecore.ContentSearch.Linq.FacetValue> options, IEnumerable <string> selected) { options = options ?? new List <Sitecore.ContentSearch.Linq.FacetValue>(); selected = selected ?? Enumerable.Empty <string>(); var values = new List <FacetValue>(); foreach (var option in options) { var value = new FacetValue() { Name = option.Name, Count = option.AggregateCount, IsSelected = selected.Contains(option.Name) }; values.Add(value); } values = SortFacetValues(values, facet.SortBy); if (facet.LimitValues > 0) { values = values.Take(facet.LimitValues).ToList(); } return(values); }
public void AddDefault(string range) { Any = true; _values[Default] = new FacetValue { Range = range }; }
private void CheckFacetCount(int expectedCount, FacetValue facets) { if (expectedCount > 0) { Assert.NotNull(facets); Assert.Equal(expectedCount, facets.Count); } }
public async Task <IActionResult> GetResultCounts(HttpRequest request) { string json = await request.GetRawBodyStringAsync(); TestScenariosResultsCountsRequestModel requestModel = JsonConvert.DeserializeObject <TestScenariosResultsCountsRequestModel>(json); if (requestModel == null || requestModel.TestScenarioIds.IsNullOrEmpty()) { _logger.Error("Null or empty test scenario ids provided"); return(new BadRequestObjectResult("Null or empty test scenario ids provided")); } ConcurrentBag <TestScenarioResultCounts> resultCounts = new ConcurrentBag <TestScenarioResultCounts>(); Parallel.ForEach(requestModel.TestScenarioIds, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, testScenarioId => { SearchModel searchModel = new SearchModel { IncludeFacets = true, Top = 1, PageNumber = 1, OverrideFacetFields = new string[] { "testResult" }, Filters = new Dictionary <string, string[]> { { "testScenarioId", new[] { testScenarioId } } } }; TestScenarioSearchResults result = _testResultsService.SearchTestScenarioResults(searchModel).Result; if (result != null && !result.Results.IsNullOrEmpty()) { Facet facet = result.Facets?.FirstOrDefault(m => m.Name == "testResult"); if (facet != null) { FacetValue passedValue = facet.FacetValues.FirstOrDefault(m => m.Name == "Passed"); FacetValue failedValue = facet.FacetValues.FirstOrDefault(m => m.Name == "Failed"); FacetValue ignoredValue = facet.FacetValues.FirstOrDefault(m => m.Name == "Ignored"); resultCounts.Add(new TestScenarioResultCounts { TestScenarioName = result.Results.First().TestScenarioName, TestScenarioId = testScenarioId, Passed = passedValue != null ? passedValue.Count : 0, Failed = failedValue != null ? failedValue.Count : 0, Ignored = ignoredValue != null ? ignoredValue.Count : 0, LastUpdatedDate = result.Results.First().LastUpdatedDate }); } } }); return(new OkObjectResult(resultCounts)); }
public void Rendering_Should_Return_Empty_FacetList_If_SearchLibrary_Returns_None() { // Arrange IList <Facet> facetsForQuerying = new List <Facet>(); var facetValues = new List <FacetValue>(); facetValues.Add(new FacetValue() { Value = "122", Hits = 2 }); facetValues.Add(new FacetValue() { Value = "127", Hits = 0 }); facetsForQuerying.Add(new Facet() { Name = "Price", DisplayName = "Price", CultureCode = "en-GB", FacetValues = facetValues }); _catalogContext.CurrentCategory = Substitute.For <Category>(); var returnedFacets = new List <Facet>(); var facetValue = new FacetValue() { Value = "177", Hits = 4 }; var facetValueList = new List <FacetValue>(); facetValueList.Add(facetValue); returnedFacets.Add(new Facet() { Name = "Price", DisplayName = "Price", CultureCode = "en-GB", FacetValues = facetValueList }); _searchLibraryInternal.GetFacetsFor(_catalogContext.CurrentCategory, facetsForQuerying).Returns(new List <Facet>()); // Act var result = _controller.Rendering(facetsForQuerying); // Assert var viewResult = result as ViewResult; var model = viewResult != null ? viewResult.Model as FacetsRenderingViewModel : null; Assert.NotNull(viewResult); Assert.NotNull(model); Assert.Empty(model.Facets); }
/// <summary> /// Checks to make sure a facet value is valid for use /// </summary> /// <param name="value">The facet value to check</param> /// <returns>Returns True if valid and False otherwise</returns> public static bool IsValid(this FacetValue value) { if (value.AggregateCount > 0) { return(true); } return(false); }
private IEnumerable <Model.Facet> ProcessFacets(IQueryable <App> query, string category, string country) { var facetResults = query.ToFacets("facets/AppsFacets"); var facets = new List <Model.Facet>(); foreach (var facetResult in facetResults.Results) { if (facetResult.Value.Values.Count <= 1) { continue; } if (string.IsNullOrEmpty(category)) { if (facetResult.Key == "Subcategory") { continue; } } if (!string.IsNullOrEmpty(country)) { if (facetResult.Key == "Country") { continue; } } if (facetResult.Value.Values.All(fv => fv.Hits == 1)) { continue; } var title = facetResult.Key; var facet = new Model.Facet { Title = title }; foreach (var facetValue in facetResult.Value.Values.OrderBy(x => x.Range)) { var value = new FacetValue { Range = facetValue.Range, Hits = facetValue.Hits }; if (facetValue.Range == "EMPTY_STRING") { facet.Values.Insert(0, value); } else { facet.Values.Add(value); } } facets.Add(facet); } return(facets); }
public void Rendering_Should_Return_Valid_ViewModel_With_Non_Null_Attributes() { // Arrange IList <Facet> facetsForQuerying = new List <Facet>(); var facetValues = new List <FacetValue>(); facetValues.Add(new FacetValue { Value = "122", Count = 2 }); facetValues.Add(new FacetValue { Value = "127", Count = 0 }); facetsForQuerying.Add(new Facet { Name = "Price", DisplayName = "Price", FacetValues = facetValues }); _catalogContext.CurrentCategory = Substitute.For <Category>(); var returnedFacets = new List <Facet>(); var facetValue = new FacetValue { Value = "177", Count = 4 }; var facetValueList = new List <FacetValue>(); facetValueList.Add(facetValue); returnedFacets.Add(new Facet { Name = "Price", DisplayName = "Price", FacetValues = facetValueList }); _catalogLibrary.GetFacets(Guid.Empty, new FacetDictionary()).ReturnsForAnyArgs(returnedFacets); // Act var result = _controller.Rendering(facetsForQuerying); // Assert var viewResult = result as ViewResult; var model = viewResult != null ? viewResult.Model as FacetsRenderingViewModel : null; Assert.NotNull(viewResult); Assert.NotNull(model); Assert.NotEmpty(model.Facets); }
public static CommonEntries.FacetValue Convert(FacetValue facetValue) { var result = new CommonEntries.FacetValue { Key = facetValue.Key, DisplayName = facetValue.DisplayName }; return(result); }
public override bool Equals(object obj) { if (obj == null || (obj != null && !(obj is FacetValueViewModel))) { return(false); } else { var fv = obj as FacetValueViewModel; return(FacetValue.GetConstraintTerm(FacetName, ValueName) == FacetValue.GetConstraintTerm(fv.FacetName, fv.ValueName)); } }
private static void ApplyAggregation(Facet facet, FacetValue value, ArraySegment <int> docsInQuery, IndexReader indexReader, int docBase, IState state) { var name = facet.AggregationField; var rangeType = FieldUtil.GetRangeTypeFromFieldName(name); if (rangeType == RangeType.None) { name = FieldUtil.ApplyRangeSuffixIfNecessary(facet.AggregationField, RangeType.Double); rangeType = RangeType.Double; } long[] longs = null; double[] doubles = null; switch (rangeType) { case RangeType.Long: longs = FieldCache_Fields.DEFAULT.GetLongs(indexReader, name, state); break; case RangeType.Double: doubles = FieldCache_Fields.DEFAULT.GetDoubles(indexReader, name, state); break; default: throw new InvalidOperationException("Invalid range type for " + facet.Name + ", don't know how to handle " + rangeType); } for (int index = 0; index < docsInQuery.Count; index++) { var doc = docsInQuery.Array[index]; var currentVal = rangeType == RangeType.Long ? longs[doc - docBase] : doubles[doc - docBase]; if ((facet.Aggregation & FacetAggregation.Max) == FacetAggregation.Max) { value.Max = Math.Max(value.Max ?? double.MinValue, currentVal); } if ((facet.Aggregation & FacetAggregation.Min) == FacetAggregation.Min) { value.Min = Math.Min(value.Min ?? double.MaxValue, currentVal); } if ((facet.Aggregation & FacetAggregation.Sum) == FacetAggregation.Sum) { value.Sum = currentVal + (value.Sum ?? 0d); } if ((facet.Aggregation & FacetAggregation.Average) == FacetAggregation.Average) { value.Average = currentVal + (value.Average ?? 0d); } } }
public void rptCheckBoxes_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) { return; } FacetValue currentItem = (FacetValue)e.Item.DataItem; Button btnCheckBox = (Button)e.Item.FindControl("btnCheckBox"); btnCheckBox.Attributes.Add("queryStringKey", _currentQueryStringKey); btnCheckBox.Attributes.Add("queryStringValue", currentItem.Value); btnCheckBox.Text = currentItem.Value + " (" + currentItem.Hits + ")"; _anyFacetHits = true; }
public void Add(FacetAggregationField field, string range) { if (_legacy) { if (Any) { return; } AddDefault(range); return; } Any = true; _values[field] = new FacetValue { Range = range, Name = string.IsNullOrWhiteSpace(field.DisplayName) ? field.Name : field.DisplayName }; }
private void HandleFacets(string field, string value, Dictionary <string, Dictionary <string, FacetValue> > facetsByName, int doc) { var facets = Facets.Values.Where(facet => facet.Name == field); foreach (var facet in facets) { switch (facet.Mode) { case FacetMode.Default: var facetValues = facetsByName.GetOrAdd(facet.DisplayName); FacetValue existing; if (facetValues.TryGetValue(value, out existing) == false) { existing = new FacetValue { Range = GetRangeName(field, value) }; facetValues[value] = existing; } ApplyFacetValueHit(existing, facet, doc, null); break; case FacetMode.Ranges: List <ParsedRange> list; if (Ranges.TryGetValue(field, out list)) { for (int i = 0; i < list.Count; i++) { var parsedRange = list[i]; if (parsedRange.IsMatch(value)) { var facetValue = Results.Results[field].Values[i]; ApplyFacetValueHit(facetValue, facet, doc, parsedRange); } } } break; default: throw new ArgumentOutOfRangeException(); } } }
/// <summary> /// Gets the facet. /// </summary> /// <param name="facetValue">The name of the facet (Sitecore template ID).</param> /// <param name="searchFacetCategory">The FacetCategory after searching on the searchtext. This contains the resultcount per facet.</param> /// <param name="searchResultsCategory">The FacetCategory after filtering on template. This is used to determine which facets are selected.</param> /// <returns></returns> internal ContentSearchFacet GetFacet(FacetValue facetValue, FacetCategory searchFacetCategory, FacetCategory searchResultsCategory) { // A FacetValue doesn't contain a usable description of the facet, just the template ID (as a string). // A lookup will be done to get a usable desciption for the facet. var templateId = facetValue.Name; var searchFacetValue = searchFacetCategory.Values.FirstOrDefault(f => f.Name == facetValue.Name); var searchResultFacetValue = searchResultsCategory.Values.FirstOrDefault(f => f.Name == facetValue.Name); var facet = new ContentSearchFacet { ResultCount = searchFacetValue != null ? searchFacetValue.AggregateCount : 0, IsSelected = searchResultFacetValue != null, TemplateId = templateId, Name = GetFacetName(templateId) }; return(facet); }
private void HandleFacets(List <ReaderFacetInfo> returnedReaders, KeyValuePair <string, FacetedQueryParser.FacetResult> result, Dictionary <string, Dictionary <string, FacetValue> > facetsByName, CancellationToken token) { foreach (var readerFacetInfo in returnedReaders) { var termsForField = IndexedTerms.GetTermsAndDocumentsFor(readerFacetInfo.Reader, readerFacetInfo.DocBase, result.Value.AggregateBy, _indexName, _state); if (facetsByName.TryGetValue(result.Key, out Dictionary <string, FacetValue> facetValues) == false) { facetsByName[result.Key] = facetValues = new Dictionary <string, FacetValue>(); } foreach (var kvp in termsForField) { token.ThrowIfCancellationRequested(); var needToApplyAggregation = result.Value.Aggregations.Count > 0; var intersectedDocuments = GetIntersectedDocuments(new ArraySegment <int>(kvp.Value), readerFacetInfo.Results, needToApplyAggregation); var intersectCount = intersectedDocuments.Count; if (intersectCount == 0) { continue; } if (facetValues.TryGetValue(kvp.Key, out FacetValue facetValue) == false) { facetValue = new FacetValue { Range = FacetedQueryHelper.GetRangeName(result.Value.AggregateBy, kvp.Key) }; facetValues.Add(kvp.Key, facetValue); } facetValue.Count += intersectCount; if (needToApplyAggregation) { var docsInQuery = new ArraySegment <int>(intersectedDocuments.Documents, 0, intersectedDocuments.Count); ApplyAggregation(result.Value.Aggregations, facetValue, docsInQuery, readerFacetInfo.Reader, readerFacetInfo.DocBase, _state); } } } }
private void ApplyFacetValueHit(FacetValue facetValue, Facet value, int docId, ParsedRange parsedRange) { facetValue.Hits++; if (value.Aggregation == FacetAggregation.Count || value.Aggregation == FacetAggregation.None) { return; } FacetValueState set; if (matches.TryGetValue(facetValue, out set) == false) { matches[facetValue] = set = new FacetValueState { Docs = new HashSet <int>(), Facet = value, Range = parsedRange }; } set.Docs.Add(docId); }
private void ApplyAggregation(Facet facet, FacetValue value, double currentVal) { if (facet.Aggregation.HasFlag(FacetAggregation.Max)) { value.Max = Math.Max(value.Max ?? Double.MinValue, currentVal); } if (facet.Aggregation.HasFlag(FacetAggregation.Min)) { value.Min = Math.Min(value.Min ?? Double.MaxValue, currentVal); } if (facet.Aggregation.HasFlag(FacetAggregation.Sum)) { value.Sum = currentVal + (value.Sum ?? 0d); } if (facet.Aggregation.HasFlag(FacetAggregation.Average)) { value.Average = currentVal + (value.Average ?? 0d); } }
protected virtual List <FacetValue> GetFacetValues(Overture.ServiceModel.Search.Facet facetResult, FacetSetting setting, IReadOnlyCollection <string> selectedFacetValues, CultureInfo cultureInfo) { var promotedValues = setting.PromotedValues; /*Expected to be already sorted*/ var facetValues = facetResult.Values .Select(resultFacetValue => { var facetValue = new FacetValue { Title = FacetLocalizationProvider.GetFormattedFacetValueTitle(facetResult.FieldName, resultFacetValue.Value, cultureInfo), Value = resultFacetValue.Value, Quantity = resultFacetValue.Count, IsSelected = selectedFacetValues.Contains(resultFacetValue.Value), MinimumValue = resultFacetValue.MinimumValue, MaximumValue = resultFacetValue.MaximumValue }; var promotedValueSetting = promotedValues.FirstOrDefault( value => value.Title.Equals(resultFacetValue.Value, StringComparison.OrdinalIgnoreCase)); if (promotedValueSetting != null) { facetValue.IsPromoted = true; facetValue.PromotionSortWeight = promotedValueSetting.SortWeight; } return(facetValue); }) .ToList(); facetValues = facetValues.OrderByDescending(x => x.IsSelected).ToList(); return(facetValues); }
private bool IsFacetValueSelected(FacetCategory resultCategory, IQuery query, FacetValue resultValue) { if (query.Facets == null) { return(false); } return(query.Facets.Any(f => f.Key.Equals(resultCategory.Name, StringComparison.InvariantCultureIgnoreCase) && f.Value.Any(v => v.Equals(resultValue.Name, StringComparison.InvariantCultureIgnoreCase)))); }
protected virtual IDictionary <string, FacetGroup> GetFacets(CatalogSearchQuery searchQuery, int totalHits) { var result = new Dictionary <string, FacetGroup>(); var storeId = searchQuery.StoreId ?? _services.StoreContext.CurrentStore.Id; var languageId = searchQuery.LanguageId ?? _services.WorkContext.WorkingLanguage.Id; foreach (var key in searchQuery.FacetDescriptors.Keys) { var descriptor = searchQuery.FacetDescriptors[key]; var facets = new List <Facet>(); var kind = FacetGroup.GetKindByKey("Catalog", key); switch (kind) { case FacetGroupKind.Category: case FacetGroupKind.Brand: case FacetGroupKind.DeliveryTime: case FacetGroupKind.Rating: case FacetGroupKind.Price: if (totalHits == 0 && !descriptor.Values.Any(x => x.IsSelected)) { continue; } break; } if (kind == FacetGroupKind.Category) { var categoryTree = _categoryService.GetCategoryTree(0, false, storeId); var categories = categoryTree.Flatten(false); if (descriptor.MaxChoicesCount > 0) { categories = categories.Take(descriptor.MaxChoicesCount); } var nameQuery = _localizedPropertyRepository.TableUntracked .Where(x => x.LocaleKeyGroup == "Category" && x.LocaleKey == "Name" && x.LanguageId == languageId); var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); foreach (var category in categories) { names.TryGetValue(category.Id, out var label); facets.Add(new Facet(new FacetValue(category.Id, IndexTypeCode.Int32) { IsSelected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(category.Id)), Label = label.HasValue() ? label : category.Name, DisplayOrder = category.DisplayOrder })); } } else if (kind == FacetGroupKind.Brand) { var manufacturers = _manufacturerService.GetAllManufacturers(null, storeId); if (descriptor.MaxChoicesCount > 0) { manufacturers = manufacturers.Take(descriptor.MaxChoicesCount).ToList(); } var nameQuery = _localizedPropertyRepository.TableUntracked .Where(x => x.LocaleKeyGroup == "Manufacturer" && x.LocaleKey == "Name" && x.LanguageId == languageId); var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); foreach (var manu in manufacturers) { names.TryGetValue(manu.Id, out var label); facets.Add(new Facet(new FacetValue(manu.Id, IndexTypeCode.Int32) { IsSelected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(manu.Id)), Label = label.HasValue() ? label : manu.Name, DisplayOrder = manu.DisplayOrder })); } } else if (kind == FacetGroupKind.DeliveryTime) { var deliveryTimes = _deliveryTimeService.GetAllDeliveryTimes(); var nameQuery = _localizedPropertyRepository.TableUntracked .Where(x => x.LocaleKeyGroup == "DeliveryTime" && x.LocaleKey == "Name" && x.LanguageId == languageId); var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); foreach (var deliveryTime in deliveryTimes) { if (descriptor.MaxChoicesCount > 0 && facets.Count >= descriptor.MaxChoicesCount) { break; } names.TryGetValue(deliveryTime.Id, out var label); facets.Add(new Facet(new FacetValue(deliveryTime.Id, IndexTypeCode.Int32) { IsSelected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(deliveryTime.Id)), Label = label.HasValue() ? label : deliveryTime.Name, DisplayOrder = deliveryTime.DisplayOrder })); } } else if (kind == FacetGroupKind.Price) { var count = 0; var hasActivePredefinedFacet = false; var minPrice = _productRepository.Table.Where(x => x.Published && !x.Deleted && !x.IsSystemProduct).Min(x => (double)x.Price); var maxPrice = _productRepository.Table.Where(x => x.Published && !x.Deleted && !x.IsSystemProduct).Max(x => (double)x.Price); minPrice = FacetUtility.MakePriceEven(minPrice); maxPrice = FacetUtility.MakePriceEven(maxPrice); for (var i = 0; i < _priceThresholds.Length; ++i) { if (descriptor.MaxChoicesCount > 0 && facets.Count >= descriptor.MaxChoicesCount) { break; } var price = _priceThresholds[i]; if (price < minPrice) { continue; } if (price >= maxPrice) { i = int.MaxValue - 1; } var selected = descriptor.Values.Any(x => x.IsSelected && x.Value == null && x.UpperValue != null && (double)x.UpperValue == price); if (selected) { hasActivePredefinedFacet = true; } facets.Add(new Facet(new FacetValue(null, price, IndexTypeCode.Double, false, true) { DisplayOrder = ++count, IsSelected = selected })); } // Add facet for custom price range. var priceDescriptorValue = descriptor.Values.FirstOrDefault(); var customPriceFacetValue = new FacetValue( priceDescriptorValue != null && !hasActivePredefinedFacet ? priceDescriptorValue.Value : null, priceDescriptorValue != null && !hasActivePredefinedFacet ? priceDescriptorValue.UpperValue : null, IndexTypeCode.Double, true, true); customPriceFacetValue.IsSelected = customPriceFacetValue.Value != null || customPriceFacetValue.UpperValue != null; if (!(totalHits == 0 && !customPriceFacetValue.IsSelected)) { facets.Insert(0, new Facet("custom", customPriceFacetValue)); } } else if (kind == FacetGroupKind.Rating) { foreach (var rating in FacetUtility.GetRatings()) { var newFacet = new Facet(rating); newFacet.Value.IsSelected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(rating.Value)); facets.Add(newFacet); } } else if (kind == FacetGroupKind.Availability || kind == FacetGroupKind.NewArrivals) { var value = descriptor.Values.FirstOrDefault(); if (value != null) { if (kind == FacetGroupKind.NewArrivals && totalHits == 0 && !value.IsSelected) { continue; } var newValue = value.Clone(); newValue.Value = true; newValue.TypeCode = IndexTypeCode.Boolean; newValue.IsRange = false; newValue.IsSelected = value.IsSelected; facets.Add(new Facet(newValue)); } } if (facets.Any(x => x.Published)) { //facets.Each(x => $"{key} {x.Value.ToString()}".Dump()); result.Add(key, new FacetGroup( "Catalog", key, descriptor.Label, descriptor.IsMultiSelect, false, descriptor.DisplayOrder, facets.OrderBy(descriptor))); } } return(result); }
protected virtual IDictionary <string, FacetGroup> GetFacets(CatalogSearchQuery searchQuery, int totalHits) { var result = new Dictionary <string, FacetGroup>(); var languageId = searchQuery.LanguageId ?? _services.WorkContext.WorkingLanguage.Id; foreach (var key in searchQuery.FacetDescriptors.Keys) { var descriptor = searchQuery.FacetDescriptors[key]; var facets = new List <Facet>(); var kind = FacetGroup.GetKindByKey(key); if (kind == FacetGroupKind.Category) { #region Category // order by product count var categoryQuery = from c in _categoryRepository.TableUntracked where !c.Deleted && c.Published join pc in _productCategoryRepository.TableUntracked on c.Id equals pc.CategoryId into pcm from pc in pcm.DefaultIfEmpty() group c by c.Id into grp orderby grp.Count() descending select new { Id = grp.FirstOrDefault().Id, Name = grp.FirstOrDefault().Name, DisplayOrder = grp.FirstOrDefault().DisplayOrder }; if (descriptor.MaxChoicesCount > 0) { categoryQuery = categoryQuery.Take(descriptor.MaxChoicesCount); } var categories = categoryQuery.ToList(); var nameQuery = _localizedPropertyRepository.TableUntracked .Where(x => x.LocaleKeyGroup == "Category" && x.LocaleKey == "Name" && x.LanguageId == languageId); var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); foreach (var category in categories) { var selected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(category.Id)); if (totalHits == 0 && !selected) { continue; } string label = null; names.TryGetValue(category.Id, out label); facets.Add(new Facet(new FacetValue(category.Id, IndexTypeCode.Int32) { IsSelected = selected, Label = label.HasValue() ? label : category.Name, DisplayOrder = category.DisplayOrder })); } #endregion } else if (kind == FacetGroupKind.Brand) { #region Brand // order by product count var manufacturerQuery = from m in _manufacturerRepository.TableUntracked where !m.Deleted && m.Published join pm in _productManufacturerRepository.TableUntracked on m.Id equals pm.ManufacturerId into pmm from pm in pmm.DefaultIfEmpty() group m by m.Id into grp orderby grp.Count() descending select new { Id = grp.FirstOrDefault().Id, Name = grp.FirstOrDefault().Name, DisplayOrder = grp.FirstOrDefault().DisplayOrder }; if (descriptor.MaxChoicesCount > 0) { manufacturerQuery = manufacturerQuery.Take(descriptor.MaxChoicesCount); } var manufacturers = manufacturerQuery.ToList(); var nameQuery = _localizedPropertyRepository.TableUntracked .Where(x => x.LocaleKeyGroup == "Manufacturer" && x.LocaleKey == "Name" && x.LanguageId == languageId); var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); foreach (var manu in manufacturers) { var selected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(manu.Id)); if (totalHits == 0 && !selected) { continue; } string label = null; names.TryGetValue(manu.Id, out label); facets.Add(new Facet(new FacetValue(manu.Id, IndexTypeCode.Int32) { IsSelected = selected, Label = label.HasValue() ? label : manu.Name, DisplayOrder = manu.DisplayOrder })); } #endregion } else if (kind == FacetGroupKind.DeliveryTime) { #region Delivery time var deliveryTimes = _deliveryTimeService.GetAllDeliveryTimes(); var nameQuery = _localizedPropertyRepository.TableUntracked .Where(x => x.LocaleKeyGroup == "DeliveryTime" && x.LocaleKey == "Name" && x.LanguageId == languageId); var names = nameQuery.ToList().ToDictionarySafe(x => x.EntityId, x => x.LocaleValue); foreach (var deliveryTime in deliveryTimes) { if (descriptor.MaxChoicesCount > 0 && facets.Count >= descriptor.MaxChoicesCount) { break; } var selected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(deliveryTime.Id)); if (totalHits == 0 && !selected) { continue; } string label = null; names.TryGetValue(deliveryTime.Id, out label); facets.Add(new Facet(new FacetValue(deliveryTime.Id, IndexTypeCode.Int32) { IsSelected = selected, Label = label.HasValue() ? label : deliveryTime.Name, DisplayOrder = deliveryTime.DisplayOrder })); } #endregion } else if (kind == FacetGroupKind.Price) { #region Price var count = 0; var hasActivePredefinedFacet = false; var minPrice = _productRepository.Table.Where(x => !x.Deleted && x.Published).Min(x => (double)x.Price); var maxPrice = _productRepository.Table.Where(x => !x.Deleted && x.Published).Max(x => (double)x.Price); minPrice = FacetUtility.MakePriceEven(minPrice); maxPrice = FacetUtility.MakePriceEven(maxPrice); for (var i = 0; i < _priceThresholds.Length; ++i) { if (descriptor.MaxChoicesCount > 0 && facets.Count >= descriptor.MaxChoicesCount) { break; } var price = _priceThresholds[i]; if (price < minPrice) { continue; } if (price >= maxPrice) { i = int.MaxValue - 1; } var selected = descriptor.Values.Any(x => x.IsSelected && x.Value == null && x.UpperValue != null && (double)x.UpperValue == price); if (totalHits == 0 && !selected) { continue; } if (selected) { hasActivePredefinedFacet = true; } facets.Add(new Facet(new FacetValue(null, price, IndexTypeCode.Double, false, true) { DisplayOrder = ++count, IsSelected = selected })); } // Add facet for custom price range. var priceDescriptorValue = descriptor.Values.FirstOrDefault(); var customPriceFacetValue = new FacetValue( priceDescriptorValue != null && !hasActivePredefinedFacet ? priceDescriptorValue.Value : null, priceDescriptorValue != null && !hasActivePredefinedFacet ? priceDescriptorValue.UpperValue : null, IndexTypeCode.Double, true, true); customPriceFacetValue.IsSelected = customPriceFacetValue.Value != null || customPriceFacetValue.UpperValue != null; if (!(totalHits == 0 && !customPriceFacetValue.IsSelected)) { facets.Insert(0, new Facet("custom", customPriceFacetValue)); } #endregion } else if (kind == FacetGroupKind.Rating) { if (totalHits == 0 && !descriptor.Values.Any(x => x.IsSelected)) { continue; } foreach (var rating in FacetUtility.GetRatings()) { var newFacet = new Facet(rating); newFacet.Value.IsSelected = descriptor.Values.Any(x => x.IsSelected && x.Value.Equals(rating.Value)); facets.Add(newFacet); } } else if (kind == FacetGroupKind.Availability || kind == FacetGroupKind.NewArrivals) { var value = descriptor.Values.FirstOrDefault(); if (value != null && !(totalHits == 0 && !value.IsSelected)) { var newValue = value.Clone(); newValue.Value = true; newValue.TypeCode = IndexTypeCode.Boolean; newValue.IsRange = false; newValue.IsSelected = value.IsSelected; facets.Add(new Facet(newValue)); } } if (facets.Any(x => x.Published)) { //facets.Each(x => $"{key} {x.Value.ToString()}".Dump()); result.Add(key, new FacetGroup( key, descriptor.Label, descriptor.IsMultiSelect, descriptor.DisplayOrder, facets.OrderBy(descriptor))); } } return(result); }