Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Refactoring - use repository extensions (SearchProductsQuery)
KrzysztofPajakdeea91721304
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.csindex 3415cb902..44fbb907a 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs@@ -5,8 +5,6 @@ using Grand.Domain.Customers;using Grand.Domain.Data;using Grand.SharedKernel.Extensions;using MediatR;-using MongoDB.Bson;-using MongoDB.Driver;using System;using System.Collections.Generic;using System.Linq;@@ -48,9 +46,11 @@ namespace Grand.Business.Catalog.Queries.Handlers#region Search products//products- var builder = Builders<Product>.Filter;- var filter = FilterDefinition<Product>.Empty;- var filterSpecification = FilterDefinition<Product>.Empty;+ var query = from p in _productRepository.Table+ select p;++ var querySpecification = from p in _productRepository.Table+ select p;//category filteringif (request.CategoryIds != null && request.CategoryIds.Any())@@ -58,30 +58,30 @@ namespace Grand.Business.Catalog.Queries.Handlersif (request.FeaturedProducts.HasValue){- filter &= builder.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)+ query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)&& y.IsFeaturedProduct == request.FeaturedProducts));}else{- filter &= builder.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)));+ query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)));}}//brandif (!string.IsNullOrEmpty(request.BrandId)){- filter &= builder.Where(x => x.BrandId == request.BrandId);+ query = query.Where(x => x.BrandId == request.BrandId);}//collection filteringif (!string.IsNullOrEmpty(request.CollectionId)){if (request.FeaturedProducts.HasValue){- filter &= builder.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId+ query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId&& y.IsFeaturedProduct == request.FeaturedProducts));}else{- filter &= builder.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId));+ query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId));}}@@ -91,27 +91,27 @@ namespace Grand.Business.Catalog.Queries.Handlers//process according to "showHidden"if (!request.ShowHidden){- filter &= builder.Where(p => p.Published);+ query = query.Where(p => p.Published);}}else if (request.OverridePublished.Value){//published only- filter &= builder.Where(p => p.Published);+ query = query.Where(p => p.Published);}else if (!request.OverridePublished.Value){//unpublished only- filter &= builder.Where(p => !p.Published);+ query = query.Where(p => !p.Published);}if (request.VisibleIndividuallyOnly){- filter &= builder.Where(p => p.VisibleIndividually);+ query = query.Where(p => p.VisibleIndividually);}if (request.ProductType.HasValue){var productTypeId = (int)request.ProductType.Value;- filter &= builder.Where(p => p.ProductTypeId == (ProductType)productTypeId);+ query = query.Where(p => p.ProductTypeId == (ProductType)productTypeId);}//The function 'CurrentUtcDateTime' is not supported by SQL Server Compact.@@ -119,24 +119,24 @@ namespace Grand.Business.Catalog.Queries.Handlersvar nowUtc = DateTime.UtcNow;if (request.PriceMin.HasValue){- filter &= builder.Where(p => p.Price >= request.PriceMin.Value);+ query = query.Where(p => p.Price >= request.PriceMin.Value);}if (request.PriceMax.HasValue){//max price- filter &= builder.Where(p => p.Price <= request.PriceMax.Value);+ query = query.Where(p => p.Price <= request.PriceMax.Value);}if (!request.ShowHidden && !_catalogSettings.IgnoreFilterableAvailableStartEndDateTime){- filter &= builder.Where(p =>+ query = query.Where(p =>(p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) &&(p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));}if (request.MarkedAsNewOnly){- filter &= builder.Where(p => p.MarkAsNew);- filter &= builder.Where(p =>+ query = query.Where(p => p.MarkAsNew);+ query = query.Where(p =>(!p.MarkAsNewStartDateTimeUtc.HasValue || p.MarkAsNewStartDateTimeUtc.Value < nowUtc) &&(!p.MarkAsNewEndDateTimeUtc.HasValue || p.MarkAsNewEndDateTimeUtc.Value > nowUtc));}@@ -146,7 +146,7 @@ namespace Grand.Business.Catalog.Queries.Handlers{if (!request.SearchDescriptions)- filter &= builder.Where(p =>+ query = query.Where(p =>p.Name.ToLower().Contains(request.Keywords.ToLower())||p.Locales.Any(x => x.LocaleKey == "Name" && x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))@@ -155,7 +155,7 @@ namespace Grand.Business.Catalog.Queries.Handlers);else{- filter &= builder.Where(p =>+ query = query.Where(p =>(p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower()))||(p.ShortDescription != null && p.ShortDescription.ToLower().Contains(request.Keywords.ToLower()))@@ -173,33 +173,36 @@ namespace Grand.Business.Catalog.Queries.Handlersif (!request.ShowHidden && !CommonHelper.IgnoreAcl){- filter &= (builder.AnyIn(x => x.CustomerGroups, allowedCustomerGroupsIds) | builder.Where(x => !x.LimitedToGroups));+ query = from p in query+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;}if (!string.IsNullOrEmpty(request.StoreId) && !CommonHelper.IgnoreStoreLimitations){- filter &= builder.Where(x => x.Stores.Any(y => y == request.StoreId) || !x.LimitedToStores);+ query = query.Where(x => x.Stores.Any(y => y == request.StoreId) || !x.LimitedToStores);}//vendor filteringif (!string.IsNullOrEmpty(request.VendorId)){- filter &= builder.Where(x => x.VendorId == request.VendorId);+ query = query.Where(x => x.VendorId == request.VendorId);}//warehouse filteringif (!string.IsNullOrEmpty(request.WarehouseId)){- filter &= (builder.Where(x => x.UseMultipleWarehouses && x.ProductWarehouseInventory.Any(y => y.WarehouseId == request.WarehouseId)) |- builder.Where(x => !x.UseMultipleWarehouses && x.WarehouseId == request.WarehouseId));+ query = query.Where(x =>+ (x.UseMultipleWarehouses && x.ProductWarehouseInventory.Any(y => y.WarehouseId == request.WarehouseId))+ || (!x.UseMultipleWarehouses && x.WarehouseId == request.WarehouseId));}//tag filteringif (!string.IsNullOrEmpty(request.ProductTag)){- filter &= builder.Where(x => x.ProductTags.Any(y => y == request.ProductTag));+ query = query.Where(x => x.ProductTags.Any(y => y == request.ProductTag));}- filterSpecification = filter;+ querySpecification = query;//search by specsif (request.FilteredSpecs != null && request.FilteredSpecs.Any())@@ -216,7 +219,7 @@ namespace Grand.Business.Catalog.Queries.Handlers{//adddictionary.Add(specification.Id, new List<string>());- filterSpecification = filterSpecification & builder.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == specification.Id && y.AllowFiltering));+ querySpecification = querySpecification.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == specification.Id && y.AllowFiltering));}dictionary[specification.Id].Add(key);}@@ -224,121 +227,117 @@ namespace Grand.Business.Catalog.Queries.Handlersforeach (var item in dictionary){- filter = filter & builder.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == item.Key && y.AllowFiltering+ query = query.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == item.Key && y.AllowFiltering&& item.Value.Contains(y.SpecificationAttributeOptionId)));}}- SortDefinition<Product> sort = null;- var builderSort = Builders<Product>.Sort;- if (_catalogSettings.SortingByAvailability)- {- sort = builderSort.Ascending(x => x.LowStock);- }-if (request.OrderBy == ProductSortingEnum.Position && request.CategoryIds != null && request.CategoryIds.Any()){//category position- sort = sort == null ? builderSort.Ascending(x => x.DisplayOrderCategory) : sort.Ascending(x => x.DisplayOrderCategory);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory) :+ query.OrderBy(x => x.DisplayOrderCategory);}else if (request.OrderBy == ProductSortingEnum.Position && !string.IsNullOrEmpty(request.BrandId)){//brand position- sort = sort == null ? builderSort.Ascending(x => x.DisplayOrderBrand) : sort.Ascending(x => x.DisplayOrderBrand);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand) :+ query.OrderBy(x => x.DisplayOrderBrand);}else if (request.OrderBy == ProductSortingEnum.Position && !string.IsNullOrEmpty(request.CollectionId)){//collection position- sort = sort == null ? builderSort.Ascending(x => x.DisplayOrderCollection) : sort.Ascending(x => x.DisplayOrderCollection);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection) :+ query.OrderBy(x => x.DisplayOrderCollection);}else if (request.OrderBy == ProductSortingEnum.Position){//otherwise sort by name- sort = sort == null ? builderSort.Ascending(x => x.Name) : sort.Ascending(x => x.Name);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.Name) :+ query.OrderBy(x => x.Name);}else if (request.OrderBy == ProductSortingEnum.NameAsc){//Name: A to Z- sort = sort == null ? builderSort.Ascending(x => x.Name) : sort.Ascending(x => x.Name);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.Name) :+ query.OrderBy(x => x.Name);}else if (request.OrderBy == ProductSortingEnum.NameDesc){//Name: Z to A- sort = sort == null ? builderSort.Descending(x => x.Name) : sort.Descending(x => x.Name);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name) :+ query.OrderByDescending(x => x.Name);}else if (request.OrderBy == ProductSortingEnum.PriceAsc){//Price: Low to High- sort = sort == null ? builderSort.Ascending(x => x.Price) : sort.Ascending(x => x.Price);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.Price) :+ query.OrderBy(x => x.Price);}else if (request.OrderBy == ProductSortingEnum.PriceDesc){//Price: High to Low- sort = sort == null ? builderSort.Descending(x => x.Price) : sort.Descending(x => x.Price);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price) :+ query.OrderByDescending(x => x.Price);}else if (request.OrderBy == ProductSortingEnum.CreatedOn){//creation date- sort = sort == null ? builderSort.Ascending(x => x.CreatedOnUtc) : sort.Ascending(x => x.CreatedOnUtc);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc) :+ query.OrderBy(x => x.CreatedOnUtc);}else if (request.OrderBy == ProductSortingEnum.OnSale){//on sale- sort = sort == null ? builderSort.Descending(x => x.OnSale) : sort.Descending(x => x.OnSale);+ query = query.OrderBy(x => x.OnSale);++ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale) :+ query.OrderBy(x => x.OnSale);}else if (request.OrderBy == ProductSortingEnum.MostViewed){//most viewed- sort = sort == null ? builderSort.Descending(x => x.Viewed) : sort.Descending(x => x.Viewed);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed) :+ query.OrderByDescending(x => x.Viewed);}else if (request.OrderBy == ProductSortingEnum.BestSellers){//best seller- sort = sort == null ? builderSort.Descending(x => x.Sold) : sort.Descending(x => x.Sold);- }+ query = query.OrderByDescending(x => x.Sold);+ query = _catalogSettings.SortingByAvailability ?+ query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold) :+ query.OrderByDescending(x => x.Sold);+ }+ var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);- var products = await PagedList<Product>.Create(_productRepository.Collection, filter, sort, request.PageIndex, request.PageSize);if (request.LoadFilterableSpecificationAttributeOptionIds && !_catalogSettings.IgnoreFilterableSpecAttributeOption){IList<string> specyfication = new List<string>();- var filterSpecExists = filterSpecification &- builder.Where(x => x.ProductSpecificationAttributes.Count > 0);- var productSpec = _productRepository.Collection.Find(filterSpecExists).Limit(1);- if (productSpec != null)+ var filterSpecExists = querySpecification.Where(x => x.ProductSpecificationAttributes.Any(x=>x.AllowFiltering));++ var qspec = from p in filterSpecExists+ from item in p.ProductSpecificationAttributes+ select item;++ var groupQuerySpec = await qspec.Where(x=>x.AllowFiltering).GroupBy(x => new { SpecificationAttributeOptionId = x.SpecificationAttributeOptionId }).ToListAsync2();+ foreach (var item in groupQuerySpec){- var qspec = await _productRepository.Collection- .Aggregate()- .Match(filterSpecification)- .Unwind(x => x.ProductSpecificationAttributes)- .Project(new BsonDocument- {- {"AllowFiltering", "$ProductSpecificationAttributes.AllowFiltering"},- {"SpecificationAttributeOptionId", "$ProductSpecificationAttributes.SpecificationAttributeOptionId"}- })- .Match(new BsonDocument("AllowFiltering", true))- .Group(new BsonDocument- {- {"_id",- new BsonDocument {- { "SpecificationAttributeOptionId", "$SpecificationAttributeOptionId" },- }- },- {"count", new BsonDocument- {- { "$sum" , 1}- }- }- })- .ToListAsync();- foreach (var item in qspec)- {- var so = item["_id"]["SpecificationAttributeOptionId"].ToString();- specyfication.Add(so);- }+ specyfication.Add(item.Key.SpecificationAttributeOptionId);}filterableSpecificationAttributeOptionIds = specyfication.ToList();