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
Improvements/code (#591)
Krzysztof Pajak6235fd5bef08
diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.csindex 3dfb8d79e..2b1858771 100644--- a/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Catalog/Events/Handlers/ProductDeletedEventHandler.cs@@ -1,5 +1,4 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Data;+using Grand.Data;using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Seo;@@ -18,7 +17,6 @@ public class ProductDeletedEventHandler : INotificationHandler<EntityDeleted<Proprivate readonly IRepository<Product> _productRepository;private readonly IRepository<ProductReview> _productReviewRepository;private readonly IRepository<ProductTag> _productTagRepository;- private readonly IProductTagService _productTagService;public ProductDeletedEventHandler(IRepository<Product> productRepository,@@ -27,8 +25,7 @@ public class ProductDeletedEventHandler : INotificationHandler<EntityDeleted<ProIRepository<EntityUrl> entityUrlRepository,IRepository<ProductTag> productTagRepository,IRepository<ProductReview> productReviewRepository,- IRepository<ProductDeleted> productDeletedRepository,- IProductTagService productTagService)+ IRepository<ProductDeleted> productDeletedRepository){_productRepository = productRepository;_customerGroupProductRepository = customerGroupProductRepository;@@ -37,7 +34,6 @@ public class ProductDeletedEventHandler : INotificationHandler<EntityDeleted<Pro_productTagRepository = productTagRepository;_productReviewRepository = productReviewRepository;_productDeletedRepository = productDeletedRepository;- _productTagService = productTagService;}public async Task Handle(EntityDeleted<Product> notification, CancellationToken cancellationToken)@@ -73,7 +69,9 @@ public class ProductDeletedEventHandler : INotificationHandler<EntityDeleted<Pro//delete product tagsvar existingProductTags = _productTagRepository.Table.Where(x => notification.Entity.ProductTags.ToList().Contains(x.Name)).ToList();- foreach (var tag in existingProductTags) await _productTagService.DetachProductTag(tag, notification.Entity.Id);++ foreach (var tag in existingProductTags)+ await _productTagRepository.UpdateField(tag.Id, x => x.Count, tag.Count - 1);//insert to deleted productsvar productDeleted = JsonSerializer.Deserialize<ProductDeleted>(JsonSerializer.Serialize(notification.Entity));diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.csindex 616360430..98015117a 100644--- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs@@ -9,8 +9,7 @@ using MediatR;namespace Grand.Business.Catalog.Queries.Handlers;-public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQuery, (IPagedList<Product> products,- IList<string> filterableSpecificationAttributeOptionIds)>+public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQuery, (IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)>{private readonly AccessControlConfig _accessControlConfig;private readonly CatalogSettings _catalogSettings;@@ -28,306 +27,459 @@ public class GetSearchProductsQueryHandler : IRequestHandler<GetSearchProductsQu_catalogSettings = catalogSettings;_accessControlConfig = accessControlConfig;}-- public async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)>- Handle(GetSearchProductsQuery request, CancellationToken cancellationToken)+ public async Task<(IPagedList<Product> products, IList<string> filterableSpecificationAttributeOptionIds)> Handle(GetSearchProductsQuery request, CancellationToken cancellationToken){var filterableSpecificationAttributeOptionIds = new List<string>();- //validate "categoryIds" parameter- if (request.CategoryIds != null && request.CategoryIds.Contains(""))- request.CategoryIds.Remove("");+ // Clean up request parameters+ CleanupRequestParameters(request);- //Access control list. Allowed customer groups+ // Access control list. Allowed customer groupsvar allowedCustomerGroupsIds = request.Customer.GetCustomerGroupIds();- #region Search products-- //products- var query = from p in _productRepository.Table- select p;-+ // Build base query+ var query = _productRepository.Table.AsQueryable();query = FilterQueryable(request, query, allowedCustomerGroupsIds);+ // Keep a copy for specifications filteringvar querySpecification = query;- //search by specs- if (request.FilteredSpecs != null && request.FilteredSpecs.Any())+ // Apply specification filters+ (query, querySpecification) = await ApplySpecificationFilters(request, query, querySpecification);++ // Order the results+ query = OrderByQueryable(request, query);++ // Create paged list+ var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);++ // Get filterable specification attributes if needed+ if (ShouldLoadFilterableSpecifications(request)){- var spec = new HashSet<string>();- var dictionary = new Dictionary<string, List<string>>();- foreach (var key in request.FilteredSpecs)- {- var specification = await _specificationAttributeService.GetSpecificationAttributeByOptionId(key);- if (specification == null) continue;- spec.Add(specification.Id);- if (!dictionary.ContainsKey(specification.Id))- {- //add- dictionary.Add(specification.Id, new List<string>());- querySpecification = querySpecification.Where(x =>- x.ProductSpecificationAttributes.Any(y =>- y.SpecificationAttributeId == specification.Id && y.AllowFiltering));- }-- dictionary[specification.Id].Add(key);- }+ filterableSpecificationAttributeOptionIds = GetFilterableSpecificationAttributeOptionIds(querySpecification);+ }++ return (products, filterableSpecificationAttributeOptionIds);+ }++ private static void CleanupRequestParameters(GetSearchProductsQuery request)+ {+ if (request.CategoryIds != null && request.CategoryIds.Contains(""))+ request.CategoryIds.Remove("");+ }- foreach (var item in dictionary)- query = query.Where(x => x.ProductSpecificationAttributes.Any(y =>- y.SpecificationAttributeId == item.Key && y.AllowFiltering- && item.Value.Contains(- y.SpecificationAttributeOptionId)));+ private async Task<(IQueryable<Product> query, IQueryable<Product> querySpecification)> ApplySpecificationFilters(+ GetSearchProductsQuery request,+ IQueryable<Product> query,+ IQueryable<Product> querySpecification)+ {+ // Apply filtered specs+ if (request.FilteredSpecs != null && request.FilteredSpecs.Any())+ {+ (query, querySpecification) = await ApplyFilteredSpecifications(request, query, querySpecification);}+ // Apply specification optionsif (request.SpecificationOptions != null && request.SpecificationOptions.Any())+ {+ query = ApplySpecificationOptions(request, query);+ }++ return (query, querySpecification);+ }++ private async Task<(IQueryable<Product> query, IQueryable<Product> querySpecification)> ApplyFilteredSpecifications(+ GetSearchProductsQuery request,+ IQueryable<Product> query,+ IQueryable<Product> querySpecification)+ {+ var specAttributeMapping = await BuildSpecificationAttributeMapping(request.FilteredSpecs, querySpecification);++ // Apply filters for each specification attribute+ foreach (var item in specAttributeMapping.Dictionary)+ {query = query.Where(x => x.ProductSpecificationAttributes.Any(y =>- request.SpecificationOptions.Contains(y.SpecificationAttributeOptionId)));+ y.SpecificationAttributeId == item.Key &&+ y.AllowFiltering &&+ item.Value.Contains(y.SpecificationAttributeOptionId)));+ }- query = OrderByQueryable(request, query);+ return (query, specAttributeMapping.QuerySpecification);+ }- var products = await PagedList<Product>.Create(query, request.PageIndex, request.PageSize);+ private async Task<(Dictionary<string, List<string>> Dictionary, IQueryable<Product> QuerySpecification)>+ BuildSpecificationAttributeMapping(IList<string> filteredSpecs, IQueryable<Product> querySpecification)+ {+ var dictionary = new Dictionary<string, List<string>>();- if (!request.LoadFilterableSpecificationAttributeOptionIds ||- _catalogSettings.IgnoreFilterableSpecAttributeOption)- return (products, filterableSpecificationAttributeOptionIds);+ foreach (var key in filteredSpecs){- var filterSpecExists =- querySpecification.Where(x => x.ProductSpecificationAttributes.Any(x => x.AllowFiltering));+ var specification = await _specificationAttributeService.GetSpecificationAttributeByOptionId(key);+ if (specification == null) continue;- var spec = from p in filterSpecExists- from item in p.ProductSpecificationAttributes- select item;+ if (!dictionary.ContainsKey(specification.Id))+ {+ // Add to dictionary+ dictionary.Add(specification.Id, new List<string>());- var groupQuerySpec = spec.Where(x => x.AllowFiltering).GroupBy(x =>- new { x.SpecificationAttributeOptionId }).ToList();- IList<string> specification =- groupQuerySpec.Select(item => item.Key.SpecificationAttributeOptionId).ToList();+ // Update querySpecification+ querySpecification = querySpecification.Where(x =>+ x.ProductSpecificationAttributes.Any(y =>+ y.SpecificationAttributeId == specification.Id && y.AllowFiltering));+ }- filterableSpecificationAttributeOptionIds = specification.ToList();+ dictionary[specification.Id].Add(key);}- return (products, filterableSpecificationAttributeOptionIds);+ return (dictionary, querySpecification);+ }- #endregion+ private static IQueryable<Product> ApplySpecificationOptions(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ return query.Where(x => x.ProductSpecificationAttributes.Any(y =>+ request.SpecificationOptions.Contains(y.SpecificationAttributeOptionId)));}- private IQueryable<Product> FilterQueryable(GetSearchProductsQuery request, IQueryable<Product> query,- string[] allowedCustomerGroupsIds)+ private bool ShouldLoadFilterableSpecifications(GetSearchProductsQuery request)+ {+ return request.LoadFilterableSpecificationAttributeOptionIds &&+ !_catalogSettings.IgnoreFilterableSpecAttributeOption;+ }++ private static List<string> GetFilterableSpecificationAttributeOptionIds(IQueryable<Product> querySpecification)+ {+ var filterSpecExists = querySpecification.Where(x =>+ x.ProductSpecificationAttributes.Any(x => x.AllowFiltering));++ var spec = from p in filterSpecExists+ from item in p.ProductSpecificationAttributes+ select item;++ var groupQuerySpec = spec.Where(x => x.AllowFiltering)+ .GroupBy(x => new { x.SpecificationAttributeOptionId })+ .ToList();++ return groupQuerySpec+ .Select(item => item.Key.SpecificationAttributeOptionId)+ .ToList();+ }++ private IQueryable<Product> FilterQueryable(GetSearchProductsQuery request, IQueryable<Product> query, string[] allowedCustomerGroupsIds)+ {+ query = ApplyCategoryFiltering(request, query);+ query = ApplyBrandFiltering(request, query);+ query = ApplyCollectionFiltering(request, query);+ query = ApplyPublishedFiltering(request, query);+ query = ApplyVisibilityFiltering(request, query);+ query = ApplyProductTypeFiltering(request, query);+ query = ApplyHomePageFiltering(request, query);+ query = ApplyPriceFiltering(request, query);+ query = ApplyRatingFiltering(request, query);+ query = ApplyAvailabilityFiltering(request, query);+ query = ApplyNewProductFiltering(request, query);+ query = ApplyKeywordFiltering(request, query);+ query = ApplyAccessControlFiltering(request, query, allowedCustomerGroupsIds);+ query = ApplyStoreFiltering(request, query);+ query = ApplyVendorFiltering(request, query);+ query = ApplyWarehouseFiltering(request, query);+ query = ApplyTagFiltering(request, query);++ return query;+ }++ private static IQueryable<Product> ApplyCategoryFiltering(GetSearchProductsQuery request, IQueryable<Product> query){- //category filteringif (request.CategoryIds != null && request.CategoryIds.Any()){if (request.FeaturedProducts.HasValue)- query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)- && y.IsFeaturedProduct ==- request.FeaturedProducts));+ query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId) && y.IsFeaturedProduct == request.FeaturedProducts));elsequery = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId)));}+ return query;+ }- //brand- if (!string.IsNullOrEmpty(request.BrandId)) query = query.Where(x => x.BrandId == request.BrandId);+ private static IQueryable<Product> ApplyBrandFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (!string.IsNullOrEmpty(request.BrandId))+ query = query.Where(x => x.BrandId == request.BrandId);+ return query;+ }- //collection filtering+ private static IQueryable<Product> ApplyCollectionFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (!string.IsNullOrEmpty(request.CollectionId)){if (request.FeaturedProducts.HasValue)- query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId- && y.IsFeaturedProduct ==- request.FeaturedProducts));+ query = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId && y.IsFeaturedProduct == request.FeaturedProducts));elsequery = query.Where(x => x.ProductCollections.Any(y => y.CollectionId == request.CollectionId));}+ return query;+ }+ private static IQueryable<Product> ApplyPublishedFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (!request.OverridePublished.HasValue){- //process according to "showHidden"- if (!request.ShowHidden) query = query.Where(p => p.Published);+ if (!request.ShowHidden)+ query = query.Where(p => p.Published);}else if (request.OverridePublished.Value){- //published onlyquery = query.Where(p => p.Published);}else if (!request.OverridePublished.Value){- //unpublished onlyquery = query.Where(p => !p.Published);}+ return query;+ }- if (request.VisibleIndividuallyOnly) query = query.Where(p => p.VisibleIndividually);-- if (request.ProductType.HasValue) query = query.Where(p => p.ProductTypeId == request.ProductType);+ private static IQueryable<Product> ApplyVisibilityFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (request.VisibleIndividuallyOnly)+ query = query.Where(p => p.VisibleIndividually);+ return query;+ }- if (request.ShowOnHomePage.HasValue) query = query.Where(p => p.ShowOnHomePage == request.ShowOnHomePage.Value);+ private static IQueryable<Product> ApplyProductTypeFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (request.ProductType.HasValue)+ query = query.Where(p => p.ProductTypeId == request.ProductType);+ return query;+ }- var nowUtc = DateTime.UtcNow;- if (request.PriceMin.HasValue) query = query.Where(p => p.Price >= request.PriceMin.Value);+ private static IQueryable<Product> ApplyHomePageFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (request.ShowOnHomePage.HasValue)+ query = query.Where(p => p.ShowOnHomePage == request.ShowOnHomePage.Value);+ return query;+ }+ private static IQueryable<Product> ApplyPriceFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (request.PriceMin.HasValue)+ query = query.Where(p => p.Price >= request.PriceMin.Value);if (request.PriceMax.HasValue)- //max pricequery = query.Where(p => p.Price <= request.PriceMax.Value);+ return query;+ }+ private static IQueryable<Product> ApplyRatingFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (request.Rating.HasValue)- //avg ratingquery = query.Where(p => p.AvgRating >= request.Rating);+ return query;+ }+ private IQueryable<Product> ApplyAvailabilityFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ var nowUtc = DateTime.UtcNow;if (!request.ShowHidden && !_catalogSettings.IgnoreFilterableAvailableStartEndDateTime)- query = query.Where(p =>- (p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) &&- (p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));+ query = query.Where(p => (p.AvailableStartDateTimeUtc == null || p.AvailableStartDateTimeUtc < nowUtc) && (p.AvailableEndDateTimeUtc == null || p.AvailableEndDateTimeUtc > nowUtc));+ return query;+ }+ private static IQueryable<Product> ApplyNewProductFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (request.MarkedAsNewOnly){+ var nowUtc = DateTime.UtcNow;query = query.Where(p => p.MarkAsNew);- query = query.Where(p =>- (!p.MarkAsNewStartDateTimeUtc.HasValue || p.MarkAsNewStartDateTimeUtc.Value < nowUtc) &&- (!p.MarkAsNewEndDateTimeUtc.HasValue || p.MarkAsNewEndDateTimeUtc.Value > nowUtc));+ query = query.Where(p => (!p.MarkAsNewStartDateTimeUtc.HasValue || p.MarkAsNewStartDateTimeUtc.Value < nowUtc) && (!p.MarkAsNewEndDateTimeUtc.HasValue || p.MarkAsNewEndDateTimeUtc.Value > nowUtc));}+ return query;+ }- //searching by keyword+ private static IQueryable<Product> ApplyKeywordFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (!string.IsNullOrWhiteSpace(request.Keywords)){if (!request.SearchDescriptions)- 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()))- ||- (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower()))- );+ 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())) || (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())));else- query = query.Where(p =>- (p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower()))- ||- (p.ShortDescription != null &&- p.ShortDescription.ToLower().Contains(request.Keywords.ToLower()))- ||- (p.FullDescription != null && p.FullDescription.ToLower().Contains(request.Keywords.ToLower()))- ||- p.Locales.Any(x =>- x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower()))- ||- (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower()))- );+ query = query.Where(p => (p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower())) || (p.ShortDescription != null && p.ShortDescription.ToLower().Contains(request.Keywords.ToLower())) || (p.FullDescription != null && p.FullDescription.ToLower().Contains(request.Keywords.ToLower())) || p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())));}+ return query;+ }+ private IQueryable<Product> ApplyAccessControlFiltering(GetSearchProductsQuery request, IQueryable<Product> query, string[] allowedCustomerGroupsIds)+ {if (!request.ShowHidden && !_accessControlConfig.IgnoreAcl)- query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;+ query = from p in query where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x)) select p;+ return query;+ }+ private IQueryable<Product> ApplyStoreFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (!string.IsNullOrEmpty(request.StoreId) && !_accessControlConfig.IgnoreStoreLimitations)query = query.Where(x => x.Stores.Any(y => y == request.StoreId) || !x.LimitedToStores);+ return query;+ }- //vendor filtering- if (!string.IsNullOrEmpty(request.VendorId)) query = query.Where(x => x.VendorId == request.VendorId);+ private static IQueryable<Product> ApplyVendorFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (!string.IsNullOrEmpty(request.VendorId))+ query = query.Where(x => x.VendorId == request.VendorId);+ return query;+ }- //warehouse filtering+ private static IQueryable<Product> ApplyWarehouseFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (!string.IsNullOrEmpty(request.WarehouseId))- query = query.Where(x =>- (x.UseMultipleWarehouses &&- x.ProductWarehouseInventory.Any(y => y.WarehouseId == request.WarehouseId))- || (!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));+ return query;+ }- //tag filtering+ private static IQueryable<Product> ApplyTagFiltering(GetSearchProductsQuery request, IQueryable<Product> query)+ {if (!string.IsNullOrEmpty(request.ProductTag))query = query.Where(x => x.ProductTags.Any(y => y == request.ProductTag));-return query;}private IQueryable<Product> OrderByQueryable(GetSearchProductsQuery request, IQueryable<Product> query){- switch (request.OrderBy)+ if (request.OrderBy == ProductSortingEnum.Position)+ {+ query = OrderByPosition(request, query);+ }+ else if (request.OrderBy == ProductSortingEnum.NameAsc)+ {+ query = OrderByNameAsc(query);+ }+ else if (request.OrderBy == ProductSortingEnum.NameDesc){- case ProductSortingEnum.Position when request.CategoryIds != null && request.CategoryIds.Any():- //category position- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory)- : query.OrderBy(x => x.DisplayOrderCategory);- break;- case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.BrandId):- //brand position- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand)- : query.OrderBy(x => x.DisplayOrderBrand);- break;- case ProductSortingEnum.Position when !string.IsNullOrEmpty(request.CollectionId):- //collection position- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection)- : query.OrderBy(x => x.DisplayOrderCollection);- break;- case ProductSortingEnum.Position:- //otherwise sort by name- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)- : query.OrderBy(x => x.Name);- break;- case ProductSortingEnum.NameAsc:- //Name: A to Z- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)- : query.OrderBy(x => x.Name);- break;- case ProductSortingEnum.NameDesc:- //Name: Z to A- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name)- : query.OrderByDescending(x => x.Name);- break;- case ProductSortingEnum.PriceAsc:- //Price: Low to High- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Price)- : query.OrderBy(x => x.Price);- break;- case ProductSortingEnum.PriceDesc:- //Price: High to Low- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price)- : query.OrderByDescending(x => x.Price);- break;- case ProductSortingEnum.CreatedOn:- //creation date- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc)- : query.OrderBy(x => x.CreatedOnUtc);- break;- case ProductSortingEnum.OnSale:- //on sale- query = query.OrderBy(x => x.OnSale);-- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale)- : query.OrderBy(x => x.OnSale);- break;- case ProductSortingEnum.MostViewed:- //most viewed- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed)- : query.OrderByDescending(x => x.Viewed);- break;- case ProductSortingEnum.BestSellers:- //best seller- query = query.OrderByDescending(x => x.Sold);-- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold)- : query.OrderByDescending(x => x.Sold);- break;- case ProductSortingEnum.Rating:- //most viewed- query = _catalogSettings.SortingByAvailability- ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.AvgRating)- : query.OrderByDescending(x => x.AvgRating).ThenByDescending(x => x.ApprovedTotalReviews);- break;+ query = OrderByNameDesc(query);+ }+ else if (request.OrderBy == ProductSortingEnum.PriceAsc)+ {+ query = OrderByPriceAsc(query);+ }+ else if (request.OrderBy == ProductSortingEnum.PriceDesc)+ {+ query = OrderByPriceDesc(query);+ }+ else if (request.OrderBy == ProductSortingEnum.CreatedOn)+ {+ query = OrderByCreatedOn(query);+ }+ else if (request.OrderBy == ProductSortingEnum.OnSale)+ {+ query = OrderByOnSale(query);+ }+ else if (request.OrderBy == ProductSortingEnum.MostViewed)+ {+ query = OrderByMostViewed(query);+ }+ else if (request.OrderBy == ProductSortingEnum.BestSellers)+ {+ query = OrderByBestSellers(query);+ }+ else if (request.OrderBy == ProductSortingEnum.Rating)+ {+ query = OrderByRating(query);}return query;}++ private IQueryable<Product> OrderByPosition(GetSearchProductsQuery request, IQueryable<Product> query)+ {+ if (request.CategoryIds != null && request.CategoryIds.Any())+ {+ query = _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCategory)+ : query.OrderBy(x => x.DisplayOrderCategory);+ }+ else if (!string.IsNullOrEmpty(request.BrandId))+ {+ query = _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderBrand)+ : query.OrderBy(x => x.DisplayOrderBrand);+ }+ else if (!string.IsNullOrEmpty(request.CollectionId))+ {+ query = _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.DisplayOrderCollection)+ : query.OrderBy(x => x.DisplayOrderCollection);+ }+ else+ {+ query = _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)+ : query.OrderBy(x => x.Name);+ }++ return query;+ }++ private IQueryable<Product> OrderByNameAsc(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Name)+ : query.OrderBy(x => x.Name);+ }++ private IQueryable<Product> OrderByNameDesc(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Name)+ : query.OrderByDescending(x => x.Name);+ }++ private IQueryable<Product> OrderByPriceAsc(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.Price)+ : query.OrderBy(x => x.Price);+ }++ private IQueryable<Product> OrderByPriceDesc(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Price)+ : query.OrderByDescending(x => x.Price);+ }++ private IQueryable<Product> OrderByCreatedOn(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.CreatedOnUtc)+ : query.OrderBy(x => x.CreatedOnUtc);+ }++ private IQueryable<Product> OrderByOnSale(IQueryable<Product> query)+ {+ query = query.OrderBy(x => x.OnSale);++ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenBy(x => x.OnSale)+ : query.OrderBy(x => x.OnSale);+ }++ private IQueryable<Product> OrderByMostViewed(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Viewed)+ : query.OrderByDescending(x => x.Viewed);+ }++ private IQueryable<Product> OrderByBestSellers(IQueryable<Product> query)+ {+ query = query.OrderByDescending(x => x.Sold);++ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.Sold)+ : query.OrderByDescending(x => x.Sold);+ }++ private IQueryable<Product> OrderByRating(IQueryable<Product> query)+ {+ return _catalogSettings.SortingByAvailability+ ? query.OrderBy(x => x.LowStock).ThenByDescending(x => x.AvgRating)+ : query.OrderByDescending(x => x.AvgRating).ThenByDescending(x => x.ApprovedTotalReviews);++ }}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountHandlerService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountHandlerService.csnew file mode 100644index 000000000..ce1aed6be--- /dev/null+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountHandlerService.cs@@ -0,0 +1,159 @@+using Grand.Business.Core.Interfaces.Catalog.Brands;+using Grand.Business.Core.Interfaces.Catalog.Categories;+using Grand.Business.Core.Interfaces.Catalog.Collections;+using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Utilities.Catalog;+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Discounts;+using Grand.Domain.Stores;++namespace Grand.Business.Catalog.Services.Discounts;++public class DiscountHandlerService : IDiscountHandlerService+{+ private readonly IDiscountService _discountService;+ private readonly ICategoryService _categoryService;+ private readonly IBrandService _brandService;+ private readonly ICollectionService _collectionService;+ private readonly IVendorService _vendorService;+ private readonly IDiscountValidationService _discountValidationService;+ private readonly CatalogSettings _catalogSettings;++ public DiscountHandlerService(+ IDiscountService discountService,+ ICategoryService categoryService,+ IBrandService brandService,+ ICollectionService collectionService,+ IVendorService vendorService,+ IDiscountValidationService discountValidationService,+ CatalogSettings catalogSettings)+ {+ _discountService = discountService;+ _categoryService = categoryService;+ _brandService = brandService;+ _collectionService = collectionService;+ _vendorService = vendorService;+ _discountValidationService = discountValidationService;+ _catalogSettings = catalogSettings;+ }++ /// <summary>+ /// Gets allowed discounts+ /// </summary>+ /// <param name="product">Product</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <returns>Discounts</returns>+ private async Task AddAllowedDiscounts(IList<ApplyDiscount> allowedDiscounts, IEnumerable<string> appliedDiscounts, Customer customer, Store store, Currency currency, DiscountType discountType)+ {+ foreach (var appliedDiscount in appliedDiscounts)+ {+ var discount = await _discountService.GetDiscountById(appliedDiscount);+ if (discount == null) continue;+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);+ if (validDiscount.IsValid && discount.DiscountTypeId == discountType)+ allowedDiscounts.Add(new ApplyDiscount {+ CouponCode = validDiscount.CouponCode,+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative,+ MaximumDiscountedQuantity = discount.MaximumDiscountedQuantity+ });+ }+ }++ public virtual async Task<IList<ApplyDiscount>> GetAllowedDiscounts(Product product, Customer customer, Store store, Currency currency)+ {+ var allowedDiscounts = new List<ApplyDiscount>();+ if (_catalogSettings.IgnoreDiscounts)+ return allowedDiscounts;++ //discounts applied to products+ await AddAllowedDiscounts(allowedDiscounts, product.AppliedDiscounts, customer, store, currency, DiscountType.AssignedToSkus);++ //discounts applied to all products+ var allProductDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, store.Id, currency.CurrencyCode);+ await AddAllowedDiscounts(allowedDiscounts, allProductDiscounts.Select(d => d.Id), customer, store, currency, DiscountType.AssignedToAllProducts);++ //discounts applied to categories+ foreach (var productCategory in product.ProductCategories)+ {+ var category = await _categoryService.GetCategoryById(productCategory.CategoryId);+ if (category == null) continue;+ await AddAllowedDiscounts(allowedDiscounts, category.AppliedDiscounts, customer, store, currency, DiscountType.AssignedToCategories);+ }++ //discounts applied to brands+ if (!string.IsNullOrEmpty(product.BrandId))+ {+ var brand = await _brandService.GetBrandById(product.BrandId);+ if (brand != null)+ await AddAllowedDiscounts(allowedDiscounts, brand.AppliedDiscounts, customer, store, currency, DiscountType.AssignedToBrands);+ }++ //discounts applied to collections+ foreach (var productCollection in product.ProductCollections)+ {+ var collection = await _collectionService.GetCollectionById(productCollection.CollectionId);+ if (collection == null) continue;+ await AddAllowedDiscounts(allowedDiscounts, collection.AppliedDiscounts, customer, store, currency, DiscountType.AssignedToCollections);+ }++ //discounts applied to vendors+ if (!string.IsNullOrEmpty(product.VendorId))+ {+ var vendor = await _vendorService.GetVendorById(product.VendorId);+ if (vendor != null)+ await AddAllowedDiscounts(allowedDiscounts, vendor.AppliedDiscounts, customer, store, currency, DiscountType.AssignedToVendors);+ }++ return FilterDiscountsByMaxQuantity(allowedDiscounts);+ }++ private static IList<ApplyDiscount> FilterDiscountsByMaxQuantity(IList<ApplyDiscount> discounts)+ {+ if (!discounts.Any())+ return discounts;++ // Identify discounts that are cumulative and have a MaximumDiscountedQuantity > 0+ var cumulativeDiscounts = discounts+ .Where(d => d.IsCumulative && (d.MaximumDiscountedQuantity ?? 0) > 0)+ .ToList();++ if (!cumulativeDiscounts.Any())+ return discounts;++ // Determine the maximum MaximumDiscountedQuantity among cumulative discounts+ var maxQuantity = cumulativeDiscounts.Max(d => d.MaximumDiscountedQuantity ?? 0);++ // Select cumulative discounts with the maximum MaximumDiscountedQuantity+ var maxCumulativeDiscounts = cumulativeDiscounts+ .Where(d => d.MaximumDiscountedQuantity == maxQuantity)+ .ToList();++ // Select discounts that are not cumulative or have MaximumDiscountedQuantity <= 0+ var otherDiscounts = discounts+ .Where(d => !(d.IsCumulative && (d.MaximumDiscountedQuantity ?? 0) > 0))+ .ToList();++ // Combine the filtered cumulative discounts with the other discounts+ return maxCumulativeDiscounts.Concat(otherDiscounts).ToList();+ }++ public async Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetDiscountAmount(Product product, Customer customer, Store store, Currency currency, double productPriceWithoutDiscount)+ {+ var allowedDiscounts = await GetAllowedDiscounts(product, customer, store, currency);++ //no discounts+ if (!allowedDiscounts.Any())+ return ([], 0);++ var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, currency,+ product, productPriceWithoutDiscount);++ return (preferredDiscount.appliedDiscount, preferredDiscount.discountAmount);+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.csindex 53f44ff3f..e12616b22 100644--- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs@@ -1,7 +1,4 @@using Grand.Business.Core.Extensions;-using Grand.Business.Core.Interfaces.Catalog.Brands;-using Grand.Business.Core.Interfaces.Catalog.Categories;-using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Business.Core.Interfaces.Catalog.Discounts;using Grand.Business.Core.Interfaces.Catalog.Prices;using Grand.Business.Core.Interfaces.Catalog.Products;@@ -12,7 +9,6 @@ using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Directory;-using Grand.Domain.Discounts;using Grand.Domain.Orders;using Grand.Domain.Stores;using Grand.Infrastructure;@@ -28,30 +24,22 @@ public class PricingService : IPricingService{#region Ctor- public PricingService(IContextAccessor contextAccessor,- IDiscountService discountService,- ICategoryService categoryService,- IBrandService brandService,- ICollectionService collectionService,+ public PricingService(+ IContextAccessor contextAccessor,IProductService productService,IMediator mediator,ICurrencyService currencyService,- IDiscountValidationService discountValidationService,+ IDiscountHandlerService discountApplicationService,ShoppingCartSettings shoppingCartSettings,CatalogSettings catalogSettings){_contextAccessor = contextAccessor;- _discountService = discountService;- _categoryService = categoryService;- _brandService = brandService;- _collectionService = collectionService;_productService = productService;_mediator = mediator;- _mediator = mediator;_currencyService = currencyService;_shoppingCartSettings = shoppingCartSettings;_catalogSettings = catalogSettings;- _discountValidationService = discountValidationService;+ _discountApplicationService = discountApplicationService;}#endregion@@ -71,311 +59,15 @@ public class PricingService : IPricingService#region Fieldsprivate readonly IContextAccessor _contextAccessor;- private readonly IDiscountService _discountService;- private readonly ICategoryService _categoryService;- private readonly IBrandService _brandService;- private readonly ICollectionService _collectionService;private readonly IProductService _productService;private readonly IMediator _mediator;private readonly ICurrencyService _currencyService;- private readonly IDiscountValidationService _discountValidationService;+ private readonly IDiscountHandlerService _discountApplicationService;private readonly ShoppingCartSettings _shoppingCartSettings;private readonly CatalogSettings _catalogSettings;#endregion- #region Utilities-- /// <summary>- /// Gets allowed discounts- /// </summary>- /// <param name="product">Product</param>- /// <param name="customer">Customer</param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <returns>Discounts</returns>- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToProduct(Product product,- Customer customer, Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- if (!product.AppliedDiscounts.Any()) return allowedDiscounts;- foreach (var appliedDiscount in product.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount == null) continue;- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToSkus)- allowedDiscounts.Add(new ApplyDiscount {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }-- return allowedDiscounts;- }-- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToAllProduct(Product product,- Customer customer, Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- var discounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, store.Id,- currency.CurrencyCode);- foreach (var discount in discounts)- {- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid)- allowedDiscounts.Add(new ApplyDiscount {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }-- return allowedDiscounts;- }--- /// <summary>- /// Gets allowed discounts applied to categories- /// </summary>- /// <param name="product">Product</param>- /// <param name="customer">Customer</param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <returns>Discounts</returns>- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCategories(Product product,- Customer customer, Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- foreach (var productCategory in product.ProductCategories)- {- var category = await _categoryService.GetCategoryById(productCategory.CategoryId);- if (category == null || !category.AppliedDiscounts.Any()) continue;- foreach (var appliedDiscount in category.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount == null) continue;- var validDiscount =- await _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid && discount.DiscountTypeId == DiscountType.AssignedToCategories)- allowedDiscounts.Add(new ApplyDiscount {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }- }-- return allowedDiscounts;- }-- /// <summary>- /// Get allowed discount applied to brands- /// </summary>- /// <param name="product"></param>- /// <param name="customer"></param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <returns></returns>- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToBrands(Product product,- Customer customer, Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- if (string.IsNullOrEmpty(product.BrandId)) return allowedDiscounts;- var brand = await _brandService.GetBrandById(product.BrandId);- if (brand == null) return allowedDiscounts;- if (!brand.AppliedDiscounts.Any()) return allowedDiscounts;- foreach (var appliedDiscount in brand.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount == null) continue;- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToBrands)- allowedDiscounts.Add(new ApplyDiscount {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }-- return allowedDiscounts;- }-- /// <summary>- /// Gets allowed discounts applied to collections- /// </summary>- /// <param name="product">Product</param>- /// <param name="customer">Customer</param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <returns>Discounts</returns>- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCollections(Product product,- Customer customer, Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- foreach (var productCollection in product.ProductCollections)- {- var collection = await _collectionService.GetCollectionById(productCollection.CollectionId);- if (collection == null || !collection.AppliedDiscounts.Any()) continue;- foreach (var appliedDiscount in collection.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount == null) continue;- var validDiscount =- await _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToCollections)- allowedDiscounts.Add(new ApplyDiscount {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }- }-- return allowedDiscounts;- }-- /// <summary>- /// Get allowed discounts applied to vendors- /// </summary>- /// <param name="product"></param>- /// <param name="customer"></param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <returns></returns>- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToVendors(Product product,- Customer customer, Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- if (string.IsNullOrEmpty(product.VendorId)) return allowedDiscounts;-- var vendor = await _mediator.Send(new GetVendorByIdQuery { Id = product.VendorId });- if (vendor == null) return allowedDiscounts;- if (!vendor.AppliedDiscounts.Any()) return allowedDiscounts;- foreach (var appliedDiscount in vendor.AppliedDiscounts)- {- var discount = await _discountService.GetDiscountById(appliedDiscount);- if (discount == null) continue;- var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToVendors)- allowedDiscounts.Add(new ApplyDiscount {- CouponCode = validDiscount.CouponCode,- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative- });- }-- return allowedDiscounts;- }-- /// <summary>- /// Gets allowed discounts- /// </summary>- /// <param name="product">Product</param>- /// <param name="customer">Customer</param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <returns>Discounts</returns>- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscounts(Product product, Customer customer,- Store store, Currency currency)- {- var allowedDiscounts = new List<ApplyDiscount>();- if (_catalogSettings.IgnoreDiscounts)- return allowedDiscounts;-- //discounts applied to products- foreach (var discount in await GetAllowedDiscountsAppliedToProduct(product, customer, store, currency))- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))- allowedDiscounts.Add(discount);-- //discounts applied to all products- foreach (var discount in await GetAllowedDiscountsAppliedToAllProduct(product, customer, store, currency))- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))- allowedDiscounts.Add(discount);-- //discounts applied to categories- foreach (var discount in await GetAllowedDiscountsAppliedToCategories(product, customer, store, currency))- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))- allowedDiscounts.Add(discount);-- //discounts applied to brands- foreach (var discount in await GetAllowedDiscountsAppliedToBrands(product, customer, store, currency))- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))- allowedDiscounts.Add(discount);-- //discounts applied to collections- foreach (var discount in await GetAllowedDiscountsAppliedToCollections(product, customer, store, currency))- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))- allowedDiscounts.Add(discount);-- //discounts applied to vendors- foreach (var discount in await GetAllowedDiscountsAppliedToVendors(product, customer, store, currency))- if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))- allowedDiscounts.Add(discount);-- return allowedDiscounts;- }-- /// <summary>- /// Gets discount amount- /// </summary>- /// <param name="product">Product</param>- /// <param name="customer">The customer</param>- /// <param name="store">Store</param>- /// <param name="currency">Currency</param>- /// <param name="productPriceWithoutDiscount">Already calculated product price without discount</param>- /// <returns>Discount amount</returns>- protected virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetDiscountAmount(- Product product,- Customer customer, Store store, Currency currency, double productPriceWithoutDiscount)- {- ArgumentNullException.ThrowIfNull(product);-- //we don't apply discounts to products with price entered by a customer- if (product.EnteredPrice)- return (0, null);-- //discounts are disabled- if (_catalogSettings.IgnoreDiscounts)- return (0, null);-- var allowedDiscounts = await GetAllowedDiscounts(product, customer, store, currency);-- //no discounts- if (!allowedDiscounts.Any())- return (0, null);-- var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, currency,- product, productPriceWithoutDiscount);-- return (preferredDiscount.discountAmount, preferredDiscount.appliedDiscount);- }-- #endregion-#region Methods/// <summary>@@ -457,8 +149,7 @@ public class PricingService : IPricingService//customer product priceif (_catalogSettings.CustomerProductPrice){- var customerPrice = await _mediator.Send(new GetPriceByCustomerProductQuery- { CustomerId = customer.Id, ProductId = product.Id });+ var customerPrice = await _mediator.Send(new GetPriceByCustomerProductQuery { CustomerId = customer.Id, ProductId = product.Id });if (customerPrice.HasValue && customerPrice.Value <await _currencyService.ConvertToPrimaryStoreCurrency(price, currency))price = await _currencyService.ConvertFromPrimaryStoreCurrency(customerPrice.Value, currency);@@ -484,8 +175,7 @@ public class PricingService : IPricingServiceif (includeDiscounts){//discount- var (tmpDiscountAmount, tmpAppliedDiscounts) =- await GetDiscountAmount(product, customer, store, currency, price);+ var (tmpAppliedDiscounts, tmpDiscountAmount) = await _discountApplicationService.GetDiscountAmount(product, customer, store, currency, price);price -= tmpDiscountAmount;if (tmpAppliedDiscounts != null)@@ -673,7 +363,7 @@ public class PricingService : IPricingService{ArgumentNullException.ThrowIfNull(shoppingCartItem);- double subTotal;+ double subTotal = 0;//unit pricevar getUnitPrice = await GetUnitPrice(shoppingCartItem, product, includeDiscounts);var unitPrice = getUnitPrice.unitprice;@@ -683,20 +373,15 @@ public class PricingService : IPricingService//discountif (appliedDiscounts.Any()){- Discount oneAndOnlyDiscount = null;- if (appliedDiscounts.Count == 1)- oneAndOnlyDiscount =- await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault()?.DiscountId);- if (oneAndOnlyDiscount is { MaximumDiscountedQuantity: not null } &&- shoppingCartItem.Quantity > oneAndOnlyDiscount.MaximumDiscountedQuantity.Value)+ var discountedQuantity = appliedDiscounts.Max(x => x.MaximumDiscountedQuantity);+ if (appliedDiscounts.Any(x => x.MaximumDiscountedQuantity.HasValue)+ && shoppingCartItem.Quantity > discountedQuantity.Value){- //we cannot apply discount for all shopping cart items- var discountedQuantity = oneAndOnlyDiscount.MaximumDiscountedQuantity.Value;- var discountedSubTotal = unitPrice * discountedQuantity;- discountAmount *= discountedQuantity;+ var discountedSubTotal = unitPrice * discountedQuantity.Value;+ discountAmount *= discountedQuantity.Value;- var notDiscountedQuantity = shoppingCartItem.Quantity - discountedQuantity;+ var notDiscountedQuantity = shoppingCartItem.Quantity - discountedQuantity.Value;var notDiscountedUnitPrice = await GetUnitPrice(shoppingCartItem, product, false);var notDiscountedSubTotal = notDiscountedUnitPrice.unitprice * notDiscountedQuantity;@@ -735,18 +420,18 @@ public class PricingService : IPricingServiceswitch (attributeValue.AttributeValueTypeId){case AttributeValueType.Simple:- {- //simple attribute- cost += attributeValue.Cost;- }+ {+ //simple attribute+ cost += attributeValue.Cost;+ }break;case AttributeValueType.AssociatedToProduct:- {- //bundled product- var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);- if (associatedProduct != null)- cost += associatedProduct.ProductCost * attributeValue.Quantity;- }+ {+ //bundled product+ var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);+ if (associatedProduct != null)+ cost += associatedProduct.ProductCost * attributeValue.Quantity;+ }break;}@@ -766,26 +451,26 @@ public class PricingService : IPricingServiceswitch (value.AttributeValueTypeId){case AttributeValueType.Simple:- {- //simple attribute- adjustment = value.PriceAdjustment;- if (adjustment > 0)- adjustment =- await _currencyService.ConvertFromPrimaryStoreCurrency(adjustment,- _contextAccessor.WorkContext.WorkingCurrency);- }+ {+ //simple attribute+ adjustment = value.PriceAdjustment;+ if (adjustment > 0)+ adjustment =+ await _currencyService.ConvertFromPrimaryStoreCurrency(adjustment,+ _contextAccessor.WorkContext.WorkingCurrency);+ }break;case AttributeValueType.AssociatedToProduct:- {- //bundled product- var associatedProduct = await _productService.GetProductById(value.AssociatedProductId);- if (associatedProduct != null)- adjustment = (await GetFinalPrice(associatedProduct,- _contextAccessor.WorkContext.CurrentCustomer,- _contextAccessor.StoreContext.CurrentStore,- _contextAccessor.WorkContext.WorkingCurrency,- value.PriceAdjustment)).finalPrice * value.Quantity;- }+ {+ //bundled product+ var associatedProduct = await _productService.GetProductById(value.AssociatedProductId);+ if (associatedProduct != null)+ adjustment = (await GetFinalPrice(associatedProduct,+ _contextAccessor.WorkContext.CurrentCustomer,+ _contextAccessor.StoreContext.CurrentStore,+ _contextAccessor.WorkContext.WorkingCurrency,+ value.PriceAdjustment)).finalPrice * value.Quantity;+ }break;}diff --git a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.csindex 1c9b95f55..db8fcbb4b 100644--- a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs@@ -82,6 +82,7 @@ public class StartupApplication : IStartupApplicationserviceCollection.AddScoped<IDiscountService, DiscountService>();serviceCollection.AddScoped<IDiscountValidationService, DiscountValidationService>();serviceCollection.AddScoped<IDiscountProviderLoader, DiscountProviderLoader>();+ serviceCollection.AddScoped<IDiscountHandlerService, DiscountHandlerService>();}private static void RegisterTaxService(IServiceCollection serviceCollection)diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.csindex cd9447fd3..64a9acda9 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs@@ -149,7 +149,8 @@ public class OrderCalculationService : IOrderCalculationServiceallowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode+ CouponCode = validDiscount.CouponCode,+ MaximumDiscountedQuantity = discount.MaximumDiscountedQuantity});}@@ -194,7 +195,8 @@ public class OrderCalculationService : IOrderCalculationServiceallowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode+ CouponCode = validDiscount.CouponCode,+ MaximumDiscountedQuantity = discount.MaximumDiscountedQuantity});}@@ -243,7 +245,8 @@ public class OrderCalculationService : IOrderCalculationServiceallowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode+ CouponCode = validDiscount.CouponCode,+ MaximumDiscountedQuantity = discount.MaximumDiscountedQuantity});}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountHandlerService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountHandlerService.csnew file mode 100644index 000000000..efb1e5bcd--- /dev/null+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountHandlerService.cs@@ -0,0 +1,33 @@+using Grand.Business.Core.Utilities.Catalog;+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Stores;++namespace Grand.Business.Core.Interfaces.Catalog.Discounts;++public interface IDiscountHandlerService+{+ /// <summary>+ /// Gets allowed discounts for a product+ /// </summary>+ /// <param name="product">Product</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <returns>Discounts</returns>+ Task<IList<ApplyDiscount>> GetAllowedDiscounts(Product product, Customer customer, Store store, Currency currency);++ /// <summary>+ /// Get discount amount+ /// </summary>+ /// <param name="product"></param>+ /// <param name="customer"></param>+ /// <param name="store"></param>+ /// <param name="currency"></param>+ /// <param name="productPriceWithoutDiscount"></param>+ /// <returns></returns>+ Task<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetDiscountAmount(Product product, Customer customer, Store store, Currency currency,+ double productPriceWithoutDiscount);++}\ No newline at end of filediff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.csindex e13359ce3..7e0e74cdb 100644--- a/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs+++ b/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs@@ -20,4 +20,9 @@ public class ApplyDiscount/// Gets or sets is discount is cumulative/// </summary>public bool IsCumulative { get; set; }++ /// <summary>+ /// Maximum discounted quantity+ /// </summary>+ public int? MaximumDiscountedQuantity { get; set; }}\ No newline at end of filediff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.csindex 057ee6d33..57c846408 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs@@ -37,7 +37,7 @@ public class ProductDeletedEventHandlerTests_productTagService = new Mock<IProductTagService>();_handler = new ProductDeletedEventHandler(_repository, _customerGroupProductRepository,_customerRepository, _entityUrlRepository, _productTagRepository, _productReviewRepository,- _productDeletedRepository, _productTagService.Object);+ _productDeletedRepository);}diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountHandlerServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountHandlerServiceTests.csnew file mode 100644index 000000000..076737230--- /dev/null+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountHandlerServiceTests.cs@@ -0,0 +1,107 @@+using Grand.Business.Catalog.Services.Discounts;+using Grand.Business.Core.Interfaces.Catalog.Brands;+using Grand.Business.Core.Interfaces.Catalog.Categories;+using Grand.Business.Core.Interfaces.Catalog.Collections;+using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Utilities.Catalog;+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Discounts;+using Grand.Domain.Stores;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Business.Catalog.Tests.Services.Discounts;++[TestClass]+public class DiscountHandlerServiceTests+{+ private readonly Mock<IDiscountService> _discountServiceMock;+ private readonly Mock<ICategoryService> _categoryServiceMock;+ private readonly Mock<IBrandService> _brandServiceMock;+ private readonly Mock<ICollectionService> _collectionServiceMock;+ private readonly Mock<IVendorService> _vendorServiceMock;+ private readonly Mock<IDiscountValidationService> _discountValidationServiceMock;+ private readonly CatalogSettings _catalogSettings;+ private readonly DiscountHandlerService _discountApplicationService;++ public DiscountHandlerServiceTests()+ {+ _discountServiceMock = new Mock<IDiscountService>();+ _categoryServiceMock = new Mock<ICategoryService>();+ _brandServiceMock = new Mock<IBrandService>();+ _collectionServiceMock = new Mock<ICollectionService>();+ _vendorServiceMock = new Mock<IVendorService>();+ _discountValidationServiceMock = new Mock<IDiscountValidationService>();+ _catalogSettings = new CatalogSettings { IgnoreDiscounts = false };++ _discountApplicationService = new DiscountHandlerService(+ _discountServiceMock.Object,+ _categoryServiceMock.Object,+ _brandServiceMock.Object,+ _collectionServiceMock.Object,+ _vendorServiceMock.Object,+ _discountValidationServiceMock.Object,+ _catalogSettings);+ }++ [TestMethod]+ public async Task GetAllowedDiscounts_ShouldReturnEmptyList_WhenIgnoreDiscountsIsTrue()+ {+ // Arrange+ _catalogSettings.IgnoreDiscounts = true;+ var product = new Product();+ var customer = new Customer();+ var store = new Store();+ var currency = new Currency();++ // Act+ var result = await _discountApplicationService.GetAllowedDiscounts(product, customer, store, currency);++ // Assert+ Assert.AreEqual(0, result.Count);+ }++ [TestMethod]+ public async Task GetAllowedDiscounts_ShouldReturnDiscounts_WhenDiscountsAreValid()+ {+ // Arrange+ var product = new Product();+ product.AppliedDiscounts.Add("discount1");+ var customer = new Customer();+ var store = new Store();+ var currency = new Currency();++ var discount = new Discount {+ Id = "discount1",+ DiscountTypeId = DiscountType.AssignedToSkus,+ IsCumulative = true,+ MaximumDiscountedQuantity = 10+ };+ var allProductDiscounts = new List<Discount>+ {+ new Discount+ {+ Id = "discount2",+ DiscountTypeId = DiscountType.AssignedToAllProducts,+ IsCumulative = true,+ MaximumDiscountedQuantity = 5+ }+ };+ _discountServiceMock.Setup(x => x.GetDiscountById(It.IsAny<string>())).ReturnsAsync(discount);+ _discountValidationServiceMock.Setup(x => x.ValidateDiscount(It.IsAny<Discount>(), It.IsAny<Customer>(), It.IsAny<Store>(), It.IsAny<Currency>()))+ .ReturnsAsync(new DiscountValidationResult { IsValid = true });+ _discountValidationServiceMock.Setup(x => x.ValidateDiscount(It.IsAny<Discount>(), It.IsAny<Customer>(), It.IsAny<Store>(), It.IsAny<Currency>()))+ .ReturnsAsync(new DiscountValidationResult { IsValid = true });+ _discountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<Discount>());++ // Act+ var result = await _discountApplicationService.GetAllowedDiscounts(product, customer, store, currency);++ // Assert+ Assert.AreEqual(1, result.Count);+ Assert.AreEqual("discount1", result[0].DiscountId);+ }+}\ No newline at end of filediff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.csindex 0d850682a..73370e55c 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs@@ -1,8 +1,5 @@using Grand.Business.Catalog.Services.Prices;using Grand.Business.Common.Services.Directory;-using Grand.Business.Core.Interfaces.Catalog.Brands;-using Grand.Business.Core.Interfaces.Catalog.Categories;-using Grand.Business.Core.Interfaces.Catalog.Collections;using Grand.Business.Core.Interfaces.Catalog.Discounts;using Grand.Business.Core.Interfaces.Catalog.Prices;using Grand.Business.Core.Interfaces.Catalog.Products;@@ -30,15 +27,10 @@ namespace Grand.Business.Catalog.Tests.Services.Prices;[TestClass]public class PriceServiceTests{- private IBrandService _brandService;private CatalogSettings _catalogSettings;- private ICategoryService _categoryService;- private ICollectionService _collectionService;private Currency _currency;private ICurrencyService _currencyService;private CurrencySettings _currencySettings;- private IDiscountService _discountService;- private Mock<IDiscountValidationService> _discountValidationService;private IMediator _eventPublisher;private IPricingService _pricingService;private IProductService _productService;@@ -48,7 +40,8 @@ public class PriceServiceTestsprivate Mock<IDiscountService> tempDiscountServiceMock;private Mock<IProductService> tempProductService;private Mock<IContextAccessor> tempWorkContext;-+ private Mock<IDiscountHandlerService> tempDiscountApplicationService;+ private IDiscountService _discountService;[TestInitialize]public void TestInitialize(){@@ -63,16 +56,6 @@ public class PriceServiceTests_workContext = tempWorkContext.Object;}- tempDiscountServiceMock = new Mock<IDiscountService>();- {- _discountService = tempDiscountServiceMock.Object;- }-- _categoryService = new Mock<ICategoryService>().Object;- _collectionService = new Mock<ICollectionService>().Object;- _brandService = new Mock<IBrandService>().Object;- _discountValidationService = new Mock<IDiscountValidationService>();-tempProductService = new Mock<IProductService>();{_productService = tempProductService.Object;@@ -86,17 +69,23 @@ public class PriceServiceTestsPrimaryExchangeRateCurrencyId = "1",PrimaryStoreCurrencyId = "1"};- //_currencyService = new Mock<ICurrencyService>().Object;+_currency = new Currency {- Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = MidpointRounding.ToEven,+ Id = "1",+ CurrencyCode = "USD",+ Rate = 1,+ Published = true,+ MidpointRoundId = MidpointRounding.ToEven,RoundingTypeId = RoundingType.Rounding001};+ tempDiscountServiceMock = new Mock<IDiscountService>();+ {+ _discountService = tempDiscountServiceMock.Object;+ }var tempCurrency = new Mock<ICurrencyService>();{tempCurrency.Setup(instance => instance.GetPrimaryStoreCurrency()).Returns(Task.FromResult(_currency));- //tempCurrency.Setup(instance => instance.ConvertToPrimaryStoreCurrency(It.IsAny<double>(), _currency)).ReturnsAsync(5);- //_currencyService = tempCurrency.Object;}var cacheManager = new Mock<ICacheBase>().Object;IRepository<Currency> _currencyRepository;@@ -118,17 +107,14 @@ public class PriceServiceTestscacheManager, _currencyRepository, _aclService,_currencySettings, _eventPublisher);+ tempDiscountApplicationService = new Mock<IDiscountHandlerService>();_pricingService = new PricingService(_workContext,- _discountService,- _categoryService,- _brandService,- _collectionService,_productService,_eventPublisher,_currencyService,- _discountValidationService.Object,+ tempDiscountApplicationService.Object,_shoppingCartSettings,_catalogSettings);}@@ -146,7 +132,11 @@ public class PriceServiceTestsproduct.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });var currency = new Currency {- Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = MidpointRounding.ToEven,+ Id = "1",+ CurrencyCode = "USD",+ Rate = 1,+ Published = true,+ MidpointRoundId = MidpointRounding.ToEven,RoundingTypeId = RoundingType.Rounding001};var customer = new Customer();@@ -247,28 +237,18 @@ public class PriceServiceTestsCurrencyCode = _currency.CurrencyCode};- tempDiscountServiceMock.Setup(x => x.GetDiscountById(discount001.Id)).ReturnsAsync(discount001);-product.AppliedDiscounts.Add(discount001.Id);- _discountValidationService.Setup(x => x.ValidateDiscount(discount001, customer, _store, _currency))- .ReturnsAsync(new DiscountValidationResult { IsValid = true });- tempDiscountServiceMock- .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode))- .ReturnsAsync(new List<Discount>());- tempDiscountServiceMock- .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode))- .ReturnsAsync(new List<Discount>());- tempDiscountServiceMock- .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode))- .ReturnsAsync(new List<Discount>());- tempDiscountServiceMock- .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToSkus, "1", _currency.CurrencyCode))- .ReturnsAsync(new List<Discount> { discount001 });-var discountAmount = discount001.DiscountAmount;- tempDiscountServiceMock- .Setup(x => x.GetPreferredDiscount(It.IsAny<List<ApplyDiscount>>(), customer, _currency, product, 49.99))+ tempDiscountApplicationService.Setup(x => x.GetAllowedDiscounts(It.IsAny<Product>(), It.IsAny<Customer>(), It.IsAny<Store>(),+ It.IsAny<Currency>())).ReturnsAsync((new List<ApplyDiscount>() {+ new ApplyDiscount()+ {+ DiscountId = discount001.Id+ }+ }));++ tempDiscountApplicationService.Setup(x => x.GetDiscountAmount(It.IsAny<Product>(), It.IsAny<Customer>(), It.IsAny<Store>(), It.IsAny<Currency>(), It.IsAny<double>())).ReturnsAsync((new List<ApplyDiscount>(), 10));//it should return 39.99 - price cheaper about 10diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.csindex 19208911c..2f4fe616d 100644--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs@@ -67,9 +67,6 @@ public static class ApplicationBuilderExtensionslogger.LogError(exception, exception.Message);}- // Set the response status code and message without throwing- context.Response.StatusCode = StatusCodes.Status500InternalServerError;- await context.Response.WriteAsync("An unexpected error occurred.");});});}diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.csindex dd8268a2a..c777a968a 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs@@ -86,7 +86,7 @@ public class GetShoppingCartHandler : IRequestHandler<GetShoppingCart, ShoppingCOrderSettings orderSettings,ShoppingCartSettings shoppingCartSettings,CatalogSettings catalogSettings,- CommonSettings commonSettings,+ CommonSettings commonSettings,IEnumTranslationService enumTranslationService){_productService = productService;@@ -267,55 +267,55 @@ public class GetShoppingCartHandler : IRequestHandler<GetShoppingCart, ShoppingCcase AttributeControlType.Checkboxes:case AttributeControlType.ColorSquares:case AttributeControlType.ImageSquares:- {- if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any()){- //clear default selection- foreach (var item in attributeModel.Values)- item.IsPreSelected = false;-- //select new values- var selectedValues =- await _checkoutAttributeParser.ParseCheckoutAttributeValues(selectedCheckoutAttributes);- foreach (var attributeValue in selectedValues)- if (attributeModel.Id == attributeValue.CheckoutAttributeId)- foreach (var item in attributeModel.Values)- if (attributeValue.Id == item.Id)- item.IsPreSelected = true;+ if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())+ {+ //clear default selection+ foreach (var item in attributeModel.Values)+ item.IsPreSelected = false;++ //select new values+ var selectedValues =+ await _checkoutAttributeParser.ParseCheckoutAttributeValues(selectedCheckoutAttributes);+ foreach (var attributeValue in selectedValues)+ if (attributeModel.Id == attributeValue.CheckoutAttributeId)+ foreach (var item in attributeModel.Values)+ if (attributeValue.Id == item.Id)+ item.IsPreSelected = true;+ }}- }break;case AttributeControlType.ReadonlyCheckboxes:- {- //do nothing- //values are already pre-set- }+ {+ //do nothing+ //values are already pre-set+ }break;case AttributeControlType.TextBox:case AttributeControlType.MultilineTextbox:case AttributeControlType.Datepicker:- {- if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any()){- var enteredText = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id)- .Select(x => x.Value).ToList();- if (enteredText.Any())- attributeModel.DefaultValue = enteredText[0];+ if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())+ {+ var enteredText = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id)+ .Select(x => x.Value).ToList();+ if (enteredText.Any())+ attributeModel.DefaultValue = enteredText[0];+ }}- }break;case AttributeControlType.FileUpload:- {- if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any()){- var downloadGuidStr = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id)- .Select(x => x.Value).FirstOrDefault();- Guid.TryParse(downloadGuidStr, out var downloadGuid);- var download = await _downloadService.GetDownloadByGuid(downloadGuid);- if (download != null)- attributeModel.DefaultValue = download.DownloadGuid.ToString();+ if (selectedCheckoutAttributes != null && selectedCheckoutAttributes.Any())+ {+ var downloadGuidStr = selectedCheckoutAttributes.Where(x => x.Key == attribute.Id)+ .Select(x => x.Value).FirstOrDefault();+ Guid.TryParse(downloadGuidStr, out var downloadGuid);+ var download = await _downloadService.GetDownloadByGuid(downloadGuid);+ if (download != null)+ attributeModel.DefaultValue = download.DownloadGuid.ToString();+ }}- }break;}@@ -448,12 +448,12 @@ public class GetShoppingCartHandler : IRequestHandler<GetShoppingCart, ShoppingC_priceFormatter.FormatPrice(cartItemModel.UnitPriceWithoutDiscountValue);cartItemModel.UnitPriceValue = productprices.productprice;cartItemModel.UnitPrice = _priceFormatter.FormatPrice(productprices.productprice);- if (appliedDiscounts != null && appliedDiscounts.Any())+ if (appliedDiscounts.Any()){- var discount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault().DiscountId);- if (discount is { MaximumDiscountedQuantity: not null })- cartItemModel.DiscountedQty = discount.MaximumDiscountedQuantity.Value;-+ if (appliedDiscounts.Any(x => x.MaximumDiscountedQuantity.HasValue))+ {+ cartItemModel.DiscountedQty = appliedDiscounts.Where(x => x.MaximumDiscountedQuantity.HasValue).Max(x => x.MaximumDiscountedQuantity.Value);+ }appliedDiscounts.ForEach(x => cartItemModel.Discounts.Add(x.DiscountId));}