Skip to content

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.

Replace ValidateShoppingCartTotalAmountCommandHandler with new validator

support1a9f5885e7da
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
index 2b3348a76..05d93b316 100644
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs
@@ -446,16 +446,10 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
throw new GrandException("Cart is empty");
//validate the entire shopping cart
- var warnings = await _shoppingCartValidator.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributes, true);
+ var warnings = await _shoppingCartValidator.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributes, true,true);
if (warnings.Any())
{
- var warningsSb = new StringBuilder();
- foreach (var warning in warnings)
- {
- warningsSb.Append(warning);
- warningsSb.Append(';');
- }
- throw new GrandException(warningsSb.ToString());
+ throw new GrandException(string.Join(", ", warnings));
}
//validate individual cart items
@@ -481,20 +475,6 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders
details.RecurringTotalCycles = product.RecurringTotalCycles;
}
- //min totals validation
- var minOrderSubtotalAmountOk = await _mediator.Send(new ValidateMinShoppingCartSubtotalAmountCommand() { Customer = _workContext.CurrentCustomer, Cart = details.Cart });
- if (!minOrderSubtotalAmountOk)
- {
- var minOrderSubtotalAmount = await _currencyService.ConvertFromPrimaryStoreCurrency(_orderSettings.MinOrderSubtotalAmount, _workContext.WorkingCurrency);
- throw new GrandException(string.Format(_translationService.GetResource("Checkout.MinOrderSubtotalAmount"), _priceFormatter.FormatPrice(minOrderSubtotalAmount, _workContext.WorkingCurrency)));
- }
-
- var minmaxOrderTotalAmountOk = await _mediator.Send(new ValidateShoppingCartTotalAmountCommand() { Customer = details.Customer, Cart = details.Cart });
- if (!minmaxOrderTotalAmountOk)
- {
- throw new GrandException(_translationService.GetResource("Checkout.MinMaxOrderTotalAmount"));
- }
-
//tax display type
if (_taxSettings.AllowCustomersToSelectTaxDisplayType)
details.TaxDisplayType = (TaxDisplayType)details.Customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, _workContext.CurrentStore.Id);
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.cs
deleted file mode 100644
index 7a2970516..000000000
--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateShoppingCartTotalAmountCommandHandler.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using Grand.Business.Core.Commands.Checkout.Orders;
-using Grand.Business.Core.Interfaces.Checkout.Orders;
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Domain.Orders;
-using MediatR;
-
-namespace Grand.Business.Checkout.Commands.Handlers.Orders
-{
- public class ValidateShoppingCartTotalAmountCommandHandler : IRequestHandler<ValidateShoppingCartTotalAmountCommand, bool>
- {
- private readonly IOrderCalculationService _orderTotalCalculationService;
- private readonly IGroupService _groupService;
- private readonly OrderSettings _orderSettings;
-
- public ValidateShoppingCartTotalAmountCommandHandler(
- IOrderCalculationService orderTotalCalculationService,
- IGroupService groupService,
- OrderSettings orderSettings)
- {
- _orderTotalCalculationService = orderTotalCalculationService;
- _groupService = groupService;
- _orderSettings = orderSettings;
- }
-
- public async Task<bool> Handle(ValidateShoppingCartTotalAmountCommand request, CancellationToken cancellationToken)
- {
- if (request.Cart == null)
- throw new ArgumentNullException(nameof(request.Cart));
-
- if (request.Customer == null)
- throw new ArgumentNullException(nameof(request.Customer));
-
- var customerGroups = await _groupService.GetAllByIds(request.Customer.Groups.ToArray());
- var minRoles = customerGroups.OrderBy(x => x.MinOrderAmount).FirstOrDefault(x => x.MinOrderAmount.HasValue);
- var minOrderAmount = minRoles?.MinOrderAmount ?? double.MinValue;
-
- var maxRoles = customerGroups.OrderByDescending(x => x.MaxOrderAmount).FirstOrDefault(x => x.MaxOrderAmount.HasValue);
- var maxOrderAmount = maxRoles?.MaxOrderAmount ?? double.MaxValue;
-
- if (!request.Cart.Any() || (!(minOrderAmount > 0) && !(maxOrderAmount > 0) &&
- !(_orderSettings.MinOrderTotalAmount > 0))) return true;
- var shoppingCartTotalBase = (await _orderTotalCalculationService.GetShoppingCartTotal(request.Cart)).shoppingCartTotal;
- if (shoppingCartTotalBase.HasValue && (shoppingCartTotalBase.Value < minOrderAmount || shoppingCartTotalBase.Value > maxOrderAmount))
- return false;
-
- return !(_orderSettings.MinOrderTotalAmount > 0) || !shoppingCartTotalBase.HasValue || !(shoppingCartTotalBase.Value < _orderSettings.MinOrderTotalAmount);
- }
- }
-}
diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs
index 4bf06bba2..7743683c4 100644
--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs
+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs
@@ -123,7 +123,7 @@ namespace Grand.Business.Checkout.Services.Orders
}
public virtual async Task<IList<string>> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart,
- IList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes)
+ IList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes, bool validateAmount)
{
var warnings = new List<string>();
checkoutAttributes ??= new List<CustomAttribute>();
@@ -142,6 +142,15 @@ namespace Grand.Business.Checkout.Services.Orders
if (!resultCheckoutAttributes.IsValid)
warnings.AddRange(resultCheckoutAttributes.Errors.Select(x => x.ErrorMessage));
}
+
+ //validate subtotal/total amount in the cart
+ if (validateAmount)
+ {
+ var validatorCheckoutAttributes = _serviceProvider.GetRequiredService<IValidator<ShoppingCartTotalAmountValidatorRecord>>();
+ var resultCheckoutAttributes = await validatorCheckoutAttributes.ValidateAsync(new ShoppingCartTotalAmountValidatorRecord(_workContext.CurrentCustomer, _workContext.WorkingCurrency, shoppingCart));
+ if (!resultCheckoutAttributes.IsValid)
+ warnings.AddRange(resultCheckoutAttributes.Errors.Select(x => x.ErrorMessage));
+ }
//event notification
await _mediator.ShoppingCartWarningsAdd(warnings, shoppingCart, checkoutAttributes, validateCheckoutAttributes);
diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.cs
new file mode 100644
index 000000000..7eae95f67
--- /dev/null
+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.cs
@@ -0,0 +1,55 @@
+using FluentValidation;
+using Grand.Business.Core.Interfaces.Catalog.Prices;
+using Grand.Business.Core.Interfaces.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Domain.Customers;
+using Grand.Domain.Directory;
+using Grand.Domain.Orders;
+
+namespace Grand.Business.Checkout.Validators;
+
+public record ShoppingCartTotalAmountValidatorRecord(Customer Customer, Currency Currency, IList<ShoppingCartItem> Cart);
+
+public class ShoppingCartTotalAmountValidator : AbstractValidator<ShoppingCartTotalAmountValidatorRecord>
+{
+ public ShoppingCartTotalAmountValidator(
+ IGroupService groupService,
+ IOrderCalculationService orderTotalCalculationService,
+ ICurrencyService currencyService,
+ IPriceFormatter priceFormatter,
+ ITranslationService translationService,
+ OrderSettings orderSettings)
+ {
+ RuleFor(x => x).CustomAsync(async (value, context, _) =>
+ {
+ var customerGroups = await groupService.GetAllByIds(value.Customer.Groups.ToArray());
+ var minRoles = customerGroups.OrderBy(x => x.MinOrderAmount).FirstOrDefault(x => x.MinOrderAmount.HasValue);
+ var minOrderAmount = minRoles?.MinOrderAmount ?? 0;
+
+ var maxRoles = customerGroups.OrderByDescending(x => x.MaxOrderAmount)
+ .FirstOrDefault(x => x.MaxOrderAmount.HasValue);
+ var maxOrderAmount = maxRoles?.MaxOrderAmount ?? int.MaxValue;
+
+ if (!value.Cart.Any() || (!(minOrderAmount > 0) && !(maxOrderAmount > 0) &&
+ !(orderSettings.MinOrderTotalAmount > 0))) return;
+
+ var shoppingCartTotalBase = (await orderTotalCalculationService.GetShoppingCartTotal(value.Cart)).shoppingCartTotal;
+
+ if (shoppingCartTotalBase.HasValue && (shoppingCartTotalBase.Value < minOrderAmount ||
+ shoppingCartTotalBase.Value > maxOrderAmount))
+ context.AddFailure(translationService.GetResource("Checkout.MinMaxOrderTotalAmount"));
+ else if (shoppingCartTotalBase.HasValue && shoppingCartTotalBase.Value < orderSettings.MinOrderTotalAmount)
+ context.AddFailure(translationService.GetResource("Checkout.MinMaxOrderTotalAmount"));
+
+ //subtotal
+ var (_, _, subTotalWithoutDiscount, _, _) = await orderTotalCalculationService.GetShoppingCartSubTotal(value.Cart, false);
+ if (subTotalWithoutDiscount < orderSettings.MinOrderSubtotalAmount)
+ {
+ var minOrderSubtotalAmount =
+ await currencyService.ConvertFromPrimaryStoreCurrency(orderSettings.MinOrderSubtotalAmount, value.Currency);
+ context.AddFailure(string.Format(translationService.GetResource("Checkout.MinOrderSubtotalAmount"), priceFormatter.FormatPrice(minOrderSubtotalAmount, value.Currency)));
+ }
+ });
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateShoppingCartTotalAmountCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateShoppingCartTotalAmountCommand.cs
deleted file mode 100644
index c0cb4d618..000000000
--- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateShoppingCartTotalAmountCommand.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-using Grand.Domain.Customers;
-using Grand.Domain.Orders;
-using MediatR;
-
-namespace Grand.Business.Core.Commands.Checkout.Orders
-{
- public class ValidateShoppingCartTotalAmountCommand : IRequest<bool>
- {
- public Customer Customer { get; set; }
- public IList<ShoppingCartItem> Cart { get; set; }
- }
-}
diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs
index e62552c74..7695a66c3 100644
--- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs
+++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs
@@ -65,9 +65,10 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders
/// <param name="shoppingCart">Shopping cart</param>
/// <param name="checkoutAttributes">Checkout attributes</param>
/// <param name="validateCheckoutAttributes">A value indicating whether to validate checkout attributes</param>
+ /// <param name="validateAmount">A value indicating whether to validate subtotal/total attributes</param>
/// <returns>Warnings</returns>
Task<IList<string>> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart,
- IList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes);
+ IList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes, bool validateAmount);
/// <summary>
/// Validates shopping cart item for reservation products
diff --git a/src/Web/Grand.Web/Controllers/CheckoutController.cs b/src/Web/Grand.Web/Controllers/CheckoutController.cs
index 400a24269..82d4e25a1 100644
--- a/src/Web/Grand.Web/Controllers/CheckoutController.cs
+++ b/src/Web/Grand.Web/Controllers/CheckoutController.cs
@@ -355,7 +355,7 @@ namespace Grand.Web.Controllers
var checkoutAttributes = await customer.GetUserField<List<CustomAttribute>>(_userFieldService,
SystemCustomerFieldNames.CheckoutAttributes,
_workContext.CurrentStore.Id);
- var scWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, true);
+ var scWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, true, true);
if (scWarnings.Any())
return RedirectToRoute("ShoppingCart", new { checkoutAttributes = true });
diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
index 4ffa23611..a1456d531 100644
--- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
+++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs
@@ -521,7 +521,7 @@ namespace Grand.Web.Controllers
}
var checkoutAttributeWarnings =
- await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, true);
+ await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, true, true);
if (checkoutAttributeWarnings.Any())
{
return RedirectToRoute("ShoppingCart", new { checkoutAttributes = true });
diff --git a/src/Web/Grand.Web/Features/Handlers/Checkout/GetConfirmOrderHandler.cs b/src/Web/Grand.Web/Features/Handlers/Checkout/GetConfirmOrderHandler.cs
index 70b2b8dff..11e379f82 100644
--- a/src/Web/Grand.Web/Features/Handlers/Checkout/GetConfirmOrderHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/Checkout/GetConfirmOrderHandler.cs
@@ -1,7 +1,5 @@
-using Grand.Business.Core.Commands.Checkout.Orders;
-using Grand.Business.Core.Interfaces.Checkout.Payments;
+using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Domain.Common;
using Grand.Domain.Customers;
@@ -19,7 +17,6 @@ namespace Grand.Web.Features.Handlers.Checkout
{
private readonly ICountryService _countryService;
private readonly IPaymentService _paymentService;
- private readonly ITranslationService _translationService;
private readonly IMediator _mediator;
private readonly OrderSettings _orderSettings;
private readonly ShippingSettings _shippingSettings;
@@ -27,7 +24,6 @@ namespace Grand.Web.Features.Handlers.Checkout
public GetConfirmOrderHandler(
ICountryService countryService,
IPaymentService paymentService,
- ITranslationService translationService,
IMediator mediator,
OrderSettings orderSettings,
ShippingSettings shippingSettings)
@@ -35,7 +31,6 @@ namespace Grand.Web.Features.Handlers.Checkout
{
_countryService = countryService;
_paymentService = paymentService;
- _translationService = translationService;
_mediator = mediator;
_orderSettings = orderSettings;
_shippingSettings = shippingSettings;
@@ -47,15 +42,7 @@ namespace Grand.Web.Features.Handlers.Checkout
//terms of service
TermsOfServiceOnOrderConfirmPage = _orderSettings.TermsOfServiceOnOrderConfirmPage
};
- //min order amount validation
- var minOrderTotalAmountOk = await _mediator.Send(new ValidateShoppingCartTotalAmountCommand { Customer = request.Customer, Cart = request.Cart }, cancellationToken);
- if (!minOrderTotalAmountOk)
- {
- model.MinOrderTotalWarning = string.Format(_translationService.GetResource("Checkout.MinMaxOrderTotalAmount"));
- }
-
await PrepareOrderReviewData(model, request);
-
return model;
}
diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs
index cd48ed77a..e5e64bb1e 100644
--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetShoppingCartHandler.cs
@@ -181,7 +181,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCart
model.GiftVoucherBox.Display = _shoppingCartSettings.ShowGiftVoucherBox;
//cart warnings
- var cartWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(request.Cart, checkoutAttributes, request.ValidateCheckoutAttributes);
+ var cartWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(request.Cart, checkoutAttributes, request.ValidateCheckoutAttributes, true);
foreach (var warning in cartWarnings)
model.Warnings.Add(warning);
diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs
index 00254eadd..0203d6645 100644
--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs
+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetWishlistHandler.cs
@@ -89,7 +89,7 @@ namespace Grand.Web.Features.Handlers.ShoppingCart
model.ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage;
//cart warnings
- var cartWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(request.Cart, null, false);
+ var cartWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(request.Cart, null, false, false);
foreach (var warning in cartWarnings)
model.Warnings.Add(warning);