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
Minor refactor - discounts services (#470)
Krzysztof Pajak44c24dd202bc
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.csnew file mode 100644index 000000000..95864aa60--- /dev/null+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs@@ -0,0 +1,39 @@+using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Queries.Catalog;+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Discounts;+using MediatR;++namespace Grand.Business.Catalog.Queries.Handlers;++public class GetDiscountAmountProviderHandler : IRequestHandler<GetDiscountAmountProvider, double>+{+ private readonly IDiscountProviderLoader _discountProviderLoader;++ public GetDiscountAmountProviderHandler(IDiscountProviderLoader discountProviderLoader)+ {+ _discountProviderLoader = discountProviderLoader;+ }++ public Task<double> Handle(GetDiscountAmountProvider request, CancellationToken cancellationToken)+ {+ return GetDiscountAmountProvider(request.Discount, request.Customer, request.Product, request.Amount);+ }++ /// <summary>+ /// Get amount from discount amount provider+ /// </summary>+ /// <param name="discount"></param>+ /// <param name="product"></param>+ /// <param name="amount"></param>+ /// <param name="customer"></param>+ /// <returns></returns>+ private async Task<double> GetDiscountAmountProvider(Discount discount, Customer customer, Product product, double amount)+ {+ var discountAmountProvider = _discountProviderLoader.LoadDiscountAmountProviderBySystemName(discount.DiscountPluginName);+ if (discountAmountProvider == null)+ return 0;+ return await discountAmountProvider.DiscountAmount(discount, customer, product, amount);+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.csnew file mode 100644index 000000000..c26d64250--- /dev/null+++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountUsageHistoryQueryHandler.cs@@ -0,0 +1,35 @@+using Grand.Business.Core.Queries.Catalog;+using Grand.Data;+using Grand.Domain;+using Grand.Domain.Discounts;+using MediatR;++namespace Grand.Business.Catalog.Queries.Handlers;++public class GetDiscountUsageHistoryQueryHandler : IRequestHandler<GetDiscountUsageHistoryQuery, IPagedList<DiscountUsageHistory>>+{+ private readonly IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;++ public GetDiscountUsageHistoryQueryHandler(IRepository<DiscountUsageHistory> discountUsageHistoryRepository)+ {+ _discountUsageHistoryRepository = discountUsageHistoryRepository;+ }++ public async Task<IPagedList<DiscountUsageHistory>> Handle(GetDiscountUsageHistoryQuery request, CancellationToken cancellationToken)+ {+ var query = from d in _discountUsageHistoryRepository.Table+ select d;++ if (!string.IsNullOrEmpty(request.DiscountId))+ query = query.Where(duh => duh.DiscountId == request.DiscountId);+ if (!string.IsNullOrEmpty(request.CustomerId))+ query = query.Where(duh => duh.CustomerId == request.CustomerId);+ if (!string.IsNullOrEmpty(request.OrderId))+ query = query.Where(duh => duh.OrderId == request.OrderId);+ if (request.Canceled.HasValue)+ query = query.Where(duh => duh.Canceled == request.Canceled.Value);+ query = query.OrderByDescending(c => c.CreatedOnUtc);++ return await PagedList<DiscountUsageHistory>.Create(query, request.PageIndex, request.PageSize);+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.csnew file mode 100644index 000000000..c251ca9ad--- /dev/null+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs@@ -0,0 +1,64 @@+using Grand.Business.Core.Interfaces.Catalog.Discounts;++namespace Grand.Business.Catalog.Services.Discounts;++public class DiscountProviderLoader : IDiscountProviderLoader+{+ private readonly IEnumerable<IDiscountProvider> _discountProviders;+ private readonly IEnumerable<IDiscountAmountProvider> _discountAmountProviders;++ public DiscountProviderLoader(IEnumerable<IDiscountProvider> discountProviders, IEnumerable<IDiscountAmountProvider> discountAmountProviders)+ {+ _discountProviders = discountProviders;+ _discountAmountProviders = discountAmountProviders;+ }++ /// <summary>+ /// Load discount provider by rule system name+ /// </summary>+ /// <param name="ruleSystemName">Rule system name</param>+ /// <returns>Found discount</returns>+ public virtual IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName)+ {+ var discountPlugins = LoadAllDiscountProviders();+ foreach (var discountPlugin in discountPlugins)+ {+ var rules = discountPlugin.GetRequirementRules();++ if (!rules.Any(x => x.SystemName.Equals(ruleSystemName, StringComparison.OrdinalIgnoreCase)))+ continue;+ return discountPlugin;+ }+ return null;+ }++ /// <summary>+ /// Load all discount providers+ /// </summary>+ /// <returns>Discount providers</returns>+ public virtual IList<IDiscountProvider> LoadAllDiscountProviders()+ {+ return _discountProviders.ToList();+ }++ /// <summary>+ /// Get all discount amount providers+ /// </summary>+ /// <returns></returns>+ public virtual IList<IDiscountAmountProvider> LoadDiscountAmountProviders()+ {+ return _discountAmountProviders.ToList();+ }++ /// <summary>+ /// Load discount amountProviderBySystemName+ /// </summary>+ /// <param name="systemName"></param>+ /// <returns></returns>+ public virtual IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName)+ {+ return _discountAmountProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));+ }+++}\ No newline at end of filediff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.csindex 2598d4d06..766dedd45 100644--- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs@@ -1,4 +1,5 @@using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Queries.Catalog;using Grand.Business.Core.Utilities.Catalog;using Grand.Domain;using Grand.Domain.Catalog;@@ -6,8 +7,6 @@ using Grand.Domain.Customers;using Grand.Data;using Grand.Domain.Directory;using Grand.Domain.Discounts;-using Grand.Domain.Orders;-using Grand.Infrastructure;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Configuration;@@ -28,9 +27,6 @@ namespace Grand.Business.Catalog.Services.Discountsprivate readonly IRepository<DiscountCoupon> _discountCouponRepository;private readonly IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;private readonly ICacheBase _cacheBase;- private readonly IWorkContext _workContext;- private readonly IEnumerable<IDiscountProvider> _discountProviders;- private readonly IEnumerable<IDiscountAmountProvider> _discountAmountProviders;private readonly IMediator _mediator;private readonly AccessControlConfig _accessControlConfig;@@ -45,18 +41,12 @@ namespace Grand.Business.Catalog.Services.DiscountsIRepository<Discount> discountRepository,IRepository<DiscountCoupon> discountCouponRepository,IRepository<DiscountUsageHistory> discountUsageHistoryRepository,- IWorkContext workContext,- IEnumerable<IDiscountProvider> discountProviders,- IEnumerable<IDiscountAmountProvider> discountAmountProviders,IMediator mediator, AccessControlConfig accessControlConfig){_cacheBase = cacheBase;_discountRepository = discountRepository;_discountCouponRepository = discountCouponRepository;_discountUsageHistoryRepository = discountUsageHistoryRepository;- _workContext = workContext;- _discountProviders = discountProviders;- _discountAmountProviders = discountAmountProviders;_mediator = mediator;_accessControlConfig = accessControlConfig;}@@ -77,58 +67,64 @@ namespace Grand.Business.Catalog.Services.Discounts}/// <summary>- /// Gets all discounts+ /// Gets active discounts by context/// </summary>/// <returns>Discounts</returns>- public virtual async Task<IList<Discount>> GetAllDiscounts(DiscountType? discountType,- string storeId = "", string currencyCode = "", string couponCode = "", string discountName = "", bool showHidden = false)+ public virtual async Task<IList<Discount>> GetActiveDiscountsByContext(DiscountType discountType, string storeId = "", string currencyCode = ""){- var key = string.Format(CacheKey.DISCOUNTS_ALL_KEY, showHidden, storeId, currencyCode, couponCode, discountName);- var result = await _cacheBase.GetAsync(key, async () =>- {- var query = from m in _discountRepository.Table- select m;- if (!showHidden)- {- var nowUtc = DateTime.UtcNow;- query = query.Where(d =>- (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc)- && (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc)- && d.IsEnabled);- }- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)- {- //Store acl- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(storeId)- select p;- }- if (!string.IsNullOrEmpty(couponCode))- {- var coupon = await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode);- if (coupon != null)- query = query.Where(d => d.Id == coupon.DiscountId);- }- if (!string.IsNullOrEmpty(discountName))- {- query = query.Where(d => d.Name != null && d.Name.ToLower().Contains(discountName.ToLower()));- }- if (!string.IsNullOrEmpty(currencyCode))- {- query = query.Where(d => d.CurrencyCode == currencyCode);- }- query = query.OrderBy(d => d.Name);+ var key = string.Format(CacheKey.DISCOUNTS_CONTEXT_KEY, discountType, storeId, currencyCode);+ var allDiscounts = await _cacheBase.GetAsync(key, () => GetDiscountsQuery(discountType, storeId, currencyCode));++ var nowUtc = DateTime.UtcNow;+ var filteredDiscounts =+ allDiscounts.Where(d => d.IsEnabled &&+ (!d.StartDateUtc.HasValue || d.StartDateUtc <= nowUtc) &&+ (!d.EndDateUtc.HasValue || d.EndDateUtc >= nowUtc));++ return filteredDiscounts.ToList();+ }+ public virtual async Task<IList<Discount>> GetDiscountsQuery(DiscountType? discountType, string storeId = "", string currencyCode = "",+ string couponCode = "", string discountName = "")+ {+ var query = _discountRepository.Table.AsQueryable();- var discounts = await Task.FromResult(query.ToList());- return discounts;- });if (discountType.HasValue){- result = result.Where(d => d.DiscountTypeId == discountType.Value).ToList();+ query = query.Where(d => d.DiscountTypeId == discountType);+ }++ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)+ {+ query = query.Where(d => !d.LimitedToStores || d.Stores.Contains(storeId));}- return result;- }+ if (!string.IsNullOrEmpty(couponCode))+ {+ var couponDiscountId = _discountCouponRepository.Table+ .Where(x => x.CouponCode == couponCode)+ .Select(x => x.DiscountId)+ .FirstOrDefault();+ if (couponDiscountId != default)+ query = query.Where(d => d.Id == couponDiscountId);+ else+ query = query.Where(d => false);+ }++ if (!string.IsNullOrEmpty(discountName))+ {+ query = query.Where(d => d.Name != null && d.Name.Contains(discountName, StringComparison.CurrentCultureIgnoreCase));+ }++ if (!string.IsNullOrEmpty(currencyCode))+ {+ query = query.Where(d => d.CurrencyCode == currencyCode);+ }++ query = query.OrderBy(d => d.Name);++ return await Task.FromResult(query.ToList());+ }+/// <summary>/// Inserts a discount/// </summary>@@ -169,10 +165,6 @@ namespace Grand.Business.Catalog.Services.Discounts{ArgumentNullException.ThrowIfNull(discount);- var usageHistory = await GetAllDiscountUsageHistory(discount.Id);- if (usageHistory.Count > 0)- throw new ArgumentException("Discount was used and have a history");-await _discountRepository.DeleteAsync(discount);await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);@@ -181,34 +173,6 @@ namespace Grand.Business.Catalog.Services.Discountsawait _mediator.EntityDeleted(discount);}- /// <summary>- /// Load discount provider by rule system name- /// </summary>- /// <param name="ruleSystemName">Rule system name</param>- /// <returns>Found discount</returns>- public virtual IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName)- {- var discountPlugins = LoadAllDiscountProviders();- foreach (var discountPlugin in discountPlugins)- {- var rules = discountPlugin.GetRequirementRules();-- if (!rules.Any(x => x.SystemName.Equals(ruleSystemName, StringComparison.OrdinalIgnoreCase)))- continue;- return discountPlugin;- }- return null;- }-- /// <summary>- /// Load all discount providers- /// </summary>- /// <returns>Discount providers</returns>- public virtual IList<IDiscountProvider> LoadAllDiscountProviders()- {- return _discountProviders.ToList();- }-/// <summary>/// Get discount by coupon code@@ -229,29 +193,6 @@ namespace Grand.Business.Catalog.Services.Discountsreturn discount;}- /// <summary>- /// Exist coupon code in discount- /// </summary>- /// <param name="couponCode"></param>- /// <param name="discountId"></param>- /// <param name="used"></param>- /// <returns></returns>- public virtual async Task<bool> ExistsCodeInDiscount(string couponCode, string discountId, bool? used)- {- if (string.IsNullOrWhiteSpace(couponCode))- return false;-- var query = _discountCouponRepository.Table.Where(x => x.CouponCode == couponCode- && x.DiscountId == discountId);-- if (used.HasValue)- query = query.Where(x => x.Used == used.Value);-- var result = await Task.FromResult(query.ToList());-- return result.Any();- }-/// <summary>/// Get all coupon codes for discount/// </summary>@@ -299,6 +240,9 @@ namespace Grand.Business.Catalog.Services.Discountspublic virtual async Task DeleteDiscountCoupon(DiscountCoupon coupon){await _discountCouponRepository.DeleteAsync(coupon);++ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);}/// <summary>@@ -308,6 +252,9 @@ namespace Grand.Business.Catalog.Services.Discountspublic virtual async Task InsertDiscountCoupon(DiscountCoupon coupon){await _discountCouponRepository.InsertAsync(coupon);++ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY);}/// <summary>@@ -352,183 +299,7 @@ namespace Grand.Business.Catalog.Services.Discounts}}- /// <summary>- /// Validate discount- /// </summary>- /// <param name="discount">Discount</param>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <returns>Discount validation result</returns>- public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency)- {- ArgumentNullException.ThrowIfNull(discount);-- string[] couponCodesToValidate = null;- if (customer != null)- couponCodesToValidate = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);-- return await ValidateDiscount(discount, customer, currency, couponCodesToValidate);- }-- /// <summary>- /// Validate discount- /// </summary>- /// <param name="discount">Discount</param>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <param name="couponCodeToValidate">Coupon code</param>- /// <returns>Discount validation result</returns>- public virtual Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency, string couponCodeToValidate)- {- var couponCodes = string.IsNullOrWhiteSpace(couponCodeToValidate) ? Array.Empty<string>() : [- couponCodeToValidate- ];- return ValidateDiscount(discount, customer, currency, couponCodes);- }-- /// <summary>- /// Validate discount- /// </summary>- /// <param name="discount">Discount</param>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <param name="couponCodesToValidate">Coupon codes</param>- /// <returns>Discount validation result</returns>- public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency, string[] couponCodesToValidate)- {- ArgumentNullException.ThrowIfNull(discount);- ArgumentNullException.ThrowIfNull(customer);-- var result = new DiscountValidationResult();-- //is enabled and use the same currency- if (!discount.IsEnabled || discount.CurrencyCode != currency.CurrencyCode)- return result;-- //do not allow use discount in the current store- if (discount.LimitedToStores && discount.Stores.All(x => _workContext.CurrentStore.Id != x))- {- result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedInStore";- return result;- }-- //check coupon code- if (discount.RequiresCouponCode)- {- if (couponCodesToValidate == null || !couponCodesToValidate.Any())- return result;- var exists = false;- foreach (var item in couponCodesToValidate)- {- if (discount.Reused)- {- if (!await ExistsCodeInDiscount(item, discount.Id, null)) continue;- result.CouponCode = item;- exists = true;- }- else- {- if (!await ExistsCodeInDiscount(item, discount.Id, false)) continue;- result.CouponCode = item;- exists = true;- }- }- if (!exists)- return result;- }-- if (discount.DiscountTypeId is DiscountType.AssignedToOrderSubTotal or DiscountType.AssignedToOrderTotal)- {- var cart = customer.ShoppingCartItems- .Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)- .ToList();-- var hasGiftVouchers = cart.Any(x => x.IsGiftVoucher);- if (hasGiftVouchers)- {- result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedWithGiftVouchers";- return result;- }- }- //time range check- DateTime now = DateTime.UtcNow;- if (discount.StartDateUtc.HasValue)- {- DateTime startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc);- if (startDate.CompareTo(now) > 0)- {- result.UserErrorResource = "ShoppingCart.Discount.NotStartedYet";- return result;- }- }- if (discount.EndDateUtc.HasValue)- {- DateTime endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc);- if (endDate.CompareTo(now) < 0)- {- result.UserErrorResource = "ShoppingCart.Discount.Expired";- return result;- }- }-- //discount limitation - n times and n times per user- switch (discount.DiscountLimitationId)- {- case DiscountLimitationType.NTimes:- {- var usedTimes = await GetAllDiscountUsageHistory(discount.Id, null, null, false, 0, 1);- if (usedTimes.TotalCount >= discount.LimitationTimes)- return result;- }- break;- case DiscountLimitationType.NTimesPerUser:- {- var usedTimes = await GetAllDiscountUsageHistory(discount.Id, customer.Id, null, false, 0, 1);- if (usedTimes.TotalCount >= discount.LimitationTimes)- {- result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedAnymore";- return result;- }- }- break;- case DiscountLimitationType.Nolimits:- default:- break;- }-- //discount requirements- var discountRules = discount.DiscountRules.ToList();- foreach (var rule in discountRules)- {- //load a plugin- var discountRequirementPlugin = LoadDiscountProviderByRuleSystemName(rule.DiscountRequirementRuleSystemName);-- if (discountRequirementPlugin == null)- continue;-- if (!discountRequirementPlugin.IsAuthenticateStore(_workContext.CurrentStore))- continue;-- var ruleRequest = new DiscountRuleValidationRequest- {- DiscountRule = rule,- Discount = discount,- Customer = customer,- Store = _workContext.CurrentStore- };- var singleRequirementRule = discountRequirementPlugin.GetRequirementRules().FirstOrDefault(x => x.SystemName.Equals(rule.DiscountRequirementRuleSystemName, StringComparison.OrdinalIgnoreCase));- if (singleRequirementRule == null) return result;- var ruleResult = await singleRequirementRule.CheckRequirement(ruleRequest);- if (ruleResult.IsValid) continue;- result.UserErrorResource = ruleResult.UserError;-- return result;- }-- result.IsValid = true;- return result;-- }+/// <summary>/// Gets a discount usage history record/// </summary>@@ -538,37 +309,7 @@ namespace Grand.Business.Catalog.Services.Discounts{return _discountUsageHistoryRepository.GetByIdAsync(discountUsageHistoryId);}-- /// <summary>- /// Gets all discount usage history records- /// </summary>- /// <param name="discountId">Discount identifier; use null to load all records</param>- /// <param name="customerId">Customer identifier; use null to load all records</param>- /// <param name="orderId">Order identifier; null to load all records</param>- /// <param name="canceled">Canceled</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>Discount usage history records</returns>- public virtual async Task<IPagedList<DiscountUsageHistory>> GetAllDiscountUsageHistory(string discountId = "",- string customerId = "", string orderId = "", bool? canceled = null,- int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from d in _discountUsageHistoryRepository.Table- select d;-- if (!string.IsNullOrEmpty(discountId))- query = query.Where(duh => duh.DiscountId == discountId);- if (!string.IsNullOrEmpty(customerId))- query = query.Where(duh => duh.CustomerId == customerId);- if (!string.IsNullOrEmpty(orderId))- query = query.Where(duh => duh.OrderId == orderId);- if (canceled.HasValue)- query = query.Where(duh => duh.Canceled == canceled.Value);- query = query.OrderByDescending(c => c.CreatedOnUtc);-- return await PagedList<DiscountUsageHistory>.Create(query, pageIndex, pageSize);- }-+/// <summary>/// Insert discount usage history item/// </summary>@@ -621,7 +362,7 @@ namespace Grand.Business.Catalog.Services.Discounts}/// <summary>- /// Get discount amount from plugin+ /// Get discount amount/// </summary>/// <param name="discount">Discount</param>/// <param name="amount">Amount</param>@@ -645,7 +386,7 @@ namespace Grand.Business.Catalog.Services.Discounts}else{- result = await GetDiscountAmountProvider(discount, customer, product, amount);+ result = await _mediator.Send(new GetDiscountAmountProvider(discount, customer, product, currency, amount));}//validate maximum discount amount@@ -728,37 +469,6 @@ namespace Grand.Business.Catalog.Services.Discountsreturn await GetPreferredDiscount(discounts, customer, currency, null, amount);}- /// <summary>- /// Get amount from discount amount provider- /// </summary>- /// <param name="discount"></param>- /// <param name="product"></param>- /// <param name="amount"></param>- /// <param name="customer"></param>- /// <returns></returns>- public virtual async Task<double> GetDiscountAmountProvider(Discount discount, Customer customer, Product product, double amount)- {- var discountAmountProvider = LoadDiscountAmountProviderBySystemName(discount.DiscountPluginName);- if (discountAmountProvider == null)- return 0;- return await discountAmountProvider.DiscountAmount(discount, customer, product, amount);- }--- public virtual IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName)- {- return _discountAmountProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));- }-- /// <summary>- /// Get all discount amount providers- /// </summary>- /// <returns></returns>- public virtual IList<IDiscountAmountProvider> LoadDiscountAmountProviders()- {- return _discountAmountProviders.ToList();- }-#endregion}}diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.csnew file mode 100644index 000000000..975195374--- /dev/null+++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs@@ -0,0 +1,241 @@+using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Queries.Catalog;+using Grand.Business.Core.Utilities.Catalog;+using Grand.Data;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Discounts;+using Grand.Domain.Orders;+using Grand.Domain.Stores;+using Grand.Infrastructure.Extensions;+using MediatR;++namespace Grand.Business.Catalog.Services.Discounts;++public class DiscountValidationService : IDiscountValidationService+{+ private readonly IDiscountProviderLoader _discountProviderLoader;+ private readonly IMediator _mediator;+ private readonly IRepository<DiscountCoupon> _discountCouponRepository;++ public DiscountValidationService(+ IDiscountProviderLoader discountProviderLoader,+ IRepository<DiscountCoupon> discountCouponRepository,+ IMediator mediator)+ {+ _discountCouponRepository = discountCouponRepository;+ _mediator = mediator;+ _discountProviderLoader = discountProviderLoader;+ }++ /// <summary>+ /// Validate discount+ /// </summary>+ /// <param name="discount">Discount</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <returns>Discount validation result</returns>+ public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store,+ Currency currency)+ {+ ArgumentNullException.ThrowIfNull(discount);++ string[] couponCodesToValidate = null;+ if (customer != null)+ couponCodesToValidate = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);++ return await ValidateDiscount(discount, customer, store, currency, couponCodesToValidate);+ }++ /// <summary>+ /// Validate discount+ /// </summary>+ /// <param name="discount">Discount</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <param name="couponCodeToValidate">Coupon code</param>+ /// <returns>Discount validation result</returns>+ public virtual Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store,+ Currency currency, string couponCodeToValidate)+ {+ var couponCodes = string.IsNullOrWhiteSpace(couponCodeToValidate)+ ? Array.Empty<string>()+ : [+ couponCodeToValidate+ ];+ return ValidateDiscount(discount, customer, store, currency, couponCodes);+ }++ /// <summary>+ /// Validate discount+ /// </summary>+ /// <param name="discount">Discount</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <param name="couponCodesToValidate">Coupon codes</param>+ /// <returns>Discount validation result</returns>+ public virtual async Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store,+ Currency currency, string[] couponCodesToValidate)+ {+ ArgumentNullException.ThrowIfNull(discount);+ ArgumentNullException.ThrowIfNull(customer);++ var result = new DiscountValidationResult();++ //is enabled and use the same currency+ if (!discount.IsEnabled || discount.CurrencyCode != currency.CurrencyCode)+ return result;++ //time range check+ DateTime now = DateTime.UtcNow;+ if (discount.StartDateUtc.HasValue)+ {+ DateTime startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc);+ if (startDate.CompareTo(now) > 0)+ {+ result.UserErrorResource = "ShoppingCart.Discount.NotStartedYet";+ return result;+ }+ }++ if (discount.EndDateUtc.HasValue)+ {+ DateTime endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc);+ if (endDate.CompareTo(now) < 0)+ {+ result.UserErrorResource = "ShoppingCart.Discount.Expired";+ return result;+ }+ }++ //do not allow use discount in the current store+ if (discount.LimitedToStores && discount.Stores.All(x => store.Id != x))+ {+ result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedInStore";+ return result;+ }++ //check coupon code+ if (discount.RequiresCouponCode)+ {+ if (couponCodesToValidate == null || couponCodesToValidate.Length == 0)+ return result;+ var exists = false;+ foreach (var item in couponCodesToValidate)+ {+ if (discount.Reused)+ {+ if (!await ExistsCodeInDiscount(item, discount.Id, null)) continue;+ result.CouponCode = item;+ exists = true;+ }+ else+ {+ if (!await ExistsCodeInDiscount(item, discount.Id, false)) continue;+ result.CouponCode = item;+ exists = true;+ }+ }++ if (!exists)+ return result;+ }++ if (discount.DiscountTypeId is DiscountType.AssignedToOrderSubTotal or DiscountType.AssignedToOrderTotal)+ {+ var cart = customer.ShoppingCartItems+ .Where(sci => sci.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)+ .ToList();++ var hasGiftVouchers = cart.Any(x => x.IsGiftVoucher);+ if (hasGiftVouchers)+ {+ result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedWithGiftVouchers";+ return result;+ }+ }++ //discount limitation - n times and n times per user+ switch (discount.DiscountLimitationId)+ {+ case DiscountLimitationType.NTimes:+ {+ var usedTimes = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id, PageSize = 1 });+ if (usedTimes.TotalCount >= discount.LimitationTimes)+ return result;+ }+ break;+ case DiscountLimitationType.NTimesPerUser:+ {+ var usedTimes = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id, CustomerId = customer.Id, PageSize = 1 });+ if (usedTimes.TotalCount >= discount.LimitationTimes)+ {+ result.UserErrorResource = "ShoppingCart.Discount.CannotBeUsedAnymore";+ return result;+ }+ }+ break;+ case DiscountLimitationType.Nolimits:+ default:+ break;+ }++ //discount requirements+ var discountRules = discount.DiscountRules.ToList();+ foreach (var rule in discountRules)+ {+ //load a plugin+ var discountRequirementPlugin =+ _discountProviderLoader.LoadDiscountProviderByRuleSystemName(rule.DiscountRequirementRuleSystemName);++ if (discountRequirementPlugin == null)+ continue;++ if (!discountRequirementPlugin.IsAuthenticateStore(store))+ continue;++ var ruleRequest = new DiscountRuleValidationRequest {+ DiscountRule = rule,+ Discount = discount,+ Customer = customer,+ Store = store+ };+ var singleRequirementRule = discountRequirementPlugin.GetRequirementRules().FirstOrDefault(x =>+ x.SystemName.Equals(rule.DiscountRequirementRuleSystemName, StringComparison.OrdinalIgnoreCase));+ if (singleRequirementRule == null) return result;+ var ruleResult = await singleRequirementRule.CheckRequirement(ruleRequest);+ if (ruleResult.IsValid) continue;+ result.UserErrorResource = ruleResult.UserError;++ return result;+ }++ result.IsValid = true;+ return result;+ }++ /// <summary>+ /// Exist coupon code in discount+ /// </summary>+ /// <param name="couponCode"></param>+ /// <param name="discountId"></param>+ /// <param name="used"></param>+ /// <returns></returns>+ public async Task<bool> ExistsCodeInDiscount(string couponCode, string discountId, bool? used)+ {+ if (string.IsNullOrWhiteSpace(couponCode))+ return false;++ var query = _discountCouponRepository.Table.Where(x => x.CouponCode == couponCode+ && x.DiscountId == discountId);++ if (used.HasValue)+ query = query.Where(x => x.Used == used.Value);++ var result = await Task.FromResult(query.ToList());+ return result.Count != 0;+ }+}\ 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 f01741132..7d3358c11 100644--- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs@@ -16,6 +16,7 @@ using Grand.Domain.Discounts;using Grand.Domain.Orders;using MediatR;using Grand.Business.Core.Interfaces.Catalog.Brands;+using Grand.Domain.Stores;using System.Globalization;namespace Grand.Business.Catalog.Services.Prices@@ -35,6 +36,7 @@ namespace Grand.Business.Catalog.Services.Pricesprivate readonly IProductService _productService;private readonly IMediator _mediator;private readonly ICurrencyService _currencyService;+ private readonly IDiscountValidationService _discountValidationService;private readonly ShoppingCartSettings _shoppingCartSettings;private readonly CatalogSettings _catalogSettings;@@ -50,6 +52,7 @@ namespace Grand.Business.Catalog.Services.PricesIProductService productService,IMediator mediator,ICurrencyService currencyService,+ IDiscountValidationService discountValidationService,ShoppingCartSettings shoppingCartSettings,CatalogSettings catalogSettings){@@ -64,6 +67,7 @@ namespace Grand.Business.Catalog.Services.Prices_currencyService = currencyService;_shoppingCartSettings = shoppingCartSettings;_catalogSettings = catalogSettings;+ _discountValidationService = discountValidationService;}#endregion@@ -87,9 +91,10 @@ namespace Grand.Business.Catalog.Services.Prices/// </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, Currency currency)+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToProduct(Product product, Customer customer, Store store, Currency currency){var allowedDiscounts = new List<ApplyDiscount>();if (_catalogSettings.IgnoreDiscounts)@@ -100,7 +105,7 @@ namespace Grand.Business.Catalog.Services.Prices{var discount = await _discountService.GetDiscountById(appliedDiscount);if (discount == null) continue;- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&discount.DiscountTypeId == DiscountType.AssignedToSkus)allowedDiscounts.Add(new ApplyDiscount {@@ -112,16 +117,16 @@ namespace Grand.Business.Catalog.Services.Pricesreturn allowedDiscounts;}- protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToAllProduct(Product product, Customer customer, Currency currency)+ 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.GetAllDiscounts(DiscountType.AssignedToAllProducts, storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);+ var discounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, storeId: store.Id, currencyCode: currency.CurrencyCode);foreach (var discount in discounts){- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid)allowedDiscounts.Add(new ApplyDiscount {CouponCode = validDiscount.CouponCode,@@ -138,9 +143,10 @@ namespace Grand.Business.Catalog.Services.Prices/// </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, Currency currency)+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCategories(Product product, Customer customer, Store store, Currency currency){var allowedDiscounts = new List<ApplyDiscount>();if (_catalogSettings.IgnoreDiscounts)@@ -154,7 +160,7 @@ namespace Grand.Business.Catalog.Services.Prices{var discount = await _discountService.GetDiscountById(appliedDiscount);if (discount == null) continue;- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid && discount.DiscountTypeId == DiscountType.AssignedToCategories)allowedDiscounts.Add(new ApplyDiscount {CouponCode = validDiscount.CouponCode,@@ -165,14 +171,16 @@ namespace Grand.Business.Catalog.Services.Prices}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, Currency currency)+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToBrands(Product product, Customer customer, Store store, Currency currency){var allowedDiscounts = new List<ApplyDiscount>();if (_catalogSettings.IgnoreDiscounts)@@ -186,7 +194,7 @@ namespace Grand.Business.Catalog.Services.Prices{var discount = await _discountService.GetDiscountById(appliedDiscount);if (discount == null) continue;- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&discount.DiscountTypeId == DiscountType.AssignedToBrands)allowedDiscounts.Add(new ApplyDiscount {@@ -203,9 +211,10 @@ namespace Grand.Business.Catalog.Services.Prices/// </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, Currency currency)+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToCollections(Product product, Customer customer, Store store, Currency currency){var allowedDiscounts = new List<ApplyDiscount>();if (_catalogSettings.IgnoreDiscounts)@@ -219,7 +228,7 @@ namespace Grand.Business.Catalog.Services.Prices{var discount = await _discountService.GetDiscountById(appliedDiscount);if (discount == null) continue;- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&discount.DiscountTypeId == DiscountType.AssignedToCollections)allowedDiscounts.Add(new ApplyDiscount {@@ -237,9 +246,10 @@ namespace Grand.Business.Catalog.Services.Prices/// </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, Currency currency)+ protected virtual async Task<IList<ApplyDiscount>> GetAllowedDiscountsAppliedToVendors(Product product, Customer customer, Store store, Currency currency){var allowedDiscounts = new List<ApplyDiscount>();if (_catalogSettings.IgnoreDiscounts)@@ -254,7 +264,7 @@ namespace Grand.Business.Catalog.Services.Prices{var discount = await _discountService.GetDiscountById(appliedDiscount);if (discount == null) continue;- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount = await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&discount.DiscountTypeId == DiscountType.AssignedToVendors)allowedDiscounts.Add(new ApplyDiscount {@@ -271,41 +281,42 @@ namespace Grand.Business.Catalog.Services.Prices/// </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, Currency currency)+ 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, currency))+ 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, currency))+ 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, currency))+ 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, currency))+ 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, currency))+ 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, currency))+ foreach (var discount in await GetAllowedDiscountsAppliedToVendors(product, customer, store, currency))if (allowedDiscounts.All(x => x.DiscountId != discount.DiscountId))allowedDiscounts.Add(discount);@@ -317,11 +328,12 @@ namespace Grand.Business.Catalog.Services.Prices/// </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, Currency currency, double productPriceWithoutDiscount)+ Customer customer, Store store, Currency currency, double productPriceWithoutDiscount){ArgumentNullException.ThrowIfNull(product);@@ -333,7 +345,7 @@ namespace Grand.Business.Catalog.Services.Pricesif (_catalogSettings.IgnoreDiscounts)return (0, null);- var allowedDiscounts = await GetAllowedDiscounts(product, customer, currency);+ var allowedDiscounts = await GetAllowedDiscounts(product, customer, store, currency);//no discountsif (!allowedDiscounts.Any())@@ -354,6 +366,7 @@ namespace Grand.Business.Catalog.Services.Prices/// </summary>/// <param name="product">Product</param>/// <param name="customer">The customer</param>+ /// <param name="store">Store</param>/// <param name="currency">The currency</param>/// <param name="additionalCharge">Additional charge</param>/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>@@ -362,12 +375,13 @@ namespace Grand.Business.Catalog.Services.Pricespublic virtual async Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice preferredTierPrice)> GetFinalPrice(Product product,Customer customer,+ Store store,Currency currency,double additionalCharge = 0,bool includeDiscounts = true,int quantity = 1){- return await GetFinalPrice(product, customer, currency, additionalCharge, includeDiscounts, quantity, null, null);+ return await GetFinalPrice(product, customer, store, currency, additionalCharge, includeDiscounts, quantity, null, null);}/// <summary>@@ -375,6 +389,7 @@ namespace Grand.Business.Catalog.Services.Prices/// </summary>/// <param name="product">Product</param>/// <param name="customer">The customer</param>+ /// <param name="store">Store</param>/// <param name="currency">Currency</param>/// <param name="additionalCharge">Additional charge</param>/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>@@ -385,6 +400,7 @@ namespace Grand.Business.Catalog.Services.Pricespublic virtual async Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice preferredTierPrice)> GetFinalPrice(Product product,Customer customer,+ Store store,Currency currency,double additionalCharge,bool includeDiscounts,@@ -407,7 +423,7 @@ namespace Grand.Business.Catalog.Services.Pricesawait _currencyService.ConvertFromPrimaryStoreCurrency(product.Price, currency);//tier prices- var tierPrice = product.GetPreferredTierPrice(customer, _workContext.CurrentStore.Id, currency.CurrencyCode, quantity);+ var tierPrice = product.GetPreferredTierPrice(customer, store.Id, currency.CurrencyCode, quantity);if (tierPrice != null){price = tierPrice.Price;@@ -437,7 +453,7 @@ namespace Grand.Business.Catalog.Services.Pricesif (includeDiscounts){//discount- var (tmpDiscountAmount, tmpAppliedDiscounts) = await GetDiscountAmount(product, customer, currency, price);+ var (tmpDiscountAmount, tmpAppliedDiscounts) = await GetDiscountAmount(product, customer, store, currency, price);price -= tmpDiscountAmount;if (tmpAppliedDiscounts != null)@@ -484,6 +500,7 @@ namespace Grand.Business.Catalog.Services.Pricesreturn await GetUnitPrice(product,_workContext.CurrentCustomer,+ _workContext.CurrentStore,_workContext.WorkingCurrency,shoppingCartItem.ShoppingCartTypeId,shoppingCartItem.Quantity,@@ -493,11 +510,13 @@ namespace Grand.Business.Catalog.Services.PricesshoppingCartItem.RentalEndDateUtc,includeDiscounts);}+/// <summary>/// Gets the shopping cart unit price/// </summary>/// <param name="product">Product</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="currency">The currency</param>/// <param name="shoppingCartType">Shopping cart type</param>/// <param name="quantity">Quantity</param>@@ -510,6 +529,7 @@ namespace Grand.Business.Catalog.Services.Pricespublic virtual async Task<(double unitprice, double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetUnitPrice(Product product,Customer customer,+ Store store,Currency currency,ShoppingCartType shoppingCartType,int quantity,@@ -539,7 +559,7 @@ namespace Grand.Business.Catalog.Services.PricesfinalPrice = await _currencyService.ConvertFromPrimaryStoreCurrency(combination.OverriddenPrice.Value, currency);if (combination.TierPrices.Any()){- var storeId = _workContext.CurrentStore.Id;+ var storeId = store.Id;var actualTierPrices = combination.TierPrices.Where(x => string.IsNullOrEmpty(x.StoreId) || x.StoreId == storeId).Where(x => string.IsNullOrEmpty(x.CustomerGroupId) ||customer.Groups.Contains(x.CustomerGroupId)).ToList();@@ -592,6 +612,7 @@ namespace Grand.Business.Catalog.Services.Pricesvar getfinalPrice = await GetFinalPrice(product,customer,+ store,currency,attributesTotalPrice,includeDiscounts,@@ -610,7 +631,7 @@ namespace Grand.Business.Catalog.Services.Prices//roundingif (_shoppingCartSettings.RoundPrices){- finalPrice = RoundingHelper.RoundPrice(finalPrice.Value, _workContext.WorkingCurrency);+ finalPrice = RoundingHelper.RoundPrice(finalPrice.Value, currency);}return (finalPrice.Value, discountAmount, appliedDiscounts);}@@ -641,7 +662,7 @@ namespace Grand.Business.Catalog.Services.Pricesif (appliedDiscounts.Count == 1)oneAndOnlyDiscount = await _discountService.GetDiscountById(appliedDiscounts.FirstOrDefault()?.DiscountId);- if (oneAndOnlyDiscount is { MaximumDiscountedQuantity: { } } &&+ if (oneAndOnlyDiscount is { MaximumDiscountedQuantity: not null } &&shoppingCartItem.Quantity > oneAndOnlyDiscount.MaximumDiscountedQuantity.Value){//we cannot apply discount for all shopping cart items@@ -733,7 +754,10 @@ namespace Grand.Business.Catalog.Services.Pricesvar associatedProduct = await _productService.GetProductById(value.AssociatedProductId);if (associatedProduct != null){- adjustment = (await GetFinalPrice(associatedProduct, _workContext.CurrentCustomer, _workContext.WorkingCurrency,+ adjustment = (await GetFinalPrice(associatedProduct,+ _workContext.CurrentCustomer,+ _workContext.CurrentStore,+ _workContext.WorkingCurrency,additionalCharge: value.PriceAdjustment, includeDiscounts: true)).finalPrice * value.Quantity;}}diff --git a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.csindex 8118a3b33..60f2105b9 100644--- a/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Catalog/Startup/StartupApplication.cs@@ -81,6 +81,8 @@ namespace Grand.Business.Catalog.Startupprivate void RegisterDiscountsService(IServiceCollection serviceCollection){serviceCollection.AddScoped<IDiscountService, DiscountService>();+ serviceCollection.AddScoped<IDiscountValidationService, DiscountValidationService>();+ serviceCollection.AddSingleton<IDiscountProviderLoader, DiscountProviderLoader>();}private 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 d408baa54..f96a49b1a 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs@@ -44,6 +44,7 @@ namespace Grand.Business.Checkout.Services.Ordersprivate readonly IProductService _productService;private readonly ICurrencyService _currencyService;private readonly IGroupService _groupService;+ private readonly IDiscountValidationService _discountValidationService;private readonly TaxSettings _taxSettings;private readonly LoyaltyPointsSettings _loyaltyPointsSettings;private readonly ShippingSettings _shippingSettings;@@ -69,6 +70,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="productService">Product service</param>/// <param name="currencyService">Currency service</param>/// <param name="groupService">Group</param>+ /// <param name="discountValidationService">Discount validation service</param>/// <param name="taxSettings">Tax settings</param>/// <param name="loyaltyPointsSettings">Loyalty points settings</param>/// <param name="shippingSettings">Shipping settings</param>@@ -86,6 +88,7 @@ namespace Grand.Business.Checkout.Services.OrdersIProductService productService,ICurrencyService currencyService,IGroupService groupService,+ IDiscountValidationService discountValidationService,TaxSettings taxSettings,LoyaltyPointsSettings loyaltyPointsSettings,ShippingSettings shippingSettings,@@ -104,6 +107,7 @@ namespace Grand.Business.Checkout.Services.Orders_productService = productService;_currencyService = currencyService;_groupService = groupService;+ _discountValidationService = discountValidationService;_taxSettings = taxSettings;_loyaltyPointsSettings = loyaltyPointsSettings;_shippingSettings = shippingSettings;@@ -119,24 +123,29 @@ namespace Grand.Business.Checkout.Services.Orders/// Gets an order discount (applied to order subtotal)/// </summary>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="currency">Currency</param>/// <param name="orderSubTotal">Order subtotal</param>/// <returns>Order discount</returns>- protected virtual async Task<(double ordersubtotaldiscount, List<ApplyDiscount> appliedDiscounts)> GetOrderSubtotalDiscount(Customer customer, Currency currency, double orderSubTotal)+ protected virtual async Task<(double ordersubtotaldiscount, List<ApplyDiscount> appliedDiscounts)>+ GetOrderSubtotalDiscount(Customer customer, Store store, Currency currency, double orderSubTotal){var appliedDiscounts = new List<ApplyDiscount>();double discountAmount = 0;if (_catalogSettings.IgnoreDiscounts)return (discountAmount, appliedDiscounts);- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToOrderSubTotal, storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);+ var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToOrderSubTotal,+ storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);var allowedDiscounts = new List<ApplyDiscount>();if (allDiscounts != null)foreach (var discount in allDiscounts){- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount =+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal && allowedDiscounts.All(x => x.DiscountId != discount.Id))+ discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal &&+ allowedDiscounts.All(x => x.DiscountId != discount.Id)){allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,@@ -146,7 +155,8 @@ namespace Grand.Business.Checkout.Services.Orders}}- var preferredDiscounts = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, _workContext.WorkingCurrency, orderSubTotal);+ var preferredDiscounts = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,+ _workContext.WorkingCurrency, orderSubTotal);appliedDiscounts = preferredDiscounts.appliedDiscount;discountAmount = preferredDiscounts.discountAmount;@@ -160,24 +170,29 @@ namespace Grand.Business.Checkout.Services.Orders/// Gets a shipping discount/// </summary>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="currency">Currency</param>/// <param name="shippingTotal">Shipping total</param>/// <returns>Shipping discount</returns>- protected virtual async Task<(double shippingDiscount, List<ApplyDiscount> appliedDiscounts)> GetShippingDiscount(Customer customer, Currency currency, double shippingTotal)+ protected virtual async Task<(double shippingDiscount, List<ApplyDiscount> appliedDiscounts)>+ GetShippingDiscount(Customer customer, Store store, Currency currency, double shippingTotal){var appliedDiscounts = new List<ApplyDiscount>();double shippingDiscountAmount = 0;if (_catalogSettings.IgnoreDiscounts)return (shippingDiscountAmount, appliedDiscounts);- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToShipping, storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);+ var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToShipping,+ storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);var allowedDiscounts = new List<ApplyDiscount>();if (allDiscounts != null)foreach (var discount in allDiscounts){- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount =+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToShipping && allowedDiscounts.All(x => x.DiscountId != discount.Id))+ discount.DiscountTypeId == DiscountType.AssignedToShipping &&+ allowedDiscounts.All(x => x.DiscountId != discount.Id)){allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,@@ -187,7 +202,8 @@ namespace Grand.Business.Checkout.Services.Orders}}- var (appliedDiscount, discountAmount) = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, _workContext.WorkingCurrency, shippingTotal);+ var (appliedDiscount, discountAmount) = await _discountService.GetPreferredDiscount(allowedDiscounts,+ customer, _workContext.WorkingCurrency, shippingTotal);appliedDiscounts = appliedDiscount;shippingDiscountAmount = discountAmount;@@ -196,8 +212,10 @@ namespace Grand.Business.Checkout.Services.Ordersif (_shoppingCartSettings.RoundPrices){- shippingDiscountAmount = RoundingHelper.RoundPrice(shippingDiscountAmount, _workContext.WorkingCurrency);+ shippingDiscountAmount =+ RoundingHelper.RoundPrice(shippingDiscountAmount, _workContext.WorkingCurrency);}+return (shippingDiscountAmount, appliedDiscounts);}@@ -205,24 +223,29 @@ namespace Grand.Business.Checkout.Services.Orders/// Gets an order discount (applied to order total)/// </summary>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="currency">Currency</param>/// <param name="orderTotal">Order total</param>/// <returns>Order discount</returns>- protected virtual async Task<(double orderTotalDiscount, List<ApplyDiscount> appliedDiscounts)> GetOrderTotalDiscount(Customer customer, Currency currency, double orderTotal)+ protected virtual async Task<(double orderTotalDiscount, List<ApplyDiscount> appliedDiscounts)>+ GetOrderTotalDiscount(Customer customer, Store store, Currency currency, double orderTotal){var appliedDiscounts = new List<ApplyDiscount>();double discountAmount = 0;if (_catalogSettings.IgnoreDiscounts)return (discountAmount, appliedDiscounts);- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToOrderTotal, storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);+ var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToOrderTotal,+ storeId: _workContext.CurrentStore.Id, currencyCode: currency.CurrencyCode);var allowedDiscounts = new List<ApplyDiscount>();if (allDiscounts != null)foreach (var discount in allDiscounts){- var validDiscount = await _discountService.ValidateDiscount(discount, customer, currency);+ var validDiscount =+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToOrderTotal && allowedDiscounts.All(x => x.DiscountId != discount.Id))+ discount.DiscountTypeId == DiscountType.AssignedToOrderTotal &&+ allowedDiscounts.All(x => x.DiscountId != discount.Id)){allowedDiscounts.Add(new ApplyDiscount {DiscountId = discount.Id,@@ -231,7 +254,9 @@ namespace Grand.Business.Checkout.Services.Orders});}}- var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer, _workContext.WorkingCurrency, orderTotal);++ var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,+ _workContext.WorkingCurrency, orderTotal);appliedDiscounts = preferredDiscount.appliedDiscount;discountAmount = preferredDiscount.discountAmount;@@ -242,6 +267,7 @@ namespace Grand.Business.Checkout.Services.Orders{discountAmount = RoundingHelper.RoundPrice(discountAmount, _workContext.WorkingCurrency);}+return (discountAmount, appliedDiscounts);}@@ -261,7 +287,8 @@ namespace Grand.Business.Checkout.Services.Ordersvar couponCodes = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);foreach (var couponCode in couponCodes){- var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(isGiftVoucherActivated: true, giftVoucherCouponCode: couponCode);+ var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(isGiftVoucherActivated: true,+ giftVoucherCouponCode: couponCode);result.AddRange(giftVouchers.Where(gc => gc.IsGiftVoucherValid(currency, store)));}@@ -278,7 +305,7 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="cart">Cart</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>public virtual async Task<(double discountAmount, List<ApplyDiscount> appliedDiscounts,- double subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>+ double subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax){double discountAmount = 0;@@ -329,15 +356,25 @@ namespace Grand.Business.Checkout.Services.Orders//checkout attributesif (customer != null){- var checkoutAttributes = customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);+ var checkoutAttributes =+ customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,+ _workContext.CurrentStore.Id);var attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes);foreach (var attributeValue in attributeValues){- var checkoutAttributePriceExclTax = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer);- var caExclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceExclTax.checkoutPrice, _workContext.WorkingCurrency);-- var (checkoutPrice, taxRate) = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true, customer);- var caInclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice, _workContext.WorkingCurrency);+ var checkoutAttributePriceExclTax =+ await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false,+ customer);+ var caExclTax =+ await _currencyService.ConvertFromPrimaryStoreCurrency(+ checkoutAttributePriceExclTax.checkoutPrice, _workContext.WorkingCurrency);++ var (checkoutPrice, taxRate) =+ await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true,+ customer);+ var caInclTax =+ await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice,+ _workContext.WorkingCurrency);subTotalExclTaxWithoutDiscount += caExclTax;subTotalInclTaxWithoutDiscount += caInclTax;@@ -364,11 +401,14 @@ namespace Grand.Business.Checkout.Services.Ordersif (_shoppingCartSettings.RoundPrices){- subTotalWithoutDiscount = RoundingHelper.RoundPrice(subTotalWithoutDiscount, _workContext.WorkingCurrency);+ subTotalWithoutDiscount =+ RoundingHelper.RoundPrice(subTotalWithoutDiscount, _workContext.WorkingCurrency);}+//We calculate discount amount on order subtotal excl tax (discount first)//calculate discount amount ('Applied to order subtotal' discount)- var orderSubtotalDiscount = await GetOrderSubtotalDiscount(customer, _workContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);+ var orderSubtotalDiscount = await GetOrderSubtotalDiscount(customer, _workContext.CurrentStore,+ _workContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);var discountAmountExclTax = orderSubtotalDiscount.ordersubtotaldiscount;appliedDiscounts = orderSubtotalDiscount.appliedDiscounts;@@ -440,7 +480,10 @@ namespace Grand.Business.Checkout.Services.Ordersif (isFreeShipping)return 0;- return cart.Where(sci => sci.IsShipEnabled && !sci.IsFreeShipping).Sum(sci => _shippingSettings.AdditionalShippingChargeByQty ? sci.AdditionalShippingChargeProduct * sci.Quantity : sci.AdditionalShippingChargeProduct);+ return cart.Where(sci => sci.IsShipEnabled && !sci.IsFreeShipping).Sum(sci =>+ _shippingSettings.AdditionalShippingChargeByQty+ ? sci.AdditionalShippingChargeProduct * sci.Quantity+ : sci.AdditionalShippingChargeProduct);}/// <summary>@@ -463,7 +506,6 @@ namespace Grand.Business.Checkout.Services.Orders{return true;}-}var shoppingCartRequiresShipping = cart.RequiresShipping();@@ -478,7 +520,8 @@ namespace Grand.Business.Checkout.Services.Orders//free shipping over $Xif (!_shippingSettings.FreeShippingOverXEnabled) return false;//check whether we have subtotal enough to have free shipping- var (_, _, _, subTotalWithDiscount, _) = await GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax);+ var (_, _, _, subTotalWithDiscount, _) =+ await GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax);return subTotalWithDiscount > _shippingSettings.FreeShippingOverXValue;//otherwise, return false@@ -490,7 +533,8 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="shippingRate">Shipping rate to adjust</param>/// <param name="cart">Cart</param>/// <returns>Adjusted shipping rate</returns>- public virtual async Task<(double shippingRate, List<ApplyDiscount> appliedDiscounts)> AdjustShippingRate(double shippingRate, IList<ShoppingCartItem> cart)+ public virtual async Task<(double shippingRate, List<ApplyDiscount> appliedDiscounts)> AdjustShippingRate(+ double shippingRate, IList<ShoppingCartItem> cart){var appliedDiscounts = new List<ApplyDiscount>();@@ -503,8 +547,10 @@ namespace Grand.Business.Checkout.Services.Ordersvar adjustedRate = shippingRate + additionalShippingCharge;//discount- var customer = _workContext.CurrentCustomer;- var (discountAmount, applyDiscounts) = await GetShippingDiscount(customer, _workContext.WorkingCurrency, adjustedRate);+ var (discountAmount, applyDiscounts) = await GetShippingDiscount(+ _workContext.CurrentCustomer,+ _workContext.CurrentStore,+ _workContext.WorkingCurrency, adjustedRate);appliedDiscounts = applyDiscounts;adjustedRate -= discountAmount;@@ -525,7 +571,9 @@ namespace Grand.Business.Checkout.Services.Orders/// </summary>/// <param name="cart">Cart</param>/// <returns>Shipping total</returns>- public virtual async Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)> GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart)+ public virtual async+ Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)>+ GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart){var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;return await GetShoppingCartShippingTotal(cart, includingTax);@@ -538,7 +586,9 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="cart">Cart</param>/// <param name="includingTax">A value indicating whether calculated price should include tax</param>/// <returns>Shipping total</returns>- public virtual async Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)> GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax)+ public virtual async+ Task<(double? shoppingCartShippingTotal, double taxRate, List<ApplyDiscount> appliedDiscounts)>+ GetShoppingCartShippingTotal(IList<ShoppingCartItem> cart, bool includingTax){double? shippingTotal = null;var appliedDiscounts = new List<ApplyDiscount>();@@ -553,7 +603,9 @@ namespace Grand.Business.Checkout.Services.OrdersShippingOption shippingOption = null;if (customer != null)- shippingOption = customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption, _workContext.CurrentStore.Id);+ shippingOption =+ customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption,+ _workContext.CurrentStore.Id);if (shippingOption != null){@@ -569,7 +621,9 @@ namespace Grand.Business.Checkout.Services.Ordersif (customer != null)shippingAddress = customer.ShippingAddress;- var shippingRateMethods = await _shippingService.LoadActiveShippingRateCalculationProviders(_workContext.CurrentCustomer, _workContext.CurrentStore.Id, cart);+ var shippingRateMethods =+ await _shippingService.LoadActiveShippingRateCalculationProviders(_workContext.CurrentCustomer,+ _workContext.CurrentStore.Id, cart);if (!shippingRateMethods.Any() && !_shippingSettings.AllowPickUpInStore)throw new GrandException("Shipping rate method could not be loaded");@@ -631,7 +685,8 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="cart">Shopping cart</param>/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee when calculating tax</param>/// <returns>Tax total</returns>- public virtual async Task<(double taxtotal, SortedDictionary<double, double> taxRates)> GetTaxTotal(IList<ShoppingCartItem> cart, bool usePaymentMethodAdditionalFee = true)+ public virtual async Task<(double taxtotal, SortedDictionary<double, double> taxRates)> GetTaxTotal(+ IList<ShoppingCartItem> cart, bool usePaymentMethodAdditionalFee = true){ArgumentNullException.ThrowIfNull(cart);@@ -694,12 +749,15 @@ namespace Grand.Business.Checkout.Services.Ordersdouble paymentMethodAdditionalFeeTax = 0;if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable){- var paymentMethodAdditionalFee = await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);+ var paymentMethodAdditionalFee =+ await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);- var additionalFeeExclTax = await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer);+ var additionalFeeExclTax =+ await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer);var paymentMethodAdditionalFeeExclTax = additionalFeeExclTax.paymentPrice;- var (paymentMethodAdditionalFeeInclTax, taxRate) = await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);+ var (paymentMethodAdditionalFeeInclTax, taxRate) =+ await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;//ensure that tax is equal or greater than zero@@ -730,6 +788,7 @@ namespace Grand.Business.Checkout.Services.Orders{taxTotal = RoundingHelper.RoundPrice(taxTotal, _workContext.WorkingCurrency);}+return (taxTotal, taxRates);}@@ -741,28 +800,23 @@ namespace Grand.Business.Checkout.Services.Orders/// <param name="useLoyaltyPoints">Use Loyalty Points</param>/// <param name="usePaymentMethodAdditionalFee">A value indicating whether we should use payment method additional fee</param>/// <returns>Shopping cart total, discount amount, applied discounts, gift vouchers, loyalty point/amount</returns>- public virtual async Task<(double? shoppingCartTotal, double discountAmount, List<ApplyDiscount> appliedDiscounts, List<AppliedGiftVoucher> appliedGiftVouchers,- int redeemedLoyaltyPoints, double redeemedLoyaltyPointsAmount)>- GetShoppingCartTotal(IList<ShoppingCartItem> cart, bool? useLoyaltyPoints = null, bool usePaymentMethodAdditionalFee = true)+ public virtual async Task<(double? shoppingCartTotal, double discountAmount, List<ApplyDiscount>+ appliedDiscounts, List<AppliedGiftVoucher> appliedGiftVouchers,+ int redeemedLoyaltyPoints, double redeemedLoyaltyPointsAmount)>+ GetShoppingCartTotal(IList<ShoppingCartItem> cart, bool? useLoyaltyPoints = null,+ bool usePaymentMethodAdditionalFee = true){-var redeemedLoyaltyPoints = 0;double redeemedLoyaltyPointsAmount = 0;- var customer = _workContext.CurrentCustomer;-- var paymentMethodSystemName = "";- if (customer != null)- {- paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(- SystemCustomerFieldNames.SelectedPaymentMethod,- _workContext.CurrentStore.Id);- }+ var paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(+ SystemCustomerFieldNames.SelectedPaymentMethod,+ _workContext.CurrentStore.Id);//subtotal without taxvar subTotal = await GetShoppingCartSubTotal(cart, false);var subTotalWithDiscountBase = subTotal.subTotalWithDiscount;-+//shipping without taxvar shippingTotal = await GetShoppingCartShippingTotal(cart, false);var shoppingCartShipping = shippingTotal.shoppingCartShippingTotal;@@ -771,8 +825,11 @@ namespace Grand.Business.Checkout.Services.Ordersdouble paymentMethodAdditionalFeeWithoutTax = 0;if (usePaymentMethodAdditionalFee && !string.IsNullOrEmpty(paymentMethodSystemName)){- var paymentMethodAdditionalFee = await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);- paymentMethodAdditionalFeeWithoutTax = (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer)).paymentPrice;+ var paymentMethodAdditionalFee =+ await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);+ paymentMethodAdditionalFeeWithoutTax =+ (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, _workContext.CurrentCustomer))+ .paymentPrice;}//tax@@ -785,15 +842,18 @@ namespace Grand.Business.Checkout.Services.Orders{resultTemp += shoppingCartShipping.Value;}+resultTemp += paymentMethodAdditionalFeeWithoutTax;resultTemp += shoppingCartTax;if (_shoppingCartSettings.RoundPrices){resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);}+#region Order total discount- var totalDiscount = await GetOrderTotalDiscount(customer, _workContext.WorkingCurrency, resultTemp);+ var totalDiscount = await GetOrderTotalDiscount(_workContext.CurrentCustomer, _workContext.CurrentStore,+ _workContext.WorkingCurrency, resultTemp);var discountAmount = totalDiscount.orderTotalDiscount;var appliedDiscounts = totalDiscount.appliedDiscounts;@@ -815,15 +875,14 @@ namespace Grand.Business.Checkout.Services.Ordersvar appliedGiftVouchers = new List<AppliedGiftVoucher>();//we don't apply gift vouchers for recurring products- var giftVouchers = await GetActiveGiftVouchers(customer, _workContext.WorkingCurrency, _workContext.CurrentStore);+ var giftVouchers =+ await GetActiveGiftVouchers(_workContext.CurrentCustomer, _workContext.WorkingCurrency, _workContext.CurrentStore);if (giftVouchers != null)foreach (var gc in giftVouchers)if (resultTemp > 0){var remainingAmount = gc.GetGiftVoucherRemainingAmount();- var amountCanBeUsed = resultTemp > remainingAmount ?- remainingAmount :- resultTemp;+ var amountCanBeUsed = resultTemp > remainingAmount ? remainingAmount : resultTemp;//reduce subtotalresultTemp -= amountCanBeUsed;@@ -845,7 +904,8 @@ namespace Grand.Business.Checkout.Services.Ordersif (!shoppingCartShipping.HasValue){//we have errors- return (null, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints, redeemedLoyaltyPointsAmount);+ return (null, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,+ redeemedLoyaltyPointsAmount);}var orderTotal = resultTemp;@@ -854,12 +914,14 @@ namespace Grand.Business.Checkout.Services.Ordersif (_loyaltyPointsSettings.Enabled){- useLoyaltyPoints ??= customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout,+ useLoyaltyPoints ??= _workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(+ SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout,_workContext.CurrentStore.Id);if (useLoyaltyPoints.Value){- var loyaltyPointsBalance = await _loyaltyPointsService.GetLoyaltyPointsBalance(customer?.Id, _workContext.CurrentStore.Id);+ var loyaltyPointsBalance =+ await _loyaltyPointsService.GetLoyaltyPointsBalance(_workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);if (CheckMinimumLoyaltyPointsToUseRequirement(loyaltyPointsBalance)){var loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);@@ -868,12 +930,16 @@ namespace Grand.Business.Checkout.Services.Ordersif (orderTotal > loyaltyPointsBalanceAmount){redeemedLoyaltyPoints = loyaltyPointsBalance;- redeemedLoyaltyPointsAmount = await _currencyService.ConvertFromPrimaryStoreCurrency(loyaltyPointsBalanceAmount, _workContext.WorkingCurrency);+ redeemedLoyaltyPointsAmount =+ await _currencyService.ConvertFromPrimaryStoreCurrency(loyaltyPointsBalanceAmount,+ _workContext.WorkingCurrency);}else{redeemedLoyaltyPointsAmount = orderTotal;- redeemedLoyaltyPoints = ConvertAmountToLoyaltyPoints(await _currencyService.ConvertToPrimaryStoreCurrency(redeemedLoyaltyPointsAmount, _workContext.WorkingCurrency));+ redeemedLoyaltyPoints = ConvertAmountToLoyaltyPoints(+ await _currencyService.ConvertToPrimaryStoreCurrency(redeemedLoyaltyPointsAmount,+ _workContext.WorkingCurrency));}}}@@ -886,7 +952,8 @@ namespace Grand.Business.Checkout.Services.Ordersif (_shoppingCartSettings.RoundPrices)orderTotal = RoundingHelper.RoundPrice(orderTotal, _workContext.WorkingCurrency);- return (orderTotal, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints, redeemedLoyaltyPointsAmount);+ return (orderTotal, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,+ redeemedLoyaltyPointsAmount);}/// <summary>@@ -904,6 +971,7 @@ namespace Grand.Business.Checkout.Services.Orders{result = RoundingHelper.RoundPrice(result, _workContext.WorkingCurrency);}+return await Task.FromResult(result);}@@ -938,4 +1006,4 @@ namespace Grand.Business.Checkout.Services.Orders#endregion}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.csnew file mode 100644index 000000000..b9bd5936c--- /dev/null+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs@@ -0,0 +1,32 @@++namespace Grand.Business.Core.Interfaces.Catalog.Discounts;++public interface IDiscountProviderLoader+{+ /// <summary>+ /// Loads existing discount provider by rule system name+ /// </summary>+ /// <param name="ruleSystemName">Rule system name</param>+ /// <returns>Discount provider</returns>+ IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName);++ /// <summary>+ /// Loads all available discount providers+ /// </summary>+ /// <returns>Discount requirement rules</returns>+ IList<IDiscountProvider> LoadAllDiscountProviders();+++ /// <summary>+ /// Load discount amount providers+ /// </summary>+ /// <returns></returns>+ IList<IDiscountAmountProvider> LoadDiscountAmountProviders();++ /// <summary>+ /// Load discount amount providerBySystemName+ /// </summary>+ /// <param name="systemName"></param>+ /// <returns></returns>+ IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName);+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.csindex b839aa1ee..1b7f7bdec 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs@@ -21,12 +21,18 @@ namespace Grand.Business.Core.Interfaces.Catalog.DiscountsTask<Discount> GetDiscountById(string discountId);/// <summary>- /// Gets all discounts+ /// Gets active discounts by context/// </summary>/// <returns>Discounts</returns>- Task<IList<Discount>> GetAllDiscounts(DiscountType? discountType, string storeId = "", string currencyCode = "",- string couponCode = "", string discountName = "", bool showHidden = false);+ Task<IList<Discount>> GetActiveDiscountsByContext(DiscountType discountType, string storeId = "", string currencyCode = "");+ /// <summary>+ /// Gets discounts query+ /// </summary>+ /// <returns>Discounts</returns>+ Task<IList<Discount>> GetDiscountsQuery(DiscountType? discountType, string storeId = "", string currencyCode = "",+ string couponCode = "", string discountName = "");+/// <summary>/// Inserts a new discount/// </summary>@@ -45,20 +51,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// <param name="discount">Discount</param>Task DeleteDiscount(Discount discount);- /// <summary>- /// Loads existing discount provider by rule system name- /// </summary>- /// <param name="ruleSystemName">Rule system name</param>- /// <returns>Discount provider</returns>- IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName);-- /// <summary>- /// Loads all available discount providers- /// </summary>- /// <returns>Discount requirement rules</returns>- IList<IDiscountProvider> LoadAllDiscountProviders();--/// <summary>/// Gets existing discount by coupon code/// </summary>@@ -66,67 +58,14 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts/// <param name="showHidden">A value that indicates if it should shows hidden records</param>/// <returns>Discount</returns>Task<Discount> GetDiscountByCouponCode(string couponCode, bool showHidden = false);-- /// <summary>- /// Exists coupon code in discount- /// </summary>- /// <param name="couponCode"></param>- /// <param name="discountId"></param>- /// <param name="used"></param>- /// <returns></returns>- Task<bool> ExistsCodeInDiscount(string couponCode, string discountId, bool? used);-- /// <summary>- /// Validates used discount- /// </summary>- /// <param name="discount">Discount</param>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <returns>Discount validation result</returns>- Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency);-- /// <summary>- /// Validates used discount with coupon code- /// </summary>- /// <param name="discount">Discount</param>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <param name="couponCodeToValidate">Coupon code that should be validated</param>- /// <returns>Discount validation result</returns>- Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency, string couponCodeToValidate);-- /// <summary>- /// Validate discount- /// </summary>- /// <param name="discount">Discount</param>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <param name="couponCodesToValidate">Coupon codes that should be validated</param>- /// <returns>Discount validation result</returns>- Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Currency currency, string[] couponCodesToValidate);--+/// <summary>/// Gets a discount usage history item/// </summary>/// <param name="discountUsageHistoryId">Discount usage history item id</param>/// <returns>Discount usage history</returns>Task<DiscountUsageHistory> GetDiscountUsageHistoryById(string discountUsageHistoryId);-- /// <summary>- /// Gets all discount usage history records- /// </summary>- /// <param name="discountId">Discount id; use null to load all existing discounts</param>- /// <param name="customerId">Customer id; use null to load all existing customers</param>- /// <param name="orderId">Order id; use null to load all existing orders</param>- /// <param name="canceled">Canceled</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>Discount usage history records</returns>- Task<IPagedList<DiscountUsageHistory>> GetAllDiscountUsageHistory(string discountId = "",- string customerId = "", string orderId = "", bool? canceled = null,- int pageIndex = 0, int pageSize = int.MaxValue);-+/// <summary>/// Inserts discount usage history item/// </summary>@@ -194,16 +133,15 @@ namespace Grand.Business.Core.Interfaces.Catalog.DiscountsTask InsertDiscountCoupon(DiscountCoupon coupon);/// <summary>- /// Gets discount amount from provider+ /// Get discount amount/// </summary>/// <param name="discount">Discount</param>/// <param name="amount">Amount</param>/// <param name="currency">currency</param>/// <param name="customer">Customer</param>/// <param name="product">Product</param>- /// <returns></returns>Task<double> GetDiscountAmount(Discount discount, Customer customer, Currency currency, Product product, double amount);-+/// <summary>/// Gets preferred discount/// </summary>@@ -227,27 +165,6 @@ namespace Grand.Business.Core.Interfaces.Catalog.DiscountsTask<(List<ApplyDiscount> appliedDiscount, double discountAmount)> GetPreferredDiscount(IList<ApplyDiscount> discounts,Customer customer, Currency currency, double amount);- /// <summary>- /// GetDiscountAmountProvider- /// </summary>- /// <param name="discount"></param>- /// <param name="customer"></param>- /// <param name="product"></param>- /// <param name="amount"></param>- /// <returns></returns>- Task<double> GetDiscountAmountProvider(Discount discount, Customer customer, Product product, double amount);-- /// <summary>- /// Load discount amount provider by systemName- /// </summary>- /// <param name="systemName"></param>- /// <returns></returns>- IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName);-- /// <summary>- /// Load discount amount providers- /// </summary>- /// <returns></returns>- IList<IDiscountAmountProvider> LoadDiscountAmountProviders();+}}diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountValidationService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountValidationService.csnew file mode 100644index 000000000..8fbb3a42b--- /dev/null+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountValidationService.cs@@ -0,0 +1,51 @@+using Grand.Business.Core.Utilities.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Discounts;+using Grand.Domain.Stores;++namespace Grand.Business.Core.Interfaces.Catalog.Discounts;++public interface IDiscountValidationService+{+ /// <summary>+ /// Validates used discount+ /// </summary>+ /// <param name="discount">Discount</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <returns>Discount validation result</returns>+ Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store, Currency currency);++ /// <summary>+ /// Validates used discount with coupon code+ /// </summary>+ /// <param name="discount">Discount</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <param name="couponCodeToValidate">Coupon code that should be validated</param>+ /// <returns>Discount validation result</returns>+ Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store, Currency currency, string couponCodeToValidate);++ /// <summary>+ /// Validate discount+ /// </summary>+ /// <param name="discount">Discount</param>+ /// <param name="customer">Customer</param>+ /// <param name="store">Store</param>+ /// <param name="currency">Currency</param>+ /// <param name="couponCodesToValidate">Coupon codes that should be validated</param>+ /// <returns>Discount validation result</returns>+ Task<DiscountValidationResult> ValidateDiscount(Discount discount, Customer customer, Store store, Currency currency, string[] couponCodesToValidate);++ /// <summary>+ /// Exist coupon code in discount+ /// </summary>+ /// <param name="couponCode"></param>+ /// <param name="discountId"></param>+ /// <param name="used"></param>+ /// <returns></returns>+ Task<bool> ExistsCodeInDiscount(string couponCode, string discountId, bool? used);+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.csindex 54dc4913b..407cc736a 100644--- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs@@ -4,6 +4,7 @@ using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Directory;using Grand.Domain.Orders;+using Grand.Domain.Stores;namespace Grand.Business.Core.Interfaces.Catalog.Prices{@@ -17,6 +18,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// </summary>/// <param name="product">Product</param>/// <param name="customer">The customer</param>+ /// <param name="store">Store</param>/// <param name="currency">The currency</param>/// <param name="additionalCharge">Additional charge</param>/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>@@ -25,6 +27,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.PricesTask<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice preferredTierPrice)> GetFinalPrice(Product product,Customer customer,+ Store store,Currency currency,double additionalCharge = 0,bool includeDiscounts = true,@@ -35,6 +38,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// </summary>/// <param name="product">Product</param>/// <param name="customer">The customer</param>+ /// <param name="store">Store</param>/// <param name="currency">The currency</param>/// <param name="additionalCharge">Additional charge</param>/// <param name="includeDiscounts">A value indicating whether include discounts or not for final price computation</param>@@ -44,6 +48,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// <returns>Final price</returns>Task<(double finalPrice, double discountAmount, List<ApplyDiscount> appliedDiscounts, TierPrice preferredTierPrice)> GetFinalPrice(Product product,Customer customer,+ Store store,Currency currency,double additionalCharge,bool includeDiscounts,@@ -69,6 +74,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// </summary>/// <param name="product">Product</param>/// <param name="customer">Customer</param>+ /// <param name="store">Store</param>/// <param name="currency">The currency</param>/// <param name="shoppingCartType">Shopping cart type</param>/// <param name="quantity">Quantity</param>@@ -80,6 +86,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Prices/// <returns>Shopping cart unit price (one item)</returns>Task<(double unitprice, double discountAmount, List<ApplyDiscount> appliedDiscounts)> GetUnitPrice(Product product,Customer customer,+ Store store,Currency currency,ShoppingCartType shoppingCartType,int quantity,diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.csnew file mode 100644index 000000000..e42a8c31c--- /dev/null+++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.cs@@ -0,0 +1,9 @@+using Grand.Domain.Catalog;+using Grand.Domain.Customers;+using Grand.Domain.Directory;+using Grand.Domain.Discounts;+using MediatR;++namespace Grand.Business.Core.Queries.Catalog;++public record GetDiscountAmountProvider(Discount Discount, Customer Customer, Product Product, Currency Currency, double Amount) : IRequest<double>;diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.csnew file mode 100644index 000000000..0a468375c--- /dev/null+++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.cs@@ -0,0 +1,15 @@+using Grand.Domain;+using Grand.Domain.Discounts;+using MediatR;++namespace Grand.Business.Core.Queries.Catalog;++public record GetDiscountUsageHistoryQuery : IRequest<IPagedList<DiscountUsageHistory>>+{+ public string DiscountId { get; set; }+ public string CustomerId{ get; set; }+ public string OrderId{ get; set; }+ public bool? Canceled { get; set; } = null;+ public int PageIndex { get; set; }+ public int PageSize { get; set; } = int.MaxValue;+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.csindex e5a5d658d..b78b7df6f 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs@@ -34,13 +34,11 @@/// Key for caching/// </summary>/// <remarks>- /// {0} : show hidden records?+ /// {0} : discount type ?/// {1} : store ident/// {2} : currency code- /// {3} : coupon code- /// {4} : discount name/// </remarks>- public static string DISCOUNTS_ALL_KEY => "Grand.discount.all-{0}-{1}-{2}-{3}-{4}";+ public static string DISCOUNTS_CONTEXT_KEY => "Grand.discount.context-{0}-{1}-{2}";/// <summary>/// Key pattern to clear cache@@ -88,15 +86,6 @@/// </remarks>public static string TRANSLATERESOURCES_ALL_KEY => "Grand.translate.all-{0}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : language ID- /// {1} : resource key- /// </remarks>- public static string TRANSLATERESOURCES_BY_RESOURCENAME_KEY => "Grand.translate.{0}-{1}";-/// <summary>/// Key pattern to clear cache/// </summary>diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.csindex 37a366b35..db12bcdcf 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs@@ -1,12 +1,17 @@-using Grand.Business.Catalog.Services.Discounts;+using DotLiquid.Util;+using Grand.Business.Catalog.Queries.Handlers;+using Grand.Business.Catalog.Services.Discounts;using Grand.Business.Core.Interfaces.Catalog.Discounts;using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Queries.Catalog;using Grand.Business.Core.Utilities.Catalog;using Grand.Data.Tests.MongoDb;using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Data;+using Grand.Domain.Directory;using Grand.Domain.Discounts;+using Grand.Domain.Stores;using Grand.Infrastructure;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Configuration;@@ -25,15 +30,16 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsprivate IRepository<DiscountCoupon> _discountCouponRepository;private IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;private Mock<ITranslationService> _translationServiceMock;-+ private GetDiscountUsageHistoryQueryHandler handler;private Mock<IWorkContext> _workContextMock;private Mock<IMediator> _mediatorMock;private DiscountService _dicountService;private MemoryCacheBase _cacheBase;-+ private GetDiscountAmountProviderHandler _getDiscountAmountProviderHandler;private IEnumerable<IDiscountProvider> _discountProviders;private IEnumerable<IDiscountAmountProvider> _discountAmountProviders;-+ private DiscountProviderLoader _discountProviderLoader;+ private DiscountValidationService _discountValidationService;[TestInitialize()]public void InitializeTests(){@@ -51,9 +57,11 @@ namespace Grand.Business.Catalog.Tests.Services.Discounts_discountProviders = new List<IDiscountProvider> { new DiscountProviderTest() };_discountAmountProviders = new List<IDiscountAmountProvider> { new DiscountAmountProviderTests() };-- _dicountService = new DiscountService(_cacheBase, _repository, _discountCouponRepository, _discountUsageHistoryRepository,- _workContextMock.Object, _discountProviders, _discountAmountProviders, _mediatorMock.Object, new AccessControlConfig());+ _discountProviderLoader = new DiscountProviderLoader(_discountProviders, _discountAmountProviders);+ _discountValidationService = new DiscountValidationService(_discountProviderLoader, _discountCouponRepository, _mediatorMock.Object);+ _dicountService = new DiscountService(_cacheBase, _repository, _discountCouponRepository, _discountUsageHistoryRepository, _mediatorMock.Object, new AccessControlConfig());+ handler = new GetDiscountUsageHistoryQueryHandler(_discountUsageHistoryRepository);+ _getDiscountAmountProviderHandler = new GetDiscountAmountProviderHandler(_discountProviderLoader);}[TestMethod()]@@ -91,7 +99,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsawait _dicountService.InsertDiscount(discount2);//Act- var result = await _dicountService.GetAllDiscounts(null, showHidden: true);+ var result = await _dicountService.GetDiscountsQuery(null);//AssertAssert.IsNotNull(result);@@ -152,7 +160,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountspublic void LoadDiscountProviderBySystemNameTest_NotNull(){//Act- var provider = _dicountService.LoadDiscountProviderByRuleSystemName("RuleSystemName");+ var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName");//AssertAssert.IsNotNull(provider);}@@ -160,7 +168,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountspublic void LoadDiscountProviderBySystemNameTest_Null(){//Act- var provider = _dicountService.LoadDiscountProviderByRuleSystemName("RuleSystemName2");+ var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName2");//AssertAssert.IsNull(provider);}@@ -169,7 +177,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountspublic void LoadAllDiscountProvidersTest(){//Act- var providers = _dicountService.LoadAllDiscountProviders();+ var providers = _discountProviderLoader.LoadAllDiscountProviders();//AssertAssert.AreEqual(1, providers.Count);}@@ -198,29 +206,6 @@ namespace Grand.Business.Catalog.Tests.Services.DiscountsAssert.AreEqual(discount.Id, coupon.Id);}- [TestMethod()]- public async Task ExistsCodeInDiscountTest()- {- //Arrange- var discount = new Discount {- Name = "test",- IsEnabled = true- };- await _dicountService.InsertDiscount(discount);-- var discountCoupon = new DiscountCoupon {- CouponCode = "TEST123",- DiscountId = discount.Id- };- await _discountCouponRepository.InsertAsync(discountCoupon);-- //Act- var coupon = await _dicountService.ExistsCodeInDiscount("TEST123", discount.Id, null);-- //Assert- Assert.AreEqual(true, coupon);- }-[TestMethod()]public async Task GetAllCouponCodesByDiscountIdTest(){@@ -443,7 +428,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsvar customer = new Customer();customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST123", StoreId = "" });//Act- var result = await _dicountService.ValidateDiscount(discount, customer, new Domain.Directory.Currency { CurrencyCode = "USD" });+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Domain.Directory.Currency { CurrencyCode = "USD" });//AssertAssert.IsTrue(result.IsValid);}@@ -467,7 +452,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsvar customer = new Customer();customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });//Act- var result = await _dicountService.ValidateDiscount(discount, customer, new Domain.Directory.Currency { CurrencyCode = "USD" });+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });//AssertAssert.IsFalse(result.IsValid);}@@ -490,7 +475,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsvar customer = new Customer();customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });//Act- var result = await _dicountService.ValidateDiscount(discount, customer, new Domain.Directory.Currency { CurrencyCode = "USD" });+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });//AssertAssert.IsFalse(result.IsValid);}@@ -515,7 +500,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsvar customer = new Customer();customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });//Act- var result = await _dicountService.ValidateDiscount(discount, customer, new Domain.Directory.Currency { CurrencyCode = "USD" });+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });//AssertAssert.IsFalse(result.IsValid);}@@ -538,7 +523,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountsvar customer = new Customer();customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });//Act- var result = await _dicountService.ValidateDiscount(discount, customer, new Domain.Directory.Currency { CurrencyCode = "USD" });+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });//AssertAssert.IsFalse(result.IsValid);}@@ -602,7 +587,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discounts};await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory2);//Act- var usageHistory = await _dicountService.GetAllDiscountUsageHistory();+ var usageHistory = await handler.Handle(new GetDiscountUsageHistoryQuery(), CancellationToken.None);//AssertAssert.AreEqual(2, usageHistory.Count);@@ -825,7 +810,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discounts};await _dicountService.InsertDiscount(discount1);//Act- var amount = await _dicountService.GetDiscountAmountProvider(discount1, new Customer(), new Product(), 100);+ var amount = await _getDiscountAmountProviderHandler.Handle(new GetDiscountAmountProvider(discount1, new Customer(), new Product(), new Currency(), 100), CancellationToken.None);//AssertAssert.AreEqual(9, amount);}@@ -834,7 +819,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountspublic void LoadDiscountAmountProviderBySystemNameTest(){//Act- var discountProvider = _dicountService.LoadDiscountAmountProviderBySystemName("SampleDiscountAmountProvider");+ var discountProvider = _discountProviderLoader.LoadDiscountAmountProviderBySystemName("SampleDiscountAmountProvider");//AssertAssert.IsNotNull(discountProvider);}@@ -843,7 +828,7 @@ namespace Grand.Business.Catalog.Tests.Services.Discountspublic void LoadDiscountAmountProvidersTest(){//Act- var discountProviders = _dicountService.LoadDiscountAmountProviders();+ var discountProviders = _discountProviderLoader.LoadDiscountAmountProviders();//AssertAssert.AreEqual(1, discountProviders.Count);}diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.csindex 7c24b319e..50be4ffe4 100644--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs@@ -47,7 +47,7 @@ namespace Grand.Business.Catalog.Tests.Services.Pricesprivate IPricingService _pricingService;private ICurrencyService _currencyService;private IMediator _eventPublisher;-+ private Mock<IDiscountValidationService> _discountValidationService;[TestInitialize()]public void TestInitialize()@@ -70,7 +70,8 @@ namespace Grand.Business.Catalog.Tests.Services.Prices_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;@@ -123,6 +124,7 @@ namespace Grand.Business.Catalog.Tests.Services.Prices_productService,_eventPublisher,_currencyService,+ _discountValidationService.Object,_shoppingCartSettings,_catalogSettings);}@@ -141,10 +143,10 @@ namespace Grand.Business.Catalog.Tests.Services.Pricesvar currency = new Currency { Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = System.MidpointRounding.ToEven, RoundingTypeId = RoundingType.Rounding001 };var customer = new Customer();- var pr = await _pricingService.GetFinalPrice(product, customer, currency, 0, false, 1);+ var pr = await _pricingService.GetFinalPrice(product, customer, _store, currency, 0, false, 1);Assert.AreEqual(49.99, pr.finalPrice);//returned price FOR ONE UNIT should be the same, even if quantity is different than 1- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 10)).finalPrice);+ Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 10)).finalPrice);}[TestMethod()]@@ -170,19 +172,19 @@ namespace Grand.Business.Catalog.Tests.Services.Pricesquantity: >=200 price: 2*/- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 1)).finalPrice);- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 5)).finalPrice);- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 9)).finalPrice);+ Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 1)).finalPrice);+ Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 5)).finalPrice);+ Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 9)).finalPrice);- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 10)).finalPrice);- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 11)).finalPrice);- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 151)).finalPrice);- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 199)).finalPrice);+ Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 10)).finalPrice);+ Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 11)).finalPrice);+ Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 151)).finalPrice);+ Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 199)).finalPrice);- var p1 = (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 200)).finalPrice;+ var p1 = (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 200)).finalPrice;Assert.AreEqual(2, p1);- Assert.AreEqual(2, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 201)).finalPrice);- Assert.AreEqual(2, (await _pricingService.GetFinalPrice(product, customer, _currency, 0, false, 22201)).finalPrice);+ Assert.AreEqual(2, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 201)).finalPrice);+ Assert.AreEqual(2, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 22201)).finalPrice);}@@ -202,7 +204,7 @@ namespace Grand.Business.Catalog.Tests.Services.Prices//additional charge +1000//==1049.99- Assert.AreEqual(1049.99, (await _pricingService.GetFinalPrice(product, customer, _currency, 1000, false, 1)).finalPrice);+ Assert.AreEqual(1049.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 1000, false, 1)).finalPrice);}[TestMethod()]@@ -231,17 +233,17 @@ namespace Grand.Business.Catalog.Tests.Services.Pricesproduct.AppliedDiscounts.Add(discount001.Id);- tempDiscountServiceMock.Setup(x => x.ValidateDiscount(discount001, customer, _currency)).ReturnsAsync(new DiscountValidationResult { IsValid = true });- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToSkus, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount> { discount001 });+ _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)).ReturnsAsync((new List<ApplyDiscount>(), 10));//it should return 39.99 - price cheaper about 10- var finalprice = await _pricingService.GetFinalPrice(product, customer, _currency, 0, true, 1);+ var finalprice = await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, true, 1);var pp = finalprice.finalPrice;Assert.AreEqual(39.99, pp);@@ -271,9 +273,9 @@ namespace Grand.Business.Catalog.Tests.Services.Pricescustomer001.ShoppingCartItems.Add(shoppingCartItem);- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());+ 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>());var pp = (await _pricingService.GetUnitPrice(shoppingCartItem, product001)).unitprice;Assert.AreEqual(49.99, pp);}@@ -301,9 +303,9 @@ namespace Grand.Business.Catalog.Tests.Services.Pricescustomer001.ShoppingCartItems.Add(shoppingCartItem);- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());- tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode, "", "", false)).ReturnsAsync(new List<Discount>());+ 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>());var subtotal = (await _pricingService.GetSubTotal(shoppingCartItem, product001)).subTotal;Assert.AreEqual(110.22, subtotal);}diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.csindex b64b0980a..107c9b869 100644--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs@@ -40,6 +40,7 @@ namespace Grand.Business.Checkout.Tests.Services.Ordersprivate Mock<IProductService> _productServiceMock;private Mock<ICurrencyService> _currencyServiceMock;private Mock<IGroupService> _groupServiceMock;+ private Mock<IDiscountValidationService> _discountValidationService;private TaxSettings _taxSettings;private LoyaltyPointsSettings _loyaltyPointsSettings;private ShippingSettings _shippingSettings;@@ -66,7 +67,7 @@ namespace Grand.Business.Checkout.Tests.Services.Orders_shippingSettings = new ShippingSettings();_shoppingCartSettings = new ShoppingCartSettings();_catalogSettings = new CatalogSettings();-+ _discountValidationService = new Mock<IDiscountValidationService>();_workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });var customer = new Customer();customer.Groups.Add("1");@@ -76,7 +77,7 @@ namespace Grand.Business.Checkout.Tests.Services.Orders_service = new OrderCalculationService(_workContextMock.Object, _pricingServiceMock.Object, _taxServiceMock.Object, _shippingServiceMock.Object,_paymentServiceMock.Object, _checkoutAttributeParserMock.Object, _discountServiceMock.Object, _giftVoucherServiceMock.Object,- _loyaltyPointsServiceMock.Object, _productServiceMock.Object, _currencyServiceMock.Object, _groupServiceMock.Object,+ _loyaltyPointsServiceMock.Object, _productServiceMock.Object, _currencyServiceMock.Object, _groupServiceMock.Object, _discountValidationService.Object,_taxSettings, _loyaltyPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings);}@@ -85,7 +86,7 @@ namespace Grand.Business.Checkout.Tests.Services.Orders{_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));_checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));- _discountServiceMock.Setup(a => a.GetAllDiscounts(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));+ _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1 } };var result = await _service.GetShoppingCartSubTotal(shoppingCartItem, false);@@ -148,7 +149,7 @@ namespace Grand.Business.Checkout.Tests.Services.Orders.Returns(Task.FromResult<IList<CustomerGroup>>(cgs));_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));_checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));- _discountServiceMock.Setup(a => a.GetAllDiscounts(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));+ _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };//Act@@ -168,7 +169,7 @@ namespace Grand.Business.Checkout.Tests.Services.Orders.Returns(Task.FromResult<IList<CustomerGroup>>(cgs));_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));_checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));- _discountServiceMock.Setup(a => a.GetAllDiscounts(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));+ _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };//Act@@ -187,7 +188,7 @@ namespace Grand.Business.Checkout.Tests.Services.Orders.Returns(Task.FromResult<IList<CustomerGroup>>(cgs));_productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));_checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));- _discountServiceMock.Setup(a => a.GetAllDiscounts(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));+ _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };//Actdiff --git a/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs b/src/Web/Grand.Web.Admin/Controllers/DiscountController.csindex 7314ffe78..c49967460 100644--- a/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs@@ -7,6 +7,7 @@ using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Utilities.Common.Security;using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Queries.Catalog;using Grand.Domain;using Grand.Infrastructure;using Grand.Web.Admin.Extensions;@@ -17,6 +18,7 @@ using Grand.Web.Admin.Models.Discounts;using Grand.Web.Common.DataSource;using Grand.Web.Common.Filters;using Grand.Web.Common.Security.Authorization;+using MediatR;using Microsoft.AspNetCore.Mvc;namespace Grand.Web.Admin.Controllers@@ -32,6 +34,8 @@ namespace Grand.Web.Admin.Controllersprivate readonly IWorkContext _workContext;private readonly IDateTimeService _dateTimeService;private readonly IGroupService _groupService;+ private readonly IDiscountProviderLoader _discountProviderLoader;+ private readonly IMediator _mediator;#endregion@@ -43,7 +47,9 @@ namespace Grand.Web.Admin.ControllersITranslationService translationService,IWorkContext workContext,IDateTimeService dateTimeService,- IGroupService groupService)+ IGroupService groupService,+ IDiscountProviderLoader discountProviderLoader,+ IMediator mediator){_discountViewModelService = discountViewModelService;_discountService = discountService;@@ -51,6 +57,8 @@ namespace Grand.Web.Admin.Controllers_workContext = workContext;_dateTimeService = dateTimeService;_groupService = groupService;+ _discountProviderLoader = discountProviderLoader;+ _mediator = mediator;}#endregion@@ -73,9 +81,9 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.List)]public async Task<IActionResult> List(DiscountListModel model, DataSourceRequest command){- var (discountModel, totalCount) = await _discountViewModelService.PrepareDiscountModel(model, command.Page, command.PageSize);- var gridModel = new DataSourceResult- {+ var (discountModel, totalCount) =+ await _discountViewModelService.PrepareDiscountModel(model, command.Page, command.PageSize);+ var gridModel = new DataSourceResult {Data = discountModel.ToList(),Total = totalCount};@@ -109,6 +117,7 @@ namespace Grand.Web.Admin.ControllersSuccess(_translationService.GetResource("admin.marketing.discounts.Added"));return continueEditing ? RedirectToAction("Edit", new { id = discount.Id }) : RedirectToAction("List");}+//If we got this far, something failed, redisplay formawait _discountViewModelService.PrepareDiscountModel(model, null);@@ -126,7 +135,9 @@ namespace Grand.Web.Admin.Controllersif (await _groupService.IsStaff(_workContext.CurrentCustomer)){- if (!discount.LimitedToStores || (discount.LimitedToStores && discount.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) && discount.Stores.Count > 1))+ if (!discount.LimitedToStores || (discount.LimitedToStores &&+ discount.Stores.Contains(_workContext.CurrentCustomer.StaffStoreId) &&+ discount.Stores.Count > 1))Warning(_translationService.GetResource("admin.marketing.discounts.Permissions"));else{@@ -162,6 +173,7 @@ namespace Grand.Web.Admin.Controllers{model.Stores = [_workContext.CurrentCustomer.StaffStoreId];}+discount = await _discountViewModelService.UpdateDiscountModel(discount, model);Success(_translationService.GetResource("admin.marketing.discounts.Updated"));if (continueEditing)@@ -170,8 +182,10 @@ namespace Grand.Web.Admin.Controllersawait SaveSelectedTabIndex();return RedirectToAction("Edit", new { id = discount.Id });}+return RedirectToAction("List");}+//If we got this far, something failed, redisplay formawait _discountViewModelService.PrepareDiscountModel(model, discount);@@ -194,18 +208,20 @@ namespace Grand.Web.Admin.Controllersreturn RedirectToAction("Edit", new { id = discount.Id });}- var usagehistory = await _discountService.GetAllDiscountUsageHistory(discount.Id);- if (usagehistory.Count > 0)+ var usageHistory = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id });+ if (usageHistory.Count > 0){Error(_translationService.GetResource("admin.marketing.discounts.Deleted.UsageHistory"));return RedirectToAction("Edit", new { id = discount.Id });}+if (ModelState.IsValid){await _discountViewModelService.DeleteDiscount(discount);Success(_translationService.GetResource("admin.marketing.discounts.Deleted"));return RedirectToAction("List");}+Error(ModelState);return RedirectToAction("Edit", new { id = discount.Id });}@@ -213,6 +229,7 @@ namespace Grand.Web.Admin.Controllers#endregion#region Discount coupon codes+[HttpPost][PermissionAuthorizeAction(PermissionActionName.Preview)]public async Task<IActionResult> CouponCodeList(DataSourceRequest command, string discountId)@@ -221,11 +238,10 @@ namespace Grand.Web.Admin.Controllersif (discount == null)throw new Exception("No discount found with the specified id");- var couponcodes = await _discountService.GetAllCouponCodesByDiscountId(discount.Id, pageIndex: command.Page - 1, pageSize: command.PageSize);- var gridModel = new DataSourceResult- {- Data = couponcodes.Select(x => new- {+ var couponcodes = await _discountService.GetAllCouponCodesByDiscountId(discount.Id,+ pageIndex: command.Page - 1, pageSize: command.PageSize);+ var gridModel = new DataSourceResult {+ Data = couponcodes.Select(x => new {x.Id,x.CouponCode,x.Used@@ -250,13 +266,15 @@ namespace Grand.Web.Admin.Controllersif (!coupon.Used)await _discountService.DeleteDiscountCoupon(coupon);else- return new JsonResult(new DataSourceResult { Errors = "You can't delete coupon code, it was used" });+ return new JsonResult(new DataSourceResult+ { Errors = "You can't delete coupon code, it was used" });return new JsonResult("");}- return ErrorForKendoGridJson(ModelState);+ return ErrorForKendoGridJson(ModelState);}+[PermissionAuthorizeAction(PermissionActionName.Edit)]public async Task<IActionResult> CouponCodeInsert(string discountId, string couponCode){@@ -276,20 +294,23 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.InsertCouponCode(discountId, couponCode);return new JsonResult("");}+return ErrorForKendoGridJson(ModelState);}+#endregion#region Discount requirements[AcceptVerbs("GET")][PermissionAuthorizeAction(PermissionActionName.Preview)]- public async Task<IActionResult> GetDiscountRequirementConfigurationUrl(string rulesystemName, string discountId, string discountRequirementId)+ public async Task<IActionResult> GetDiscountRequirementConfigurationUrl(string rulesystemName,+ string discountId, string discountRequirementId){if (string.IsNullOrEmpty(rulesystemName))throw new ArgumentNullException(nameof(rulesystemName));- var discountPlugin = _discountService.LoadDiscountProviderByRuleSystemName(rulesystemName);+ var discountPlugin = _discountProviderLoader.LoadDiscountProviderByRuleSystemName(rulesystemName);if (discountPlugin == null)throw new ArgumentException("Discount requirement rule could not be loaded");@@ -298,8 +319,10 @@ namespace Grand.Web.Admin.Controllersif (discount == null)throw new ArgumentException("Discount could not be loaded");- var singleRequirement = discountPlugin.GetRequirementRules().FirstOrDefault(x => x.SystemName.Equals(rulesystemName, StringComparison.OrdinalIgnoreCase));- var url = _discountViewModelService.GetRequirementUrlInternal(singleRequirement, discount, discountRequirementId);+ var singleRequirement = discountPlugin.GetRequirementRules().FirstOrDefault(x =>+ x.SystemName.Equals(rulesystemName, StringComparison.OrdinalIgnoreCase));+ var url = _discountViewModelService.GetRequirementUrlInternal(singleRequirement, discount,+ discountRequirementId);return Json(new { url });}@@ -314,12 +337,16 @@ namespace Grand.Web.Admin.Controllersif (discountRequirement == null)throw new ArgumentException("Discount requirement could not be loaded");- var discountPlugin = _discountService.LoadDiscountProviderByRuleSystemName(discountRequirement.DiscountRequirementRuleSystemName);+ var discountPlugin =+ _discountProviderLoader.LoadDiscountProviderByRuleSystemName(discountRequirement+ .DiscountRequirementRuleSystemName);if (discountPlugin == null)throw new ArgumentException("Discount requirement rule could not be loaded");- var discountRequirementRule = discountPlugin.GetRequirementRules().First(x => x.SystemName == discountRequirement.DiscountRequirementRuleSystemName);- var url = _discountViewModelService.GetRequirementUrlInternal(discountRequirementRule, discount, discountRequirementId);+ var discountRequirementRule = discountPlugin.GetRequirementRules()+ .First(x => x.SystemName == discountRequirement.DiscountRequirementRuleSystemName);+ var url = _discountViewModelService.GetRequirementUrlInternal(discountRequirementRule, discount,+ discountRequirementId);var ruleName = discountRequirementRule.FriendlyName;return Json(new { url, ruleName });@@ -342,6 +369,7 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.DeleteDiscountRequirement(discountRequirement, discount);return Json(new { Result = true });}+return ErrorForKendoGridJson(ModelState);}@@ -351,17 +379,17 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Preview)][HttpPost]- public async Task<IActionResult> ProductList(DataSourceRequest command, string discountId, [FromServices] IProductService productService)+ public async Task<IActionResult> ProductList(DataSourceRequest command, string discountId,+ [FromServices] IProductService productService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)throw new Exception("No discount found with the specified id");- var products = await productService.GetProductsByDiscount(discount.Id, pageIndex: command.Page - 1, pageSize: command.PageSize);- var gridModel = new DataSourceResult- {- Data = products.Select(x => new DiscountModel.AppliedToProductModel- {+ var products = await productService.GetProductsByDiscount(discount.Id, pageIndex: command.Page - 1,+ pageSize: command.PageSize);+ var gridModel = new DataSourceResult {+ Data = products.Select(x => new DiscountModel.AppliedToProductModel {ProductId = x.Id,ProductName = x.Name}),@@ -372,7 +400,8 @@ namespace Grand.Web.Admin.Controllers}[PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> ProductDelete(string discountId, string productId, [FromServices] IProductService productService)+ public async Task<IActionResult> ProductDelete(string discountId, string productId,+ [FromServices] IProductService productService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)@@ -387,6 +416,7 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.DeleteProduct(discount, product);return new JsonResult("");}+return ErrorForKendoGridJson(ModelState);}@@ -399,12 +429,12 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Edit)][HttpPost]- public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command, DiscountModel.AddProductToDiscountModel model)+ public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command,+ DiscountModel.AddProductToDiscountModel model){var products = await _discountViewModelService.PrepareProductModel(model, command.Page, command.PageSize);- var gridModel = new DataSourceResult- {+ var gridModel = new DataSourceResult {Data = products.products.ToList(),Total = products.totalCount};@@ -424,6 +454,7 @@ namespace Grand.Web.Admin.Controllers{await _discountViewModelService.InsertProductToDiscountModel(model);}+return Content("");}@@ -433,7 +464,8 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Preview)][HttpPost]- public async Task<IActionResult> CategoryList(DataSourceRequest command, string discountId, [FromServices] ICategoryService categoryService)+ public async Task<IActionResult> CategoryList(DataSourceRequest command, string discountId,+ [FromServices] ICategoryService categoryService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)@@ -443,14 +475,13 @@ namespace Grand.Web.Admin.Controllersvar items = new List<DiscountModel.AppliedToCategoryModel>();foreach (var item in categories){- items.Add(new DiscountModel.AppliedToCategoryModel- {+ items.Add(new DiscountModel.AppliedToCategoryModel {CategoryId = item.Id,CategoryName = await categoryService.GetFormattedBreadCrumb(item)});}- var gridModel = new DataSourceResult- {++ var gridModel = new DataSourceResult {Data = items,Total = categories.Count};@@ -459,7 +490,8 @@ namespace Grand.Web.Admin.Controllers}[PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> CategoryDelete(string discountId, string categoryId, [FromServices] ICategoryService categoryService)+ public async Task<IActionResult> CategoryDelete(string discountId, string categoryId,+ [FromServices] ICategoryService categoryService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)@@ -474,6 +506,7 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.DeleteCategory(discount, category);return new JsonResult("");}+return ErrorForKendoGridJson(ModelState);}@@ -486,7 +519,8 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Edit)][HttpPost]- public async Task<IActionResult> CategoryAddPopupList(DataSourceRequest command, DiscountModel.AddCategoryToDiscountModel model, [FromServices] ICategoryService categoryService)+ public async Task<IActionResult> CategoryAddPopupList(DataSourceRequest command,+ DiscountModel.AddCategoryToDiscountModel model, [FromServices] ICategoryService categoryService){var categories = await categoryService.GetAllCategories(categoryName: model.SearchCategoryName,pageIndex: command.Page - 1, pageSize: command.PageSize, showHidden: true);@@ -497,8 +531,8 @@ namespace Grand.Web.Admin.ControllerscategoryModel.Breadcrumb = await categoryService.GetFormattedBreadCrumb(item);items.Add(categoryModel);}- var gridModel = new DataSourceResult- {++ var gridModel = new DataSourceResult {Data = items,Total = categories.TotalCount};@@ -518,6 +552,7 @@ namespace Grand.Web.Admin.Controllers{await _discountViewModelService.InsertCategoryToDiscountModel(model);}+return Content("");}@@ -527,17 +562,16 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Preview)][HttpPost]- public async Task<IActionResult> BrandList(DataSourceRequest command, string discountId, [FromServices] IBrandService brandService)+ public async Task<IActionResult> BrandList(DataSourceRequest command, string discountId,+ [FromServices] IBrandService brandService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)throw new Exception("No discount found with the specified id");var brands = await brandService.GetAllBrandsByDiscount(discount.Id);- var gridModel = new DataSourceResult- {- Data = brands.Select(x => new DiscountModel.AppliedToBrandModel- {+ var gridModel = new DataSourceResult {+ Data = brands.Select(x => new DiscountModel.AppliedToBrandModel {BrandId = x.Id,BrandName = x.Name}),@@ -548,7 +582,8 @@ namespace Grand.Web.Admin.Controllers}[PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> BrandDelete(string discountId, string brandId, [FromServices] IBrandService brandService)+ public async Task<IActionResult> BrandDelete(string discountId, string brandId,+ [FromServices] IBrandService brandService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)@@ -562,6 +597,7 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.DeleteBrand(discount, brand);return new JsonResult("");}+return ErrorForKendoGridJson(ModelState);}@@ -574,12 +610,13 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Edit)][HttpPost]- public async Task<IActionResult> BrandAddPopupList(DataSourceRequest command, DiscountModel.AddBrandToDiscountModel model, [FromServices] IBrandService brandService)+ public async Task<IActionResult> BrandAddPopupList(DataSourceRequest command,+ DiscountModel.AddBrandToDiscountModel model, [FromServices] IBrandService brandService){- var brands = await brandService.GetAllBrands(model.SearchBrandName, _workContext.CurrentCustomer.StaffStoreId, command.Page - 1, command.PageSize, true);+ var brands = await brandService.GetAllBrands(model.SearchBrandName,+ _workContext.CurrentCustomer.StaffStoreId, command.Page - 1, command.PageSize, true);- var gridModel = new DataSourceResult- {+ var gridModel = new DataSourceResult {Data = brands.Select(x => x.ToModel()),Total = brands.TotalCount};@@ -599,6 +636,7 @@ namespace Grand.Web.Admin.Controllers{await _discountViewModelService.InsertBrandToDiscountModel(model);}+return Content("");}@@ -608,17 +646,16 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Preview)][HttpPost]- public async Task<IActionResult> CollectionList(DataSourceRequest command, string discountId, [FromServices] ICollectionService collectionService)+ public async Task<IActionResult> CollectionList(DataSourceRequest command, string discountId,+ [FromServices] ICollectionService collectionService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)throw new Exception("No discount found with the specified id");var collections = await collectionService.GetAllCollectionsByDiscount(discount.Id);- var gridModel = new DataSourceResult- {- Data = collections.Select(x => new DiscountModel.AppliedToCollectionModel- {+ var gridModel = new DataSourceResult {+ Data = collections.Select(x => new DiscountModel.AppliedToCollectionModel {CollectionId = x.Id,CollectionName = x.Name}),@@ -629,7 +666,8 @@ namespace Grand.Web.Admin.Controllers}[PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> CollectionDelete(string discountId, string collectionId, [FromServices] ICollectionService collectionService)+ public async Task<IActionResult> CollectionDelete(string discountId, string collectionId,+ [FromServices] ICollectionService collectionService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)@@ -644,6 +682,7 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.DeleteCollection(discount, collection);return new JsonResult("");}+return ErrorForKendoGridJson(ModelState);}@@ -656,12 +695,12 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Edit)][HttpPost]- public async Task<IActionResult> CollectionAddPopupList(DataSourceRequest command, DiscountModel.AddCollectionToDiscountModel model, [FromServices] ICollectionService collectionService)+ public async Task<IActionResult> CollectionAddPopupList(DataSourceRequest command,+ DiscountModel.AddCollectionToDiscountModel model, [FromServices] ICollectionService collectionService){var collections = await collectionService.GetAllCollections(model.SearchCollectionName, "",command.Page - 1, command.PageSize, true);- var gridModel = new DataSourceResult- {+ var gridModel = new DataSourceResult {Data = collections.Select(x => x.ToModel()),Total = collections.TotalCount};@@ -681,6 +720,7 @@ namespace Grand.Web.Admin.Controllers{await _discountViewModelService.InsertCollectionToDiscountModel(model);}+return Content("");}@@ -690,17 +730,16 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Preview)][HttpPost]- public async Task<IActionResult> VendorList(DataSourceRequest command, string discountId, [FromServices] IVendorService vendorService)+ public async Task<IActionResult> VendorList(DataSourceRequest command, string discountId,+ [FromServices] IVendorService vendorService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)throw new Exception("No discount found with the specified id");var vendors = await vendorService.GetAllVendorsByDiscount(discount.Id);- var gridModel = new DataSourceResult- {- Data = vendors.Select(x => new DiscountModel.AppliedToVendorModel- {+ var gridModel = new DataSourceResult {+ Data = vendors.Select(x => new DiscountModel.AppliedToVendorModel {VendorId = x.Id,VendorName = x.Name}),@@ -711,7 +750,8 @@ namespace Grand.Web.Admin.Controllers}[PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> VendorDelete(string discountId, string vendorId, [FromServices] IVendorService vendorService)+ public async Task<IActionResult> VendorDelete(string discountId, string vendorId,+ [FromServices] IVendorService vendorService){var discount = await _discountService.GetDiscountById(discountId);if (discount == null)@@ -725,6 +765,7 @@ namespace Grand.Web.Admin.Controllersawait _discountViewModelService.DeleteVendor(discount, vendor);return new JsonResult("");}+return ErrorForKendoGridJson(ModelState);}@@ -737,19 +778,21 @@ namespace Grand.Web.Admin.Controllers[PermissionAuthorizeAction(PermissionActionName.Edit)][HttpPost]- public async Task<IActionResult> VendorAddPopupList(DataSourceRequest command, DiscountModel.AddVendorToDiscountModel model, [FromServices] IVendorService vendorService)+ public async Task<IActionResult> VendorAddPopupList(DataSourceRequest command,+ DiscountModel.AddVendorToDiscountModel model, [FromServices] IVendorService vendorService){- var vendors = await vendorService.GetAllVendors(model.SearchVendorName, command.Page - 1, command.PageSize, true);+ var vendors =+ await vendorService.GetAllVendors(model.SearchVendorName, command.Page - 1, command.PageSize, true);//search for emailsif (!string.IsNullOrEmpty(model.SearchVendorEmail)){- var tempVendors = vendors.Where(x => x.Email.ToLowerInvariant().Contains(model.SearchVendorEmail.Trim()));+ var tempVendors =+ vendors.Where(x => x.Email.ToLowerInvariant().Contains(model.SearchVendorEmail.Trim()));vendors = new PagedList<Domain.Vendors.Vendor>(tempVendors, command.Page - 1, command.PageSize);}- var gridModel = new DataSourceResult- {+ var gridModel = new DataSourceResult {Data = vendors.Select(x => x.ToModel()),Total = vendors.TotalCount};@@ -769,6 +812,7 @@ namespace Grand.Web.Admin.Controllers{await _discountViewModelService.InsertVendorToDiscountModel(model);}+return Content("");}@@ -784,9 +828,10 @@ namespace Grand.Web.Admin.Controllersif (discount == null)throw new ArgumentException("No discount found with the specified id");- var (usageHistoryModels, totalCount) = await _discountViewModelService.PrepareDiscountUsageHistoryModel(discount, command.Page, command.PageSize);- var gridModel = new DataSourceResult- {+ var (usageHistoryModels, totalCount) =+ await _discountViewModelService.PrepareDiscountUsageHistoryModel(discount, command.Page,+ command.PageSize);+ var gridModel = new DataSourceResult {Data = usageHistoryModels.ToList(),Total = totalCount};@@ -811,9 +856,10 @@ namespace Grand.Web.Admin.Controllerselsereturn ErrorForKendoGridJson(ModelState);}+return new JsonResult("");}#endregion}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs b/src/Web/Grand.Web.Admin/Services/BrandViewModelService.csindex e12957e43..3646d8aa4 100644--- a/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/BrandViewModelService.cs@@ -88,7 +88,7 @@ namespace Grand.Web.Admin.ServicesArgumentNullException.ThrowIfNull(model);model.AvailableDiscounts = (await _discountService- .GetAllDiscounts(DiscountType.AssignedToBrands, storeId: _workContext.CurrentCustomer.Id, showHidden: true))+ .GetDiscountsQuery(DiscountType.AssignedToBrands, storeId: _workContext.CurrentCustomer.Id)).Select(d => d.ToModel(_dateTimeService)).ToList();@@ -102,7 +102,7 @@ namespace Grand.Web.Admin.Services{var brand = model.ToEntity();//discounts- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToBrands, showHidden: true);+ var allDiscounts = await _discountService.GetDiscountsQuery(DiscountType.AssignedToBrands);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))@@ -130,7 +130,7 @@ namespace Grand.Web.Admin.Servicesbrand = model.ToEntity(brand);brand.Locales = await model.Locales.ToTranslationProperty(brand, x => x.Name, _seoSettings, _slugService, _languageService);//discounts- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToBrands, showHidden: true);+ var allDiscounts = await _discountService.GetDiscountsQuery(DiscountType.AssignedToBrands);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))diff --git a/src/Web/Grand.Web.Admin/Services/CategoryViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CategoryViewModelService.csindex 158eb007d..bf9ee219b 100644--- a/src/Web/Grand.Web.Admin/Services/CategoryViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/CategoryViewModelService.cs@@ -84,7 +84,7 @@ namespace Grand.Web.Admin.ServicesArgumentNullException.ThrowIfNull(model);model.AvailableDiscounts = (await _discountService- .GetAllDiscounts(DiscountType.AssignedToCategories, storeId: storeId, showHidden: true))+ .GetDiscountsQuery(DiscountType.AssignedToCategories, storeId: storeId)).Select(d => d.ToModel()).ToList();@@ -162,7 +162,7 @@ namespace Grand.Web.Admin.Servicespublic async Task<Category> InsertCategoryModel(CategoryModel model){var category = model.ToEntity();- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToCategories, showHidden: true);+ var allDiscounts = await _discountService.GetDiscountsQuery(DiscountType.AssignedToCategories);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))@@ -193,7 +193,7 @@ namespace Grand.Web.Admin.Services//localescategory.Locales = await model.Locales.ToTranslationProperty(category, x => x.Name, _seoSettings, _slugService, _languageService);//discounts- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToCategories, showHidden: true);+ var allDiscounts = await _discountService.GetDiscountsQuery(DiscountType.AssignedToCategories);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))diff --git a/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.csindex 7153bbcc6..f3a1c1246 100644--- a/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/CollectionViewModelService.cs@@ -102,7 +102,7 @@ namespace Grand.Web.Admin.ServicesArgumentNullException.ThrowIfNull(model);model.AvailableDiscounts = (await _discountService- .GetAllDiscounts(DiscountType.AssignedToCollections, storeId: _workContext.CurrentCustomer.Id, showHidden: true))+ .GetDiscountsQuery(DiscountType.AssignedToCollections, storeId: _workContext.CurrentCustomer.Id)).Select(d => d.ToModel()).ToList();@@ -116,7 +116,7 @@ namespace Grand.Web.Admin.Services{var collection = model.ToEntity();//discounts- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToCollections, showHidden: true);+ var allDiscounts = await _discountService.GetDiscountsQuery(DiscountType.AssignedToCollections);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))@@ -144,7 +144,7 @@ namespace Grand.Web.Admin.Servicescollection = model.ToEntity(collection);collection.Locales = await model.Locales.ToTranslationProperty(collection, x => x.Name, _seoSettings, _slugService, _languageService);//discounts- var allDiscounts = await _discountService.GetAllDiscounts(DiscountType.AssignedToCollections, showHidden: true);+ var allDiscounts = await _discountService.GetDiscountsQuery(DiscountType.AssignedToCollections);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))diff --git a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.csindex 6bddefb1d..94a54ac16 100644--- a/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/DiscountViewModelService.cs@@ -10,6 +10,7 @@ using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Stores;using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Queries.Catalog;using Grand.Domain.Catalog;using Grand.Domain.Discounts;using Grand.Domain.Vendors;@@ -19,6 +20,7 @@ using Grand.Web.Admin.Interfaces;using Grand.Web.Admin.Models.Catalog;using Grand.Web.Admin.Models.Discounts;using Grand.Web.Common.Extensions;+using MediatR;using Microsoft.AspNetCore.Mvc.Rendering;namespace Grand.Web.Admin.Services@@ -40,7 +42,8 @@ namespace Grand.Web.Admin.Servicesprivate readonly IOrderService _orderService;private readonly IPriceFormatter _priceFormatter;private readonly IDateTimeService _dateTimeService;-+ private readonly IDiscountProviderLoader _discountProviderLoader;+ private readonly IMediator _mediator;#endregion#region Constructors@@ -57,7 +60,9 @@ namespace Grand.Web.Admin.ServicesIVendorService vendorService,IOrderService orderService,IPriceFormatter priceFormatter,- IDateTimeService dateTimeService)+ IDateTimeService dateTimeService,+ IDiscountProviderLoader discountProviderLoader,+ IMediator mediator){_discountService = discountService;_translationService = translationService;@@ -72,6 +77,8 @@ namespace Grand.Web.Admin.Services_orderService = orderService;_priceFormatter = priceFormatter;_dateTimeService = dateTimeService;+ _discountProviderLoader = discountProviderLoader;+ _mediator = mediator;}#endregion@@ -93,19 +100,17 @@ namespace Grand.Web.Admin.ServicesDiscountType? discountType = null;if (model.SearchDiscountTypeId > 0)discountType = (DiscountType)model.SearchDiscountTypeId;- var discounts = await _discountService.GetAllDiscounts(discountType,+ var discounts = await _discountService.GetDiscountsQuery(discountType,_workContext.CurrentCustomer.StaffStoreId,null,model.SearchDiscountCouponCode,- model.SearchDiscountName,- true);+ model.SearchDiscountName);var items = new List<DiscountModel>();foreach (var x in discounts.Skip((pageIndex - 1) * pageSize).Take(pageSize)){var discountModel = x.ToModel(_dateTimeService);discountModel.DiscountTypeName = x.DiscountTypeId.GetTranslationEnum(_translationService, _workContext);- discountModel.TimesUsed =- (await _discountService.GetAllDiscountUsageHistory(x.Id, pageSize: 1)).TotalCount;+ discountModel.TimesUsed = (await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = x.Id, PageSize = 1})).TotalCount;items.Add(discountModel);}@@ -121,7 +126,7 @@ namespace Grand.Web.Admin.Services"admin.marketing.discounts.Requirements.DiscountRequirementType.Select"),Value = ""});- var discountPlugins = _discountService.LoadAllDiscountProviders();+ var discountPlugins = _discountProviderLoader.LoadAllDiscountProviders();foreach (var discountPlugin in discountPlugins)foreach (var discountRule in discountPlugin.GetRequirementRules())model.AvailableDiscountRequirementRules.Add(new SelectListItem@@ -133,7 +138,7 @@ namespace Grand.Web.Admin.Services}//discount amount providers- foreach (var item in _discountService.LoadDiscountAmountProviders())+ foreach (var item in _discountProviderLoader.LoadDiscountAmountProviders()){model.AvailableDiscountAmountProviders.Add(new SelectListItem { Value = item.SystemName, Text = item.FriendlyName });}@@ -144,7 +149,7 @@ namespace Grand.Web.Admin.Servicesforeach (var dr in discount.DiscountRules.OrderBy(dr => dr.Id)){var discountPlugin =- _discountService.LoadDiscountProviderByRuleSystemName(dr.DiscountRequirementRuleSystemName);+ _discountProviderLoader.LoadDiscountProviderByRuleSystemName(dr.DiscountRequirementRuleSystemName);var discountRequirement = discountPlugin.GetRequirementRules().Single(x => x.SystemName == dr.DiscountRequirementRuleSystemName);{@@ -415,8 +420,7 @@ namespace Grand.Web.Admin.ServicesTask<(IEnumerable<DiscountModel.DiscountUsageHistoryModel> usageHistoryModels, int totalCount)>PrepareDiscountUsageHistoryModel(Discount discount, int pageIndex, int pageSize){- var duh = await _discountService.GetAllDiscountUsageHistory(discount.Id, null, null, null, pageIndex - 1,- pageSize);+ var duh = await _mediator.Send(new GetDiscountUsageHistoryQuery { DiscountId = discount.Id, PageIndex = pageIndex - 1, PageSize = pageSize });var items = new List<DiscountModel.DiscountUsageHistoryModel>();foreach (var x in duh)diff --git a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.csindex bcd19f41f..e0dddc36a 100644--- a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs@@ -15,12 +15,14 @@ using Grand.Business.Core.Interfaces.Common.Stores;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.Messages;using Grand.Business.Core.Interfaces.Storage;+using Grand.Business.Core.Queries.Catalog;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Directory;using Grand.Domain.Orders;using Grand.Domain.Payments;using Grand.Domain.Shipping;+using Grand.Domain.Stores;using Grand.Domain.Tax;using Grand.Infrastructure;using Grand.Web.Admin.Extensions;@@ -527,7 +529,8 @@ namespace Grand.Web.Admin.Servicesmodel.SuggestedRefundedAmount = _priceFormatter.FormatPrice(suggestedRefundedAmount, orderCurrency);//used discounts- var duh = await _discountService.GetAllDiscountUsageHistory(orderId: order.Id);+ var duh = await _mediator.Send(new GetDiscountUsageHistoryQuery { OrderId = order.Id });+foreach (var d in duh){var discount = await _discountService.GetDiscountById(d.DiscountId);@@ -855,8 +858,9 @@ namespace Grand.Web.Admin.Servicesvar customer = await _customerService.GetCustomerById(order.CustomerId);var currency = await _currencyService.GetCurrencyByCode(order.CustomerCurrencyCode);+ var store = await _storeService.GetStoreById(order.StoreId);var presetQty = 1;- var presetPrice = (await _pricingService.GetFinalPrice(product, customer, currency, 0, true, presetQty))+ var presetPrice = (await _pricingService.GetFinalPrice(product, customer, store, currency, 0, true, presetQty)).finalPrice;var productPrice = await _taxService.GetProductPrice(product, presetPrice, true, customer);var presetPriceInclTax = productPrice.productprice;diff --git a/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs b/src/Web/Grand.Web.Admin/Services/ProductViewModelService.csindex 0d13971e2..233aa227e 100644--- a/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/ProductViewModelService.cs@@ -510,7 +510,7 @@ namespace Grand.Web.Admin.Services//discountsmodel.AvailableDiscounts = (await discountService- .GetAllDiscounts(DiscountType.AssignedToSkus, storeId: workContext.CurrentCustomer.StaffStoreId, showHidden: true))+ .GetDiscountsQuery(DiscountType.AssignedToSkus, storeId: workContext.CurrentCustomer.StaffStoreId)).Select(d => d.ToModel(dateTimeService)).ToList();if (!excludeProperties && product != null)@@ -796,7 +796,7 @@ namespace Grand.Web.Admin.Services//warehousesawait SaveProductWarehouseInventory(product, model.ProductWarehouseInventoryModels);//discounts- var allDiscounts = await discountService.GetAllDiscounts(DiscountType.AssignedToSkus, storeId: workContext.CurrentCustomer.StaffStoreId, showHidden: true);+ var allDiscounts = await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, storeId: workContext.CurrentCustomer.StaffStoreId);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))@@ -839,7 +839,7 @@ namespace Grand.Web.Admin.Services//picture seo namesawait UpdatePictureSeoNames(product);//discounts- var allDiscounts = await discountService.GetAllDiscounts(DiscountType.AssignedToSkus, storeId: workContext.CurrentCustomer.StaffStoreId, showHidden: true);+ var allDiscounts = await discountService.GetDiscountsQuery(DiscountType.AssignedToSkus, storeId: workContext.CurrentCustomer.StaffStoreId);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))diff --git a/src/Web/Grand.Web.Admin/Services/VendorViewModelService.cs b/src/Web/Grand.Web.Admin/Services/VendorViewModelService.csindex 14173d9b5..ea63e12c1 100644--- a/src/Web/Grand.Web.Admin/Services/VendorViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/VendorViewModelService.cs@@ -44,7 +44,7 @@ namespace Grand.Web.Admin.ServicesArgumentNullException.ThrowIfNull(model);model.AvailableDiscounts = (await discountService- .GetAllDiscounts(DiscountType.AssignedToVendors, showHidden: true))+ .GetDiscountsQuery(DiscountType.AssignedToVendors)).Select(d => d.ToModel(dateTimeService)).ToList();@@ -173,7 +173,7 @@ namespace Grand.Web.Admin.Servicesawait vendorService.InsertVendor(vendor);//discounts- var allDiscounts = await discountService.GetAllDiscounts(DiscountType.AssignedToVendors, showHidden: true);+ var allDiscounts = await discountService.GetDiscountsQuery(DiscountType.AssignedToVendors);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))@@ -201,7 +201,7 @@ namespace Grand.Web.Admin.Servicesvendor.Address = model.Address.ToEntity(vendor.Address);//discounts- var allDiscounts = await discountService.GetAllDiscounts(DiscountType.AssignedToVendors, showHidden: true);+ var allDiscounts = await discountService.GetDiscountsQuery(DiscountType.AssignedToVendors);foreach (var discount in allDiscounts){if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.csindex 317f3f812..0cda0158b 100644--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetSearchAutoCompleteHandler.cs@@ -231,9 +231,9 @@ namespace Grand.Web.Features.Handlers.Catalog{var finalPriceWithoutDiscount =(await _taxService.GetProductPrice(product,- (await _pricingService.GetFinalPrice(product, request.Customer, request.Currency, includeDiscounts: false)).finalPrice)).productprice;+ (await _pricingService.GetFinalPrice(product, request.Customer, request.Store, request.Currency, includeDiscounts: false)).finalPrice)).productprice;- var appliedPrice = await _pricingService.GetFinalPrice(product, request.Customer, request.Currency, includeDiscounts: true);+ var appliedPrice = await _pricingService.GetFinalPrice(product, request.Customer, request.Store, request.Currency, includeDiscounts: true);var finalPriceWithDiscount = (await _taxService.GetProductPrice(product, appliedPrice.finalPrice)).productprice;var price = _priceFormatter.FormatPrice(finalPriceWithoutDiscount);diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.csindex 00224eaeb..da12d1586 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsAttributeChangeHandler.cs@@ -91,6 +91,7 @@ namespace Grand.Web.Features.Handlers.Products//we do not calculate price of "customer enters price" option is enabledvar unitprice = await _pricingService.GetUnitPrice(request.Product,request.Customer,+ request.Store,request.Currency,ShoppingCartType.ShoppingCart,1, customAttributes, default,diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.csindex 2913f9906..93814ccfa 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductDetailsPageHandler.cs@@ -681,11 +681,11 @@ namespace Grand.Web.Features.Handlers.Productsvar oldproductprice = await _taxService.GetProductPrice(product, product.OldPrice);var oldPriceBase = oldproductprice.productprice;var finalPriceWithoutDiscount = (await _taxService.GetProductPrice(product,- (await _pricingService.GetFinalPrice(product, _workContext.CurrentCustomer,+ (await _pricingService.GetFinalPrice(product, _workContext.CurrentCustomer, _workContext.CurrentStore,_workContext.WorkingCurrency, includeDiscounts: false)).finalPrice)).productprice;var appliedPrice = await _pricingService.GetFinalPrice(product, _workContext.CurrentCustomer,- _workContext.WorkingCurrency, includeDiscounts: true);+ _workContext.CurrentStore, _workContext.WorkingCurrency, includeDiscounts: true);var finalPriceWithDiscount =(await _taxService.GetProductPrice(product, appliedPrice.finalPrice)).productprice;var oldPrice =@@ -1090,7 +1090,7 @@ namespace Grand.Web.Features.Handlers.Products{var tier = new ProductDetailsModel.TierPriceModel();var priceBase = await _taxService.GetProductPrice(product, (await _pricingService.GetFinalPrice(product,- _workContext.CurrentCustomer, _workContext.WorkingCurrency,+ _workContext.CurrentCustomer, _workContext.CurrentStore, _workContext.WorkingCurrency,0, _catalogSettings.DisplayTierPricesWithDiscounts, tierPrice.Quantity)).finalPrice);tier.Quantity = tierPrice.Quantity;tier.Price = _priceFormatter.FormatPrice(priceBase.productprice, _workContext.WorkingCurrency);@@ -1179,7 +1179,7 @@ namespace Grand.Web.Features.Handlers.Productsif (displayPrices){var productprice = await _taxService.GetProductPrice(p1,- (await _pricingService.GetFinalPrice(p1, _workContext.CurrentCustomer,+ (await _pricingService.GetFinalPrice(p1, _workContext.CurrentCustomer, _workContext.CurrentStore,_workContext.WorkingCurrency, includeDiscounts: true)).finalPrice);bundleProduct.Price = _priceFormatter.FormatPrice(productprice.productprice);bundleProduct.PriceValue = productprice.productprice;diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.csindex 58f8ae2c9..af30a3cc7 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs@@ -246,7 +246,7 @@ namespace Grand.Web.Features.Handlers.Products{//calculate for the maximum quantity (in case if we have tier prices)var tmpPrice = (await _pricingService.GetFinalPrice(associatedProduct,- _workContext.CurrentCustomer, _workContext.WorkingCurrency, 0, true,+ _workContext.CurrentCustomer, _workContext.CurrentStore, _workContext.WorkingCurrency, 0, true,int.MaxValue)).finalPrice;if (minPossiblePrice.HasValue && !(tmpPrice < minPossiblePrice.Value)) continue;minPriceProduct = associatedProduct;@@ -364,7 +364,7 @@ namespace Grand.Web.Features.Handlers.Products//calculate for the maximum quantity (in case if we have tier prices)var infoPrice = await _pricingService.GetFinalPrice(product,- _workContext.CurrentCustomer, _workContext.WorkingCurrency, 0, true, int.MaxValue);+ _workContext.CurrentCustomer, _workContext.CurrentStore, _workContext.WorkingCurrency, 0, true, int.MaxValue);priceModel.AppliedDiscounts = infoPrice.appliedDiscounts;priceModel.PreferredTierPrice = infoPrice.preferredTierPrice;diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.csindex e5e64bb1e..e53ee0c74 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs@@ -52,6 +52,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCartprivate readonly IGroupService _groupService;private readonly IMediator _mediator;private readonly IShoppingCartValidator _shoppingCartValidator;+ private readonly IDiscountValidationService _discountValidationService;private readonly LinkGenerator _linkGenerator;private readonly MediaSettings _mediaSettings;private readonly OrderSettings _orderSettings;@@ -80,6 +81,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCartIGroupService groupService,IMediator mediator,IShoppingCartValidator shoppingCartValidator,+ IDiscountValidationService discountValidationService,LinkGenerator linkGenerator,MediaSettings mediaSettings,OrderSettings orderSettings,@@ -107,6 +109,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCart_groupService = groupService;_mediator = mediator;_shoppingCartValidator = shoppingCartValidator;+ _discountValidationService = discountValidationService;_linkGenerator = linkGenerator;_mediaSettings = mediaSettings;_orderSettings = orderSettings;@@ -169,7 +172,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCart{var discount = await _discountService.GetDiscountByCouponCode(couponCode);if (discount is { RequiresCouponCode: true } &&- (await _discountService.ValidateDiscount(discount, request.Customer, request.Currency)).IsValid)+ (await _discountValidationService.ValidateDiscount(discount, request.Customer, request.Store, request.Currency)).IsValid){model.DiscountBox.AppliedDiscountsWithCodes.Add(new ShoppingCartModel.DiscountBoxModel.DiscountInfoModel {Id = discount.Id,diff --git a/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs b/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.csindex 4ce1b045f..5e7320381 100644--- a/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs+++ b/src/Web/Grand.Web/Validators/ShoppingCart/DiscountCouponValidator.cs@@ -12,6 +12,7 @@ namespace Grand.Web.Validators.ShoppingCart{public DiscountCouponValidator(IEnumerable<IValidatorConsumer<DiscountCouponModel>> validators,+ IDiscountValidationService discountValidationService,IDiscountService discountService, IWorkContext workContext,ITranslationService translationService): base(validators)@@ -26,27 +27,26 @@ namespace Grand.Web.Validators.ShoppingCartx.DiscountCouponCode = x.DiscountCouponCode.ToUpper();//we find even hidden records here. this way we can display a user-friendly message if it's expiredvar discount = await discountService.GetDiscountByCouponCode(x.DiscountCouponCode, true);- if (discount is { RequiresCouponCode: true })+ if (discount is { RequiresCouponCode: true, IsEnabled: true }){var coupons =workContext.CurrentCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);var existsAndUsed = false;foreach (var item in coupons){- if (await discountService.ExistsCodeInDiscount(item, discount.Id, null))+ if (await discountValidationService.ExistsCodeInDiscount(item, discount.Id, null))existsAndUsed = true;}if (!existsAndUsed){if (!discount.Reused)- existsAndUsed =- !await discountService.ExistsCodeInDiscount(x.DiscountCouponCode, discount.Id, false);+ existsAndUsed = !await discountValidationService.ExistsCodeInDiscount(x.DiscountCouponCode, discount.Id, false);if (!existsAndUsed){- var validationResult = await discountService.ValidateDiscount(discount,- workContext.CurrentCustomer, workContext.WorkingCurrency, x.DiscountCouponCode);+ var validationResult = await discountValidationService.ValidateDiscount(discount,+ workContext.CurrentCustomer, workContext.CurrentStore, workContext.WorkingCurrency, x.DiscountCouponCode);if (!validationResult.IsValid)context.AddFailure(!string.IsNullOrEmpty(validationResult.UserErrorResource)? translationService.GetResource(validationResult.UserErrorResource)