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
Grand.Business.Checkout - Code cleanup (ReSharper)
support0416d361cc42
diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.csindex 048f9966e..7997b1dc5 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs@@ -5,65 +5,66 @@ using Grand.Business.Core.Interfaces.Messages;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class+ ActivatedValueForPurchasedGiftVouchersCommandHandler : IRequestHandler<ActivatedValueForPurchasedGiftVouchersCommand+ , bool>{- public class ActivatedValueForPurchasedGiftVouchersCommandHandler : IRequestHandler<ActivatedValueForPurchasedGiftVouchersCommand, bool>+ private readonly IGiftVoucherService _giftVoucherService;+ private readonly ILanguageService _languageService;+ private readonly IMessageProviderService _messageProviderService;++ public ActivatedValueForPurchasedGiftVouchersCommandHandler(+ IGiftVoucherService giftVoucherService,+ ILanguageService languageService,+ IMessageProviderService messageProviderService){- private readonly IGiftVoucherService _giftVoucherService;- private readonly ILanguageService _languageService;- private readonly IMessageProviderService _messageProviderService;+ _giftVoucherService = giftVoucherService;+ _languageService = languageService;+ _messageProviderService = messageProviderService;+ }- public ActivatedValueForPurchasedGiftVouchersCommandHandler(- IGiftVoucherService giftVoucherService,- ILanguageService languageService,- IMessageProviderService messageProviderService)- {- _giftVoucherService = giftVoucherService;- _languageService = languageService;- _messageProviderService = messageProviderService;- }+ public async Task<bool> Handle(ActivatedValueForPurchasedGiftVouchersCommand request,+ CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- public async Task<bool> Handle(ActivatedValueForPurchasedGiftVouchersCommand request, CancellationToken cancellationToken)+ foreach (var orderItem in request.Order.OrderItems){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- foreach (var orderItem in request.Order.OrderItems)- {- var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(purchasedWithOrderItemId: orderItem.Id,- isGiftVoucherActivated: !request.Activate);- foreach (var gc in giftVouchers)+ var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(orderItem.Id,+ isGiftVoucherActivated: !request.Activate);+ foreach (var gc in giftVouchers)+ if (request.Activate){- if (request.Activate)- {- //activate- if (gc.GiftVoucherTypeId == GiftVoucherType.Virtual)+ //activate+ if (gc.GiftVoucherTypeId == GiftVoucherType.Virtual)+ //send email for virtual gift voucher+ if (!string.IsNullOrEmpty(gc.RecipientEmail) &&+ !string.IsNullOrEmpty(gc.SenderEmail)){- //send email for virtual gift voucher- if (!string.IsNullOrEmpty(gc.RecipientEmail) &&- !string.IsNullOrEmpty(gc.SenderEmail))- {- var customerLang = await _languageService.GetLanguageById(request.Order.CustomerLanguageId) ??- (await _languageService.GetAllLanguages()).FirstOrDefault();- if (customerLang == null)- throw new Exception("No languages could be loaded");- _ = await _messageProviderService.SendGiftVoucherMessage(gc, request.Order, customerLang.Id);- gc.IsRecipientNotified = true;- }+ var customerLang =+ await _languageService.GetLanguageById(request.Order.CustomerLanguageId) ??+ (await _languageService.GetAllLanguages()).FirstOrDefault();+ if (customerLang == null)+ throw new Exception("No languages could be loaded");+ _ = await _messageProviderService.SendGiftVoucherMessage(gc, request.Order,+ customerLang.Id);+ gc.IsRecipientNotified = true;}- gc.IsGiftVoucherActivated = true;- await _giftVoucherService.UpdateGiftVoucher(gc);- }- else- {- //deactivate- gc.IsGiftVoucherActivated = false;- await _giftVoucherService.UpdateGiftVoucher(gc);- }- }- }- return true;+ gc.IsGiftVoucherActivated = true;+ await _giftVoucherService.UpdateGiftVoucher(gc);+ }+ else+ {+ //deactivate+ gc.IsGiftVoucherActivated = false;+ await _giftVoucherService.UpdateGiftVoucher(gc);+ }}++ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.csindex 19eff12f2..6d0eb9e4b 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddCustomerReservationCommandHandler.cs@@ -3,99 +3,87 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Domain.Catalog;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class AddCustomerReservationCommandHandler : IRequestHandler<AddCustomerReservationCommand, bool>{- public class AddCustomerReservationCommandHandler : IRequestHandler<AddCustomerReservationCommand, bool>- {- private readonly IProductReservationService _productReservationService;+ private readonly IProductReservationService _productReservationService;- public AddCustomerReservationCommandHandler(IProductReservationService productReservationService)- {- _productReservationService = productReservationService;- }+ public AddCustomerReservationCommandHandler(IProductReservationService productReservationService)+ {+ _productReservationService = productReservationService;+ }- public async Task<bool> Handle(AddCustomerReservationCommand request, CancellationToken cancellationToken)+ public async Task<bool> Handle(AddCustomerReservationCommand request, CancellationToken cancellationToken)+ {+ if (request.RentalStartDate.HasValue && request.RentalEndDate.HasValue){- if (request.RentalStartDate.HasValue && request.RentalEndDate.HasValue)+ var reservations =+ await _productReservationService.GetProductReservationsByProductId(request.Product.Id, true, null);+ var reserved = await _productReservationService.GetCustomerReservationsHelpers(request.Customer.Id);+ foreach (var item in reserved){- var reservations = await _productReservationService.GetProductReservationsByProductId(request.Product.Id, true, null);- var reserved = await _productReservationService.GetCustomerReservationsHelpers(request.Customer.Id);- foreach (var item in reserved)- {- var match = reservations.FirstOrDefault(x => x.Id == item.ReservationId);- if (match != null)- {- reservations.Remove(match);- }- }-- IGrouping<string, ProductReservation> groupToBook = null;-- var grouped = reservations.GroupBy(x => x.Resource);- foreach (var group in grouped)- {- var groupCanBeBooked = true;- if (request.Product.IncBothDate && request.Product.IntervalUnitId == IntervalUnit.Day)- {- for (DateTime iterator = request.RentalStartDate.Value; iterator <= request.RentalEndDate.Value; iterator += new TimeSpan(24, 0, 0))- {- if (group.Select(x => x.Date).Contains(iterator)) continue;- groupCanBeBooked = false;- break;- }- }- else- {- for (DateTime iterator = request.RentalStartDate.Value; iterator < request.RentalEndDate.Value; iterator += new TimeSpan(24, 0, 0))- {- if (group.Select(x => x.Date).Contains(iterator)) continue;- groupCanBeBooked = false;- break;- }- }+ var match = reservations.FirstOrDefault(x => x.Id == item.ReservationId);+ if (match != null) reservations.Remove(match);+ }- if (!groupCanBeBooked) continue;- groupToBook = group;- break;- }+ IGrouping<string, ProductReservation> groupToBook = null;- if (groupToBook != null)- {- if (request.Product.IncBothDate && request.Product.IntervalUnitId == IntervalUnit.Day)+ var grouped = reservations.GroupBy(x => x.Resource);+ foreach (var group in grouped)+ {+ var groupCanBeBooked = true;+ if (request.Product.IncBothDate && request.Product.IntervalUnitId == IntervalUnit.Day)+ for (var iterator = request.RentalStartDate.Value;+ iterator <= request.RentalEndDate.Value;+ iterator += new TimeSpan(24, 0, 0)){- foreach (var item in groupToBook.Where(x => x.Date >= request.RentalStartDate && x.Date <= request.RentalEndDate))- {- await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {- CustomerId = request.Customer.Id,- ReservationId = item.Id,- ShoppingCartItemId = request.ShoppingCartItem.Id- });- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}- else+ else+ for (var iterator = request.RentalStartDate.Value;+ iterator < request.RentalEndDate.Value;+ iterator += new TimeSpan(24, 0, 0)){- foreach (var item in groupToBook.Where(x => x.Date >= request.RentalStartDate && x.Date < request.RentalEndDate))- {- await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {- CustomerId = request.Customer.Id,- ReservationId = item.Id,- ShoppingCartItemId = request.ShoppingCartItem.Id- });- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}- }+ if (!groupCanBeBooked) continue;+ groupToBook = group;+ break;}- if (!string.IsNullOrEmpty(request.ReservationId))++ if (groupToBook != null){- await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {- CustomerId = request.Customer.Id,- ReservationId = request.ReservationId,- ShoppingCartItemId = request.ShoppingCartItem.Id- });+ if (request.Product.IncBothDate && request.Product.IntervalUnitId == IntervalUnit.Day)+ foreach (var item in groupToBook.Where(x =>+ x.Date >= request.RentalStartDate && x.Date <= request.RentalEndDate))+ await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {+ CustomerId = request.Customer.Id,+ ReservationId = item.Id,+ ShoppingCartItemId = request.ShoppingCartItem.Id+ });+ else+ foreach (var item in groupToBook.Where(x =>+ x.Date >= request.RentalStartDate && x.Date < request.RentalEndDate))+ await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {+ CustomerId = request.Customer.Id,+ ReservationId = item.Id,+ ShoppingCartItemId = request.ShoppingCartItem.Id+ });}- return true;}- }+ if (!string.IsNullOrEmpty(request.ReservationId))+ await _productReservationService.InsertCustomerReservationsHelper(new CustomerReservationsHelper {+ CustomerId = request.Customer.Id,+ ReservationId = request.ReservationId,+ ShoppingCartItemId = request.ShoppingCartItem.Id+ });+ return true;+ }}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.csindex 39e2f6140..d6328953f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AddRequiredProductsCommandHandler.cs@@ -6,70 +6,67 @@ using Grand.Domain.Catalog;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class AddRequiredProductsCommandHandler : IRequestHandler<AddRequiredProductsCommand, bool>{- public class AddRequiredProductsCommandHandler : IRequestHandler<AddRequiredProductsCommand, bool>+ private readonly IProductService _productService;+ private readonly IShoppingCartService _shoppingCartService;+ private readonly ShoppingCartSettings _shoppingCartSettings;++ public AddRequiredProductsCommandHandler(IShoppingCartService shoppingCartService,+ ShoppingCartSettings shoppingCartSettings+ , IProductService productService){- private readonly IShoppingCartService _shoppingCartService;- private readonly ShoppingCartSettings _shoppingCartSettings;- private readonly IProductService _productService;+ _shoppingCartService = shoppingCartService;+ _shoppingCartSettings = shoppingCartSettings;+ _productService = productService;+ }- public AddRequiredProductsCommandHandler(IShoppingCartService shoppingCartService, ShoppingCartSettings shoppingCartSettings- , IProductService productService)- {- _shoppingCartService = shoppingCartService;- _shoppingCartSettings = shoppingCartSettings;- _productService = productService;- }+ public async Task<bool> Handle(AddRequiredProductsCommand request, CancellationToken cancellationToken)+ {+ var customer = request.Customer;+ var shoppingCartType = request.ShoppingCartType;+ var storeId = request.StoreId;+ var product = request.Product;+ var cart = customer.ShoppingCartItems+ .Where(sci => sci.ShoppingCartTypeId == shoppingCartType)+ .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId)+ .ToList();- public async Task<bool> Handle(AddRequiredProductsCommand request, CancellationToken cancellationToken)+ if (!product.RequireOtherProducts) return true;{- var customer = request.Customer;- var shoppingCartType = request.ShoppingCartType;- var storeId = request.StoreId;- var product = request.Product;- var cart = customer.ShoppingCartItems- .Where(sci => sci.ShoppingCartTypeId == shoppingCartType)- .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId)- .ToList();-- if (!product.RequireOtherProducts) return true;+ var requiredProducts = new List<Product>();+ foreach (var id in product.ParseRequiredProductIds()){- var requiredProducts = new List<Product>();- foreach (var id in product.ParseRequiredProductIds())- {- var rp = await _productService.GetProductById(id);- if (rp != null)- requiredProducts.Add(rp);- }+ var rp = await _productService.GetProductById(id);+ if (rp != null)+ requiredProducts.Add(rp);+ }- foreach (var rp in requiredProducts)- {- //ensure that product is in the cart- var alreadyInTheCart = cart.Any(sci => sci.ProductId == rp.Id);- //not in the cart- if (alreadyInTheCart) continue;- if (!product.AutoAddRequiredProducts) continue;- var addToCart = await _shoppingCartService.AddToCart(customer: customer,- productId: rp.Id,- shoppingCartType: shoppingCartType,- storeId: storeId,- automaticallyAddRequiredProductsIfEnabled: false,- validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false });+ foreach (var rp in requiredProducts)+ {+ //ensure that product is in the cart+ var alreadyInTheCart = cart.Any(sci => sci.ProductId == rp.Id);+ //not in the cart+ if (alreadyInTheCart) continue;+ if (!product.AutoAddRequiredProducts) continue;+ var addToCart = await _shoppingCartService.AddToCart(customer,+ rp.Id,+ shoppingCartType,+ storeId,+ automaticallyAddRequiredProductsIfEnabled: false,+ validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false });- if (rp.RequireOtherProducts && addToCart.warnings.Count == 0)- {- await Handle(new AddRequiredProductsCommand {- Customer = customer,- ShoppingCartType = shoppingCartType,- StoreId = storeId,- Product = rp- }, cancellationToken);- }- }+ if (rp.RequireOtherProducts && addToCart.warnings.Count == 0)+ await Handle(new AddRequiredProductsCommand {+ Customer = customer,+ ShoppingCartType = shoppingCartType,+ StoreId = storeId,+ Product = rp+ }, cancellationToken);}- return true;}+ return true;}-}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.csindex 14d78850b..3cf52bed5 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs@@ -5,55 +5,58 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class AwardLoyaltyPointsCommandHandler : IRequestHandler<AwardLoyaltyPointsCommand, bool>{- public class AwardLoyaltyPointsCommandHandler : IRequestHandler<AwardLoyaltyPointsCommand, bool>+ private readonly ICurrencyService _currencyService;+ private readonly ICustomerService _customerService;+ private readonly ILoyaltyPointsService _loyaltyPointsService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly ITranslationService _translationService;++ public AwardLoyaltyPointsCommandHandler(+ ICustomerService customerService,+ ILoyaltyPointsService loyaltyPointsService,+ IMediator mediator,+ IOrderService orderService,+ ITranslationService translationService,+ ICurrencyService currencyService)+ {+ _customerService = customerService;+ _loyaltyPointsService = loyaltyPointsService;+ _mediator = mediator;+ _orderService = orderService;+ _translationService = translationService;+ _currencyService = currencyService;+ }++ public async Task<bool> Handle(AwardLoyaltyPointsCommand request, CancellationToken cancellationToken){- private readonly ICustomerService _customerService;- private readonly ILoyaltyPointsService _loyaltyPointsService;- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly ITranslationService _translationService;- private readonly ICurrencyService _currencyService;-- public AwardLoyaltyPointsCommandHandler(- ICustomerService customerService,- ILoyaltyPointsService loyaltyPointsService,- IMediator mediator,- IOrderService orderService,- ITranslationService translationService,- ICurrencyService currencyService)- {- _customerService = customerService;- _loyaltyPointsService = loyaltyPointsService;- _mediator = mediator;- _orderService = orderService;- _translationService = translationService;- _currencyService = currencyService;- }-- public async Task<bool> Handle(AwardLoyaltyPointsCommand request, CancellationToken cancellationToken)- {- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- var customer = await _customerService.GetCustomerById(request.Order.CustomerId);- var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode);- var amount = await _currencyService.ConvertToPrimaryStoreCurrency(request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency);- var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount }, cancellationToken);- if (points <= 0)- return false;-- //add loyalty points- await _loyaltyPointsService.AddLoyaltyPointsHistory(customer.Id, points,- request.Order.StoreId, string.Format(_translationService.GetResource("LoyaltyPoints.Message.EarnedForOrder"), request.Order.OrderNumber));-- request.Order.CalcLoyaltyPoints += points;- //assign to order- await _orderService.UpdateOrder(request.Order);-- return true;-- }+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));++ var customer = await _customerService.GetCustomerById(request.Order.CustomerId);+ var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode);+ var amount =+ await _currencyService.ConvertToPrimaryStoreCurrency(+ request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency);+ var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount },+ cancellationToken);+ if (points <= 0)+ return false;++ //add loyalty points+ await _loyaltyPointsService.AddLoyaltyPointsHistory(customer.Id, points,+ request.Order.StoreId,+ string.Format(_translationService.GetResource("LoyaltyPoints.Message.EarnedForOrder"),+ request.Order.OrderNumber));++ request.Order.CalcLoyaltyPoints += points;+ //assign to order+ await _orderService.UpdateOrder(request.Order);++ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandler.csindex 94d129a7c..17d49fc39 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandler.cs@@ -2,31 +2,31 @@using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class CalculateLoyaltyPointsCommandHandler : IRequestHandler<CalculateLoyaltyPointsCommand, int>{- public class CalculateLoyaltyPointsCommandHandler : IRequestHandler<CalculateLoyaltyPointsCommand, int>- {- private readonly LoyaltyPointsSettings _loyaltyPointsSettings;+ private readonly LoyaltyPointsSettings _loyaltyPointsSettings;- public CalculateLoyaltyPointsCommandHandler(LoyaltyPointsSettings loyaltyPointsSettings)- {- _loyaltyPointsSettings = loyaltyPointsSettings;- }+ public CalculateLoyaltyPointsCommandHandler(LoyaltyPointsSettings loyaltyPointsSettings)+ {+ _loyaltyPointsSettings = loyaltyPointsSettings;+ }- public async Task<int> Handle(CalculateLoyaltyPointsCommand request, CancellationToken cancellationToken)- {- if (!_loyaltyPointsSettings.Enabled)- return 0;+ public async Task<int> Handle(CalculateLoyaltyPointsCommand request, CancellationToken cancellationToken)+ {+ if (!_loyaltyPointsSettings.Enabled)+ return 0;- if (_loyaltyPointsSettings.PointsForPurchases_Amount <= 0)- return 0;+ if (_loyaltyPointsSettings.PointsForPurchases_Amount <= 0)+ return 0;- if (request.Customer == null)- return 0;+ if (request.Customer == null)+ return 0;- var points = (int)Math.Truncate(request.Amount / _loyaltyPointsSettings.PointsForPurchases_Amount * _loyaltyPointsSettings.PointsForPurchases_Points);+ var points = (int)Math.Truncate(request.Amount / _loyaltyPointsSettings.PointsForPurchases_Amount *+ _loyaltyPointsSettings.PointsForPurchases_Points);- return await Task.FromResult(points);- }+ return await Task.FromResult(points);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.csindex b85b1af4e..4b1507b5f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs@@ -1,117 +1,112 @@-using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Events.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Discounts;using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;+using Grand.Business.Core.Interfaces.Checkout.Payments;using Grand.Business.Core.Interfaces.Checkout.Shipping;-using Grand.Business.Core.Events.Checkout.Orders;using Grand.Domain.Orders;using MediatR;-using Grand.Business.Core.Interfaces.Checkout.Payments;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class CancelOrderCommandHandler : IRequestHandler<CancelOrderCommand, bool>{- public class CancelOrderCommandHandler : IRequestHandler<CancelOrderCommand, bool>+ private readonly IAuctionService _auctionService;+ private readonly IDiscountService _discountService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentService _paymentService;+ private readonly IPaymentTransactionService _paymentTransactionService;+ private readonly IProductReservationService _productReservationService;+ private readonly IProductService _productService;+ private readonly IShipmentService _shipmentService;++ public CancelOrderCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IProductService productService,+ IInventoryManageService inventoryManageService,+ IProductReservationService productReservationService,+ IAuctionService auctionService,+ IDiscountService discountService,+ IPaymentService paymentService,+ IPaymentTransactionService paymentTransactionService){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;- private readonly IProductReservationService _productReservationService;- private readonly IAuctionService _auctionService;- private readonly IDiscountService _discountService;- private readonly IPaymentService _paymentService;- private readonly IPaymentTransactionService _paymentTransactionService;-- public CancelOrderCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IProductService productService,- IInventoryManageService inventoryManageService,- IProductReservationService productReservationService,- IAuctionService auctionService,- IDiscountService discountService,- IPaymentService paymentService,- IPaymentTransactionService paymentTransactionService)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _productService = productService;- _inventoryManageService = inventoryManageService;- _productReservationService = productReservationService;- _auctionService = auctionService;- _discountService = discountService;- _paymentService = paymentService;- _paymentTransactionService = paymentTransactionService;- }+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ _productReservationService = productReservationService;+ _auctionService = auctionService;+ _discountService = discountService;+ _paymentService = paymentService;+ _paymentTransactionService = paymentTransactionService;+ }- public async Task<bool> Handle(CancelOrderCommand request, CancellationToken cancellationToken)+ public async Task<bool> Handle(CancelOrderCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));++ if (request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)+ throw new Exception("Cannot do cancel for order.");++ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);+ if (shipments.Any())+ throw new Exception("Cannot do cancel for order with shipments");++ //Cancel order+ await _mediator.Send(new SetOrderStatusCommand {+ Order = request.Order,+ Os = OrderStatusSystem.Cancelled,+ NotifyCustomer = request.NotifyCustomer,+ NotifyStoreOwner = request.NotifyStoreOwner+ }, cancellationToken);++ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = "Order has been cancelled",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });++ //return (add) back redeemed loyalty points+ await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand { Order = request.Order }, cancellationToken);++ //Adjust inventory+ foreach (var orderItem in request.Order.OrderItems){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)- throw new Exception("Cannot do cancel for order.");-- var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);- if (shipments.Any())- throw new Exception("Cannot do cancel for order with shipments");-- //Cancel order- await _mediator.Send(new SetOrderStatusCommand- {- Order = request.Order,- Os = OrderStatusSystem.Cancelled,- NotifyCustomer = request.NotifyCustomer,- NotifyStoreOwner = request.NotifyStoreOwner- }, cancellationToken);-- //add a note- await _orderService.InsertOrderNote(new OrderNote- {- Note = "Order has been cancelled",- DisplayToCustomer = false,- OrderId = request.Order.Id-- });-- //return (add) back redeemed loyalty points- await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand { Order = request.Order }, cancellationToken);-- //Adjust inventory- foreach (var orderItem in request.Order.OrderItems)- {- var product = await _productService.GetProductById(orderItem.ProductId);- await _inventoryManageService.AdjustReserved(product, orderItem.Quantity - orderItem.CancelQty, orderItem.Attributes, orderItem.WarehouseId);- }- //update open qty- foreach (var orderItem in request.Order.OrderItems)- {- orderItem.OpenQty = 0;- }-- await _orderService.UpdateOrder(request.Order);-- //cancel reservations- await _productReservationService.CancelReservationsByOrderId(request.Order.Id);-- //cancel bid- await _auctionService.CancelBidByOrder(request.Order.Id);-- //cancel discount- await _discountService.CancelDiscount(request.Order.Id);-- //cancel payments- var payment = await _paymentTransactionService.GetOrderByGuid(request.Order.OrderGuid);- if (payment != null)- await _paymentService.CancelPayment(payment);-- //event notification- await _mediator.Publish(new OrderCancelledEvent(request.Order), cancellationToken);-- return true;+ var product = await _productService.GetProductById(orderItem.ProductId);+ await _inventoryManageService.AdjustReserved(product, orderItem.Quantity - orderItem.CancelQty,+ orderItem.Attributes, orderItem.WarehouseId);}++ //update open qty+ foreach (var orderItem in request.Order.OrderItems) orderItem.OpenQty = 0;++ await _orderService.UpdateOrder(request.Order);++ //cancel reservations+ await _productReservationService.CancelReservationsByOrderId(request.Order.Id);++ //cancel bid+ await _auctionService.CancelBidByOrder(request.Order.Id);++ //cancel discount+ await _discountService.CancelDiscount(request.Order.Id);++ //cancel payments+ var payment = await _paymentTransactionService.GetOrderByGuid(request.Order.OrderGuid);+ if (payment != null)+ await _paymentService.CancelPayment(payment);++ //event notification+ await _mediator.Publish(new OrderCancelledEvent(request.Order), cancellationToken);++ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.csindex cbf963211..02aea6f73 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs@@ -1,89 +1,82 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;using Grand.Domain.Orders;using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class CancelOrderItemCommandHandler : IRequestHandler<CancelOrderItemCommand, (bool error, string message)>{- public class CancelOrderItemCommandHandler : IRequestHandler<CancelOrderItemCommand, (bool error, string message)>- {- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IProductService _productService;+ private readonly IShipmentService _shipmentService;- public CancelOrderItemCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IProductService productService,- IInventoryManageService inventoryManageService)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _productService = productService;- _inventoryManageService = inventoryManageService;- }+ public CancelOrderItemCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IProductService productService,+ IInventoryManageService inventoryManageService)+ {+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ }- public async Task<(bool error, string message)> Handle(CancelOrderItemCommand request, CancellationToken cancellationToken)- {- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ public async Task<(bool error, string message)> Handle(CancelOrderItemCommand request,+ CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));+ if (request.OrderItem == null)+ throw new ArgumentNullException(nameof(request.OrderItem));- var product = await _productService.GetProductById(request.OrderItem.ProductId);- if (product == null)- return (true, "Product not exists.");+ var product = await _productService.GetProductById(request.OrderItem.ProductId);+ if (product == null)+ return (true, "Product not exists.");- if (request.OrderItem.OpenQty == 0 || request.OrderItem.Status == OrderItemStatus.Close)- {- return (true, "You can't cancel this order item.");- }- if (product.IsGiftVoucher)- {- return (true, "You can't cancel gift voucher, please delete it.");- }+ if (request.OrderItem.OpenQty == 0 || request.OrderItem.Status == OrderItemStatus.Close)+ return (true, "You can't cancel this order item.");+ if (product.IsGiftVoucher) return (true, "You can't cancel gift voucher, please delete it.");- //add a note- await _orderService.InsertOrderNote(new OrderNote {- Note = $"Order item has been canceled - {product.Name} - Qty: {request.OrderItem.OpenQty}",- DisplayToCustomer = false,- OrderId = request.Order.Id- });+ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = $"Order item has been canceled - {product.Name} - Qty: {request.OrderItem.OpenQty}",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });- await _inventoryManageService.AdjustReserved(product, request.OrderItem.OpenQty, request.OrderItem.Attributes, request.OrderItem.WarehouseId);+ await _inventoryManageService.AdjustReserved(product, request.OrderItem.OpenQty, request.OrderItem.Attributes,+ request.OrderItem.WarehouseId);- request.OrderItem.CancelQty = request.OrderItem.OpenQty;- request.OrderItem.CancelAmount = Math.Round(request.OrderItem.UnitPriceInclTax / request.OrderItem.CancelQty, 2);- request.OrderItem.OpenQty = 0;- request.OrderItem.Status = OrderItemStatus.Close;+ request.OrderItem.CancelQty = request.OrderItem.OpenQty;+ request.OrderItem.CancelAmount =+ Math.Round(request.OrderItem.UnitPriceInclTax / request.OrderItem.CancelQty, 2);+ request.OrderItem.OpenQty = 0;+ request.OrderItem.Status = OrderItemStatus.Close;- if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped)- {- var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);- if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.ShippedDateUtc != null))- {- request.Order.ShippingStatusId = ShippingStatus.Shipped;- }- if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))- {- request.Order.ShippingStatusId = ShippingStatus.Delivered;- }- }+ if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped)+ {+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.ShippedDateUtc != null))+ request.Order.ShippingStatusId = ShippingStatus.Shipped;+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))+ request.Order.ShippingStatusId = ShippingStatus.Delivered;+ }- await _orderService.UpdateOrder(request.Order);+ await _orderService.UpdateOrder(request.Order);- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);- return (false, "");- }+ return (false, "");}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.csindex df599a83d..0e6faeed6 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs@@ -1,4 +1,5 @@using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;using Grand.Business.Core.Queries.Checkout.Orders;@@ -6,97 +7,94 @@ using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-using Grand.Business.Core.Extensions;using Microsoft.Extensions.Logging;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class CaptureCommandHandler : IRequestHandler<CaptureCommand, IList<string>>{- public class CaptureCommandHandler : IRequestHandler<CaptureCommand, IList<string>>+ private readonly ILogger<CaptureCommandHandler> _logger;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentService _paymentService;+ private readonly IPaymentTransactionService _paymentTransaction;++ public CaptureCommandHandler(+ IPaymentService paymentService,+ IPaymentTransactionService paymentTransaction,+ IMediator mediator,+ IOrderService orderService,+ ILogger<CaptureCommandHandler> logger){- private readonly IPaymentService _paymentService;- private readonly IPaymentTransactionService _paymentTransaction;- private readonly IOrderService _orderService;- private readonly IMediator _mediator;- private readonly ILogger<CaptureCommandHandler> _logger;+ _paymentService = paymentService;+ _paymentTransaction = paymentTransaction;+ _mediator = mediator;+ _orderService = orderService;+ _logger = logger;+ }- public CaptureCommandHandler(- IPaymentService paymentService,- IPaymentTransactionService paymentTransaction,- IMediator mediator,- IOrderService orderService,- ILogger<CaptureCommandHandler> logger)- {- _paymentService = paymentService;- _paymentTransaction = paymentTransaction;- _mediator = mediator;- _orderService = orderService;- _logger = logger;- }+ public async Task<IList<string>> Handle(CaptureCommand command, CancellationToken cancellationToken)+ {+ var paymentTransaction = command.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(command.PaymentTransaction));++ var canCapture = await _mediator.Send(new CanCaptureQuery { PaymentTransaction = paymentTransaction },+ cancellationToken);+ if (!canCapture)+ throw new GrandException("Cannot do capture for order.");- public async Task<IList<string>> Handle(CaptureCommand command, CancellationToken cancellationToken)+ CapturePaymentResult result = null;+ try{- var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ result = await _paymentService.Capture(paymentTransaction);- var canCapture = await _mediator.Send(new CanCaptureQuery { PaymentTransaction = paymentTransaction }, cancellationToken);- if (!canCapture)- throw new GrandException("Cannot do capture for order.");+ //event notification+ await _mediator.CapturePaymentTransactionDetailsEvent(result, paymentTransaction);- CapturePaymentResult result = null;- try+ if (result.Success){- result = await _paymentService.Capture(paymentTransaction);+ paymentTransaction = await _paymentTransaction.GetById(paymentTransaction.Id);+ paymentTransaction.PaidAmount = paymentTransaction.TransactionAmount;+ paymentTransaction.CaptureTransactionId = result.CaptureTransactionId;+ paymentTransaction.CaptureTransactionResult = result.CaptureTransactionResult;+ paymentTransaction.TransactionStatus = result.NewPaymentStatus;- //event notification- await _mediator.CapturePaymentTransactionDetailsEvent(result, paymentTransaction);+ await _paymentTransaction.UpdatePaymentTransaction(paymentTransaction);- if (result.Success)+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order != null && paymentTransaction.TransactionStatus == TransactionStatus.Paid){- paymentTransaction = await _paymentTransaction.GetById(paymentTransaction.Id);- paymentTransaction.PaidAmount = paymentTransaction.TransactionAmount;- paymentTransaction.CaptureTransactionId = result.CaptureTransactionId;- paymentTransaction.CaptureTransactionResult = result.CaptureTransactionResult;- paymentTransaction.TransactionStatus = result.NewPaymentStatus;-- await _paymentTransaction.UpdatePaymentTransaction(paymentTransaction);-- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order != null && paymentTransaction.TransactionStatus == TransactionStatus.Paid)- {- order.PaidAmount = paymentTransaction.PaidAmount;- order.PaymentStatusId = PaymentStatus.Paid;- order.PaidDateUtc = DateTime.UtcNow;- await _orderService.UpdateOrder(order);- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- if (order.PaymentStatusId == PaymentStatus.Paid)- {- await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);- }- }+ order.PaidAmount = paymentTransaction.PaidAmount;+ order.PaymentStatusId = PaymentStatus.Paid;+ order.PaidDateUtc = DateTime.UtcNow;+ await _orderService.UpdateOrder(order);+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ if (order.PaymentStatusId == PaymentStatus.Paid)+ await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);}}- catch (Exception exc)- {- result ??= new CapturePaymentResult();- result.AddError($"Error: {exc.Message}. Full exception: {exc}");- }+ }+ catch (Exception exc)+ {+ result ??= new CapturePaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");+ }- //process errors- var error = "";- for (var i = 0; i < result.Errors.Count; i++)- {- error += $"Error {i}: {result.Errors[i]}";- if (i != result.Errors.Count - 1)- error += ". ";- }- if (!string.IsNullOrEmpty(error))- {- //log it- _logger.LogError("Error capturing order code # {PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);- }- return result.Errors;+ //process errors+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++)+ {+ error += $"Error {i}: {result.Errors[i]}";+ if (i != result.Errors.Count - 1)+ error += ". ";}++ if (!string.IsNullOrEmpty(error))+ //log it+ _logger.LogError("Error capturing order code # {PaymentTransactionOrderCode}. Error: {Error}",+ paymentTransaction.OrderCode, error);+ return result.Errors;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.csindex 0b0e88d32..2c91fd7b2 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs@@ -5,96 +5,85 @@ using Grand.Domain.Payments;using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class CheckOrderStatusCommandHandler : IRequestHandler<CheckOrderStatusCommand, bool>{- public class CheckOrderStatusCommandHandler : IRequestHandler<CheckOrderStatusCommand, bool>+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly OrderSettings _orderSettings;++ public CheckOrderStatusCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ OrderSettings orderSettings)+ {+ _mediator = mediator;+ _orderService = orderService;+ _orderSettings = orderSettings;+ }++ public async Task<bool> Handle(CheckOrderStatusCommand request, CancellationToken cancellationToken){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly OrderSettings _orderSettings;+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- public CheckOrderStatusCommandHandler(- IMediator mediator,- IOrderService orderService,- OrderSettings orderSettings)+ if (request.Order.PaymentStatusId == PaymentStatus.Paid && !request.Order.PaidDateUtc.HasValue){- _mediator = mediator;- _orderService = orderService;- _orderSettings = orderSettings;+ //ensure that paid date is set+ request.Order.PaidDateUtc = DateTime.UtcNow;+ await _orderService.UpdateOrder(request.Order);}- public async Task<bool> Handle(CheckOrderStatusCommand request, CancellationToken cancellationToken)+ switch (request.Order.OrderStatusId){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.Order.PaymentStatusId == PaymentStatus.Paid && !request.Order.PaidDateUtc.HasValue)+ case (int)OrderStatusSystem.Pending:{- //ensure that paid date is set- request.Order.PaidDateUtc = DateTime.UtcNow;- await _orderService.UpdateOrder(request.Order);- }+ if (request.Order.PaymentStatusId is PaymentStatus.Authorized or PaymentStatus.Paid+ or PaymentStatus.PartiallyPaid)+ await _mediator.Send(new SetOrderStatusCommand {+ Order = request.Order,+ Os = OrderStatusSystem.Processing,+ NotifyCustomer = false,+ NotifyStoreOwner = false+ }, cancellationToken);- switch (request.Order.OrderStatusId)- {- case (int)OrderStatusSystem.Pending:- {- if (request.Order.PaymentStatusId is PaymentStatus.Authorized or PaymentStatus.Paid or PaymentStatus.PartiallyPaid)- {- await _mediator.Send(new SetOrderStatusCommand- {- Order = request.Order,- Os = OrderStatusSystem.Processing,- NotifyCustomer = false,- NotifyStoreOwner = false- }, cancellationToken);- }+ if (request.Order.ShippingStatusId is ShippingStatus.PartiallyShipped or ShippingStatus.Shipped+ or ShippingStatus.Delivered)+ await _mediator.Send(new SetOrderStatusCommand {+ Order = request.Order,+ Os = OrderStatusSystem.Processing,+ NotifyCustomer = false,+ NotifyStoreOwner = false+ }, cancellationToken);- if (request.Order.ShippingStatusId is ShippingStatus.PartiallyShipped or ShippingStatus.Shipped or ShippingStatus.Delivered)- {- await _mediator.Send(new SetOrderStatusCommand- {- Order = request.Order,- Os = OrderStatusSystem.Processing,- NotifyCustomer = false,- NotifyStoreOwner = false- }, cancellationToken);- }-- break;- }- case (int)OrderStatusSystem.Cancelled or (int)OrderStatusSystem.Complete:- return true;+ break;}+ case (int)OrderStatusSystem.Cancelled or (int)OrderStatusSystem.Complete:+ return true;+ }- if (request.Order.PaymentStatusId != PaymentStatus.Paid) return true;- bool completed;- if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired)- {- completed = true;- }+ if (request.Order.PaymentStatusId != PaymentStatus.Paid) return true;+ bool completed;+ if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired)+ {+ completed = true;+ }+ else+ {+ if (_orderSettings.CompleteOrderWhenDelivered)+ completed = request.Order.ShippingStatusId == ShippingStatus.Delivered;else- {- if (_orderSettings.CompleteOrderWhenDelivered)- {- completed = request.Order.ShippingStatusId == ShippingStatus.Delivered;- }- else- {- completed = request.Order.ShippingStatusId is ShippingStatus.Shipped or ShippingStatus.Delivered;- }- }- if (completed)- {- await _mediator.Send(new SetOrderStatusCommand- {- Order = request.Order,- Os = OrderStatusSystem.Complete,- NotifyCustomer = true,- NotifyStoreOwner = false- }, cancellationToken);- }- return true;+ completed = request.Order.ShippingStatusId is ShippingStatus.Shipped or ShippingStatus.Delivered;}++ if (completed)+ await _mediator.Send(new SetOrderStatusCommand {+ Order = request.Order,+ Os = OrderStatusSystem.Complete,+ NotifyCustomer = true,+ NotifyStoreOwner = false+ }, cancellationToken);+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.csindex fdf39b87e..ca8a98332 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs@@ -1,104 +1,106 @@-using Grand.Business.Core.Interfaces.Catalog.Discounts;-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Events.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Discounts;+using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class DeleteOrderCommandHandler : IRequestHandler<DeleteOrderCommand, bool>{- public class DeleteOrderCommandHandler : IRequestHandler<DeleteOrderCommand, bool>+ private readonly IAuctionService _auctionService;+ private readonly IDiscountService _discountService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly OrderSettings _orderSettings;+ private readonly IProductReservationService _productReservationService;+ private readonly IProductService _productService;+ private readonly IShipmentService _shipmentService;++ public DeleteOrderCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IProductService productService,+ IInventoryManageService inventoryManageService,+ IProductReservationService productReservationService,+ IAuctionService auctionService,+ IDiscountService discountService,+ OrderSettings orderSettings){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;- private readonly IProductReservationService _productReservationService;- private readonly IAuctionService _auctionService;- private readonly IDiscountService _discountService;- private readonly OrderSettings _orderSettings;-- public DeleteOrderCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IProductService productService,- IInventoryManageService inventoryManageService,- IProductReservationService productReservationService,- IAuctionService auctionService,- IDiscountService discountService,- OrderSettings orderSettings)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _productService = productService;- _inventoryManageService = inventoryManageService;- _productReservationService = productReservationService;- _auctionService = auctionService;- _discountService = discountService;- _orderSettings = orderSettings;- }+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ _productReservationService = productReservationService;+ _auctionService = auctionService;+ _discountService = discountService;+ _orderSettings = orderSettings;+ }- public async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken)- {- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ public async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);- if (shipments.Any())- throw new Exception("Cannot do delete for order with shipments");+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);+ if (shipments.Any())+ throw new Exception("Cannot do delete for order with shipments");- //check whether the order wasn't cancelled before- if (request.Order.OrderStatusId != (int)OrderStatusSystem.Cancelled)- {- //return (add) back redeemed loyalty points- await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand { Order = request.Order }, cancellationToken);+ //check whether the order wasn't cancelled before+ if (request.Order.OrderStatusId != (int)OrderStatusSystem.Cancelled)+ {+ //return (add) back redeemed loyalty points+ await _mediator.Send(new ReturnBackRedeemedLoyaltyPointsCommand { Order = request.Order },+ cancellationToken);- //reduce (cancel) back loyalty points (previously awarded for this order)- await _mediator.Send(new ReduceLoyaltyPointsCommand { Order = request.Order }, cancellationToken);+ //reduce (cancel) back loyalty points (previously awarded for this order)+ await _mediator.Send(new ReduceLoyaltyPointsCommand { Order = request.Order }, cancellationToken);- //Adjust inventory- foreach (var orderItem in request.Order.OrderItems)- {- var product = await _productService.GetProductById(orderItem.ProductId);- if (product != null)- await _inventoryManageService.AdjustReserved(product, orderItem.Quantity-orderItem.CancelQty, orderItem.Attributes, orderItem.WarehouseId);- }+ //Adjust inventory+ foreach (var orderItem in request.Order.OrderItems)+ {+ var product = await _productService.GetProductById(orderItem.ProductId);+ if (product != null)+ await _inventoryManageService.AdjustReserved(product, orderItem.Quantity - orderItem.CancelQty,+ orderItem.Attributes, orderItem.WarehouseId);+ }- //cancel reservations- await _productReservationService.CancelReservationsByOrderId(request.Order.Id);+ //cancel reservations+ await _productReservationService.CancelReservationsByOrderId(request.Order.Id);- //cancel bid- await _auctionService.CancelBidByOrder(request.Order.Id);- }+ //cancel bid+ await _auctionService.CancelBidByOrder(request.Order.Id);+ }- //deactivate gift vouchers- if (_orderSettings.DeactivateGiftVouchersAfterDeletingOrder)- await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = false }, cancellationToken);+ //deactivate gift vouchers+ if (_orderSettings.DeactivateGiftVouchersAfterDeletingOrder)+ await _mediator.Send(+ new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = false },+ cancellationToken);- request.Order.Deleted = true;- //now delete an order- await _orderService.UpdateOrder(request.Order);+ request.Order.Deleted = true;+ //now delete an order+ await _orderService.UpdateOrder(request.Order);- //cancel discounts- await _discountService.CancelDiscount(request.Order.Id);+ //cancel discounts+ await _discountService.CancelDiscount(request.Order.Id);- //add a note- await _orderService.InsertOrderNote(new OrderNote- {- Note = "Order has been deleted",- DisplayToCustomer = false,- OrderId = request.Order.Id- });+ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = "Order has been deleted",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });- //event notification- await _mediator.Publish(new OrderDeletedEvent(request.Order), cancellationToken);+ //event notification+ await _mediator.Publish(new OrderDeletedEvent(request.Order), cancellationToken);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.csindex 87e353fd3..4d1d272cc 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs@@ -1,5 +1,5 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;@@ -7,107 +7,98 @@ using Grand.Domain.Orders;using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class DeleteOrderItemCommandHandler : IRequestHandler<DeleteOrderItemCommand, (bool error, string message)>{- public class DeleteOrderItemCommandHandler : IRequestHandler<DeleteOrderItemCommand, (bool error, string message)>+ private readonly IGiftVoucherService _giftVoucherService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IProductService _productService;+ private readonly IShipmentService _shipmentService;++ public DeleteOrderItemCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IProductService productService,+ IGiftVoucherService giftVoucherService,+ IInventoryManageService inventoryManageService){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IProductService _productService;- private readonly IGiftVoucherService _giftVoucherService;- private readonly IInventoryManageService _inventoryManageService;-- public DeleteOrderItemCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IProductService productService,- IGiftVoucherService giftVoucherService,- IInventoryManageService inventoryManageService)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _productService = productService;- _giftVoucherService = giftVoucherService;- _inventoryManageService = inventoryManageService;- }+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _productService = productService;+ _giftVoucherService = giftVoucherService;+ _inventoryManageService = inventoryManageService;+ }++ public async Task<(bool error, string message)> Handle(DeleteOrderItemCommand request,+ CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));++ if (request.OrderItem == null)+ throw new ArgumentNullException(nameof(request.OrderItem));++ var product = await _productService.GetProductById(request.OrderItem.ProductId);+ if (product == null)+ return (true, "Product not exists.");- public async Task<(bool error, string message)> Handle(DeleteOrderItemCommand request, CancellationToken cancellationToken)+ if (request.OrderItem.OpenQty == 0+ || request.OrderItem.Status == OrderItemStatus.Close+ || request.OrderItem.OpenQty != request.OrderItem.Quantity+ )+ return (true, "You can't delete this order item.");+ if (product.IsGiftVoucher){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));-- var product = await _productService.GetProductById(request.OrderItem.ProductId);- if (product == null)- return (true, "Product not exists.");-- if (request.OrderItem.OpenQty == 0- || request.OrderItem.Status == OrderItemStatus.Close- || request.OrderItem.OpenQty != request.OrderItem.Quantity- )- {- return (true, "You can't delete this order item.");- }- if (product.IsGiftVoucher)- {- var giftVouchers = await _giftVoucherService.GetGiftVouchersByPurchasedWithOrderItemId(request.OrderItem.Id);- if(giftVouchers.Any())- return (true, "You can't delete item with gift voucher, first go to gift vouchers and delete it");- }-- var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);- foreach (var shipment in shipments)- {- if (shipment.ShipmentItems.Any(x => x.OrderItemId == request.OrderItem.Id))- {- return (true, $"This order item is in associated with shipment {shipment.ShipmentNumber}. Please delete it first.");- }- }- if ((await _giftVoucherService.GetGiftVouchersByPurchasedWithOrderItemId(request.OrderItem.Id)).Count > 0)- {- //we cannot delete an order item with associated gift vouchers- //a store owner should delete them first- return (true, "This order item has an associated gift voucher record. Please delete it first.");- }-- //add a note- await _orderService.InsertOrderNote(new OrderNote {- Note = $"Order item has been deleted - {product.Name}",- DisplayToCustomer = false,- OrderId = request.Order.Id- });-- await _inventoryManageService.AdjustReserved(product, request.OrderItem.Quantity, request.OrderItem.Attributes, request.OrderItem.WarehouseId);-- //delete item- request.Order.OrderItems.Remove(request.OrderItem);-- request.Order.OrderSubtotalExclTax -= request.OrderItem.PriceExclTax;- request.Order.OrderSubtotalInclTax -= request.OrderItem.PriceInclTax;- request.Order.OrderTax -= request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax;- request.Order.OrderTotal -= request.OrderItem.PriceInclTax;-- if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped)- {- if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))- {- request.Order.ShippingStatusId = ShippingStatus.Delivered;- }- }- //TODO- //request.Order.OrderTaxes-- await _orderService.UpdateOrder(request.Order);-- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);-- return (false, "");+ var giftVouchers =+ await _giftVoucherService.GetGiftVouchersByPurchasedWithOrderItemId(request.OrderItem.Id);+ if (giftVouchers.Any())+ return (true, "You can't delete item with gift voucher, first go to gift vouchers and delete it");}++ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);+ foreach (var shipment in shipments)+ if (shipment.ShipmentItems.Any(x => x.OrderItemId == request.OrderItem.Id))+ return (true,+ $"This order item is in associated with shipment {shipment.ShipmentNumber}. Please delete it first.");+ if ((await _giftVoucherService.GetGiftVouchersByPurchasedWithOrderItemId(request.OrderItem.Id)).Count > 0)+ //we cannot delete an order item with associated gift vouchers+ //a store owner should delete them first+ return (true, "This order item has an associated gift voucher record. Please delete it first.");++ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = $"Order item has been deleted - {product.Name}",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });++ await _inventoryManageService.AdjustReserved(product, request.OrderItem.Quantity, request.OrderItem.Attributes,+ request.OrderItem.WarehouseId);++ //delete item+ request.Order.OrderItems.Remove(request.OrderItem);++ request.Order.OrderSubtotalExclTax -= request.OrderItem.PriceExclTax;+ request.Order.OrderSubtotalInclTax -= request.OrderItem.PriceInclTax;+ request.Order.OrderTax -= request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax;+ request.Order.OrderTotal -= request.OrderItem.PriceInclTax;++ if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped)+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))+ request.Order.ShippingStatusId = ShippingStatus.Delivered;+ //TODO+ //request.Order.OrderTaxes++ await _orderService.UpdateOrder(request.Order);++ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);++ return (false, "");}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.csindex a7c8891cd..f321770f9 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs@@ -1,101 +1,96 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Domain.Orders;using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class InsertOrderItemCommandHandler : IRequestHandler<InsertOrderItemCommand, bool>{- public class InsertOrderItemCommandHandler : IRequestHandler<InsertOrderItemCommand, bool>+ private readonly IGiftVoucherService _giftVoucherService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;++ public InsertOrderItemCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IGiftVoucherService giftVoucherService,+ IInventoryManageService inventoryManageService){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IGiftVoucherService _giftVoucherService;- private readonly IInventoryManageService _inventoryManageService;-- public InsertOrderItemCommandHandler(- IMediator mediator,- IOrderService orderService,- IGiftVoucherService giftVoucherService,- IInventoryManageService inventoryManageService)- {- _mediator = mediator;- _orderService = orderService;- _giftVoucherService = giftVoucherService;- _inventoryManageService = inventoryManageService;- }+ _mediator = mediator;+ _orderService = orderService;+ _giftVoucherService = giftVoucherService;+ _inventoryManageService = inventoryManageService;+ }++ public async Task<bool> Handle(InsertOrderItemCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));++ if (request.OrderItem == null)+ throw new ArgumentNullException(nameof(request.OrderItem));++ request.Order.OrderItems.Add(request.OrderItem);+ request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax;+ request.Order.OrderSubtotalInclTax += request.OrderItem.PriceInclTax;+ request.Order.OrderTax += request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax;+ request.Order.OrderTotal += request.OrderItem.PriceInclTax;- public async Task<bool> Handle(InsertOrderItemCommand request, CancellationToken cancellationToken)+ if (request.Order.ShippingStatusId == ShippingStatus.Delivered+ && request.OrderItem.IsShipEnabled)+ request.Order.ShippingStatusId = ShippingStatus.PartiallyShipped;++ if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired+ && request.OrderItem.IsShipEnabled)+ request.Order.ShippingStatusId = ShippingStatus.Pending;++ //TODO+ //request.Order.OrderTaxes++ await _orderService.UpdateOrder(request.Order);++ //adjust inventory+ await _inventoryManageService.AdjustReserved(request.Product, -request.OrderItem.Quantity,+ request.OrderItem.Attributes, request.OrderItem.WarehouseId);++ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);++ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = "A new order item has been added",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });++ //gift vouchers+ if (!request.Product.IsGiftVoucher) return true;+ for (var i = 0; i < request.OrderItem.Quantity; i++){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));-- request.Order.OrderItems.Add(request.OrderItem);- request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax;- request.Order.OrderSubtotalInclTax += request.OrderItem.PriceInclTax;- request.Order.OrderTax += request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax;- request.Order.OrderTotal += request.OrderItem.PriceInclTax;-- if (request.Order.ShippingStatusId == ShippingStatus.Delivered- && request.OrderItem.IsShipEnabled)- {- request.Order.ShippingStatusId = ShippingStatus.PartiallyShipped;- }-- if (request.Order.ShippingStatusId == ShippingStatus.ShippingNotRequired- && request.OrderItem.IsShipEnabled)- {- request.Order.ShippingStatusId = ShippingStatus.Pending;- }-- //TODO- //request.Order.OrderTaxes-- await _orderService.UpdateOrder(request.Order);-- //adjust inventory- await _inventoryManageService.AdjustReserved(request.Product, -request.OrderItem.Quantity, request.OrderItem.Attributes, request.OrderItem.WarehouseId);-- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);-- //add a note- await _orderService.InsertOrderNote(new OrderNote- {- Note = "A new order item has been added",- DisplayToCustomer = false,- OrderId = request.Order.Id- });-- //gift vouchers- if (!request.Product.IsGiftVoucher) return true;- for (var i = 0; i < request.OrderItem.Quantity; i++)- {- var gc = new GiftVoucher- {- GiftVoucherTypeId = request.Product.GiftVoucherTypeId,- PurchasedWithOrderItem = request.OrderItem,- Amount = request.OrderItem.UnitPriceExclTax,- CurrencyCode = request.Order.CustomerCurrencyCode,- IsGiftVoucherActivated = false,- Code = _giftVoucherService.GenerateGiftVoucherCode(),-- //TODO- //RecipientName = recipientName,- //RecipientEmail = recipientEmail,- //SenderName = senderName,- //SenderEmail = senderEmail,- //Message = giftVoucherMessage,- IsRecipientNotified = false- };- await _giftVoucherService.InsertGiftVoucher(gc);- }- return true;+ var gc = new GiftVoucher {+ GiftVoucherTypeId = request.Product.GiftVoucherTypeId,+ PurchasedWithOrderItem = request.OrderItem,+ Amount = request.OrderItem.UnitPriceExclTax,+ CurrencyCode = request.Order.CustomerCurrencyCode,+ IsGiftVoucherActivated = false,+ Code = _giftVoucherService.GenerateGiftVoucherCode(),++ //TODO+ //RecipientName = recipientName,+ //RecipientEmail = recipientEmail,+ //SenderName = senderName,+ //SenderEmail = senderEmail,+ //Message = giftVoucherMessage,+ IsRecipientNotified = false+ };+ await _giftVoucherService.InsertGiftVoucher(gc);}++ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.csindex e3b1abb09..7780ff199 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs@@ -5,47 +5,46 @@ using Grand.Business.Core.Interfaces.Checkout.Payments;using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class MarkAsAuthorizedCommandHandler : IRequestHandler<MarkAsAuthorizedCommand, bool>{- public class MarkAsAuthorizedCommandHandler : IRequestHandler<MarkAsAuthorizedCommand, bool>+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public MarkAsAuthorizedCommandHandler(+ IOrderService orderService,+ IPaymentTransactionService paymentTransactionService,+ IMediator mediator){- private readonly IOrderService _orderService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IMediator _mediator;-- public MarkAsAuthorizedCommandHandler(- IOrderService orderService,- IPaymentTransactionService paymentTransactionService,- IMediator mediator)- {- _orderService = orderService;- _paymentTransactionService = paymentTransactionService;- _mediator = mediator;- }-- public async Task<bool> Handle(MarkAsAuthorizedCommand request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));-- paymentTransaction.TransactionStatus = TransactionStatus.Authorized;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);-- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));-- order.PaymentStatusId = PaymentStatus.Authorized;- await _orderService.UpdateOrder(order);-- //event notification- await _mediator.Publish(new PaymentTransactionMarkAsAuthorizedEvent(paymentTransaction), cancellationToken);-- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);-- return true;- }+ _orderService = orderService;+ _paymentTransactionService = paymentTransactionService;+ _mediator = mediator;+ }++ public async Task<bool> Handle(MarkAsAuthorizedCommand request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));++ paymentTransaction.TransactionStatus = TransactionStatus.Authorized;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);++ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));++ order.PaymentStatusId = PaymentStatus.Authorized;+ await _orderService.UpdateOrder(order);++ //event notification+ await _mediator.Publish(new PaymentTransactionMarkAsAuthorizedEvent(paymentTransaction), cancellationToken);++ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);++ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.csindex bc5c8e1a9..f4312471e 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs@@ -7,62 +7,59 @@ using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders-{- public class MarkAsPaidCommandHandler : IRequestHandler<MarkAsPaidCommand, bool>- {- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IPaymentTransactionService _paymentTransactionService;+namespace Grand.Business.Checkout.Commands.Handlers.Orders;- public MarkAsPaidCommandHandler(- IMediator mediator,- IOrderService orderService,- IPaymentTransactionService paymentTransactionService)- {- _mediator = mediator;- _orderService = orderService;- _paymentTransactionService = paymentTransactionService;- }+public class MarkAsPaidCommandHandler : IRequestHandler<MarkAsPaidCommand, bool>+{+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentTransactionService _paymentTransactionService;- public async Task<bool> Handle(MarkAsPaidCommand request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ public MarkAsPaidCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IPaymentTransactionService paymentTransactionService)+ {+ _mediator = mediator;+ _orderService = orderService;+ _paymentTransactionService = paymentTransactionService;+ }- var canMarkOrderAsPaid = await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }, cancellationToken);- if (!canMarkOrderAsPaid)- throw new GrandException("You can't mark this Payment Transaction as paid");+ public async Task<bool> Handle(MarkAsPaidCommand request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- paymentTransaction.TransactionStatus = TransactionStatus.Paid;- paymentTransaction.PaidAmount = paymentTransaction.TransactionAmount;+ var canMarkOrderAsPaid =+ await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction },+ cancellationToken);+ if (!canMarkOrderAsPaid)+ throw new GrandException("You can't mark this Payment Transaction as paid");- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ paymentTransaction.TransactionStatus = TransactionStatus.Paid;+ paymentTransaction.PaidAmount = paymentTransaction.TransactionAmount;- order.PaidAmount = paymentTransaction.PaidAmount;- order.PaymentStatusId = PaymentStatus.Paid;- order.PaidDateUtc = DateTime.UtcNow;- await _orderService.UpdateOrder(order);+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));- //add a note- await _orderService.InsertOrderNote(new OrderNote- {- Note = "Order has been marked as paid",- DisplayToCustomer = false,- OrderId = order.Id+ order.PaidAmount = paymentTransaction.PaidAmount;+ order.PaymentStatusId = PaymentStatus.Paid;+ order.PaidDateUtc = DateTime.UtcNow;+ await _orderService.UpdateOrder(order);- });+ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = "Order has been marked as paid",+ DisplayToCustomer = false,+ OrderId = order.Id+ });- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- if (order.PaymentStatusId == PaymentStatus.Paid)- {- await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);- }- return true;- }+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ if (order.PaymentStatusId == PaymentStatus.Paid)+ await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.csindex 96aa3d757..d26f90ba3 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MaxOrderNumberCommandHandler.cs@@ -1,31 +1,30 @@-using Grand.Data;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Data;using Grand.Domain.Orders;-using Grand.Business.Core.Commands.Checkout.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class MaxOrderNumberCommandHandler : IRequestHandler<MaxOrderNumberCommand, int?>{- public class MaxOrderNumberCommandHandler : IRequestHandler<MaxOrderNumberCommand, int?>- {- private readonly IRepository<Order> _orderRepository;+ private readonly IRepository<Order> _orderRepository;- public MaxOrderNumberCommandHandler(IRepository<Order> orderRepository)- {- _orderRepository = orderRepository;- }+ public MaxOrderNumberCommandHandler(IRepository<Order> orderRepository)+ {+ _orderRepository = orderRepository;+ }- public async Task<int?> Handle(MaxOrderNumberCommand request, CancellationToken cancellationToken)- {- var count = _orderRepository.Table.Count();- if (count == 0 && !request.OrderNumber.HasValue)- return null;+ public async Task<int?> Handle(MaxOrderNumberCommand request, CancellationToken cancellationToken)+ {+ var count = _orderRepository.Table.Count();+ if (count == 0 && !request.OrderNumber.HasValue)+ return null;- var max = count > 0 ? _orderRepository.Table.Max(x => x.OrderNumber) : 0;- if (!request.OrderNumber.HasValue) return max;- if (request.OrderNumber.Value <= max) return max;- await _orderRepository.InsertAsync(new Order { OrderNumber = request.OrderNumber.Value, Deleted = true });- max = request.OrderNumber.Value;- return max;- }+ var max = count > 0 ? _orderRepository.Table.Max(x => x.OrderNumber) : 0;+ if (!request.OrderNumber.HasValue) return max;+ if (request.OrderNumber.Value <= max) return max;+ await _orderRepository.InsertAsync(new Order { OrderNumber = request.OrderNumber.Value, Deleted = true });+ max = request.OrderNumber.Value;+ return max;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.csindex d1baf4f81..dba44d69f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs@@ -6,150 +6,149 @@ using Grand.Business.Core.Interfaces.Messages;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class OrderStatusCommandHandler : IRequestHandler<SetOrderStatusCommand, bool>{- public class OrderStatusCommandHandler : IRequestHandler<SetOrderStatusCommand, bool>+ private readonly ICustomerService _customerService;+ private readonly LoyaltyPointsSettings _loyaltyPointsSettings;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly OrderSettings _orderSettings;+ private readonly IPdfService _pdfService;+ private readonly IVendorService _vendorService;++ public OrderStatusCommandHandler(+ IOrderService orderService,+ ICustomerService customerService,+ IPdfService pdfService,+ IMessageProviderService messageProviderService,+ IVendorService vendorService,+ IMediator mediator,+ OrderSettings orderSettings,+ LoyaltyPointsSettings loyaltyPointsSettings){- private readonly IOrderService _orderService;- private readonly ICustomerService _customerService;- private readonly IPdfService _pdfService;- private readonly IMessageProviderService _messageProviderService;- private readonly IVendorService _vendorService;- private readonly IMediator _mediator;- private readonly OrderSettings _orderSettings;- private readonly LoyaltyPointsSettings _loyaltyPointsSettings;-- public OrderStatusCommandHandler(- IOrderService orderService,- ICustomerService customerService,- IPdfService pdfService,- IMessageProviderService messageProviderService,- IVendorService vendorService,- IMediator mediator,- OrderSettings orderSettings,- LoyaltyPointsSettings loyaltyPointsSettings)+ _orderService = orderService;+ _customerService = customerService;+ _pdfService = pdfService;+ _messageProviderService = messageProviderService;+ _vendorService = vendorService;+ _mediator = mediator;+ _orderSettings = orderSettings;+ _loyaltyPointsSettings = loyaltyPointsSettings;+ }++ public async Task<bool> Handle(SetOrderStatusCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));++ var prevOrderStatus = request.Order.OrderStatusId;+ if (prevOrderStatus == (int)request.Os)+ return false;++ //set and save new order status+ request.Order.OrderStatusId = (int)request.Os;+ await _orderService.UpdateOrder(request.Order);++ //order notes, notifications+ await _orderService.InsertOrderNote(new OrderNote {+ Note = $"Order status has been changed to {request.Os.ToString()}",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });++ var customer = await _customerService.GetCustomerById(request.Order.CustomerId);++ if (prevOrderStatus != (int)OrderStatusSystem.Complete &&+ request.Os == OrderStatusSystem.Complete+ && request.NotifyCustomer){- _orderService = orderService;- _customerService = customerService;- _pdfService = pdfService;- _messageProviderService = messageProviderService;- _vendorService = vendorService;- _mediator = mediator;- _orderSettings = orderSettings;- _loyaltyPointsSettings = loyaltyPointsSettings;+ //notification++ var orderCompletedAttachmentFilePath = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail+ ? await _pdfService.PrintOrderToPdf(request.Order, "")+ : null;+ var orderCompletedAttachmentFileName =+ _orderSettings.AttachPdfInvoiceToOrderCompletedEmail ? "order.pdf" : null;++ var orderCompletedAttachments = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail &&+ _orderSettings.AttachPdfInvoiceToBinary+ ? [+ await _pdfService.SaveOrderToBinary(request.Order, "")+ ]+ : new List<string>();++ await _messageProviderService+ .SendOrderCompletedCustomerMessage(request.Order, customer, request.Order.CustomerLanguageId,+ orderCompletedAttachmentFilePath,+ orderCompletedAttachmentFileName, orderCompletedAttachments);}- public async Task<bool> Handle(SetOrderStatusCommand request, CancellationToken cancellationToken)+ if (prevOrderStatus != (int)OrderStatusSystem.Cancelled &&+ request.Os == OrderStatusSystem.Cancelled+ && request.NotifyCustomer){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- var prevOrderStatus = request.Order.OrderStatusId;- if (prevOrderStatus == (int)request.Os)- return false;-- //set and save new order status- request.Order.OrderStatusId = (int)request.Os;- await _orderService.UpdateOrder(request.Order);-- //order notes, notifications- await _orderService.InsertOrderNote(new OrderNote {- Note = $"Order status has been changed to {request.Os.ToString()}",- DisplayToCustomer = false,- OrderId = request.Order.Id- });-- var customer = await _customerService.GetCustomerById(request.Order.CustomerId);-- if (prevOrderStatus != (int)OrderStatusSystem.Complete &&- request.Os == OrderStatusSystem.Complete- && request.NotifyCustomer)- {- //notification-- var orderCompletedAttachmentFilePath = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail ?- await _pdfService.PrintOrderToPdf(request.Order, "") : null;- var orderCompletedAttachmentFileName = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail ?- "order.pdf" : null;-- var orderCompletedAttachments = _orderSettings.AttachPdfInvoiceToOrderCompletedEmail && _orderSettings.AttachPdfInvoiceToBinary ? [- await _pdfService.SaveOrderToBinary(request.Order, "")- ]- : new List<string>();-- await _messageProviderService- .SendOrderCompletedCustomerMessage(request.Order, customer, request.Order.CustomerLanguageId, orderCompletedAttachmentFilePath,- orderCompletedAttachmentFileName, orderCompletedAttachments);- }-- if (prevOrderStatus != (int)OrderStatusSystem.Cancelled &&- request.Os == OrderStatusSystem.Cancelled- && request.NotifyCustomer)- {- //notification customer- await _messageProviderService.SendOrderCancelledCustomerMessage(request.Order, customer, request.Order.CustomerLanguageId);-- //notification for vendor- await VendorNotification(request.Order);- }-- if (prevOrderStatus != (int)OrderStatusSystem.Cancelled &&- request.Os == OrderStatusSystem.Cancelled- && request.NotifyStoreOwner)- {- //notification store owner- var orderCancelledStoreOwnerNotificationQueuedEmailId = await _messageProviderService.SendOrderCancelledStoreOwnerMessage(request.Order, customer, request.Order.CustomerLanguageId);- if (orderCancelledStoreOwnerNotificationQueuedEmailId > 0)- {- await _orderService.InsertOrderNote(new OrderNote {- Note = "\"Order cancelled\" by customer.",- DisplayToCustomer = true,- OrderId = request.Order.Id- });- }- //notification for vendor- await VendorNotification(request.Order);- }-- //loyalty points- if (_loyaltyPointsSettings.PointsForPurchases_Awarded == request.Order.OrderStatusId)- {- await _mediator.Send(new AwardLoyaltyPointsCommand { Order = request.Order }, cancellationToken);- }- if (_loyaltyPointsSettings.ReduceLoyaltyPointsAfterCancelOrder && request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)- {- await _mediator.Send(new ReduceLoyaltyPointsCommand { Order = request.Order }, cancellationToken);- }-- //gift vouchers activation- if (_orderSettings.GiftVouchers_Activated_OrderStatusId > 0 &&- _orderSettings.GiftVouchers_Activated_OrderStatusId == request.Order.OrderStatusId)- {- await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = true }, cancellationToken);- }-- //gift vouchers deactivation- if (_orderSettings.DeactivateGiftVouchersAfterCancelOrder &&- request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)- {- await _mediator.Send(new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = false }, cancellationToken);- }-- return true;+ //notification customer+ await _messageProviderService.SendOrderCancelledCustomerMessage(request.Order, customer,+ request.Order.CustomerLanguageId);++ //notification for vendor+ await VendorNotification(request.Order);}- private async Task VendorNotification(Order order)+ if (prevOrderStatus != (int)OrderStatusSystem.Cancelled &&+ request.Os == OrderStatusSystem.Cancelled+ && request.NotifyStoreOwner){+ //notification store owner+ var orderCancelledStoreOwnerNotificationQueuedEmailId =+ await _messageProviderService.SendOrderCancelledStoreOwnerMessage(request.Order, customer,+ request.Order.CustomerLanguageId);+ if (orderCancelledStoreOwnerNotificationQueuedEmailId > 0)+ await _orderService.InsertOrderNote(new OrderNote {+ Note = "\"Order cancelled\" by customer.",+ DisplayToCustomer = true,+ OrderId = request.Order.Id+ });//notification for vendor- foreach (var orderItem in order.OrderItems)- {- if (string.IsNullOrEmpty(orderItem.VendorId)) continue;- var vendor = await _vendorService.GetVendorById(orderItem.VendorId);- if (vendor is { Deleted: false, Active: true })- {- await _messageProviderService.SendOrderCancelledVendorMessage(order, vendor, order.CustomerLanguageId);- }- }+ await VendorNotification(request.Order);+ }++ //loyalty points+ if (_loyaltyPointsSettings.PointsForPurchases_Awarded == request.Order.OrderStatusId)+ await _mediator.Send(new AwardLoyaltyPointsCommand { Order = request.Order }, cancellationToken);+ if (_loyaltyPointsSettings.ReduceLoyaltyPointsAfterCancelOrder &&+ request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)+ await _mediator.Send(new ReduceLoyaltyPointsCommand { Order = request.Order }, cancellationToken);++ //gift vouchers activation+ if (_orderSettings.GiftVouchers_Activated_OrderStatusId > 0 &&+ _orderSettings.GiftVouchers_Activated_OrderStatusId == request.Order.OrderStatusId)+ await _mediator.Send(+ new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = true },+ cancellationToken);++ //gift vouchers deactivation+ if (_orderSettings.DeactivateGiftVouchersAfterCancelOrder &&+ request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)+ await _mediator.Send(+ new ActivatedValueForPurchasedGiftVouchersCommand { Order = request.Order, Activate = false },+ cancellationToken);++ return true;+ }++ private async Task VendorNotification(Order order)+ {+ //notification for vendor+ foreach (var orderItem in order.OrderItems)+ {+ if (string.IsNullOrEmpty(orderItem.VendorId)) continue;+ var vendor = await _vendorService.GetVendorById(orderItem.VendorId);+ if (vendor is { Deleted: false, Active: true })+ await _messageProviderService.SendOrderCancelledVendorMessage(order, vendor, order.CustomerLanguageId);}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.csindex da85c5cd1..148780b79 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs@@ -6,59 +6,61 @@ using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class PartiallyPaidOfflineCommandHandler : IRequestHandler<PartiallyPaidOfflineCommand, bool>{- public class PartiallyPaidOfflineCommandHandler : IRequestHandler<PartiallyPaidOfflineCommand, bool>- {- private readonly IOrderService _orderService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IMediator _mediator;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentTransactionService _paymentTransactionService;- public PartiallyPaidOfflineCommandHandler(- IOrderService orderService,- IPaymentTransactionService paymentTransactionService,- IMediator mediator)- {- _orderService = orderService;- _paymentTransactionService = paymentTransactionService;- _mediator = mediator;- _orderService = orderService;- }+ public PartiallyPaidOfflineCommandHandler(+ IOrderService orderService,+ IPaymentTransactionService paymentTransactionService,+ IMediator mediator)+ {+ _orderService = orderService;+ _paymentTransactionService = paymentTransactionService;+ _mediator = mediator;+ _orderService = orderService;+ }- public async Task<bool> Handle(PartiallyPaidOfflineCommand command, CancellationToken cancellationToken)- {- var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ public async Task<bool> Handle(PartiallyPaidOfflineCommand command, CancellationToken cancellationToken)+ {+ var paymentTransaction = command.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(command.PaymentTransaction));- var amountToPaid = command.AmountToPaid;+ var amountToPaid = command.AmountToPaid;- var canPartiallyPaidOffline = await _mediator.Send(new CanPartiallyPaidOfflineQuery { PaymentTransaction = paymentTransaction, AmountToPaid = amountToPaid }, cancellationToken);- if (!canPartiallyPaidOffline)- throw new GrandException("You can't partially paid (offline) this transaction");+ var canPartiallyPaidOffline =+ await _mediator.Send(+ new CanPartiallyPaidOfflineQuery+ { PaymentTransaction = paymentTransaction, AmountToPaid = amountToPaid }, cancellationToken);+ if (!canPartiallyPaidOffline)+ throw new GrandException("You can't partially paid (offline) this transaction");- paymentTransaction.PaidAmount += amountToPaid;- paymentTransaction.TransactionStatus = paymentTransaction.PaidAmount >= paymentTransaction.TransactionAmount ? TransactionStatus.Paid : TransactionStatus.PartialPaid;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);+ paymentTransaction.PaidAmount += amountToPaid;+ paymentTransaction.TransactionStatus = paymentTransaction.PaidAmount >= paymentTransaction.TransactionAmount+ ? TransactionStatus.Paid+ : TransactionStatus.PartialPaid;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));- //update order info- order.PaidAmount += amountToPaid;- order.PaymentStatusId = order.PaidAmount >= order.OrderTotal ? PaymentStatus.Paid : PaymentStatus.PartiallyPaid;- await _orderService.UpdateOrder(order);+ //update order info+ order.PaidAmount += amountToPaid;+ order.PaymentStatusId = order.PaidAmount >= order.OrderTotal ? PaymentStatus.Paid : PaymentStatus.PartiallyPaid;+ await _orderService.UpdateOrder(order);- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- if (order.PaymentStatusId == PaymentStatus.Paid)- {- await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);- }+ if (order.PaymentStatusId == PaymentStatus.Paid)+ await _mediator.Send(new ProcessOrderPaidCommand { Order = order }, cancellationToken);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.csindex 98ca1201c..242db8b52 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs@@ -2,118 +2,127 @@using Grand.Business.Core.Events.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;+using Grand.Business.Core.Interfaces.Messages;using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Business.Core.Utilities.Checkout;-using Grand.Business.Core.Interfaces.Messages;using Grand.Domain.Localization;+using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;using Microsoft.Extensions.Logging;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class PartiallyRefundCommandHandler : IRequestHandler<PartiallyRefundCommand, IList<string>>{- public class PartiallyRefundCommandHandler : IRequestHandler<PartiallyRefundCommand, IList<string>>+ private readonly LanguageSettings _languageSettings;+ private readonly ILogger<PartiallyRefundCommandHandler> _logger;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly IPaymentService _paymentService;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public PartiallyRefundCommandHandler(+ IPaymentService paymentService,+ IPaymentTransactionService paymentTransactionService,+ IMediator mediator,+ IMessageProviderService messageProviderService,+ ILogger<PartiallyRefundCommandHandler> logger,+ IOrderService orderService,+ LanguageSettings languageSettings){- private readonly IPaymentService _paymentService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IMediator _mediator;- private readonly IMessageProviderService _messageProviderService;- private readonly ILogger<PartiallyRefundCommandHandler> _logger;- private readonly IOrderService _orderService;- private readonly LanguageSettings _languageSettings;-- public PartiallyRefundCommandHandler(- IPaymentService paymentService,- IPaymentTransactionService paymentTransactionService,- IMediator mediator,- IMessageProviderService messageProviderService,- ILogger<PartiallyRefundCommandHandler> logger,- IOrderService orderService,- LanguageSettings languageSettings)- {- _paymentService = paymentService;- _paymentTransactionService = paymentTransactionService;- _orderService = orderService;- _mediator = mediator;- _messageProviderService = messageProviderService;- _logger = logger;- _languageSettings = languageSettings;- }+ _paymentService = paymentService;+ _paymentTransactionService = paymentTransactionService;+ _orderService = orderService;+ _mediator = mediator;+ _messageProviderService = messageProviderService;+ _logger = logger;+ _languageSettings = languageSettings;+ }- public async Task<IList<string>> Handle(PartiallyRefundCommand command, CancellationToken cancellationToken)+ public async Task<IList<string>> Handle(PartiallyRefundCommand command, CancellationToken cancellationToken)+ {+ var paymentTransaction = command.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(command.PaymentTransaction));++ var amountToRefund = command.AmountToRefund;++ var canPartiallyRefund =+ await _mediator.Send(+ new CanPartiallyRefundQuery+ { AmountToRefund = amountToRefund, PaymentTransaction = paymentTransaction }, cancellationToken);+ if (!canPartiallyRefund)+ throw new GrandException("Cannot do partial refund for order.");++ var request = new RefundPaymentRequest();+ RefundPaymentResult result = null;+ try{- var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));-- var amountToRefund = command.AmountToRefund;+ request.PaymentTransaction = paymentTransaction;+ request.AmountToRefund = amountToRefund;+ request.IsPartialRefund = true;- var canPartiallyRefund = await _mediator.Send(new CanPartiallyRefundQuery { AmountToRefund = amountToRefund, PaymentTransaction = paymentTransaction }, cancellationToken);- if (!canPartiallyRefund)- throw new GrandException("Cannot do partial refund for order.");+ result = await _paymentService.Refund(request);- var request = new RefundPaymentRequest();- RefundPaymentResult result = null;- try+ if (result.Success){- request.PaymentTransaction = paymentTransaction;- request.AmountToRefund = amountToRefund;- request.IsPartialRefund = true;+ paymentTransaction = await _paymentTransactionService.GetById(paymentTransaction.Id);+ paymentTransaction.TransactionStatus = result.NewTransactionStatus;+ paymentTransaction.RefundedAmount += amountToRefund;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- result = await _paymentService.Refund(request);+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));- if (result.Success)+ //total amount refunded+ if (paymentTransaction.TransactionStatus == TransactionStatus.Refunded){- paymentTransaction = await _paymentTransactionService.GetById(paymentTransaction.Id);- paymentTransaction.TransactionStatus = result.NewTransactionStatus;- paymentTransaction.RefundedAmount += amountToRefund;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);-- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));-- //total amount refunded- if (paymentTransaction.TransactionStatus == Domain.Payments.TransactionStatus.Refunded)- {- var totalAmountRefunded = order.RefundedAmount + amountToRefund;-- order.RefundedAmount = totalAmountRefunded;- order.PaymentStatusId = order.RefundedAmount == order.OrderTotal ? Domain.Payments.PaymentStatus.Refunded : Domain.Payments.PaymentStatus.PartiallyRefunded;- await _orderService.UpdateOrder(order);+ var totalAmountRefunded = order.RefundedAmount + amountToRefund;- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ order.RefundedAmount = totalAmountRefunded;+ order.PaymentStatusId = order.RefundedAmount == order.OrderTotal+ ? PaymentStatus.Refunded+ : PaymentStatus.PartiallyRefunded;+ await _orderService.UpdateOrder(order);- //notifications- await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId);+ //notifications+ await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund,+ _languageSettings.DefaultAdminLanguageId);- }- //raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken);+ await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund,+ order.CustomerLanguageId);}- }- catch (Exception exc)- {- result ??= new RefundPaymentResult();- result.AddError($"Error: {exc.Message}. Full exception: {exc}");- }- //process errors- var error = "";- for (var i = 0; i < result.Errors.Count; i++)- {- error += $"Error {i}: {result.Errors[i]}";- if (i != result.Errors.Count - 1)- error += ". ";+ //raise event+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund),+ cancellationToken);}+ }+ catch (Exception exc)+ {+ result ??= new RefundPaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");+ }- if (string.IsNullOrEmpty(error)) return result.Errors;-- _logger.LogError("Error refunding order #{PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);- return result.Errors;+ //process errors+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++)+ {+ error += $"Error {i}: {result.Errors[i]}";+ if (i != result.Errors.Count - 1)+ error += ". ";}++ if (string.IsNullOrEmpty(error)) return result.Errors;++ _logger.LogError("Error refunding order #{PaymentTransactionOrderCode}. Error: {Error}",+ paymentTransaction.OrderCode, error);+ return result.Errors;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.csindex 4f17920b7..9e2c844a0 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs@@ -2,78 +2,87 @@using Grand.Business.Core.Events.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Localization;using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class PartiallyRefundOfflineCommandHandler : IRequestHandler<PartiallyRefundOfflineCommand, bool>{- public class PartiallyRefundOfflineCommandHandler : IRequestHandler<PartiallyRefundOfflineCommand, bool>- {- private readonly IOrderService _orderService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IMediator _mediator;- private readonly IMessageProviderService _messageProviderService;- private readonly LanguageSettings _languageSettings;+ private readonly LanguageSettings _languageSettings;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly IPaymentTransactionService _paymentTransactionService;- public PartiallyRefundOfflineCommandHandler(- IOrderService orderService,- IPaymentTransactionService paymentTransactionService,- IMediator mediator,- IMessageProviderService messageProviderService,- LanguageSettings languageSettings)- {- _orderService = orderService;- _paymentTransactionService = paymentTransactionService;- _mediator = mediator;- _messageProviderService = messageProviderService;- _languageSettings = languageSettings;- _orderService = orderService;- }+ public PartiallyRefundOfflineCommandHandler(+ IOrderService orderService,+ IPaymentTransactionService paymentTransactionService,+ IMediator mediator,+ IMessageProviderService messageProviderService,+ LanguageSettings languageSettings)+ {+ _orderService = orderService;+ _paymentTransactionService = paymentTransactionService;+ _mediator = mediator;+ _messageProviderService = messageProviderService;+ _languageSettings = languageSettings;+ _orderService = orderService;+ }- public async Task<bool> Handle(PartiallyRefundOfflineCommand command, CancellationToken cancellationToken)- {- var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ public async Task<bool> Handle(PartiallyRefundOfflineCommand command, CancellationToken cancellationToken)+ {+ var paymentTransaction = command.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(command.PaymentTransaction));- var amountToRefund = command.AmountToRefund;+ var amountToRefund = command.AmountToRefund;- var canPartiallyRefundOffline = await _mediator.Send(new CanPartiallyRefundOfflineQuery { PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund }, cancellationToken);- if (!canPartiallyRefundOffline)- throw new GrandException("You can't partially refund (offline) this order");+ var canPartiallyRefundOffline =+ await _mediator.Send(+ new CanPartiallyRefundOfflineQuery+ { PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund }, cancellationToken);+ if (!canPartiallyRefundOffline)+ throw new GrandException("You can't partially refund (offline) this order");- paymentTransaction.RefundedAmount += amountToRefund;- paymentTransaction.TransactionStatus = paymentTransaction.RefundedAmount >= paymentTransaction.TransactionAmount ? TransactionStatus.Refunded : TransactionStatus.PartiallyRefunded;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);+ paymentTransaction.RefundedAmount += amountToRefund;+ paymentTransaction.TransactionStatus = paymentTransaction.RefundedAmount >= paymentTransaction.TransactionAmount+ ? TransactionStatus.Refunded+ : TransactionStatus.PartiallyRefunded;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));- //total amount refunded- var totalAmountRefunded = order.RefundedAmount + amountToRefund;+ //total amount refunded+ var totalAmountRefunded = order.RefundedAmount + amountToRefund;- //update order info- order.RefundedAmount = totalAmountRefunded;- order.PaymentStatusId = order.RefundedAmount >= order.OrderTotal ? PaymentStatus.Refunded : PaymentStatus.PartiallyRefunded;- await _orderService.UpdateOrder(order);+ //update order info+ order.RefundedAmount = totalAmountRefunded;+ order.PaymentStatusId = order.RefundedAmount >= order.OrderTotal+ ? PaymentStatus.Refunded+ : PaymentStatus.PartiallyRefunded;+ await _orderService.UpdateOrder(order);- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- //notifications- _ = await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId);+ //notifications+ _ = await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund,+ _languageSettings.DefaultAdminLanguageId);- _ = await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId);+ _ = await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund,+ order.CustomerLanguageId);- //raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken);- return true;- }+ //raise event+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund),+ cancellationToken);+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.csindex 30a1ed183..35cc681a1 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs@@ -15,7 +15,6 @@ using Grand.Business.Core.Interfaces.Common.Pdf;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.Messages;using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Business.Core.Utilities.Catalog;using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Catalog;using Grand.Domain.Common;@@ -33,1077 +32,1092 @@ using MediatR;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, PlaceOrderResult>{- public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, PlaceOrderResult>+ private readonly IAffiliateService _affiliateService;+ private readonly IAuctionService _auctionService;+ private readonly ICheckoutAttributeFormatter _checkoutAttributeFormatter;+ private readonly ICountryService _countryService;+ private readonly ICurrencyService _currencyService;+ private readonly ICustomerService _customerService;+ private readonly IDiscountService _discountService;+ private readonly IGiftVoucherService _giftVoucherService;+ private readonly IGroupService _groupService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly ILanguageService _languageService;+ private readonly ILogger<PlaceOrderCommandHandler> _logger;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly OrderSettings _orderSettings;+ private readonly IOrderCalculationService _orderTotalCalculationService;+ private readonly IPaymentService _paymentService;+ private readonly PaymentSettings _paymentSettings;+ private readonly IPaymentTransactionService _paymentTransactionService;+ private readonly IPricingService _pricingService;+ private readonly IProductAttributeFormatter _productAttributeFormatter;+ private readonly IProductReservationService _productReservationService;+ private readonly IProductService _productService;+ private readonly ISalesEmployeeService _salesEmployeeService;+ private readonly IServiceScopeFactory _serviceScopeFactory;+ private readonly ShippingSettings _shippingSettings;+ private readonly ShoppingCartSettings _shoppingCartSettings;+ private readonly IShoppingCartValidator _shoppingCartValidator;+ private readonly ITaxService _taxService;+ private readonly TaxSettings _taxSettings;+ private readonly IVendorService _vendorService;+ private readonly IWorkContext _workContext;++ public PlaceOrderCommandHandler(+ IOrderService orderService,+ ILanguageService languageService,+ IProductService productService,+ IInventoryManageService inventoryManageService,+ IPaymentService paymentService,+ IPaymentTransactionService paymentTransactionService,+ ILogger<PlaceOrderCommandHandler> logger,+ IOrderCalculationService orderTotalCalculationService,+ IPricingService priceCalculationService,+ IProductAttributeFormatter productAttributeFormatter,+ IGiftVoucherService giftVoucherService,+ ICheckoutAttributeFormatter checkoutAttributeFormatter,+ ITaxService taxService,+ ICustomerService customerService,+ IDiscountService discountService,+ IWorkContext workContext,+ IGroupService groupService,+ IMessageProviderService messageProviderService,+ IVendorService vendorService,+ ISalesEmployeeService salesEmployeeService,+ ICurrencyService currencyService,+ IAffiliateService affiliateService,+ IMediator mediator,+ IProductReservationService productReservationService,+ IAuctionService auctionService,+ ICountryService countryService,+ IShoppingCartValidator shoppingCartValidator,+ IServiceScopeFactory serviceScopeFactory,+ ShippingSettings shippingSettings,+ ShoppingCartSettings shoppingCartSettings,+ PaymentSettings paymentSettings,+ OrderSettings orderSettings,+ TaxSettings taxSettings){- private readonly IOrderService _orderService;- private readonly ILanguageService _languageService;- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;- private readonly IPaymentService _paymentService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly ILogger<PlaceOrderCommandHandler> _logger;- private readonly IOrderCalculationService _orderTotalCalculationService;- private readonly IPricingService _pricingService;- private readonly IProductAttributeFormatter _productAttributeFormatter;- private readonly IGiftVoucherService _giftVoucherService;- private readonly ICheckoutAttributeFormatter _checkoutAttributeFormatter;- private readonly ITaxService _taxService;- private readonly ICustomerService _customerService;- private readonly IDiscountService _discountService;- private readonly IWorkContext _workContext;- private readonly IGroupService _groupService;- private readonly IMessageProviderService _messageProviderService;- private readonly IVendorService _vendorService;- private readonly ISalesEmployeeService _salesEmployeeService;- private readonly ICurrencyService _currencyService;- private readonly IAffiliateService _affiliateService;- private readonly IMediator _mediator;- private readonly IProductReservationService _productReservationService;- private readonly IAuctionService _auctionService;- private readonly ICountryService _countryService;- private readonly IShoppingCartValidator _shoppingCartValidator;- private readonly IServiceScopeFactory _serviceScopeFactory;- private readonly ShippingSettings _shippingSettings;- private readonly ShoppingCartSettings _shoppingCartSettings;- private readonly PaymentSettings _paymentSettings;- private readonly OrderSettings _orderSettings;- private readonly TaxSettings _taxSettings;-- public PlaceOrderCommandHandler(- IOrderService orderService,- ILanguageService languageService,- IProductService productService,- IInventoryManageService inventoryManageService,- IPaymentService paymentService,- IPaymentTransactionService paymentTransactionService,- ILogger<PlaceOrderCommandHandler> logger,- IOrderCalculationService orderTotalCalculationService,- IPricingService priceCalculationService,- IProductAttributeFormatter productAttributeFormatter,- IGiftVoucherService giftVoucherService,- ICheckoutAttributeFormatter checkoutAttributeFormatter,- ITaxService taxService,- ICustomerService customerService,- IDiscountService discountService,- IWorkContext workContext,- IGroupService groupService,- IMessageProviderService messageProviderService,- IVendorService vendorService,- ISalesEmployeeService salesEmployeeService,- ICurrencyService currencyService,- IAffiliateService affiliateService,- IMediator mediator,- IProductReservationService productReservationService,- IAuctionService auctionService,- ICountryService countryService,- IShoppingCartValidator shoppingCartValidator,- IServiceScopeFactory serviceScopeFactory,- ShippingSettings shippingSettings,- ShoppingCartSettings shoppingCartSettings,- PaymentSettings paymentSettings,- OrderSettings orderSettings,- TaxSettings taxSettings)- {- _orderService = orderService;- _languageService = languageService;- _productService = productService;- _inventoryManageService = inventoryManageService;- _paymentService = paymentService;- _paymentTransactionService = paymentTransactionService;- _logger = logger;- _orderTotalCalculationService = orderTotalCalculationService;- _pricingService = priceCalculationService;- _productAttributeFormatter = productAttributeFormatter;- _giftVoucherService = giftVoucherService;- _checkoutAttributeFormatter = checkoutAttributeFormatter;- _taxService = taxService;- _customerService = customerService;- _groupService = groupService;- _discountService = discountService;- _workContext = workContext;- _messageProviderService = messageProviderService;- _vendorService = vendorService;- _salesEmployeeService = salesEmployeeService;- _currencyService = currencyService;- _affiliateService = affiliateService;- _mediator = mediator;- _productReservationService = productReservationService;- _auctionService = auctionService;- _countryService = countryService;- _shoppingCartValidator = shoppingCartValidator;- _serviceScopeFactory = serviceScopeFactory;- _shippingSettings = shippingSettings;- _shoppingCartSettings = shoppingCartSettings;- _paymentSettings = paymentSettings;- _orderSettings = orderSettings;- _taxSettings = taxSettings;- }+ _orderService = orderService;+ _languageService = languageService;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ _paymentService = paymentService;+ _paymentTransactionService = paymentTransactionService;+ _logger = logger;+ _orderTotalCalculationService = orderTotalCalculationService;+ _pricingService = priceCalculationService;+ _productAttributeFormatter = productAttributeFormatter;+ _giftVoucherService = giftVoucherService;+ _checkoutAttributeFormatter = checkoutAttributeFormatter;+ _taxService = taxService;+ _customerService = customerService;+ _groupService = groupService;+ _discountService = discountService;+ _workContext = workContext;+ _messageProviderService = messageProviderService;+ _vendorService = vendorService;+ _salesEmployeeService = salesEmployeeService;+ _currencyService = currencyService;+ _affiliateService = affiliateService;+ _mediator = mediator;+ _productReservationService = productReservationService;+ _auctionService = auctionService;+ _countryService = countryService;+ _shoppingCartValidator = shoppingCartValidator;+ _serviceScopeFactory = serviceScopeFactory;+ _shippingSettings = shippingSettings;+ _shoppingCartSettings = shoppingCartSettings;+ _paymentSettings = paymentSettings;+ _orderSettings = orderSettings;+ _taxSettings = taxSettings;+ }- public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, CancellationToken cancellationToken)+ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, CancellationToken cancellationToken)+ {+ var result = new PlaceOrderResult();+ try{- var result = new PlaceOrderResult();- try- {- //prepare order details- var details = await PreparePlaceOrderDetails();+ //prepare order details+ var details = await PreparePlaceOrderDetails();- //event notification- await _mediator.PlaceOrderDetailsEvent(result, details);+ //event notification+ await _mediator.PlaceOrderDetailsEvent(result, details);- //return if exist errors- if (result.Errors.Any())- return result;+ //return if exist errors+ if (result.Errors.Any())+ return result;- #region Payment workflow+ #region Payment workflow- var processPayment = await PrepareProcessPayment(details);+ var processPayment = await PrepareProcessPayment(details);- #endregion+ #endregion- if (processPayment.paymentResult.Success)- {- #region Save order details+ if (processPayment.paymentResult.Success)+ {+ #region Save order details- var orderHeader = PrepareOrderHeader(processPayment.paymentTransaction, processPayment.paymentResult, details);+ var orderHeader = PrepareOrderHeader(processPayment.paymentTransaction, processPayment.paymentResult,+ details);- result.PlacedOrder = await SaveOrderDetails(details, orderHeader);- result.PaymentTransaction = processPayment.paymentTransaction;+ result.PlacedOrder = await SaveOrderDetails(details, orderHeader);+ result.PaymentTransaction = processPayment.paymentTransaction;- #endregion+ #endregion- #region Payment transaction+ #region Payment transaction- await UpdatePaymentTransaction(processPayment.paymentTransaction, result.PlacedOrder, processPayment.paymentResult);+ await UpdatePaymentTransaction(processPayment.paymentTransaction, result.PlacedOrder,+ processPayment.paymentResult);- #endregion+ #endregion- #region Events & notes+ #region Events & notes- _ = Task.Run(() => SendNotification(_serviceScopeFactory, result.PlacedOrder, _workContext.CurrentCustomer, _workContext.OriginalCustomerIfImpersonated), cancellationToken);+ _ = Task.Run(+ () => SendNotification(_serviceScopeFactory, result.PlacedOrder, _workContext.CurrentCustomer,+ _workContext.OriginalCustomerIfImpersonated), cancellationToken);- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = result.PlacedOrder }, cancellationToken);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = result.PlacedOrder }, cancellationToken);- //raise event- await _mediator.Publish(new OrderPlacedEvent(result.PlacedOrder), cancellationToken);+ //raise event+ await _mediator.Publish(new OrderPlacedEvent(result.PlacedOrder), cancellationToken);- if (result.PlacedOrder.PaymentStatusId == PaymentStatus.Paid)- {- await _mediator.Send(new ProcessOrderPaidCommand { Order = result.PlacedOrder }, cancellationToken);- }+ if (result.PlacedOrder.PaymentStatusId == PaymentStatus.Paid)+ await _mediator.Send(new ProcessOrderPaidCommand { Order = result.PlacedOrder }, cancellationToken);- #endregion- }- else- {- await _paymentTransactionService.SetError(processPayment.paymentTransaction.Id, processPayment.paymentResult.Errors.ToList());- foreach (var paymentError in processPayment.paymentResult.Errors)- result.AddError(paymentError);- }+ #endregion}- catch (Exception exc)+ else{- _logger.LogError(exc, exc.Message);- result.AddError(exc.Message);+ await _paymentTransactionService.SetError(processPayment.paymentTransaction.Id,+ processPayment.paymentResult.Errors.ToList());+ foreach (var paymentError in processPayment.paymentResult.Errors)+ result.AddError(paymentError);}+ }+ catch (Exception exc)+ {+ _logger.LogError(exc, exc.Message);+ result.AddError(exc.Message);+ }- #region Process errors+ #region Process errors- var error = "";- for (var i = 0; i < result.Errors.Count; i++)- {- error += $"Error {i + 1}: {result.Errors[i]}";- if (i != result.Errors.Count - 1)- error += ". ";- }+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++)+ {+ error += $"Error {i + 1}: {result.Errors[i]}";+ if (i != result.Errors.Count - 1)+ error += ". ";+ }- if (string.IsNullOrEmpty(error)) return result;- //log it- _logger.LogError("Error while placing order. {Error}", error);+ if (string.IsNullOrEmpty(error)) return result;+ //log it+ _logger.LogError("Error while placing order. {Error}", error);- #endregion+ #endregion- return result;- }+ return result;+ }- protected virtual async Task<(ProcessPaymentResult paymentResult, PaymentTransaction paymentTransaction)>- PrepareProcessPayment(PlaceOrderContainer details)+ protected virtual async Task<(ProcessPaymentResult paymentResult, PaymentTransaction paymentTransaction)>+ PrepareProcessPayment(PlaceOrderContainer details)+ {+ //payment transaction+ var paymentTransaction = await PreparePaymentTransaction(details);++ //process payment+ ProcessPaymentResult processPaymentResult;+ //skip payment workflow if order total equals zero+ var skipPaymentWorkflow = details.OrderTotal == 0;+ if (!skipPaymentWorkflow){- //payment transaction- var paymentTransaction = await PreparePaymentTransaction(details);-- //process payment- ProcessPaymentResult processPaymentResult;- //skip payment workflow if order total equals zero- var skipPaymentWorkflow = details.OrderTotal == 0;- if (!skipPaymentWorkflow)- {- var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(details.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");+ var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(details.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");- //ensure that payment method is active- if (!paymentMethod.IsPaymentMethodActive(_paymentSettings))- throw new GrandException("Payment method is not active");+ //ensure that payment method is active+ if (!paymentMethod.IsPaymentMethodActive(_paymentSettings))+ throw new GrandException("Payment method is not active");- //standard cart- processPaymentResult = await _paymentService.ProcessPayment(paymentTransaction);- }- else- {- //payment is not required- processPaymentResult = new ProcessPaymentResult {- NewPaymentTransactionStatus = TransactionStatus.Paid- };- }+ //standard cart+ processPaymentResult = await _paymentService.ProcessPayment(paymentTransaction);+ }+ else+ {+ //payment is not required+ processPaymentResult = new ProcessPaymentResult {+ NewPaymentTransactionStatus = TransactionStatus.Paid+ };+ }- if (processPaymentResult == null)- throw new GrandException("processPaymentResult is not available");+ if (processPaymentResult == null)+ throw new GrandException("processPaymentResult is not available");- return (processPaymentResult, paymentTransaction);- }+ return (processPaymentResult, paymentTransaction);+ }- private async Task<PaymentTransaction> PreparePaymentTransaction(PlaceOrderContainer details)+ private async Task<PaymentTransaction> PreparePaymentTransaction(PlaceOrderContainer details)+ {+ var update = false;+ var paymentTransaction = new PaymentTransaction();+ var paymentTransactionId =+ details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PaymentTransaction,+ _workContext.CurrentStore.Id);+ if (!string.IsNullOrEmpty(paymentTransactionId)){- var update = false;- PaymentTransaction paymentTransaction = new PaymentTransaction();- var paymentTransactionId = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PaymentTransaction, _workContext.CurrentStore.Id);- if (!string.IsNullOrEmpty(paymentTransactionId))- {- paymentTransaction = await _paymentTransactionService.GetById(paymentTransactionId);- if (paymentTransaction != null)- {- update = true;- }- else- paymentTransaction = new PaymentTransaction();- }-- paymentTransaction.TransactionStatus = TransactionStatus.Pending;- paymentTransaction.IPAddress = details.Customer.LastIpAddress;- paymentTransaction.OrderCode = string.IsNullOrEmpty(paymentTransaction.OrderCode) ? await _mediator.Send(new PrepareOrderCodeCommand()) : paymentTransaction.OrderCode;- paymentTransaction.OrderGuid = paymentTransaction.OrderGuid == Guid.Empty ? Guid.NewGuid() : paymentTransaction.OrderGuid;- paymentTransaction.PaymentMethodSystemName = details.PaymentMethodSystemName;- paymentTransaction.StoreId = _workContext.CurrentStore.Id;- paymentTransaction.CustomerId = details.Customer.Id;- paymentTransaction.TransactionAmount = details.OrderTotal;- paymentTransaction.CurrencyRate = details.CurrencyRate;- paymentTransaction.CurrencyCode = details.Currency.CurrencyCode;- paymentTransaction.CustomerEmail = details.Customer.BillingAddress.Email;- paymentTransaction.Temp = true;-- if (update)- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);+ paymentTransaction = await _paymentTransactionService.GetById(paymentTransactionId);+ if (paymentTransaction != null)+ update = true;else- await _paymentTransactionService.InsertPaymentTransaction(paymentTransaction);-- return paymentTransaction;+ paymentTransaction = new PaymentTransaction();}- private async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction, Order order, ProcessPaymentResult processPaymentResult)- {- paymentTransaction.TransactionAmount = order.OrderTotal;- paymentTransaction.PaidAmount = order.PaidAmount;- paymentTransaction.Temp = false;- paymentTransaction.TransactionStatus = processPaymentResult.NewPaymentTransactionStatus;- paymentTransaction.Errors.Clear();+ paymentTransaction.TransactionStatus = TransactionStatus.Pending;+ paymentTransaction.IPAddress = details.Customer.LastIpAddress;+ paymentTransaction.OrderCode = string.IsNullOrEmpty(paymentTransaction.OrderCode)+ ? await _mediator.Send(new PrepareOrderCodeCommand())+ : paymentTransaction.OrderCode;+ paymentTransaction.OrderGuid =+ paymentTransaction.OrderGuid == Guid.Empty ? Guid.NewGuid() : paymentTransaction.OrderGuid;+ paymentTransaction.PaymentMethodSystemName = details.PaymentMethodSystemName;+ paymentTransaction.StoreId = _workContext.CurrentStore.Id;+ paymentTransaction.CustomerId = details.Customer.Id;+ paymentTransaction.TransactionAmount = details.OrderTotal;+ paymentTransaction.CurrencyRate = details.CurrencyRate;+ paymentTransaction.CurrencyCode = details.Currency.CurrencyCode;+ paymentTransaction.CustomerEmail = details.Customer.BillingAddress.Email;+ paymentTransaction.Temp = true;++ if (update)await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- }- private async Task<double?> PrepareCommissionRate(Product product, PlaceOrderContainer details)- {- var commissionRate = default(double?);- if (!string.IsNullOrEmpty(product.VendorId))- {- var vendor = await _vendorService.GetVendorById(product.VendorId);- if (vendor is { Commission: { } })- commissionRate = vendor.Commission.Value;- }+ else+ await _paymentTransactionService.InsertPaymentTransaction(paymentTransaction);- if (commissionRate.HasValue) return commissionRate;- if (string.IsNullOrEmpty(details.Customer.SeId)) return null;- var salesEmployee = await _salesEmployeeService.GetSalesEmployeeById(details.Customer.SeId);- if (salesEmployee is { Active: true, Commission: { } })- commissionRate = salesEmployee.Commission.Value;+ return paymentTransaction;+ }++ private async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction, Order order,+ ProcessPaymentResult processPaymentResult)+ {+ paymentTransaction.TransactionAmount = order.OrderTotal;+ paymentTransaction.PaidAmount = order.PaidAmount;+ paymentTransaction.Temp = false;+ paymentTransaction.TransactionStatus = processPaymentResult.NewPaymentTransactionStatus;+ paymentTransaction.Errors.Clear();+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);+ }- return commissionRate;+ private async Task<double?> PrepareCommissionRate(Product product, PlaceOrderContainer details)+ {+ var commissionRate = default(double?);+ if (!string.IsNullOrEmpty(product.VendorId))+ {+ var vendor = await _vendorService.GetVendorById(product.VendorId);+ if (vendor is { Commission: not null })+ commissionRate = vendor.Commission.Value;}- /// <summary>- /// Gets shopping cart item weight (of one item)- /// </summary>- /// <param name="shoppingCartItem">Shopping cart item</param>- /// <returns>Shopping cart item weight</returns>- private async Task<double> GetShoppingCartItemWeight(ShoppingCartItem shoppingCartItem)+ if (commissionRate.HasValue) return commissionRate;+ if (string.IsNullOrEmpty(details.Customer.SeId)) return null;+ var salesEmployee = await _salesEmployeeService.GetSalesEmployeeById(details.Customer.SeId);+ if (salesEmployee is { Active: true, Commission: not null })+ commissionRate = salesEmployee.Commission.Value;++ return commissionRate;+ }++ /// <summary>+ /// Gets shopping cart item weight (of one item)+ /// </summary>+ /// <param name="shoppingCartItem">Shopping cart item</param>+ /// <returns>Shopping cart item weight</returns>+ private async Task<double> GetShoppingCartItemWeight(ShoppingCartItem shoppingCartItem)+ {+ if (shoppingCartItem == null)+ throw new ArgumentNullException(nameof(shoppingCartItem));+ var product = await _productService.GetProductById(shoppingCartItem.ProductId);+ if (product == null)+ return 0;++ //attribute weight+ double attributesTotalWeight = 0;+ if (shoppingCartItem.Attributes != null && shoppingCartItem.Attributes.Any()){- if (shoppingCartItem == null)- throw new ArgumentNullException(nameof(shoppingCartItem));- var product = await _productService.GetProductById(shoppingCartItem.ProductId);- if (product == null)- return 0;-- //attribute weight- double attributesTotalWeight = 0;- if (shoppingCartItem.Attributes != null && shoppingCartItem.Attributes.Any())- {- var attributeValues = product.ParseProductAttributeValues(shoppingCartItem.Attributes);- foreach (var attributeValue in attributeValues)+ var attributeValues = product.ParseProductAttributeValues(shoppingCartItem.Attributes);+ foreach (var attributeValue in attributeValues)+ switch (attributeValue.AttributeValueTypeId){- switch (attributeValue.AttributeValueTypeId)+ case AttributeValueType.Simple:+ {+ //simple attribute+ attributesTotalWeight += attributeValue.WeightAdjustment;+ }+ break;+ case AttributeValueType.AssociatedToProduct:{- case AttributeValueType.Simple:- {- //simple attribute- attributesTotalWeight += attributeValue.WeightAdjustment;- }- break;- case AttributeValueType.AssociatedToProduct:- {- //bundled product- var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);- if (associatedProduct is { IsShipEnabled: true })- {- attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;- }- }- break;+ //bundled product+ var associatedProduct =+ await _productService.GetProductById(attributeValue.AssociatedProductId);+ if (associatedProduct is { IsShipEnabled: true })+ attributesTotalWeight += associatedProduct.Weight * attributeValue.Quantity;}+ break;}- }- var weight = product.Weight + attributesTotalWeight;- return weight;}- protected virtual async Task<PlaceOrderContainer> PreparePlaceOrderDetails()- {- var details = new PlaceOrderContainer {- //customer- Customer = _workContext.CurrentCustomer- };- if (details.Customer == null)- throw new ArgumentException("Customer is not set");-- //check whether customer is guest- if (await _groupService.IsGuest(details.Customer) && !_orderSettings.AnonymousCheckoutAllowed)- throw new GrandException("Anonymous checkout is not allowed");+ var weight = product.Weight + attributesTotalWeight;+ return weight;+ }- //billing address- if (details.Customer.BillingAddress == null)- throw new GrandException("Billing address is not provided");+ protected virtual async Task<PlaceOrderContainer> PreparePlaceOrderDetails()+ {+ var details = new PlaceOrderContainer {+ //customer+ Customer = _workContext.CurrentCustomer+ };+ if (details.Customer == null)+ throw new ArgumentException("Customer is not set");++ //check whether customer is guest+ if (await _groupService.IsGuest(details.Customer) && !_orderSettings.AnonymousCheckoutAllowed)+ throw new GrandException("Anonymous checkout is not allowed");++ //billing address+ if (details.Customer.BillingAddress == null)+ throw new GrandException("Billing address is not provided");++ if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email))+ throw new GrandException("Email is not valid");++ //affiliate+ if (!string.IsNullOrEmpty(details.Customer.AffiliateId))+ {+ var affiliate = await _affiliateService.GetAffiliateById(details.Customer.AffiliateId);+ if (affiliate is { Active: true })+ details.AffiliateId = affiliate.Id;+ }- if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email))- throw new GrandException("Email is not valid");+ //customer currency+ var currencyTmp = await _currencyService.GetCurrencyById(+ details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId,+ _workContext.CurrentStore.Id));+ var customerCurrency = currencyTmp is { Published: true } ? currencyTmp : _workContext.WorkingCurrency;+ details.Currency = customerCurrency;+ var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();+ details.CurrencyRate = Math.Round(customerCurrency.Rate / primaryStoreCurrency.Rate, 6);+ details.PrimaryCurrencyCode = primaryStoreCurrency.CurrencyCode;++ //customer language+ details.Language = await _languageService.GetLanguageById(+ details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId,+ _workContext.CurrentStore.Id));++ if (details.Language is not { Published: true })+ details.Language = _workContext.WorkingLanguage;++ details.BillingAddress = details.Customer.BillingAddress;+ if (!string.IsNullOrEmpty(details.BillingAddress.CountryId))+ {+ var country = await _countryService.GetCountryById(details.BillingAddress.CountryId);+ if (country is { AllowsBilling: false })+ throw new GrandException($"Country '{country.Name}' is not allowed for billing");+ }- //affiliate- if (!string.IsNullOrEmpty(details.Customer.AffiliateId))+ //checkout attributes+ details.CheckoutAttributes =+ details.Customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,+ _workContext.CurrentStore.Id);+ details.CheckoutAttributeDescription =+ await _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributes, details.Customer);++ //load and validate customer shopping cart+ details.Cart = details.Customer.ShoppingCartItems+ .Where(sci => sci.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions)+ .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id)+ .ToList();++ if (!details.Cart.Any())+ throw new GrandException("Cart is empty");++ //validate the entire shopping cart+ var warnings =+ await _shoppingCartValidator.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributes, true, true);+ if (warnings.Any()) throw new GrandException(string.Join(", ", warnings));++ //validate individual cart items+ foreach (var sci in details.Cart)+ {+ var product = await _productService.GetProductById(sci.ProductId);+ var sciWarnings = await _shoppingCartValidator.GetShoppingCartItemWarnings(details.Customer, sci, product,+ new ShoppingCartValidatorOptions());+ if (sciWarnings.Any()){- var affiliate = await _affiliateService.GetAffiliateById(details.Customer.AffiliateId);- if (affiliate is { Active: true })- details.AffiliateId = affiliate.Id;+ var warningsSb = new StringBuilder();+ foreach (var warning in sciWarnings)+ {+ warningsSb.Append(warning);+ warningsSb.Append(';');+ }++ throw new GrandException(warningsSb.ToString());}- //customer currency- var currencyTmp = await _currencyService.GetCurrencyById(details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, _workContext.CurrentStore.Id));- var customerCurrency = currencyTmp is { Published: true } ? currencyTmp : _workContext.WorkingCurrency;- details.Currency = customerCurrency;- var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();- details.CurrencyRate = Math.Round(customerCurrency.Rate / primaryStoreCurrency.Rate, 6);- details.PrimaryCurrencyCode = primaryStoreCurrency.CurrencyCode;+ if (!product.IsRecurring) continue;+ details.IsRecurring = true;+ details.RecurringCycleLength = product.RecurringCycleLength;+ details.RecurringCyclePeriodId = product.RecurringCyclePeriodId;+ details.RecurringTotalCycles = product.RecurringTotalCycles;+ }- //customer language- details.Language = await _languageService.GetLanguageById(details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, _workContext.CurrentStore.Id));+ //tax display type+ if (_taxSettings.AllowCustomersToSelectTaxDisplayType)+ details.TaxDisplayType =+ (TaxDisplayType)details.Customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId,+ _workContext.CurrentStore.Id);+ else+ details.TaxDisplayType = _taxSettings.TaxDisplayType;- if (details.Language is not { Published: true })- details.Language = _workContext.WorkingLanguage;+ //sub total+ //sub total (incl tax)+ var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true);+ var orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;+ var orderSubTotalAppliedDiscounts = shoppingCartSubTotal.appliedDiscounts;+ var subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;- details.BillingAddress = details.Customer.BillingAddress;- if (!string.IsNullOrEmpty(details.BillingAddress.CountryId))- {- var country = await _countryService.GetCountryById(details.BillingAddress.CountryId);- if (country is { AllowsBilling: false }) throw new GrandException($"Country '{country.Name}' is not allowed for billing");- }+ details.OrderSubTotalInclTax = subTotalWithoutDiscountBase;+ details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount;- //checkout attributes- details.CheckoutAttributes = details.Customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);- details.CheckoutAttributeDescription = await _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributes, details.Customer);+ foreach (var disc in orderSubTotalAppliedDiscounts.Where(disc =>+ details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))+ details.AppliedDiscounts.Add(disc);- //load and validate customer shopping cart- details.Cart = details.Customer.ShoppingCartItems- .Where(sci => sci.ShoppingCartTypeId is ShoppingCartType.ShoppingCart or ShoppingCartType.Auctions)- .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, _workContext.CurrentStore.Id)- .ToList();+ //sub total (excl tax)+ shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false);+ orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;+ subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;- if (!details.Cart.Any())- throw new GrandException("Cart is empty");+ details.OrderSubTotalExclTax = subTotalWithoutDiscountBase;+ details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount;- //validate the entire shopping cart- var warnings = await _shoppingCartValidator.GetShoppingCartWarnings(details.Cart, details.CheckoutAttributes, true,true);- if (warnings.Any())- {- throw new GrandException(string.Join(", ", warnings));- }+ //shipping info+ var shoppingCartRequiresShipping = details.Cart.RequiresShipping();- //validate individual cart items- foreach (var sci in details.Cart)+ if (shoppingCartRequiresShipping)+ {+ var pickupPoint =+ details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPickupPoint,+ _workContext.CurrentStore.Id);+ if (_shippingSettings.AllowPickUpInStore && pickupPoint != null){- var product = await _productService.GetProductById(sci.ProductId);- var sciWarnings = await _shoppingCartValidator.GetShoppingCartItemWarnings(details.Customer, sci, product, new ShoppingCartValidatorOptions());- if (sciWarnings.Any())- {- var warningsSb = new StringBuilder();- foreach (var warning in sciWarnings)- {- warningsSb.Append(warning);- warningsSb.Append(';');- }- throw new GrandException(warningsSb.ToString());- }-- if (!product.IsRecurring) continue;- details.IsRecurring = true;- details.RecurringCycleLength = product.RecurringCycleLength;- details.RecurringCyclePeriodId = product.RecurringCyclePeriodId;- details.RecurringTotalCycles = product.RecurringTotalCycles;+ details.PickUpInStore = true;+ details.PickupPoint = await _mediator.Send(new GetPickupPointById { Id = pickupPoint });}-- //tax display type- if (_taxSettings.AllowCustomersToSelectTaxDisplayType)- details.TaxDisplayType = (TaxDisplayType)details.Customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, _workContext.CurrentStore.Id);else- details.TaxDisplayType = _taxSettings.TaxDisplayType;-- //sub total- //sub total (incl tax)- var shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, true);- var orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;- List<ApplyDiscount> orderSubTotalAppliedDiscounts = shoppingCartSubTotal.appliedDiscounts;- var subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;-- details.OrderSubTotalInclTax = subTotalWithoutDiscountBase;- details.OrderSubTotalDiscountInclTax = orderSubTotalDiscountAmount;-- foreach (var disc in orderSubTotalAppliedDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))- details.AppliedDiscounts.Add(disc);-- //sub total (excl tax)- shoppingCartSubTotal = await _orderTotalCalculationService.GetShoppingCartSubTotal(details.Cart, false);- orderSubTotalDiscountAmount = shoppingCartSubTotal.discountAmount;- subTotalWithoutDiscountBase = shoppingCartSubTotal.subTotalWithoutDiscount;-- details.OrderSubTotalExclTax = subTotalWithoutDiscountBase;- details.OrderSubTotalDiscountExclTax = orderSubTotalDiscountAmount;-- //shipping info- var shoppingCartRequiresShipping = details.Cart.RequiresShipping();-- if (shoppingCartRequiresShipping){- var pickupPoint = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPickupPoint, _workContext.CurrentStore.Id);- if (_shippingSettings.AllowPickUpInStore && pickupPoint != null)- {- details.PickUpInStore = true;- details.PickupPoint = await _mediator.Send(new GetPickupPointById { Id = pickupPoint });- }- else- {- if (details.Customer.ShippingAddress == null)- throw new GrandException("Shipping address is not provided");+ if (details.Customer.ShippingAddress == null)+ throw new GrandException("Shipping address is not provided");- if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email))- throw new GrandException("Email is not valid");+ if (!CommonHelper.IsValidEmail(details.Customer.ShippingAddress.Email))+ throw new GrandException("Email is not valid");- //clone shipping address- details.ShippingAddress = details.Customer.ShippingAddress;- if (!string.IsNullOrEmpty(details.ShippingAddress.CountryId))- {- var country = await _countryService.GetCountryById(details.ShippingAddress.CountryId);- if (country is { AllowsShipping: false }) throw new GrandException($"Country '{country.Name}' is not allowed for shipping");- }- }- var shippingOption = details.Customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption, _workContext.CurrentStore.Id);- if (shippingOption != null)+ //clone shipping address+ details.ShippingAddress = details.Customer.ShippingAddress;+ if (!string.IsNullOrEmpty(details.ShippingAddress.CountryId)){- details.ShippingMethodName = shippingOption.Name;- details.ShippingRateProviderSystemName = shippingOption.ShippingRateProviderSystemName;+ var country = await _countryService.GetCountryById(details.ShippingAddress.CountryId);+ if (country is { AllowsShipping: false })+ throw new GrandException($"Country '{country.Name}' is not allowed for shipping");}}- details.ShippingStatus = shoppingCartRequiresShipping- ? ShippingStatus.Pending- : ShippingStatus.ShippingNotRequired;-- //shipping total- var (orderShippingTotalInclTax, _, shippingTotalDiscounts) = await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true);- var orderShippingTotalExclTax = (await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false)).shoppingCartShippingTotal;- if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)- throw new GrandException("Shipping total couldn't be calculated");-- foreach (var disc in shippingTotalDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))+ var shippingOption =+ details.Customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption,+ _workContext.CurrentStore.Id);+ if (shippingOption != null){- details.AppliedDiscounts.Add(disc);+ details.ShippingMethodName = shippingOption.Name;+ details.ShippingRateProviderSystemName = shippingOption.ShippingRateProviderSystemName;}- details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value;- details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value;-- //payment- var paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod, _workContext.CurrentStore.Id);- details.PaymentMethodSystemName = paymentMethodSystemName;- var paymentAdditionalFee = await _paymentService.GetAdditionalHandlingFee(details.Cart, paymentMethodSystemName);- details.PaymentAdditionalFeeInclTax = (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer)).paymentPrice;- details.PaymentAdditionalFeeExclTax = (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer)).paymentPrice;-- //tax total- //tax amount- var (taxTotal, taxRates) = await _orderTotalCalculationService.GetTaxTotal(details.Cart);- details.OrderTaxTotal = taxTotal;-- //tax rates- foreach (var kvp in taxRates)- {- details.Taxes.Add(new OrderTax {- Percent = Math.Round(kvp.Key, 2),- Amount = kvp.Value- });- }-- //order total (and applied discounts, gift vouchers, loyalty points)- var (orderTotal, orderDiscountAmount, orderAppliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints, redeemedLoyaltyPointsAmount) = await _orderTotalCalculationService.GetShoppingCartTotal(details.Cart);- if (!orderTotal.HasValue)- throw new GrandException("Order total couldn't be calculated");-- details.OrderDiscountAmount = orderDiscountAmount;- details.RedeemedLoyaltyPoints = redeemedLoyaltyPoints;- details.RedeemedLoyaltyPointsAmount = redeemedLoyaltyPointsAmount;- details.AppliedGiftVouchers = appliedGiftVouchers;- details.OrderTotal = orderTotal.Value;-- //discount history- foreach (var disc in orderAppliedDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))- {- details.AppliedDiscounts.Add(disc);- }-- return details;}- protected virtual async Task<OrderItem> PrepareOrderItem(ShoppingCartItem sc, Product product, PlaceOrderContainer details)- {- var scUnitPrice = (await _pricingService.GetUnitPrice(sc, product)).unitprice;- var scUnitPriceWithoutDisc = (await _pricingService.GetUnitPrice(sc, product, false)).unitprice;-- var (scSubTotal, discountAmount, scDiscounts) = await _pricingService.GetSubTotal(sc, product);-- var prices = await _taxService.GetTaxProductPrice(product, details.Customer, scUnitPrice, scUnitPriceWithoutDisc, sc.Quantity, scSubTotal, discountAmount, _taxSettings.PricesIncludeTax);- var scUnitPriceWithoutDiscInclTax = prices.UnitPriceWithoutDiscInclTax;- var scUnitPriceWithoutDiscExclTax = prices.UnitPriceWithoutDiscExclTax;- var scUnitPriceInclTax = prices.UnitPriceInclTax;- var scUnitPriceExclTax = prices.UnitPriceExclTax;- var scSubTotalInclTax = prices.SubTotalInclTax;- var scSubTotalExclTax = prices.SubTotalExclTax;- var discountAmountInclTax = prices.DiscountAmountInclTax;- var discountAmountExclTax = prices.DiscountAmountExclTax;-- foreach (var disc in scDiscounts.Where(disc => details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))- {- details.AppliedDiscounts.Add(disc);- }- var attributeDescription = await _productAttributeFormatter.FormatAttributes(product, sc.Attributes, details.Customer);- var itemWeight = await GetShoppingCartItemWeight(sc);- var warehouseId = !string.IsNullOrEmpty(sc.WarehouseId) ? sc.WarehouseId : _workContext.CurrentStore.DefaultWarehouseId;- if (!product.UseMultipleWarehouses && string.IsNullOrEmpty(warehouseId))- {- if (!string.IsNullOrEmpty(product.WarehouseId))- {- warehouseId = product.WarehouseId;- }- }-- var commissionRate = await PrepareCommissionRate(product, details);- var commission = commissionRate.HasValue ?- Math.Round(commissionRate.Value * scSubTotal / 100, 2) : 0;-- //save order item- var orderItem = new OrderItem {- OrderItemGuid = Guid.NewGuid(),- ProductId = sc.ProductId,- Sku = product.FormatSku(sc.Attributes),- VendorId = product.VendorId,- WarehouseId = warehouseId,- SeId = details.Customer.SeId,- TaxRate = Math.Round(prices.TaxRate, 2),- UnitPriceWithoutDiscInclTax = Math.Round(scUnitPriceWithoutDiscInclTax, 6),- UnitPriceWithoutDiscExclTax = Math.Round(scUnitPriceWithoutDiscExclTax, 6),- UnitPriceInclTax = Math.Round(scUnitPriceInclTax, 6),- UnitPriceExclTax = Math.Round(scUnitPriceExclTax, 6),- PriceInclTax = Math.Round(scSubTotalInclTax, 6),- PriceExclTax = Math.Round(scSubTotalExclTax, 6),- OriginalProductCost = await _pricingService.GetProductCost(product, sc.Attributes),- AttributeDescription = attributeDescription,- Attributes = sc.Attributes,- Quantity = sc.Quantity,- OpenQty = sc.Quantity,- IsShipEnabled = product.IsShipEnabled,- DiscountAmountInclTax = Math.Round(discountAmountInclTax, 6),- DiscountAmountExclTax = Math.Round(discountAmountExclTax, 6),- DownloadCount = 0,- IsDownloadActivated = false,- LicenseDownloadId = "",- ItemWeight = itemWeight,- RentalStartDateUtc = sc.RentalStartDateUtc,- RentalEndDateUtc = sc.RentalEndDateUtc,- CreatedOnUtc = DateTime.UtcNow,- Commission = commission,- cId = sc.cId- };+ details.ShippingStatus = shoppingCartRequiresShipping+ ? ShippingStatus.Pending+ : ShippingStatus.ShippingNotRequired;++ //shipping total++ var (orderShippingTotalInclTax, _, shippingTotalDiscounts) =+ await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, true);+ var orderShippingTotalExclTax =+ (await _orderTotalCalculationService.GetShoppingCartShippingTotal(details.Cart, false))+ .shoppingCartShippingTotal;+ if (!orderShippingTotalInclTax.HasValue || !orderShippingTotalExclTax.HasValue)+ throw new GrandException("Shipping total couldn't be calculated");++ foreach (var disc in shippingTotalDiscounts.Where(disc =>+ details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))+ details.AppliedDiscounts.Add(disc);+ details.OrderShippingTotalInclTax = orderShippingTotalInclTax.Value;+ details.OrderShippingTotalExclTax = orderShippingTotalExclTax.Value;++ //payment+ var paymentMethodSystemName =+ _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.SelectedPaymentMethod,+ _workContext.CurrentStore.Id);+ details.PaymentMethodSystemName = paymentMethodSystemName;+ var paymentAdditionalFee =+ await _paymentService.GetAdditionalHandlingFee(details.Cart, paymentMethodSystemName);+ details.PaymentAdditionalFeeInclTax =+ (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, true, details.Customer))+ .paymentPrice;+ details.PaymentAdditionalFeeExclTax =+ (await _taxService.GetPaymentMethodAdditionalFee(paymentAdditionalFee, false, details.Customer))+ .paymentPrice;++ //tax total+ //tax amount+ var (taxTotal, taxRates) = await _orderTotalCalculationService.GetTaxTotal(details.Cart);+ details.OrderTaxTotal = taxTotal;++ //tax rates+ foreach (var kvp in taxRates)+ details.Taxes.Add(new OrderTax {+ Percent = Math.Round(kvp.Key, 2),+ Amount = kvp.Value+ });++ //order total (and applied discounts, gift vouchers, loyalty points)+ var (orderTotal, orderDiscountAmount, orderAppliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,+ redeemedLoyaltyPointsAmount) = await _orderTotalCalculationService.GetShoppingCartTotal(details.Cart);+ if (!orderTotal.HasValue)+ throw new GrandException("Order total couldn't be calculated");++ details.OrderDiscountAmount = orderDiscountAmount;+ details.RedeemedLoyaltyPoints = redeemedLoyaltyPoints;+ details.RedeemedLoyaltyPointsAmount = redeemedLoyaltyPointsAmount;+ details.AppliedGiftVouchers = appliedGiftVouchers;+ details.OrderTotal = orderTotal.Value;++ //discount history+ foreach (var disc in orderAppliedDiscounts.Where(disc =>+ details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))+ details.AppliedDiscounts.Add(disc);++ return details;+ }- var reservationInfo = ReservationInfo(sc, product);+ protected virtual async Task<OrderItem> PrepareOrderItem(ShoppingCartItem sc, Product product,+ PlaceOrderContainer details)+ {+ var scUnitPrice = (await _pricingService.GetUnitPrice(sc, product)).unitprice;+ var scUnitPriceWithoutDisc = (await _pricingService.GetUnitPrice(sc, product, false)).unitprice;++ var (scSubTotal, discountAmount, scDiscounts) = await _pricingService.GetSubTotal(sc, product);++ var prices = await _taxService.GetTaxProductPrice(product, details.Customer, scUnitPrice,+ scUnitPriceWithoutDisc, sc.Quantity, scSubTotal, discountAmount, _taxSettings.PricesIncludeTax);+ var scUnitPriceWithoutDiscInclTax = prices.UnitPriceWithoutDiscInclTax;+ var scUnitPriceWithoutDiscExclTax = prices.UnitPriceWithoutDiscExclTax;+ var scUnitPriceInclTax = prices.UnitPriceInclTax;+ var scUnitPriceExclTax = prices.UnitPriceExclTax;+ var scSubTotalInclTax = prices.SubTotalInclTax;+ var scSubTotalExclTax = prices.SubTotalExclTax;+ var discountAmountInclTax = prices.DiscountAmountInclTax;+ var discountAmountExclTax = prices.DiscountAmountExclTax;++ foreach (var disc in scDiscounts.Where(disc =>+ details.AppliedDiscounts.All(x => x.DiscountId != disc.DiscountId)))+ details.AppliedDiscounts.Add(disc);+ var attributeDescription =+ await _productAttributeFormatter.FormatAttributes(product, sc.Attributes, details.Customer);+ var itemWeight = await GetShoppingCartItemWeight(sc);+ var warehouseId = !string.IsNullOrEmpty(sc.WarehouseId)+ ? sc.WarehouseId+ : _workContext.CurrentStore.DefaultWarehouseId;+ if (!product.UseMultipleWarehouses && string.IsNullOrEmpty(warehouseId))+ if (!string.IsNullOrEmpty(product.WarehouseId))+ warehouseId = product.WarehouseId;++ var commissionRate = await PrepareCommissionRate(product, details);+ var commission = commissionRate.HasValue ? Math.Round(commissionRate.Value * scSubTotal / 100, 2) : 0;++ //save order item+ var orderItem = new OrderItem {+ OrderItemGuid = Guid.NewGuid(),+ ProductId = sc.ProductId,+ Sku = product.FormatSku(sc.Attributes),+ VendorId = product.VendorId,+ WarehouseId = warehouseId,+ SeId = details.Customer.SeId,+ TaxRate = Math.Round(prices.TaxRate, 2),+ UnitPriceWithoutDiscInclTax = Math.Round(scUnitPriceWithoutDiscInclTax, 6),+ UnitPriceWithoutDiscExclTax = Math.Round(scUnitPriceWithoutDiscExclTax, 6),+ UnitPriceInclTax = Math.Round(scUnitPriceInclTax, 6),+ UnitPriceExclTax = Math.Round(scUnitPriceExclTax, 6),+ PriceInclTax = Math.Round(scSubTotalInclTax, 6),+ PriceExclTax = Math.Round(scSubTotalExclTax, 6),+ OriginalProductCost = await _pricingService.GetProductCost(product, sc.Attributes),+ AttributeDescription = attributeDescription,+ Attributes = sc.Attributes,+ Quantity = sc.Quantity,+ OpenQty = sc.Quantity,+ IsShipEnabled = product.IsShipEnabled,+ DiscountAmountInclTax = Math.Round(discountAmountInclTax, 6),+ DiscountAmountExclTax = Math.Round(discountAmountExclTax, 6),+ DownloadCount = 0,+ IsDownloadActivated = false,+ LicenseDownloadId = "",+ ItemWeight = itemWeight,+ RentalStartDateUtc = sc.RentalStartDateUtc,+ RentalEndDateUtc = sc.RentalEndDateUtc,+ CreatedOnUtc = DateTime.UtcNow,+ Commission = commission,+ cId = sc.cId+ };++ var reservationInfo = ReservationInfo(sc, product);++ if (string.IsNullOrEmpty(reservationInfo)) return orderItem;+ if (!string.IsNullOrEmpty(orderItem.AttributeDescription))+ orderItem.AttributeDescription += "<br>" + reservationInfo;+ else+ orderItem.AttributeDescription = reservationInfo;+ return orderItem;+ }- if (string.IsNullOrEmpty(reservationInfo)) return orderItem;- if (!string.IsNullOrEmpty(orderItem.AttributeDescription))- {- orderItem.AttributeDescription += "<br>" + reservationInfo;- }+ private static string ReservationInfo(ShoppingCartItem sc, Product product)+ {+ var reservationInfo = "";+ if (product.ProductTypeId == ProductType.Reservation)+ {+ if (sc.RentalEndDateUtc == default(DateTime) || sc.RentalEndDateUtc == null)+ reservationInfo = sc.RentalStartDateUtc.ToString();else- {- orderItem.AttributeDescription = reservationInfo;- }- return orderItem;- }+ reservationInfo = sc.RentalStartDateUtc + " - " + sc.RentalEndDateUtc;- private static string ReservationInfo(ShoppingCartItem sc, Product product)- {- var reservationInfo = "";- if (product.ProductTypeId == ProductType.Reservation)- {- if (sc.RentalEndDateUtc == default(DateTime) || sc.RentalEndDateUtc == null)- {- reservationInfo = sc.RentalStartDateUtc.ToString();- }- else- {- reservationInfo = sc.RentalStartDateUtc + " - " + sc.RentalEndDateUtc;- }+ if (!string.IsNullOrEmpty(sc.Parameter)) reservationInfo += "<br>" + sc.Parameter;- if (!string.IsNullOrEmpty(sc.Parameter))- {- reservationInfo += "<br>" + sc.Parameter;- }+ if (!string.IsNullOrEmpty(sc.Duration)) reservationInfo += "<br>" + sc.Duration;+ }- if (!string.IsNullOrEmpty(sc.Duration))- {- reservationInfo += "<br>" + sc.Duration;- }- }+ return reservationInfo;+ }- return reservationInfo;- }+ protected virtual async Task GenerateGiftVoucher(PlaceOrderContainer details, ShoppingCartItem sc, Order order,+ OrderItem orderItem, Product product)+ {+ GiftVoucherExtensions.GetGiftVoucherAttribute(sc.Attributes,+ out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);- protected virtual async Task GenerateGiftVoucher(PlaceOrderContainer details, ShoppingCartItem sc, Order order, OrderItem orderItem, Product product)+ for (var i = 0; i < sc.Quantity; i++){- GiftVoucherExtensions.GetGiftVoucherAttribute(sc.Attributes,- out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);-- for (var i = 0; i < sc.Quantity; i++)- {- var amount = orderItem.UnitPriceInclTax;- if (product.OverGiftAmount.HasValue)- amount = await _currencyService.ConvertFromPrimaryStoreCurrency(product.OverGiftAmount.Value, details.Currency);-- var gc = new GiftVoucher {- GiftVoucherTypeId = product.GiftVoucherTypeId,- PurchasedWithOrderItem = orderItem,- Amount = amount,- CurrencyCode = order.CustomerCurrencyCode,- IsGiftVoucherActivated = false,- Code = _giftVoucherService.GenerateGiftVoucherCode(),- RecipientName = giftVoucherRecipientName,- RecipientEmail = giftVoucherRecipientEmail,- SenderName = giftVoucherSenderName,- SenderEmail = giftVoucherSenderEmail,- Message = giftVoucherMessage,- IsRecipientNotified = false,- StoreId = _orderSettings.GiftVouchers_Assign_StoreId ? _workContext.CurrentStore.Id : string.Empty- };- await _giftVoucherService.InsertGiftVoucher(gc);- }+ var amount = orderItem.UnitPriceInclTax;+ if (product.OverGiftAmount.HasValue)+ amount = await _currencyService.ConvertFromPrimaryStoreCurrency(product.OverGiftAmount.Value,+ details.Currency);++ var gc = new GiftVoucher {+ GiftVoucherTypeId = product.GiftVoucherTypeId,+ PurchasedWithOrderItem = orderItem,+ Amount = amount,+ CurrencyCode = order.CustomerCurrencyCode,+ IsGiftVoucherActivated = false,+ Code = _giftVoucherService.GenerateGiftVoucherCode(),+ RecipientName = giftVoucherRecipientName,+ RecipientEmail = giftVoucherRecipientEmail,+ SenderName = giftVoucherSenderName,+ SenderEmail = giftVoucherSenderEmail,+ Message = giftVoucherMessage,+ IsRecipientNotified = false,+ StoreId = _orderSettings.GiftVouchers_Assign_StoreId ? _workContext.CurrentStore.Id : string.Empty+ };+ await _giftVoucherService.InsertGiftVoucher(gc);}+ }- protected virtual async Task UpdateProductReservation(Order order, PlaceOrderContainer details)+ protected virtual async Task UpdateProductReservation(Order order, PlaceOrderContainer details)+ {+ var reservationsToUpdate = new List<ProductReservation>();+ foreach (var sc in details.Cart.Where(x =>+ (x.RentalStartDateUtc.HasValue && x.RentalEndDateUtc.HasValue) ||+ !string.IsNullOrEmpty(x.ReservationId))){- var reservationsToUpdate = new List<ProductReservation>();- foreach (var sc in details.Cart.Where(x => (x.RentalStartDateUtc.HasValue && x.RentalEndDateUtc.HasValue) || !string.IsNullOrEmpty(x.ReservationId)))+ var product = await _productService.GetProductById(sc.ProductId);+ if (!string.IsNullOrEmpty(sc.ReservationId)){- var product = await _productService.GetProductById(sc.ProductId);- if (!string.IsNullOrEmpty(sc.ReservationId))- {- var reservation = await _productReservationService.GetProductReservation(sc.ReservationId);- reservationsToUpdate.Add(reservation);- }+ var reservation = await _productReservationService.GetProductReservation(sc.ReservationId);+ reservationsToUpdate.Add(reservation);+ }- if (!sc.RentalStartDateUtc.HasValue || !sc.RentalEndDateUtc.HasValue) continue;- var reservations = await _productReservationService.GetProductReservationsByProductId(product.Id, true, null);- var grouped = reservations.GroupBy(x => x.Resource);+ if (!sc.RentalStartDateUtc.HasValue || !sc.RentalEndDateUtc.HasValue) continue;+ var reservations =+ await _productReservationService.GetProductReservationsByProductId(product.Id, true, null);+ var grouped = reservations.GroupBy(x => x.Resource);- IGrouping<string, ProductReservation> groupToBook = null;- foreach (var group in grouped)- {- var groupCanBeBooked = true;- if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)+ IGrouping<string, ProductReservation> groupToBook = null;+ foreach (var group in grouped)+ {+ var groupCanBeBooked = true;+ if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)+ for (var iterator = sc.RentalStartDateUtc.Value;+ iterator <= sc.RentalEndDateUtc.Value;+ iterator += new TimeSpan(24, 0, 0)){- for (DateTime iterator = sc.RentalStartDateUtc.Value; iterator <= sc.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0))- {- if (group.Select(x => x.Date).Contains(iterator)) continue;- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}- else+ else+ for (var iterator = sc.RentalStartDateUtc.Value;+ iterator < sc.RentalEndDateUtc.Value;+ iterator += new TimeSpan(24, 0, 0)){- for (DateTime iterator = sc.RentalStartDateUtc.Value; iterator < sc.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0))- {- if (group.Select(x => x.Date).Contains(iterator)) continue;- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}- if (!groupCanBeBooked) continue;- groupToBook = group;- break;- }-- if (groupToBook == null)- {- throw new Exception("ShoppingCart.Reservation.NoFreeReservationsInThisPeriod");- }-- var temp = groupToBook.AsQueryable();- if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)- {- temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date <= sc.RentalEndDateUtc);- }- else- {- temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date < sc.RentalEndDateUtc);- }+ if (!groupCanBeBooked) continue;+ groupToBook = group;+ break;+ }- foreach (var item in temp)- {- item.OrderId = order.OrderGuid.ToString();- await _productReservationService.UpdateProductReservation(item);- }+ if (groupToBook == null) throw new Exception("ShoppingCart.Reservation.NoFreeReservationsInThisPeriod");- reservationsToUpdate.AddRange(temp);- }- var reserved = await _productReservationService.GetCustomerReservationsHelpers(order.CustomerId);- foreach (var res in reserved)- {- await _productReservationService.DeleteCustomerReservationsHelper(res);- }+ var temp = groupToBook.AsQueryable();+ if (product.IncBothDate && product.IntervalUnitId == IntervalUnit.Day)+ temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date <= sc.RentalEndDateUtc);+ else+ temp = temp.Where(x => x.Date >= sc.RentalStartDateUtc && x.Date < sc.RentalEndDateUtc);- foreach (var resToUpdate in reservationsToUpdate)+ foreach (var item in temp){- resToUpdate.OrderId = order.Id;- await _productReservationService.UpdateProductReservation(resToUpdate);+ item.OrderId = order.OrderGuid.ToString();+ await _productReservationService.UpdateProductReservation(item);}+ reservationsToUpdate.AddRange(temp);}- protected virtual async Task UpdateAuctionEnded(ShoppingCartItem sc, Product product, Order order)+ var reserved = await _productReservationService.GetCustomerReservationsHelpers(order.CustomerId);+ foreach (var res in reserved) await _productReservationService.DeleteCustomerReservationsHelper(res);++ foreach (var resToUpdate in reservationsToUpdate){- if (product.ProductTypeId == ProductType.Auction && sc.ShoppingCartTypeId == ShoppingCartType.ShoppingCart)- {- await _auctionService.UpdateAuctionEnded(product, true, true);- await _auctionService.UpdateHighestBid(product, product.Price, order.CustomerId);- await _messageProviderService.SendAuctionEndedBinCustomerMessage(product, order.CustomerId, order.CustomerLanguageId, order.StoreId);- await _auctionService.InsertBid(new Bid {- CustomerId = order.CustomerId,- OrderId = order.Id,- Amount = product.Price,- Date = DateTime.UtcNow,- ProductId = product.Id,- StoreId = order.StoreId,- Win = true,- Bin = true- });- }- if (product.ProductTypeId == ProductType.Auction && _orderSettings.UnpublishAuctionProduct)- {- await _productService.UnPublishProduct(product);- }+ resToUpdate.OrderId = order.Id;+ await _productReservationService.UpdateProductReservation(resToUpdate);}+ }- protected virtual async Task UpdateBids(Order order, PlaceOrderContainer details)+ protected virtual async Task UpdateAuctionEnded(ShoppingCartItem sc, Product product, Order order)+ {+ if (product.ProductTypeId == ProductType.Auction && sc.ShoppingCartTypeId == ShoppingCartType.ShoppingCart){- foreach (var sc in details.Cart.Where(x => x.ShoppingCartTypeId == ShoppingCartType.Auctions))- {- var bid = (await _auctionService.GetBidsByProductId(sc.Id)).FirstOrDefault(x => x.CustomerId == details.Customer.Id);- if (bid == null) continue;- bid.OrderId = order.Id;- await _auctionService.UpdateBid(bid);- }+ await _auctionService.UpdateAuctionEnded(product, true, true);+ await _auctionService.UpdateHighestBid(product, product.Price, order.CustomerId);+ await _messageProviderService.SendAuctionEndedBinCustomerMessage(product, order.CustomerId,+ order.CustomerLanguageId, order.StoreId);+ await _auctionService.InsertBid(new Bid {+ CustomerId = order.CustomerId,+ OrderId = order.Id,+ Amount = product.Price,+ Date = DateTime.UtcNow,+ ProductId = product.Id,+ StoreId = order.StoreId,+ Win = true,+ Bin = true+ });}- protected virtual async Task InsertDiscountUsageHistory(Order order, PlaceOrderContainer details)++ if (product.ProductTypeId == ProductType.Auction && _orderSettings.UnpublishAuctionProduct)+ await _productService.UnPublishProduct(product);+ }++ protected virtual async Task UpdateBids(Order order, PlaceOrderContainer details)+ {+ foreach (var sc in details.Cart.Where(x => x.ShoppingCartTypeId == ShoppingCartType.Auctions)){- foreach (var discount in details.AppliedDiscounts)- {- var duh = new DiscountUsageHistory {- DiscountId = discount.DiscountId,- CouponCode = discount.CouponCode,- OrderId = order.Id,- CustomerId = order.CustomerId- };- await _discountService.InsertDiscountUsageHistory(duh);- }+ var bid = (await _auctionService.GetBidsByProductId(sc.Id)).FirstOrDefault(x =>+ x.CustomerId == details.Customer.Id);+ if (bid == null) continue;+ bid.OrderId = order.Id;+ await _auctionService.UpdateBid(bid);}+ }- protected virtual async Task AppliedGiftVouchers(Order order, PlaceOrderContainer details)+ protected virtual async Task InsertDiscountUsageHistory(Order order, PlaceOrderContainer details)+ {+ foreach (var discount in details.AppliedDiscounts){- foreach (var agc in details.AppliedGiftVouchers)- {- var amountUsed = agc.AmountCanBeUsed;- var giftVoucherUsageHistory = new GiftVoucherUsageHistory {- GiftVoucherId = agc.GiftVoucher.Id,- UsedWithOrderId = order.Id,- UsedValue = amountUsed,- CreatedOnUtc = DateTime.UtcNow- };- agc.GiftVoucher.GiftVoucherUsageHistory.Add(giftVoucherUsageHistory);- await _giftVoucherService.UpdateGiftVoucher(agc.GiftVoucher);- }+ var duh = new DiscountUsageHistory {+ DiscountId = discount.DiscountId,+ CouponCode = discount.CouponCode,+ OrderId = order.Id,+ CustomerId = order.CustomerId+ };+ await _discountService.InsertDiscountUsageHistory(duh);}+ }- /// <summary>- /// Prepare order header- /// </summary>- /// <returns>Order</returns>- protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction,- ProcessPaymentResult processPaymentResult, PlaceOrderContainer details)+ protected virtual async Task AppliedGiftVouchers(Order order, PlaceOrderContainer details)+ {+ foreach (var agc in details.AppliedGiftVouchers){- var paymentStatus = PaymentStatus.Pending;-- if (processPaymentResult.NewPaymentTransactionStatus == TransactionStatus.Paid && processPaymentResult.PaidAmount == details.OrderTotal)- paymentStatus = PaymentStatus.Paid;-- if (processPaymentResult.NewPaymentTransactionStatus == TransactionStatus.Paid &&- processPaymentResult.PaidAmount > 0 &&- processPaymentResult.PaidAmount < details.OrderTotal)- paymentStatus = PaymentStatus.PartiallyPaid;--- var order = new Order {- StoreId = paymentTransaction.StoreId,- OrderGuid = paymentTransaction.OrderGuid,- Code = paymentTransaction.OrderCode,- CustomerId = details.Customer.Id,- OwnerId = string.IsNullOrEmpty(details.Customer.OwnerId) ? details.Customer.Id : details.Customer.OwnerId,- SeId = details.Customer.SeId,- CustomerLanguageId = details.Language.Id,- CustomerTaxDisplayTypeId = details.TaxDisplayType,- CustomerIp = details.Customer.LastIpAddress,- OrderSubtotalInclTax = Math.Round(details.OrderSubTotalInclTax, 6),- OrderSubtotalExclTax = Math.Round(details.OrderSubTotalExclTax, 6),- OrderSubTotalDiscountInclTax = Math.Round(details.OrderSubTotalDiscountInclTax, 6),- OrderSubTotalDiscountExclTax = Math.Round(details.OrderSubTotalDiscountExclTax, 6),- OrderShippingInclTax = Math.Round(details.OrderShippingTotalInclTax, 6),- OrderShippingExclTax = Math.Round(details.OrderShippingTotalExclTax, 6),- PaymentMethodAdditionalFeeInclTax = Math.Round(details.PaymentAdditionalFeeInclTax, 6),- PaymentMethodAdditionalFeeExclTax = Math.Round(details.PaymentAdditionalFeeExclTax, 6),- OrderTax = Math.Round(details.OrderTaxTotal, 6),- OrderTotal = Math.Round(details.OrderTotal, 6),- RefundedAmount = 0,- OrderDiscount = Math.Round(details.OrderDiscountAmount, 6),- CheckoutAttributeDescription = details.CheckoutAttributeDescription,- CheckoutAttributes = details.CheckoutAttributes,- CustomerCurrencyCode = details.Currency.CurrencyCode,- PrimaryCurrencyCode = details.PrimaryCurrencyCode,- CurrencyRate = details.CurrencyRate,- Rate = details.Currency.Rate,- AffiliateId = details.AffiliateId,- OrderStatusId = (int)OrderStatusSystem.Pending,- PaymentMethodSystemName = paymentTransaction.PaymentMethodSystemName,- PaymentOptionAttribute = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PaymentOptionAttribute, paymentTransaction.StoreId),- PaymentStatusId = paymentStatus,- PaidAmount = processPaymentResult.PaidAmount,- PaidDateUtc = processPaymentResult.PaidAmount > 0 ? DateTime.UtcNow : null,- BillingAddress = details.BillingAddress,- ShippingAddress = details.ShippingAddress,- ShippingStatusId = details.ShippingStatus,- ShippingMethod = details.ShippingMethodName,- PickUpInStore = details.PickUpInStore,- PickupPoint = details.PickupPoint,- ShippingRateProviderSystemName = details.ShippingRateProviderSystemName,- VatNumber = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumber),- VatNumberStatusId = details.Customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId),- CompanyName = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Company),- FirstName = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.FirstName),- LastName = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastName),- CustomerEmail = details.Customer.Email,- UrlReferrer = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastUrlReferrer),- ShippingOptionAttributeDescription = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ShippingOptionAttributeDescription, paymentTransaction.StoreId),- ShippingOptionAttribute = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ShippingOptionAttribute, paymentTransaction.StoreId),- RedeemedLoyaltyPoints = details.RedeemedLoyaltyPoints,- RedeemedLoyaltyPointsAmount = details.RedeemedLoyaltyPointsAmount,- LoyaltyPointsWereAdded = details.RedeemedLoyaltyPoints > 0,- IsRecurring = details.IsRecurring,- RecurringCycleLength = details.RecurringCycleLength,- RecurringCyclePeriodId = details.RecurringCyclePeriodId,- RecurringTotalCycles = details.RecurringTotalCycles+ var amountUsed = agc.AmountCanBeUsed;+ var giftVoucherUsageHistory = new GiftVoucherUsageHistory {+ GiftVoucherId = agc.GiftVoucher.Id,+ UsedWithOrderId = order.Id,+ UsedValue = amountUsed,+ CreatedOnUtc = DateTime.UtcNow};-- foreach (var item in details.Taxes)- {- order.OrderTaxes.Add(item);- }- return order;+ agc.GiftVoucher.GiftVoucherUsageHistory.Add(giftVoucherUsageHistory);+ await _giftVoucherService.UpdateGiftVoucher(agc.GiftVoucher);}+ }++ /// <summary>+ /// Prepare order header+ /// </summary>+ /// <returns>Order</returns>+ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction,+ ProcessPaymentResult processPaymentResult, PlaceOrderContainer details)+ {+ var paymentStatus = PaymentStatus.Pending;++ if (processPaymentResult.NewPaymentTransactionStatus == TransactionStatus.Paid &&+ processPaymentResult.PaidAmount == details.OrderTotal)+ paymentStatus = PaymentStatus.Paid;++ if (processPaymentResult.NewPaymentTransactionStatus == TransactionStatus.Paid &&+ processPaymentResult.PaidAmount > 0 &&+ processPaymentResult.PaidAmount < details.OrderTotal)+ paymentStatus = PaymentStatus.PartiallyPaid;+++ var order = new Order {+ StoreId = paymentTransaction.StoreId,+ OrderGuid = paymentTransaction.OrderGuid,+ Code = paymentTransaction.OrderCode,+ CustomerId = details.Customer.Id,+ OwnerId = string.IsNullOrEmpty(details.Customer.OwnerId) ? details.Customer.Id : details.Customer.OwnerId,+ SeId = details.Customer.SeId,+ CustomerLanguageId = details.Language.Id,+ CustomerTaxDisplayTypeId = details.TaxDisplayType,+ CustomerIp = details.Customer.LastIpAddress,+ OrderSubtotalInclTax = Math.Round(details.OrderSubTotalInclTax, 6),+ OrderSubtotalExclTax = Math.Round(details.OrderSubTotalExclTax, 6),+ OrderSubTotalDiscountInclTax = Math.Round(details.OrderSubTotalDiscountInclTax, 6),+ OrderSubTotalDiscountExclTax = Math.Round(details.OrderSubTotalDiscountExclTax, 6),+ OrderShippingInclTax = Math.Round(details.OrderShippingTotalInclTax, 6),+ OrderShippingExclTax = Math.Round(details.OrderShippingTotalExclTax, 6),+ PaymentMethodAdditionalFeeInclTax = Math.Round(details.PaymentAdditionalFeeInclTax, 6),+ PaymentMethodAdditionalFeeExclTax = Math.Round(details.PaymentAdditionalFeeExclTax, 6),+ OrderTax = Math.Round(details.OrderTaxTotal, 6),+ OrderTotal = Math.Round(details.OrderTotal, 6),+ RefundedAmount = 0,+ OrderDiscount = Math.Round(details.OrderDiscountAmount, 6),+ CheckoutAttributeDescription = details.CheckoutAttributeDescription,+ CheckoutAttributes = details.CheckoutAttributes,+ CustomerCurrencyCode = details.Currency.CurrencyCode,+ PrimaryCurrencyCode = details.PrimaryCurrencyCode,+ CurrencyRate = details.CurrencyRate,+ Rate = details.Currency.Rate,+ AffiliateId = details.AffiliateId,+ OrderStatusId = (int)OrderStatusSystem.Pending,+ PaymentMethodSystemName = paymentTransaction.PaymentMethodSystemName,+ PaymentOptionAttribute =+ details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PaymentOptionAttribute,+ paymentTransaction.StoreId),+ PaymentStatusId = paymentStatus,+ PaidAmount = processPaymentResult.PaidAmount,+ PaidDateUtc = processPaymentResult.PaidAmount > 0 ? DateTime.UtcNow : null,+ BillingAddress = details.BillingAddress,+ ShippingAddress = details.ShippingAddress,+ ShippingStatusId = details.ShippingStatus,+ ShippingMethod = details.ShippingMethodName,+ PickUpInStore = details.PickUpInStore,+ PickupPoint = details.PickupPoint,+ ShippingRateProviderSystemName = details.ShippingRateProviderSystemName,+ VatNumber = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.VatNumber),+ VatNumberStatusId =+ details.Customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.VatNumberStatusId),+ CompanyName = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.Company),+ FirstName = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.FirstName),+ LastName = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastName),+ CustomerEmail = details.Customer.Email,+ UrlReferrer = details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastUrlReferrer),+ ShippingOptionAttributeDescription =+ details.Customer.GetUserFieldFromEntity<string>(+ SystemCustomerFieldNames.ShippingOptionAttributeDescription, paymentTransaction.StoreId),+ ShippingOptionAttribute =+ details.Customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ShippingOptionAttribute,+ paymentTransaction.StoreId),+ RedeemedLoyaltyPoints = details.RedeemedLoyaltyPoints,+ RedeemedLoyaltyPointsAmount = details.RedeemedLoyaltyPointsAmount,+ LoyaltyPointsWereAdded = details.RedeemedLoyaltyPoints > 0,+ IsRecurring = details.IsRecurring,+ RecurringCycleLength = details.RecurringCycleLength,+ RecurringCyclePeriodId = details.RecurringCyclePeriodId,+ RecurringTotalCycles = details.RecurringTotalCycles+ };++ foreach (var item in details.Taxes) order.OrderTaxes.Add(item);+ return order;+ }- /// <summary>- /// Save order details- /// </summary>- /// <param name="details">Place order container</param>- /// <param name="order">Order</param>- /// <returns>Order</returns>- protected virtual async Task<Order> SaveOrderDetails(PlaceOrderContainer details, Order order)+ /// <summary>+ /// Save order details+ /// </summary>+ /// <param name="details">Place order container</param>+ /// <param name="order">Order</param>+ /// <returns>Order</returns>+ protected virtual async Task<Order> SaveOrderDetails(PlaceOrderContainer details, Order order)+ {+ //move shopping cart items to order items+ foreach (var sc in details.Cart){- //move shopping cart items to order items- foreach (var sc in details.Cart)- {- var product = await _productService.GetProductById(sc.ProductId);+ var product = await _productService.GetProductById(sc.ProductId);- var orderItem = await PrepareOrderItem(sc, product, details);+ var orderItem = await PrepareOrderItem(sc, product, details);- order.OrderItems.Add(orderItem);+ order.OrderItems.Add(orderItem);- //gift vouchers- if (product.IsGiftVoucher)- {- await GenerateGiftVoucher(details, sc, order, orderItem, product);- }+ //gift vouchers+ if (product.IsGiftVoucher) await GenerateGiftVoucher(details, sc, order, orderItem, product);- //update auction ended- await UpdateAuctionEnded(sc, product, order);+ //update auction ended+ await UpdateAuctionEnded(sc, product, order);- //inventory- await _inventoryManageService.AdjustReserved(product, -sc.Quantity, sc.Attributes, orderItem.WarehouseId);+ //inventory+ await _inventoryManageService.AdjustReserved(product, -sc.Quantity, sc.Attributes, orderItem.WarehouseId);- //update sold- _ = _productService.IncrementProductField(product, x => x.Sold, sc.Quantity);- }+ //update sold+ _ = _productService.IncrementProductField(product, x => x.Sold, sc.Quantity);+ }- //insert order- await _orderService.InsertOrder(order);+ //insert order+ await _orderService.InsertOrder(order);- //update reservation- await UpdateProductReservation(order, details);+ //update reservation+ await UpdateProductReservation(order, details);- //update bids- await UpdateBids(order, details);+ //update bids+ await UpdateBids(order, details);- //clear shopping cart- await _customerService.ClearShoppingCartItem(order.CustomerId, details.Cart);+ //clear shopping cart+ await _customerService.ClearShoppingCartItem(order.CustomerId, details.Cart);- //discount usage history- await InsertDiscountUsageHistory(order, details);+ //discount usage history+ await InsertDiscountUsageHistory(order, details);- //gift voucher usage history- if (details.AppliedGiftVouchers != null)- await AppliedGiftVouchers(order, details);+ //gift voucher usage history+ if (details.AppliedGiftVouchers != null)+ await AppliedGiftVouchers(order, details);- //reset checkout data- await _customerService.ResetCheckoutData(details.Customer, order.StoreId, clearCouponCodes: true, clearCheckoutAttributes: true);+ //reset checkout data+ await _customerService.ResetCheckoutData(details.Customer, order.StoreId, true, true);- return order;- }+ return order;+ }- /// <summary>- /// Send notification order- /// </summary>- /// <param name="scopeFactory"></param>- /// <param name="order">Order</param>- /// <param name="customer"></param>- /// <param name="originalCustomerIfImpersonated"></param>- protected virtual async Task SendNotification(IServiceScopeFactory scopeFactory, Order order, Customer customer, Customer originalCustomerIfImpersonated)+ /// <summary>+ /// Send notification order+ /// </summary>+ /// <param name="scopeFactory"></param>+ /// <param name="order">Order</param>+ /// <param name="customer"></param>+ /// <param name="originalCustomerIfImpersonated"></param>+ protected virtual async Task SendNotification(IServiceScopeFactory scopeFactory, Order order, Customer customer,+ Customer originalCustomerIfImpersonated)+ {+ using var scope = scopeFactory.CreateScope();++ var workContext = scope.ServiceProvider.GetService<IWorkContextSetter>();+ await workContext.SetCurrentCustomer(customer);+ await workContext.SetWorkingLanguage(customer);+ await workContext.SetWorkingCurrency(customer);+ await workContext.SetTaxDisplayType(customer);++ var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();+ var messageProviderService = scope.ServiceProvider.GetRequiredService<IMessageProviderService>();+ var orderSettings = scope.ServiceProvider.GetRequiredService<OrderSettings>();+ var languageSettings = scope.ServiceProvider.GetRequiredService<LanguageSettings>();+ var pdfService = scope.ServiceProvider.GetRequiredService<IPdfService>();+ var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();+ try{- using var scope = scopeFactory.CreateScope();-- var workContext = scope.ServiceProvider.GetService<IWorkContextSetter>();- await workContext.SetCurrentCustomer(customer);- await workContext.SetWorkingLanguage(customer);- await workContext.SetWorkingCurrency(customer);- await workContext.SetTaxDisplayType(customer);-- var orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();- var messageProviderService = scope.ServiceProvider.GetRequiredService<IMessageProviderService>();- var orderSettings = scope.ServiceProvider.GetRequiredService<OrderSettings>();- var languageSettings = scope.ServiceProvider.GetRequiredService<LanguageSettings>();- var pdfService = scope.ServiceProvider.GetRequiredService<IPdfService>();- var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();- try- {- //notes, messages- if (originalCustomerIfImpersonated != null)- {- //this order is placed by a store administrator impersonating a customer- await orderService.InsertOrderNote(new OrderNote {- Note =- $"Order placed by a store owner ('{originalCustomerIfImpersonated.Email}'. ID = {originalCustomerIfImpersonated.Id}) impersonating the customer.",- DisplayToCustomer = false,- OrderId = order.Id- });- }- else- {- await orderService.InsertOrderNote(new OrderNote {- Note = "Order placed",- DisplayToCustomer = false,- OrderId = order.Id-- });- }+ //notes, messages+ if (originalCustomerIfImpersonated != null)+ //this order is placed by a store administrator impersonating a customer+ await orderService.InsertOrderNote(new OrderNote {+ Note =+ $"Order placed by a store owner ('{originalCustomerIfImpersonated.Email}'. ID = {originalCustomerIfImpersonated.Id}) impersonating the customer.",+ DisplayToCustomer = false,+ OrderId = order.Id+ });+ else+ await orderService.InsertOrderNote(new OrderNote {+ Note = "Order placed",+ DisplayToCustomer = false,+ OrderId = order.Id+ });- //send email notifications- await messageProviderService.SendOrderPlacedStoreOwnerMessage(order, customer, languageSettings.DefaultAdminLanguageId);+ //send email notifications+ await messageProviderService.SendOrderPlacedStoreOwnerMessage(order, customer,+ languageSettings.DefaultAdminLanguageId);- string orderPlacedAttachmentFilePath = string.Empty, orderPlacedAttachmentFileName = string.Empty;- var orderPlacedAttachments = new List<string>();+ string orderPlacedAttachmentFilePath = string.Empty, orderPlacedAttachmentFileName = string.Empty;+ var orderPlacedAttachments = new List<string>();- try- {- orderPlacedAttachmentFilePath = orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !orderSettings.AttachPdfInvoiceToBinary ?- await pdfService.PrintOrderToPdf(order, order.CustomerLanguageId) : null;- orderPlacedAttachmentFileName = orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !orderSettings.AttachPdfInvoiceToBinary ?- "order.pdf" : null;- orderPlacedAttachments = orderSettings.AttachPdfInvoiceToOrderPlacedEmail && orderSettings.AttachPdfInvoiceToBinary ? [- await pdfService.SaveOrderToBinary(order, order.CustomerLanguageId)- ]- : [];- }- catch (Exception ex)- {- _logger.LogError(ex, "Error - order placed attachment file {OrderOrderNumber}", order.OrderNumber);- }-- await messageProviderService- .SendOrderPlacedCustomerMessage(order, customer, order.CustomerLanguageId, orderPlacedAttachmentFilePath, orderPlacedAttachmentFileName, orderPlacedAttachments);-- if (order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId)))- {- var vendors = await mediator.Send(new GetVendorsInOrderQuery { Order = order });- foreach (var vendor in vendors)- {- await messageProviderService.SendOrderPlacedVendorMessage(order, customer, vendor, languageSettings.DefaultAdminLanguageId);- }- }+ try+ {+ orderPlacedAttachmentFilePath =+ orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !orderSettings.AttachPdfInvoiceToBinary+ ? await pdfService.PrintOrderToPdf(order, order.CustomerLanguageId)+ : null;+ orderPlacedAttachmentFileName =+ orderSettings.AttachPdfInvoiceToOrderPlacedEmail && !orderSettings.AttachPdfInvoiceToBinary+ ? "order.pdf"+ : null;+ orderPlacedAttachments = orderSettings.AttachPdfInvoiceToOrderPlacedEmail &&+ orderSettings.AttachPdfInvoiceToBinary+ ? [+ await pdfService.SaveOrderToBinary(order, order.CustomerLanguageId)+ ]+ : [];}- catch (Exception e)+ catch (Exception ex){- _logger.LogError(e, "Place order send notification error");+ _logger.LogError(ex, "Error - order placed attachment file {OrderOrderNumber}", order.OrderNumber);}+ await messageProviderService+ .SendOrderPlacedCustomerMessage(order, customer, order.CustomerLanguageId,+ orderPlacedAttachmentFilePath, orderPlacedAttachmentFileName, orderPlacedAttachments);++ if (order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId)))+ {+ var vendors = await mediator.Send(new GetVendorsInOrderQuery { Order = order });+ foreach (var vendor in vendors)+ await messageProviderService.SendOrderPlacedVendorMessage(order, customer, vendor,+ languageSettings.DefaultAdminLanguageId);+ }+ }+ catch (Exception e)+ {+ _logger.LogError(e, "Place order send notification error");}}-}-+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PrepareOrderCodeCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PrepareOrderCodeCommandHandler.csindex d9b32cb4d..25160a150 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PrepareOrderCodeCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PrepareOrderCodeCommandHandler.cs@@ -1,34 +1,33 @@-using Grand.Domain.Orders;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class PrepareOrderCodeCommandHandler : IRequestHandler<PrepareOrderCodeCommand, string>{- public class PrepareOrderCodeCommandHandler : IRequestHandler<PrepareOrderCodeCommand, string>- {- private readonly OrderSettings _orderSettings;+ private static readonly Random random = new();+ private readonly OrderSettings _orderSettings;- public PrepareOrderCodeCommandHandler(OrderSettings orderSettings)- {- _orderSettings = orderSettings;- }+ public PrepareOrderCodeCommandHandler(OrderSettings orderSettings)+ {+ _orderSettings = orderSettings;+ }- public async Task<string> Handle(PrepareOrderCodeCommand request, CancellationToken cancellationToken)- {- var length = _orderSettings.LengthCode;- if (length == 0)- length = 8;+ public async Task<string> Handle(PrepareOrderCodeCommand request, CancellationToken cancellationToken)+ {+ var length = _orderSettings.LengthCode;+ if (length == 0)+ length = 8;- var code = RandomString(length);- return await Task.FromResult(code);- }+ var code = RandomString(length);+ return await Task.FromResult(code);+ }- private string RandomString(int length)- {- const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";- return new string(Enumerable.Repeat(chars, length)- .Select(s => s[random.Next(s.Length)]).ToArray());- }- private static Random random = new Random();+ private string RandomString(int length)+ {+ const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";+ return new string(Enumerable.Repeat(chars, length)+ .Select(s => s[random.Next(s.Length)]).ToArray());}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.csindex 45102c536..664e46d58 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs@@ -1,87 +1,91 @@using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Events.Checkout.Orders;-using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Business.Core.Interfaces.Common.Pdf;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Localization;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class ProcessOrderPaidCommandHandler : IRequestHandler<ProcessOrderPaidCommand, bool>{- public class ProcessOrderPaidCommandHandler : IRequestHandler<ProcessOrderPaidCommand, bool>- {- private readonly IMessageProviderService _messageProviderService;- private readonly ICustomerService _customerService;- private readonly IMediator _mediator;- private readonly IPdfService _pdfService;- private readonly OrderSettings _orderSettings;- private readonly LanguageSettings _languageSettings;+ private readonly ICustomerService _customerService;+ private readonly LanguageSettings _languageSettings;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly OrderSettings _orderSettings;+ private readonly IPdfService _pdfService;- public ProcessOrderPaidCommandHandler(- IMessageProviderService messageProviderService,- ICustomerService customerService,- IMediator mediator,- IPdfService pdfService,- OrderSettings orderSettings,- LanguageSettings languageSettings)- {- _messageProviderService = messageProviderService;- _customerService = customerService;- _mediator = mediator;- _pdfService = pdfService;- _orderSettings = orderSettings;- _languageSettings = languageSettings;- }+ public ProcessOrderPaidCommandHandler(+ IMessageProviderService messageProviderService,+ ICustomerService customerService,+ IMediator mediator,+ IPdfService pdfService,+ OrderSettings orderSettings,+ LanguageSettings languageSettings)+ {+ _messageProviderService = messageProviderService;+ _customerService = customerService;+ _mediator = mediator;+ _pdfService = pdfService;+ _orderSettings = orderSettings;+ _languageSettings = languageSettings;+ }- public async Task<bool> Handle(ProcessOrderPaidCommand request, CancellationToken cancellationToken)- {- await ProcessOrderPaid(request.Order);- return true;- }+ public async Task<bool> Handle(ProcessOrderPaidCommand request, CancellationToken cancellationToken)+ {+ await ProcessOrderPaid(request.Order);+ return true;+ }- /// <summary>- /// Process order paid status- /// </summary>- /// <param name="order">Order</param>- protected virtual async Task ProcessOrderPaid(Order order)- {- if (order == null)- throw new ArgumentNullException(nameof(order));+ /// <summary>+ /// Process order paid status+ /// </summary>+ /// <param name="order">Order</param>+ protected virtual async Task ProcessOrderPaid(Order order)+ {+ if (order == null)+ throw new ArgumentNullException(nameof(order));- //raise event- await _mediator.Publish(new OrderPaidEvent(order));+ //raise event+ await _mediator.Publish(new OrderPaidEvent(order));- //order paid email notification- if (order.OrderTotal != 0)- {- var customer = await _customerService.GetCustomerById(order.CustomerId);+ //order paid email notification+ if (order.OrderTotal != 0)+ {+ var customer = await _customerService.GetCustomerById(order.CustomerId);- var orderPaidAttachmentFilePath = _orderSettings.AttachPdfInvoiceToOrderPaidEmail && !_orderSettings.AttachPdfInvoiceToBinary ?- await _pdfService.PrintOrderToPdf(order, "")+ var orderPaidAttachmentFilePath =+ _orderSettings.AttachPdfInvoiceToOrderPaidEmail && !_orderSettings.AttachPdfInvoiceToBinary+ ? await _pdfService.PrintOrderToPdf(order, "")+ : null;+ var orderPaidAttachmentFileName =+ _orderSettings.AttachPdfInvoiceToOrderPaidEmail && !_orderSettings.AttachPdfInvoiceToBinary+ ? "order.pdf": null;- var orderPaidAttachmentFileName = _orderSettings.AttachPdfInvoiceToOrderPaidEmail && !_orderSettings.AttachPdfInvoiceToBinary ?- "order.pdf" : null;- var orderPaidAttachments = _orderSettings.AttachPdfInvoiceToOrderPaidEmail && _orderSettings.AttachPdfInvoiceToBinary ? [+ var orderPaidAttachments =+ _orderSettings.AttachPdfInvoiceToOrderPaidEmail && _orderSettings.AttachPdfInvoiceToBinary+ ? [await _pdfService.SaveOrderToBinary(order, "")]: new List<string>();- await _messageProviderService.SendOrderPaidCustomerMessage(order, customer, order.CustomerLanguageId,- orderPaidAttachmentFilePath, orderPaidAttachmentFileName, orderPaidAttachments);+ await _messageProviderService.SendOrderPaidCustomerMessage(order, customer, order.CustomerLanguageId,+ orderPaidAttachmentFilePath, orderPaidAttachmentFileName, orderPaidAttachments);- await _messageProviderService.SendOrderPaidStoreOwnerMessage(order, customer, _languageSettings.DefaultAdminLanguageId);- if (order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId)))- {- var vendors = await _mediator.Send(new GetVendorsInOrderQuery { Order = order });- foreach (var vendor in vendors)- {- await _messageProviderService.SendOrderPaidVendorMessage(order, vendor, _languageSettings.DefaultAdminLanguageId);- }- }+ await _messageProviderService.SendOrderPaidStoreOwnerMessage(order, customer,+ _languageSettings.DefaultAdminLanguageId);+ if (order.OrderItems.Any(x => !string.IsNullOrEmpty(x.VendorId)))+ {+ var vendors = await _mediator.Send(new GetVendorsInOrderQuery { Order = order });+ foreach (var vendor in vendors)+ await _messageProviderService.SendOrderPaidVendorMessage(order, vendor,+ _languageSettings.DefaultAdminLanguageId);}}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.csindex 20e72d129..80012581a 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs@@ -1,67 +1,64 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Catalog;using Grand.Domain.Orders;using Grand.Domain.Tax;using MediatR;-using Grand.Business.Core.Utilities.Checkout;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class ReOrderCommandHandler : IRequestHandler<ReOrderCommand, IList<string>>{- public class ReOrderCommandHandler : IRequestHandler<ReOrderCommand, IList<string>>- {- private readonly ICustomerService _customerService;- private readonly IProductService _productService;- private readonly IShoppingCartService _shoppingCartService;- private readonly TaxSettings _taxSettings;+ private readonly ICustomerService _customerService;+ private readonly IProductService _productService;+ private readonly IShoppingCartService _shoppingCartService;+ private readonly TaxSettings _taxSettings;- public ReOrderCommandHandler(- ICustomerService customerService,- IProductService productService,- IShoppingCartService shoppingCartService,- TaxSettings taxSettings)- {- _customerService = customerService;- _productService = productService;- _shoppingCartService = shoppingCartService;- _taxSettings = taxSettings;- }+ public ReOrderCommandHandler(+ ICustomerService customerService,+ IProductService productService,+ IShoppingCartService shoppingCartService,+ TaxSettings taxSettings)+ {+ _customerService = customerService;+ _productService = productService;+ _shoppingCartService = shoppingCartService;+ _taxSettings = taxSettings;+ }- public async Task<IList<string>> Handle(ReOrderCommand request, CancellationToken cancellationToken)- {- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ public async Task<IList<string>> Handle(ReOrderCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- var warnings = new List<string>();- var customer = await _customerService.GetCustomerById(request.Order.CustomerId);+ var warnings = new List<string>();+ var customer = await _customerService.GetCustomerById(request.Order.CustomerId);- foreach (var orderItem in request.Order.OrderItems)+ foreach (var orderItem in request.Order.OrderItems)+ {+ var product = await _productService.GetProductById(orderItem.ProductId);+ if (product != null){- var product = await _productService.GetProductById(orderItem.ProductId);- if (product != null)- {- if (product.ProductTypeId == ProductType.SimpleProduct)- {- warnings.AddRange((await _shoppingCartService.AddToCart(customer, orderItem.ProductId,- ShoppingCartType.ShoppingCart, request.Order.StoreId, orderItem.WarehouseId,- orderItem.Attributes,- product.EnteredPrice ?- _taxSettings.PricesIncludeTax ? orderItem.UnitPriceInclTax : orderItem.UnitPriceExclTax+ if (product.ProductTypeId == ProductType.SimpleProduct)+ warnings.AddRange((await _shoppingCartService.AddToCart(customer, orderItem.ProductId,+ ShoppingCartType.ShoppingCart, request.Order.StoreId, orderItem.WarehouseId,+ orderItem.Attributes,+ product.EnteredPrice+ ? _taxSettings.PricesIncludeTax ? orderItem.UnitPriceInclTax : orderItem.UnitPriceExclTax: (double?)default,- orderItem.RentalStartDateUtc, orderItem.RentalEndDateUtc,- orderItem.Quantity, false,- validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false })).warnings);- }- }- else- {- warnings.Add("Product is not available");- }+ orderItem.RentalStartDateUtc, orderItem.RentalEndDateUtc,+ orderItem.Quantity, false,+ validator: new ShoppingCartValidatorOptions { GetRequiredProductWarnings = false })).warnings);+ }+ else+ {+ warnings.Add("Product is not available");}-- return warnings;}++ return warnings;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.csindex 26549c1c7..2ef9b6d04 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs@@ -5,60 +5,63 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class ReduceLoyaltyPointsCommandHandler : IRequestHandler<ReduceLoyaltyPointsCommand, bool>{- public class ReduceLoyaltyPointsCommandHandler : IRequestHandler<ReduceLoyaltyPointsCommand, bool>- {- private readonly ICustomerService _customerService;- private readonly ILoyaltyPointsService _loyaltyPointsService;- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly ITranslationService _translationService;- private readonly ICurrencyService _currencyService;+ private readonly ICurrencyService _currencyService;+ private readonly ICustomerService _customerService;+ private readonly ILoyaltyPointsService _loyaltyPointsService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly ITranslationService _translationService;- public ReduceLoyaltyPointsCommandHandler(- ICustomerService customerService,- ILoyaltyPointsService loyaltyPointsService,- IMediator mediator,- IOrderService orderService,- ITranslationService translationService,- ICurrencyService currencyService)- {- _customerService = customerService;- _loyaltyPointsService = loyaltyPointsService;- _mediator = mediator;- _orderService = orderService;- _translationService = translationService;- _currencyService = currencyService;- }+ public ReduceLoyaltyPointsCommandHandler(+ ICustomerService customerService,+ ILoyaltyPointsService loyaltyPointsService,+ IMediator mediator,+ IOrderService orderService,+ ITranslationService translationService,+ ICurrencyService currencyService)+ {+ _customerService = customerService;+ _loyaltyPointsService = loyaltyPointsService;+ _mediator = mediator;+ _orderService = orderService;+ _translationService = translationService;+ _currencyService = currencyService;+ }- public async Task<bool> Handle(ReduceLoyaltyPointsCommand request, CancellationToken cancellationToken)- {- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ public async Task<bool> Handle(ReduceLoyaltyPointsCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- var customer = await _customerService.GetCustomerById(request.Order.CustomerId);+ var customer = await _customerService.GetCustomerById(request.Order.CustomerId);- var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode);+ var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode);- var amount = await _currencyService.ConvertToPrimaryStoreCurrency(request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency);+ var amount =+ await _currencyService.ConvertToPrimaryStoreCurrency(+ request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency);- var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount }, cancellationToken);- if (points <= 0)- return false;+ var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount },+ cancellationToken);+ if (points <= 0)+ return false;- if (request.Order.CalcLoyaltyPoints < points)- return false;+ if (request.Order.CalcLoyaltyPoints < points)+ return false;- //reduce loyalty points- await _loyaltyPointsService.AddLoyaltyPointsHistory(customer.Id, -points, request.Order.StoreId,- string.Format(_translationService.GetResource("LoyaltyPoints.Message.ReducedForOrder"), request.Order.OrderNumber));+ //reduce loyalty points+ await _loyaltyPointsService.AddLoyaltyPointsHistory(customer.Id, -points, request.Order.StoreId,+ string.Format(_translationService.GetResource("LoyaltyPoints.Message.ReducedForOrder"),+ request.Order.OrderNumber));- request.Order.CalcLoyaltyPoints -= points;- //assign to order- await _orderService.UpdateOrder(request.Order);+ request.Order.CalcLoyaltyPoints -= points;+ //assign to order+ await _orderService.UpdateOrder(request.Order);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.csindex 441963f63..cb33a7dd1 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs@@ -2,109 +2,114 @@using Grand.Business.Core.Events.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Utilities.Checkout;using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Localization;+using Grand.Domain.Payments;using MediatR;using Microsoft.Extensions.Logging;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class RefundCommandHandler : IRequestHandler<RefundCommand, IList<string>>{- public class RefundCommandHandler : IRequestHandler<RefundCommand, IList<string>>+ private readonly LanguageSettings _languageSettings;+ private readonly ILogger<RefundCommandHandler> _logger;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly IPaymentService _paymentService;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public RefundCommandHandler(+ IMediator mediator,+ IPaymentService paymentService,+ IPaymentTransactionService paymentTransactionService,+ IOrderService orderService,+ IMessageProviderService messageProviderService,+ ILogger<RefundCommandHandler> logger,+ LanguageSettings languageSettings){- private readonly IMediator _mediator;- private readonly IPaymentService _paymentService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IOrderService _orderService;- private readonly IMessageProviderService _messageProviderService;- private readonly ILogger<RefundCommandHandler> _logger;- private readonly LanguageSettings _languageSettings;-- public RefundCommandHandler(- IMediator mediator,- IPaymentService paymentService,- IPaymentTransactionService paymentTransactionService,- IOrderService orderService,- IMessageProviderService messageProviderService,- ILogger<RefundCommandHandler> logger,- LanguageSettings languageSettings)- {- _mediator = mediator;- _paymentService = paymentService;- _paymentTransactionService = paymentTransactionService;- _orderService = orderService;- _messageProviderService = messageProviderService;- _logger = logger;- _languageSettings = languageSettings;- }+ _mediator = mediator;+ _paymentService = paymentService;+ _paymentTransactionService = paymentTransactionService;+ _orderService = orderService;+ _messageProviderService = messageProviderService;+ _logger = logger;+ _languageSettings = languageSettings;+ }- public async Task<IList<string>> Handle(RefundCommand command, CancellationToken cancellationToken)- {- var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ public async Task<IList<string>> Handle(RefundCommand command, CancellationToken cancellationToken)+ {+ var paymentTransaction = command.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(command.PaymentTransaction));- //if (!await CanRefund(order))- // throw new GrandException("Cannot do refund for order.");+ //if (!await CanRefund(order))+ // throw new GrandException("Cannot do refund for order.");- var request = new RefundPaymentRequest();- RefundPaymentResult result = null;- try+ var request = new RefundPaymentRequest();+ RefundPaymentResult result = null;+ try+ {+ request.PaymentTransaction = paymentTransaction;+ request.AmountToRefund = paymentTransaction.PaidAmount;+ request.IsPartialRefund = false;+ result = await _paymentService.Refund(request);+ if (result.Success){- request.PaymentTransaction = paymentTransaction;- request.AmountToRefund = paymentTransaction.PaidAmount;- request.IsPartialRefund = false;- result = await _paymentService.Refund(request);- if (result.Success)- {- paymentTransaction.TransactionStatus = result.NewTransactionStatus;- paymentTransaction.RefundedAmount += request.AmountToRefund;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);-- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ paymentTransaction.TransactionStatus = result.NewTransactionStatus;+ paymentTransaction.RefundedAmount += request.AmountToRefund;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- var totalAmountRefunded = order.RefundedAmount + request.AmountToRefund;+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));- //update order info- order.RefundedAmount = totalAmountRefunded;- order.PaymentStatusId = order.RefundedAmount == order.OrderTotal ? Domain.Payments.PaymentStatus.Refunded : Domain.Payments.PaymentStatus.PartiallyRefunded;- await _orderService.UpdateOrder(order);+ var totalAmountRefunded = order.RefundedAmount + request.AmountToRefund;- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ //update order info+ order.RefundedAmount = totalAmountRefunded;+ order.PaymentStatusId = order.RefundedAmount == order.OrderTotal+ ? PaymentStatus.Refunded+ : PaymentStatus.PartiallyRefunded;+ await _orderService.UpdateOrder(order);- //notifications for store owner- await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, request.AmountToRefund, _languageSettings.DefaultAdminLanguageId);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- //notifications for customer- await _messageProviderService.SendOrderRefundedCustomerMessage(order, request.AmountToRefund, order.CustomerLanguageId);+ //notifications for store owner+ await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, request.AmountToRefund,+ _languageSettings.DefaultAdminLanguageId);- //raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, request.AmountToRefund), cancellationToken);- }+ //notifications for customer+ await _messageProviderService.SendOrderRefundedCustomerMessage(order, request.AmountToRefund,+ order.CustomerLanguageId);+ //raise event+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, request.AmountToRefund),+ cancellationToken);}- catch (Exception exc)- {- result ??= new RefundPaymentResult();- result.AddError($"Error: {exc.Message}. Full exception: {exc}");- }-- //process errors- var error = "";- for (var i = 0; i < result.Errors.Count; i++)- {- error += $"Error {i}: {result.Errors[i]}";- if (i != result.Errors.Count - 1)- error += ". ";- }+ }+ catch (Exception exc)+ {+ result ??= new RefundPaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");+ }- if (string.IsNullOrEmpty(error)) return result.Errors;- _logger.LogError("Error refunding order #{PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);- return result.Errors;+ //process errors+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++)+ {+ error += $"Error {i}: {result.Errors[i]}";+ if (i != result.Errors.Count - 1)+ error += ". ";}++ if (string.IsNullOrEmpty(error)) return result.Errors;+ _logger.LogError("Error refunding order #{PaymentTransactionOrderCode}. Error: {Error}",+ paymentTransaction.OrderCode, error);+ return result.Errors;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.csindex bdc0713e0..5934aff3f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs@@ -2,81 +2,88 @@using Grand.Business.Core.Events.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Localization;using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class RefundOfflineCommandHandler : IRequestHandler<RefundOfflineCommand, bool>{- public class RefundOfflineCommandHandler : IRequestHandler<RefundOfflineCommand, bool>+ private readonly LanguageSettings _languageSettings;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public RefundOfflineCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IPaymentTransactionService paymentTransactionService,+ IMessageProviderService messageProviderService,+ LanguageSettings languageSettings)+ {+ _mediator = mediator;+ _orderService = orderService;+ _paymentTransactionService = paymentTransactionService;+ _messageProviderService = messageProviderService;+ _languageSettings = languageSettings;+ }++ public async Task<bool> Handle(RefundOfflineCommand request, CancellationToken cancellationToken){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IMessageProviderService _messageProviderService;- private readonly LanguageSettings _languageSettings;-- public RefundOfflineCommandHandler(- IMediator mediator,- IOrderService orderService,- IPaymentTransactionService paymentTransactionService,- IMessageProviderService messageProviderService,- LanguageSettings languageSettings)- {- _mediator = mediator;- _orderService = orderService;- _paymentTransactionService = paymentTransactionService;- _messageProviderService = messageProviderService;- _languageSettings = languageSettings;- }-- public async Task<bool> Handle(RefundOfflineCommand request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));-- var canRefundOffline = await _mediator.Send(new CanRefundOfflineQuery { PaymentTransaction = paymentTransaction }, cancellationToken);- if (!canRefundOffline)- throw new GrandException("You can't refund this payment transaction");-- paymentTransaction.RefundedAmount += paymentTransaction.TransactionAmount;- paymentTransaction.TransactionStatus = paymentTransaction.RefundedAmount >= paymentTransaction.TransactionAmount ? TransactionStatus.Refunded : TransactionStatus.PartiallyRefunded;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);--- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));-- //amount to refund- var amountToRefund = order.OrderTotal;-- //total amount refunded- var totalAmountRefunded = order.RefundedAmount + amountToRefund;-- //update order info- order.RefundedAmount = totalAmountRefunded;- order.PaymentStatusId = order.RefundedAmount >= order.OrderTotal ? PaymentStatus.Refunded : PaymentStatus.PartiallyRefunded;-- await _orderService.UpdateOrder(order);--- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);-- //notifications for store owner- await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId);-- //notifications for customer- await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId);-- //raise event- await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken);- return true;- }+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));++ var canRefundOffline =+ await _mediator.Send(new CanRefundOfflineQuery { PaymentTransaction = paymentTransaction },+ cancellationToken);+ if (!canRefundOffline)+ throw new GrandException("You can't refund this payment transaction");++ paymentTransaction.RefundedAmount += paymentTransaction.TransactionAmount;+ paymentTransaction.TransactionStatus = paymentTransaction.RefundedAmount >= paymentTransaction.TransactionAmount+ ? TransactionStatus.Refunded+ : TransactionStatus.PartiallyRefunded;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);+++ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));++ //amount to refund+ var amountToRefund = order.OrderTotal;++ //total amount refunded+ var totalAmountRefunded = order.RefundedAmount + amountToRefund;++ //update order info+ order.RefundedAmount = totalAmountRefunded;+ order.PaymentStatusId = order.RefundedAmount >= order.OrderTotal+ ? PaymentStatus.Refunded+ : PaymentStatus.PartiallyRefunded;++ await _orderService.UpdateOrder(order);+++ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);++ //notifications for store owner+ await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund,+ _languageSettings.DefaultAdminLanguageId);++ //notifications for customer+ await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId);++ //raise event+ await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund),+ cancellationToken);+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.csindex 5f197ecad..398f6fdd9 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs@@ -3,35 +3,37 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Common.Localization;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class+ ReturnBackRedeemedLoyaltyPointsCommandHandler : IRequestHandler<ReturnBackRedeemedLoyaltyPointsCommand, bool>{- public class ReturnBackRedeemedLoyaltyPointsCommandHandler : IRequestHandler<ReturnBackRedeemedLoyaltyPointsCommand, bool>- {- private readonly ILoyaltyPointsService _loyaltyPointsService;- private readonly ITranslationService _translationService;+ private readonly ILoyaltyPointsService _loyaltyPointsService;+ private readonly ITranslationService _translationService;- public ReturnBackRedeemedLoyaltyPointsCommandHandler(- ILoyaltyPointsService loyaltyPointsService,- ITranslationService translationService)- {- _loyaltyPointsService = loyaltyPointsService;- _translationService = translationService;- }+ public ReturnBackRedeemedLoyaltyPointsCommandHandler(+ ILoyaltyPointsService loyaltyPointsService,+ ITranslationService translationService)+ {+ _loyaltyPointsService = loyaltyPointsService;+ _translationService = translationService;+ }- public async Task<bool> Handle(ReturnBackRedeemedLoyaltyPointsCommand request, CancellationToken cancellationToken)- {- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ public async Task<bool> Handle(ReturnBackRedeemedLoyaltyPointsCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- //were some points redeemed when placing an order?- if (request.Order.RedeemedLoyaltyPoints == 0)- return false;+ //were some points redeemed when placing an order?+ if (request.Order.RedeemedLoyaltyPoints == 0)+ return false;- //return back- await _loyaltyPointsService.AddLoyaltyPointsHistory(request.Order.CustomerId, -request.Order.RedeemedLoyaltyPoints, request.Order.StoreId,- string.Format(_translationService.GetResource("LoyaltyPoints.Message.ReturnedForOrder"), request.Order.OrderNumber));+ //return back+ await _loyaltyPointsService.AddLoyaltyPointsHistory(request.Order.CustomerId,+ -request.Order.RedeemedLoyaltyPoints, request.Order.StoreId,+ string.Format(_translationService.GetResource("LoyaltyPoints.Message.ReturnedForOrder"),+ request.Order.OrderNumber));- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.csindex 117fde479..435df0fd4 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs@@ -1,88 +1,86 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;using Grand.Domain.Orders;using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class UpdateOrderItemCommandHandler : IRequestHandler<UpdateOrderItemCommand, bool>{- public class UpdateOrderItemCommandHandler : IRequestHandler<UpdateOrderItemCommand, bool>+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IProductService _productService;+ private readonly IShipmentService _shipmentService;++ public UpdateOrderItemCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IProductService productService,+ IInventoryManageService inventoryManageService){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ }- public UpdateOrderItemCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IProductService productService,- IInventoryManageService inventoryManageService)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _productService = productService;- _inventoryManageService = inventoryManageService;- }+ public async Task<bool> Handle(UpdateOrderItemCommand request, CancellationToken cancellationToken)+ {+ if (request.Order == null)+ throw new ArgumentNullException(nameof(request.Order));- public async Task<bool> Handle(UpdateOrderItemCommand request, CancellationToken cancellationToken)+ if (request.OrderItem == null)+ throw new ArgumentNullException(nameof(request.OrderItem));++ var originalOrder = await _orderService.GetOrderById(request.Order.Id);+ var originalOrderItem = originalOrder.OrderItems.FirstOrDefault(x => x.Id == request.OrderItem.Id);+ if (originalOrderItem != null){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax - originalOrderItem.PriceExclTax;+ request.Order.OrderSubtotalInclTax += request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax;+ request.Order.OrderTax +=+ request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax+ - (originalOrderItem.PriceInclTax - originalOrderItem.PriceExclTax);+ request.Order.OrderTotal += request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax;- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));+ //TODO+ //request.Order.OrderTaxes- var originalOrder = await _orderService.GetOrderById(request.Order.Id);- var originalOrderItem = originalOrder.OrderItems.FirstOrDefault(x => x.Id == request.OrderItem.Id);- if (originalOrderItem != null)+ //adjust inventory+ if (originalOrderItem.Quantity != request.OrderItem.Quantity){- request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax - originalOrderItem.PriceExclTax;- request.Order.OrderSubtotalInclTax += request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax;- request.Order.OrderTax +=- request.OrderItem.PriceInclTax - request.OrderItem.PriceExclTax- - (originalOrderItem.PriceInclTax - originalOrderItem.PriceExclTax);- request.Order.OrderTotal += request.OrderItem.PriceInclTax - originalOrderItem.PriceInclTax;-- //TODO- //request.Order.OrderTaxes+ var qtyDifference = originalOrderItem.Quantity - request.OrderItem.Quantity;+ var product = await _productService.GetProductById(request.OrderItem.ProductId);+ await _inventoryManageService.AdjustReserved(product, qtyDifference, request.OrderItem.Attributes,+ request.OrderItem.WarehouseId);- //adjust inventory- if (originalOrderItem.Quantity != request.OrderItem.Quantity)+ if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped){- var qtyDifference = originalOrderItem.Quantity - request.OrderItem.Quantity;- var product = await _productService.GetProductById(request.OrderItem.ProductId);- await _inventoryManageService.AdjustReserved(product, qtyDifference, request.OrderItem.Attributes,- request.OrderItem.WarehouseId);-- if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped)- {- var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);- if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))- {- request.Order.ShippingStatusId = ShippingStatus.Delivered;- }- }+ if (!request.Order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))+ request.Order.ShippingStatusId = ShippingStatus.Delivered;}}- await _orderService.UpdateOrder(request.Order);- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);+ }- //add a note- await _orderService.InsertOrderNote(new OrderNote {- Note = "Order item has been edited",- DisplayToCustomer = false,- OrderId = request.Order.Id- });+ await _orderService.UpdateOrder(request.Order);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = request.Order }, cancellationToken);- return true;- }+ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = "Order item has been edited",+ DisplayToCustomer = false,+ OrderId = request.Order.Id+ });++ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.csindex a47663a9a..b8b41909d 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs@@ -3,45 +3,47 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class+ ValidateMinShoppingCartSubtotalAmountCommandHandler : IRequestHandler<ValidateMinShoppingCartSubtotalAmountCommand,+ bool>{- public class ValidateMinShoppingCartSubtotalAmountCommandHandler : IRequestHandler<ValidateMinShoppingCartSubtotalAmountCommand, bool>+ private readonly OrderSettings _orderSettings;+ private readonly IOrderCalculationService _orderTotalCalculationService;++ public ValidateMinShoppingCartSubtotalAmountCommandHandler(+ IOrderCalculationService orderTotalCalculationService,+ OrderSettings orderSettings)+ {+ _orderTotalCalculationService = orderTotalCalculationService;+ _orderSettings = orderSettings;+ }++ public async Task<bool> Handle(ValidateMinShoppingCartSubtotalAmountCommand request,+ CancellationToken cancellationToken){- private readonly IOrderCalculationService _orderTotalCalculationService;- private readonly OrderSettings _orderSettings;-- public ValidateMinShoppingCartSubtotalAmountCommandHandler(- IOrderCalculationService orderTotalCalculationService,- OrderSettings orderSettings)- {- _orderTotalCalculationService = orderTotalCalculationService;- _orderSettings = orderSettings;- }-- public async Task<bool> Handle(ValidateMinShoppingCartSubtotalAmountCommand request, CancellationToken cancellationToken)- {- if (request.Cart == null)- throw new ArgumentNullException(nameof(request.Cart));-- if (request.Customer == null)- throw new ArgumentNullException(nameof(request.Customer));-- return await ValidateMinOrderSubtotalAmount(request.Cart);- }-- protected virtual async Task<bool> ValidateMinOrderSubtotalAmount(IList<ShoppingCartItem> cart)- {- ArgumentNullException.ThrowIfNull(cart);-- if (!cart.Any())- return false;-- //min order amount sub-total validation- if (!cart.Any() || !(_orderSettings.MinOrderSubtotalAmount > 0)) return true;- //subtotal- var (_, _, subTotalWithoutDiscount, _, _) = await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false);- return !(subTotalWithoutDiscount < _orderSettings.MinOrderSubtotalAmount);- }+ if (request.Cart == null)+ throw new ArgumentNullException(nameof(request.Cart));++ if (request.Customer == null)+ throw new ArgumentNullException(nameof(request.Customer));++ return await ValidateMinOrderSubtotalAmount(request.Cart);+ }++ protected virtual async Task<bool> ValidateMinOrderSubtotalAmount(IList<ShoppingCartItem> cart)+ {+ ArgumentNullException.ThrowIfNull(cart);++ if (!cart.Any())+ return false;+ //min order amount sub-total validation+ if (!cart.Any() || !(_orderSettings.MinOrderSubtotalAmount > 0)) return true;+ //subtotal+ var (_, _, subTotalWithoutDiscount, _, _) =+ await _orderTotalCalculationService.GetShoppingCartSubTotal(cart, false);+ return !(subTotalWithoutDiscount < _orderSettings.MinOrderSubtotalAmount);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.csindex 55f331dd7..35e513ec2 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs@@ -1,93 +1,96 @@using Grand.Business.Core.Commands.Checkout.Orders;+using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Business.Core.Utilities.Checkout;+using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-using Grand.Business.Core.Extensions;using Microsoft.Extensions.Logging;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class VoidCommandHandler : IRequestHandler<VoidCommand, IList<string>>{- public class VoidCommandHandler : IRequestHandler<VoidCommand, IList<string>>+ private readonly ILogger<VoidCommandHandler> _logger;+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentService _paymentService;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public VoidCommandHandler(+ IOrderService orderService,+ IMediator mediator,+ IPaymentService paymentService,+ IPaymentTransactionService paymentTransactionService,+ ILogger<VoidCommandHandler> logger){- private readonly IOrderService _orderService;- private readonly IMediator _mediator;- private readonly IPaymentService _paymentService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly ILogger<VoidCommandHandler> _logger;+ _orderService = orderService;+ _mediator = mediator;+ _paymentService = paymentService;+ _paymentTransactionService = paymentTransactionService;+ _logger = logger;+ }- public VoidCommandHandler(- IOrderService orderService,- IMediator mediator,- IPaymentService paymentService,- IPaymentTransactionService paymentTransactionService,- ILogger<VoidCommandHandler> logger)- {- _orderService = orderService;- _mediator = mediator;- _paymentService = paymentService;- _paymentTransactionService = paymentTransactionService;- _logger = logger;- }- public async Task<IList<string>> Handle(VoidCommand command, CancellationToken cancellationToken)+ public async Task<IList<string>> Handle(VoidCommand command, CancellationToken cancellationToken)+ {+ var paymentTransaction = command.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(command.PaymentTransaction));++ var canVoid = await _mediator.Send(new CanVoidQuery { PaymentTransaction = paymentTransaction },+ cancellationToken);+ if (!canVoid)+ throw new GrandException("Cannot do void for order.");++ VoidPaymentResult result = null;+ try{- var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ result = await _paymentService.Void(paymentTransaction);- var canVoid = await _mediator.Send(new CanVoidQuery { PaymentTransaction = paymentTransaction }, cancellationToken);- if (!canVoid)- throw new GrandException("Cannot do void for order.");+ //event notification+ await _mediator.VoidPaymentTransactionDetailsEvent(result, paymentTransaction);- VoidPaymentResult result = null;- try+ if (result.Success){- result = await _paymentService.Void(paymentTransaction);+ //update order info+ paymentTransaction.TransactionStatus = result.NewTransactionStatus;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);- //event notification- await _mediator.VoidPaymentTransactionDetailsEvent(result, paymentTransaction);+ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));- if (result.Success)+ if (paymentTransaction.TransactionStatus == TransactionStatus.Voided){- //update order info- paymentTransaction.TransactionStatus = result.NewTransactionStatus;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);-- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));-- if (paymentTransaction.TransactionStatus == Domain.Payments.TransactionStatus.Voided)- {- order.PaymentStatusId = Domain.Payments.PaymentStatus.Voided;- await _orderService.UpdateOrder(order);+ order.PaymentStatusId = PaymentStatus.Voided;+ await _orderService.UpdateOrder(order);- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- }+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);}}- catch (Exception exc)- {- result ??= new VoidPaymentResult();- result.AddError($"Error: {exc.Message}. Full exception: {exc}");- }-- //process errors- var error = "";- for (var i = 0; i < result.Errors.Count; i++)- {- error += $"Error {i}: {result.Errors[i]}";- if (i != result.Errors.Count - 1)- error += ". ";- }+ }+ catch (Exception exc)+ {+ result ??= new VoidPaymentResult();+ result.AddError($"Error: {exc.Message}. Full exception: {exc}");+ }- if (string.IsNullOrEmpty(error)) return result.Errors;-- _logger.LogError("Error voiding order #{PaymentTransactionOrderCode}. Error: {Error}", paymentTransaction.OrderCode, error);- return result.Errors;+ //process errors+ var error = "";+ for (var i = 0; i < result.Errors.Count; i++)+ {+ error += $"Error {i}: {result.Errors[i]}";+ if (i != result.Errors.Count - 1)+ error += ". ";}++ if (string.IsNullOrEmpty(error)) return result.Errors;++ _logger.LogError("Error voiding order #{PaymentTransactionOrderCode}. Error: {Error}",+ paymentTransaction.OrderCode, error);+ return result.Errors;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.csindex 497a1c104..e9269de0c 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs@@ -7,49 +7,49 @@ using Grand.Domain.Payments;using Grand.SharedKernel;using MediatR;-namespace Grand.Business.Checkout.Commands.Handlers.Orders+namespace Grand.Business.Checkout.Commands.Handlers.Orders;++public class VoidOfflineCommandHandler : IRequestHandler<VoidOfflineCommand, bool>{- public class VoidOfflineCommandHandler : IRequestHandler<VoidOfflineCommand, bool>+ private readonly IMediator _mediator;+ private readonly IOrderService _orderService;+ private readonly IPaymentTransactionService _paymentTransactionService;++ public VoidOfflineCommandHandler(+ IOrderService orderService,+ IPaymentTransactionService paymentTransactionService,+ IMediator mediator){- private readonly IOrderService _orderService;- private readonly IPaymentTransactionService _paymentTransactionService;- private readonly IMediator _mediator;-- public VoidOfflineCommandHandler(- IOrderService orderService,- IPaymentTransactionService paymentTransactionService,- IMediator mediator)- {- _orderService = orderService;- _paymentTransactionService = paymentTransactionService;- _mediator = mediator;- }-- public async Task<bool> Handle(VoidOfflineCommand request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));-- paymentTransaction.TransactionStatus = TransactionStatus.Voided;- await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);-- var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));-- if (!await _mediator.Send(new CanVoidOfflineQuery { PaymentTransaction = paymentTransaction }, cancellationToken))- throw new GrandException("You can't void this order");-- order.PaymentStatusId = PaymentStatus.Voided;- await _orderService.UpdateOrder(order);-- //event notification- await _mediator.Publish(new PaymentTransactionVoidOfflineEvent(paymentTransaction), cancellationToken);-- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- return true;- }+ _orderService = orderService;+ _paymentTransactionService = paymentTransactionService;+ _mediator = mediator;+ }++ public async Task<bool> Handle(VoidOfflineCommand request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));++ paymentTransaction.TransactionStatus = TransactionStatus.Voided;+ await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);++ var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);+ if (order == null)+ throw new ArgumentNullException(nameof(order));++ if (!await _mediator.Send(new CanVoidOfflineQuery { PaymentTransaction = paymentTransaction },+ cancellationToken))+ throw new GrandException("You can't void this order");++ order.PaymentStatusId = PaymentStatus.Voided;+ await _orderService.UpdateOrder(order);++ //event notification+ await _mediator.Publish(new PaymentTransactionVoidOfflineEvent(paymentTransaction), cancellationToken);++ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.csindex 89a1d717f..112756f2c 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs@@ -1,77 +1,74 @@using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Commands.Checkout.Shipping;+using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;using Grand.Business.Core.Interfaces.Messages;using Grand.Domain.Orders;using Grand.Domain.Shipping;using MediatR;-using Grand.Business.Core.Extensions;-namespace Grand.Business.Checkout.Commands.Handlers.Shipping+namespace Grand.Business.Checkout.Commands.Handlers.Shipping;++public class DeliveryCommandHandler : IRequestHandler<DeliveryCommand, bool>{- public class DeliveryCommandHandler : IRequestHandler<DeliveryCommand, bool>- {- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IMessageProviderService _messageProviderService;+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly IShipmentService _shipmentService;- public DeliveryCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IMessageProviderService messageProviderService)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _messageProviderService = messageProviderService;- }+ public DeliveryCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IMessageProviderService messageProviderService)+ {+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _messageProviderService = messageProviderService;+ }- public async Task<bool> Handle(DeliveryCommand request, CancellationToken cancellationToken)- {- if (request.Shipment == null)- throw new ArgumentNullException(nameof(request.Shipment));+ public async Task<bool> Handle(DeliveryCommand request, CancellationToken cancellationToken)+ {+ if (request.Shipment == null)+ throw new ArgumentNullException(nameof(request.Shipment));- var order = await _orderService.GetOrderById(request.Shipment.OrderId);- if (order == null)- throw new Exception("Order cannot be loaded");+ var order = await _orderService.GetOrderById(request.Shipment.OrderId);+ if (order == null)+ throw new Exception("Order cannot be loaded");- if (!request.Shipment.ShippedDateUtc.HasValue)- throw new Exception("This shipment is not shipped yet");+ if (!request.Shipment.ShippedDateUtc.HasValue)+ throw new Exception("This shipment is not shipped yet");- if (request.Shipment.DeliveryDateUtc.HasValue)- throw new Exception("This shipment is already delivered");+ if (request.Shipment.DeliveryDateUtc.HasValue)+ throw new Exception("This shipment is already delivered");- request.Shipment.DeliveryDateUtc = DateTime.UtcNow;- await _shipmentService.UpdateShipment(request.Shipment);+ request.Shipment.DeliveryDateUtc = DateTime.UtcNow;+ await _shipmentService.UpdateShipment(request.Shipment);- var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId);- if (!order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))- {- order.ShippingStatusId = ShippingStatus.Delivered;- await _orderService.UpdateOrder(order);- }+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId);+ if (!order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null))+ {+ order.ShippingStatusId = ShippingStatus.Delivered;+ await _orderService.UpdateOrder(order);+ }- //add a note- await _orderService.InsertOrderNote(new OrderNote {- Note = $"Shipment #{request.Shipment.ShipmentNumber} has been delivered",- DisplayToCustomer = false,- OrderId = order.Id- });- if (request.NotifyCustomer)- {- //send email notification- await _messageProviderService.SendShipmentDeliveredCustomerMessage(request.Shipment, order);- }- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = $"Shipment #{request.Shipment.ShipmentNumber} has been delivered",+ DisplayToCustomer = false,+ OrderId = order.Id+ });+ if (request.NotifyCustomer)+ //send email notification+ await _messageProviderService.SendShipmentDeliveredCustomerMessage(request.Shipment, order);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- //event- await _mediator.PublishShipmentDelivered(request.Shipment);+ //event+ await _mediator.PublishShipmentDelivered(request.Shipment);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.csindex fe0fbaf9a..949203511 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs@@ -1,78 +1,80 @@using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Commands.Checkout.Shipping;+using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;using Grand.Business.Core.Interfaces.Messages;using Grand.Domain.Orders;using Grand.Domain.Shipping;using MediatR;-using Grand.Business.Core.Extensions;-namespace Grand.Business.Checkout.Commands.Handlers.Shipping+namespace Grand.Business.Checkout.Commands.Handlers.Shipping;++public class ShipCommandHandler : IRequestHandler<ShipCommand, bool>{- public class ShipCommandHandler : IRequestHandler<ShipCommand, bool>+ private readonly IMediator _mediator;+ private readonly IMessageProviderService _messageProviderService;+ private readonly IOrderService _orderService;+ private readonly IShipmentService _shipmentService;++ public ShipCommandHandler(+ IMediator mediator,+ IOrderService orderService,+ IShipmentService shipmentService,+ IMessageProviderService messageProviderService){- private readonly IMediator _mediator;- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IMessageProviderService _messageProviderService;+ _mediator = mediator;+ _orderService = orderService;+ _shipmentService = shipmentService;+ _messageProviderService = messageProviderService;+ }- public ShipCommandHandler(- IMediator mediator,- IOrderService orderService,- IShipmentService shipmentService,- IMessageProviderService messageProviderService)- {- _mediator = mediator;- _orderService = orderService;- _shipmentService = shipmentService;- _messageProviderService = messageProviderService;- }+ public async Task<bool> Handle(ShipCommand request, CancellationToken cancellationToken)+ {+ if (request.Shipment == null)+ throw new ArgumentNullException(nameof(request.Shipment));- public async Task<bool> Handle(ShipCommand request, CancellationToken cancellationToken)- {- if (request.Shipment == null)- throw new ArgumentNullException(nameof(request.Shipment));+ var order = await _orderService.GetOrderById(request.Shipment.OrderId);+ if (order == null)+ throw new Exception("Order cannot be loaded");- var order = await _orderService.GetOrderById(request.Shipment.OrderId);- if (order == null)- throw new Exception("Order cannot be loaded");+ if (request.Shipment.ShippedDateUtc.HasValue)+ throw new Exception("This shipment is already shipped");- if (request.Shipment.ShippedDateUtc.HasValue)- throw new Exception("This shipment is already shipped");+ request.Shipment.ShippedDateUtc = DateTime.UtcNow;+ await _shipmentService.UpdateShipment(request.Shipment);- request.Shipment.ShippedDateUtc = DateTime.UtcNow;- await _shipmentService.UpdateShipment(request.Shipment);+ //check whether we have more items to ship+ if (order.HasItemsToAddToShipment())+ {+ order.ShippingStatusId = ShippingStatus.PartiallyShipped;+ }+ else+ {+ var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId);+ order.ShippingStatusId = shipments.All(x => x.ShippedDateUtc != null)+ ? ShippingStatus.Shipped+ : ShippingStatus.PartiallyShipped;+ }- //check whether we have more items to ship- if (order.HasItemsToAddToShipment())- order.ShippingStatusId = ShippingStatus.PartiallyShipped;- else- {- var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId);- order.ShippingStatusId = shipments.All(x => x.ShippedDateUtc != null) ? ShippingStatus.Shipped : ShippingStatus.PartiallyShipped;- }- await _orderService.UpdateOrder(order);+ await _orderService.UpdateOrder(order);- //add a note- await _orderService.InsertOrderNote(new OrderNote {- Note = $"Shipment #{request.Shipment.ShipmentNumber} has been sent",- DisplayToCustomer = false,- OrderId = order.Id- });+ //add a note+ await _orderService.InsertOrderNote(new OrderNote {+ Note = $"Shipment #{request.Shipment.ShipmentNumber} has been sent",+ DisplayToCustomer = false,+ OrderId = order.Id+ });- if (request.NotifyCustomer)- {- //notify customer- await _messageProviderService.SendShipmentSentCustomerMessage(request.Shipment, order);- }- //check order status- await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);+ if (request.NotifyCustomer)+ //notify customer+ await _messageProviderService.SendShipmentSentCustomerMessage(request.Shipment, order);+ //check order status+ await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken);- //event- await _mediator.PublishShipmentSent(request.Shipment);+ //event+ await _mediator.PublishShipmentSent(request.Shipment);- return true;- }+ return true;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Customers/CustomerRegisteredEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Customers/CustomerRegisteredEventHandler.csindex 070b1516c..7d3b527fa 100644--- a/src/Business/Grand.Business.Checkout/Events/Customers/CustomerRegisteredEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Customers/CustomerRegisteredEventHandler.cs@@ -1,37 +1,36 @@-using Grand.Business.Core.Interfaces.Checkout.Orders;+using Grand.Business.Core.Events.Customers;+using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Events.Customers;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Events.Customers+namespace Grand.Business.Checkout.Events.Customers;++public class CustomerRegisteredEventHandler : INotificationHandler<CustomerRegisteredEvent>{- public class CustomerRegisteredEventHandler : INotificationHandler<CustomerRegisteredEvent>+ private readonly ILoyaltyPointsService _loyaltyPointsService;+ private readonly LoyaltyPointsSettings _loyaltyPointsSettings;+ private readonly ITranslationService _translationService;++ public CustomerRegisteredEventHandler(+ ITranslationService translationService,+ ILoyaltyPointsService loyaltyPointsService,+ LoyaltyPointsSettings loyaltyPointsSettings+ ){- private readonly ITranslationService _translationService;- private readonly ILoyaltyPointsService _loyaltyPointsService;- private readonly LoyaltyPointsSettings _loyaltyPointsSettings;+ _translationService = translationService;+ _loyaltyPointsService = loyaltyPointsService;+ _loyaltyPointsSettings = loyaltyPointsSettings;+ }- public CustomerRegisteredEventHandler(- ITranslationService translationService,- ILoyaltyPointsService loyaltyPointsService,- LoyaltyPointsSettings loyaltyPointsSettings- )- {- _translationService = translationService;- _loyaltyPointsService = loyaltyPointsService;- _loyaltyPointsSettings = loyaltyPointsSettings;- }- public async Task Handle(CustomerRegisteredEvent notification, CancellationToken cancellationToken)- {- //Add loyalty points for customer registration (if enabled)- if (_loyaltyPointsSettings.Enabled &&- _loyaltyPointsSettings.PointsForRegistration > 0)- {- await _loyaltyPointsService.AddLoyaltyPointsHistory(notification.Customer.Id, _loyaltyPointsSettings.PointsForRegistration,- notification.Customer.StoreId,- _translationService.GetResource("LoyaltyPoints.Message.EarnedForRegistration"), "", 0);- }- }+ public async Task Handle(CustomerRegisteredEvent notification, CancellationToken cancellationToken)+ {+ //Add loyalty points for customer registration (if enabled)+ if (_loyaltyPointsSettings.Enabled &&+ _loyaltyPointsSettings.PointsForRegistration > 0)+ await _loyaltyPointsService.AddLoyaltyPointsHistory(notification.Customer.Id,+ _loyaltyPointsSettings.PointsForRegistration,+ notification.Customer.StoreId,+ _translationService.GetResource("LoyaltyPoints.Message.EarnedForRegistration"));}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnDeletedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnDeletedEventHandler.csindex ac1de9b2a..083ccf4a6 100644--- a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnDeletedEventHandler.cs@@ -3,30 +3,30 @@ using Grand.Domain.Orders;using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Business.Checkout.Events.Orders+namespace Grand.Business.Checkout.Events.Orders;++public class MerchandiseReturnDeletedEventHandler : INotificationHandler<EntityDeleted<MerchandiseReturn>>{- public class MerchandiseReturnDeletedEventHandler : INotificationHandler<EntityDeleted<MerchandiseReturn>>- {- private readonly IOrderService _orderService;+ private readonly IOrderService _orderService;- public MerchandiseReturnDeletedEventHandler(IOrderService orderService)- {- _orderService = orderService;- }+ public MerchandiseReturnDeletedEventHandler(IOrderService orderService)+ {+ _orderService = orderService;+ }- public async Task Handle(EntityDeleted<MerchandiseReturn> notification, CancellationToken cancellationToken)+ public async Task Handle(EntityDeleted<MerchandiseReturn> notification, CancellationToken cancellationToken)+ {+ var order = await _orderService.GetOrderById(notification.Entity.OrderId);+ if (order != null){- var order = await _orderService.GetOrderById(notification.Entity.OrderId);- if (order != null)+ foreach (var item in notification.Entity.MerchandiseReturnItems){- foreach (var item in notification.Entity.MerchandiseReturnItems)- {- var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);- if (orderItem != null)- orderItem.ReturnQty -= item.Quantity;- }- await _orderService.UpdateOrder(order);+ var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);+ if (orderItem != null)+ orderItem.ReturnQty -= item.Quantity;}++ await _orderService.UpdateOrder(order);}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnInsertEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnInsertEventHandler.csindex 7de819127..8e5b7584f 100644--- a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnInsertEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnInsertEventHandler.cs@@ -3,30 +3,30 @@ using Grand.Domain.Orders;using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Business.Checkout.Events.Orders+namespace Grand.Business.Checkout.Events.Orders;++public class MerchandiseReturnInsertEventHandler : INotificationHandler<EntityInserted<MerchandiseReturn>>{- public class MerchandiseReturnInsertEventHandler : INotificationHandler<EntityInserted<MerchandiseReturn>>- {- private readonly IOrderService _orderService;+ private readonly IOrderService _orderService;- public MerchandiseReturnInsertEventHandler(IOrderService orderService)- {- _orderService = orderService;- }+ public MerchandiseReturnInsertEventHandler(IOrderService orderService)+ {+ _orderService = orderService;+ }- public async Task Handle(EntityInserted<MerchandiseReturn> notification, CancellationToken cancellationToken)+ public async Task Handle(EntityInserted<MerchandiseReturn> notification, CancellationToken cancellationToken)+ {+ var order = await _orderService.GetOrderById(notification.Entity.OrderId);+ if (order != null){- var order = await _orderService.GetOrderById(notification.Entity.OrderId);- if (order != null)+ foreach (var item in notification.Entity.MerchandiseReturnItems){- foreach (var item in notification.Entity.MerchandiseReturnItems)- {- var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);- if (orderItem != null)- orderItem.ReturnQty += item.Quantity;- }- await _orderService.UpdateOrder(order);+ var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);+ if (orderItem != null)+ orderItem.ReturnQty += item.Quantity;}++ await _orderService.UpdateOrder(order);}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Orders/OrderDeletedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/OrderDeletedEventHandler.csindex 5ac922024..919c2623b 100644--- a/src/Business/Grand.Business.Checkout/Events/Orders/OrderDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Orders/OrderDeletedEventHandler.cs@@ -1,23 +1,22 @@using Grand.Business.Core.Events.Checkout.Orders;-using Grand.Domain.Catalog;using Grand.Data;+using Grand.Domain.Catalog;using MediatR;-namespace Grand.Business.Checkout.Events.Orders+namespace Grand.Business.Checkout.Events.Orders;++public class OrderDeletedEventHandler : INotificationHandler<OrderDeletedEvent>{- public class OrderDeletedEventHandler : INotificationHandler<OrderDeletedEvent>- {- private readonly IRepository<ProductAlsoPurchased> _productAlsoPurchasedRepository;+ private readonly IRepository<ProductAlsoPurchased> _productAlsoPurchasedRepository;- public OrderDeletedEventHandler(IRepository<ProductAlsoPurchased> productAlsoPurchasedRepository)- {- _productAlsoPurchasedRepository = productAlsoPurchasedRepository;- }+ public OrderDeletedEventHandler(IRepository<ProductAlsoPurchased> productAlsoPurchasedRepository)+ {+ _productAlsoPurchasedRepository = productAlsoPurchasedRepository;+ }- public Task Handle(OrderDeletedEvent notification, CancellationToken cancellationToken)- {- //delete product also purchased- return _productAlsoPurchasedRepository.DeleteManyAsync(x=>x.OrderId == notification.Order.Id);- }+ public Task Handle(OrderDeletedEvent notification, CancellationToken cancellationToken)+ {+ //delete product also purchased+ return _productAlsoPurchasedRepository.DeleteManyAsync(x => x.OrderId == notification.Order.Id);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.csindex 94aa15dd1..8fb2c7ee7 100644--- a/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedEventHandler.cs@@ -1,89 +1,85 @@using Grand.Business.Core.Events.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Customers;-using Grand.Domain.Catalog;using Grand.Data;+using Grand.Domain.Catalog;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Events.Orders+namespace Grand.Business.Checkout.Events.Orders;++public class OrderPlacedEventHandler : INotificationHandler<OrderPlacedEvent>{- public class OrderPlacedEventHandler : INotificationHandler<OrderPlacedEvent>+ private readonly ICustomerService _customerService;+ private readonly ILoyaltyPointsService _loyaltyPointsService;+ private readonly IRepository<ProductAlsoPurchased> _productAlsoPurchasedRepository;++ public OrderPlacedEventHandler(+ IRepository<ProductAlsoPurchased> productAlsoPurchasedRepository,+ ICustomerService customerService,+ ILoyaltyPointsService loyaltyPointsService){- private readonly IRepository<ProductAlsoPurchased> _productAlsoPurchasedRepository;- private readonly ICustomerService _customerService;- private readonly ILoyaltyPointsService _loyaltyPointsService;+ _productAlsoPurchasedRepository = productAlsoPurchasedRepository;+ _customerService = customerService;+ _loyaltyPointsService = loyaltyPointsService;+ }- public OrderPlacedEventHandler(- IRepository<ProductAlsoPurchased> productAlsoPurchasedRepository,- ICustomerService customerService,- ILoyaltyPointsService loyaltyPointsService)- {- _productAlsoPurchasedRepository = productAlsoPurchasedRepository;- _customerService = customerService;- _loyaltyPointsService = loyaltyPointsService;- }+ public Task Handle(OrderPlacedEvent notification, CancellationToken cancellationToken)+ {+ //insert product also purchased+ _ = InsertProductAlsoPurchased(notification.Order);+ //update customer+ _ = UpdateCustomer(notification.Order);+ //Insert Loyalty Points History+ _ = InsertLoyaltyPointsHistory(notification.Order);+ return Task.CompletedTask;+ }- public Task Handle(OrderPlacedEvent notification, CancellationToken cancellationToken)+ private Task InsertProductAlsoPurchased(Order order)+ {+ foreach (var item in order.OrderItems)+ foreach (var it in order.OrderItems.Where(x => x.ProductId != item.ProductId)){- //insert product also purchased- _ = InsertProductAlsoPurchased(notification.Order);- //update customer- _ = UpdateCustomer(notification.Order);- //Insert Loyalty Points History- _ = InsertLoyaltyPointsHistory(notification.Order);- return Task.CompletedTask;+ var productPurchase = new ProductAlsoPurchased {+ ProductId = item.ProductId,+ OrderId = order.Id,+ CreatedOrderOnUtc = order.CreatedOnUtc,+ Quantity = it.Quantity,+ StoreId = order.StoreId,+ ProductId2 = it.ProductId+ };+ _productAlsoPurchasedRepository.InsertAsync(productPurchase);}- private Task InsertProductAlsoPurchased(Order order)- {- foreach (var item in order.OrderItems)- {- foreach (var it in order.OrderItems.Where(x => x.ProductId != item.ProductId))- {- var productPurchase = new ProductAlsoPurchased {- ProductId = item.ProductId,- OrderId = order.Id,- CreatedOrderOnUtc = order.CreatedOnUtc,- Quantity = it.Quantity,- StoreId = order.StoreId,- ProductId2 = it.ProductId- };- _productAlsoPurchasedRepository.InsertAsync(productPurchase);- }- }- return Task.CompletedTask;- }+ return Task.CompletedTask;+ }- private Task UpdateCustomer(Order order)- {- //Updated field "free shipping" after added a new order- _customerService.UpdateCustomerField(order.CustomerId, x => x.FreeShipping, false);+ private Task UpdateCustomer(Order order)+ {+ //Updated field "free shipping" after added a new order+ _customerService.UpdateCustomerField(order.CustomerId, x => x.FreeShipping, false);- //Update field Last purchase date after added a new order- _customerService.UpdateCustomerField(order.CustomerId, x => x.LastPurchaseDateUtc, order.CreatedOnUtc);+ //Update field Last purchase date after added a new order+ _customerService.UpdateCustomerField(order.CustomerId, x => x.LastPurchaseDateUtc, order.CreatedOnUtc);- //Update field Last update cart date after added a new order- _customerService.UpdateCustomerField(order.CustomerId, x => x.LastUpdateCartDateUtc, null);+ //Update field Last update cart date after added a new order+ _customerService.UpdateCustomerField(order.CustomerId, x => x.LastUpdateCartDateUtc, null);- //Update field has contribution after added a new order- _customerService.UpdateCustomerField(order.CustomerId, x => x.HasContributions, true);+ //Update field has contribution after added a new order+ _customerService.UpdateCustomerField(order.CustomerId, x => x.HasContributions, true);- return Task.CompletedTask;- }+ return Task.CompletedTask;+ }- private Task InsertLoyaltyPointsHistory(Order order)- {- //loyalty points history- if (order.RedeemedLoyaltyPointsAmount > 0)- {- _loyaltyPointsService.AddLoyaltyPointsHistory(order.CustomerId,- -order.RedeemedLoyaltyPoints, order.StoreId,- $"Loyalty points redeemed for order {order.OrderNumber}",- order.Id, order.RedeemedLoyaltyPointsAmount);- }+ private Task InsertLoyaltyPointsHistory(Order order)+ {+ //loyalty points history+ if (order.RedeemedLoyaltyPointsAmount > 0)+ _loyaltyPointsService.AddLoyaltyPointsHistory(order.CustomerId,+ -order.RedeemedLoyaltyPoints, order.StoreId,+ $"Loyalty points redeemed for order {order.OrderNumber}",+ order.Id, order.RedeemedLoyaltyPointsAmount);- return Task.CompletedTask;- }+ return Task.CompletedTask;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.csindex e26f46795..5b7f9c716 100644--- a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentDeletedEventHandler.cs@@ -1,73 +1,75 @@using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Domain.Orders;using Grand.Domain.Shipping;using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Business.Checkout.Events.Shipping+namespace Grand.Business.Checkout.Events.Shipping;++/// <summary>+/// Update order items+/// </summary>+public class ShipmentDeletedEventHandler : INotificationHandler<EntityDeleted<Shipment>>{- /// <summary>- /// Update order items- /// </summary>- public class ShipmentDeletedEventHandler : INotificationHandler<EntityDeleted<Shipment>>+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IOrderService _orderService;+ private readonly IShipmentService _shipmentService;++ public ShipmentDeletedEventHandler(+ IOrderService orderService,+ IShipmentService shipmentService,+ IInventoryManageService inventoryManageService){- private readonly IOrderService _orderService;- private readonly IShipmentService _shipmentService;- private readonly IInventoryManageService _inventoryManageService;- public ShipmentDeletedEventHandler(- IOrderService orderService,- IShipmentService shipmentService,- IInventoryManageService inventoryManageService)- {- _orderService = orderService;- _shipmentService = shipmentService;- _inventoryManageService = inventoryManageService;- }+ _orderService = orderService;+ _shipmentService = shipmentService;+ _inventoryManageService = inventoryManageService;+ }++ public async Task Handle(EntityDeleted<Shipment> notification, CancellationToken cancellationToken)+ {+ //reverse booked inventory+ foreach (var shipmentItem in notification.Entity.ShipmentItems)+ await _inventoryManageService.ReverseBookedInventory(notification.Entity, shipmentItem);+- public async Task Handle(EntityDeleted<Shipment> notification, CancellationToken cancellationToken)+ var order = await _orderService.GetOrderById(notification.Entity.OrderId);+ if (order != null){- //reverse booked inventory- foreach (var shipmentItem in notification.Entity.ShipmentItems)+ foreach (var item in notification.Entity.ShipmentItems){- await _inventoryManageService.ReverseBookedInventory(notification.Entity, shipmentItem);+ var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);+ if (orderItem == null) continue;+ orderItem.ShipQty -= item.Quantity;+ orderItem.OpenQty += item.Quantity;+ orderItem.Status = orderItem.OpenQty <= 0 ? OrderItemStatus.Close : OrderItemStatus.Open;}-- var order = await _orderService.GetOrderById(notification.Entity.OrderId);- if (order != null)+ if (!order.OrderItems.Any(x => x.ShipQty > 0)){- foreach (var item in notification.Entity.ShipmentItems)- {- var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);- if (orderItem == null) continue;- orderItem.ShipQty -= item.Quantity;- orderItem.OpenQty += item.Quantity;- orderItem.Status = orderItem.OpenQty <= 0 ? Domain.Orders.OrderItemStatus.Close : Domain.Orders.OrderItemStatus.Open;- }-- if (!order.OrderItems.Any(x => x.ShipQty > 0))+ order.ShippingStatusId = ShippingStatus.Pending;+ }+ else+ {+ if (order.ShippingStatusId == ShippingStatus.Delivered){- order.ShippingStatusId = ShippingStatus.Pending;+ order.ShippingStatusId = ShippingStatus.PartiallyShipped;}else{- if (order.ShippingStatusId == ShippingStatus.Delivered)- order.ShippingStatusId = ShippingStatus.PartiallyShipped;- else+ var shipments = await _shipmentService.GetShipmentsByOrder(order.Id);+ if (shipments.Any()){- var shipments = await _shipmentService.GetShipmentsByOrder(order.Id);- if (shipments.Any())- {- if (shipments.Any(x => x.ShippedDateUtc == null))- order.ShippingStatusId = ShippingStatus.PreparedToShipped;- if (shipments.Any(x => x.ShippedDateUtc != null))- order.ShippingStatusId = ShippingStatus.PartiallyShipped;- }+ if (shipments.Any(x => x.ShippedDateUtc == null))+ order.ShippingStatusId = ShippingStatus.PreparedToShipped;+ if (shipments.Any(x => x.ShippedDateUtc != null))+ order.ShippingStatusId = ShippingStatus.PartiallyShipped;}}- await _orderService.UpdateOrder(order);}++ await _orderService.UpdateOrder(order);}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.csindex 8c1155186..a240ddad6 100644--- a/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/Shipping/ShipmentInsertedEventHandler.cs@@ -1,54 +1,54 @@using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Checkout.Orders;+using Grand.Domain.Orders;using Grand.Domain.Shipping;using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Business.Checkout.Events.Shipping+namespace Grand.Business.Checkout.Events.Shipping;++/// <summary>+/// Update order items+/// </summary>+public class ShipmentInsertedEventHandler : INotificationHandler<EntityInserted<Shipment>>{- /// <summary>- /// Update order items- /// </summary>- public class ShipmentInsertedEventHandler : INotificationHandler<EntityInserted<Shipment>>- {- private readonly IOrderService _orderService;- private readonly IProductService _productService;- private readonly IInventoryManageService _inventoryManageService;+ private readonly IInventoryManageService _inventoryManageService;+ private readonly IOrderService _orderService;+ private readonly IProductService _productService;- public ShipmentInsertedEventHandler(IOrderService orderService, IProductService productService, IInventoryManageService inventoryManageService)- {- _orderService = orderService;- _productService = productService;- _inventoryManageService = inventoryManageService;- }+ public ShipmentInsertedEventHandler(IOrderService orderService, IProductService productService,+ IInventoryManageService inventoryManageService)+ {+ _orderService = orderService;+ _productService = productService;+ _inventoryManageService = inventoryManageService;+ }- public async Task Handle(EntityInserted<Shipment> notification, CancellationToken cancellationToken)+ public async Task Handle(EntityInserted<Shipment> notification, CancellationToken cancellationToken)+ {+ var order = await _orderService.GetOrderById(notification.Entity.OrderId);+ if (order != null){- var order = await _orderService.GetOrderById(notification.Entity.OrderId);- if (order != null)- {- foreach (var item in notification.Entity.ShipmentItems)- {- var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);- if (orderItem == null) continue;- orderItem.ShipQty += item.Quantity;- orderItem.OpenQty -= item.Quantity;- orderItem.Status = orderItem.OpenQty <= 0 ? Domain.Orders.OrderItemStatus.Close : Domain.Orders.OrderItemStatus.Open;- }-- if (order.ShippingStatusId == ShippingStatus.Pending)- order.ShippingStatusId = ShippingStatus.PreparedToShipped;-- await _orderService.UpdateOrder(order);- }-foreach (var item in notification.Entity.ShipmentItems){- var product = await _productService.GetProductById(item.ProductId);- if (product != null)- await _inventoryManageService.BookReservedInventory(product, notification.Entity, item);+ var orderItem = order.OrderItems.FirstOrDefault(x => x.Id == item.OrderItemId);+ if (orderItem == null) continue;+ orderItem.ShipQty += item.Quantity;+ orderItem.OpenQty -= item.Quantity;+ orderItem.Status = orderItem.OpenQty <= 0 ? OrderItemStatus.Close : OrderItemStatus.Open;}+ if (order.ShippingStatusId == ShippingStatus.Pending)+ order.ShippingStatusId = ShippingStatus.PreparedToShipped;++ await _orderService.UpdateOrder(order);+ }++ foreach (var item in notification.Entity.ShipmentItems)+ {+ var product = await _productService.GetProductById(item.ProductId);+ if (product != null)+ await _inventoryManageService.BookReservedInventory(product, notification.Entity, item);}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.csindex 1ba2ec6a9..7af975b52 100644--- a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/CustomerLoggedInEventHandler.cs@@ -1,26 +1,24 @@-using Grand.Business.Core.Interfaces.Checkout.Orders;-using Grand.Business.Core.Events.Customers;+using Grand.Business.Core.Events.Customers;+using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Infrastructure;using MediatR;-namespace Grand.Business.Checkout.Events.ShoppingCart-{- public class CustomerLoggedInEventHandler : INotificationHandler<CustomerLoggedInEvent>- {- private readonly IShoppingCartService _shoppingCartService;- private readonly IWorkContext _workContext;+namespace Grand.Business.Checkout.Events.ShoppingCart;- public CustomerLoggedInEventHandler(IShoppingCartService shoppingCartService, IWorkContext workContext)- {- _shoppingCartService = shoppingCartService;- _workContext = workContext;- }+public class CustomerLoggedInEventHandler : INotificationHandler<CustomerLoggedInEvent>+{+ private readonly IShoppingCartService _shoppingCartService;+ private readonly IWorkContext _workContext;- public async Task Handle(CustomerLoggedInEvent notification, CancellationToken cancellationToken)- {- //migrate shopping cart- await _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, notification.Customer, true);+ public CustomerLoggedInEventHandler(IShoppingCartService shoppingCartService, IWorkContext workContext)+ {+ _shoppingCartService = shoppingCartService;+ _workContext = workContext;+ }- }+ public async Task Handle(CustomerLoggedInEvent notification, CancellationToken cancellationToken)+ {+ //migrate shopping cart+ await _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, notification.Customer, true);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.csindex dc1a3b798..7de8b4c64 100644--- a/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.cs+++ b/src/Business/Grand.Business.Checkout/Events/ShoppingCart/ShoppingCartItemDeletedEventHandler.cs@@ -3,31 +3,28 @@ using Grand.Domain.Orders;using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Business.Checkout.Events.ShoppingCart-{- /// <summary>- /// Update order items- /// </summary>- public class ShoppingCartItemDeletedEventHandler : INotificationHandler<EntityDeleted<ShoppingCartItem>>- {+namespace Grand.Business.Checkout.Events.ShoppingCart;- private readonly IProductReservationService _productReservationService;+/// <summary>+/// Update order items+/// </summary>+public class ShoppingCartItemDeletedEventHandler : INotificationHandler<EntityDeleted<ShoppingCartItem>>+{+ private readonly IProductReservationService _productReservationService;- public ShoppingCartItemDeletedEventHandler(IProductReservationService productReservationService)- {- _productReservationService = productReservationService;- }+ public ShoppingCartItemDeletedEventHandler(IProductReservationService productReservationService)+ {+ _productReservationService = productReservationService;+ }- public async Task Handle(EntityDeleted<ShoppingCartItem> notification, CancellationToken cancellationToken)+ public async Task Handle(EntityDeleted<ShoppingCartItem> notification, CancellationToken cancellationToken)+ {+ if ((notification.Entity.RentalStartDateUtc.HasValue && notification.Entity.RentalEndDateUtc.HasValue) ||+ !string.IsNullOrEmpty(notification.Entity.ReservationId)){- if ((notification.Entity.RentalStartDateUtc.HasValue && notification.Entity.RentalEndDateUtc.HasValue) || !string.IsNullOrEmpty(notification.Entity.ReservationId))- {- var reserved = await _productReservationService.GetCustomerReservationsHelperBySciId(notification.Entity.Id);- foreach (var res in reserved)- {- await _productReservationService.DeleteCustomerReservationsHelper(res);- }- }+ var reserved =+ await _productReservationService.GetCustomerReservationsHelperBySciId(notification.Entity.Id);+ foreach (var res in reserved) await _productReservationService.DeleteCustomerReservationsHelper(res);}}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.csindex f182d12bc..b0e1901c9 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs@@ -2,17 +2,16 @@using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanCancelOrderQueryHandler : IRequestHandler<CanCancelOrderQuery, bool>{- public class CanCancelOrderQueryHandler : IRequestHandler<CanCancelOrderQuery, bool>+ public Task<bool> Handle(CanCancelOrderQuery request, CancellationToken cancellationToken){- public Task<bool> Handle(CanCancelOrderQuery request, CancellationToken cancellationToken)- {- var order = request.Order;- if (order == null)- throw new ArgumentNullException(nameof(request.Order));+ var order = request.Order;+ if (order == null)+ throw new ArgumentNullException(nameof(request.Order));- return Task.FromResult(order.OrderStatusId == (int)OrderStatusSystem.Pending);- }+ return Task.FromResult(order.OrderStatusId == (int)OrderStatusSystem.Pending);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.csindex 2e9834d60..4e56c77c3 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs@@ -3,28 +3,27 @@ using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanCaptureQueryHandler : IRequestHandler<CanCaptureQuery, bool>{- public class CanCaptureQueryHandler : IRequestHandler<CanCaptureQuery, bool>- {- private readonly IPaymentService _paymentService;+ private readonly IPaymentService _paymentService;- public CanCaptureQueryHandler(IPaymentService paymentService)- {- _paymentService = paymentService;- }+ public CanCaptureQueryHandler(IPaymentService paymentService)+ {+ _paymentService = paymentService;+ }- public async Task<bool> Handle(CanCaptureQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ public async Task<bool> Handle(CanCaptureQuery request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Pending)- return false;+ if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Pending)+ return false;- return paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&- await _paymentService.SupportCapture(paymentTransaction.PaymentMethodSystemName);- }+ return paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&+ await _paymentService.SupportCapture(paymentTransaction.PaymentMethodSystemName);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.csindex 888b373ba..58e8ed8be 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs@@ -2,17 +2,20 @@using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class+ CanMarkPaymentTransactionAsAuthorizedQueryHandler : IRequestHandler<CanMarkPaymentTransactionAsAuthorizedQuery,+ bool>{- public class CanMarkPaymentTransactionAsAuthorizedQueryHandler : IRequestHandler<CanMarkPaymentTransactionAsAuthorizedQuery, bool>+ public Task<bool> Handle(CanMarkPaymentTransactionAsAuthorizedQuery request, CancellationToken cancellationToken){- public Task<bool> Handle(CanMarkPaymentTransactionAsAuthorizedQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- return paymentTransaction.TransactionStatus == TransactionStatus.Canceled ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Pending);- }+ return paymentTransaction.TransactionStatus == TransactionStatus.Canceled+ ? Task.FromResult(false)+ : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Pending);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.csindex 2af4804fd..9784003e0 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs@@ -2,20 +2,20 @@using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanMarkPaymentTransactionAsPaidQueryHandler : IRequestHandler<CanMarkPaymentTransactionAsPaidQuery, bool>{- public class CanMarkPaymentTransactionAsPaidQueryHandler : IRequestHandler<CanMarkPaymentTransactionAsPaidQuery, bool>+ public async Task<bool> Handle(CanMarkPaymentTransactionAsPaidQuery request, CancellationToken cancellationToken){- public async Task<bool> Handle(CanMarkPaymentTransactionAsPaidQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Paid or TransactionStatus.Refunded or TransactionStatus.PartiallyRefunded or TransactionStatus.Voided)- return false;+ if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Paid+ or TransactionStatus.Refunded or TransactionStatus.PartiallyRefunded or TransactionStatus.Voided)+ return false;- return await Task.FromResult(true);- }+ return await Task.FromResult(true);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.csindex ec1d11ea4..3dd54ab43 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs@@ -2,26 +2,28 @@using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanPartiallyPaidOfflineQueryHandler : IRequestHandler<CanPartiallyPaidOfflineQuery, bool>{- public class CanPartiallyPaidOfflineQueryHandler : IRequestHandler<CanPartiallyPaidOfflineQuery, bool>+ public Task<bool> Handle(CanPartiallyPaidOfflineQuery request, CancellationToken cancellationToken){- public Task<bool> Handle(CanPartiallyPaidOfflineQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- var amountToPaid = request.AmountToPaid;+ var amountToPaid = request.AmountToPaid;- if (paymentTransaction.TransactionAmount == 0)- return Task.FromResult(false);+ if (paymentTransaction.TransactionAmount == 0)+ return Task.FromResult(false);- var canBePaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;- if (canBePaid <= 0)- return Task.FromResult(false);+ var canBePaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount;+ if (canBePaid <= 0)+ return Task.FromResult(false);- return amountToPaid > canBePaid ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus is TransactionStatus.PartialPaid or TransactionStatus.Pending or TransactionStatus.PartiallyRefunded or TransactionStatus.Refunded);- }+ return amountToPaid > canBePaid+ ? Task.FromResult(false)+ : Task.FromResult(paymentTransaction.TransactionStatus is TransactionStatus.PartialPaid+ or TransactionStatus.Pending or TransactionStatus.PartiallyRefunded or TransactionStatus.Refunded);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.csindex 8547028ea..11ff7d13e 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs@@ -2,26 +2,28 @@using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanPartiallyRefundOfflineQueryHandler : IRequestHandler<CanPartiallyRefundOfflineQuery, bool>{- public class CanPartiallyRefundOfflineQueryHandler : IRequestHandler<CanPartiallyRefundOfflineQuery, bool>+ public Task<bool> Handle(CanPartiallyRefundOfflineQuery request, CancellationToken cancellationToken){- public Task<bool> Handle(CanPartiallyRefundOfflineQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- var amountToRefund = request.AmountToRefund;+ var amountToRefund = request.AmountToRefund;- if (paymentTransaction.TransactionAmount == 0)- return Task.FromResult(false);+ if (paymentTransaction.TransactionAmount == 0)+ return Task.FromResult(false);- var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;- if (canBeRefunded <= 0)- return Task.FromResult(false);+ var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;+ if (canBeRefunded <= 0)+ return Task.FromResult(false);- return amountToRefund > canBeRefunded ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded);- }+ return amountToRefund > canBeRefunded+ ? Task.FromResult(false)+ : Task.FromResult(paymentTransaction.TransactionStatus is TransactionStatus.Paid+ or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.csindex 71363d198..8bf49cfb9 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs@@ -3,41 +3,41 @@ using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanPartiallyRefundQueryHandler : IRequestHandler<CanPartiallyRefundQuery, bool>{- public class CanPartiallyRefundQueryHandler : IRequestHandler<CanPartiallyRefundQuery, bool>- {- private readonly IPaymentService _paymentService;+ private readonly IPaymentService _paymentService;- public CanPartiallyRefundQueryHandler(IPaymentService paymentService)- {- _paymentService = paymentService;- }+ public CanPartiallyRefundQueryHandler(IPaymentService paymentService)+ {+ _paymentService = paymentService;+ }- public async Task<bool> Handle(CanPartiallyRefundQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ public async Task<bool> Handle(CanPartiallyRefundQuery request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- var amountToRefund = request.AmountToRefund;+ var amountToRefund = request.AmountToRefund;- if (paymentTransaction.TransactionAmount == 0)- return false;+ if (paymentTransaction.TransactionAmount == 0)+ return false;- //uncomment the lines below in order to allow this operation for cancelled orders- //if (order.OrderStatus == OrderStatus.Cancelled)- // return false;+ //uncomment the lines below in order to allow this operation for cancelled orders+ //if (order.OrderStatus == OrderStatus.Cancelled)+ // return false;- var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;- if (canBeRefunded <= 0)- return false;+ var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount;+ if (canBeRefunded <= 0)+ return false;- if (amountToRefund > canBeRefunded)- return false;+ if (amountToRefund > canBeRefunded)+ return false;- return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded &&- await _paymentService.SupportPartiallyRefund(paymentTransaction.PaymentMethodSystemName);- }+ return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid+ or TransactionStatus.PartiallyRefunded &&+ await _paymentService.SupportPartiallyRefund(paymentTransaction.PaymentMethodSystemName);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.csindex 47797d3b7..7414b7cc9 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs@@ -2,21 +2,22 @@using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanRefundOfflineQueryHandler : IRequestHandler<CanRefundOfflineQuery, bool>{- public class CanRefundOfflineQueryHandler : IRequestHandler<CanRefundOfflineQuery, bool>+ public Task<bool> Handle(CanRefundOfflineQuery request, CancellationToken cancellationToken){- public Task<bool> Handle(CanRefundOfflineQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionAmount == 0)- return Task.FromResult(false);+ if (paymentTransaction.TransactionAmount == 0)+ return Task.FromResult(false);- //refund cannot be made if previously a partial refund has been already done. only other partial refund can be made in this case- return paymentTransaction.RefundedAmount > 0 ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Paid);- }+ //refund cannot be made if previously a partial refund has been already done. only other partial refund can be made in this case+ return paymentTransaction.RefundedAmount > 0+ ? Task.FromResult(false)+ : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Paid);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.csindex f49d49cba..2acf964a4 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs@@ -3,33 +3,33 @@ using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanRefundQueryHandler : IRequestHandler<CanRefundQuery, bool>{- public class CanRefundQueryHandler : IRequestHandler<CanRefundQuery, bool>- {- private readonly IPaymentService _paymentService;+ private readonly IPaymentService _paymentService;- public CanRefundQueryHandler(IPaymentService paymentService)- {- _paymentService = paymentService;- }+ public CanRefundQueryHandler(IPaymentService paymentService)+ {+ _paymentService = paymentService;+ }- public async Task<bool> Handle(CanRefundQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ public async Task<bool> Handle(CanRefundQuery request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionAmount == 0)- return false;+ if (paymentTransaction.TransactionAmount == 0)+ return false;- if (paymentTransaction.RefundedAmount > 0)- return false;+ if (paymentTransaction.RefundedAmount > 0)+ return false;- //if (order.OrderStatus == OrderStatus.Cancelled)- // return false;- return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid or TransactionStatus.PartiallyRefunded &&- await _paymentService.SupportRefund(paymentTransaction.PaymentMethodSystemName);- }+ //if (order.OrderStatus == OrderStatus.Cancelled)+ // return false;+ return paymentTransaction.TransactionStatus is TransactionStatus.Paid or TransactionStatus.PartialPaid+ or TransactionStatus.PartiallyRefunded &&+ await _paymentService.SupportRefund(paymentTransaction.PaymentMethodSystemName);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.csindex 43dace663..57156643c 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs@@ -2,17 +2,18 @@using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanVoidOfflineQueryHandler : IRequestHandler<CanVoidOfflineQuery, bool>{- public class CanVoidOfflineQueryHandler : IRequestHandler<CanVoidOfflineQuery, bool>+ public Task<bool> Handle(CanVoidOfflineQuery request, CancellationToken cancellationToken){- public Task<bool> Handle(CanVoidOfflineQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- return paymentTransaction.TransactionAmount == 0 ? Task.FromResult(false) : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Authorized);- }+ return paymentTransaction.TransactionAmount == 0+ ? Task.FromResult(false)+ : Task.FromResult(paymentTransaction.TransactionStatus == TransactionStatus.Authorized);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.csindex 55487eae8..e6c0e8fef 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs@@ -3,28 +3,27 @@ using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class CanVoidQueryHandler : IRequestHandler<CanVoidQuery, bool>{- public class CanVoidQueryHandler : IRequestHandler<CanVoidQuery, bool>- {- private readonly IPaymentService _paymentService;+ private readonly IPaymentService _paymentService;- public CanVoidQueryHandler(IPaymentService paymentService)- {- _paymentService = paymentService;- }+ public CanVoidQueryHandler(IPaymentService paymentService)+ {+ _paymentService = paymentService;+ }- public async Task<bool> Handle(CanVoidQuery request, CancellationToken cancellationToken)- {- var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ public async Task<bool> Handle(CanVoidQuery request, CancellationToken cancellationToken)+ {+ var paymentTransaction = request.PaymentTransaction;+ if (paymentTransaction == null)+ throw new ArgumentNullException(nameof(request.PaymentTransaction));- if (paymentTransaction.TransactionAmount == 0)- return false;+ if (paymentTransaction.TransactionAmount == 0)+ return false;- return paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&- await _paymentService.SupportVoid(paymentTransaction.PaymentMethodSystemName);- }+ return paymentTransaction.TransactionStatus == TransactionStatus.Authorized &&+ await _paymentService.SupportVoid(paymentTransaction.PaymentMethodSystemName);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.csindex ba5f4d6a6..acb7c6e7b 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetGiftVoucherQueryHandler.cs@@ -3,42 +3,41 @@ using Grand.Data;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class GetGiftVoucherQueryHandler : IRequestHandler<GetGiftVoucherQuery, IQueryable<GiftVoucher>>{- public class GetGiftVoucherQueryHandler : IRequestHandler<GetGiftVoucherQuery, IQueryable<GiftVoucher>>+ private readonly IRepository<GiftVoucher> _giftVoucherRepository;++ public GetGiftVoucherQueryHandler(IRepository<GiftVoucher> giftVoucherRepository)+ {+ _giftVoucherRepository = giftVoucherRepository;+ }++ public Task<IQueryable<GiftVoucher>> Handle(GetGiftVoucherQuery request, CancellationToken cancellationToken){- private readonly IRepository<GiftVoucher> _giftVoucherRepository;-- public GetGiftVoucherQueryHandler(IRepository<GiftVoucher> giftVoucherRepository)- {- _giftVoucherRepository = giftVoucherRepository;- }-- public Task<IQueryable<GiftVoucher>> Handle(GetGiftVoucherQuery request, CancellationToken cancellationToken)- {- var query = from p in _giftVoucherRepository.Table- select p;-- if (!string.IsNullOrEmpty(request.GiftVoucherId))- query = query.Where(gc => gc.Id == request.GiftVoucherId);-- if (!string.IsNullOrEmpty(request.PurchasedWithOrderItemId))- query = query.Where(gc => gc.PurchasedWithOrderItem.Id == request.PurchasedWithOrderItemId);-- if (request.CreatedFromUtc.HasValue)- query = query.Where(gc => request.CreatedFromUtc.Value <= gc.CreatedOnUtc);- if (request.CreatedToUtc.HasValue)- query = query.Where(gc => request.CreatedToUtc.Value >= gc.CreatedOnUtc);- if (request.IsGiftVoucherActivated.HasValue)- query = query.Where(gc => gc.IsGiftVoucherActivated == request.IsGiftVoucherActivated.Value);- if (!string.IsNullOrEmpty(request.Code))- query = query.Where(gc => gc.Code!=null && gc.Code == request.Code.ToLowerInvariant());- if (!string.IsNullOrWhiteSpace(request.RecipientName))- query = query.Where(c => c.RecipientName!=null && c.RecipientName.Contains(request.RecipientName));-- query = query.OrderByDescending(gc => gc.CreatedOnUtc);-- return Task.FromResult(query);- }+ var query = from p in _giftVoucherRepository.Table+ select p;++ if (!string.IsNullOrEmpty(request.GiftVoucherId))+ query = query.Where(gc => gc.Id == request.GiftVoucherId);++ if (!string.IsNullOrEmpty(request.PurchasedWithOrderItemId))+ query = query.Where(gc => gc.PurchasedWithOrderItem.Id == request.PurchasedWithOrderItemId);++ if (request.CreatedFromUtc.HasValue)+ query = query.Where(gc => request.CreatedFromUtc.Value <= gc.CreatedOnUtc);+ if (request.CreatedToUtc.HasValue)+ query = query.Where(gc => request.CreatedToUtc.Value >= gc.CreatedOnUtc);+ if (request.IsGiftVoucherActivated.HasValue)+ query = query.Where(gc => gc.IsGiftVoucherActivated == request.IsGiftVoucherActivated.Value);+ if (!string.IsNullOrEmpty(request.Code))+ query = query.Where(gc => gc.Code != null && gc.Code == request.Code.ToLowerInvariant());+ if (!string.IsNullOrWhiteSpace(request.RecipientName))+ query = query.Where(c => c.RecipientName != null && c.RecipientName.Contains(request.RecipientName));++ query = query.OrderByDescending(gc => gc.CreatedOnUtc);++ return Task.FromResult(query);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.csindex a86495cfa..dab2e3bbe 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnCountQueryHandler.cs@@ -3,22 +3,22 @@ using Grand.Data;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class GetMerchandiseReturnCountQueryHandler : IRequestHandler<GetMerchandiseReturnCountQuery, int>{- public class GetMerchandiseReturnCountQueryHandler : IRequestHandler<GetMerchandiseReturnCountQuery, int>- {- private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;+ private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;- public GetMerchandiseReturnCountQueryHandler(IRepository<MerchandiseReturn> merchandiseReturnRepository)- {- _merchandiseReturnRepository = merchandiseReturnRepository;- }+ public GetMerchandiseReturnCountQueryHandler(IRepository<MerchandiseReturn> merchandiseReturnRepository)+ {+ _merchandiseReturnRepository = merchandiseReturnRepository;+ }- public async Task<int> Handle(GetMerchandiseReturnCountQuery request, CancellationToken cancellationToken)- {- return await Task.FromResult(- _merchandiseReturnRepository.Table.Count(x => x.MerchandiseReturnStatusId == request.RequestStatusId &&- (string.IsNullOrEmpty(request.StoreId) || x.StoreId == request.StoreId)));- }+ public async Task<int> Handle(GetMerchandiseReturnCountQuery request, CancellationToken cancellationToken)+ {+ return await Task.FromResult(+ _merchandiseReturnRepository.Table.Count(x => x.MerchandiseReturnStatusId == request.RequestStatusId &&+ (string.IsNullOrEmpty(request.StoreId) ||+ x.StoreId == request.StoreId)));}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.csindex bb4e3f6d8..bf91a6b5a 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs@@ -3,51 +3,53 @@ using Grand.Data;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class+ GetMerchandiseReturnQueryHandler : IRequestHandler<GetMerchandiseReturnQuery, IQueryable<MerchandiseReturn>>{- public class GetMerchandiseReturnQueryHandler : IRequestHandler<GetMerchandiseReturnQuery, IQueryable<MerchandiseReturn>>+ private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;++ public GetMerchandiseReturnQueryHandler(IRepository<MerchandiseReturn> merchandiseReturnRepository){- private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;+ _merchandiseReturnRepository = merchandiseReturnRepository;+ }- public GetMerchandiseReturnQueryHandler(IRepository<MerchandiseReturn> merchandiseReturnRepository)- {- _merchandiseReturnRepository = merchandiseReturnRepository;- }+ public Task<IQueryable<MerchandiseReturn>> Handle(GetMerchandiseReturnQuery request,+ CancellationToken cancellationToken)+ {+ var query = from p in _merchandiseReturnRepository.Table+ select p;- public Task<IQueryable<MerchandiseReturn>> Handle(GetMerchandiseReturnQuery request, CancellationToken cancellationToken)- {- var query = from p in _merchandiseReturnRepository.Table- select p;+ if (!string.IsNullOrEmpty(request.StoreId))+ query = query.Where(rr => request.StoreId == rr.StoreId);- if (!string.IsNullOrEmpty(request.StoreId))- query = query.Where(rr => request.StoreId == rr.StoreId);+ if (!string.IsNullOrEmpty(request.CustomerId))+ query = query.Where(rr => request.CustomerId == rr.CustomerId);- if (!string.IsNullOrEmpty(request.CustomerId))- query = query.Where(rr => request.CustomerId == rr.CustomerId);+ if (!string.IsNullOrEmpty(request.VendorId))+ query = query.Where(rr => request.VendorId == rr.VendorId);- if (!string.IsNullOrEmpty(request.VendorId))- query = query.Where(rr => request.VendorId == rr.VendorId);+ if (!string.IsNullOrEmpty(request.OwnerId))+ query = query.Where(rr => request.OwnerId == rr.OwnerId);- if (!string.IsNullOrEmpty(request.OwnerId))- query = query.Where(rr => request.OwnerId == rr.OwnerId);+ if (request.Rs.HasValue)+ {+ var returnStatusId = (int)request.Rs.Value;+ query = query.Where(rr => rr.MerchandiseReturnStatusId == returnStatusId);+ }- if (request.Rs.HasValue)- {- var returnStatusId = (int)request.Rs.Value;- query = query.Where(rr => rr.MerchandiseReturnStatusId == returnStatusId);- }- if (!string.IsNullOrEmpty(request.OrderItemId))- query = query.Where(rr => rr.MerchandiseReturnItems.Any(x => x.OrderItemId == request.OrderItemId));+ if (!string.IsNullOrEmpty(request.OrderItemId))+ query = query.Where(rr => rr.MerchandiseReturnItems.Any(x => x.OrderItemId == request.OrderItemId));- if (request.CreatedFromUtc.HasValue)- query = query.Where(rr => request.CreatedFromUtc.Value <= rr.CreatedOnUtc);+ if (request.CreatedFromUtc.HasValue)+ query = query.Where(rr => request.CreatedFromUtc.Value <= rr.CreatedOnUtc);- if (request.CreatedToUtc.HasValue)- query = query.Where(rr => request.CreatedToUtc.Value >= rr.CreatedOnUtc);+ if (request.CreatedToUtc.HasValue)+ query = query.Where(rr => request.CreatedToUtc.Value >= rr.CreatedOnUtc);- query = query.OrderByDescending(rr => rr.CreatedOnUtc);+ query = query.OrderByDescending(rr => rr.CreatedOnUtc);- return Task.FromResult(query);- }+ return Task.FromResult(query);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.csindex 77eb9ac24..cae94b410 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs@@ -3,109 +3,100 @@ using Grand.Data;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, IQueryable<Order>>{- public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, IQueryable<Order>>- {- private readonly IRepository<Order> _orderRepository;+ private readonly IRepository<Order> _orderRepository;- public GetOrderQueryHandler(IRepository<Order> orderRepository)- {- _orderRepository = orderRepository;- }+ public GetOrderQueryHandler(IRepository<Order> orderRepository)+ {+ _orderRepository = orderRepository;+ }- public Task<IQueryable<Order>> Handle(GetOrderQuery request, CancellationToken cancellationToken)- {- var query = from p in _orderRepository.Table- select p;+ public Task<IQueryable<Order>> Handle(GetOrderQuery request, CancellationToken cancellationToken)+ {+ var query = from p in _orderRepository.Table+ select p;- if (!string.IsNullOrEmpty(request.OrderId))- query = query.Where(o => o.Id == request.OrderId);+ if (!string.IsNullOrEmpty(request.OrderId))+ query = query.Where(o => o.Id == request.OrderId);- if (!string.IsNullOrEmpty(request.StoreId))- query = query.Where(o => o.StoreId == request.StoreId);+ if (!string.IsNullOrEmpty(request.StoreId))+ query = query.Where(o => o.StoreId == request.StoreId);- if (!string.IsNullOrEmpty(request.VendorId))- {- query = query- .Where(o => o.OrderItems+ if (!string.IsNullOrEmpty(request.VendorId))+ query = query+ .Where(o => o.OrderItems.Any(orderItem => orderItem.VendorId == request.VendorId));- }- if (!string.IsNullOrEmpty(request.CustomerId))- query = query.Where(o => o.CustomerId == request.CustomerId);+ if (!string.IsNullOrEmpty(request.CustomerId))+ query = query.Where(o => o.CustomerId == request.CustomerId);- if (!string.IsNullOrEmpty(request.CustomerId))- query = query.Where(o => o.CustomerId == request.CustomerId);+ if (!string.IsNullOrEmpty(request.CustomerId))+ query = query.Where(o => o.CustomerId == request.CustomerId);- if (!string.IsNullOrEmpty(request.SalesEmployeeId))- query = query.Where(o => o.SeId == request.SalesEmployeeId);+ if (!string.IsNullOrEmpty(request.SalesEmployeeId))+ query = query.Where(o => o.SeId == request.SalesEmployeeId);- if (!string.IsNullOrEmpty(request.ProductId))- {- query = query- .Where(o => o.OrderItems+ if (!string.IsNullOrEmpty(request.ProductId))+ query = query+ .Where(o => o.OrderItems.Any(orderItem => orderItem.ProductId == request.ProductId));- }- if (!string.IsNullOrEmpty(request.WarehouseId))- {- query = query- .Where(o => o.OrderItems+ if (!string.IsNullOrEmpty(request.WarehouseId))+ query = query+ .Where(o => o.OrderItems.Any(orderItem =>orderItem.WarehouseId == request.WarehouseId- ));- }- if (!string.IsNullOrEmpty(request.BillingCountryId))- query = query.Where(o => o.BillingAddress != null && o.BillingAddress.CountryId == request.BillingCountryId);+ ));+ if (!string.IsNullOrEmpty(request.BillingCountryId))+ query = query.Where(o =>+ o.BillingAddress != null && o.BillingAddress.CountryId == request.BillingCountryId);- if (!string.IsNullOrEmpty(request.PaymentMethodSystemName))- query = query.Where(o => o.PaymentMethodSystemName == request.PaymentMethodSystemName);+ if (!string.IsNullOrEmpty(request.PaymentMethodSystemName))+ query = query.Where(o => o.PaymentMethodSystemName == request.PaymentMethodSystemName);- if (!string.IsNullOrEmpty(request.AffiliateId))- query = query.Where(o => o.AffiliateId == request.AffiliateId);+ if (!string.IsNullOrEmpty(request.AffiliateId))+ query = query.Where(o => o.AffiliateId == request.AffiliateId);- if (!string.IsNullOrEmpty(request.OwnerId))- query = query.Where(o => o.OwnerId == request.OwnerId);+ if (!string.IsNullOrEmpty(request.OwnerId))+ query = query.Where(o => o.OwnerId == request.OwnerId);- if (request.CreatedFromUtc.HasValue)- query = query.Where(o => request.CreatedFromUtc.Value <= o.CreatedOnUtc);+ if (request.CreatedFromUtc.HasValue)+ query = query.Where(o => request.CreatedFromUtc.Value <= o.CreatedOnUtc);- if (request.CreatedToUtc.HasValue)- query = query.Where(o => request.CreatedToUtc.Value >= o.CreatedOnUtc);+ if (request.CreatedToUtc.HasValue)+ query = query.Where(o => request.CreatedToUtc.Value >= o.CreatedOnUtc);- if (request.Os.HasValue)- query = query.Where(o => request.Os.Value == o.OrderStatusId);+ if (request.Os.HasValue)+ query = query.Where(o => request.Os.Value == o.OrderStatusId);- if (request.Ps.HasValue)- query = query.Where(o => request.Ps.Value == o.PaymentStatusId);+ if (request.Ps.HasValue)+ query = query.Where(o => request.Ps.Value == o.PaymentStatusId);- if (request.Ss.HasValue)- query = query.Where(o => request.Ss.Value == o.ShippingStatusId);+ if (request.Ss.HasValue)+ query = query.Where(o => request.Ss.Value == o.ShippingStatusId);- if (!string.IsNullOrEmpty(request.BillingEmail))- query = query.Where(o => o.BillingAddress != null && o.BillingAddress.Email == request.BillingEmail);+ if (!string.IsNullOrEmpty(request.BillingEmail))+ query = query.Where(o => o.BillingAddress != null && o.BillingAddress.Email == request.BillingEmail);- if (!string.IsNullOrEmpty(request.BillingLastName))- query = query.Where(o => o.BillingAddress != null && o.BillingAddress.LastName.Contains(request.BillingLastName));+ if (!string.IsNullOrEmpty(request.BillingLastName))+ query = query.Where(o =>+ o.BillingAddress != null && o.BillingAddress.LastName.Contains(request.BillingLastName));- if (!string.IsNullOrEmpty(request.OrderGuid))- {- if (Guid.TryParse(request.OrderGuid, out Guid orderGuid))- query = query.Where(o => o.OrderGuid == orderGuid);- }- if (!string.IsNullOrEmpty(request.OrderCode))- {- query = query.Where(o => o.Code == request.OrderCode.ToUpperInvariant());- }+ if (!string.IsNullOrEmpty(request.OrderGuid))+ if (Guid.TryParse(request.OrderGuid, out var orderGuid))+ query = query.Where(o => o.OrderGuid == orderGuid);+ if (!string.IsNullOrEmpty(request.OrderCode))+ query = query.Where(o => o.Code == request.OrderCode.ToUpperInvariant());- //tag filtering- if (!string.IsNullOrEmpty(request.OrderTagId))- query = query.Where(o => o.OrderTags.Any(y => y == request.OrderTagId));+ //tag filtering+ if (!string.IsNullOrEmpty(request.OrderTagId))+ query = query.Where(o => o.OrderTags.Any(y => y == request.OrderTagId));- query = query.Where(o => !o.Deleted);- query = query.OrderByDescending(o => o.CreatedOnUtc);+ query = query.Where(o => !o.Deleted);+ query = query.OrderByDescending(o => o.CreatedOnUtc);- return Task.FromResult(query);- }+ return Task.FromResult(query);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.csindex 24b55b753..96417bf34 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs@@ -3,43 +3,44 @@ using Grand.Data;using Grand.Domain.Payments;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class+ GetPaymentTransactionQueryHandler : IRequestHandler<GetPaymentTransactionQuery, IQueryable<PaymentTransaction>>{- public class GetPaymentTransactionQueryHandler : IRequestHandler<GetPaymentTransactionQuery, IQueryable<PaymentTransaction>>- {- private readonly IRepository<PaymentTransaction> _paymentTransactionRepository;+ private readonly IRepository<PaymentTransaction> _paymentTransactionRepository;- public GetPaymentTransactionQueryHandler(IRepository<PaymentTransaction> paymentTransactionRepository)- {- _paymentTransactionRepository = paymentTransactionRepository;- }+ public GetPaymentTransactionQueryHandler(IRepository<PaymentTransaction> paymentTransactionRepository)+ {+ _paymentTransactionRepository = paymentTransactionRepository;+ }- public Task<IQueryable<PaymentTransaction>> Handle(GetPaymentTransactionQuery request, CancellationToken cancellationToken)- {- var query = from p in _paymentTransactionRepository.Table- select p;+ public Task<IQueryable<PaymentTransaction>> Handle(GetPaymentTransactionQuery request,+ CancellationToken cancellationToken)+ {+ var query = from p in _paymentTransactionRepository.Table+ select p;- if (!string.IsNullOrEmpty(request.StoreId))- query = query.Where(rr => request.StoreId == rr.StoreId);+ if (!string.IsNullOrEmpty(request.StoreId))+ query = query.Where(rr => request.StoreId == rr.StoreId);- if (!string.IsNullOrEmpty(request.CustomerEmail))- query = query.Where(rr => rr.CustomerEmail == request.CustomerEmail.ToLowerInvariant());+ if (!string.IsNullOrEmpty(request.CustomerEmail))+ query = query.Where(rr => rr.CustomerEmail == request.CustomerEmail.ToLowerInvariant());- if (request.OrderGuid.HasValue)- query = query.Where(rr => rr.OrderGuid == request.OrderGuid.Value);+ if (request.OrderGuid.HasValue)+ query = query.Where(rr => rr.OrderGuid == request.OrderGuid.Value);- if (request.Ts.HasValue)- query = query.Where(rr => rr.TransactionStatus == request.Ts.Value);+ if (request.Ts.HasValue)+ query = query.Where(rr => rr.TransactionStatus == request.Ts.Value);- if (request.CreatedFromUtc.HasValue)- query = query.Where(rr => request.CreatedFromUtc.Value <= rr.CreatedOnUtc);+ if (request.CreatedFromUtc.HasValue)+ query = query.Where(rr => request.CreatedFromUtc.Value <= rr.CreatedOnUtc);- if (request.CreatedToUtc.HasValue)- query = query.Where(rr => request.CreatedToUtc.Value >= rr.CreatedOnUtc);+ if (request.CreatedToUtc.HasValue)+ query = query.Where(rr => request.CreatedToUtc.Value >= rr.CreatedOnUtc);- query = query.OrderByDescending(rr => rr.CreatedOnUtc);+ query = query.OrderByDescending(rr => rr.CreatedOnUtc);- return Task.FromResult(query);- }+ return Task.FromResult(query);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.csindex 10849ac77..55ec16231 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs@@ -3,18 +3,19 @@ using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class GetPickupPointByIdQueryHandler : IRequestHandler<GetPickupPointById, PickupPoint>{- public class GetPickupPointByIdQueryHandler : IRequestHandler<GetPickupPointById, PickupPoint>+ private readonly IPickupPointService _pickupPointService;++ public GetPickupPointByIdQueryHandler(IPickupPointService pickupPointService)+ {+ _pickupPointService = pickupPointService;+ }++ public async Task<PickupPoint> Handle(GetPickupPointById request, CancellationToken cancellationToken){- private readonly IPickupPointService _pickupPointService;- public GetPickupPointByIdQueryHandler(IPickupPointService pickupPointService)- {- _pickupPointService = pickupPointService;- }- public async Task<PickupPoint> Handle(GetPickupPointById request, CancellationToken cancellationToken)- {- return await _pickupPointService.GetPickupPointById(request.Id);- }+ return await _pickupPointService.GetPickupPointById(request.Id);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.csindex 5bf4ba27a..ac6585120 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetVendorsInOrderQueryHandler.cs@@ -1,39 +1,35 @@-using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Orders;using Grand.Domain.Vendors;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class GetVendorsInOrderQueryHandler : IRequestHandler<GetVendorsInOrderQuery, IList<Vendor>>{- public class GetVendorsInOrderQueryHandler : IRequestHandler<GetVendorsInOrderQuery, IList<Vendor>>+ private readonly IVendorService _vendorService;++ public GetVendorsInOrderQueryHandler(IVendorService vendorService){- private readonly IVendorService _vendorService;+ _vendorService = vendorService;+ }- public GetVendorsInOrderQueryHandler(IVendorService vendorService)- {- _vendorService = vendorService;- }+ public async Task<IList<Vendor>> Handle(GetVendorsInOrderQuery request, CancellationToken cancellationToken)+ {+ return await GetVendorsInOrder(request.Order);+ }- public async Task<IList<Vendor>> Handle(GetVendorsInOrderQuery request, CancellationToken cancellationToken)+ protected virtual async Task<IList<Vendor>> GetVendorsInOrder(Order order)+ {+ var vendors = new List<Vendor>();+ foreach (var vendorKey in order.OrderItems.GroupBy(x => x.VendorId)){- return await GetVendorsInOrder(request.Order);+ if (string.IsNullOrEmpty(vendorKey.Key)) continue;+ var vendor = await _vendorService.GetVendorById(vendorKey.Key);+ if (vendor is { Deleted: false, Active: true }) vendors.Add(vendor);}- protected virtual async Task<IList<Vendor>> GetVendorsInOrder(Order order)- {- var vendors = new List<Vendor>();- foreach (var vendorKey in order.OrderItems.GroupBy(x => x.VendorId))- {- if (string.IsNullOrEmpty(vendorKey.Key)) continue;- var vendor = await _vendorService.GetVendorById(vendorKey.Key);- if (vendor is { Deleted: false, Active: true })- {- vendors.Add(vendor);- }- }-- return vendors;- }+ return vendors;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.csindex 0298ab378..0a5a4a90a 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/IsMerchandiseReturnAllowedQueryHandler.cs@@ -4,59 +4,62 @@ using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Queries.Handlers.Orders+namespace Grand.Business.Checkout.Queries.Handlers.Orders;++public class IsMerchandiseReturnAllowedQueryHandler : IRequestHandler<IsMerchandiseReturnAllowedQuery, bool>{- public class IsMerchandiseReturnAllowedQueryHandler : IRequestHandler<IsMerchandiseReturnAllowedQuery, bool>+ private readonly IMediator _mediator;+ private readonly OrderSettings _orderSettings;+ private readonly IProductService _productService;+ private readonly IShipmentService _shipmentService;++ public IsMerchandiseReturnAllowedQueryHandler(+ IShipmentService shipmentService,+ IProductService productService,+ IMediator mediator,+ OrderSettings orderSettings){- private readonly IShipmentService _shipmentService;- private readonly IProductService _productService;- private readonly IMediator _mediator;- private readonly OrderSettings _orderSettings;-- public IsMerchandiseReturnAllowedQueryHandler(- IShipmentService shipmentService,- IProductService productService,- IMediator mediator,- OrderSettings orderSettings)- {- _shipmentService = shipmentService;- _productService = productService;- _mediator = mediator;- _orderSettings = orderSettings;- }+ _shipmentService = shipmentService;+ _productService = productService;+ _mediator = mediator;+ _orderSettings = orderSettings;+ }++ public async Task<bool> Handle(IsMerchandiseReturnAllowedQuery request, CancellationToken cancellationToken)+ {+ if (!_orderSettings.MerchandiseReturnsEnabled)+ return false;- public async Task<bool> Handle(IsMerchandiseReturnAllowedQuery request, CancellationToken cancellationToken)+ if (request.Order == null || request.Order.Deleted)+ return false;++ var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);++ //validate allowed number of days+ if (_orderSettings.NumberOfDaysMerchandiseReturnAvailable > 0){- if (!_orderSettings.MerchandiseReturnsEnabled)+ var daysPassed = (DateTime.UtcNow - request.Order.CreatedOnUtc).TotalDays;+ if (daysPassed >= _orderSettings.NumberOfDaysMerchandiseReturnAvailable)return false;+ }- if (request.Order == null || request.Order.Deleted)+ foreach (var item in request.Order.OrderItems)+ {+ var product = await _productService.GetProductById(item.ProductId);+ if (product == null)return false;- var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);-- //validate allowed number of days- if (_orderSettings.NumberOfDaysMerchandiseReturnAvailable > 0)- {- var daysPassed = (DateTime.UtcNow - request.Order.CreatedOnUtc).TotalDays;- if (daysPassed >= _orderSettings.NumberOfDaysMerchandiseReturnAvailable)- return false;- }- foreach (var item in request.Order.OrderItems)- {- var product = await _productService.GetProductById(item.ProductId);- if (product == null)- return false;-- var qtyDelivery = shipments.Where(x => x.DeliveryDateUtc.HasValue).SelectMany(x => x.ShipmentItems).Where(x => x.OrderItemId == item.Id).Sum(x => x.Quantity);- var merchandiseReturns = (await _mediator.Send(new GetMerchandiseReturnQuery { OrderItemId = item.Id }, cancellationToken)).ToList();- var qtyReturn = merchandiseReturns.Sum(rr => rr.MerchandiseReturnItems.Sum(rrItem => rrItem.Quantity));-- if (!product.NotReturnable && qtyDelivery - qtyReturn > 0)- return true;- }- return false;+ var qtyDelivery = shipments.Where(x => x.DeliveryDateUtc.HasValue).SelectMany(x => x.ShipmentItems)+ .Where(x => x.OrderItemId == item.Id).Sum(x => x.Quantity);+ var merchandiseReturns =+ (await _mediator.Send(new GetMerchandiseReturnQuery { OrderItemId = item.Id }, cancellationToken))+ .ToList();+ var qtyReturn = merchandiseReturns.Sum(rr => rr.MerchandiseReturnItems.Sum(rrItem => rrItem.Quantity));+ if (!product.NotReturnable && qtyDelivery - qtyReturn > 0)+ return true;}++ return false;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.csindex 4e5580b7b..3b5c4e73f 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs@@ -11,141 +11,148 @@ using Grand.Infrastructure;using Grand.SharedKernel.Extensions;using System.Net;-namespace Grand.Business.Checkout.Services.CheckoutAttributes+namespace Grand.Business.Checkout.Services.CheckoutAttributes;++/// <summary>+/// Checkout attribute helper+/// </summary>+public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter{+ private readonly ICheckoutAttributeParser _checkoutAttributeParser;+ private readonly ICurrencyService _currencyService;+ private readonly IPriceFormatter _priceFormatter;+ private readonly ITaxService _taxService;+ private readonly IWorkContext _workContext;++ public CheckoutAttributeFormatter(IWorkContext workContext,+ ICheckoutAttributeParser checkoutAttributeParser,+ ICurrencyService currencyService,+ ITaxService taxService,+ IPriceFormatter priceFormatter)+ {+ _workContext = workContext;+ _checkoutAttributeParser = checkoutAttributeParser;+ _currencyService = currencyService;+ _taxService = taxService;+ _priceFormatter = priceFormatter;+ }+/// <summary>- /// Checkout attribute helper+ /// Formats attributes/// </summary>- public class CheckoutAttributeFormatter : ICheckoutAttributeFormatter+ /// <param name="customAttributes">Attributes</param>+ /// <param name="customer">Customer</param>+ /// <param name="separator">Separator</param>+ /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>+ /// <param name="renderPrices">A value indicating whether to render prices</param>+ /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>+ /// <returns>Attributes</returns>+ public virtual async Task<string> FormatAttributes(IList<CustomAttribute> customAttributes,+ Customer customer,+ string separator = "<br />",+ bool htmlEncode = true,+ bool renderPrices = true,+ bool allowHyperlinks = true){- private readonly IWorkContext _workContext;- private readonly ICheckoutAttributeParser _checkoutAttributeParser;- private readonly ICurrencyService _currencyService;- private readonly ITaxService _taxService;- private readonly IPriceFormatter _priceFormatter;+ var result = new StringBuilder();- public CheckoutAttributeFormatter(IWorkContext workContext,- ICheckoutAttributeParser checkoutAttributeParser,- ICurrencyService currencyService,- ITaxService taxService,- IPriceFormatter priceFormatter)- {- _workContext = workContext;- _checkoutAttributeParser = checkoutAttributeParser;- _currencyService = currencyService;- _taxService = taxService;- _priceFormatter = priceFormatter;- }+ if (customAttributes == null || !customAttributes.Any())+ return result.ToString();- /// <summary>- /// Formats attributes- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <param name="customer">Customer</param>- /// <param name="separator">Separator</param>- /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>- /// <param name="renderPrices">A value indicating whether to render prices</param>- /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>- /// <returns>Attributes</returns>- public virtual async Task<string> FormatAttributes(IList<CustomAttribute> customAttributes,- Customer customer,- string separator = "<br />",- bool htmlEncode = true,- bool renderPrices = true,- bool allowHyperlinks = true)+ var attributes = await _checkoutAttributeParser.ParseCheckoutAttributes(customAttributes);+ for (var i = 0; i < attributes.Count; i++){- var result = new StringBuilder();-- if (customAttributes == null || !customAttributes.Any())- return result.ToString();-- var attributes = await _checkoutAttributeParser.ParseCheckoutAttributes(customAttributes);- for (var i = 0; i < attributes.Count; i++)+ var attribute = attributes[i];+ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();+ for (var j = 0; j < valuesStr.Count; j++){- var attribute = attributes[i];- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();- for (var j = 0; j < valuesStr.Count; j++)+ var valueStr = valuesStr[j];+ var formattedAttribute = "";+ if (!attribute.ShouldHaveValues()){- var valueStr = valuesStr[j];- var formattedAttribute = "";- if (!attribute.ShouldHaveValues())+ switch (attribute.AttributeControlTypeId){- switch (attribute.AttributeControlTypeId)+ //no values+ case AttributeControlType.MultilineTextbox:{- //no values- case AttributeControlType.MultilineTextbox:- {- //multiline text box- var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);- //encode (if required)- if (htmlEncode)- attributeName = WebUtility.HtmlEncode(attributeName);- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";- //we never encode multiline text box input- break;- }- case AttributeControlType.FileUpload:+ //multiline text box+ var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);+ //encode (if required)+ if (htmlEncode)+ attributeName = WebUtility.HtmlEncode(attributeName);+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";+ //we never encode multiline text box input+ break;+ }+ case AttributeControlType.FileUpload:+ {+ //file upload+ if (Guid.TryParse(valueStr, out var downloadGuid)){- //file upload- if (Guid.TryParse(valueStr, out var downloadGuid))+ var attributeText = string.Empty;+ var attributeName =+ attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);+ if (allowHyperlinks){- var attributeText = string.Empty;- var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);- if (allowHyperlinks)- {- //hyperlinks are allowed- var downloadLink =- $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";- attributeText =- $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)}</a>";- }- formattedAttribute = $"{attributeName}: {attributeText}";+ //hyperlinks are allowed+ var downloadLink =+ $"{_workContext.CurrentHost.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}";+ attributeText =+ $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{attribute.GetTranslation(a => a.TextPrompt, _workContext.WorkingLanguage.Id)}</a>";}- break;- }- default:- {- //other attributes (text box, datepicker)- formattedAttribute =- $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";- //encode (if required)- if (htmlEncode)- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);- break;+ formattedAttribute = $"{attributeName}: {attributeText}";}++ break;+ }+ default:+ {+ //other attributes (text box, datepicker)+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";+ //encode (if required)+ if (htmlEncode)+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);+ break;}}- else+ }+ else+ {+ var attributeValue = attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr);+ if (attributeValue != null){- var attributeValue = attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr);- if (attributeValue != null)+ formattedAttribute =+ $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}";+ if (renderPrices){- formattedAttribute =- $"{attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}: {attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id)}";- if (renderPrices)+ var priceAdjustmentBase =+ (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer))+ .checkoutPrice;+ var priceAdjustment =+ await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase,+ _workContext.WorkingCurrency);+ if (priceAdjustmentBase > 0){- var priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer)).checkoutPrice;- var priceAdjustment = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);- if (priceAdjustmentBase > 0)- {- var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);- formattedAttribute += $" [+{priceAdjustmentStr}]";- }+ var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);+ formattedAttribute += $" [+{priceAdjustmentStr}]";}}- //encode (if required)- if (htmlEncode)- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}- if (string.IsNullOrEmpty(formattedAttribute)) continue;- if (i != 0 || j != 0)- result.Append(separator);- result.Append(formattedAttribute);+ //encode (if required)+ if (htmlEncode)+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);}++ if (string.IsNullOrEmpty(formattedAttribute)) continue;+ if (i != 0 || j != 0)+ result.Append(separator);+ result.Append(formattedAttribute);}- return result.ToString();}++ return result.ToString();}}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.csindex f382142cb..5bd07a654 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs@@ -2,180 +2,194 @@ using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;using Grand.Domain.Common;using Grand.Domain.Orders;-namespace Grand.Business.Checkout.Services.CheckoutAttributes+namespace Grand.Business.Checkout.Services.CheckoutAttributes;++/// <summary>+/// Checkout attribute parser+/// </summary>+public class CheckoutAttributeParser : ICheckoutAttributeParser{+ private readonly ICheckoutAttributeService _checkoutAttributeService;++ public CheckoutAttributeParser(ICheckoutAttributeService checkoutAttributeService)+ {+ _checkoutAttributeService = checkoutAttributeService;+ }+/// <summary>- /// Checkout attribute parser+ /// Gets selected checkout attributes/// </summary>- public class CheckoutAttributeParser : ICheckoutAttributeParser+ /// <param name="customAttributes">Attributes</param>+ /// <returns>Selected checkout attributes</returns>+ public virtual async Task<IList<CheckoutAttribute>> ParseCheckoutAttributes(IList<CustomAttribute> customAttributes){- private readonly ICheckoutAttributeService _checkoutAttributeService;+ var result = new List<CheckoutAttribute>();+ if (customAttributes == null || !customAttributes.Any())+ return result;- public CheckoutAttributeParser(ICheckoutAttributeService checkoutAttributeService)+ foreach (var customAttribute in customAttributes.GroupBy(x => x.Key)){- _checkoutAttributeService = checkoutAttributeService;+ var attribute = await _checkoutAttributeService.GetCheckoutAttributeById(customAttribute.Key);+ if (attribute != null) result.Add(attribute);}- /// <summary>- /// Gets selected checkout attributes- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <returns>Selected checkout attributes</returns>- public virtual async Task<IList<CheckoutAttribute>> ParseCheckoutAttributes(IList<CustomAttribute> customAttributes)+ return result;+ }++ /// <summary>+ /// Get checkout attribute values+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <returns>Checkout attribute values</returns>+ public virtual async Task<IList<CheckoutAttributeValue>> ParseCheckoutAttributeValues(+ IList<CustomAttribute> customAttributes)+ {+ var values = new List<CheckoutAttributeValue>();+ if (customAttributes == null || !customAttributes.Any())+ return values;++ var attributes = await ParseCheckoutAttributes(customAttributes);+ foreach (var attribute in attributes){- var result = new List<CheckoutAttribute>();- if (customAttributes == null || !customAttributes.Any())- return result;-- foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))- {- var attribute = await _checkoutAttributeService.GetCheckoutAttributeById(customAttribute.Key);- if (attribute != null)- {- result.Add(attribute);- }- }- return result;+ if (!attribute.ShouldHaveValues())+ continue;++ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);+ values.AddRange(from valueStr in valuesStr+ where !string.IsNullOrEmpty(valueStr)+ select attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr)+ into value+ where value != null+ select value);}- /// <summary>- /// Get checkout attribute values- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <returns>Checkout attribute values</returns>- public virtual async Task<IList<CheckoutAttributeValue>> ParseCheckoutAttributeValues(IList<CustomAttribute> customAttributes)- {- var values = new List<CheckoutAttributeValue>();- if (customAttributes == null || !customAttributes.Any())- return values;-- var attributes = await ParseCheckoutAttributes(customAttributes);- foreach (var attribute in attributes)- {- if (!attribute.ShouldHaveValues())- continue;-- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr)- select attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);- }+ return values;+ }++ /// <summary>+ /// Get checkout attribute values with checkout attribute+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <returns>Checkout attribute values with checkout attribute </returns>+ public virtual async Task<IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>> ParseCheckoutAttributeValue(+ IList<CustomAttribute> customAttributes)+ {+ var values = new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>();+ if (customAttributes == null || !customAttributes.Any())return values;- }- /// <summary>- /// Get checkout attribute values with checkout attribute- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <returns>Checkout attribute values with checkout attribute </returns>- public virtual async Task<IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>> ParseCheckoutAttributeValue(IList<CustomAttribute> customAttributes)+ var attributes = await ParseCheckoutAttributes(customAttributes);+ foreach (var attribute in attributes){- var values = new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>();- if (customAttributes == null || !customAttributes.Any())- return values;-- var attributes = await ParseCheckoutAttributes(customAttributes);- foreach (var attribute in attributes)- {- if (!attribute.ShouldHaveValues())- continue;-- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);- values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr)- select attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select (attribute, value));- }- return values;+ if (!attribute.ShouldHaveValues())+ continue;++ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);+ values.AddRange(from valueStr in valuesStr+ where !string.IsNullOrEmpty(valueStr)+ select attribute.CheckoutAttributeValues.FirstOrDefault(x => x.Id == valueStr)+ into value+ where value != null+ select (attribute, value));}- /// <summary>- /// Adds an attribute- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <param name="ca">Checkout attribute</param>- /// <param name="value">Value</param>- /// <returns>Attributes</returns>- public virtual IList<CustomAttribute> AddCheckoutAttribute(IList<CustomAttribute> customAttributes, CheckoutAttribute ca, string value)- {- customAttributes ??= new List<CustomAttribute>();+ return values;+ }- customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });- return customAttributes;- }+ /// <summary>+ /// Adds an attribute+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <param name="ca">Checkout attribute</param>+ /// <param name="value">Value</param>+ /// <returns>Attributes</returns>+ public virtual IList<CustomAttribute> AddCheckoutAttribute(IList<CustomAttribute> customAttributes,+ CheckoutAttribute ca, string value)+ {+ customAttributes ??= new List<CustomAttribute>();- /// <summary>- /// Removes checkout attributes which cannot be applied to the current cart and returns an update attributes- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <param name="cart">Shopping cart items</param>- /// <returns>Updated attributes</returns>- public virtual async Task<IList<CustomAttribute>> EnsureOnlyActiveAttributes(IList<CustomAttribute> customAttributes, IList<ShoppingCartItem> cart)- {- customAttributes ??= new List<CustomAttribute>();+ customAttributes.Add(new CustomAttribute { Key = ca.Id, Value = value });+ return customAttributes;+ }- if (cart.RequiresShipping()) return customAttributes;- var attributes = await ParseCheckoutAttributes(customAttributes);- var checkoutAttributeIdsToRemove = (from ca in attributes where ca.ShippableProductRequired select ca.Id).ToList();+ /// <summary>+ /// Removes checkout attributes which cannot be applied to the current cart and returns an update attributes+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <param name="cart">Shopping cart items</param>+ /// <returns>Updated attributes</returns>+ public virtual async Task<IList<CustomAttribute>> EnsureOnlyActiveAttributes(+ IList<CustomAttribute> customAttributes, IList<ShoppingCartItem> cart)+ {+ customAttributes ??= new List<CustomAttribute>();- foreach (var attr in checkoutAttributeIdsToRemove.Select(id => customAttributes.FirstOrDefault(x => x.Key == id)).Where(attr => attr != null))- {- customAttributes.Remove(attr);- }+ if (cart.RequiresShipping()) return customAttributes;+ var attributes = await ParseCheckoutAttributes(customAttributes);+ var checkoutAttributeIdsToRemove =+ (from ca in attributes where ca.ShippableProductRequired select ca.Id).ToList();- return customAttributes;- }- /// <summary>- /// Check whether condition of some attribute is met.- /// </summary>- /// <param name="attribute">Checkout attribute</param>- /// <param name="customAttributes">Selected attributes</param>- /// <returns>Result</returns>- public virtual async Task<bool?> IsConditionMet(CheckoutAttribute attribute, IList<CustomAttribute> customAttributes)- {- ArgumentNullException.ThrowIfNull(attribute);-- customAttributes ??= new List<CustomAttribute>();-- var conditionAttribute = attribute.ConditionAttribute;- if (!conditionAttribute.Any())- //no condition- return null;-- //load an attribute this one depends on- var dependOnAttribute = (await ParseCheckoutAttributes(conditionAttribute)).FirstOrDefault();- if (dependOnAttribute == null)- return true;-- var valuesThatShouldBeSelected = conditionAttribute.Where(x => x.Key == dependOnAttribute.Id).Select(x => x.Value)- .Where(x => !string.IsNullOrEmpty(x))- .ToList();-- var selectedValues = customAttributes.Where(x => x.Key == dependOnAttribute.Id).Select(x => x.Value).ToList();- if (valuesThatShouldBeSelected.Count != selectedValues.Count)- return false;-- //compare values- var allFound = true;- foreach (var t1 in valuesThatShouldBeSelected)- {- var found = false;- foreach (var t2 in selectedValues.Where(t2 => t1 == t2))- found = true;- if (!found)- allFound = false;- }-- return allFound;- }+ foreach (var attr in checkoutAttributeIdsToRemove+ .Select(id => customAttributes.FirstOrDefault(x => x.Key == id))+ .Where(attr => attr != null)) customAttributes.Remove(attr);++ return customAttributes;+ }++ /// <summary>+ /// Check whether condition of some attribute is met.+ /// </summary>+ /// <param name="attribute">Checkout attribute</param>+ /// <param name="customAttributes">Selected attributes</param>+ /// <returns>Result</returns>+ public virtual async Task<bool?> IsConditionMet(CheckoutAttribute attribute,+ IList<CustomAttribute> customAttributes)+ {+ ArgumentNullException.ThrowIfNull(attribute);++ customAttributes ??= new List<CustomAttribute>();++ var conditionAttribute = attribute.ConditionAttribute;+ if (!conditionAttribute.Any())+ //no condition+ return null;++ //load an attribute this one depends on+ var dependOnAttribute = (await ParseCheckoutAttributes(conditionAttribute)).FirstOrDefault();+ if (dependOnAttribute == null)+ return true;++ var valuesThatShouldBeSelected = conditionAttribute.Where(x => x.Key == dependOnAttribute.Id)+ .Select(x => x.Value)+ .Where(x => !string.IsNullOrEmpty(x))+ .ToList();- /// <summary>- /// Remove an attribute- /// </summary>- /// <param name="customAttributes">Attributes</param>- /// <param name="attribute">Checkout attribute</param>- /// <returns>Updated</returns>- public virtual IList<CustomAttribute> RemoveCheckoutAttribute(IList<CustomAttribute> customAttributes, CheckoutAttribute attribute)+ var selectedValues = customAttributes.Where(x => x.Key == dependOnAttribute.Id).Select(x => x.Value).ToList();+ if (valuesThatShouldBeSelected.Count != selectedValues.Count)+ return false;++ //compare values+ var allFound = true;+ foreach (var t1 in valuesThatShouldBeSelected){- return customAttributes.Where(x => x.Key != attribute.Id).ToList();+ var found = false;+ foreach (var t2 in selectedValues.Where(t2 => t1 == t2))+ found = true;+ if (!found)+ allFound = false;}+ return allFound;+ }++ /// <summary>+ /// Remove an attribute+ /// </summary>+ /// <param name="customAttributes">Attributes</param>+ /// <param name="attribute">Checkout attribute</param>+ /// <returns>Updated</returns>+ public virtual IList<CustomAttribute> RemoveCheckoutAttribute(IList<CustomAttribute> customAttributes,+ CheckoutAttribute attribute)+ {+ return customAttributes.Where(x => x.Key != attribute.Id).ToList();}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.csindex 7339c96be..cabec3e84 100644--- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs+++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs@@ -1,6 +1,6 @@using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;-using Grand.Domain.Customers;using Grand.Data;+using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.Infrastructure;using Grand.Infrastructure.Caching;@@ -9,150 +9,147 @@ using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.CheckoutAttributes+namespace Grand.Business.Checkout.Services.CheckoutAttributes;++/// <summary>+/// Checkout attribute service+/// </summary>+public class CheckoutAttributeService : ICheckoutAttributeService{+ #region Ctor+/// <summary>- /// Checkout attribute service+ /// Ctor/// </summary>- public class CheckoutAttributeService : ICheckoutAttributeService+ public CheckoutAttributeService(+ ICacheBase cacheBase,+ IRepository<CheckoutAttribute> checkoutAttributeRepository,+ IMediator mediator,+ IWorkContext workContext, AccessControlConfig accessControlConfig){- #region Fields-- private readonly IRepository<CheckoutAttribute> _checkoutAttributeRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;- private readonly IWorkContext _workContext;- private readonly AccessControlConfig _accessControlConfig;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- public CheckoutAttributeService(- ICacheBase cacheBase,- IRepository<CheckoutAttribute> checkoutAttributeRepository,- IMediator mediator,- IWorkContext workContext, AccessControlConfig accessControlConfig)- {- _cacheBase = cacheBase;- _checkoutAttributeRepository = checkoutAttributeRepository;- _mediator = mediator;- _workContext = workContext;- _accessControlConfig = accessControlConfig;- }-- #endregion-- #region Methods-- /// <summary>- /// Gets all checkout attributes- /// </summary>- /// <param name="storeId">Store identifier</param>- /// <param name="excludeShippableAttributes">A value indicating whether we should exclude shippable attributes</param>- /// <param name="ignoreAcl"></param>- /// <returns>Checkout attributes</returns>- public virtual async Task<IList<CheckoutAttribute>> GetAllCheckoutAttributes(string storeId = "", bool excludeShippableAttributes = false, bool ignoreAcl = false)+ _cacheBase = cacheBase;+ _checkoutAttributeRepository = checkoutAttributeRepository;+ _mediator = mediator;+ _workContext = workContext;+ _accessControlConfig = accessControlConfig;+ }++ #endregion++ #region Fields++ private readonly IRepository<CheckoutAttribute> _checkoutAttributeRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;+ private readonly IWorkContext _workContext;+ private readonly AccessControlConfig _accessControlConfig;++ #endregion++ #region Methods++ /// <summary>+ /// Gets all checkout attributes+ /// </summary>+ /// <param name="storeId">Store identifier</param>+ /// <param name="excludeShippableAttributes">A value indicating whether we should exclude shippable attributes</param>+ /// <param name="ignoreAcl"></param>+ /// <returns>Checkout attributes</returns>+ public virtual async Task<IList<CheckoutAttribute>> GetAllCheckoutAttributes(string storeId = "",+ bool excludeShippableAttributes = false, bool ignoreAcl = false)+ {+ var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes, ignoreAcl);+ return await _cacheBase.GetAsync(key, async () =>{- var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes, ignoreAcl);- return await _cacheBase.GetAsync(key, async () =>- {- var query = from p in _checkoutAttributeRepository.Table- select p;+ var query = from p in _checkoutAttributeRepository.Table+ select p;- query = query.OrderBy(c => c.DisplayOrder);+ query = query.OrderBy(c => c.DisplayOrder);- if ((!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations) ||- (!ignoreAcl && !_accessControlConfig.IgnoreAcl))- {- if (!ignoreAcl && !_accessControlConfig.IgnoreAcl)- {- var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();- query = from p in query- where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))- select p;- }- //Store acl- if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)- {- query = from p in query- where !p.LimitedToStores || p.Stores.Contains(storeId)- select p;- }- }- if (excludeShippableAttributes)+ if ((!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations) ||+ (!ignoreAcl && !_accessControlConfig.IgnoreAcl))+ {+ if (!ignoreAcl && !_accessControlConfig.IgnoreAcl){- query = query.Where(x => !x.ShippableProductRequired);+ var allowedCustomerGroupsIds = _workContext.CurrentCustomer.GetCustomerGroupIds();+ query = from p in query+ where !p.LimitedToGroups || allowedCustomerGroupsIds.Any(x => p.CustomerGroups.Contains(x))+ select p;}- return await Task.FromResult(query.ToList());- });- }+ //Store acl+ if (!string.IsNullOrEmpty(storeId) && !_accessControlConfig.IgnoreStoreLimitations)+ query = from p in query+ where !p.LimitedToStores || p.Stores.Contains(storeId)+ select p;+ }- /// <summary>- /// Gets a checkout attribute- /// </summary>- /// <param name="checkoutAttributeId">Checkout attribute identifier</param>- /// <returns>Checkout attribute</returns>- public virtual Task<CheckoutAttribute> GetCheckoutAttributeById(string checkoutAttributeId)- {- var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId);- return _cacheBase.GetAsync(key, () => _checkoutAttributeRepository.GetByIdAsync(checkoutAttributeId));- }-- /// <summary>- /// Inserts a checkout attribute- /// </summary>- /// <param name="checkoutAttribute">Checkout attribute</param>- public virtual async Task InsertCheckoutAttribute(CheckoutAttribute checkoutAttribute)- {- ArgumentNullException.ThrowIfNull(checkoutAttribute);+ if (excludeShippableAttributes) query = query.Where(x => !x.ShippableProductRequired);+ return await Task.FromResult(query.ToList());+ });+ }- await _checkoutAttributeRepository.InsertAsync(checkoutAttribute);+ /// <summary>+ /// Gets a checkout attribute+ /// </summary>+ /// <param name="checkoutAttributeId">Checkout attribute identifier</param>+ /// <returns>Checkout attribute</returns>+ public virtual Task<CheckoutAttribute> GetCheckoutAttributeById(string checkoutAttributeId)+ {+ var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId);+ return _cacheBase.GetAsync(key, () => _checkoutAttributeRepository.GetByIdAsync(checkoutAttributeId));+ }- await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTES_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);+ /// <summary>+ /// Inserts a checkout attribute+ /// </summary>+ /// <param name="checkoutAttribute">Checkout attribute</param>+ public virtual async Task InsertCheckoutAttribute(CheckoutAttribute checkoutAttribute)+ {+ ArgumentNullException.ThrowIfNull(checkoutAttribute);- //event notification- await _mediator.EntityInserted(checkoutAttribute);- }+ await _checkoutAttributeRepository.InsertAsync(checkoutAttribute);- /// <summary>- /// Updates the checkout attribute- /// </summary>- /// <param name="checkoutAttribute">Checkout attribute</param>- public virtual async Task UpdateCheckoutAttribute(CheckoutAttribute checkoutAttribute)- {- ArgumentNullException.ThrowIfNull(checkoutAttribute);+ await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);- await _checkoutAttributeRepository.UpdateAsync(checkoutAttribute);+ //event notification+ await _mediator.EntityInserted(checkoutAttribute);+ }- await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTES_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);+ /// <summary>+ /// Updates the checkout attribute+ /// </summary>+ /// <param name="checkoutAttribute">Checkout attribute</param>+ public virtual async Task UpdateCheckoutAttribute(CheckoutAttribute checkoutAttribute)+ {+ ArgumentNullException.ThrowIfNull(checkoutAttribute);- //event notification- await _mediator.EntityUpdated(checkoutAttribute);- }- /// <summary>- /// Deletes a checkout attribute- /// </summary>- /// <param name="checkoutAttribute">Checkout attribute</param>- public virtual async Task DeleteCheckoutAttribute(CheckoutAttribute checkoutAttribute)- {- ArgumentNullException.ThrowIfNull(checkoutAttribute);+ await _checkoutAttributeRepository.UpdateAsync(checkoutAttribute);++ await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);++ //event notification+ await _mediator.EntityUpdated(checkoutAttribute);+ }- await _checkoutAttributeRepository.DeleteAsync(checkoutAttribute);+ /// <summary>+ /// Deletes a checkout attribute+ /// </summary>+ /// <param name="checkoutAttribute">Checkout attribute</param>+ public virtual async Task DeleteCheckoutAttribute(CheckoutAttribute checkoutAttribute)+ {+ ArgumentNullException.ThrowIfNull(checkoutAttribute);- await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTES_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);+ await _checkoutAttributeRepository.DeleteAsync(checkoutAttribute);- //event notification- await _mediator.EntityDeleted(checkoutAttribute);- }+ await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTES_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.CHECKOUTATTRIBUTEVALUES_PATTERN_KEY);- #endregion+ //event notification+ await _mediator.EntityDeleted(checkoutAttribute);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.cs b/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.csindex c1811d16b..78bcf1d87 100644--- a/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.cs+++ b/src/Business/Grand.Business.Checkout/Services/ExportImpot/OrderSchemaProperty.cs@@ -3,77 +3,81 @@ using Grand.Business.Core.Interfaces.ExportImport;using Grand.Business.Core.Utilities.ExportImport;using Grand.Domain.Orders;-namespace Grand.Business.Checkout.Services.ExportImpot+namespace Grand.Business.Checkout.Services.ExportImpot;++public class OrderSchemaProperty : ISchemaProperty<Order>{- public class OrderSchemaProperty : ISchemaProperty<Order>- {- private readonly ICountryService _countryService;+ private readonly ICountryService _countryService;- public OrderSchemaProperty(ICountryService countryService)- {- _countryService = countryService;- }+ public OrderSchemaProperty(ICountryService countryService)+ {+ _countryService = countryService;+ }- public virtual async Task<PropertyByName<Order>[]> GetProperties()- {- var properties = new[]- {- new PropertyByName<Order>("OrderNumber", p=>p.OrderNumber),- new PropertyByName<Order>("OrderCode", p=>p.Code),- new PropertyByName<Order>("OrderId", p=>p.Id),- new PropertyByName<Order>("StoreId", p=>p.StoreId),- new PropertyByName<Order>("OrderGuid",p=>p.OrderGuid),- new PropertyByName<Order>("CustomerId",p=>p.CustomerId),- new PropertyByName<Order>("OrderStatusId", p=>p.OrderStatusId),- new PropertyByName<Order>("PaymentStatusId", p=>p.PaymentStatusId),- new PropertyByName<Order>("ShippingStatusId", p=>p.ShippingStatusId),- new PropertyByName<Order>("OrderSubtotalInclTax", p=>p.OrderSubtotalInclTax),- new PropertyByName<Order>("OrderSubtotalExclTax", p=>p.OrderSubtotalExclTax),- new PropertyByName<Order>("OrderSubTotalDiscountInclTax", p=>p.OrderSubTotalDiscountInclTax),- new PropertyByName<Order>("OrderSubTotalDiscountExclTax", p=>p.OrderSubTotalDiscountExclTax),- new PropertyByName<Order>("OrderShippingInclTax", p=>p.OrderShippingInclTax),- new PropertyByName<Order>("OrderShippingExclTax", p=>p.OrderShippingExclTax),- new PropertyByName<Order>("PaymentMethodAdditionalFeeInclTax", p=>p.PaymentMethodAdditionalFeeInclTax),- new PropertyByName<Order>("PaymentMethodAdditionalFeeExclTax", p=>p.PaymentMethodAdditionalFeeExclTax),- new PropertyByName<Order>("OrderTax", p=>p.OrderTax),- new PropertyByName<Order>("OrderTotal", p=>p.OrderTotal),- new PropertyByName<Order>("RefundedAmount", p=>p.RefundedAmount),- new PropertyByName<Order>("OrderDiscount", p=>p.OrderDiscount),- new PropertyByName<Order>("CurrencyRate", p=>p.CurrencyRate),- new PropertyByName<Order>("CustomerCurrencyCode", p=>p.CustomerCurrencyCode),- new PropertyByName<Order>("AffiliateId", p=>p.AffiliateId),- new PropertyByName<Order>("PaymentMethodSystemName", p=>p.PaymentMethodSystemName),- new PropertyByName<Order>("ShippingPickUpInStore", p=>p.PickUpInStore),- new PropertyByName<Order>("ShippingMethod", p=>p.ShippingMethod),- new PropertyByName<Order>("ShippingRateComputationMethodSystemName", p=>p.ShippingRateProviderSystemName),- new PropertyByName<Order>("VatNumber", p=>p.VatNumber),- new PropertyByName<Order>("CreatedOnUtc", p=>p.CreatedOnUtc.ToOADate()),- new PropertyByName<Order>("BillingFirstName", p=>p.BillingAddress?.FirstName),- new PropertyByName<Order>("BillingLastName", p=>p.BillingAddress?.LastName),- new PropertyByName<Order>("BillingEmail", p=>p.BillingAddress?.Email),- new PropertyByName<Order>("BillingCompany", p=>p.BillingAddress?.Company),- new PropertyByName<Order>("BillingVatNumber", p=>p.BillingAddress?.VatNumber),- new PropertyByName<Order>("BillingCountry",p=>p.BillingAddress!=null ? _countryService.GetCountryById(p.BillingAddress.CountryId).Result?.Name : ""),- new PropertyByName<Order>("BillingCity", p=>p.BillingAddress?.City),- new PropertyByName<Order>("BillingAddress1",p=>p.BillingAddress?.Address1),- new PropertyByName<Order>("BillingAddress2", p=>p.BillingAddress?.Address2),- new PropertyByName<Order>("BillingZipPostalCode", p=>p.BillingAddress?.ZipPostalCode),- new PropertyByName<Order>("BillingPhoneNumber", p=>p.BillingAddress?.PhoneNumber),- new PropertyByName<Order>("BillingFaxNumber", p=>p.BillingAddress?.FaxNumber),- new PropertyByName<Order>("ShippingFirstName", p=>p.ShippingAddress?.FirstName),- new PropertyByName<Order>("ShippingLastName", p=>p.ShippingAddress?.LastName),- new PropertyByName<Order>("ShippingEmail", p=>p.ShippingAddress?.Email),- new PropertyByName<Order>("ShippingCompany", p=>p.ShippingAddress?.Company),- new PropertyByName<Order>("ShippingVatNumber", p=>p.ShippingAddress?.VatNumber),- new PropertyByName<Order>("ShippingCountry",p=>p.ShippingAddress!=null ? _countryService.GetCountryById(p.ShippingAddress.CountryId).Result?.Name : ""),- new PropertyByName<Order>("ShippingCity", p=>p.ShippingAddress?.City),- new PropertyByName<Order>("ShippingAddress1", p=>p.ShippingAddress?.Address1),- new PropertyByName<Order>("ShippingAddress2", p=>p.ShippingAddress?.Address2),- new PropertyByName<Order>("ShippingZipPostalCode", p=>p.ShippingAddress?.ZipPostalCode),- new PropertyByName<Order>("ShippingPhoneNumber",p=>p.ShippingAddress?.PhoneNumber),- new PropertyByName<Order>("ShippingFaxNumber", p=>p.ShippingAddress?.FaxNumber)- };- return await Task.FromResult(properties);- }+ public virtual async Task<PropertyByName<Order>[]> GetProperties()+ {+ var properties = new[] {+ new PropertyByName<Order>("OrderNumber", p => p.OrderNumber),+ new PropertyByName<Order>("OrderCode", p => p.Code),+ new PropertyByName<Order>("OrderId", p => p.Id),+ new PropertyByName<Order>("StoreId", p => p.StoreId),+ new PropertyByName<Order>("OrderGuid", p => p.OrderGuid),+ new PropertyByName<Order>("CustomerId", p => p.CustomerId),+ new PropertyByName<Order>("OrderStatusId", p => p.OrderStatusId),+ new PropertyByName<Order>("PaymentStatusId", p => p.PaymentStatusId),+ new PropertyByName<Order>("ShippingStatusId", p => p.ShippingStatusId),+ new PropertyByName<Order>("OrderSubtotalInclTax", p => p.OrderSubtotalInclTax),+ new PropertyByName<Order>("OrderSubtotalExclTax", p => p.OrderSubtotalExclTax),+ new PropertyByName<Order>("OrderSubTotalDiscountInclTax", p => p.OrderSubTotalDiscountInclTax),+ new PropertyByName<Order>("OrderSubTotalDiscountExclTax", p => p.OrderSubTotalDiscountExclTax),+ new PropertyByName<Order>("OrderShippingInclTax", p => p.OrderShippingInclTax),+ new PropertyByName<Order>("OrderShippingExclTax", p => p.OrderShippingExclTax),+ new PropertyByName<Order>("PaymentMethodAdditionalFeeInclTax", p => p.PaymentMethodAdditionalFeeInclTax),+ new PropertyByName<Order>("PaymentMethodAdditionalFeeExclTax", p => p.PaymentMethodAdditionalFeeExclTax),+ new PropertyByName<Order>("OrderTax", p => p.OrderTax),+ new PropertyByName<Order>("OrderTotal", p => p.OrderTotal),+ new PropertyByName<Order>("RefundedAmount", p => p.RefundedAmount),+ new PropertyByName<Order>("OrderDiscount", p => p.OrderDiscount),+ new PropertyByName<Order>("CurrencyRate", p => p.CurrencyRate),+ new PropertyByName<Order>("CustomerCurrencyCode", p => p.CustomerCurrencyCode),+ new PropertyByName<Order>("AffiliateId", p => p.AffiliateId),+ new PropertyByName<Order>("PaymentMethodSystemName", p => p.PaymentMethodSystemName),+ new PropertyByName<Order>("ShippingPickUpInStore", p => p.PickUpInStore),+ new PropertyByName<Order>("ShippingMethod", p => p.ShippingMethod),+ new PropertyByName<Order>("ShippingRateComputationMethodSystemName", p => p.ShippingRateProviderSystemName),+ new PropertyByName<Order>("VatNumber", p => p.VatNumber),+ new PropertyByName<Order>("CreatedOnUtc", p => p.CreatedOnUtc.ToOADate()),+ new PropertyByName<Order>("BillingFirstName", p => p.BillingAddress?.FirstName),+ new PropertyByName<Order>("BillingLastName", p => p.BillingAddress?.LastName),+ new PropertyByName<Order>("BillingEmail", p => p.BillingAddress?.Email),+ new PropertyByName<Order>("BillingCompany", p => p.BillingAddress?.Company),+ new PropertyByName<Order>("BillingVatNumber", p => p.BillingAddress?.VatNumber),+ new PropertyByName<Order>("BillingCountry",+ p => p.BillingAddress != null+ ? _countryService.GetCountryById(p.BillingAddress.CountryId).Result?.Name+ : ""),+ new PropertyByName<Order>("BillingCity", p => p.BillingAddress?.City),+ new PropertyByName<Order>("BillingAddress1", p => p.BillingAddress?.Address1),+ new PropertyByName<Order>("BillingAddress2", p => p.BillingAddress?.Address2),+ new PropertyByName<Order>("BillingZipPostalCode", p => p.BillingAddress?.ZipPostalCode),+ new PropertyByName<Order>("BillingPhoneNumber", p => p.BillingAddress?.PhoneNumber),+ new PropertyByName<Order>("BillingFaxNumber", p => p.BillingAddress?.FaxNumber),+ new PropertyByName<Order>("ShippingFirstName", p => p.ShippingAddress?.FirstName),+ new PropertyByName<Order>("ShippingLastName", p => p.ShippingAddress?.LastName),+ new PropertyByName<Order>("ShippingEmail", p => p.ShippingAddress?.Email),+ new PropertyByName<Order>("ShippingCompany", p => p.ShippingAddress?.Company),+ new PropertyByName<Order>("ShippingVatNumber", p => p.ShippingAddress?.VatNumber),+ new PropertyByName<Order>("ShippingCountry",+ p => p.ShippingAddress != null+ ? _countryService.GetCountryById(p.ShippingAddress.CountryId).Result?.Name+ : ""),+ new PropertyByName<Order>("ShippingCity", p => p.ShippingAddress?.City),+ new PropertyByName<Order>("ShippingAddress1", p => p.ShippingAddress?.Address1),+ new PropertyByName<Order>("ShippingAddress2", p => p.ShippingAddress?.Address2),+ new PropertyByName<Order>("ShippingZipPostalCode", p => p.ShippingAddress?.ZipPostalCode),+ new PropertyByName<Order>("ShippingPhoneNumber", p => p.ShippingAddress?.PhoneNumber),+ new PropertyByName<Order>("ShippingFaxNumber", p => p.ShippingAddress?.FaxNumber)+ };+ return await Task.FromResult(properties);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.csindex 168d1ddbf..a9968ffa4 100644--- a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs+++ b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs@@ -1,169 +1,170 @@using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Infrastructure.Extensions;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Orders;+using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.GiftVouchers+namespace Grand.Business.Checkout.Services.GiftVouchers;++/// <summary>+/// Gift voucher service+/// </summary>+public class GiftVoucherService : IGiftVoucherService{+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ /// <param name="giftVoucherRepository">Gift voucher context</param>+ /// <param name="mediator">Mediator</param>+ public GiftVoucherService(IRepository<GiftVoucher> giftVoucherRepository, IMediator mediator)+ {+ _giftVoucherRepository = giftVoucherRepository;+ _mediator = mediator;+ }++ #endregion++ #region Fields++ private readonly IRepository<GiftVoucher> _giftVoucherRepository;+ private readonly IMediator _mediator;++ #endregion++ #region Methods++ /// <summary>+ /// Gets a gift voucher+ /// </summary>+ /// <param name="giftVoucherId">Gift voucher identifier</param>+ /// <returns>Gift voucher entry</returns>+ public virtual Task<GiftVoucher> GetGiftVoucherById(string giftVoucherId)+ {+ return _giftVoucherRepository.GetByIdAsync(giftVoucherId);+ }++ /// <summary>+ /// Gets all gift vouchers+ /// </summary>+ /// <param name="purchasedWithOrderItemId">Associated order ID; null to load all records</param>+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>+ /// <param name="isGiftVoucherActivated">Value indicating whether gift voucher is activated; null to load all records</param>+ /// <param name="giftVoucherCouponCode">Gift voucher coupon code; null to load all records</param>+ /// <param name="recipientName">Recipient name; null to load all records</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <returns>Gift vouchers</returns>+ public virtual async Task<IPagedList<GiftVoucher>> GetAllGiftVouchers(string purchasedWithOrderItemId = "",+ DateTime? createdFromUtc = null, DateTime? createdToUtc = null,+ bool? isGiftVoucherActivated = null, string giftVoucherCouponCode = null,+ string recipientName = null,+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var model = new GetGiftVoucherQuery {+ CreatedFromUtc = createdFromUtc,+ CreatedToUtc = createdToUtc,+ Code = giftVoucherCouponCode,+ IsGiftVoucherActivated = isGiftVoucherActivated,+ PageIndex = pageIndex,+ PageSize = pageSize,+ PurchasedWithOrderItemId = purchasedWithOrderItemId,+ RecipientName = recipientName+ };++ var query = await _mediator.Send(model);+ return await PagedList<GiftVoucher>.Create(query, pageIndex, pageSize);+ }++ public virtual async Task<IList<GiftVoucherUsageHistory>> GetAllGiftVoucherUsageHistory(string orderId = "")+ {+ var query = from g in _giftVoucherRepository.Table+ from h in g.GiftVoucherUsageHistory+ select h;++ query = query.Where(x => x.UsedWithOrderId == orderId);+ return await Task.FromResult(query.ToList());+ }++ /// <summary>+ /// Inserts a gift voucher+ /// </summary>+ /// <param name="giftVoucher">Gift voucher</param>+ public virtual async Task InsertGiftVoucher(GiftVoucher giftVoucher)+ {+ ArgumentNullException.ThrowIfNull(giftVoucher);++ giftVoucher.Code = giftVoucher.Code.ToLowerInvariant();++ await _giftVoucherRepository.InsertAsync(giftVoucher);++ //event notification+ await _mediator.EntityInserted(giftVoucher);+ }+/// <summary>- /// Gift voucher service+ /// Updates the gift voucher/// </summary>- public class GiftVoucherService : IGiftVoucherService+ /// <param name="giftVoucher">Gift voucher</param>+ public virtual async Task UpdateGiftVoucher(GiftVoucher giftVoucher){- #region Fields-- private readonly IRepository<GiftVoucher> _giftVoucherRepository;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="giftVoucherRepository">Gift voucher context</param>- /// <param name="mediator">Mediator</param>- public GiftVoucherService(IRepository<GiftVoucher> giftVoucherRepository, IMediator mediator)- {- _giftVoucherRepository = giftVoucherRepository;- _mediator = mediator;- }-- #endregion-- #region Methods--- /// <summary>- /// Gets a gift voucher- /// </summary>- /// <param name="giftVoucherId">Gift voucher identifier</param>- /// <returns>Gift voucher entry</returns>- public virtual Task<GiftVoucher> GetGiftVoucherById(string giftVoucherId)- {- return _giftVoucherRepository.GetByIdAsync(giftVoucherId);- }-- /// <summary>- /// Gets all gift vouchers- /// </summary>- /// <param name="purchasedWithOrderItemId">Associated order ID; null to load all records</param>- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>- /// <param name="isGiftVoucherActivated">Value indicating whether gift voucher is activated; null to load all records</param>- /// <param name="giftVoucherCouponCode">Gift voucher coupon code; null to load all records</param>- /// <param name="recipientName">Recipient name; null to load all records</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>Gift vouchers</returns>- public virtual async Task<IPagedList<GiftVoucher>> GetAllGiftVouchers(string purchasedWithOrderItemId = "",- DateTime? createdFromUtc = null, DateTime? createdToUtc = null,- bool? isGiftVoucherActivated = null, string giftVoucherCouponCode = null,- string recipientName = null,- int pageIndex = 0, int pageSize = int.MaxValue)- {- var model = new GetGiftVoucherQuery {- CreatedFromUtc = createdFromUtc,- CreatedToUtc = createdToUtc,- Code = giftVoucherCouponCode,- IsGiftVoucherActivated = isGiftVoucherActivated,- PageIndex = pageIndex,- PageSize = pageSize,- PurchasedWithOrderItemId = purchasedWithOrderItemId,- RecipientName = recipientName- };-- var query = await _mediator.Send(model);- return await PagedList<GiftVoucher>.Create(query, pageIndex, pageSize);- }-- public virtual async Task<IList<GiftVoucherUsageHistory>> GetAllGiftVoucherUsageHistory(string orderId = "")- {- var query = from g in _giftVoucherRepository.Table- from h in g.GiftVoucherUsageHistory- select h;-- query = query.Where(x => x.UsedWithOrderId == orderId);- return await Task.FromResult(query.ToList());- }-- /// <summary>- /// Inserts a gift voucher- /// </summary>- /// <param name="giftVoucher">Gift voucher</param>- public virtual async Task InsertGiftVoucher(GiftVoucher giftVoucher)- {- ArgumentNullException.ThrowIfNull(giftVoucher);-- giftVoucher.Code = giftVoucher.Code.ToLowerInvariant();-- await _giftVoucherRepository.InsertAsync(giftVoucher);-- //event notification- await _mediator.EntityInserted(giftVoucher);- }-- /// <summary>- /// Updates the gift voucher- /// </summary>- /// <param name="giftVoucher">Gift voucher</param>- public virtual async Task UpdateGiftVoucher(GiftVoucher giftVoucher)- {- ArgumentNullException.ThrowIfNull(giftVoucher);-- giftVoucher.Code = giftVoucher.Code.ToLowerInvariant();-- await _giftVoucherRepository.UpdateAsync(giftVoucher);-- //event notification- await _mediator.EntityUpdated(giftVoucher);- }- /// <summary>- /// Deletes a gift voucher- /// </summary>- /// <param name="giftVoucher">Gift voucher</param>- public virtual async Task DeleteGiftVoucher(GiftVoucher giftVoucher)- {- ArgumentNullException.ThrowIfNull(giftVoucher);-- await _giftVoucherRepository.DeleteAsync(giftVoucher);-- //event notification- await _mediator.EntityDeleted(giftVoucher);- }-- /// <summary>- /// Gets gift vouchers by 'PurchasedWithOrderItemId'- /// </summary>- /// <param name="purchasedWithOrderItemId">Purchased with order item identifier</param>- /// <returns>Gift voucher entries</returns>- public virtual async Task<IList<GiftVoucher>> GetGiftVouchersByPurchasedWithOrderItemId(string purchasedWithOrderItemId)- {- if (string.IsNullOrEmpty(purchasedWithOrderItemId))- return new List<GiftVoucher>();-- var query = from p in _giftVoucherRepository.Table- select p;-- query = query.Where(gc => gc.PurchasedWithOrderItem!=null && gc.PurchasedWithOrderItem.Id == purchasedWithOrderItemId);- query = query.OrderBy(gc => gc.Id);-- return await Task.FromResult(query.ToList());- }-- /// <summary>- /// Generate new gift voucher code- /// </summary>- /// <returns>Result</returns>- public virtual string GenerateGiftVoucherCode()- {- return Guid.NewGuid().ToString()[..8];- }-- #endregion+ ArgumentNullException.ThrowIfNull(giftVoucher);++ giftVoucher.Code = giftVoucher.Code.ToLowerInvariant();++ await _giftVoucherRepository.UpdateAsync(giftVoucher);++ //event notification+ await _mediator.EntityUpdated(giftVoucher);}-}++ /// <summary>+ /// Deletes a gift voucher+ /// </summary>+ /// <param name="giftVoucher">Gift voucher</param>+ public virtual async Task DeleteGiftVoucher(GiftVoucher giftVoucher)+ {+ ArgumentNullException.ThrowIfNull(giftVoucher);++ await _giftVoucherRepository.DeleteAsync(giftVoucher);++ //event notification+ await _mediator.EntityDeleted(giftVoucher);+ }++ /// <summary>+ /// Gets gift vouchers by 'PurchasedWithOrderItemId'+ /// </summary>+ /// <param name="purchasedWithOrderItemId">Purchased with order item identifier</param>+ /// <returns>Gift voucher entries</returns>+ public virtual async Task<IList<GiftVoucher>> GetGiftVouchersByPurchasedWithOrderItemId(+ string purchasedWithOrderItemId)+ {+ if (string.IsNullOrEmpty(purchasedWithOrderItemId))+ return new List<GiftVoucher>();++ var query = from p in _giftVoucherRepository.Table+ select p;++ query = query.Where(gc =>+ gc.PurchasedWithOrderItem != null && gc.PurchasedWithOrderItem.Id == purchasedWithOrderItemId);+ query = query.OrderBy(gc => gc.Id);++ return await Task.FromResult(query.ToList());+ }++ /// <summary>+ /// Generate new gift voucher code+ /// </summary>+ /// <returns>Result</returns>+ public virtual string GenerateGiftVoucherCode()+ {+ return Guid.NewGuid().ToString()[..8];+ }++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.csindex 2c00e34f5..526811426 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs@@ -4,113 +4,110 @@ using Grand.Domain.Orders;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++/// <summary>+/// LoyaltyPoints service interface+/// </summary>+public class LoyaltyPointsService : ILoyaltyPointsService{+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ /// <param name="rphRepository">LoyaltyPointsHistory repository</param>+ /// <param name="loyaltyPointsSettings">Loyalty points settings</param>+ /// <param name="mediator">Mediator</param>+ public LoyaltyPointsService(IRepository<LoyaltyPointsHistory> rphRepository,+ LoyaltyPointsSettings loyaltyPointsSettings,+ IMediator mediator)+ {+ _rphRepository = rphRepository;+ _loyaltyPointsSettings = loyaltyPointsSettings;+ _mediator = mediator;+ }++ #endregion++ #region Fields++ private readonly IRepository<LoyaltyPointsHistory> _rphRepository;+ private readonly LoyaltyPointsSettings _loyaltyPointsSettings;+ private readonly IMediator _mediator;++ #endregion++ #region Methods+/// <summary>- /// LoyaltyPoints service interface+ /// Get loyalty points for customer/// </summary>- public class LoyaltyPointsService : ILoyaltyPointsService+ /// <param name="customerId">Customer Id</param>+ /// <param name="storeId">Store ident</param>+ /// <returns>PointsBalance</returns>+ public virtual async Task<int> GetLoyaltyPointsBalance(string customerId, string storeId){- #region Fields-- private readonly IRepository<LoyaltyPointsHistory> _rphRepository;- private readonly LoyaltyPointsSettings _loyaltyPointsSettings;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="rphRepository">LoyaltyPointsHistory repository</param>- /// <param name="loyaltyPointsSettings">Loyalty points settings</param>- /// <param name="mediator">Mediator</param>- public LoyaltyPointsService(IRepository<LoyaltyPointsHistory> rphRepository,- LoyaltyPointsSettings loyaltyPointsSettings,- IMediator mediator)- {- _rphRepository = rphRepository;- _loyaltyPointsSettings = loyaltyPointsSettings;- _mediator = mediator;- }- #endregion-- #region Methods-- /// <summary>- /// Get loyalty points for customer- /// </summary>- /// <param name="customerId">Customer Id</param>- /// <param name="storeId">Store ident</param>- /// <returns>PointsBalance</returns>- public virtual async Task<int> GetLoyaltyPointsBalance(string customerId, string storeId)- {- var query = from p in _rphRepository.Table- select p;-- if (!string.IsNullOrEmpty(customerId))- query = query.Where(rph => rph.CustomerId == customerId);- if (!_loyaltyPointsSettings.PointsAccumulatedForAllStores)+ var query = from p in _rphRepository.Table+ select p;++ if (!string.IsNullOrEmpty(customerId))+ query = query.Where(rph => rph.CustomerId == customerId);+ if (!_loyaltyPointsSettings.PointsAccumulatedForAllStores)+ query = query.Where(rph => rph.StoreId == storeId);+ query = query.OrderByDescending(rph => rph.CreatedOnUtc);++ var lastRph = await Task.FromResult(query.FirstOrDefault());+ return lastRph?.PointsBalance ?? 0;+ }++ /// <summary>+ /// Add loyalty points+ /// </summary>+ /// <param name="customerId">Customer Id</param>+ /// <param name="points">Points</param>+ /// <param name="storeId">Store ident</param>+ /// <param name="message">Message</param>+ /// <param name="usedWithOrderId">Used with OrderId</param>+ /// <param name="usedAmount">Used amount</param>+ /// <returns>LoyaltyPointsHistory</returns>+ public virtual async Task<LoyaltyPointsHistory> AddLoyaltyPointsHistory(string customerId, int points,+ string storeId, string message = "",+ string usedWithOrderId = "", double usedAmount = 0)+ {+ var loyaltyPointsHistory = new LoyaltyPointsHistory {+ CustomerId = customerId,+ UsedWithOrderId = usedWithOrderId,+ Points = points,+ PointsBalance = await GetLoyaltyPointsBalance(customerId, storeId) + points,+ UsedAmount = usedAmount,+ Message = message,+ StoreId = storeId+ };+ await _rphRepository.InsertAsync(loyaltyPointsHistory);++ //event notification+ await _mediator.EntityInserted(loyaltyPointsHistory);++ return loyaltyPointsHistory;+ }++ public virtual async Task<IList<LoyaltyPointsHistory>> GetLoyaltyPointsHistory(string customerId = "",+ string storeId = "", bool showAll = false)+ {+ var query = from p in _rphRepository.Table+ select p;++ if (!string.IsNullOrEmpty(customerId))+ query = query.Where(rph => rph.CustomerId == customerId);+ if (!showAll && !_loyaltyPointsSettings.PointsAccumulatedForAllStores)+ //filter by store+ if (!string.IsNullOrEmpty(storeId))query = query.Where(rph => rph.StoreId == storeId);- query = query.OrderByDescending(rph => rph.CreatedOnUtc);-- var lastRph = await Task.FromResult(query.FirstOrDefault());- return lastRph?.PointsBalance ?? 0;-- }-- /// <summary>- /// Add loyalty points- /// </summary>- /// <param name="customerId">Customer Id</param>- /// <param name="points">Points</param>- /// <param name="storeId">Store ident</param>- /// <param name="message">Message</param>- /// <param name="usedWithOrderId">Used with OrderId</param>- /// <param name="usedAmount">Used amount</param>- /// <returns>LoyaltyPointsHistory</returns>- public virtual async Task<LoyaltyPointsHistory> AddLoyaltyPointsHistory(string customerId, int points, string storeId, string message = "",- string usedWithOrderId = "", double usedAmount = 0)- {-- var loyaltyPointsHistory = new LoyaltyPointsHistory- {- CustomerId = customerId,- UsedWithOrderId = usedWithOrderId,- Points = points,- PointsBalance = await GetLoyaltyPointsBalance(customerId, storeId) + points,- UsedAmount = usedAmount,- Message = message,- StoreId = storeId- };- await _rphRepository.InsertAsync(loyaltyPointsHistory);-- //event notification- await _mediator.EntityInserted(loyaltyPointsHistory);-- return loyaltyPointsHistory;- }-- public virtual async Task<IList<LoyaltyPointsHistory>> GetLoyaltyPointsHistory(string customerId = "", string storeId = "", bool showAll = false)- {- var query = from p in _rphRepository.Table- select p;-- if (!string.IsNullOrEmpty(customerId))- query = query.Where(rph => rph.CustomerId == customerId);- if (!showAll && !_loyaltyPointsSettings.PointsAccumulatedForAllStores)- {- //filter by store- if (!string.IsNullOrEmpty(storeId))- query = query.Where(rph => rph.StoreId == storeId);- }- query = query.OrderByDescending(rph => rph.CreatedOnUtc);-- return await Task.FromResult(query.ToList());- }-- #endregion+ query = query.OrderByDescending(rph => rph.CreatedOnUtc);++ return await Task.FromResult(query.ToList());}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.csindex c0d68d2a3..e4080eda6 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs@@ -1,372 +1,375 @@using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Orders;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++/// <summary>+/// Merchandise return service+/// </summary>+public class MerchandiseReturnService : IMerchandiseReturnService{+ #region Ctor+/// <summary>- /// Merchandise return service+ /// Ctor/// </summary>- public class MerchandiseReturnService : IMerchandiseReturnService+ /// <param name="merchandiseReturnRepository">Merchandise return repository</param>+ /// <param name="merchandiseReturnActionRepository">Merchandise return action repository</param>+ /// <param name="merchandiseReturnReasonRepository">Merchandise return reason repository</param>+ /// <param name="merchandiseReturnNoteRepository">Merchandise return note repository</param>+ /// <param name="cacheBase">Cache</param>+ /// <param name="mediator">Mediator</param>+ public MerchandiseReturnService(IRepository<MerchandiseReturn> merchandiseReturnRepository,+ IRepository<MerchandiseReturnAction> merchandiseReturnActionRepository,+ IRepository<MerchandiseReturnReason> merchandiseReturnReasonRepository,+ IRepository<MerchandiseReturnNote> merchandiseReturnNoteRepository,+ ICacheBase cacheBase,+ IMediator mediator){- #region Fields- private static readonly object Locker = new();-- private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;- private readonly IRepository<MerchandiseReturnAction> _merchandiseReturnActionRepository;- private readonly IRepository<MerchandiseReturnReason> _merchandiseReturnReasonRepository;- private readonly IRepository<MerchandiseReturnNote> _merchandiseReturnNoteRepository;- private readonly ICacheBase _cacheBase;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="merchandiseReturnRepository">Merchandise return repository</param>- /// <param name="merchandiseReturnActionRepository">Merchandise return action repository</param>- /// <param name="merchandiseReturnReasonRepository">Merchandise return reason repository</param>- /// <param name="merchandiseReturnNoteRepository">Merchandise return note repository</param>- /// <param name="cacheBase">Cache</param>- /// <param name="mediator">Mediator</param>- public MerchandiseReturnService(IRepository<MerchandiseReturn> merchandiseReturnRepository,- IRepository<MerchandiseReturnAction> merchandiseReturnActionRepository,- IRepository<MerchandiseReturnReason> merchandiseReturnReasonRepository,- IRepository<MerchandiseReturnNote> merchandiseReturnNoteRepository,- ICacheBase cacheBase,- IMediator mediator)- {- _merchandiseReturnRepository = merchandiseReturnRepository;- _merchandiseReturnActionRepository = merchandiseReturnActionRepository;- _merchandiseReturnReasonRepository = merchandiseReturnReasonRepository;- _merchandiseReturnNoteRepository = merchandiseReturnNoteRepository;- _cacheBase = cacheBase;- _mediator = mediator;- }+ _merchandiseReturnRepository = merchandiseReturnRepository;+ _merchandiseReturnActionRepository = merchandiseReturnActionRepository;+ _merchandiseReturnReasonRepository = merchandiseReturnReasonRepository;+ _merchandiseReturnNoteRepository = merchandiseReturnNoteRepository;+ _cacheBase = cacheBase;+ _mediator = mediator;+ }- #endregion+ #endregion- #region Methods+ #region Fields-- /// <summary>- /// Gets a merchandise return- /// </summary>- /// <param name="merchandiseReturnId">Merchandise return identifier</param>- /// <returns>Merchandise return</returns>- public virtual Task<MerchandiseReturn> GetMerchandiseReturnById(string merchandiseReturnId)- {- return _merchandiseReturnRepository.GetByIdAsync(merchandiseReturnId);- }+ private static readonly object Locker = new();- /// <summary>- /// Gets a merchandise return- /// </summary>- /// <param name="id">Merchandise return identifier</param>- /// <returns>Merchandise return</returns>- public virtual Task<MerchandiseReturn> GetMerchandiseReturnById(int id)- {- return Task.FromResult(_merchandiseReturnRepository.Table.FirstOrDefault(x => x.ReturnNumber == id));- }+ private readonly IRepository<MerchandiseReturn> _merchandiseReturnRepository;+ private readonly IRepository<MerchandiseReturnAction> _merchandiseReturnActionRepository;+ private readonly IRepository<MerchandiseReturnReason> _merchandiseReturnReasonRepository;+ private readonly IRepository<MerchandiseReturnNote> _merchandiseReturnNoteRepository;+ private readonly ICacheBase _cacheBase;+ private readonly IMediator _mediator;- /// <summary>- /// Search merchandise returns- /// </summary>- /// <param name="storeId">Store identifier; 0 to load all entries</param>- /// <param name="customerId">Customer identifier; null to load all entries</param>- /// <param name="orderItemId">Order item identifier; 0 to load all entries</param>- /// <param name="vendorId">Vendor identifier</param>- /// <param name="ownerId">Owner identifier</param>- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>- /// <param name="rs">Merchandise return status; null to load all entries</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>Merchandise returns</returns>- public virtual async Task<IPagedList<MerchandiseReturn>> SearchMerchandiseReturns(string storeId = "", string customerId = "",- string orderItemId = "", string vendorId = "", string ownerId = "", MerchandiseReturnStatus? rs = null,- int pageIndex = 0, int pageSize = int.MaxValue, DateTime? createdFromUtc = null, DateTime? createdToUtc = null)- {- var model = new GetMerchandiseReturnQuery- {- CreatedFromUtc = createdFromUtc,- CreatedToUtc = createdToUtc,- PageIndex = pageIndex,- PageSize = pageSize,- CustomerId = customerId,- VendorId = vendorId,- OwnerId = ownerId,- StoreId = storeId,- OrderItemId = orderItemId,- Rs = rs- };-- var query = await _mediator.Send(model);- return await PagedList<MerchandiseReturn>.Create(query, pageIndex, pageSize);- }+ #endregion- /// <summary>- /// Gets all merchandise return actions- /// </summary>- /// <returns>Merchandise return actions</returns>- public virtual async Task<IList<MerchandiseReturnAction>> GetAllMerchandiseReturnActions()- {- return await _cacheBase.GetAsync(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY, async () =>- {- var query = from rra in _merchandiseReturnActionRepository.Table- orderby rra.DisplayOrder- select rra;- return await Task.FromResult(query.ToList());- });- }+ #region Methods- /// <summary>- /// Gets a merchandise return action- /// </summary>- /// <param name="merchandiseReturnActionId">Merchandise return action identifier</param>- /// <returns>Merchandise return action</returns>- public virtual Task<MerchandiseReturnAction> GetMerchandiseReturnActionById(string merchandiseReturnActionId)- {- return _merchandiseReturnActionRepository.GetByIdAsync(merchandiseReturnActionId);- }+ /// <summary>+ /// Gets a merchandise return+ /// </summary>+ /// <param name="merchandiseReturnId">Merchandise return identifier</param>+ /// <returns>Merchandise return</returns>+ public virtual Task<MerchandiseReturn> GetMerchandiseReturnById(string merchandiseReturnId)+ {+ return _merchandiseReturnRepository.GetByIdAsync(merchandiseReturnId);+ }- /// <summary>- /// Inserts a merchandise return- /// </summary>- /// <param name="merchandiseReturn">Merchandise return </param>- public virtual async Task InsertMerchandiseReturn(MerchandiseReturn merchandiseReturn)- {- ArgumentNullException.ThrowIfNull(merchandiseReturn);-- lock (Locker)- {- var requestExists = _merchandiseReturnRepository.Table.FirstOrDefault();- var requestNumber = requestExists != null ? _merchandiseReturnRepository.Table.Max(x => x.ReturnNumber) + 1 : 1;- merchandiseReturn.ReturnNumber = requestNumber;- }- await _merchandiseReturnRepository.InsertAsync(merchandiseReturn);-- //event notification- await _mediator.EntityInserted(merchandiseReturn);- }+ /// <summary>+ /// Gets a merchandise return+ /// </summary>+ /// <param name="id">Merchandise return identifier</param>+ /// <returns>Merchandise return</returns>+ public virtual Task<MerchandiseReturn> GetMerchandiseReturnById(int id)+ {+ return Task.FromResult(_merchandiseReturnRepository.Table.FirstOrDefault(x => x.ReturnNumber == id));+ }++ /// <summary>+ /// Search merchandise returns+ /// </summary>+ /// <param name="storeId">Store identifier; 0 to load all entries</param>+ /// <param name="customerId">Customer identifier; null to load all entries</param>+ /// <param name="orderItemId">Order item identifier; 0 to load all entries</param>+ /// <param name="vendorId">Vendor identifier</param>+ /// <param name="ownerId">Owner identifier</param>+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>+ /// <param name="rs">Merchandise return status; null to load all entries</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <returns>Merchandise returns</returns>+ public virtual async Task<IPagedList<MerchandiseReturn>> SearchMerchandiseReturns(string storeId = "",+ string customerId = "",+ string orderItemId = "", string vendorId = "", string ownerId = "", MerchandiseReturnStatus? rs = null,+ int pageIndex = 0, int pageSize = int.MaxValue, DateTime? createdFromUtc = null, DateTime? createdToUtc = null)+ {+ var model = new GetMerchandiseReturnQuery {+ CreatedFromUtc = createdFromUtc,+ CreatedToUtc = createdToUtc,+ PageIndex = pageIndex,+ PageSize = pageSize,+ CustomerId = customerId,+ VendorId = vendorId,+ OwnerId = ownerId,+ StoreId = storeId,+ OrderItemId = orderItemId,+ Rs = rs+ };++ var query = await _mediator.Send(model);+ return await PagedList<MerchandiseReturn>.Create(query, pageIndex, pageSize);+ }- /// <summary>- ///- /// </summary>- /// <param name="merchandiseReturn"></param>- public virtual async Task UpdateMerchandiseReturn(MerchandiseReturn merchandiseReturn)+ /// <summary>+ /// Gets all merchandise return actions+ /// </summary>+ /// <returns>Merchandise return actions</returns>+ public virtual async Task<IList<MerchandiseReturnAction>> GetAllMerchandiseReturnActions()+ {+ return await _cacheBase.GetAsync(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY, async () =>{- ArgumentNullException.ThrowIfNull(merchandiseReturn);+ var query = from rra in _merchandiseReturnActionRepository.Table+ orderby rra.DisplayOrder+ select rra;+ return await Task.FromResult(query.ToList());+ });+ }- await _merchandiseReturnRepository.UpdateAsync(merchandiseReturn);+ /// <summary>+ /// Gets a merchandise return action+ /// </summary>+ /// <param name="merchandiseReturnActionId">Merchandise return action identifier</param>+ /// <returns>Merchandise return action</returns>+ public virtual Task<MerchandiseReturnAction> GetMerchandiseReturnActionById(string merchandiseReturnActionId)+ {+ return _merchandiseReturnActionRepository.GetByIdAsync(merchandiseReturnActionId);+ }- //event notification- await _mediator.EntityUpdated(merchandiseReturn);- }- /// <summary>- /// Deletes a merchandise return- /// </summary>- /// <param name="merchandiseReturn">Merchandise return</param>- public virtual async Task DeleteMerchandiseReturn(MerchandiseReturn merchandiseReturn)+ /// <summary>+ /// Inserts a merchandise return+ /// </summary>+ /// <param name="merchandiseReturn">Merchandise return </param>+ public virtual async Task InsertMerchandiseReturn(MerchandiseReturn merchandiseReturn)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturn);++ lock (Locker){- ArgumentNullException.ThrowIfNull(merchandiseReturn);+ var requestExists = _merchandiseReturnRepository.Table.FirstOrDefault();+ var requestNumber = requestExists != null+ ? _merchandiseReturnRepository.Table.Max(x => x.ReturnNumber) + 1+ : 1;+ merchandiseReturn.ReturnNumber = requestNumber;+ }- await _merchandiseReturnRepository.DeleteAsync(merchandiseReturn);+ await _merchandiseReturnRepository.InsertAsync(merchandiseReturn);- //event notification- await _mediator.EntityDeleted(merchandiseReturn);- }+ //event notification+ await _mediator.EntityInserted(merchandiseReturn);+ }- /// <summary>- /// Inserts a merchandise return action- /// </summary>- /// <param name="merchandiseReturnAction">Merchandise return action</param>- public virtual async Task InsertMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnAction);+ /// <summary>+ /// </summary>+ /// <param name="merchandiseReturn"></param>+ public virtual async Task UpdateMerchandiseReturn(MerchandiseReturn merchandiseReturn)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturn);- await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction);+ await _merchandiseReturnRepository.UpdateAsync(merchandiseReturn);- //event notification- await _mediator.EntityInserted(merchandiseReturnAction);+ //event notification+ await _mediator.EntityUpdated(merchandiseReturn);+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY);- }- /// <summary>- /// Updates the merchandise return action- /// </summary>- /// <param name="merchandiseReturnAction">Merchandise return action</param>- public virtual async Task UpdateMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnAction);+ /// <summary>+ /// Deletes a merchandise return+ /// </summary>+ /// <param name="merchandiseReturn">Merchandise return</param>+ public virtual async Task DeleteMerchandiseReturn(MerchandiseReturn merchandiseReturn)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturn);- await _merchandiseReturnActionRepository.UpdateAsync(merchandiseReturnAction);+ await _merchandiseReturnRepository.DeleteAsync(merchandiseReturn);- //event notification- await _mediator.EntityUpdated(merchandiseReturnAction);+ //event notification+ await _mediator.EntityDeleted(merchandiseReturn);+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY);+ /// <summary>+ /// Inserts a merchandise return action+ /// </summary>+ /// <param name="merchandiseReturnAction">Merchandise return action</param>+ public virtual async Task InsertMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnAction);- }- /// <summary>- /// Delete a merchandise return action- /// </summary>- /// <param name="merchandiseReturnAction">Merchandise return action</param>- public virtual async Task DeleteMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnAction);+ await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction);- await _merchandiseReturnActionRepository.DeleteAsync(merchandiseReturnAction);+ //event notification+ await _mediator.EntityInserted(merchandiseReturnAction);- //event notification- await _mediator.EntityDeleted(merchandiseReturnAction);- }- /// <summary>- /// Delete a merchandise return reason- /// </summary>- /// <param name="merchandiseReturnReason">Merchandise return reason</param>- public virtual async Task DeleteMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnReason);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY);+ }- await _merchandiseReturnReasonRepository.DeleteAsync(merchandiseReturnReason);+ /// <summary>+ /// Updates the merchandise return action+ /// </summary>+ /// <param name="merchandiseReturnAction">Merchandise return action</param>+ public virtual async Task UpdateMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnAction);- //event notification- await _mediator.EntityDeleted(merchandiseReturnReason);+ await _merchandiseReturnActionRepository.UpdateAsync(merchandiseReturnAction);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY);+ //event notification+ await _mediator.EntityUpdated(merchandiseReturnAction);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY);+ }- /// <summary>- /// Gets all merchandise return reasons- /// </summary>- /// <returns>Merchandise return reasons</returns>- public virtual async Task<IList<MerchandiseReturnReason>> GetAllMerchandiseReturnReasons()- {- return await _cacheBase.GetAsync(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY, async () =>- {- var query = from rra in _merchandiseReturnReasonRepository.Table- orderby rra.DisplayOrder- select rra;- return await Task.FromResult(query.ToList());- });- }+ /// <summary>+ /// Delete a merchandise return action+ /// </summary>+ /// <param name="merchandiseReturnAction">Merchandise return action</param>+ public virtual async Task DeleteMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnAction);- /// <summary>- /// Gets a merchandise return reasons- /// </summary>- /// <param name="merchandiseReturnReasonId">Merchandise return reasons identifier</param>- /// <returns>Merchandise return reasons</returns>- public virtual Task<MerchandiseReturnReason> GetMerchandiseReturnReasonById(string merchandiseReturnReasonId)- {- return _merchandiseReturnReasonRepository.GetByIdAsync(merchandiseReturnReasonId);- }+ await _merchandiseReturnActionRepository.DeleteAsync(merchandiseReturnAction);- /// <summary>- /// Inserts a merchandise return reasons- /// </summary>- /// <param name="merchandiseReturnReason">Merchandise return reasons</param>- public virtual async Task InsertMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnReason);+ //event notification+ await _mediator.EntityDeleted(merchandiseReturnAction);+ }++ /// <summary>+ /// Delete a merchandise return reason+ /// </summary>+ /// <param name="merchandiseReturnReason">Merchandise return reason</param>+ public virtual async Task DeleteMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnReason);- await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason);+ await _merchandiseReturnReasonRepository.DeleteAsync(merchandiseReturnReason);- //event notification- await _mediator.EntityInserted(merchandiseReturnReason);+ //event notification+ await _mediator.EntityDeleted(merchandiseReturnReason);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY);+ }- /// <summary>- /// Updates the merchandise return reasons- /// </summary>- /// <param name="merchandiseReturnReason">Merchandise return reasons</param>- public virtual async Task UpdateMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)+ /// <summary>+ /// Gets all merchandise return reasons+ /// </summary>+ /// <returns>Merchandise return reasons</returns>+ public virtual async Task<IList<MerchandiseReturnReason>> GetAllMerchandiseReturnReasons()+ {+ return await _cacheBase.GetAsync(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY, async () =>{- ArgumentNullException.ThrowIfNull(merchandiseReturnReason);+ var query = from rra in _merchandiseReturnReasonRepository.Table+ orderby rra.DisplayOrder+ select rra;+ return await Task.FromResult(query.ToList());+ });+ }- await _merchandiseReturnReasonRepository.UpdateAsync(merchandiseReturnReason);+ /// <summary>+ /// Gets a merchandise return reasons+ /// </summary>+ /// <param name="merchandiseReturnReasonId">Merchandise return reasons identifier</param>+ /// <returns>Merchandise return reasons</returns>+ public virtual Task<MerchandiseReturnReason> GetMerchandiseReturnReasonById(string merchandiseReturnReasonId)+ {+ return _merchandiseReturnReasonRepository.GetByIdAsync(merchandiseReturnReasonId);+ }- //event notification- await _mediator.EntityUpdated(merchandiseReturnReason);+ /// <summary>+ /// Inserts a merchandise return reasons+ /// </summary>+ /// <param name="merchandiseReturnReason">Merchandise return reasons</param>+ public virtual async Task InsertMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnReason);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY);+ await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason);- }+ //event notification+ await _mediator.EntityInserted(merchandiseReturnReason);- #region Merchandise return notes+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY);+ }- /// <summary>- /// Deletes a merchandise return note- /// </summary>- /// <param name="merchandiseReturnNote">The merchandise return note</param>- public virtual async Task DeleteMerchandiseReturnNote(MerchandiseReturnNote merchandiseReturnNote)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnNote);+ /// <summary>+ /// Updates the merchandise return reasons+ /// </summary>+ /// <param name="merchandiseReturnReason">Merchandise return reasons</param>+ public virtual async Task UpdateMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnReason);- await _merchandiseReturnNoteRepository.DeleteAsync(merchandiseReturnNote);+ await _merchandiseReturnReasonRepository.UpdateAsync(merchandiseReturnReason);- //event notification- await _mediator.EntityDeleted(merchandiseReturnNote);- }+ //event notification+ await _mediator.EntityUpdated(merchandiseReturnReason);- /// <summary>- /// Inserts a merchandise return note- /// </summary>- /// <param name="merchandiseReturnNote">The merchandise return note</param>- public virtual async Task InsertMerchandiseReturnNote(MerchandiseReturnNote merchandiseReturnNote)- {- ArgumentNullException.ThrowIfNull(merchandiseReturnNote);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY);+ }- await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);+ #region Merchandise return notes- //event notification- await _mediator.EntityInserted(merchandiseReturnNote);- }+ /// <summary>+ /// Deletes a merchandise return note+ /// </summary>+ /// <param name="merchandiseReturnNote">The merchandise return note</param>+ public virtual async Task DeleteMerchandiseReturnNote(MerchandiseReturnNote merchandiseReturnNote)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnNote);- /// <summary>- /// Get notes related to merchandise return- /// </summary>- /// <param name="merchandiseReturnId">The merchandise return identifier</param>- /// <returns>List of merchandise return notes</returns>- public virtual async Task<IList<MerchandiseReturnNote>> GetMerchandiseReturnNotes(string merchandiseReturnId)- {- var query = from merchandiseReturnNote in _merchandiseReturnNoteRepository.Table- where merchandiseReturnNote.MerchandiseReturnId == merchandiseReturnId- orderby merchandiseReturnNote.CreatedOnUtc descending- select merchandiseReturnNote;+ await _merchandiseReturnNoteRepository.DeleteAsync(merchandiseReturnNote);- return await Task.FromResult(query.ToList());- }+ //event notification+ await _mediator.EntityDeleted(merchandiseReturnNote);+ }- /// <summary>- /// Get merchandise return note by id- /// </summary>- /// <param name="merchandiseReturnNoteId">The merchandise return note identifier</param>- /// <returns>MerchandiseReturnNote</returns>- public virtual Task<MerchandiseReturnNote> GetMerchandiseReturnNote(string merchandiseReturnNoteId)- {- return Task.FromResult(_merchandiseReturnNoteRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnNoteId));- }+ /// <summary>+ /// Inserts a merchandise return note+ /// </summary>+ /// <param name="merchandiseReturnNote">The merchandise return note</param>+ public virtual async Task InsertMerchandiseReturnNote(MerchandiseReturnNote merchandiseReturnNote)+ {+ ArgumentNullException.ThrowIfNull(merchandiseReturnNote);++ await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);++ //event notification+ await _mediator.EntityInserted(merchandiseReturnNote);+ }++ /// <summary>+ /// Get notes related to merchandise return+ /// </summary>+ /// <param name="merchandiseReturnId">The merchandise return identifier</param>+ /// <returns>List of merchandise return notes</returns>+ public virtual async Task<IList<MerchandiseReturnNote>> GetMerchandiseReturnNotes(string merchandiseReturnId)+ {+ var query = from merchandiseReturnNote in _merchandiseReturnNoteRepository.Table+ where merchandiseReturnNote.MerchandiseReturnId == merchandiseReturnId+ orderby merchandiseReturnNote.CreatedOnUtc descending+ select merchandiseReturnNote;- #endregion+ return await Task.FromResult(query.ToList());+ }- #endregion+ /// <summary>+ /// Get merchandise return note by id+ /// </summary>+ /// <param name="merchandiseReturnNoteId">The merchandise return note identifier</param>+ /// <returns>MerchandiseReturnNote</returns>+ public virtual Task<MerchandiseReturnNote> GetMerchandiseReturnNote(string merchandiseReturnNoteId)+ {+ return Task.FromResult(+ _merchandiseReturnNoteRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnNoteId));}-}++ #endregion++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.csindex f96a49b1a..19251db11 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs@@ -3,14 +3,14 @@ using Grand.Business.Core.Interfaces.Catalog.Discounts;using Grand.Business.Core.Interfaces.Catalog.Prices;using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Business.Core.Interfaces.Catalog.Tax;-using Grand.Business.Core.Utilities.Catalog;using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;using Grand.Business.Core.Interfaces.Checkout.Shipping;-using Grand.Business.Core.Utilities.Checkout;using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Utilities.Catalog;+using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;@@ -23,987 +23,953 @@ using Grand.Domain.Tax;using Grand.Infrastructure;using Grand.SharedKernel;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++/// <summary>+/// Order calc service+/// </summary>+public class OrderCalculationService : IOrderCalculationService{+ #region Ctor+/// <summary>- /// Order calc service+ /// Ctor/// </summary>- public class OrderCalculationService : IOrderCalculationService+ /// <param name="workContext">Work context</param>+ /// <param name="priceCalculationService">Price calculation service</param>+ /// <param name="taxService">Tax service</param>+ /// <param name="shippingService">Shipping service</param>+ /// <param name="paymentService">Payment service</param>+ /// <param name="checkoutAttributeParser">Checkout attribute parser</param>+ /// <param name="discountService">Discount service</param>+ /// <param name="giftVoucherService">Gift voucher service</param>+ /// <param name="loyaltyPointsService">Loyalty points service</param>+ /// <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>+ /// <param name="shoppingCartSettings">Shopping cart settings</param>+ /// <param name="catalogSettings">Catalog settings</param>+ public OrderCalculationService(IWorkContext workContext,+ IPricingService priceCalculationService,+ ITaxService taxService,+ IShippingService shippingService,+ IPaymentService paymentService,+ ICheckoutAttributeParser checkoutAttributeParser,+ IDiscountService discountService,+ IGiftVoucherService giftVoucherService,+ ILoyaltyPointsService loyaltyPointsService,+ IProductService productService,+ ICurrencyService currencyService,+ IGroupService groupService,+ IDiscountValidationService discountValidationService,+ TaxSettings taxSettings,+ LoyaltyPointsSettings loyaltyPointsSettings,+ ShippingSettings shippingSettings,+ ShoppingCartSettings shoppingCartSettings,+ CatalogSettings catalogSettings){- #region Fields-- private readonly IWorkContext _workContext;- private readonly IPricingService _pricingService;- private readonly ITaxService _taxService;- private readonly IShippingService _shippingService;- private readonly IPaymentService _paymentService;- private readonly ICheckoutAttributeParser _checkoutAttributeParser;- private readonly IDiscountService _discountService;- private readonly IGiftVoucherService _giftVoucherService;- private readonly ILoyaltyPointsService _loyaltyPointsService;- private 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;- private readonly ShoppingCartSettings _shoppingCartSettings;- private readonly CatalogSettings _catalogSettings;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="workContext">Work context</param>- /// <param name="priceCalculationService">Price calculation service</param>- /// <param name="taxService">Tax service</param>- /// <param name="shippingService">Shipping service</param>- /// <param name="paymentService">Payment service</param>- /// <param name="checkoutAttributeParser">Checkout attribute parser</param>- /// <param name="discountService">Discount service</param>- /// <param name="giftVoucherService">Gift voucher service</param>- /// <param name="loyaltyPointsService">Loyalty points service</param>- /// <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>- /// <param name="shoppingCartSettings">Shopping cart settings</param>- /// <param name="catalogSettings">Catalog settings</param>- public OrderCalculationService(IWorkContext workContext,- IPricingService priceCalculationService,- ITaxService taxService,- IShippingService shippingService,- IPaymentService paymentService,- ICheckoutAttributeParser checkoutAttributeParser,- IDiscountService discountService,- IGiftVoucherService giftVoucherService,- ILoyaltyPointsService loyaltyPointsService,- IProductService productService,- ICurrencyService currencyService,- IGroupService groupService,- IDiscountValidationService discountValidationService,- TaxSettings taxSettings,- LoyaltyPointsSettings loyaltyPointsSettings,- ShippingSettings shippingSettings,- ShoppingCartSettings shoppingCartSettings,- CatalogSettings catalogSettings)- {- _workContext = workContext;- _pricingService = priceCalculationService;- _taxService = taxService;- _shippingService = shippingService;- _paymentService = paymentService;- _checkoutAttributeParser = checkoutAttributeParser;- _discountService = discountService;- _giftVoucherService = giftVoucherService;- _loyaltyPointsService = loyaltyPointsService;- _productService = productService;- _currencyService = currencyService;- _groupService = groupService;- _discountValidationService = discountValidationService;- _taxSettings = taxSettings;- _loyaltyPointsSettings = loyaltyPointsSettings;- _shippingSettings = shippingSettings;- _shoppingCartSettings = shoppingCartSettings;- _catalogSettings = catalogSettings;- }-- #endregion+ _workContext = workContext;+ _pricingService = priceCalculationService;+ _taxService = taxService;+ _shippingService = shippingService;+ _paymentService = paymentService;+ _checkoutAttributeParser = checkoutAttributeParser;+ _discountService = discountService;+ _giftVoucherService = giftVoucherService;+ _loyaltyPointsService = loyaltyPointsService;+ _productService = productService;+ _currencyService = currencyService;+ _groupService = groupService;+ _discountValidationService = discountValidationService;+ _taxSettings = taxSettings;+ _loyaltyPointsSettings = loyaltyPointsSettings;+ _shippingSettings = shippingSettings;+ _shoppingCartSettings = shoppingCartSettings;+ _catalogSettings = catalogSettings;+ }- #region Utilities-- /// <summary>- /// 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, Store store, Currency currency, double orderSubTotal)- {- var appliedDiscounts = new List<ApplyDiscount>();- double discountAmount = 0;- if (_catalogSettings.IgnoreDiscounts)- return (discountAmount, appliedDiscounts);-- 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 _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal &&- allowedDiscounts.All(x => x.DiscountId != discount.Id))- {- allowedDiscounts.Add(new ApplyDiscount {- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode- });- }- }+ #endregion++ #region Fields++ private readonly IWorkContext _workContext;+ private readonly IPricingService _pricingService;+ private readonly ITaxService _taxService;+ private readonly IShippingService _shippingService;+ private readonly IPaymentService _paymentService;+ private readonly ICheckoutAttributeParser _checkoutAttributeParser;+ private readonly IDiscountService _discountService;+ private readonly IGiftVoucherService _giftVoucherService;+ private readonly ILoyaltyPointsService _loyaltyPointsService;+ private 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;+ private readonly ShoppingCartSettings _shoppingCartSettings;+ private readonly CatalogSettings _catalogSettings;++ #endregion++ #region Utilities- var preferredDiscounts = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,- _workContext.WorkingCurrency, orderSubTotal);- appliedDiscounts = preferredDiscounts.appliedDiscount;- discountAmount = preferredDiscounts.discountAmount;+ /// <summary>+ /// 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, Store store, Currency currency, double orderSubTotal)+ {+ var appliedDiscounts = new List<ApplyDiscount>();+ double discountAmount = 0;+ if (_catalogSettings.IgnoreDiscounts)+ return (discountAmount, appliedDiscounts);- if (discountAmount < 0)- discountAmount = 0;+ var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToOrderSubTotal,+ _workContext.CurrentStore.Id, currency.CurrencyCode);+ var allowedDiscounts = new List<ApplyDiscount>();+ if (allDiscounts != null)+ foreach (var discount in allDiscounts)+ {+ var validDiscount =+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToOrderSubTotal &&+ allowedDiscounts.All(x => x.DiscountId != discount.Id))+ allowedDiscounts.Add(new ApplyDiscount {+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative,+ CouponCode = validDiscount.CouponCode+ });+ }- return (discountAmount, appliedDiscounts);- }+ var preferredDiscounts = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,+ _workContext.WorkingCurrency, orderSubTotal);+ appliedDiscounts = preferredDiscounts.appliedDiscount;+ discountAmount = preferredDiscounts.discountAmount;- /// <summary>- /// 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, Store store, Currency currency, double shippingTotal)- {- var appliedDiscounts = new List<ApplyDiscount>();- double shippingDiscountAmount = 0;- if (_catalogSettings.IgnoreDiscounts)- return (shippingDiscountAmount, appliedDiscounts);-- 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 _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToShipping &&- allowedDiscounts.All(x => x.DiscountId != discount.Id))- {- allowedDiscounts.Add(new ApplyDiscount {- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode- });- }- }+ if (discountAmount < 0)+ discountAmount = 0;- var (appliedDiscount, discountAmount) = await _discountService.GetPreferredDiscount(allowedDiscounts,- customer, _workContext.WorkingCurrency, shippingTotal);- appliedDiscounts = appliedDiscount;- shippingDiscountAmount = discountAmount;+ return (discountAmount, appliedDiscounts);+ }- if (shippingDiscountAmount < 0)- shippingDiscountAmount = 0;+ /// <summary>+ /// 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, Store store, Currency currency, double shippingTotal)+ {+ var appliedDiscounts = new List<ApplyDiscount>();+ double shippingDiscountAmount = 0;+ if (_catalogSettings.IgnoreDiscounts)+ return (shippingDiscountAmount, appliedDiscounts);- if (_shoppingCartSettings.RoundPrices)+ var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToShipping,+ _workContext.CurrentStore.Id, currency.CurrencyCode);+ var allowedDiscounts = new List<ApplyDiscount>();+ if (allDiscounts != null)+ foreach (var discount in allDiscounts){- shippingDiscountAmount =- RoundingHelper.RoundPrice(shippingDiscountAmount, _workContext.WorkingCurrency);+ var validDiscount =+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToShipping &&+ allowedDiscounts.All(x => x.DiscountId != discount.Id))+ allowedDiscounts.Add(new ApplyDiscount {+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative,+ CouponCode = validDiscount.CouponCode+ });}- return (shippingDiscountAmount, appliedDiscounts);- }+ var (appliedDiscount, discountAmount) = await _discountService.GetPreferredDiscount(allowedDiscounts,+ customer, _workContext.WorkingCurrency, shippingTotal);+ appliedDiscounts = appliedDiscount;+ shippingDiscountAmount = discountAmount;- /// <summary>- /// 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, Store store, Currency currency, double orderTotal)- {- var appliedDiscounts = new List<ApplyDiscount>();- double discountAmount = 0;- if (_catalogSettings.IgnoreDiscounts)- return (discountAmount, appliedDiscounts);-- 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 _discountValidationService.ValidateDiscount(discount, customer, store, currency);- if (validDiscount.IsValid &&- discount.DiscountTypeId == DiscountType.AssignedToOrderTotal &&- allowedDiscounts.All(x => x.DiscountId != discount.Id))- {- allowedDiscounts.Add(new ApplyDiscount {- DiscountId = discount.Id,- IsCumulative = discount.IsCumulative,- CouponCode = validDiscount.CouponCode- });- }- }+ if (shippingDiscountAmount < 0)+ shippingDiscountAmount = 0;++ if (_shoppingCartSettings.RoundPrices)+ shippingDiscountAmount =+ RoundingHelper.RoundPrice(shippingDiscountAmount, _workContext.WorkingCurrency);- var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,- _workContext.WorkingCurrency, orderTotal);- appliedDiscounts = preferredDiscount.appliedDiscount;- discountAmount = preferredDiscount.discountAmount;+ return (shippingDiscountAmount, appliedDiscounts);+ }- if (discountAmount < 0)- discountAmount = 0;+ /// <summary>+ /// 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, Store store, Currency currency, double orderTotal)+ {+ var appliedDiscounts = new List<ApplyDiscount>();+ double discountAmount = 0;+ if (_catalogSettings.IgnoreDiscounts)+ return (discountAmount, appliedDiscounts);- if (_shoppingCartSettings.RoundPrices)+ var allDiscounts = await _discountService.GetActiveDiscountsByContext(DiscountType.AssignedToOrderTotal,+ _workContext.CurrentStore.Id, currency.CurrencyCode);+ var allowedDiscounts = new List<ApplyDiscount>();+ if (allDiscounts != null)+ foreach (var discount in allDiscounts){- discountAmount = RoundingHelper.RoundPrice(discountAmount, _workContext.WorkingCurrency);+ var validDiscount =+ await _discountValidationService.ValidateDiscount(discount, customer, store, currency);+ if (validDiscount.IsValid &&+ discount.DiscountTypeId == DiscountType.AssignedToOrderTotal &&+ allowedDiscounts.All(x => x.DiscountId != discount.Id))+ allowedDiscounts.Add(new ApplyDiscount {+ DiscountId = discount.Id,+ IsCumulative = discount.IsCumulative,+ CouponCode = validDiscount.CouponCode+ });}- return (discountAmount, appliedDiscounts);- }+ var preferredDiscount = await _discountService.GetPreferredDiscount(allowedDiscounts, customer,+ _workContext.WorkingCurrency, orderTotal);+ appliedDiscounts = preferredDiscount.appliedDiscount;+ discountAmount = preferredDiscount.discountAmount;- /// <summary>- /// Get active gift vouchers that are applied by a customer- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="currency">Currency</param>- /// <param name="store">Store</param>- /// <returns>Active gift vouchers</returns>- private async Task<IList<GiftVoucher>> GetActiveGiftVouchers(Customer customer, Currency currency, Store store)- {- var result = new List<GiftVoucher>();- if (customer == null)- return result;+ if (discountAmount < 0)+ discountAmount = 0;- var couponCodes = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);- foreach (var couponCode in couponCodes)- {- var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(isGiftVoucherActivated: true,- giftVoucherCouponCode: couponCode);- result.AddRange(giftVouchers.Where(gc => gc.IsGiftVoucherValid(currency, store)));- }+ if (_shoppingCartSettings.RoundPrices)+ discountAmount = RoundingHelper.RoundPrice(discountAmount, _workContext.WorkingCurrency);++ return (discountAmount, appliedDiscounts);+ }+ /// <summary>+ /// Get active gift vouchers that are applied by a customer+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="currency">Currency</param>+ /// <param name="store">Store</param>+ /// <returns>Active gift vouchers</returns>+ private async Task<IList<GiftVoucher>> GetActiveGiftVouchers(Customer customer, Currency currency, Store store)+ {+ var result = new List<GiftVoucher>();+ if (customer == null)return result;++ var couponCodes = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);+ foreach (var couponCode in couponCodes)+ {+ var giftVouchers = await _giftVoucherService.GetAllGiftVouchers(isGiftVoucherActivated: true,+ giftVoucherCouponCode: couponCode);+ result.AddRange(giftVouchers.Where(gc => gc.IsGiftVoucherValid(currency, store)));}- #endregion+ return result;+ }- #region Methods+ #endregion- /// <summary>- /// Gets shopping cart subtotal- /// </summary>- /// <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)>- GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax)- {- double discountAmount = 0;- var appliedDiscounts = new List<ApplyDiscount>();- double subTotalWithoutDiscount = 0;- double subTotalWithDiscount = 0;- var taxRates = new SortedDictionary<double, double>();-- if (!cart.Any())- return (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates);-- //get the customer- Customer customer = _workContext.CurrentCustomer;-- //sub totals- double subTotalExclTaxWithoutDiscount = 0;- double subTotalInclTaxWithoutDiscount = 0;- foreach (var shoppingCartItem in cart)- {- var product = await _productService.GetProductById(shoppingCartItem.ProductId);- if (product == null)- continue;+ #region Methods- var subtotal = await _pricingService.GetSubTotal(shoppingCartItem, product);- var sciSubTotal = subtotal.subTotal;+ /// <summary>+ /// Gets shopping cart subtotal+ /// </summary>+ /// <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)>+ GetShoppingCartSubTotal(IList<ShoppingCartItem> cart, bool includingTax)+ {+ double discountAmount = 0;+ var appliedDiscounts = new List<ApplyDiscount>();+ double subTotalWithoutDiscount = 0;+ double subTotalWithDiscount = 0;+ var taxRates = new SortedDictionary<double, double>();- var pricesExcl = await _taxService.GetProductPrice(product, sciSubTotal, false, customer);- var sciExclTax = pricesExcl.productprice;+ if (!cart.Any())+ return (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates);- var (sciInclTax, taxRate) = await _taxService.GetProductPrice(product, sciSubTotal, true, customer);+ //get the customer+ var customer = _workContext.CurrentCustomer;- subTotalExclTaxWithoutDiscount += sciExclTax;- subTotalInclTaxWithoutDiscount += sciInclTax;+ //sub totals+ double subTotalExclTaxWithoutDiscount = 0;+ double subTotalInclTaxWithoutDiscount = 0;+ foreach (var shoppingCartItem in cart)+ {+ var product = await _productService.GetProductById(shoppingCartItem.ProductId);+ if (product == null)+ continue;- //tax rates- var sciTax = sciInclTax - sciExclTax;- if (!(taxRate > 0) || !(sciTax > 0)) continue;- if (!taxRates.ContainsKey(taxRate))- {- taxRates.Add(taxRate, sciTax);- }- else- {- taxRates[taxRate] += sciTax;- }- }+ var subtotal = await _pricingService.GetSubTotal(shoppingCartItem, product);+ var sciSubTotal = subtotal.subTotal;- //checkout attributes- if (customer != null)- {- 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);-- subTotalExclTaxWithoutDiscount += caExclTax;- subTotalInclTaxWithoutDiscount += caInclTax;-- //tax rates- var caTax = caInclTax - caExclTax;- if (!(taxRate > 0) || !(caTax > 0)) continue;- if (!taxRates.ContainsKey(taxRate))- {- taxRates.Add(taxRate, caTax);- }- else- {- taxRates[taxRate] += caTax;- }- }- }+ var pricesExcl = await _taxService.GetProductPrice(product, sciSubTotal, false, customer);+ var sciExclTax = pricesExcl.productprice;- //subtotal without discount- subTotalWithoutDiscount = includingTax ? subTotalInclTaxWithoutDiscount : subTotalExclTaxWithoutDiscount;+ var (sciInclTax, taxRate) = await _taxService.GetProductPrice(product, sciSubTotal, true, customer);- if (subTotalWithoutDiscount < 0)- subTotalWithoutDiscount = 0;+ subTotalExclTaxWithoutDiscount += sciExclTax;+ subTotalInclTaxWithoutDiscount += sciInclTax;- if (_shoppingCartSettings.RoundPrices)- {- subTotalWithoutDiscount =- RoundingHelper.RoundPrice(subTotalWithoutDiscount, _workContext.WorkingCurrency);- }+ //tax rates+ var sciTax = sciInclTax - sciExclTax;+ if (!(taxRate > 0) || !(sciTax > 0)) continue;+ if (!taxRates.ContainsKey(taxRate))+ taxRates.Add(taxRate, sciTax);+ else+ taxRates[taxRate] += sciTax;+ }- //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.CurrentStore,- _workContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);- var discountAmountExclTax = orderSubtotalDiscount.ordersubtotaldiscount;- appliedDiscounts = orderSubtotalDiscount.appliedDiscounts;-- if (subTotalExclTaxWithoutDiscount < discountAmountExclTax)- discountAmountExclTax = subTotalExclTaxWithoutDiscount;- var discountAmountInclTax = discountAmountExclTax;- //subtotal with discount (excl tax)- var subTotalExclTaxWithDiscount = subTotalExclTaxWithoutDiscount - discountAmountExclTax;- var subTotalInclTaxWithDiscount = subTotalExclTaxWithDiscount;-- //add tax for shopping items & checkout attributes- var tempTaxRates = new Dictionary<double, double>(taxRates);- foreach (KeyValuePair<double, double> kvp in tempTaxRates)+ //checkout attributes+ if (customer != null)+ {+ var checkoutAttributes =+ customer.GetUserFieldFromEntity<List<CustomAttribute>>(SystemCustomerFieldNames.CheckoutAttributes,+ _workContext.CurrentStore.Id);+ var attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes);+ foreach (var attributeValue in attributeValues){- var taxRate = kvp.Key;- var taxValue = kvp.Value;+ 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;- if (taxValue == 0) continue;- //discount the tax amount that applies to subtotal items- if (subTotalExclTaxWithoutDiscount > 0)- {- var discountTax = taxRates[taxRate] * (discountAmountExclTax / subTotalExclTaxWithoutDiscount);- discountAmountInclTax += discountTax;- taxValue = taxRates[taxRate] - discountTax;- if (_shoppingCartSettings.RoundPrices)- taxValue = RoundingHelper.RoundPrice(taxValue, _workContext.WorkingCurrency);- taxRates[taxRate] = taxValue;- }-- //subtotal with discount (incl tax)- subTotalInclTaxWithDiscount += taxValue;+ //tax rates+ var caTax = caInclTax - caExclTax;+ if (!(taxRate > 0) || !(caTax > 0)) continue;+ if (!taxRates.ContainsKey(taxRate))+ taxRates.Add(taxRate, caTax);+ else+ taxRates[taxRate] += caTax;}+ }- if (_shoppingCartSettings.RoundPrices)- {- discountAmountInclTax = RoundingHelper.RoundPrice(discountAmountInclTax, _workContext.WorkingCurrency);- discountAmountExclTax = RoundingHelper.RoundPrice(discountAmountExclTax, _workContext.WorkingCurrency);- }+ //subtotal without discount+ subTotalWithoutDiscount = includingTax ? subTotalInclTaxWithoutDiscount : subTotalExclTaxWithoutDiscount;++ if (subTotalWithoutDiscount < 0)+ subTotalWithoutDiscount = 0;++ if (_shoppingCartSettings.RoundPrices)+ 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.CurrentStore,+ _workContext.WorkingCurrency, subTotalExclTaxWithoutDiscount);+ var discountAmountExclTax = orderSubtotalDiscount.ordersubtotaldiscount;+ appliedDiscounts = orderSubtotalDiscount.appliedDiscounts;++ if (subTotalExclTaxWithoutDiscount < discountAmountExclTax)+ discountAmountExclTax = subTotalExclTaxWithoutDiscount;+ var discountAmountInclTax = discountAmountExclTax;+ //subtotal with discount (excl tax)+ var subTotalExclTaxWithDiscount = subTotalExclTaxWithoutDiscount - discountAmountExclTax;+ var subTotalInclTaxWithDiscount = subTotalExclTaxWithDiscount;++ //add tax for shopping items & checkout attributes+ var tempTaxRates = new Dictionary<double, double>(taxRates);+ foreach (var kvp in tempTaxRates)+ {+ var taxRate = kvp.Key;+ var taxValue = kvp.Value;- if (includingTax)+ if (taxValue == 0) continue;+ //discount the tax amount that applies to subtotal items+ if (subTotalExclTaxWithoutDiscount > 0){- subTotalWithDiscount = subTotalInclTaxWithDiscount;- discountAmount = discountAmountInclTax;+ var discountTax = taxRates[taxRate] * (discountAmountExclTax / subTotalExclTaxWithoutDiscount);+ discountAmountInclTax += discountTax;+ taxValue = taxRates[taxRate] - discountTax;+ if (_shoppingCartSettings.RoundPrices)+ taxValue = RoundingHelper.RoundPrice(taxValue, _workContext.WorkingCurrency);+ taxRates[taxRate] = taxValue;}- else- {- subTotalWithDiscount = subTotalExclTaxWithDiscount;- discountAmount = discountAmountExclTax;- }-- if (subTotalWithDiscount < 0)- subTotalWithDiscount = 0;- if (_shoppingCartSettings.RoundPrices)- subTotalWithDiscount = RoundingHelper.RoundPrice(subTotalWithDiscount, _workContext.WorkingCurrency);-- return (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates);+ //subtotal with discount (incl tax)+ subTotalInclTaxWithDiscount += taxValue;}-- /// <summary>- /// Gets shopping cart additional shipping charge- /// </summary>- /// <param name="cart">Cart</param>- /// <returns>Additional shipping charge</returns>- public virtual async Task<double> GetShoppingCartAdditionalShippingCharge(IList<ShoppingCartItem> cart)+ if (_shoppingCartSettings.RoundPrices){- var isFreeShipping = await IsFreeShipping(cart);- if (isFreeShipping)- return 0;-- return cart.Where(sci => sci.IsShipEnabled && !sci.IsFreeShipping).Sum(sci =>- _shippingSettings.AdditionalShippingChargeByQty- ? sci.AdditionalShippingChargeProduct * sci.Quantity- : sci.AdditionalShippingChargeProduct);+ discountAmountInclTax = RoundingHelper.RoundPrice(discountAmountInclTax, _workContext.WorkingCurrency);+ discountAmountExclTax = RoundingHelper.RoundPrice(discountAmountExclTax, _workContext.WorkingCurrency);}- /// <summary>- /// Gets a value indicating whether shipping is free- /// </summary>- /// <param name="cart">Cart</param>- /// <returns>A value indicating whether shipping is free</returns>- public virtual async Task<bool> IsFreeShipping(IList<ShoppingCartItem> cart)+ if (includingTax){- Customer customer = _workContext.CurrentCustomer;- if (customer != null)- {- //check whether customer has a free shipping- if (customer.FreeShipping)- return true;+ subTotalWithDiscount = subTotalInclTaxWithDiscount;+ discountAmount = discountAmountInclTax;+ }+ else+ {+ subTotalWithDiscount = subTotalExclTaxWithDiscount;+ discountAmount = discountAmountExclTax;+ }- //check whether customer is in a customer group with free shipping applied- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());- if (customerGroups.Any(customerGroup => customerGroup.FreeShipping))- {- return true;- }- }+ if (subTotalWithDiscount < 0)+ subTotalWithDiscount = 0;- var shoppingCartRequiresShipping = cart.RequiresShipping();- if (!shoppingCartRequiresShipping)- return true;+ if (_shoppingCartSettings.RoundPrices)+ subTotalWithDiscount = RoundingHelper.RoundPrice(subTotalWithDiscount, _workContext.WorkingCurrency);- //check whether all shopping cart items are marked as free shipping- var allItemsAreFreeShipping = cart.All(sc => !sc.IsShipEnabled || sc.IsFreeShipping);- if (allItemsAreFreeShipping)- return true;+ return (discountAmount, appliedDiscounts, subTotalWithoutDiscount, subTotalWithDiscount, taxRates);+ }- //free shipping over $X- if (!_shippingSettings.FreeShippingOverXEnabled) return false;- //check whether we have subtotal enough to have free shipping- var (_, _, _, subTotalWithDiscount, _) =- await GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax);- return subTotalWithDiscount > _shippingSettings.FreeShippingOverXValue;- //otherwise, return false- }+ /// <summary>+ /// Gets shopping cart additional shipping charge+ /// </summary>+ /// <param name="cart">Cart</param>+ /// <returns>Additional shipping charge</returns>+ public virtual async Task<double> GetShoppingCartAdditionalShippingCharge(IList<ShoppingCartItem> cart)+ {+ var isFreeShipping = await IsFreeShipping(cart);+ if (isFreeShipping)+ return 0;++ return cart.Where(sci => sci.IsShipEnabled && !sci.IsFreeShipping).Sum(sci =>+ _shippingSettings.AdditionalShippingChargeByQty+ ? sci.AdditionalShippingChargeProduct * sci.Quantity+ : sci.AdditionalShippingChargeProduct);+ }- /// <summary>- /// Adjust shipping rate (free shipping, additional charges, discounts)- /// </summary>- /// <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)+ /// <summary>+ /// Gets a value indicating whether shipping is free+ /// </summary>+ /// <param name="cart">Cart</param>+ /// <returns>A value indicating whether shipping is free</returns>+ public virtual async Task<bool> IsFreeShipping(IList<ShoppingCartItem> cart)+ {+ var customer = _workContext.CurrentCustomer;+ if (customer != null){- var appliedDiscounts = new List<ApplyDiscount>();+ //check whether customer has a free shipping+ if (customer.FreeShipping)+ return true;- //free shipping- if (await IsFreeShipping(cart))- return (0, appliedDiscounts);+ //check whether customer is in a customer group with free shipping applied+ var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());+ if (customerGroups.Any(customerGroup => customerGroup.FreeShipping)) return true;+ }- //additional shipping charges- var additionalShippingCharge = await GetShoppingCartAdditionalShippingCharge(cart);- var adjustedRate = shippingRate + additionalShippingCharge;+ var shoppingCartRequiresShipping = cart.RequiresShipping();+ if (!shoppingCartRequiresShipping)+ return true;- //discount- var (discountAmount, applyDiscounts) = await GetShippingDiscount(- _workContext.CurrentCustomer,- _workContext.CurrentStore,- _workContext.WorkingCurrency, adjustedRate);- appliedDiscounts = applyDiscounts;+ //check whether all shopping cart items are marked as free shipping+ var allItemsAreFreeShipping = cart.All(sc => !sc.IsShipEnabled || sc.IsFreeShipping);+ if (allItemsAreFreeShipping)+ return true;- adjustedRate -= discountAmount;+ //free shipping over $X+ if (!_shippingSettings.FreeShippingOverXEnabled) return false;+ //check whether we have subtotal enough to have free shipping+ var (_, _, _, subTotalWithDiscount, _) =+ await GetShoppingCartSubTotal(cart, _shippingSettings.FreeShippingOverXIncludingTax);- if (adjustedRate < 0)- adjustedRate = 0;+ return subTotalWithDiscount > _shippingSettings.FreeShippingOverXValue;+ //otherwise, return false+ }- if (_shoppingCartSettings.RoundPrices)- {- adjustedRate = RoundingHelper.RoundPrice(adjustedRate, _workContext.WorkingCurrency);- }+ /// <summary>+ /// Adjust shipping rate (free shipping, additional charges, discounts)+ /// </summary>+ /// <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)+ {+ var appliedDiscounts = new List<ApplyDiscount>();- return (adjustedRate, appliedDiscounts);- }+ //free shipping+ if (await IsFreeShipping(cart))+ return (0, appliedDiscounts);- /// <summary>- /// Gets shopping cart shipping total- /// </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)- {- var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;- return await GetShoppingCartShippingTotal(cart, includingTax);- }+ //additional shipping charges+ var additionalShippingCharge = await GetShoppingCartAdditionalShippingCharge(cart);+ var adjustedRate = shippingRate + additionalShippingCharge;+ //discount+ var (discountAmount, applyDiscounts) = await GetShippingDiscount(+ _workContext.CurrentCustomer,+ _workContext.CurrentStore,+ _workContext.WorkingCurrency, adjustedRate);+ appliedDiscounts = applyDiscounts;- /// <summary>- /// Gets shopping cart shipping total- /// </summary>- /// <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)- {- double? shippingTotal = null;- var appliedDiscounts = new List<ApplyDiscount>();- double taxRate = 0;+ adjustedRate -= discountAmount;- var customer = _workContext.CurrentCustomer;- var currency = await _currencyService.GetPrimaryExchangeRateCurrency();+ if (adjustedRate < 0)+ adjustedRate = 0;- var isFreeShipping = await IsFreeShipping(cart);- if (isFreeShipping)- return (0, taxRate, appliedDiscounts);+ if (_shoppingCartSettings.RoundPrices)+ adjustedRate = RoundingHelper.RoundPrice(adjustedRate, _workContext.WorkingCurrency);- ShippingOption shippingOption = null;- if (customer != null)- shippingOption =- customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption,- _workContext.CurrentStore.Id);+ return (adjustedRate, appliedDiscounts);+ }- if (shippingOption != null)- {- var rate = shippingOption.Rate;- var adjustShippingRate = await AdjustShippingRate(rate, cart);- shippingTotal = adjustShippingRate.shippingRate;- appliedDiscounts = adjustShippingRate.appliedDiscounts;- }- else- {- //use fixed rate (if possible)- Address shippingAddress = null;- if (customer != null)- shippingAddress = customer.ShippingAddress;+ /// <summary>+ /// Gets shopping cart shipping total+ /// </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)+ {+ var includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax;+ return await GetShoppingCartShippingTotal(cart, includingTax);+ }- 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");+ /// <summary>+ /// Gets shopping cart shipping total+ /// </summary>+ /// <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)+ {+ double? shippingTotal = null;+ var appliedDiscounts = new List<ApplyDiscount>();+ double taxRate = 0;- if (shippingRateMethods.Count == 1)- {- var shippingRateMethod = shippingRateMethods[0];+ var customer = _workContext.CurrentCustomer;+ var currency = await _currencyService.GetPrimaryExchangeRateCurrency();- var shippingOptionRequest = await _shippingService.CreateShippingOptionRequests(customer, cart,- shippingAddress,- _workContext.CurrentStore);+ var isFreeShipping = await IsFreeShipping(cart);+ if (isFreeShipping)+ return (0, taxRate, appliedDiscounts);- double? fixedRate = null;- //calculate fixed rates for each request-package- var fixedRateTmp = await shippingRateMethod.GetFixedRate(shippingOptionRequest);- if (fixedRateTmp.HasValue)- {- fixedRate = 0;- fixedRate += fixedRateTmp.Value;- }+ ShippingOption shippingOption = null;+ if (customer != null)+ shippingOption =+ customer.GetUserFieldFromEntity<ShippingOption>(SystemCustomerFieldNames.SelectedShippingOption,+ _workContext.CurrentStore.Id);- if (fixedRate.HasValue)- {- //adjust shipping rate- var adjustShippingRate = await AdjustShippingRate(fixedRate.Value, cart);- shippingTotal = adjustShippingRate.shippingRate;- appliedDiscounts = adjustShippingRate.appliedDiscounts;- }- }- }+ if (shippingOption != null)+ {+ var rate = shippingOption.Rate;+ var adjustShippingRate = await AdjustShippingRate(rate, cart);+ shippingTotal = adjustShippingRate.shippingRate;+ appliedDiscounts = adjustShippingRate.appliedDiscounts;+ }+ else+ {+ //use fixed rate (if possible)+ Address shippingAddress = null;+ if (customer != null)+ shippingAddress = customer.ShippingAddress;- switch (shippingTotal)- {- case null:- return (null, taxRate, appliedDiscounts);- case < 0:- shippingTotal = 0;- break;- }+ 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");- //round- if (_shoppingCartSettings.RoundPrices)- shippingTotal = RoundingHelper.RoundPrice(shippingTotal.Value, currency);+ if (shippingRateMethods.Count == 1)+ {+ var shippingRateMethod = shippingRateMethods[0];- var shippingPrice = await _taxService.GetShippingPrice(shippingTotal.Value, includingTax, customer);- double? shippingTotalTaxed = shippingPrice.shippingPrice;- taxRate = shippingPrice.taxRate;+ var shippingOptionRequest = await _shippingService.CreateShippingOptionRequests(customer, cart,+ shippingAddress,+ _workContext.CurrentStore);- //round- if (_shoppingCartSettings.RoundPrices)- shippingTotalTaxed = RoundingHelper.RoundPrice(shippingTotalTaxed.Value, currency);+ double? fixedRate = null;+ //calculate fixed rates for each request-package+ var fixedRateTmp = await shippingRateMethod.GetFixedRate(shippingOptionRequest);+ if (fixedRateTmp.HasValue)+ {+ fixedRate = 0;+ fixedRate += fixedRateTmp.Value;+ }- return (shippingTotalTaxed, taxRate, appliedDiscounts);+ if (fixedRate.HasValue)+ {+ //adjust shipping rate+ var adjustShippingRate = await AdjustShippingRate(fixedRate.Value, cart);+ shippingTotal = adjustShippingRate.shippingRate;+ appliedDiscounts = adjustShippingRate.appliedDiscounts;+ }+ }}- /// <summary>- /// Gets tax- /// </summary>- /// <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)+ switch (shippingTotal){- ArgumentNullException.ThrowIfNull(cart);+ case null:+ return (null, taxRate, appliedDiscounts);+ case < 0:+ shippingTotal = 0;+ break;+ }- var taxRates = new SortedDictionary<double, double>();+ //round+ if (_shoppingCartSettings.RoundPrices)+ shippingTotal = RoundingHelper.RoundPrice(shippingTotal.Value, currency);- var customer = _workContext.CurrentCustomer;- var paymentMethodSystemName = "";- if (customer != null)- {- paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(- SystemCustomerFieldNames.SelectedPaymentMethod,- _workContext.CurrentStore.Id);- }+ var shippingPrice = await _taxService.GetShippingPrice(shippingTotal.Value, includingTax, customer);+ double? shippingTotalTaxed = shippingPrice.shippingPrice;+ taxRate = shippingPrice.taxRate;- //order sub total (items + checkout attributes)- double subTotalTaxTotal = 0;+ //round+ if (_shoppingCartSettings.RoundPrices)+ shippingTotalTaxed = RoundingHelper.RoundPrice(shippingTotalTaxed.Value, currency);- var shoppingCartSubTotal = await GetShoppingCartSubTotal(cart, false);- SortedDictionary<double, double> orderSubTotalTaxRates = shoppingCartSubTotal.taxRates;+ return (shippingTotalTaxed, taxRate, appliedDiscounts);+ }- foreach (var (taxRate, taxValue) in orderSubTotalTaxRates)- {- subTotalTaxTotal += taxValue;+ /// <summary>+ /// Gets tax+ /// </summary>+ /// <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)+ {+ ArgumentNullException.ThrowIfNull(cart);- if (!(taxRate > 0) || !(taxValue > 0)) continue;- if (!taxRates.ContainsKey(taxRate))- taxRates.Add(taxRate, taxValue);- else- taxRates[taxRate] += taxValue;- }+ var taxRates = new SortedDictionary<double, double>();- //shipping- double shippingTax = 0;- if (_taxSettings.ShippingIsTaxable)- {- var shippingTotalExcl = await GetShoppingCartShippingTotal(cart, false);- var shippingExclTax = shippingTotalExcl.shoppingCartShippingTotal;+ var customer = _workContext.CurrentCustomer;+ var paymentMethodSystemName = "";+ if (customer != null)+ paymentMethodSystemName = customer.GetUserFieldFromEntity<string>(+ SystemCustomerFieldNames.SelectedPaymentMethod,+ _workContext.CurrentStore.Id);- var (shippingInclTax, taxRate, _) = await GetShoppingCartShippingTotal(cart, true);+ //order sub total (items + checkout attributes)+ double subTotalTaxTotal = 0;- if (shippingExclTax.HasValue && shippingInclTax.HasValue)- {- shippingTax = shippingInclTax.Value - shippingExclTax.Value;- //ensure that tax is equal or greater than zero- if (shippingTax < 0)- shippingTax = 0;+ var shoppingCartSubTotal = await GetShoppingCartSubTotal(cart, false);+ var orderSubTotalTaxRates = shoppingCartSubTotal.taxRates;- //tax rates- if (taxRate > 0 && shippingTax > 0)- {- if (!taxRates.ContainsKey(taxRate))- taxRates.Add(taxRate, shippingTax);- else- taxRates[taxRate] += shippingTax;- }- }- }+ foreach (var (taxRate, taxValue) in orderSubTotalTaxRates)+ {+ subTotalTaxTotal += taxValue;- //payment method additional fee- double paymentMethodAdditionalFeeTax = 0;- if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable)- {- var paymentMethodAdditionalFee =- await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);+ if (!(taxRate > 0) || !(taxValue > 0)) continue;+ if (!taxRates.ContainsKey(taxRate))+ taxRates.Add(taxRate, taxValue);+ else+ taxRates[taxRate] += taxValue;+ }- var additionalFeeExclTax =- await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer);- var paymentMethodAdditionalFeeExclTax = additionalFeeExclTax.paymentPrice;+ //shipping+ double shippingTax = 0;+ if (_taxSettings.ShippingIsTaxable)+ {+ var shippingTotalExcl = await GetShoppingCartShippingTotal(cart, false);+ var shippingExclTax = shippingTotalExcl.shoppingCartShippingTotal;- var (paymentMethodAdditionalFeeInclTax, taxRate) =- await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);+ var (shippingInclTax, taxRate, _) = await GetShoppingCartShippingTotal(cart, true);- paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;+ if (shippingExclTax.HasValue && shippingInclTax.HasValue)+ {+ shippingTax = shippingInclTax.Value - shippingExclTax.Value;//ensure that tax is equal or greater than zero- if (paymentMethodAdditionalFeeTax < 0)- paymentMethodAdditionalFeeTax = 0;+ if (shippingTax < 0)+ shippingTax = 0;//tax rates- if (taxRate > 0 && paymentMethodAdditionalFeeTax > 0)+ if (taxRate > 0 && shippingTax > 0){if (!taxRates.ContainsKey(taxRate))- taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);+ taxRates.Add(taxRate, shippingTax);else- taxRates[taxRate] += paymentMethodAdditionalFeeTax;+ taxRates[taxRate] += shippingTax;}}+ }++ //payment method additional fee+ double paymentMethodAdditionalFeeTax = 0;+ if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable)+ {+ var paymentMethodAdditionalFee =+ await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);- //add at least one tax rate (0%)- if (!taxRates.Any())- taxRates.Add(0, 0);+ var additionalFeeExclTax =+ await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer);+ var paymentMethodAdditionalFeeExclTax = additionalFeeExclTax.paymentPrice;- //summarize taxes- var taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;+ var (paymentMethodAdditionalFeeInclTax, taxRate) =+ await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer);++ paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;//ensure that tax is equal or greater than zero- if (taxTotal < 0)- taxTotal = 0;- //round tax- if (_shoppingCartSettings.RoundPrices)+ if (paymentMethodAdditionalFeeTax < 0)+ paymentMethodAdditionalFeeTax = 0;++ //tax rates+ if (taxRate > 0 && paymentMethodAdditionalFeeTax > 0){- taxTotal = RoundingHelper.RoundPrice(taxTotal, _workContext.WorkingCurrency);+ if (!taxRates.ContainsKey(taxRate))+ taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);+ else+ taxRates[taxRate] += paymentMethodAdditionalFeeTax;}-- return (taxTotal, taxRates);}+ //add at least one tax rate (0%)+ if (!taxRates.Any())+ taxRates.Add(0, 0);- /// <summary>- /// Gets shopping cart total- /// </summary>- /// <param name="cart">Cart</param>- /// <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)- {- var redeemedLoyaltyPoints = 0;- double redeemedLoyaltyPointsAmount = 0;+ //summarize taxes+ var taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;+ //ensure that tax is equal or greater than zero+ if (taxTotal < 0)+ taxTotal = 0;+ //round tax+ if (_shoppingCartSettings.RoundPrices)+ taxTotal = RoundingHelper.RoundPrice(taxTotal, _workContext.WorkingCurrency);- var paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(- SystemCustomerFieldNames.SelectedPaymentMethod,- _workContext.CurrentStore.Id);+ return (taxTotal, taxRates);+ }- //subtotal without tax- var subTotal = await GetShoppingCartSubTotal(cart, false);- var subTotalWithDiscountBase = subTotal.subTotalWithDiscount;- //shipping without tax- var shippingTotal = await GetShoppingCartShippingTotal(cart, false);- var shoppingCartShipping = shippingTotal.shoppingCartShippingTotal;+ /// <summary>+ /// Gets shopping cart total+ /// </summary>+ /// <param name="cart">Cart</param>+ /// <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)+ {+ var redeemedLoyaltyPoints = 0;+ double redeemedLoyaltyPointsAmount = 0;- //payment method additional fee without tax- double paymentMethodAdditionalFeeWithoutTax = 0;- if (usePaymentMethodAdditionalFee && !string.IsNullOrEmpty(paymentMethodSystemName))- {- var paymentMethodAdditionalFee =- await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);- paymentMethodAdditionalFeeWithoutTax =- (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, _workContext.CurrentCustomer))- .paymentPrice;- }+ var paymentMethodSystemName = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(+ SystemCustomerFieldNames.SelectedPaymentMethod,+ _workContext.CurrentStore.Id);- //tax- var shoppingCartTax = (await GetTaxTotal(cart, usePaymentMethodAdditionalFee)).taxtotal;+ //subtotal without tax+ var subTotal = await GetShoppingCartSubTotal(cart, false);+ var subTotalWithDiscountBase = subTotal.subTotalWithDiscount;- //order total- double resultTemp = 0;- resultTemp += subTotalWithDiscountBase;- if (shoppingCartShipping.HasValue)- {- resultTemp += shoppingCartShipping.Value;- }+ //shipping without tax+ var shippingTotal = await GetShoppingCartShippingTotal(cart, false);+ var shoppingCartShipping = shippingTotal.shoppingCartShippingTotal;- resultTemp += paymentMethodAdditionalFeeWithoutTax;- resultTemp += shoppingCartTax;- if (_shoppingCartSettings.RoundPrices)- {- resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);- }+ //payment method additional fee without tax+ double paymentMethodAdditionalFeeWithoutTax = 0;+ if (usePaymentMethodAdditionalFee && !string.IsNullOrEmpty(paymentMethodSystemName))+ {+ var paymentMethodAdditionalFee =+ await _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);+ paymentMethodAdditionalFeeWithoutTax =+ (await _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false,+ _workContext.CurrentCustomer))+ .paymentPrice;+ }- #region Order total discount+ //tax+ var shoppingCartTax = (await GetTaxTotal(cart, usePaymentMethodAdditionalFee)).taxtotal;- var totalDiscount = await GetOrderTotalDiscount(_workContext.CurrentCustomer, _workContext.CurrentStore,- _workContext.WorkingCurrency, resultTemp);- var discountAmount = totalDiscount.orderTotalDiscount;- var appliedDiscounts = totalDiscount.appliedDiscounts;+ //order total+ double resultTemp = 0;+ resultTemp += subTotalWithDiscountBase;+ if (shoppingCartShipping.HasValue) resultTemp += shoppingCartShipping.Value;- //sub totals with discount- if (resultTemp < discountAmount)- discountAmount = resultTemp;+ resultTemp += paymentMethodAdditionalFeeWithoutTax;+ resultTemp += shoppingCartTax;+ if (_shoppingCartSettings.RoundPrices)+ resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);- //reduce subtotal- resultTemp -= discountAmount;+ #region Order total discount- if (resultTemp < 0)- resultTemp = 0;- if (_shoppingCartSettings.RoundPrices)- resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);+ var totalDiscount = await GetOrderTotalDiscount(_workContext.CurrentCustomer, _workContext.CurrentStore,+ _workContext.WorkingCurrency, resultTemp);+ var discountAmount = totalDiscount.orderTotalDiscount;+ var appliedDiscounts = totalDiscount.appliedDiscounts;- #endregion+ //sub totals with discount+ if (resultTemp < discountAmount)+ discountAmount = resultTemp;- #region Applied gift vouchers+ //reduce subtotal+ resultTemp -= discountAmount;- var appliedGiftVouchers = new List<AppliedGiftVoucher>();- //we don't apply gift vouchers for recurring products- 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;+ if (resultTemp < 0)+ resultTemp = 0;+ if (_shoppingCartSettings.RoundPrices)+ resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);- //reduce subtotal- resultTemp -= amountCanBeUsed;+ #endregion- var appliedGiftVoucher = new AppliedGiftVoucher {- GiftVoucher = gc,- AmountCanBeUsed = amountCanBeUsed- };- appliedGiftVouchers.Add(appliedGiftVoucher);- }+ #region Applied gift vouchers- #endregion+ var appliedGiftVouchers = new List<AppliedGiftVoucher>();+ //we don't apply gift vouchers for recurring products+ 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;- if (resultTemp < 0)- resultTemp = 0;- if (_shoppingCartSettings.RoundPrices)- resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);+ //reduce subtotal+ resultTemp -= amountCanBeUsed;- if (!shoppingCartShipping.HasValue)- {- //we have errors- return (null, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,- redeemedLoyaltyPointsAmount);- }+ var appliedGiftVoucher = new AppliedGiftVoucher {+ GiftVoucher = gc,+ AmountCanBeUsed = amountCanBeUsed+ };+ appliedGiftVouchers.Add(appliedGiftVoucher);+ }- var orderTotal = resultTemp;+ #endregion- #region Loyalty points+ if (resultTemp < 0)+ resultTemp = 0;+ if (_shoppingCartSettings.RoundPrices)+ resultTemp = RoundingHelper.RoundPrice(resultTemp, _workContext.WorkingCurrency);- if (_loyaltyPointsSettings.Enabled)- {- useLoyaltyPoints ??= _workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(- SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout,- _workContext.CurrentStore.Id);+ if (!shoppingCartShipping.HasValue)+ //we have errors+ return (null, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,+ redeemedLoyaltyPointsAmount);++ var orderTotal = resultTemp;++ #region Loyalty points++ if (_loyaltyPointsSettings.Enabled)+ {+ useLoyaltyPoints ??= _workContext.CurrentCustomer.GetUserFieldFromEntity<bool>(+ SystemCustomerFieldNames.UseLoyaltyPointsDuringCheckout,+ _workContext.CurrentStore.Id);- if (useLoyaltyPoints.Value)+ if (useLoyaltyPoints.Value)+ {+ var loyaltyPointsBalance =+ await _loyaltyPointsService.GetLoyaltyPointsBalance(_workContext.CurrentCustomer.Id,+ _workContext.CurrentStore.Id);+ if (CheckMinimumLoyaltyPointsToUseRequirement(loyaltyPointsBalance)){- var loyaltyPointsBalance =- await _loyaltyPointsService.GetLoyaltyPointsBalance(_workContext.CurrentCustomer.Id, _workContext.CurrentStore.Id);- if (CheckMinimumLoyaltyPointsToUseRequirement(loyaltyPointsBalance))+ var loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);+ if (orderTotal > 0){- var loyaltyPointsBalanceAmount = await ConvertLoyaltyPointsToAmount(loyaltyPointsBalance);- if (orderTotal > 0)+ if (orderTotal > loyaltyPointsBalanceAmount){- if (orderTotal > loyaltyPointsBalanceAmount)- {- redeemedLoyaltyPoints = loyaltyPointsBalance;- redeemedLoyaltyPointsAmount =- await _currencyService.ConvertFromPrimaryStoreCurrency(loyaltyPointsBalanceAmount,- _workContext.WorkingCurrency);- }- else- {- redeemedLoyaltyPointsAmount = orderTotal;- redeemedLoyaltyPoints = ConvertAmountToLoyaltyPoints(- await _currencyService.ConvertToPrimaryStoreCurrency(redeemedLoyaltyPointsAmount,- _workContext.WorkingCurrency));- }+ redeemedLoyaltyPoints = loyaltyPointsBalance;+ redeemedLoyaltyPointsAmount =+ await _currencyService.ConvertFromPrimaryStoreCurrency(loyaltyPointsBalanceAmount,+ _workContext.WorkingCurrency);+ }+ else+ {+ redeemedLoyaltyPointsAmount = orderTotal;+ redeemedLoyaltyPoints = ConvertAmountToLoyaltyPoints(+ await _currencyService.ConvertToPrimaryStoreCurrency(redeemedLoyaltyPointsAmount,+ _workContext.WorkingCurrency));}}}}+ }- #endregion+ #endregion- orderTotal -= redeemedLoyaltyPointsAmount;- if (_shoppingCartSettings.RoundPrices)- orderTotal = RoundingHelper.RoundPrice(orderTotal, _workContext.WorkingCurrency);+ orderTotal -= redeemedLoyaltyPointsAmount;+ if (_shoppingCartSettings.RoundPrices)+ orderTotal = RoundingHelper.RoundPrice(orderTotal, _workContext.WorkingCurrency);- return (orderTotal, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,- redeemedLoyaltyPointsAmount);- }+ return (orderTotal, discountAmount, appliedDiscounts, appliedGiftVouchers, redeemedLoyaltyPoints,+ redeemedLoyaltyPointsAmount);+ }- /// <summary>- /// Converts existing loyalty points to amount- /// </summary>- /// <param name="loyaltyPoints">Loyalty points</param>- /// <returns>Converted value</returns>- public virtual async Task<double> ConvertLoyaltyPointsToAmount(int loyaltyPoints)- {- if (loyaltyPoints <= 0)- return 0;+ /// <summary>+ /// Converts existing loyalty points to amount+ /// </summary>+ /// <param name="loyaltyPoints">Loyalty points</param>+ /// <returns>Converted value</returns>+ public virtual async Task<double> ConvertLoyaltyPointsToAmount(int loyaltyPoints)+ {+ if (loyaltyPoints <= 0)+ return 0;- var result = loyaltyPoints * _loyaltyPointsSettings.ExchangeRate;- if (_shoppingCartSettings.RoundPrices)- {- result = RoundingHelper.RoundPrice(result, _workContext.WorkingCurrency);- }+ var result = loyaltyPoints * _loyaltyPointsSettings.ExchangeRate;+ if (_shoppingCartSettings.RoundPrices) result = RoundingHelper.RoundPrice(result, _workContext.WorkingCurrency);- return await Task.FromResult(result);- }-- /// <summary>- /// Converts an amount to loyalty points- /// </summary>- /// <param name="amount">Amount</param>- /// <returns>Converted value</returns>- public virtual int ConvertAmountToLoyaltyPoints(double amount)- {- var result = 0;- if (amount <= 0)- return 0;+ return await Task.FromResult(result);+ }- if (_loyaltyPointsSettings.ExchangeRate > 0)- result = (int)Math.Ceiling(amount / _loyaltyPointsSettings.ExchangeRate);- return result;- }+ /// <summary>+ /// Converts an amount to loyalty points+ /// </summary>+ /// <param name="amount">Amount</param>+ /// <returns>Converted value</returns>+ public virtual int ConvertAmountToLoyaltyPoints(double amount)+ {+ var result = 0;+ if (amount <= 0)+ return 0;- /// <summary>- /// Gets a value indicating whether a customer has minimum amount of loyalty points to use (if enabled)- /// </summary>- /// <param name="loyaltyPoints">Loyalty points to check</param>- /// <returns>true - loyalty points could use; false - cannot be used.</returns>- public virtual bool CheckMinimumLoyaltyPointsToUseRequirement(int loyaltyPoints)- {- if (_loyaltyPointsSettings.MinimumLoyaltyPointsToUse <= 0)- return true;+ if (_loyaltyPointsSettings.ExchangeRate > 0)+ result = (int)Math.Ceiling(amount / _loyaltyPointsSettings.ExchangeRate);+ return result;+ }- return loyaltyPoints >= _loyaltyPointsSettings.MinimumLoyaltyPointsToUse;- }+ /// <summary>+ /// Gets a value indicating whether a customer has minimum amount of loyalty points to use (if enabled)+ /// </summary>+ /// <param name="loyaltyPoints">Loyalty points to check</param>+ /// <returns>true - loyalty points could use; false - cannot be used.</returns>+ public virtual bool CheckMinimumLoyaltyPointsToUseRequirement(int loyaltyPoints)+ {+ if (_loyaltyPointsSettings.MinimumLoyaltyPointsToUse <= 0)+ return true;- #endregion+ return loyaltyPoints >= _loyaltyPointsSettings.MinimumLoyaltyPointsToUse;}++ #endregion}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.csindex 4d972ea61..dcd664828 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs@@ -1,320 +1,327 @@using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Orders;using Grand.Domain.Payments;using Grand.Domain.Shipping;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++/// <summary>+/// Order service+/// </summary>+public class OrderService : IOrderService{+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ /// <param name="orderRepository">Order repository</param>+ /// <param name="orderNoteRepository">Order note repository</param>+ /// <param name="mediator">Mediator</param>+ public OrderService(IRepository<Order> orderRepository,+ IRepository<OrderNote> orderNoteRepository,+ IMediator mediator+ )+ {+ _orderRepository = orderRepository;+ _orderNoteRepository = orderNoteRepository;+ _mediator = mediator;+ }++ #endregion++ #region Fields++ private readonly IRepository<Order> _orderRepository;+ private readonly IRepository<OrderNote> _orderNoteRepository;+ private readonly IMediator _mediator;++ #endregion++ #region Methods++ #region Orders++ /// <summary>+ /// Gets an order+ /// </summary>+ /// <param name="orderId">The order identifier</param>+ /// <returns>Order</returns>+ public virtual Task<Order> GetOrderById(string orderId)+ {+ return _orderRepository.GetByIdAsync(orderId);+ }+++ /// <summary>+ /// Gets an order+ /// </summary>+ /// <param name="orderItemId">The order item identifier</param>+ /// <returns>Order</returns>+ public virtual Task<Order> GetOrderByOrderItemId(string orderItemId)+ {+ var query = from o in _orderRepository.Table+ where o.OrderItems.Any(x => x.Id == orderItemId)+ select o;++ return Task.FromResult(query.FirstOrDefault());+ }+/// <summary>- /// Order service+ /// Gets an order/// </summary>- public class OrderService : IOrderService+ /// <param name="orderNumber">The order number</param>+ /// <returns>Order</returns>+ public virtual Task<Order> GetOrderByNumber(int orderNumber){- #region Fields-- private readonly IRepository<Order> _orderRepository;- private readonly IRepository<OrderNote> _orderNoteRepository;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="orderRepository">Order repository</param>- /// <param name="orderNoteRepository">Order note repository</param>- /// <param name="mediator">Mediator</param>- public OrderService(IRepository<Order> orderRepository,- IRepository<OrderNote> orderNoteRepository,- IMediator mediator- )- {- _orderRepository = orderRepository;- _orderNoteRepository = orderNoteRepository;- _mediator = mediator;- }-- #endregion-- #region Methods-- #region Orders-- /// <summary>- /// Gets an order- /// </summary>- /// <param name="orderId">The order identifier</param>- /// <returns>Order</returns>- public virtual Task<Order> GetOrderById(string orderId)- {- return _orderRepository.GetByIdAsync(orderId);- }--- /// <summary>- /// Gets an order- /// </summary>- /// <param name="orderItemId">The order item identifier</param>- /// <returns>Order</returns>- public virtual Task<Order> GetOrderByOrderItemId(string orderItemId)- {- var query = from o in _orderRepository.Table- where o.OrderItems.Any(x => x.Id == orderItemId)- select o;-- return Task.FromResult(query.FirstOrDefault());- }- /// <summary>- /// Gets an order- /// </summary>- /// <param name="orderNumber">The order number</param>- /// <returns>Order</returns>- public virtual Task<Order> GetOrderByNumber(int orderNumber)- {- return Task.FromResult(_orderRepository.Table.FirstOrDefault(x => x.OrderNumber == orderNumber));- }-- /// <summary>- /// Gets orders by code- /// </summary>- /// <param name="code">The order code</param>- /// <returns>Order</returns>- public virtual async Task<IList<Order>> GetOrdersByCode(string code)- {- if (string.IsNullOrEmpty(code))- return new List<Order>();-- return await Task.FromResult(_orderRepository.Table.Where(x => x.Code == code.ToUpperInvariant()).ToList());- }--- /// <summary>- /// Get orders by identifiers- /// </summary>- /// <param name="orderIds">Order identifiers</param>- /// <returns>Order</returns>- public virtual async Task<IList<Order>> GetOrdersByIds(string[] orderIds)- {- if (orderIds == null || orderIds.Length == 0)- return new List<Order>();-- var query = from o in _orderRepository.Table- where orderIds.Contains(o.Id)- select o;- var orders = await Task.FromResult(query.ToList());- //sort by passed identifiers- return orderIds.Select(id => orders.Find(x => x.Id == id)).Where(order => order != null).ToList();- }-- /// <summary>- /// Gets an order- /// </summary>- /// <param name="orderGuid">The order identifier</param>- /// <returns>Order</returns>- public virtual Task<Order> GetOrderByGuid(Guid orderGuid)- {- var query = from o in _orderRepository.Table- where o.OrderGuid == orderGuid- select o;- return Task.FromResult(query.FirstOrDefault());- }-- /// <summary>- /// Search orders- /// </summary>- /// <param name="storeId">Store identifier; 0 to load all orders</param>- /// <param name="vendorId">Vendor identifier; null to load all orders</param>- /// <param name="customerId">Customer identifier; 0 to load all orders</param>- /// <param name="productId">Product identifier which was purchased in an order; 0 to load all orders</param>- /// <param name="affiliateId">Affiliate identifier; 0 to load all orders</param>- /// <param name="warehouseId">Warehouse identifier, only orders with products from a specified warehouse will be loaded; 0 to load all orders</param>- /// <param name="billingCountryId">Billing country identifier; 0 to load all orders</param>- /// <param name="ownerId">Owner identifier</param>- /// <param name="salesEmployeeId">Sales employee identifier</param>- /// <param name="paymentMethodSystemName">Payment method system name; null to load all records</param>- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>- /// <param name="os">Order status; null to load all orders</param>- /// <param name="ps">Order payment status; null to load all orders</param>- /// <param name="ss">Order shipment status; null to load all orders</param>- /// <param name="billingEmail">Billing email. Leave empty to load all records.</param>- /// <param name="billingLastName"></param>- /// <param name="orderGuid">Search by order GUID (Global unique identifier) or part of GUID. Leave empty to load all orders.</param>- /// <param name="orderCode"></param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <param name="orderTagId">Order tag identifier</param>- /// <returns>Orders</returns>- public virtual async Task<IPagedList<Order>> SearchOrders(string storeId = "",- string vendorId = "", string customerId = "",- string productId = "", string affiliateId = "", string warehouseId = "",- string billingCountryId = "", string ownerId = "", string salesEmployeeId = "", string paymentMethodSystemName = null,- DateTime? createdFromUtc = null, DateTime? createdToUtc = null,- int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,- string billingEmail = null, string billingLastName = "", string orderGuid = null,- string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "")- {- var queryModel = new GetOrderQuery- {- AffiliateId = affiliateId,- BillingCountryId = billingCountryId,- BillingEmail = billingEmail,- BillingLastName = billingLastName,- CreatedFromUtc = createdFromUtc,- CreatedToUtc = createdToUtc,- CustomerId = customerId,- OrderGuid = orderGuid,- OrderCode = orderCode,- Os = os,- PageIndex = pageIndex,- PageSize = pageSize,- PaymentMethodSystemName = paymentMethodSystemName,- ProductId = productId,- Ps = ps,- Ss = ss,- StoreId = storeId,- VendorId = vendorId,- WarehouseId = warehouseId,- OrderTagId = orderTagId,- OwnerId = ownerId,- SalesEmployeeId = salesEmployeeId- };- var query = await _mediator.Send(queryModel);- return await PagedList<Order>.Create(query, pageIndex, pageSize);- }-- /// <summary>- /// Inserts an order- /// </summary>- /// <param name="order">Order</param>- public virtual async Task InsertOrder(Order order)- {- ArgumentNullException.ThrowIfNull(order);-- var orderExists = _orderRepository.Table.OrderByDescending(x => x.OrderNumber).Select(x => x.OrderNumber).FirstOrDefault();- order.OrderNumber = orderExists != 0 ? orderExists + 1 : 1;-- await _orderRepository.InsertAsync(order);-- //event notification- await _mediator.EntityInserted(order);- }-- /// <summary>- /// Updates the order- /// </summary>- /// <param name="order">The order</param>- public virtual async Task UpdateOrder(Order order)- {- ArgumentNullException.ThrowIfNull(order);-- await _orderRepository.UpdateAsync(order);-- //event notification- await _mediator.EntityUpdated(order);- }-- /// <summary>- /// Cancel UnPaid Orders and has pending status- /// </summary>- /// <param name="expirationDateUtc">Date at which all unPaid orders and has pending status Would be Canceled</param>- public async Task CancelExpiredOrders(DateTime expirationDateUtc)- {- var orders = _orderRepository.Table- .Where(o => o.CreatedOnUtc < expirationDateUtc && o.PaymentStatusId == PaymentStatus.Pending &&- o.OrderStatusId == (int)OrderStatusSystem.Pending && (o.ShippingStatusId == ShippingStatus.Pending- || o.ShippingStatusId == ShippingStatus.ShippingNotRequired))- .ToList();-- foreach (var order in orders)- await _mediator.Send(new CancelOrderCommand { Order = order, NotifyCustomer = true });- }-- #endregion-- #region Orders items-- /// <summary>- /// Gets an item- /// </summary>- /// <param name="orderItemGuid">Order identifier</param>- /// <returns>Order item</returns>- public virtual Task<OrderItem> GetOrderItemByGuid(Guid orderItemGuid)- {- var query = from order in _orderRepository.Table- from orderItem in order.OrderItems- select orderItem;-- query = from orderItem in query- where orderItem.OrderItemGuid == orderItemGuid- select orderItem;-- return Task.FromResult(query.FirstOrDefault());- }-- #endregion-- #region Orders notes-- /// <summary>- /// Deletes an order note- /// </summary>- /// <param name="orderNote">The order note</param>- public virtual async Task DeleteOrderNote(OrderNote orderNote)- {- ArgumentNullException.ThrowIfNull(orderNote);-- await _orderNoteRepository.DeleteAsync(orderNote);-- //event notification- await _mediator.EntityDeleted(orderNote);- }-- /// <summary>- /// Deletes an order note- /// </summary>- /// <param name="orderNote">The order note</param>- public virtual async Task InsertOrderNote(OrderNote orderNote)- {- ArgumentNullException.ThrowIfNull(orderNote);-- await _orderNoteRepository.InsertAsync(orderNote);-- //event notification- await _mediator.EntityInserted(orderNote);- }-- public virtual async Task<IList<OrderNote>> GetOrderNotes(string orderId)- {- var query = from orderNote in _orderNoteRepository.Table- where orderNote.OrderId == orderId- orderby orderNote.CreatedOnUtc descending- select orderNote;-- return await Task.FromResult(query.ToList());- }-- /// <summary>- /// Get order note by id- /// </summary>- /// <param name="orderNoteId">Order note identifier</param>- /// <returns>OrderNote</returns>- public virtual Task<OrderNote> GetOrderNote(string orderNoteId)- {- return Task.FromResult(_orderNoteRepository.Table.FirstOrDefault(x => x.Id == orderNoteId));- }--- #endregion-- #endregion+ return Task.FromResult(_orderRepository.Table.FirstOrDefault(x => x.OrderNumber == orderNumber));}-}++ /// <summary>+ /// Gets orders by code+ /// </summary>+ /// <param name="code">The order code</param>+ /// <returns>Order</returns>+ public virtual async Task<IList<Order>> GetOrdersByCode(string code)+ {+ if (string.IsNullOrEmpty(code))+ return new List<Order>();++ return await Task.FromResult(_orderRepository.Table.Where(x => x.Code == code.ToUpperInvariant()).ToList());+ }+++ /// <summary>+ /// Get orders by identifiers+ /// </summary>+ /// <param name="orderIds">Order identifiers</param>+ /// <returns>Order</returns>+ public virtual async Task<IList<Order>> GetOrdersByIds(string[] orderIds)+ {+ if (orderIds == null || orderIds.Length == 0)+ return new List<Order>();++ var query = from o in _orderRepository.Table+ where orderIds.Contains(o.Id)+ select o;+ var orders = await Task.FromResult(query.ToList());+ //sort by passed identifiers+ return orderIds.Select(id => orders.Find(x => x.Id == id)).Where(order => order != null).ToList();+ }++ /// <summary>+ /// Gets an order+ /// </summary>+ /// <param name="orderGuid">The order identifier</param>+ /// <returns>Order</returns>+ public virtual Task<Order> GetOrderByGuid(Guid orderGuid)+ {+ var query = from o in _orderRepository.Table+ where o.OrderGuid == orderGuid+ select o;+ return Task.FromResult(query.FirstOrDefault());+ }++ /// <summary>+ /// Search orders+ /// </summary>+ /// <param name="storeId">Store identifier; 0 to load all orders</param>+ /// <param name="vendorId">Vendor identifier; null to load all orders</param>+ /// <param name="customerId">Customer identifier; 0 to load all orders</param>+ /// <param name="productId">Product identifier which was purchased in an order; 0 to load all orders</param>+ /// <param name="affiliateId">Affiliate identifier; 0 to load all orders</param>+ /// <param name="warehouseId">+ /// Warehouse identifier, only orders with products from a specified warehouse will be loaded; 0+ /// to load all orders+ /// </param>+ /// <param name="billingCountryId">Billing country identifier; 0 to load all orders</param>+ /// <param name="ownerId">Owner identifier</param>+ /// <param name="salesEmployeeId">Sales employee identifier</param>+ /// <param name="paymentMethodSystemName">Payment method system name; null to load all records</param>+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>+ /// <param name="os">Order status; null to load all orders</param>+ /// <param name="ps">Order payment status; null to load all orders</param>+ /// <param name="ss">Order shipment status; null to load all orders</param>+ /// <param name="billingEmail">Billing email. Leave empty to load all records.</param>+ /// <param name="billingLastName"></param>+ /// <param name="orderGuid">+ /// Search by order GUID (Global unique identifier) or part of GUID. Leave empty to load all+ /// orders.+ /// </param>+ /// <param name="orderCode"></param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <param name="orderTagId">Order tag identifier</param>+ /// <returns>Orders</returns>+ public virtual async Task<IPagedList<Order>> SearchOrders(string storeId = "",+ string vendorId = "", string customerId = "",+ string productId = "", string affiliateId = "", string warehouseId = "",+ string billingCountryId = "", string ownerId = "", string salesEmployeeId = "",+ string paymentMethodSystemName = null,+ DateTime? createdFromUtc = null, DateTime? createdToUtc = null,+ int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,+ string billingEmail = null, string billingLastName = "", string orderGuid = null,+ string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "")+ {+ var queryModel = new GetOrderQuery {+ AffiliateId = affiliateId,+ BillingCountryId = billingCountryId,+ BillingEmail = billingEmail,+ BillingLastName = billingLastName,+ CreatedFromUtc = createdFromUtc,+ CreatedToUtc = createdToUtc,+ CustomerId = customerId,+ OrderGuid = orderGuid,+ OrderCode = orderCode,+ Os = os,+ PageIndex = pageIndex,+ PageSize = pageSize,+ PaymentMethodSystemName = paymentMethodSystemName,+ ProductId = productId,+ Ps = ps,+ Ss = ss,+ StoreId = storeId,+ VendorId = vendorId,+ WarehouseId = warehouseId,+ OrderTagId = orderTagId,+ OwnerId = ownerId,+ SalesEmployeeId = salesEmployeeId+ };+ var query = await _mediator.Send(queryModel);+ return await PagedList<Order>.Create(query, pageIndex, pageSize);+ }++ /// <summary>+ /// Inserts an order+ /// </summary>+ /// <param name="order">Order</param>+ public virtual async Task InsertOrder(Order order)+ {+ ArgumentNullException.ThrowIfNull(order);++ var orderExists = _orderRepository.Table.OrderByDescending(x => x.OrderNumber).Select(x => x.OrderNumber)+ .FirstOrDefault();+ order.OrderNumber = orderExists != 0 ? orderExists + 1 : 1;++ await _orderRepository.InsertAsync(order);++ //event notification+ await _mediator.EntityInserted(order);+ }++ /// <summary>+ /// Updates the order+ /// </summary>+ /// <param name="order">The order</param>+ public virtual async Task UpdateOrder(Order order)+ {+ ArgumentNullException.ThrowIfNull(order);++ await _orderRepository.UpdateAsync(order);++ //event notification+ await _mediator.EntityUpdated(order);+ }++ /// <summary>+ /// Cancel UnPaid Orders and has pending status+ /// </summary>+ /// <param name="expirationDateUtc">Date at which all unPaid orders and has pending status Would be Canceled</param>+ public async Task CancelExpiredOrders(DateTime expirationDateUtc)+ {+ var orders = _orderRepository.Table+ .Where(o => o.CreatedOnUtc < expirationDateUtc && o.PaymentStatusId == PaymentStatus.Pending &&+ o.OrderStatusId == (int)OrderStatusSystem.Pending &&+ (o.ShippingStatusId == ShippingStatus.Pending+ || o.ShippingStatusId == ShippingStatus.ShippingNotRequired))+ .ToList();++ foreach (var order in orders)+ await _mediator.Send(new CancelOrderCommand { Order = order, NotifyCustomer = true });+ }++ #endregion++ #region Orders items++ /// <summary>+ /// Gets an item+ /// </summary>+ /// <param name="orderItemGuid">Order identifier</param>+ /// <returns>Order item</returns>+ public virtual Task<OrderItem> GetOrderItemByGuid(Guid orderItemGuid)+ {+ var query = from order in _orderRepository.Table+ from orderItem in order.OrderItems+ select orderItem;++ query = from orderItem in query+ where orderItem.OrderItemGuid == orderItemGuid+ select orderItem;++ return Task.FromResult(query.FirstOrDefault());+ }++ #endregion++ #region Orders notes++ /// <summary>+ /// Deletes an order note+ /// </summary>+ /// <param name="orderNote">The order note</param>+ public virtual async Task DeleteOrderNote(OrderNote orderNote)+ {+ ArgumentNullException.ThrowIfNull(orderNote);++ await _orderNoteRepository.DeleteAsync(orderNote);++ //event notification+ await _mediator.EntityDeleted(orderNote);+ }++ /// <summary>+ /// Deletes an order note+ /// </summary>+ /// <param name="orderNote">The order note</param>+ public virtual async Task InsertOrderNote(OrderNote orderNote)+ {+ ArgumentNullException.ThrowIfNull(orderNote);++ await _orderNoteRepository.InsertAsync(orderNote);++ //event notification+ await _mediator.EntityInserted(orderNote);+ }++ public virtual async Task<IList<OrderNote>> GetOrderNotes(string orderId)+ {+ var query = from orderNote in _orderNoteRepository.Table+ where orderNote.OrderId == orderId+ orderby orderNote.CreatedOnUtc descending+ select orderNote;++ return await Task.FromResult(query.ToList());+ }++ /// <summary>+ /// Get order note by id+ /// </summary>+ /// <param name="orderNoteId">Order note identifier</param>+ /// <returns>OrderNote</returns>+ public virtual Task<OrderNote> GetOrderNote(string orderNoteId)+ {+ return Task.FromResult(_orderNoteRepository.Table.FirstOrDefault(x => x.Id == orderNoteId));+ }++ #endregion++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.csindex 179bdc1b9..7e2ce57e1 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs@@ -6,88 +6,89 @@ using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++public class OrderStatusService : IOrderStatusService{- public class OrderStatusService : IOrderStatusService+ private readonly ICacheBase _cacheBase;+ private readonly IMediator _mediator;+ private readonly IRepository<OrderStatus> _orderStatusRepository;++ public OrderStatusService(+ IRepository<OrderStatus> orderStatusRepository,+ ICacheBase cacheBase,+ IMediator mediator){- private readonly IRepository<OrderStatus> _orderStatusRepository;- private readonly ICacheBase _cacheBase;- private readonly IMediator _mediator;-- public OrderStatusService(- IRepository<OrderStatus> orderStatusRepository,- ICacheBase cacheBase,- IMediator mediator)- {- _orderStatusRepository = orderStatusRepository;- _cacheBase = cacheBase;- _mediator = mediator;- }+ _orderStatusRepository = orderStatusRepository;+ _cacheBase = cacheBase;+ _mediator = mediator;+ }- public virtual async Task<IList<OrderStatus>> GetAll()- {- var orderStatuses = await _cacheBase.GetAsync(CacheKey.ORDER_STATUS_ALL, async () =>- {- var query = from p in _orderStatusRepository.Table- select p;-- query = query.OrderBy(l => l.DisplayOrder);- return await Task.FromResult(query.ToList());- });-- return orderStatuses;- }- public virtual async Task<OrderStatus> GetById(string id)- {- return (await GetAll()).FirstOrDefault(x => x.Id == id);- }- public virtual async Task<OrderStatus> GetByStatusId(int statusId)+ public virtual async Task<IList<OrderStatus>> GetAll()+ {+ var orderStatuses = await _cacheBase.GetAsync(CacheKey.ORDER_STATUS_ALL, async () =>{- return (await GetAll()).FirstOrDefault(x => x.StatusId == statusId);- }+ var query = from p in _orderStatusRepository.Table+ select p;- public virtual async Task Insert(OrderStatus orderStatus)- {- ArgumentNullException.ThrowIfNull(orderStatus);+ query = query.OrderBy(l => l.DisplayOrder);+ return await Task.FromResult(query.ToList());+ });- //insert order status- await _orderStatusRepository.InsertAsync(orderStatus);+ return orderStatuses;+ }- //cache- await _cacheBase.RemoveByPrefix(CacheKey.ORDER_STATUS_ALL);+ public virtual async Task<OrderStatus> GetById(string id)+ {+ return (await GetAll()).FirstOrDefault(x => x.Id == id);+ }- //event notification- await _mediator.EntityInserted(orderStatus);- }+ public virtual async Task<OrderStatus> GetByStatusId(int statusId)+ {+ return (await GetAll()).FirstOrDefault(x => x.StatusId == statusId);+ }- public virtual async Task Update(OrderStatus orderStatus)- {- ArgumentNullException.ThrowIfNull(orderStatus);+ public virtual async Task Insert(OrderStatus orderStatus)+ {+ ArgumentNullException.ThrowIfNull(orderStatus);- //update order status- await _orderStatusRepository.UpdateAsync(orderStatus);+ //insert order status+ await _orderStatusRepository.InsertAsync(orderStatus);- //cache- await _cacheBase.RemoveByPrefix(CacheKey.ORDER_STATUS_ALL);+ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.ORDER_STATUS_ALL);- //event notification- await _mediator.EntityUpdated(orderStatus);- }- public virtual async Task Delete(OrderStatus orderStatus)- {- ArgumentNullException.ThrowIfNull(orderStatus);+ //event notification+ await _mediator.EntityInserted(orderStatus);+ }++ public virtual async Task Update(OrderStatus orderStatus)+ {+ ArgumentNullException.ThrowIfNull(orderStatus);- if (orderStatus.IsSystem)- throw new Exception("You can't delete system status");+ //update order status+ await _orderStatusRepository.UpdateAsync(orderStatus);++ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.ORDER_STATUS_ALL);++ //event notification+ await _mediator.EntityUpdated(orderStatus);+ }++ public virtual async Task Delete(OrderStatus orderStatus)+ {+ ArgumentNullException.ThrowIfNull(orderStatus);- await _orderStatusRepository.DeleteAsync(orderStatus);+ if (orderStatus.IsSystem)+ throw new Exception("You can't delete system status");- //cache- await _cacheBase.RemoveByPrefix(CacheKey.ORDER_STATUS_ALL);+ await _orderStatusRepository.DeleteAsync(orderStatus);- //event notification- await _mediator.EntityDeleted(orderStatus);- }+ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.ORDER_STATUS_ALL);+ //event notification+ await _mediator.EntityDeleted(orderStatus);}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.csindex efa5d2051..92b44dd46 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs@@ -1,201 +1,199 @@using Grand.Business.Core.Interfaces.Checkout.Orders;+using Grand.Data;+using Grand.Domain.Orders;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Data;-using Grand.Domain.Orders;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++public class OrderTagService : IOrderTagService{- public class OrderTagService : IOrderTagService+ #region Ctor++ public OrderTagService(IRepository<OrderTag> orderTagRepository,+ IRepository<Order> orderRepository,+ ICacheBase cacheBase,+ IMediator mediator+ ){+ _orderTagRepository = orderTagRepository;+ _orderRepository = orderRepository;+ _mediator = mediator;+ _cacheBase = cacheBase;+ }- #region Fields+ #endregion- private readonly IRepository<OrderTag> _orderTagRepository;- private readonly IRepository<Order> _orderRepository;- private readonly ICacheBase _cacheBase;- private readonly IMediator _mediator;+ #region Utilities- #endregion+ /// <summary>+ /// Get order's count for each of existing order tag+ /// </summary>+ /// <param name="orderTagId">Order tag identifier</param>+ /// <returns>Dictionary of "order's tag ID : order's count"</returns>+ private async Task<Dictionary<string, int>> GetOrderCount(string orderTagId)+ {+ var key = string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId);+ return await _cacheBase.GetAsync(key, async () =>+ {+ var query = from ot in _orderTagRepository.Table+ select ot;- #region Ctor+ var dictionary = query.ToList().ToDictionary(tag => tag.Id, tag => tag.Count);+ return await Task.FromResult(dictionary);+ });+ }- public OrderTagService(IRepository<OrderTag> orderTagRepository,- IRepository<Order> orderRepository,- ICacheBase cacheBase,- IMediator mediator- )- {- _orderTagRepository = orderTagRepository;- _orderRepository = orderRepository;- _mediator = mediator;- _cacheBase = cacheBase;- }-- #endregion-- #region Utilities-- /// <summary>- /// Get order's count for each of existing order tag- /// </summary>- /// <param name="orderTagId">Order tag identifier</param>- /// <returns>Dictionary of "order's tag ID : order's count"</returns>- private async Task<Dictionary<string, int>> GetOrderCount(string orderTagId)- {- var key = string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId);- return await _cacheBase.GetAsync(key, async () =>- {- var query = from ot in _orderTagRepository.Table- select ot;-- var dictionary = query.ToList().ToDictionary(tag => tag.Id, tag => tag.Count);- return await Task.FromResult(dictionary);- });- }-- #endregion-- #region Methods--- /// <summary>- /// Gets all order tags- /// </summary>- /// <returns>Order tags</returns>- public virtual async Task<IList<OrderTag>> GetAllOrderTags()- {- return await Task.FromResult(_orderTagRepository.Table.ToList());- }-- /// <summary>- /// Gets order's tag by id- /// </summary>- /// <param name="orderTagId">Order's tag identifier</param>- /// <returns>Order's tag</returns>- public virtual Task<OrderTag> GetOrderTagById(string orderTagId)- {- return _orderTagRepository.GetByIdAsync(orderTagId);- }-- /// <summary>- /// Gets order's tag by name- /// </summary>- /// <param name="name">Order's tag name</param>- /// <returns>Order's tag</returns>- public virtual Task<OrderTag> GetOrderTagByName(string name)- {- return _orderTagRepository.GetOneAsync(x=>x.Name == name);- }-- /// <summary>- /// Inserts a order's tag- /// </summary>- /// <param name="orderTag">Order's tag</param>- public virtual async Task InsertOrderTag(OrderTag orderTag)- {- ArgumentNullException.ThrowIfNull(orderTag);+ #endregion- await _orderTagRepository.InsertAsync(orderTag);+ #region Fields- //cache- await _cacheBase.RemoveByPrefix(CacheKey.ORDERTAG_PATTERN_KEY);+ private readonly IRepository<OrderTag> _orderTagRepository;+ private readonly IRepository<Order> _orderRepository;+ private readonly ICacheBase _cacheBase;+ private readonly IMediator _mediator;- //event notification- await _mediator.EntityInserted(orderTag);- }+ #endregion- /// <summary>- /// Updating a order's tag- /// </summary>- /// <param name="orderTag">Order tag</param>- public virtual async Task UpdateOrderTag(OrderTag orderTag)- {- ArgumentNullException.ThrowIfNull(orderTag);+ #region Methods- await _orderTagRepository.UpdateAsync(orderTag);+ /// <summary>+ /// Gets all order tags+ /// </summary>+ /// <returns>Order tags</returns>+ public virtual async Task<IList<OrderTag>> GetAllOrderTags()+ {+ return await Task.FromResult(_orderTagRepository.Table.ToList());+ }- //cache- await _cacheBase.RemoveByPrefix(CacheKey.ORDERTAG_PATTERN_KEY);+ /// <summary>+ /// Gets order's tag by id+ /// </summary>+ /// <param name="orderTagId">Order's tag identifier</param>+ /// <returns>Order's tag</returns>+ public virtual Task<OrderTag> GetOrderTagById(string orderTagId)+ {+ return _orderTagRepository.GetByIdAsync(orderTagId);+ }- //event notification- await _mediator.EntityUpdated(orderTag);- }- /// <summary>- /// Delete an order's tag- /// </summary>- /// <param name="orderTag">Order's tag</param>- public virtual async Task DeleteOrderTag(OrderTag orderTag)- {- ArgumentNullException.ThrowIfNull(orderTag);+ /// <summary>+ /// Gets order's tag by name+ /// </summary>+ /// <param name="name">Order's tag name</param>+ /// <returns>Order's tag</returns>+ public virtual Task<OrderTag> GetOrderTagByName(string name)+ {+ return _orderTagRepository.GetOneAsync(x => x.Name == name);+ }- //update orders- await _orderRepository.Pull(string.Empty, x => x.OrderTags, orderTag.Id);+ /// <summary>+ /// Inserts a order's tag+ /// </summary>+ /// <param name="orderTag">Order's tag</param>+ public virtual async Task InsertOrderTag(OrderTag orderTag)+ {+ ArgumentNullException.ThrowIfNull(orderTag);- //delete tag- await _orderTagRepository.DeleteAsync(orderTag);+ await _orderTagRepository.InsertAsync(orderTag);- //cache- await _cacheBase.RemoveByPrefix(CacheKey.ORDERTAG_PATTERN_KEY);- await _cacheBase.RemoveByPrefix(CacheKey.ORDERS_PATTERN_KEY);+ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.ORDERTAG_PATTERN_KEY);- //event notification- await _mediator.EntityDeleted(orderTag);- }+ //event notification+ await _mediator.EntityInserted(orderTag);+ }- /// <summary>- /// Attach a tag to the order- /// </summary>- /// <param name="orderTagId">Order tag ident</param>- /// <param name="orderId">Order's identification</param>- public virtual async Task AttachOrderTag(string orderTagId, string orderId)- {- //assign to product- await _orderRepository.AddToSet(orderId, x => x.OrderTags, orderTagId);-- var orderTag = await GetOrderTagById(orderTagId);- //update product tag- await _orderTagRepository.UpdateField(orderTagId, x => x.Count, orderTag.Count + 1);-- //cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERS_BY_ID_KEY, orderId));- await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId));-- //event notification- await _mediator.EntityUpdated(orderTag);- }-- /// <summary>- /// Detach a tag from the order- /// </summary>- /// <param name="orderTagId">Order Tag ident</param>- /// <param name="orderId">Order ident</param>- public virtual async Task DetachOrderTag(string orderTagId, string orderId)- {- await _orderRepository.Pull(orderId, x => x.OrderTags, orderTagId);-- var orderTag = await GetOrderTagById(orderTagId);- //update product tag- await _orderTagRepository.UpdateField(orderTagId, x => x.Count, orderTag.Count - 1);-- //cache- await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERS_BY_ID_KEY, orderId));- await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId));- }-- /// <summary>- /// Get number of orders- /// </summary>- /// <param name="orderTagId">Order's tag identifier</param>- /// <returns>Number of orders</returns>- public virtual async Task<int> GetOrderCount(string orderTagId, string storeId)- {- var dictionary = await GetOrderCount(orderTagId);- return dictionary.ContainsKey(orderTagId) ? dictionary[orderTagId] : 0;- }+ /// <summary>+ /// Updating a order's tag+ /// </summary>+ /// <param name="orderTag">Order tag</param>+ public virtual async Task UpdateOrderTag(OrderTag orderTag)+ {+ ArgumentNullException.ThrowIfNull(orderTag);++ await _orderTagRepository.UpdateAsync(orderTag);++ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.ORDERTAG_PATTERN_KEY);++ //event notification+ await _mediator.EntityUpdated(orderTag);+ }- #endregion+ /// <summary>+ /// Delete an order's tag+ /// </summary>+ /// <param name="orderTag">Order's tag</param>+ public virtual async Task DeleteOrderTag(OrderTag orderTag)+ {+ ArgumentNullException.ThrowIfNull(orderTag);++ //update orders+ await _orderRepository.Pull(string.Empty, x => x.OrderTags, orderTag.Id);++ //delete tag+ await _orderTagRepository.DeleteAsync(orderTag);++ //cache+ await _cacheBase.RemoveByPrefix(CacheKey.ORDERTAG_PATTERN_KEY);+ await _cacheBase.RemoveByPrefix(CacheKey.ORDERS_PATTERN_KEY);++ //event notification+ await _mediator.EntityDeleted(orderTag);}-}++ /// <summary>+ /// Attach a tag to the order+ /// </summary>+ /// <param name="orderTagId">Order tag ident</param>+ /// <param name="orderId">Order's identification</param>+ public virtual async Task AttachOrderTag(string orderTagId, string orderId)+ {+ //assign to product+ await _orderRepository.AddToSet(orderId, x => x.OrderTags, orderTagId);++ var orderTag = await GetOrderTagById(orderTagId);+ //update product tag+ await _orderTagRepository.UpdateField(orderTagId, x => x.Count, orderTag.Count + 1);++ //cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERS_BY_ID_KEY, orderId));+ await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId));++ //event notification+ await _mediator.EntityUpdated(orderTag);+ }++ /// <summary>+ /// Detach a tag from the order+ /// </summary>+ /// <param name="orderTagId">Order Tag ident</param>+ /// <param name="orderId">Order ident</param>+ public virtual async Task DetachOrderTag(string orderTagId, string orderId)+ {+ await _orderRepository.Pull(orderId, x => x.OrderTags, orderTagId);++ var orderTag = await GetOrderTagById(orderTagId);+ //update product tag+ await _orderTagRepository.UpdateField(orderTagId, x => x.Count, orderTag.Count - 1);++ //cache+ await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERS_BY_ID_KEY, orderId));+ await _cacheBase.RemoveAsync(string.Format(CacheKey.ORDERTAG_COUNT_KEY, orderTagId));+ }++ /// <summary>+ /// Get number of orders+ /// </summary>+ /// <param name="orderTagId">Order's tag identifier</param>+ /// <returns>Number of orders</returns>+ public virtual async Task<int> GetOrderCount(string orderTagId, string storeId)+ {+ var dictionary = await GetOrderCount(orderTagId);+ return dictionary.ContainsKey(orderTagId) ? dictionary[orderTagId] : 0;+ }++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.csindex 9fe05f01e..59e3106c7 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs@@ -14,430 +14,438 @@ using Grand.Infrastructure;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++/// <summary>+/// Shopping cart service+/// </summary>+public class ShoppingCartService : IShoppingCartService{- /// <summary>- /// Shopping cart service- /// </summary>- public class ShoppingCartService : IShoppingCartService+ #region Ctor++ public ShoppingCartService(+ IWorkContext workContext,+ IProductService productService,+ ICustomerService customerService,+ IMediator mediator,+ IUserFieldService userFieldService,+ IShoppingCartValidator shoppingCartValidator,+ ShoppingCartSettings shoppingCartSettings){- #region Fields-- private readonly IWorkContext _workContext;- private readonly IProductService _productService;- private readonly ICustomerService _customerService;- private readonly IMediator _mediator;- private readonly IUserFieldService _userFieldService;- private readonly IShoppingCartValidator _shoppingCartValidator;- private readonly ShoppingCartSettings _shoppingCartSettings;-- #endregion-- #region Ctor-- public ShoppingCartService(- IWorkContext workContext,- IProductService productService,- ICustomerService customerService,- IMediator mediator,- IUserFieldService userFieldService,- IShoppingCartValidator shoppingCartValidator,- ShoppingCartSettings shoppingCartSettings)- {- _workContext = workContext;- _productService = productService;- _customerService = customerService;- _mediator = mediator;- _userFieldService = userFieldService;- _shoppingCartValidator = shoppingCartValidator;- _shoppingCartSettings = shoppingCartSettings;- }+ _workContext = workContext;+ _productService = productService;+ _customerService = customerService;+ _mediator = mediator;+ _userFieldService = userFieldService;+ _shoppingCartValidator = shoppingCartValidator;+ _shoppingCartSettings = shoppingCartSettings;+ }- #endregion+ #endregion- #region Methods+ #region Fields- /// <summary>- /// Gets shopping cart- /// </summary>- /// <param name="storeId">Store identifier; pass null to load all records</param>- /// <param name="shoppingCartType">Shopping cart type; pass null to load all records</param>- /// <returns>Shopping Cart</returns>- public virtual async Task<IList<ShoppingCartItem>> GetShoppingCart(string storeId = null, params ShoppingCartType[] shoppingCartType)- {- var model = new List<ShoppingCartItem>();- var cart = _workContext.CurrentCustomer.ShoppingCartItems.ToList();+ private readonly IWorkContext _workContext;+ private readonly IProductService _productService;+ private readonly ICustomerService _customerService;+ private readonly IMediator _mediator;+ private readonly IUserFieldService _userFieldService;+ private readonly IShoppingCartValidator _shoppingCartValidator;+ private readonly ShoppingCartSettings _shoppingCartSettings;- if (!string.IsNullOrEmpty(storeId))- cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId).ToList();+ #endregion- if (shoppingCartType.Length > 0)- cart = cart.Where(sci => shoppingCartType.Contains(sci.ShoppingCartTypeId)).ToList();+ #region Methods- foreach (var item in cart)- {- var product = await _productService.GetProductById(item.ProductId);- if (product == null)- continue;+ /// <summary>+ /// Gets shopping cart+ /// </summary>+ /// <param name="storeId">Store identifier; pass null to load all records</param>+ /// <param name="shoppingCartType">Shopping cart type; pass null to load all records</param>+ /// <returns>Shopping Cart</returns>+ public virtual async Task<IList<ShoppingCartItem>> GetShoppingCart(string storeId = null,+ params ShoppingCartType[] shoppingCartType)+ {+ var model = new List<ShoppingCartItem>();+ var cart = _workContext.CurrentCustomer.ShoppingCartItems.ToList();- model.Add(item);- }- return model;- }+ if (!string.IsNullOrEmpty(storeId))+ cart = cart.LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId).ToList();- /// <summary>- /// Finds a shopping cart item in the cart- /// </summary>- /// <param name="shoppingCart">Shopping cart</param>- /// <param name="shoppingCartType">Shopping cart type</param>- /// <param name="warehouseId"></param>- /// <param name="attributes">Attributes</param>- /// <param name="customerEnteredPrice">Price entered by a customer</param>- /// <param name="rentalStartDate">Rental start date</param>- /// <param name="rentalEndDate">Rental end date</param>- /// <param name="productId"></param>- /// <returns>Found shopping cart item</returns>- public virtual async Task<ShoppingCartItem> FindShoppingCartItem(IList<ShoppingCartItem> shoppingCart,- ShoppingCartType shoppingCartType,- string productId,- string warehouseId = null,- IList<CustomAttribute> attributes = null,- double? customerEnteredPrice = null,- DateTime? rentalStartDate = null,- DateTime? rentalEndDate = null)+ if (shoppingCartType.Length > 0)+ cart = cart.Where(sci => shoppingCartType.Contains(sci.ShoppingCartTypeId)).ToList();++ foreach (var item in cart){- ArgumentNullException.ThrowIfNull(shoppingCart);+ var product = await _productService.GetProductById(item.ProductId);+ if (product == null)+ continue;- foreach (var sci in shoppingCart.Where(a => a.ShoppingCartTypeId == shoppingCartType))- {- if (sci.ProductId != productId || sci.WarehouseId != warehouseId) continue;- //attributes- var product = await _productService.GetProductById(sci.ProductId);- var attributesEqual = ProductExtensions.AreProductAttributesEqual(product, sci.Attributes, attributes, false);- if (product.ProductTypeId == ProductType.BundledProduct)- {- foreach (var bundle in product.BundleProducts)- {- var p1 = await _productService.GetProductById(bundle.ProductId);- if (p1 == null) continue;- if (!ProductExtensions.AreProductAttributesEqual(p1, sci.Attributes, attributes, false))- attributesEqual = false;- }- }- //gift vouchers- var giftVoucherInfoSame = true;- if (product.IsGiftVoucher)- {- GiftVoucherExtensions.GetGiftVoucherAttribute(attributes,- out var giftVoucherRecipientName1, out _,- out var giftVoucherSenderName1, out _, out _);+ model.Add(item);+ }- GiftVoucherExtensions.GetGiftVoucherAttribute(sci.Attributes,- out var giftVoucherRecipientName2, out _,- out var giftVoucherSenderName2, out _, out _);+ return model;+ }- if (!string.Equals(giftVoucherRecipientName1, giftVoucherRecipientName2, StringComparison.InvariantCultureIgnoreCase) ||- !string.Equals(giftVoucherSenderName1, giftVoucherSenderName2, StringComparison.InvariantCultureIgnoreCase))- giftVoucherInfoSame = false;- }+ /// <summary>+ /// Finds a shopping cart item in the cart+ /// </summary>+ /// <param name="shoppingCart">Shopping cart</param>+ /// <param name="shoppingCartType">Shopping cart type</param>+ /// <param name="warehouseId"></param>+ /// <param name="attributes">Attributes</param>+ /// <param name="customerEnteredPrice">Price entered by a customer</param>+ /// <param name="rentalStartDate">Rental start date</param>+ /// <param name="rentalEndDate">Rental end date</param>+ /// <param name="productId"></param>+ /// <returns>Found shopping cart item</returns>+ public virtual async Task<ShoppingCartItem> FindShoppingCartItem(IList<ShoppingCartItem> shoppingCart,+ ShoppingCartType shoppingCartType,+ string productId,+ string warehouseId = null,+ IList<CustomAttribute> attributes = null,+ double? customerEnteredPrice = null,+ DateTime? rentalStartDate = null,+ DateTime? rentalEndDate = null)+ {+ ArgumentNullException.ThrowIfNull(shoppingCart);- //price is the same (for products which require customers to enter a price)- var customerEnteredPricesEqual = true;- if (sci.EnteredPrice.HasValue)- {- if (customerEnteredPrice.HasValue)- customerEnteredPricesEqual = Math.Round(sci.EnteredPrice.Value, 2) == Math.Round(customerEnteredPrice.Value, 2);- else- customerEnteredPricesEqual = false;- }- else+ foreach (var sci in shoppingCart.Where(a => a.ShoppingCartTypeId == shoppingCartType))+ {+ if (sci.ProductId != productId || sci.WarehouseId != warehouseId) continue;+ //attributes+ var product = await _productService.GetProductById(sci.ProductId);+ var attributesEqual =+ ProductExtensions.AreProductAttributesEqual(product, sci.Attributes, attributes, false);+ if (product.ProductTypeId == ProductType.BundledProduct)+ foreach (var bundle in product.BundleProducts){- if (customerEnteredPrice.HasValue)- customerEnteredPricesEqual = false;+ var p1 = await _productService.GetProductById(bundle.ProductId);+ if (p1 == null) continue;+ if (!ProductExtensions.AreProductAttributesEqual(p1, sci.Attributes, attributes, false))+ attributesEqual = false;}- //found?- if (attributesEqual && giftVoucherInfoSame && customerEnteredPricesEqual)- return sci;+ //gift vouchers+ var giftVoucherInfoSame = true;+ if (product.IsGiftVoucher)+ {+ GiftVoucherExtensions.GetGiftVoucherAttribute(attributes,+ out var giftVoucherRecipientName1, out _,+ out var giftVoucherSenderName1, out _, out _);++ GiftVoucherExtensions.GetGiftVoucherAttribute(sci.Attributes,+ out var giftVoucherRecipientName2, out _,+ out var giftVoucherSenderName2, out _, out _);++ if (!string.Equals(giftVoucherRecipientName1, giftVoucherRecipientName2,+ StringComparison.InvariantCultureIgnoreCase) ||+ !string.Equals(giftVoucherSenderName1, giftVoucherSenderName2,+ StringComparison.InvariantCultureIgnoreCase))+ giftVoucherInfoSame = false;}- return null;+ //price is the same (for products which require customers to enter a price)+ var customerEnteredPricesEqual = true;+ if (sci.EnteredPrice.HasValue)+ {+ if (customerEnteredPrice.HasValue)+ customerEnteredPricesEqual = Math.Round(sci.EnteredPrice.Value, 2) ==+ Math.Round(customerEnteredPrice.Value, 2);+ else+ customerEnteredPricesEqual = false;+ }+ else+ {+ if (customerEnteredPrice.HasValue)+ customerEnteredPricesEqual = false;+ }++ //found?+ if (attributesEqual && giftVoucherInfoSame && customerEnteredPricesEqual)+ return sci;}- /// <summary>- /// Add a product to shopping cart- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="productId">Product id</param>- /// <param name="shoppingCartType">ShoppingCartType</param>- /// <param name="storeId">Store id</param>- /// <param name="warehouseId">Warehouse id</param>- /// <param name="attributes">Attributes</param>- /// <param name="customerEnteredPrice">EnteredPrice</param>- /// <param name="rentalStartDate">RentalStartDate</param>- /// <param name="rentalEndDate">RentalEndDate</param>- /// <param name="quantity">Quantity</param>- /// <param name="automaticallyAddRequiredProductsIfEnabled">AutomaticallyAddRequiredProductsIfEnabled</param>- /// <param name="reservationId">ReservationId</param>- /// <param name="parameter">Parameter for reservation</param>- /// <param name="duration">Duration for reservation</param>- /// <param name="validator">ShoppingCartValidatorOptions</param>- /// <returns>(warnings, shoppingCartItem)</returns>- public virtual async Task<(IList<string> warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer, string productId,- ShoppingCartType shoppingCartType, string storeId,- string warehouseId = null, IList<CustomAttribute> attributes = null,- double? customerEnteredPrice = null,- DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,- int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true,- string reservationId = "", string parameter = "", string duration = "",- ShoppingCartValidatorOptions validator = null)- {- ArgumentNullException.ThrowIfNull(customer);+ return null;+ }- validator ??= new ShoppingCartValidatorOptions();+ /// <summary>+ /// Add a product to shopping cart+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="productId">Product id</param>+ /// <param name="shoppingCartType">ShoppingCartType</param>+ /// <param name="storeId">Store id</param>+ /// <param name="warehouseId">Warehouse id</param>+ /// <param name="attributes">Attributes</param>+ /// <param name="customerEnteredPrice">EnteredPrice</param>+ /// <param name="rentalStartDate">RentalStartDate</param>+ /// <param name="rentalEndDate">RentalEndDate</param>+ /// <param name="quantity">Quantity</param>+ /// <param name="automaticallyAddRequiredProductsIfEnabled">AutomaticallyAddRequiredProductsIfEnabled</param>+ /// <param name="reservationId">ReservationId</param>+ /// <param name="parameter">Parameter for reservation</param>+ /// <param name="duration">Duration for reservation</param>+ /// <param name="validator">ShoppingCartValidatorOptions</param>+ /// <returns>(warnings, shoppingCartItem)</returns>+ public virtual async Task<(IList<string> warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer,+ string productId,+ ShoppingCartType shoppingCartType, string storeId,+ string warehouseId = null, IList<CustomAttribute> attributes = null,+ double? customerEnteredPrice = null,+ DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,+ int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true,+ string reservationId = "", string parameter = "", string duration = "",+ ShoppingCartValidatorOptions validator = null)+ {+ ArgumentNullException.ThrowIfNull(customer);++ validator ??= new ShoppingCartValidatorOptions();++ var product = await _productService.GetProductById(productId);+ if (product == null)+ throw new ArgumentNullException(nameof(product));++ var cart = customer.ShoppingCartItems+ .Where(sci => sci.ShoppingCartTypeId == shoppingCartType)+ .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId)+ .ToList();++ var warnings = (await _shoppingCartValidator.CheckCommonWarnings(customer, cart, product, shoppingCartType,+ rentalStartDate,+ rentalEndDate, quantity, reservationId)).ToList();++ if (warnings.Any())+ return (warnings, null);++ var shoppingCartItem = await FindShoppingCartItem(cart,+ shoppingCartType, productId, warehouseId, attributes, customerEnteredPrice,+ rentalStartDate, rentalEndDate);++ var update = shoppingCartItem != null && product.ProductTypeId != ProductType.Reservation+ && string.IsNullOrEmpty(product.AllowedQuantities);++ if (update) shoppingCartItem.Quantity += quantity;+ else+ shoppingCartItem = new ShoppingCartItem {+ ShoppingCartTypeId = shoppingCartType,+ StoreId = storeId,+ WarehouseId = warehouseId,+ ProductId = productId,+ Attributes = attributes,+ EnteredPrice = customerEnteredPrice,+ Quantity = quantity,+ RentalStartDateUtc = rentalStartDate,+ RentalEndDateUtc = rentalEndDate,+ AdditionalShippingChargeProduct = product.AdditionalShippingCharge,+ IsFreeShipping = product.IsFreeShipping,+ IsShipEnabled = product.IsShipEnabled,+ IsTaxExempt = product.IsTaxExempt,+ IsGiftVoucher = product.IsGiftVoucher,+ CreatedOnUtc = DateTime.UtcNow,+ ReservationId = reservationId,+ Parameter = parameter,+ Duration = duration+ };+ warnings.AddRange(+ await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, validator));++ if (warnings.Any()) return (warnings, shoppingCartItem);+ if (update) await UpdateExistingShoppingCartItem(shoppingCartItem, customer, attributes);+ else+ shoppingCartItem = await InsertNewItem(customer, product, shoppingCartItem,+ automaticallyAddRequiredProductsIfEnabled);++ if (product.ProductTypeId == ProductType.Reservation)+ await _mediator.Send(new AddCustomerReservationCommand {+ Customer = customer,+ Product = product,+ ShoppingCartItem = shoppingCartItem,+ RentalStartDate = rentalStartDate,+ RentalEndDate = rentalEndDate,+ ReservationId = reservationId+ });+ //reset checkout info+ await _customerService.ResetCheckoutData(customer, storeId);++ return (warnings, shoppingCartItem);+ }- var product = await _productService.GetProductById(productId);- if (product == null)- throw new ArgumentNullException(nameof(product));-- var cart = customer.ShoppingCartItems- .Where(sci => sci.ShoppingCartTypeId == shoppingCartType)- .LimitPerStore(_shoppingCartSettings.SharedCartBetweenStores, storeId)- .ToList();-- var warnings = (await _shoppingCartValidator.CheckCommonWarnings(customer, cart, product, shoppingCartType, rentalStartDate,- rentalEndDate, quantity, reservationId)).ToList();-- if (warnings.Any())- return (warnings, null);-- var shoppingCartItem = await FindShoppingCartItem(cart,- shoppingCartType, productId, warehouseId, attributes, customerEnteredPrice,- rentalStartDate, rentalEndDate);-- var update = shoppingCartItem != null && product.ProductTypeId != ProductType.Reservation- && string.IsNullOrEmpty(product.AllowedQuantities);-- if (update) shoppingCartItem.Quantity += quantity;- else {- shoppingCartItem = new ShoppingCartItem {- ShoppingCartTypeId = shoppingCartType,- StoreId = storeId,- WarehouseId = warehouseId,- ProductId = productId,- Attributes = attributes,- EnteredPrice = customerEnteredPrice,- Quantity = quantity,- RentalStartDateUtc = rentalStartDate,- RentalEndDateUtc = rentalEndDate,- AdditionalShippingChargeProduct = product.AdditionalShippingCharge,- IsFreeShipping = product.IsFreeShipping,- IsShipEnabled = product.IsShipEnabled,- IsTaxExempt = product.IsTaxExempt,- IsGiftVoucher = product.IsGiftVoucher,- CreatedOnUtc = DateTime.UtcNow,- ReservationId = reservationId,- Parameter = parameter,- Duration = duration- };- }- warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, validator));-- if (warnings.Any()) return (warnings, shoppingCartItem);- if (update) await UpdateExistingShoppingCartItem(shoppingCartItem, customer, attributes);- else shoppingCartItem = await InsertNewItem(customer, product, shoppingCartItem, automaticallyAddRequiredProductsIfEnabled);-- if (product.ProductTypeId == ProductType.Reservation)- await _mediator.Send(new AddCustomerReservationCommand {- Customer = customer,- Product = product,- ShoppingCartItem = shoppingCartItem,- RentalStartDate = rentalStartDate,- RentalEndDate = rentalEndDate,- ReservationId = reservationId- });- //reset checkout info- await _customerService.ResetCheckoutData(customer, storeId);-- return (warnings, shoppingCartItem);- }+ private async Task UpdateExistingShoppingCartItem(ShoppingCartItem shoppingCartItem, Customer customer,+ IList<CustomAttribute> attributes)+ {+ shoppingCartItem.Attributes = attributes;+ shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;+ await _customerService.UpdateShoppingCartItem(customer.Id, shoppingCartItem);++ //event notification+ await _mediator.EntityUpdated(shoppingCartItem);+ }++ private async Task<ShoppingCartItem> InsertNewItem(+ Customer customer, Product product, ShoppingCartItem shoppingCartItem,+ bool automaticallyAddRequiredProductsIfEnabled)+ {+ customer.ShoppingCartItems.Add(shoppingCartItem);+ await _customerService.InsertShoppingCartItem(customer.Id, shoppingCartItem);++ //event notification+ await _mediator.Publish(new AddToCartEvent(customer, shoppingCartItem, product));+ if (automaticallyAddRequiredProductsIfEnabled)+ await _mediator.Send(new AddRequiredProductsCommand {+ Customer = customer,+ Product = product,+ ShoppingCartType = shoppingCartItem.ShoppingCartTypeId,+ StoreId = shoppingCartItem.StoreId+ });++ return shoppingCartItem;+ }- private async Task UpdateExistingShoppingCartItem(ShoppingCartItem shoppingCartItem, Customer customer,- IList<CustomAttribute> attributes)+ /// <summary>+ /// Updates the shopping cart item+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="shoppingCartItemId">Shopping cart item identifier</param>+ /// <param name="warehouseId"></param>+ /// <param name="attributes">Attributes</param>+ /// <param name="customerEnteredPrice">New customer entered price</param>+ /// <param name="rentalStartDate">Rental start date</param>+ /// <param name="rentalEndDate">Rental end date</param>+ /// <param name="quantity">New shopping cart item quantity</param>+ /// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>+ /// <param name="reservationId"></param>+ /// <param name="sciId"></param>+ /// <returns>Warnings</returns>+ public virtual async Task<IList<string>> UpdateShoppingCartItem(Customer customer,+ string shoppingCartItemId, string warehouseId, IList<CustomAttribute> attributes,+ double? customerEnteredPrice,+ DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,+ int quantity = 1, bool resetCheckoutData = true, string reservationId = "", string sciId = "")+ {+ ArgumentNullException.ThrowIfNull(customer);++ var warnings = new List<string>();++ var shoppingCartItem = customer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId);+ if (shoppingCartItem == null) return warnings;+ if (resetCheckoutData)+ //reset checkout data+ await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);+ if (quantity > 0){+ var product = await _productService.GetProductById(shoppingCartItem.ProductId);+ shoppingCartItem.Quantity = quantity;+ shoppingCartItem.WarehouseId = warehouseId;shoppingCartItem.Attributes = attributes;+ shoppingCartItem.EnteredPrice = customerEnteredPrice;+ shoppingCartItem.RentalStartDateUtc = rentalStartDate;+ shoppingCartItem.RentalEndDateUtc = rentalEndDate;shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;+ shoppingCartItem.AdditionalShippingChargeProduct = product.AdditionalShippingCharge;+ shoppingCartItem.IsFreeShipping = product.IsFreeShipping;+ shoppingCartItem.IsShipEnabled = product.IsShipEnabled;+ shoppingCartItem.IsTaxExempt = product.IsTaxExempt;+ shoppingCartItem.IsGiftVoucher = product.IsGiftVoucher;+ //check warnings+ warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem,+ product, new ShoppingCartValidatorOptions()));+ if (warnings.Any()) return warnings;+ //if everything is OK, then update a shopping cart itemawait _customerService.UpdateShoppingCartItem(customer.Id, shoppingCartItem);//event notificationawait _mediator.EntityUpdated(shoppingCartItem);}-- private async Task<ShoppingCartItem> InsertNewItem(- Customer customer, Product product, ShoppingCartItem shoppingCartItem, bool automaticallyAddRequiredProductsIfEnabled)+ else{-- customer.ShoppingCartItems.Add(shoppingCartItem);- await _customerService.InsertShoppingCartItem(customer.Id, shoppingCartItem);-- //event notification- await _mediator.Publish(new AddToCartEvent(customer, shoppingCartItem, product));- if (automaticallyAddRequiredProductsIfEnabled)- {- await _mediator.Send(new AddRequiredProductsCommand {- Customer = customer,- Product = product,- ShoppingCartType = shoppingCartItem.ShoppingCartTypeId,- StoreId = shoppingCartItem.StoreId- });- }-- return shoppingCartItem;+ //delete a shopping cart item+ await DeleteShoppingCartItem(customer, shoppingCartItem, resetCheckoutData, true);}- /// <summary>- /// Updates the shopping cart item- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="shoppingCartItemId">Shopping cart item identifier</param>- /// <param name="warehouseId"></param>- /// <param name="attributes">Attributes</param>- /// <param name="customerEnteredPrice">New customer entered price</param>- /// <param name="rentalStartDate">Rental start date</param>- /// <param name="rentalEndDate">Rental end date</param>- /// <param name="quantity">New shopping cart item quantity</param>- /// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>- /// <param name="reservationId"></param>- /// <param name="sciId"></param>- /// <returns>Warnings</returns>- public virtual async Task<IList<string>> UpdateShoppingCartItem(Customer customer,- string shoppingCartItemId, string warehouseId, IList<CustomAttribute> attributes,- double? customerEnteredPrice,- DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,- int quantity = 1, bool resetCheckoutData = true, string reservationId = "", string sciId = "")- {- ArgumentNullException.ThrowIfNull(customer);-- var warnings = new List<string>();-- var shoppingCartItem = customer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId);- if (shoppingCartItem == null) return warnings;- if (resetCheckoutData)- {- //reset checkout data- await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);- }- if (quantity > 0)- {- var product = await _productService.GetProductById(shoppingCartItem.ProductId);- shoppingCartItem.Quantity = quantity;- shoppingCartItem.WarehouseId = warehouseId;- shoppingCartItem.Attributes = attributes;- shoppingCartItem.EnteredPrice = customerEnteredPrice;- shoppingCartItem.RentalStartDateUtc = rentalStartDate;- shoppingCartItem.RentalEndDateUtc = rentalEndDate;- shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;- shoppingCartItem.AdditionalShippingChargeProduct = product.AdditionalShippingCharge;- shoppingCartItem.IsFreeShipping = product.IsFreeShipping;- shoppingCartItem.IsShipEnabled = product.IsShipEnabled;- shoppingCartItem.IsTaxExempt = product.IsTaxExempt;- shoppingCartItem.IsGiftVoucher = product.IsGiftVoucher;- //check warnings- warnings.AddRange(await _shoppingCartValidator.GetShoppingCartItemWarnings(customer, shoppingCartItem, product, new ShoppingCartValidatorOptions()));- if (warnings.Any()) return warnings;- //if everything is OK, then update a shopping cart item- await _customerService.UpdateShoppingCartItem(customer.Id, shoppingCartItem);-- //event notification- await _mediator.EntityUpdated(shoppingCartItem);- }- else- {- //delete a shopping cart item- await DeleteShoppingCartItem(customer, shoppingCartItem, resetCheckoutData, true);- }-- return warnings;- }+ return warnings;+ }- /// <summary>- /// Delete shopping cart item- /// </summary>- /// <param name="customer"></param>- /// <param name="shoppingCartItem">Shopping cart item</param>- /// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>- /// <param name="ensureOnlyActiveCheckoutAttributes">A value indicating whether to ensure that only active checkout attributes are attached to the current customer</param>- public virtual async Task DeleteShoppingCartItem(Customer customer, ShoppingCartItem shoppingCartItem, bool resetCheckoutData = true,- bool ensureOnlyActiveCheckoutAttributes = false)- {- ArgumentNullException.ThrowIfNull(shoppingCartItem);+ /// <summary>+ /// Delete shopping cart item+ /// </summary>+ /// <param name="customer"></param>+ /// <param name="shoppingCartItem">Shopping cart item</param>+ /// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>+ /// <param name="ensureOnlyActiveCheckoutAttributes">+ /// A value indicating whether to ensure that only active checkout+ /// attributes are attached to the current customer+ /// </param>+ public virtual async Task DeleteShoppingCartItem(Customer customer, ShoppingCartItem shoppingCartItem,+ bool resetCheckoutData = true,+ bool ensureOnlyActiveCheckoutAttributes = false)+ {+ ArgumentNullException.ThrowIfNull(shoppingCartItem);- //reset checkout data- if (resetCheckoutData)- {- await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);- }+ //reset checkout data+ if (resetCheckoutData) await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);- //delete item- customer.ShoppingCartItems.Remove(customer.ShoppingCartItems.FirstOrDefault(x => x.Id == shoppingCartItem.Id));- await _customerService.DeleteShoppingCartItem(customer.Id, shoppingCartItem);+ //delete item+ customer.ShoppingCartItems.Remove(customer.ShoppingCartItems.FirstOrDefault(x => x.Id == shoppingCartItem.Id));+ await _customerService.DeleteShoppingCartItem(customer.Id, shoppingCartItem);- //event notification- await _mediator.EntityDeleted(shoppingCartItem);- }+ //event notification+ await _mediator.EntityDeleted(shoppingCartItem);+ }- /// <summary>- /// Migrate shopping cart- /// </summary>- /// <param name="fromCustomer">From customer</param>- /// <param name="toCustomer">To customer</param>- /// <param name="includeCouponCodes">A value indicating whether to coupon codes (discount and gift voucher) should be also re-applied</param>- public virtual async Task MigrateShoppingCart(Customer fromCustomer, Customer toCustomer, bool includeCouponCodes)+ /// <summary>+ /// Migrate shopping cart+ /// </summary>+ /// <param name="fromCustomer">From customer</param>+ /// <param name="toCustomer">To customer</param>+ /// <param name="includeCouponCodes">+ /// A value indicating whether to coupon codes (discount and gift voucher) should be also+ /// re-applied+ /// </param>+ public virtual async Task MigrateShoppingCart(Customer fromCustomer, Customer toCustomer, bool includeCouponCodes)+ {+ ArgumentNullException.ThrowIfNull(fromCustomer);+ ArgumentNullException.ThrowIfNull(toCustomer);++ if (fromCustomer.Id == toCustomer.Id)+ return; //the same customer++ //shopping cart items+ var fromCart = fromCustomer.ShoppingCartItems.ToList();+ foreach (var sci in fromCart)+ await AddToCart(toCustomer, sci.ProductId, sci.ShoppingCartTypeId, sci.StoreId, sci.WarehouseId,+ sci.Attributes, sci.EnteredPrice,+ sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.ReservationId, sci.Parameter,+ sci.Duration,+ new ShoppingCartValidatorOptions());+ foreach (var sci in fromCart) await DeleteShoppingCartItem(fromCustomer, sci);++ //copy discount and gift voucher coupon codes+ if (includeCouponCodes){- ArgumentNullException.ThrowIfNull(fromCustomer);- ArgumentNullException.ThrowIfNull(toCustomer);-- if (fromCustomer.Id == toCustomer.Id)- return; //the same customer-- //shopping cart items- var fromCart = fromCustomer.ShoppingCartItems.ToList();- foreach (var sci in fromCart)- {- await AddToCart(toCustomer, sci.ProductId, sci.ShoppingCartTypeId, sci.StoreId, sci.WarehouseId,- sci.Attributes, sci.EnteredPrice,- sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false, sci.ReservationId, sci.Parameter, sci.Duration,- new ShoppingCartValidatorOptions());- }- foreach (var sci in fromCart)- {- await DeleteShoppingCartItem(fromCustomer, sci);- }-- //copy discount and gift voucher coupon codes- if (includeCouponCodes)- {- //discount- var coupons = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);- var resultCoupons = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.DiscountCoupons, coupons);- await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.DiscountCoupons, resultCoupons);-- //gift voucher- var giftVoucher = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);- var resultGift = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons, giftVoucher);- await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, resultGift);- }-- //copy url referer- var lastUrlReferrer = await fromCustomer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.LastUrlReferrer);- await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.LastUrlReferrer, lastUrlReferrer);-- //move selected checkout attributes- var checkoutAttributes = await fromCustomer.GetUserField<List<CustomAttribute>>(_userFieldService, SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);- await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.CheckoutAttributes, checkoutAttributes, _workContext.CurrentStore.Id);+ //discount+ var coupons = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons);+ var resultCoupons = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.DiscountCoupons, coupons);+ await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.DiscountCoupons, resultCoupons);++ //gift voucher+ var giftVoucher = fromCustomer.ParseAppliedCouponCodes(SystemCustomerFieldNames.GiftVoucherCoupons);+ var resultGift = toCustomer.ApplyCouponCode(SystemCustomerFieldNames.GiftVoucherCoupons, giftVoucher);+ await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.GiftVoucherCoupons, resultGift);}- #endregion+ //copy url referer+ var lastUrlReferrer =+ await fromCustomer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.LastUrlReferrer);+ await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.LastUrlReferrer, lastUrlReferrer);++ //move selected checkout attributes+ var checkoutAttributes = await fromCustomer.GetUserField<List<CustomAttribute>>(_userFieldService,+ SystemCustomerFieldNames.CheckoutAttributes, _workContext.CurrentStore.Id);+ await _userFieldService.SaveField(toCustomer, SystemCustomerFieldNames.CheckoutAttributes, checkoutAttributes,+ _workContext.CurrentStore.Id);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.csindex 88abf5753..aba21690f 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs@@ -10,204 +10,228 @@ using Grand.Infrastructure;using Grand.Infrastructure.Validators;using MediatR;-namespace Grand.Business.Checkout.Services.Orders+namespace Grand.Business.Checkout.Services.Orders;++public class ShoppingCartValidator : IShoppingCartValidator{- public class ShoppingCartValidator : IShoppingCartValidator+ private readonly IMediator _mediator;+ private readonly IValidatorFactory _validatorFactory;++ private readonly IWorkContext _workContext;++ public ShoppingCartValidator(+ IWorkContext workContext,+ IMediator mediator,+ IValidatorFactory validatorFactory){+ _workContext = workContext;+ _mediator = mediator;+ _validatorFactory = validatorFactory;+ }- private readonly IWorkContext _workContext;- private readonly IMediator _mediator;- private readonly IValidatorFactory _validatorFactory;-- public ShoppingCartValidator(- IWorkContext workContext,- IMediator mediator,- IValidatorFactory validatorFactory)- {- _workContext = workContext;- _mediator = mediator;- _validatorFactory = validatorFactory;- }+ public virtual async Task<IList<string>> GetStandardWarnings(Customer customer, Product product,+ ShoppingCartItem shoppingCartItem)+ {+ ArgumentNullException.ThrowIfNull(customer);+ ArgumentNullException.ThrowIfNull(product);- public virtual async Task<IList<string>> GetStandardWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem)- {- ArgumentNullException.ThrowIfNull(customer);- ArgumentNullException.ThrowIfNull(product);+ var warnings = new List<string>();- var warnings = new List<string>();+ var result = await _validatorFactory.GetValidator<ShoppingCartStandardValidatorRecord>()+ .ValidateAsync(new ShoppingCartStandardValidatorRecord(customer, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- var result = await _validatorFactory.GetValidator<ShoppingCartStandardValidatorRecord>().ValidateAsync(new ShoppingCartStandardValidatorRecord(customer, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ return warnings;+ }- return warnings;- }+ public virtual async Task<IList<string>> GetShoppingCartItemAttributeWarnings(Customer customer, Product product,+ ShoppingCartItem shoppingCartItem, bool ignoreNonCombinableAttributes = false)+ {+ ArgumentNullException.ThrowIfNull(product);- public virtual async Task<IList<string>> GetShoppingCartItemAttributeWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem, bool ignoreNonCombinableAttributes = false)- {- ArgumentNullException.ThrowIfNull(product);+ var warnings = new List<string>();- var warnings = new List<string>();+ var result = await _validatorFactory.GetValidator<ShoppingCartItemAttributeValidatorRecord>()+ .ValidateAsync(new ShoppingCartItemAttributeValidatorRecord(customer, product, shoppingCartItem,+ ignoreNonCombinableAttributes));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- var result = await _validatorFactory.GetValidator<ShoppingCartItemAttributeValidatorRecord>().ValidateAsync(new ShoppingCartItemAttributeValidatorRecord(customer, product, shoppingCartItem, ignoreNonCombinableAttributes));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ return warnings;+ }- return warnings;- }+ public virtual async Task<IList<string>> GetShoppingCartItemGiftVoucherWarnings(Customer customer,+ Product product, ShoppingCartItem shoppingCartItem)+ {+ ArgumentNullException.ThrowIfNull(product);- public virtual async Task<IList<string>> GetShoppingCartItemGiftVoucherWarnings(Customer customer,- Product product, ShoppingCartItem shoppingCartItem)- {- ArgumentNullException.ThrowIfNull(product);+ var warnings = new List<string>();- var warnings = new List<string>();+ //gift vouchers+ if (!product.IsGiftVoucher) return warnings;+ var result = await _validatorFactory.GetValidator<ShoppingCartGiftVoucherValidatorRecord>()+ .ValidateAsync(new ShoppingCartGiftVoucherValidatorRecord(customer, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- //gift vouchers- if (!product.IsGiftVoucher) return warnings;- var result = await _validatorFactory.GetValidator<ShoppingCartGiftVoucherValidatorRecord>().ValidateAsync(new ShoppingCartGiftVoucherValidatorRecord(customer, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ return warnings;+ }- return warnings;- }+ public virtual async Task<IList<string>> GetInventoryProductWarnings(Customer customer, Product product,+ ShoppingCartItem shoppingCartItem)+ {+ var warnings = new List<string>();- public virtual async Task<IList<string>> GetInventoryProductWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem)- {- var warnings = new List<string>();+ var result = await _validatorFactory.GetValidator<ShoppingCartInventoryProductValidatorRecord>()+ .ValidateAsync(new ShoppingCartInventoryProductValidatorRecord(customer, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- var result = await _validatorFactory.GetValidator<ShoppingCartInventoryProductValidatorRecord>().ValidateAsync(new ShoppingCartInventoryProductValidatorRecord(customer, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ return warnings;+ }- return warnings;- }+ public virtual async Task<IList<string>> GetAuctionProductWarning(double bid, Product product, Customer customer)+ {+ var warnings = new List<string>();+ if (product.ProductTypeId != ProductType.Auction) return warnings;+ var result = await _validatorFactory.GetValidator<ShoppingCartAuctionValidatorRecord>()+ .ValidateAsync(new ShoppingCartAuctionValidatorRecord(customer, product, null, bid));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));++ return warnings;+ }- public virtual async Task<IList<string>> GetAuctionProductWarning(double bid, Product product, Customer customer)- {- var warnings = new List<string>();- if (product.ProductTypeId != ProductType.Auction) return warnings;- var result = await _validatorFactory.GetValidator<ShoppingCartAuctionValidatorRecord>().ValidateAsync(new ShoppingCartAuctionValidatorRecord(customer, product, null, bid));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ public virtual async Task<IList<string>> GetReservationProductWarnings(Customer customer, Product product,+ ShoppingCartItem shoppingCartItem)+ {+ var warnings = new List<string>();+ if (product.ProductTypeId != ProductType.Reservation)return warnings;- }- public virtual async Task<IList<string>> GetReservationProductWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem)- {- var warnings = new List<string>();+ var result = await _validatorFactory.GetValidator<ShoppingCartReservationProductValidatorRecord>()+ .ValidateAsync(new ShoppingCartReservationProductValidatorRecord(customer, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- if (product.ProductTypeId != ProductType.Reservation)- return warnings;+ return warnings;+ }- var result = await _validatorFactory.GetValidator<ShoppingCartReservationProductValidatorRecord>().ValidateAsync(new ShoppingCartReservationProductValidatorRecord(customer, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ public virtual async Task<IList<string>> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart,+ IList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes, bool validateAmount)+ {+ var warnings = new List<string>();+ checkoutAttributes ??= new List<CustomAttribute>();- return warnings;- }+ var result = await _validatorFactory.GetValidator<ShoppingCartWarningsValidatorRecord>()+ .ValidateAsync(new ShoppingCartWarningsValidatorRecord(_workContext.CurrentCustomer,+ _workContext.CurrentStore, shoppingCart));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- public virtual async Task<IList<string>> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart,- IList<CustomAttribute> checkoutAttributes, bool validateCheckoutAttributes, bool validateAmount)+ //validate checkout attributes+ if (validateCheckoutAttributes){- var warnings = new List<string>();- checkoutAttributes ??= new List<CustomAttribute>();-- var result = await _validatorFactory.GetValidator<ShoppingCartWarningsValidatorRecord>().ValidateAsync(new ShoppingCartWarningsValidatorRecord(_workContext.CurrentCustomer, _workContext.CurrentStore, shoppingCart));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));-- //validate checkout attributes- if (validateCheckoutAttributes)- {- var resultCheckoutAttributes = await _validatorFactory.GetValidator<ShoppingCartCheckoutAttributesValidatorRecord>().ValidateAsync(new ShoppingCartCheckoutAttributesValidatorRecord(_workContext.CurrentCustomer, _workContext.CurrentStore,- shoppingCart, checkoutAttributes));- if (!resultCheckoutAttributes.IsValid)- warnings.AddRange(resultCheckoutAttributes.Errors.Select(x => x.ErrorMessage));- }-- //validate subtotal/total amount in the cart- if (validateAmount)- {- var resultCheckoutAttributes = await _validatorFactory.GetValidator<ShoppingCartTotalAmountValidatorRecord>().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);-- return warnings;+ var resultCheckoutAttributes = await _validatorFactory+ .GetValidator<ShoppingCartCheckoutAttributesValidatorRecord>().ValidateAsync(+ new ShoppingCartCheckoutAttributesValidatorRecord(_workContext.CurrentCustomer,+ _workContext.CurrentStore,+ shoppingCart, checkoutAttributes));+ if (!resultCheckoutAttributes.IsValid)+ warnings.AddRange(resultCheckoutAttributes.Errors.Select(x => x.ErrorMessage));}- public async Task<IList<string>> CheckCommonWarnings(Customer customer, IList<ShoppingCartItem> currentCart, Product product,- ShoppingCartType shoppingCartType, DateTime? rentalStartDate, DateTime? rentalEndDate,- int quantity, string reservationId)+ //validate subtotal/total amount in the cart+ if (validateAmount){- var warnings = new List<string>();+ var resultCheckoutAttributes = await _validatorFactory+ .GetValidator<ShoppingCartTotalAmountValidatorRecord>().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);++ return warnings;+ }++ public async Task<IList<string>> CheckCommonWarnings(Customer customer, IList<ShoppingCartItem> currentCart,+ Product product,+ ShoppingCartType shoppingCartType, DateTime? rentalStartDate, DateTime? rentalEndDate,+ int quantity, string reservationId)+ {+ var warnings = new List<string>();- var result = await _validatorFactory.GetValidator<ShoppingCartCommonWarningsValidatorRecord>().ValidateAsync(new ShoppingCartCommonWarningsValidatorRecord(customer, _workContext.CurrentStore, currentCart,+ var result = await _validatorFactory.GetValidator<ShoppingCartCommonWarningsValidatorRecord>().ValidateAsync(+ new ShoppingCartCommonWarningsValidatorRecord(customer, _workContext.CurrentStore, currentCart,product, shoppingCartType, rentalStartDate, rentalEndDate, quantity, reservationId));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- return warnings;- }+ return warnings;+ }- public virtual async Task<IList<string>> GetShoppingCartItemWarnings(Customer customer, ShoppingCartItem shoppingCartItem,- Product product, ShoppingCartValidatorOptions options)- {- ArgumentNullException.ThrowIfNull(product);+ public virtual async Task<IList<string>> GetShoppingCartItemWarnings(Customer customer,+ ShoppingCartItem shoppingCartItem,+ Product product, ShoppingCartValidatorOptions options)+ {+ ArgumentNullException.ThrowIfNull(product);- var warnings = new List<string>();+ var warnings = new List<string>();- //standard properties- if (options.GetStandardWarnings)- warnings.AddRange(await GetStandardWarnings(customer, product, shoppingCartItem));+ //standard properties+ if (options.GetStandardWarnings)+ warnings.AddRange(await GetStandardWarnings(customer, product, shoppingCartItem));- //inventory properties- if (options.GetInventoryWarnings)- warnings.AddRange(await GetInventoryProductWarnings(customer, product, shoppingCartItem));+ //inventory properties+ if (options.GetInventoryWarnings)+ warnings.AddRange(await GetInventoryProductWarnings(customer, product, shoppingCartItem));- //selected attributes- if (options.GetAttributesWarnings)- warnings.AddRange(await GetShoppingCartItemAttributeWarnings(customer, product, shoppingCartItem));+ //selected attributes+ if (options.GetAttributesWarnings)+ warnings.AddRange(await GetShoppingCartItemAttributeWarnings(customer, product, shoppingCartItem));- //gift vouchers- if (options.GetGiftVoucherWarnings)- warnings.AddRange(await GetShoppingCartItemGiftVoucherWarnings(customer, product, shoppingCartItem));+ //gift vouchers+ if (options.GetGiftVoucherWarnings)+ warnings.AddRange(await GetShoppingCartItemGiftVoucherWarnings(customer, product, shoppingCartItem));- //required products- if (options.GetRequiredProductWarnings)- warnings.AddRange(await GetRequiredProductWarnings(customer, shoppingCartItem, product, shoppingCartItem.StoreId));+ //required products+ if (options.GetRequiredProductWarnings)+ warnings.AddRange(await GetRequiredProductWarnings(customer, shoppingCartItem, product,+ shoppingCartItem.StoreId));- //reservation products- if (options.GetReservationWarnings)- warnings.AddRange(await GetReservationProductWarnings(customer, product, shoppingCartItem));+ //reservation products+ if (options.GetReservationWarnings)+ warnings.AddRange(await GetReservationProductWarnings(customer, product, shoppingCartItem));- //event notification- await _mediator.ShoppingCartItemWarningsAdded(warnings, customer, shoppingCartItem, product);+ //event notification+ await _mediator.ShoppingCartItemWarningsAdded(warnings, customer, shoppingCartItem, product);- return warnings;- }+ return warnings;+ }- public virtual async Task<IList<string>> GetRequiredProductWarnings(Customer customer,- ShoppingCartItem shoppingCartItem, Product product, string storeId)- {- ArgumentNullException.ThrowIfNull(customer);- ArgumentNullException.ThrowIfNull(product);+ public virtual async Task<IList<string>> GetRequiredProductWarnings(Customer customer,+ ShoppingCartItem shoppingCartItem, Product product, string storeId)+ {+ ArgumentNullException.ThrowIfNull(customer);+ ArgumentNullException.ThrowIfNull(product);- var warnings = new List<string>();+ var warnings = new List<string>();- if (!product.RequireOtherProducts) return warnings;-- var result = await _validatorFactory.GetValidator<ShoppingCartRequiredProductValidatorRecord>().ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(_workContext.CurrentCustomer, _workContext.CurrentStore, product, shoppingCartItem));- if (!result.IsValid)- warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));- return warnings;- }+ if (!product.RequireOtherProducts) return warnings;++ var result = await _validatorFactory.GetValidator<ShoppingCartRequiredProductValidatorRecord>()+ .ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(_workContext.CurrentCustomer,+ _workContext.CurrentStore, product, shoppingCartItem));+ if (!result.IsValid)+ warnings.AddRange(result.Errors.Select(x => x.ErrorMessage));+ return warnings;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.csindex 53dfe5abf..c1abd43a5 100644--- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs@@ -1,7 +1,7 @@using Grand.Business.Core.Enums.Checkout;using Grand.Business.Core.Interfaces.Checkout.Payments;-using Grand.Business.Core.Utilities.Checkout;using Grand.Business.Core.Interfaces.Common.Configuration;+using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Orders;@@ -10,400 +10,405 @@ using Grand.Domain.Shipping;using Grand.Infrastructure.Extensions;using Grand.SharedKernel;-namespace Grand.Business.Checkout.Services.Payments+namespace Grand.Business.Checkout.Services.Payments;++/// <summary>+/// Payment service+/// </summary>+public class PaymentService : IPaymentService{+ #region Ctor+/// <summary>- /// Payment service+ /// Ctor/// </summary>- public class PaymentService : IPaymentService+ /// <param name="paymentSettings">Payment settings</param>+ /// <param name="paymentProviders">Payment providers</param>+ /// <param name="settingService">Setting service</param>+ public PaymentService(PaymentSettings paymentSettings,+ IEnumerable<IPaymentProvider> paymentProviders,+ ISettingService settingService){- #region Fields-- private readonly PaymentSettings _paymentSettings;- private readonly IEnumerable<IPaymentProvider> _paymentProviders;- private readonly ISettingService _settingService;-- #endregion+ _paymentSettings = paymentSettings;+ _paymentProviders = paymentProviders;+ _settingService = settingService;+ }- #region Ctor+ #endregion- /// <summary>- /// Ctor- /// </summary>- /// <param name="paymentSettings">Payment settings</param>- /// <param name="paymentProviders">Payment providers</param>- /// <param name="settingService">Setting service</param>- public PaymentService(PaymentSettings paymentSettings,- IEnumerable<IPaymentProvider> paymentProviders,- ISettingService settingService)- {- _paymentSettings = paymentSettings;- _paymentProviders = paymentProviders;- _settingService = settingService;- }+ #region Fields- #endregion+ private readonly PaymentSettings _paymentSettings;+ private readonly IEnumerable<IPaymentProvider> _paymentProviders;+ private readonly ISettingService _settingService;- #region Methods+ #endregion- /// <summary>- /// Load active payment methods- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="storeId">Store ident</param>- /// <param name="filterByCountryId">Specified country</param>- /// <returns>Payment methods</returns>- public virtual async Task<IList<IPaymentProvider>> LoadActivePaymentMethods(Customer customer = null, string storeId = "", string filterByCountryId = "")- {- var pm = LoadAllPaymentMethods(customer, storeId, filterByCountryId)- .Where(provider => _paymentSettings.ActivePaymentProviderSystemNames.Contains(provider.SystemName, StringComparer.OrdinalIgnoreCase))- .ToList();-- if (customer == null) return await Task.FromResult(pm);- var selectedShippingOption = customer.GetUserFieldFromEntity<ShippingOption>(- SystemCustomerFieldNames.SelectedShippingOption, storeId);-- if (selectedShippingOption == null) return await Task.FromResult(pm);- for (var i = pm.Count - 1; i >= 0; i--)- {- var restrictedGroupIds = GetRestrictedShippingIds(pm[i]);- if (restrictedGroupIds.Contains(selectedShippingOption.Name))- {- pm.Remove(pm[i]);- }- }- return await Task.FromResult(pm);- }+ #region Methods- /// <summary>- /// Load payment provider by system name- /// </summary>- /// <param name="systemName">System name</param>- /// <returns>Found payment provider</returns>- public virtual IPaymentProvider LoadPaymentMethodBySystemName(string systemName)+ /// <summary>+ /// Load active payment methods+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="storeId">Store ident</param>+ /// <param name="filterByCountryId">Specified country</param>+ /// <returns>Payment methods</returns>+ public virtual async Task<IList<IPaymentProvider>> LoadActivePaymentMethods(Customer customer = null,+ string storeId = "", string filterByCountryId = "")+ {+ var pm = LoadAllPaymentMethods(customer, storeId, filterByCountryId)+ .Where(provider =>+ _paymentSettings.ActivePaymentProviderSystemNames.Contains(provider.SystemName,+ StringComparer.OrdinalIgnoreCase))+ .ToList();++ if (customer == null) return await Task.FromResult(pm);+ var selectedShippingOption = customer.GetUserFieldFromEntity<ShippingOption>(+ SystemCustomerFieldNames.SelectedShippingOption, storeId);++ if (selectedShippingOption == null) return await Task.FromResult(pm);+ for (var i = pm.Count - 1; i >= 0; i--){- return _paymentProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));+ var restrictedGroupIds = GetRestrictedShippingIds(pm[i]);+ if (restrictedGroupIds.Contains(selectedShippingOption.Name)) pm.Remove(pm[i]);}- /// <summary>- /// Load all payment providers- /// </summary>- /// <param name="storeId">Store ident</param>- /// <param name="customer">Customer</param>- /// <param name="filterByCountryId">Load records allowed only in a specified country; pass "" to load all records</param>- /// <returns>Payment providers</returns>- public virtual IList<IPaymentProvider> LoadAllPaymentMethods(Customer customer = null, string storeId = "", string filterByCountryId = "")- {- var paymentMethods = _paymentProviders- .Where(x =>- x.IsAuthenticateStore(storeId) &&- x.IsAuthenticateGroup(customer))- .OrderBy(x => x.Priority).ToList();- return string.IsNullOrEmpty(filterByCountryId) ? paymentMethods :- //filter by country- (from pm in paymentMethods let restrictedCountryIds = GetRestrictedCountryIds(pm) where !restrictedCountryIds.Contains(filterByCountryId) select pm).ToList();- }+ return await Task.FromResult(pm);+ }- /// <summary>- /// Gets a list of country identifiers in which a certain payment method is now allowed- /// </summary>- /// <param name="paymentMethod">Payment method</param>- /// <returns>A list of country identifiers</returns>- public virtual IList<string> GetRestrictedCountryIds(IPaymentProvider paymentMethod)- {- ArgumentNullException.ThrowIfNull(paymentMethod);+ /// <summary>+ /// Load payment provider by system name+ /// </summary>+ /// <param name="systemName">System name</param>+ /// <returns>Found payment provider</returns>+ public virtual IPaymentProvider LoadPaymentMethodBySystemName(string systemName)+ {+ return _paymentProviders.FirstOrDefault(+ x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase));+ }- var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";- var restrictedCountryIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);- return restrictedCountryIds == null ? new List<string>() : restrictedCountryIds.Ids;- }+ /// <summary>+ /// Load all payment providers+ /// </summary>+ /// <param name="storeId">Store ident</param>+ /// <param name="customer">Customer</param>+ /// <param name="filterByCountryId">Load records allowed only in a specified country; pass "" to load all records</param>+ /// <returns>Payment providers</returns>+ public virtual IList<IPaymentProvider> LoadAllPaymentMethods(Customer customer = null, string storeId = "",+ string filterByCountryId = "")+ {+ var paymentMethods = _paymentProviders+ .Where(x =>+ x.IsAuthenticateStore(storeId) &&+ x.IsAuthenticateGroup(customer))+ .OrderBy(x => x.Priority).ToList();+ return string.IsNullOrEmpty(filterByCountryId)+ ? paymentMethods+ :+ //filter by country+ (from pm in paymentMethods+ let restrictedCountryIds = GetRestrictedCountryIds(pm)+ where !restrictedCountryIds.Contains(filterByCountryId)+ select pm).ToList();+ }- /// <summary>- /// Gets a list of role identifiers in which a certain payment method is now allowed- /// </summary>- /// <param name="paymentMethod">Payment method</param>- /// <returns>A list of role identifiers</returns>- public virtual IList<string> GetRestrictedShippingIds(IPaymentProvider paymentMethod)- {- ArgumentNullException.ThrowIfNull(paymentMethod);+ /// <summary>+ /// Gets a list of country identifiers in which a certain payment method is now allowed+ /// </summary>+ /// <param name="paymentMethod">Payment method</param>+ /// <returns>A list of country identifiers</returns>+ public virtual IList<string> GetRestrictedCountryIds(IPaymentProvider paymentMethod)+ {+ ArgumentNullException.ThrowIfNull(paymentMethod);- var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";- var restrictedShippingIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);- return restrictedShippingIds == null ? new List<string>() : restrictedShippingIds.Ids;- }- /// <summary>- /// Saves a list of country identifiers in which a certain payment method is now allowed- /// </summary>- /// <param name="paymentMethod">Payment method</param>- /// <param name="countryIds">A list of country identifiers</param>- public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds)- {- ArgumentNullException.ThrowIfNull(paymentMethod);+ var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";+ var restrictedCountryIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);+ return restrictedCountryIds == null ? new List<string>() : restrictedCountryIds.Ids;+ }- var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";- await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = countryIds });- }+ /// <summary>+ /// Gets a list of role identifiers in which a certain payment method is now allowed+ /// </summary>+ /// <param name="paymentMethod">Payment method</param>+ /// <returns>A list of role identifiers</returns>+ public virtual IList<string> GetRestrictedShippingIds(IPaymentProvider paymentMethod)+ {+ ArgumentNullException.ThrowIfNull(paymentMethod);- /// <summary>- /// Saves a list of role identifiers in which a certain payment method is now allowed- /// </summary>- /// <param name="paymentMethod">Payment method</param>- /// <param name="groupIds">A list of group identifiers</param>- public virtual async Task SaveRestrictedGroupIds(IPaymentProvider paymentMethod, List<string> groupIds)- {- ArgumentNullException.ThrowIfNull(paymentMethod);+ var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";+ var restrictedShippingIds = _settingService.GetSettingByKey<PaymentRestrictedSettings>(settingKey);+ return restrictedShippingIds == null ? new List<string>() : restrictedShippingIds.Ids;+ }- var settingKey = $"PaymentMethodRestictionsGroup.{paymentMethod.SystemName}";- await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = groupIds });- }+ /// <summary>+ /// Saves a list of country identifiers in which a certain payment method is now allowed+ /// </summary>+ /// <param name="paymentMethod">Payment method</param>+ /// <param name="countryIds">A list of country identifiers</param>+ public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List<string> countryIds)+ {+ ArgumentNullException.ThrowIfNull(paymentMethod);- /// <summary>- /// Saves a list of shipping identifiers in which a certain payment method is now allowed- /// </summary>- /// <param name="paymentMethod">Payment method</param>- /// <param name="shippingIds">A list of country identifiers</param>- public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds)- {- ArgumentNullException.ThrowIfNull(paymentMethod);+ var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}";+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = countryIds });+ }- var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";- await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = shippingIds });- }+ /// <summary>+ /// Saves a list of role identifiers in which a certain payment method is now allowed+ /// </summary>+ /// <param name="paymentMethod">Payment method</param>+ /// <param name="groupIds">A list of group identifiers</param>+ public virtual async Task SaveRestrictedGroupIds(IPaymentProvider paymentMethod, List<string> groupIds)+ {+ ArgumentNullException.ThrowIfNull(paymentMethod);- /// <summary>- /// Process a payment- /// </summary>- /// <param name="paymentTransaction">Payment transaction</param>- /// <returns>Process payment result</returns>- public virtual async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);-- if (paymentTransaction.TransactionAmount == 0)- {- var result = new ProcessPaymentResult- {- NewPaymentTransactionStatus = TransactionStatus.Paid- };- return result;- }-- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- return await paymentMethod.ProcessPayment(paymentTransaction);- }+ var settingKey = $"PaymentMethodRestictionsGroup.{paymentMethod.SystemName}";+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = groupIds });+ }- /// <summary>- /// Post process payment- /// </summary>- /// <param name="paymentTransaction">Payment transaction</param>- public virtual async Task PostProcessPayment(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);+ /// <summary>+ /// Saves a list of shipping identifiers in which a certain payment method is now allowed+ /// </summary>+ /// <param name="paymentMethod">Payment method</param>+ /// <param name="shippingIds">A list of country identifiers</param>+ public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List<string> shippingIds)+ {+ ArgumentNullException.ThrowIfNull(paymentMethod);- if (paymentTransaction.TransactionStatus == TransactionStatus.Paid)- return;+ var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}";+ await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = shippingIds });+ }- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- await paymentMethod.PostProcessPayment(paymentTransaction);- }+ /// <summary>+ /// Process a payment+ /// </summary>+ /// <param name="paymentTransaction">Payment transaction</param>+ /// <returns>Process payment result</returns>+ public virtual async Task<ProcessPaymentResult> ProcessPayment(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);- /// <summary>- /// Post redirect payment (used by payment gateways that redirecting to a another URL)- /// </summary>- /// <param name="paymentTransaction">Payment Transaction</param>- public virtual async Task PostRedirectPayment(PaymentTransaction paymentTransaction)+ if (paymentTransaction.TransactionAmount == 0){- ArgumentNullException.ThrowIfNull(paymentTransaction);-- //already paid or order.OrderTotal == 0- if (paymentTransaction.TransactionStatus == TransactionStatus.Paid)- return;-- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- await paymentMethod.PostRedirectPayment(paymentTransaction);+ var result = new ProcessPaymentResult {+ NewPaymentTransactionStatus = TransactionStatus.Paid+ };+ return result;}- /// <summary>- /// Cancel payment transaction- /// </summary>- /// <param name="paymentTransaction">Payment transaction</param>- public virtual async Task CancelPayment(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);+ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ return await paymentMethod.ProcessPayment(paymentTransaction);+ }- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- await paymentMethod.CancelPayment(paymentTransaction);+ /// <summary>+ /// Post process payment+ /// </summary>+ /// <param name="paymentTransaction">Payment transaction</param>+ public virtual async Task PostProcessPayment(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);- }+ if (paymentTransaction.TransactionStatus == TransactionStatus.Paid)+ return;+ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ await paymentMethod.PostProcessPayment(paymentTransaction);+ }- /// <summary>- /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)- /// </summary>- /// <param name="paymentTransaction">Payment transaction</param>- /// <returns>Result</returns>- public virtual async Task<bool> CanRePostRedirectPayment(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);+ /// <summary>+ /// Post redirect payment (used by payment gateways that redirecting to a another URL)+ /// </summary>+ /// <param name="paymentTransaction">Payment Transaction</param>+ public virtual async Task PostRedirectPayment(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);- if (!_paymentSettings.AllowRePostingPayments)- return false;+ //already paid or order.OrderTotal == 0+ if (paymentTransaction.TransactionStatus == TransactionStatus.Paid)+ return;- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod is not { PaymentMethodType: PaymentMethodType.Redirection })- return false; //Payment method couldn't be loaded (for example, was uninstalled)+ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ await paymentMethod.PostRedirectPayment(paymentTransaction);+ }- if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or not TransactionStatus.Pending)- return false; //do not allow for cancelled orders+ /// <summary>+ /// Cancel payment transaction+ /// </summary>+ /// <param name="paymentTransaction">Payment transaction</param>+ public virtual async Task CancelPayment(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);- return await paymentMethod.CanRePostRedirectPayment(paymentTransaction);- }+ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ await paymentMethod.CancelPayment(paymentTransaction);+ }+ /// <summary>+ /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for+ /// redirection payment methods)+ /// </summary>+ /// <param name="paymentTransaction">Payment transaction</param>+ /// <returns>Result</returns>+ public virtual async Task<bool> CanRePostRedirectPayment(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);- /// <summary>- /// Gets an additional handling fee of a payment method- /// </summary>- /// <param name="cart">Shopping cart</param>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>Additional handling fee</returns>- public virtual async Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart, string paymentMethodSystemName)- {- if (string.IsNullOrEmpty(paymentMethodSystemName))- return 0;+ if (!_paymentSettings.AllowRePostingPayments)+ return false;- var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- if (paymentMethod == null)- return 0;+ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod is not { PaymentMethodType: PaymentMethodType.Redirection })+ return false; //Payment method couldn't be loaded (for example, was uninstalled)- var result = await paymentMethod.GetAdditionalHandlingFee(cart);- if (result < 0)- result = 0;+ if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or not TransactionStatus.Pending)+ return false; //do not allow for cancelled orders- return result;- }+ return await paymentMethod.CanRePostRedirectPayment(paymentTransaction);+ }+ /// <summary>+ /// Gets an additional handling fee of a payment method+ /// </summary>+ /// <param name="cart">Shopping cart</param>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>Additional handling fee</returns>+ public virtual async Task<double> GetAdditionalHandlingFee(IList<ShoppingCartItem> cart,+ string paymentMethodSystemName)+ {+ if (string.IsNullOrEmpty(paymentMethodSystemName))+ return 0;- /// <summary>- /// Gets a value indicating whether capture is supported by payment method- /// </summary>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>A value indicating whether capture is supported</returns>- public virtual async Task<bool> SupportCapture(string paymentMethodSystemName)- {- var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- if (paymentMethod == null)- return false;- return await paymentMethod.SupportCapture();- }+ var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);+ if (paymentMethod == null)+ return 0;- /// <summary>- /// Captures payment- /// </summary>- /// <param name="paymentTransaction">Payment transaction</param>- /// <returns>Capture payment result</returns>- public virtual async Task<CapturePaymentResult> Capture(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);+ var result = await paymentMethod.GetAdditionalHandlingFee(cart);+ if (result < 0)+ result = 0;- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- return await paymentMethod.Capture(paymentTransaction);- }+ return result;+ }+ /// <summary>+ /// Gets a value indicating whether capture is supported by payment method+ /// </summary>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>A value indicating whether capture is supported</returns>+ public virtual async Task<bool> SupportCapture(string paymentMethodSystemName)+ {+ var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);+ if (paymentMethod == null)+ return false;+ return await paymentMethod.SupportCapture();+ }- /// <summary>- /// Gets a value indicating whether partial refund is supported by payment method- /// </summary>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>A value indicating whether partial refund is supported</returns>- public virtual async Task<bool> SupportPartiallyRefund(string paymentMethodSystemName)- {- var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- if (paymentMethod == null)- return false;- return await paymentMethod.SupportPartiallyRefund();- }+ /// <summary>+ /// Captures payment+ /// </summary>+ /// <param name="paymentTransaction">Payment transaction</param>+ /// <returns>Capture payment result</returns>+ public virtual async Task<CapturePaymentResult> Capture(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);- /// <summary>- /// Gets a value indicating whether refund is supported by payment method- /// </summary>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>A value indicating whether refund is supported</returns>- public virtual async Task<bool> SupportRefund(string paymentMethodSystemName)- {- var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- if (paymentMethod == null)- return false;- return await paymentMethod.SupportRefund();- }+ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ return await paymentMethod.Capture(paymentTransaction);+ }- /// <summary>- /// Refunds a payment- /// </summary>- /// <param name="refundPaymentRequest">Request</param>- /// <returns>Result</returns>- public virtual async Task<RefundPaymentResult> Refund(RefundPaymentRequest refundPaymentRequest)- {- var paymentMethod = LoadPaymentMethodBySystemName(refundPaymentRequest.PaymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- return await paymentMethod.Refund(refundPaymentRequest);- }+ /// <summary>+ /// Gets a value indicating whether partial refund is supported by payment method+ /// </summary>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>A value indicating whether partial refund is supported</returns>+ public virtual async Task<bool> SupportPartiallyRefund(string paymentMethodSystemName)+ {+ var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);+ if (paymentMethod == null)+ return false;+ return await paymentMethod.SupportPartiallyRefund();+ }+ /// <summary>+ /// Gets a value indicating whether refund is supported by payment method+ /// </summary>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>A value indicating whether refund is supported</returns>+ public virtual async Task<bool> SupportRefund(string paymentMethodSystemName)+ {+ var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);+ if (paymentMethod == null)+ return false;+ return await paymentMethod.SupportRefund();+ }- /// <summary>- /// Gets a value indicating whether void is supported by payment method- /// </summary>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>A value indicating whether void is supported</returns>- public virtual async Task<bool> SupportVoid(string paymentMethodSystemName)- {- var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- if (paymentMethod == null)- return false;- return await paymentMethod.SupportVoid();- }+ /// <summary>+ /// Refunds a payment+ /// </summary>+ /// <param name="refundPaymentRequest">Request</param>+ /// <returns>Result</returns>+ public virtual async Task<RefundPaymentResult> Refund(RefundPaymentRequest refundPaymentRequest)+ {+ var paymentMethod =+ LoadPaymentMethodBySystemName(refundPaymentRequest.PaymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ return await paymentMethod.Refund(refundPaymentRequest);+ }- /// <summary>- /// Voids a payment- /// </summary>- /// <param name="paymentTransaction">Payment transaction</param>- /// <returns>Result</returns>- public virtual async Task<VoidPaymentResult> Void(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);- var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);- if (paymentMethod == null)- throw new GrandException("Payment method couldn't be loaded");- return await paymentMethod.Void(paymentTransaction);- }+ /// <summary>+ /// Gets a value indicating whether void is supported by payment method+ /// </summary>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>A value indicating whether void is supported</returns>+ public virtual async Task<bool> SupportVoid(string paymentMethodSystemName)+ {+ var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);+ if (paymentMethod == null)+ return false;+ return await paymentMethod.SupportVoid();+ }+ /// <summary>+ /// Voids a payment+ /// </summary>+ /// <param name="paymentTransaction">Payment transaction</param>+ /// <returns>Result</returns>+ public virtual async Task<VoidPaymentResult> Void(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);++ var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName);+ if (paymentMethod == null)+ throw new GrandException("Payment method couldn't be loaded");+ return await paymentMethod.Void(paymentTransaction);+ }- /// <summary>- /// Gets a payment method type- /// </summary>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>A payment method type</returns>- public virtual PaymentMethodType GetPaymentMethodType(string paymentMethodSystemName)- {- var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);- return paymentMethod?.PaymentMethodType ?? PaymentMethodType.Other;- }- #endregion+ /// <summary>+ /// Gets a payment method type+ /// </summary>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>A payment method type</returns>+ public virtual PaymentMethodType GetPaymentMethodType(string paymentMethodSystemName)+ {+ var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);+ return paymentMethod?.PaymentMethodType ?? PaymentMethodType.Other;}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.csindex 98f9a488d..bddcadecb 100644--- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs@@ -1,163 +1,162 @@using Grand.Business.Core.Interfaces.Checkout.Payments;using Grand.Business.Core.Queries.Checkout.Orders;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Payments;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Payments+namespace Grand.Business.Checkout.Services.Payments;++public class PaymentTransactionService : IPaymentTransactionService{- public class PaymentTransactionService : IPaymentTransactionService+ private readonly IMediator _mediator;+ private readonly IRepository<PaymentTransaction> _repositoryPaymentTransaction;++ public PaymentTransactionService(+ IRepository<PaymentTransaction> repositoryPaymentTransaction,+ IMediator mediator)+ {+ _repositoryPaymentTransaction = repositoryPaymentTransaction;+ _mediator = mediator;+ }++ /// <summary>+ /// Inserts an payment transaction+ /// </summary>+ /// <param name="paymentTransaction">payment transaction</param>+ public virtual async Task InsertPaymentTransaction(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);++ await _repositoryPaymentTransaction.InsertAsync(paymentTransaction);++ //event notification+ await _mediator.EntityInserted(paymentTransaction);+ }++ /// <summary>+ /// Update an payment transaction+ /// </summary>+ /// <param name="paymentTransaction">payment transaction</param>+ public virtual async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);++ await _repositoryPaymentTransaction.UpdateAsync(paymentTransaction);++ //event notification+ await _mediator.EntityUpdated(paymentTransaction);+ }++ /// <summary>+ /// Delete an payment transaction+ /// </summary>+ /// <param name="paymentTransaction">payment transaction</param>+ public virtual async Task DeletePaymentTransaction(PaymentTransaction paymentTransaction)+ {+ ArgumentNullException.ThrowIfNull(paymentTransaction);++ await _repositoryPaymentTransaction.DeleteAsync(paymentTransaction);++ //event notification+ await _mediator.EntityDeleted(paymentTransaction);+ }++ /// <summary>+ /// Gets an payment transaction+ /// </summary>+ /// <param name="id">The identifier</param>+ /// <returns>PaymentTransaction</returns>+ public virtual Task<PaymentTransaction> GetById(string id)+ {+ return _repositoryPaymentTransaction.GetByIdAsync(id);+ }++ /// <summary>+ /// Gets an payment transactions for order Ident+ /// </summary>+ /// <param name="orderCode">The order code</param>+ /// <returns>PaymentTransaction</returns>+ public virtual async Task<IList<PaymentTransaction>> GetByOrderCode(string orderCode){- private readonly IRepository<PaymentTransaction> _repositoryPaymentTransaction;- private readonly IMediator _mediator;-- public PaymentTransactionService(- IRepository<PaymentTransaction> repositoryPaymentTransaction,- IMediator mediator)- {- _repositoryPaymentTransaction = repositoryPaymentTransaction;- _mediator = mediator;- }- /// <summary>- /// Inserts an payment transaction- /// </summary>- /// <param name="paymentTransaction">payment transaction</param>- public virtual async Task InsertPaymentTransaction(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);-- await _repositoryPaymentTransaction.InsertAsync(paymentTransaction);-- //event notification- await _mediator.EntityInserted(paymentTransaction);-- }- /// <summary>- /// Update an payment transaction- /// </summary>- /// <param name="paymentTransaction">payment transaction</param>- public virtual async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);-- await _repositoryPaymentTransaction.UpdateAsync(paymentTransaction);-- //event notification- await _mediator.EntityUpdated(paymentTransaction);-- }-- /// <summary>- /// Delete an payment transaction- /// </summary>- /// <param name="paymentTransaction">payment transaction</param>- public virtual async Task DeletePaymentTransaction(PaymentTransaction paymentTransaction)- {- ArgumentNullException.ThrowIfNull(paymentTransaction);-- await _repositoryPaymentTransaction.DeleteAsync(paymentTransaction);-- //event notification- await _mediator.EntityDeleted(paymentTransaction);-- }-- /// <summary>- /// Gets an payment transaction- /// </summary>- /// <param name="id">The identifier</param>- /// <returns>PaymentTransaction</returns>- public virtual Task<PaymentTransaction> GetById(string id)- {- return _repositoryPaymentTransaction.GetByIdAsync(id);- }-- /// <summary>- /// Gets an payment transactions for order Ident- /// </summary>- /// <param name="orderCode">The order code</param>- /// <returns>PaymentTransaction</returns>- public virtual async Task<IList<PaymentTransaction>> GetByOrderCode(string orderCode)- {- return await Task.FromResult(- _repositoryPaymentTransaction.Table.Where(x => x.OrderCode == orderCode)+ return await Task.FromResult(+ _repositoryPaymentTransaction.Table.Where(x => x.OrderCode == orderCode).ToList());- }-- /// <summary>- /// Gets an payment transactions for order guid- /// </summary>- /// <param name="orderGuid">The order guid</param>- /// <returns>PaymentTransaction</returns>- public virtual async Task<PaymentTransaction> GetOrderByGuid(Guid orderGuid)- {- return await Task.FromResult(_repositoryPaymentTransaction.Table.FirstOrDefault(x => x.OrderGuid == orderGuid));- }-- /// <summary>- /// Get an payment transactions by authorization transaction ID and payment method system name- /// </summary>- /// <param name="authorizationTransactionId">Authorization transaction ID</param>- /// <param name="paymentMethodSystemName">Payment method system name</param>- /// <returns>Order</returns>- public virtual async Task<IList<PaymentTransaction>> GetByAuthorizationTransactionIdAndPaymentMethod(string authorizationTransactionId, string paymentMethodSystemName)- {- var query = from p in _repositoryPaymentTransaction.Table- select p;-- if (!string.IsNullOrEmpty(authorizationTransactionId))- query = query.Where(c => c.AuthorizationTransactionId == authorizationTransactionId);-- if (!string.IsNullOrEmpty(paymentMethodSystemName))- query = query.Where(c => c.PaymentMethodSystemName == paymentMethodSystemName);-- return await Task.FromResult(query.ToList());- }-- /// <summary>- /// Search payment transactions- /// </summary>- /// <param name="orderGuid">Order ident by guid</param>- /// <param name="storeId">Store ident</param>- /// <param name="customerEmail">Customer email</param>- /// <param name="ts">Transaction status</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>- /// <returns>Page list payment transaction</returns>- public virtual async Task<IPagedList<PaymentTransaction>> SearchPaymentTransactions(- Guid? orderGuid = null,- string storeId = "",- string customerEmail = "",- TransactionStatus? ts = null,- int pageIndex = 0, int pageSize = int.MaxValue,- DateTime? createdFromUtc = null,- DateTime? createdToUtc = null)- {- var model = new GetPaymentTransactionQuery {- CreatedFromUtc = createdFromUtc,- CreatedToUtc = createdToUtc,- PageIndex = pageIndex,- PageSize = pageSize,- OrderGuid = orderGuid,- CustomerEmail = customerEmail,- StoreId = storeId,- Ts = ts- };-- var query = await _mediator.Send(model);- return await PagedList<PaymentTransaction>.Create(query, pageIndex, pageSize);- }-- /// <summary>- /// Set payment error for transaction- /// </summary>- public virtual async Task SetError(string paymentTransactionId, List<string> errors)- {- await _repositoryPaymentTransaction.UpdateField(paymentTransactionId, x => x.Errors, errors);- }}-}++ /// <summary>+ /// Gets an payment transactions for order guid+ /// </summary>+ /// <param name="orderGuid">The order guid</param>+ /// <returns>PaymentTransaction</returns>+ public virtual async Task<PaymentTransaction> GetOrderByGuid(Guid orderGuid)+ {+ return await Task.FromResult(_repositoryPaymentTransaction.Table.FirstOrDefault(x => x.OrderGuid == orderGuid));+ }++ /// <summary>+ /// Get an payment transactions by authorization transaction ID and payment method system name+ /// </summary>+ /// <param name="authorizationTransactionId">Authorization transaction ID</param>+ /// <param name="paymentMethodSystemName">Payment method system name</param>+ /// <returns>Order</returns>+ public virtual async Task<IList<PaymentTransaction>> GetByAuthorizationTransactionIdAndPaymentMethod(+ string authorizationTransactionId, string paymentMethodSystemName)+ {+ var query = from p in _repositoryPaymentTransaction.Table+ select p;++ if (!string.IsNullOrEmpty(authorizationTransactionId))+ query = query.Where(c => c.AuthorizationTransactionId == authorizationTransactionId);++ if (!string.IsNullOrEmpty(paymentMethodSystemName))+ query = query.Where(c => c.PaymentMethodSystemName == paymentMethodSystemName);++ return await Task.FromResult(query.ToList());+ }++ /// <summary>+ /// Search payment transactions+ /// </summary>+ /// <param name="orderGuid">Order ident by guid</param>+ /// <param name="storeId">Store ident</param>+ /// <param name="customerEmail">Customer email</param>+ /// <param name="ts">Transaction status</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>+ /// <returns>Page list payment transaction</returns>+ public virtual async Task<IPagedList<PaymentTransaction>> SearchPaymentTransactions(+ Guid? orderGuid = null,+ string storeId = "",+ string customerEmail = "",+ TransactionStatus? ts = null,+ int pageIndex = 0, int pageSize = int.MaxValue,+ DateTime? createdFromUtc = null,+ DateTime? createdToUtc = null)+ {+ var model = new GetPaymentTransactionQuery {+ CreatedFromUtc = createdFromUtc,+ CreatedToUtc = createdToUtc,+ PageIndex = pageIndex,+ PageSize = pageSize,+ OrderGuid = orderGuid,+ CustomerEmail = customerEmail,+ StoreId = storeId,+ Ts = ts+ };++ var query = await _mediator.Send(model);+ return await PagedList<PaymentTransaction>.Create(query, pageIndex, pageSize);+ }++ /// <summary>+ /// Set payment error for transaction+ /// </summary>+ public virtual async Task SetError(string paymentTransactionId, List<string> errors)+ {+ await _repositoryPaymentTransaction.UpdateField(paymentTransactionId, x => x.Errors, errors);+ }+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.csindex 5935f3164..c8aa1636d 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs@@ -1,123 +1,121 @@using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Data;+using Grand.Domain.Shipping;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Data;-using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Services.Shipping+namespace Grand.Business.Checkout.Services.Shipping;++public class DeliveryDateService : IDeliveryDateService{- public class DeliveryDateService : IDeliveryDateService+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ public DeliveryDateService(+ IRepository<DeliveryDate> deliveryDateRepository,+ IMediator mediator,+ ICacheBase cacheBase){- #region Fields+ _deliveryDateRepository = deliveryDateRepository;+ _mediator = mediator;+ _cacheBase = cacheBase;+ }- private readonly IRepository<DeliveryDate> _deliveryDateRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;+ #endregion- #endregion+ #region Fields- #region Ctor+ private readonly IRepository<DeliveryDate> _deliveryDateRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;- /// <summary>- /// Ctor- /// </summary>- public DeliveryDateService(- IRepository<DeliveryDate> deliveryDateRepository,- IMediator mediator,- ICacheBase cacheBase)- {- _deliveryDateRepository = deliveryDateRepository;- _mediator = mediator;- _cacheBase = cacheBase;- }+ #endregion- #endregion+ #region Delivery dates- #region Delivery dates+ /// <summary>+ /// Gets a delivery date+ /// </summary>+ /// <param name="deliveryDateId">The delivery date identifier</param>+ /// <returns>Delivery date</returns>+ public virtual Task<DeliveryDate> GetDeliveryDateById(string deliveryDateId)+ {+ var key = string.Format(CacheKey.DELIVERYDATE_BY_ID_KEY, deliveryDateId);+ return _cacheBase.GetAsync(key, () => _deliveryDateRepository.GetByIdAsync(deliveryDateId));+ }- /// <summary>- /// Gets a delivery date- /// </summary>- /// <param name="deliveryDateId">The delivery date identifier</param>- /// <returns>Delivery date</returns>- public virtual Task<DeliveryDate> GetDeliveryDateById(string deliveryDateId)- {- var key = string.Format(CacheKey.DELIVERYDATE_BY_ID_KEY, deliveryDateId);- return _cacheBase.GetAsync(key, () => _deliveryDateRepository.GetByIdAsync(deliveryDateId));- }-- /// <summary>- /// Gets all delivery dates- /// </summary>- /// <returns>Delivery dates</returns>- public virtual async Task<IList<DeliveryDate>> GetAllDeliveryDates()- {- return await _cacheBase.GetAsync(CacheKey.DELIVERYDATE_ALL, async () =>- {- var query = from dd in _deliveryDateRepository.Table- orderby dd.DisplayOrder- select dd;- return await Task.FromResult(query.ToList());- });- }-- /// <summary>- /// Inserts a delivery date- /// </summary>- /// <param name="deliveryDate">Delivery date</param>- public virtual async Task InsertDeliveryDate(DeliveryDate deliveryDate)+ /// <summary>+ /// Gets all delivery dates+ /// </summary>+ /// <returns>Delivery dates</returns>+ public virtual async Task<IList<DeliveryDate>> GetAllDeliveryDates()+ {+ return await _cacheBase.GetAsync(CacheKey.DELIVERYDATE_ALL, async () =>{- ArgumentNullException.ThrowIfNull(deliveryDate);-- await _deliveryDateRepository.InsertAsync(deliveryDate);+ var query = from dd in _deliveryDateRepository.Table+ orderby dd.DisplayOrder+ select dd;+ return await Task.FromResult(query.ToList());+ });+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.DELIVERYDATE_PATTERN_KEY);+ /// <summary>+ /// Inserts a delivery date+ /// </summary>+ /// <param name="deliveryDate">Delivery date</param>+ public virtual async Task InsertDeliveryDate(DeliveryDate deliveryDate)+ {+ ArgumentNullException.ThrowIfNull(deliveryDate);- //event notification- await _mediator.EntityInserted(deliveryDate);- }+ await _deliveryDateRepository.InsertAsync(deliveryDate);- /// <summary>- /// Updates the delivery date- /// </summary>- /// <param name="deliveryDate">Delivery date</param>- public virtual async Task UpdateDeliveryDate(DeliveryDate deliveryDate)- {- ArgumentNullException.ThrowIfNull(deliveryDate);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.DELIVERYDATE_PATTERN_KEY);- await _deliveryDateRepository.UpdateAsync(deliveryDate);+ //event notification+ await _mediator.EntityInserted(deliveryDate);+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.DELIVERYDATE_PATTERN_KEY);+ /// <summary>+ /// Updates the delivery date+ /// </summary>+ /// <param name="deliveryDate">Delivery date</param>+ public virtual async Task UpdateDeliveryDate(DeliveryDate deliveryDate)+ {+ ArgumentNullException.ThrowIfNull(deliveryDate);- //event notification- await _mediator.EntityUpdated(deliveryDate);- }+ await _deliveryDateRepository.UpdateAsync(deliveryDate);- /// <summary>- /// Deletes a delivery date- /// </summary>- /// <param name="deliveryDate">The delivery date</param>- public virtual async Task DeleteDeliveryDate(DeliveryDate deliveryDate)- {- ArgumentNullException.ThrowIfNull(deliveryDate);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.DELIVERYDATE_PATTERN_KEY);- await _deliveryDateRepository.DeleteAsync(deliveryDate);+ //event notification+ await _mediator.EntityUpdated(deliveryDate);+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.DELIVERYDATE_PATTERN_KEY);+ /// <summary>+ /// Deletes a delivery date+ /// </summary>+ /// <param name="deliveryDate">The delivery date</param>+ public virtual async Task DeleteDeliveryDate(DeliveryDate deliveryDate)+ {+ ArgumentNullException.ThrowIfNull(deliveryDate);- //clear product cache- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);+ await _deliveryDateRepository.DeleteAsync(deliveryDate);- //event notification- await _mediator.EntityDeleted(deliveryDate);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.DELIVERYDATE_PATTERN_KEY);- #endregion+ //clear product cache+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);+ //event notification+ await _mediator.EntityDeleted(deliveryDate);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.csindex 8941b9088..202dfefea 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs@@ -1,130 +1,129 @@using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Data;+using Grand.Domain.Shipping;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Data;-using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Services.Shipping+namespace Grand.Business.Checkout.Services.Shipping;++public class PickupPointService : IPickupPointService{- public class PickupPointService : IPickupPointService+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ public PickupPointService(+ IRepository<PickupPoint> pickupPointsRepository,+ IMediator mediator,+ ICacheBase cacheBase){- #region Fields+ _pickupPointsRepository = pickupPointsRepository;+ _mediator = mediator;+ _cacheBase = cacheBase;+ }- private readonly IRepository<PickupPoint> _pickupPointsRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;+ #endregion- #endregion+ #region Fields- #region Ctor+ private readonly IRepository<PickupPoint> _pickupPointsRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;- /// <summary>- /// Ctor- /// </summary>- public PickupPointService(- IRepository<PickupPoint> pickupPointsRepository,- IMediator mediator,- ICacheBase cacheBase)- {- _pickupPointsRepository = pickupPointsRepository;- _mediator = mediator;- _cacheBase = cacheBase;- }-- #endregion-- #region Methods- /// <summary>- /// Gets a pickup point- /// </summary>- /// <param name="pickupPointId">The pickup point identifier</param>- /// <returns>Delivery date</returns>- public virtual Task<PickupPoint> GetPickupPointById(string pickupPointId)- {- var key = string.Format(CacheKey.PICKUPPOINTS_BY_ID_KEY, pickupPointId);- return _cacheBase.GetAsync(key, () => _pickupPointsRepository.GetByIdAsync(pickupPointId));- }-- /// <summary>- /// Gets all pickup points- /// </summary>- /// <returns>Warehouses</returns>- public virtual async Task<IList<PickupPoint>> GetAllPickupPoints()- {- return await _cacheBase.GetAsync(CacheKey.PICKUPPOINTS_ALL, async () =>- {- var query = from pp in _pickupPointsRepository.Table- orderby pp.DisplayOrder- select pp;- return await Task.FromResult(query.ToList());- });- }-- /// <summary>- /// Gets all pickup points- /// </summary>- /// <returns>Warehouses</returns>- public virtual async Task<IList<PickupPoint>> LoadActivePickupPoints(string storeId = "")- {- var pickupPoints = await GetAllPickupPoints();- return pickupPoints.Where(pp => pp.StoreId == storeId || string.IsNullOrEmpty(pp.StoreId)).ToList();- }+ #endregion+ #region Methods++ /// <summary>+ /// Gets a pickup point+ /// </summary>+ /// <param name="pickupPointId">The pickup point identifier</param>+ /// <returns>Delivery date</returns>+ public virtual Task<PickupPoint> GetPickupPointById(string pickupPointId)+ {+ var key = string.Format(CacheKey.PICKUPPOINTS_BY_ID_KEY, pickupPointId);+ return _cacheBase.GetAsync(key, () => _pickupPointsRepository.GetByIdAsync(pickupPointId));+ }- /// <summary>- /// Inserts a pickup point- /// </summary>- /// <param name="pickupPoint">Pickup Point</param>- public virtual async Task InsertPickupPoint(PickupPoint pickupPoint)+ /// <summary>+ /// Gets all pickup points+ /// </summary>+ /// <returns>Warehouses</returns>+ public virtual async Task<IList<PickupPoint>> GetAllPickupPoints()+ {+ return await _cacheBase.GetAsync(CacheKey.PICKUPPOINTS_ALL, async () =>{- ArgumentNullException.ThrowIfNull(pickupPoint);+ var query = from pp in _pickupPointsRepository.Table+ orderby pp.DisplayOrder+ select pp;+ return await Task.FromResult(query.ToList());+ });+ }- await _pickupPointsRepository.InsertAsync(pickupPoint);+ /// <summary>+ /// Gets all pickup points+ /// </summary>+ /// <returns>Warehouses</returns>+ public virtual async Task<IList<PickupPoint>> LoadActivePickupPoints(string storeId = "")+ {+ var pickupPoints = await GetAllPickupPoints();+ return pickupPoints.Where(pp => pp.StoreId == storeId || string.IsNullOrEmpty(pp.StoreId)).ToList();+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.PICKUPPOINTS_PATTERN_KEY);- //event notification- await _mediator.EntityInserted(pickupPoint);- }+ /// <summary>+ /// Inserts a pickup point+ /// </summary>+ /// <param name="pickupPoint">Pickup Point</param>+ public virtual async Task InsertPickupPoint(PickupPoint pickupPoint)+ {+ ArgumentNullException.ThrowIfNull(pickupPoint);- /// <summary>- /// Updates the pickupPoint- /// </summary>- /// <param name="pickupPoint">Pickup Point</param>- public virtual async Task UpdatePickupPoint(PickupPoint pickupPoint)- {- ArgumentNullException.ThrowIfNull(pickupPoint);+ await _pickupPointsRepository.InsertAsync(pickupPoint);- await _pickupPointsRepository.UpdateAsync(pickupPoint);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.PICKUPPOINTS_PATTERN_KEY);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.PICKUPPOINTS_PATTERN_KEY);+ //event notification+ await _mediator.EntityInserted(pickupPoint);+ }- //event notification- await _mediator.EntityUpdated(pickupPoint);- }+ /// <summary>+ /// Updates the pickupPoint+ /// </summary>+ /// <param name="pickupPoint">Pickup Point</param>+ public virtual async Task UpdatePickupPoint(PickupPoint pickupPoint)+ {+ ArgumentNullException.ThrowIfNull(pickupPoint);- /// <summary>- /// Deletes a pickup point- /// </summary>- /// <param name="pickupPoint">pickup point</param>- public virtual async Task DeletePickupPoint(PickupPoint pickupPoint)- {- ArgumentNullException.ThrowIfNull(pickupPoint);+ await _pickupPointsRepository.UpdateAsync(pickupPoint);++ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.PICKUPPOINTS_PATTERN_KEY);- await _pickupPointsRepository.DeleteAsync(pickupPoint);+ //event notification+ await _mediator.EntityUpdated(pickupPoint);+ }- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.PICKUPPOINTS_PATTERN_KEY);+ /// <summary>+ /// Deletes a pickup point+ /// </summary>+ /// <param name="pickupPoint">pickup point</param>+ public virtual async Task DeletePickupPoint(PickupPoint pickupPoint)+ {+ ArgumentNullException.ThrowIfNull(pickupPoint);- //event notification- await _mediator.EntityDeleted(pickupPoint);- }+ await _pickupPointsRepository.DeleteAsync(pickupPoint);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.PICKUPPOINTS_PATTERN_KEY);- #endregion+ //event notification+ await _mediator.EntityDeleted(pickupPoint);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.csindex 4c531c3e1..a9196ce1c 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs@@ -1,223 +1,220 @@using Grand.Business.Core.Interfaces.Checkout.Shipping;-using Grand.Domain;using Grand.Data;+using Grand.Domain;using Grand.Domain.Shipping;using Grand.Infrastructure.Extensions;using MediatR;-namespace Grand.Business.Checkout.Services.Shipping+namespace Grand.Business.Checkout.Services.Shipping;++/// <summary>+/// Shipment service+/// </summary>+public class ShipmentService : IShipmentService{+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ /// <param name="shipmentRepository">Shipment repository</param>+ /// <param name="shipmentNoteRepository">Order note repository</param>+ /// <param name="mediator">Mediator</param>+ public ShipmentService(IRepository<Shipment> shipmentRepository, IRepository<ShipmentNote> shipmentNoteRepository,+ IMediator mediator)+ {+ _shipmentRepository = shipmentRepository;+ _shipmentNoteRepository = shipmentNoteRepository;+ _mediator = mediator;+ }++ #endregion++ #region Fields++ private readonly IRepository<Shipment> _shipmentRepository;+ private readonly IRepository<ShipmentNote> _shipmentNoteRepository;+ private readonly IMediator _mediator;++ #endregion++ #region Methods++ /// <summary>+ /// Search shipments+ /// </summary>+ /// <param name="vendorId">Vendor identifier; "" to load all records</param>+ /// <param name="storeId">Store identifier</param>+ /// <param name="warehouseId">+ /// Warehouse identifier, only shipments with products from a specified warehouse will be loaded;+ /// 0 to load all orders+ /// </param>+ /// <param name="shippingCountryId">Shipping country identifier; "" to load all records</param>+ /// <param name="shippingStateId">Shipping state identifier; "" to load all records</param>+ /// <param name="shippingCity">Shipping city; null to load all records</param>+ /// <param name="trackingNumber">Search by tracking number</param>+ /// <param name="loadNotShipped">A value indicating whether we should load only not shipped shipments</param>+ /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>+ /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>+ /// <param name="pageIndex">Page index</param>+ /// <param name="pageSize">Page size</param>+ /// <returns>Shipments</returns>+ public virtual async Task<IPagedList<Shipment>> GetAllShipments(string storeId = "", string vendorId = "",+ string warehouseId = "",+ string shippingCountryId = "",+ int shippingStateId = 0,+ string shippingCity = null,+ string trackingNumber = null,+ bool loadNotShipped = false,+ DateTime? createdFromUtc = null, DateTime? createdToUtc = null,+ int pageIndex = 0, int pageSize = int.MaxValue)+ {+ var query = from p in _shipmentRepository.Table+ select p;++ if (!string.IsNullOrEmpty(storeId)) query = query.Where(x => x.StoreId == storeId);+ if (!string.IsNullOrEmpty(vendorId)) query = query.Where(x => x.VendorId == vendorId);+ if (!string.IsNullOrEmpty(trackingNumber))+ query = query.Where(s => s.TrackingNumber.Contains(trackingNumber));++ if (loadNotShipped)+ query = query.Where(s => !s.ShippedDateUtc.HasValue);+ if (createdFromUtc.HasValue)+ query = query.Where(s => createdFromUtc.Value <= s.CreatedOnUtc);+ if (createdToUtc.HasValue)+ query = query.Where(s => createdToUtc.Value >= s.CreatedOnUtc);++ query = query.OrderByDescending(x => x.CreatedOnUtc);+ var shipments = await PagedList<Shipment>.Create(query, pageIndex, pageSize);+ return shipments;+ }+/// <summary>- /// Shipment service+ /// Get shipment by identifiers/// </summary>- public class ShipmentService : IShipmentService+ /// <param name="shipmentIds">Shipment identifiers</param>+ /// <returns>Shipments</returns>+ public virtual async Task<IList<Shipment>> GetShipmentsByIds(string[] shipmentIds){- #region Fields-- private readonly IRepository<Shipment> _shipmentRepository;- private readonly IRepository<ShipmentNote> _shipmentNoteRepository;- private readonly IMediator _mediator;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="shipmentRepository">Shipment repository</param>- /// <param name="shipmentNoteRepository">Order note repository</param>- /// <param name="mediator">Mediator</param>- public ShipmentService(IRepository<Shipment> shipmentRepository, IRepository<ShipmentNote> shipmentNoteRepository,- IMediator mediator)- {- _shipmentRepository = shipmentRepository;- _shipmentNoteRepository = shipmentNoteRepository;- _mediator = mediator;- }-- #endregion-- #region Methods-- /// <summary>- /// Search shipments- /// </summary>- /// <param name="vendorId">Vendor identifier; "" to load all records</param>- /// <param name="storeId">Store identifier</param>- /// <param name="warehouseId">Warehouse identifier, only shipments with products from a specified warehouse will be loaded; 0 to load all orders</param>- /// <param name="shippingCountryId">Shipping country identifier; "" to load all records</param>- /// <param name="shippingStateId">Shipping state identifier; "" to load all records</param>- /// <param name="shippingCity">Shipping city; null to load all records</param>- /// <param name="trackingNumber">Search by tracking number</param>- /// <param name="loadNotShipped">A value indicating whether we should load only not shipped shipments</param>- /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>- /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>- /// <param name="pageIndex">Page index</param>- /// <param name="pageSize">Page size</param>- /// <returns>Shipments</returns>- public virtual async Task<IPagedList<Shipment>> GetAllShipments(string storeId = "", string vendorId = "", string warehouseId = "",- string shippingCountryId = "",- int shippingStateId = 0,- string shippingCity = null,- string trackingNumber = null,- bool loadNotShipped = false,- DateTime? createdFromUtc = null, DateTime? createdToUtc = null,- int pageIndex = 0, int pageSize = int.MaxValue)- {- var query = from p in _shipmentRepository.Table- select p;-- if (!string.IsNullOrEmpty(storeId))- {- query = query.Where(x => x.StoreId == storeId);- }- if (!string.IsNullOrEmpty(vendorId))- {- query = query.Where(x => x.VendorId == vendorId);- }- if (!string.IsNullOrEmpty(trackingNumber))- query = query.Where(s => s.TrackingNumber.Contains(trackingNumber));-- if (loadNotShipped)- query = query.Where(s => !s.ShippedDateUtc.HasValue);- if (createdFromUtc.HasValue)- query = query.Where(s => createdFromUtc.Value <= s.CreatedOnUtc);- if (createdToUtc.HasValue)- query = query.Where(s => createdToUtc.Value >= s.CreatedOnUtc);-- query = query.OrderByDescending(x => x.CreatedOnUtc);- var shipments = await PagedList<Shipment>.Create(query, pageIndex, pageSize);- return shipments;-- }-- /// <summary>- /// Get shipment by identifiers- /// </summary>- /// <param name="shipmentIds">Shipment identifiers</param>- /// <returns>Shipments</returns>- public virtual async Task<IList<Shipment>> GetShipmentsByIds(string[] shipmentIds)- {- if (shipmentIds == null || shipmentIds.Length == 0)- return new List<Shipment>();-- var query = from o in _shipmentRepository.Table- where shipmentIds.Contains(o.Id)- select o;- return await Task.FromResult(query.ToList());- }--- public virtual async Task<IList<Shipment>> GetShipmentsByOrder(string orderId)- {- return await Task.FromResult(_shipmentRepository.Table.Where(x => x.OrderId == orderId).ToList());- }-- /// <summary>- /// Gets a shipment- /// </summary>- /// <param name="shipmentId">Shipment identifier</param>- /// <returns>Shipment</returns>- public virtual Task<Shipment> GetShipmentById(string shipmentId)- {- return _shipmentRepository.GetByIdAsync(shipmentId);- }-- /// <summary>- /// Inserts a shipment- /// </summary>- /// <param name="shipment">Shipment</param>- public virtual async Task InsertShipment(Shipment shipment)- {- ArgumentNullException.ThrowIfNull(shipment);- var shipmentExists = _shipmentRepository.Table.FirstOrDefault();- shipment.ShipmentNumber = shipmentExists != null ? _shipmentRepository.Table.Max(x => x.ShipmentNumber) + 1 : 1;- await _shipmentRepository.InsertAsync(shipment);-- //event notification- await _mediator.EntityInserted(shipment);- }-- /// <summary>- /// Updates the shipment- /// </summary>- /// <param name="shipment">Shipment</param>- public virtual async Task UpdateShipment(Shipment shipment)- {- ArgumentNullException.ThrowIfNull(shipment);-- await _shipmentRepository.UpdateAsync(shipment);-- //event notification- await _mediator.EntityUpdated(shipment);- }-- /// <summary>- /// Deletes a shipment- /// </summary>- /// <param name="shipment">Shipment</param>- public virtual async Task DeleteShipment(Shipment shipment)- {- ArgumentNullException.ThrowIfNull(shipment);-- await _shipmentRepository.DeleteAsync(shipment);-- //event notification- await _mediator.EntityDeleted(shipment);- }-- #region Shipment notes-- /// <summary>- /// Deletes an order note- /// </summary>- /// <param name="shipmentNote">The order note</param>- public virtual async Task DeleteShipmentNote(ShipmentNote shipmentNote)- {- ArgumentNullException.ThrowIfNull(shipmentNote);-- await _shipmentNoteRepository.DeleteAsync(shipmentNote);-- //event notification- await _mediator.EntityDeleted(shipmentNote);- }-- /// <summary>- /// Deletes an shipment note- /// </summary>- /// <param name="shipmentNote">The shipment note</param>- public virtual async Task InsertShipmentNote(ShipmentNote shipmentNote)- {- ArgumentNullException.ThrowIfNull(shipmentNote);-- await _shipmentNoteRepository.InsertAsync(shipmentNote);-- //event notification- await _mediator.EntityInserted(shipmentNote);- }-- public virtual async Task<IList<ShipmentNote>> GetShipmentNotes(string shipmentId)- {- var query = from shipmentNote in _shipmentNoteRepository.Table- where shipmentNote.ShipmentId == shipmentId- orderby shipmentNote.CreatedOnUtc descending- select shipmentNote;-- return await Task.FromResult(query.ToList());- }-- /// <summary>- /// Get shipment note by id- /// </summary>- /// <param name="shipmentNoteId">Shipment note identifier</param>- /// <returns>shipmentNote</returns>- public virtual Task<ShipmentNote> GetShipmentNote(string shipmentNoteId)- {- return Task.FromResult(_shipmentNoteRepository.Table.FirstOrDefault(x => x.Id == shipmentNoteId));- }- #endregion-- #endregion+ if (shipmentIds == null || shipmentIds.Length == 0)+ return new List<Shipment>();++ var query = from o in _shipmentRepository.Table+ where shipmentIds.Contains(o.Id)+ select o;+ return await Task.FromResult(query.ToList());+ }+++ public virtual async Task<IList<Shipment>> GetShipmentsByOrder(string orderId)+ {+ return await Task.FromResult(_shipmentRepository.Table.Where(x => x.OrderId == orderId).ToList());+ }++ /// <summary>+ /// Gets a shipment+ /// </summary>+ /// <param name="shipmentId">Shipment identifier</param>+ /// <returns>Shipment</returns>+ public virtual Task<Shipment> GetShipmentById(string shipmentId)+ {+ return _shipmentRepository.GetByIdAsync(shipmentId);}-}++ /// <summary>+ /// Inserts a shipment+ /// </summary>+ /// <param name="shipment">Shipment</param>+ public virtual async Task InsertShipment(Shipment shipment)+ {+ ArgumentNullException.ThrowIfNull(shipment);+ var shipmentExists = _shipmentRepository.Table.FirstOrDefault();+ shipment.ShipmentNumber = shipmentExists != null ? _shipmentRepository.Table.Max(x => x.ShipmentNumber) + 1 : 1;+ await _shipmentRepository.InsertAsync(shipment);++ //event notification+ await _mediator.EntityInserted(shipment);+ }++ /// <summary>+ /// Updates the shipment+ /// </summary>+ /// <param name="shipment">Shipment</param>+ public virtual async Task UpdateShipment(Shipment shipment)+ {+ ArgumentNullException.ThrowIfNull(shipment);++ await _shipmentRepository.UpdateAsync(shipment);++ //event notification+ await _mediator.EntityUpdated(shipment);+ }++ /// <summary>+ /// Deletes a shipment+ /// </summary>+ /// <param name="shipment">Shipment</param>+ public virtual async Task DeleteShipment(Shipment shipment)+ {+ ArgumentNullException.ThrowIfNull(shipment);++ await _shipmentRepository.DeleteAsync(shipment);++ //event notification+ await _mediator.EntityDeleted(shipment);+ }++ #region Shipment notes++ /// <summary>+ /// Deletes an order note+ /// </summary>+ /// <param name="shipmentNote">The order note</param>+ public virtual async Task DeleteShipmentNote(ShipmentNote shipmentNote)+ {+ ArgumentNullException.ThrowIfNull(shipmentNote);++ await _shipmentNoteRepository.DeleteAsync(shipmentNote);++ //event notification+ await _mediator.EntityDeleted(shipmentNote);+ }++ /// <summary>+ /// Deletes an shipment note+ /// </summary>+ /// <param name="shipmentNote">The shipment note</param>+ public virtual async Task InsertShipmentNote(ShipmentNote shipmentNote)+ {+ ArgumentNullException.ThrowIfNull(shipmentNote);++ await _shipmentNoteRepository.InsertAsync(shipmentNote);++ //event notification+ await _mediator.EntityInserted(shipmentNote);+ }++ public virtual async Task<IList<ShipmentNote>> GetShipmentNotes(string shipmentId)+ {+ var query = from shipmentNote in _shipmentNoteRepository.Table+ where shipmentNote.ShipmentId == shipmentId+ orderby shipmentNote.CreatedOnUtc descending+ select shipmentNote;++ return await Task.FromResult(query.ToList());+ }++ /// <summary>+ /// Get shipment note by id+ /// </summary>+ /// <param name="shipmentNoteId">Shipment note identifier</param>+ /// <returns>shipmentNote</returns>+ public virtual Task<ShipmentNote> GetShipmentNote(string shipmentNoteId)+ {+ return Task.FromResult(_shipmentNoteRepository.Table.FirstOrDefault(x => x.Id == shipmentNoteId));+ }++ #endregion++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.csindex 52f92b965..e71fcaf67 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs@@ -1,135 +1,131 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Data;+using Grand.Domain.Customers;+using Grand.Domain.Shipping;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Domain.Customers;-using Grand.Data;-using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Services.Shipping+namespace Grand.Business.Checkout.Services.Shipping;++public class ShippingMethodService : IShippingMethodService{- public class ShippingMethodService : IShippingMethodService+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ public ShippingMethodService(+ IRepository<ShippingMethod> shippingMethodRepository,+ IMediator mediator,+ ICacheBase cacheBase){- #region Fields-- private readonly IRepository<ShippingMethod> _shippingMethodRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;+ _shippingMethodRepository = shippingMethodRepository;+ _mediator = mediator;+ _cacheBase = cacheBase;+ }- #endregion+ #endregion- #region Ctor+ #region Fields- /// <summary>- /// Ctor- /// </summary>- public ShippingMethodService(- IRepository<ShippingMethod> shippingMethodRepository,- IMediator mediator,- ICacheBase cacheBase)- {- _shippingMethodRepository = shippingMethodRepository;- _mediator = mediator;- _cacheBase = cacheBase;- }+ private readonly IRepository<ShippingMethod> _shippingMethodRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;- #endregion+ #endregion- #region Shipping methods+ #region Shipping methods+ /// <summary>+ /// Deletes a shipping method+ /// </summary>+ /// <param name="shippingMethod">The shipping method</param>+ public virtual async Task DeleteShippingMethod(ShippingMethod shippingMethod)+ {+ ArgumentNullException.ThrowIfNull(shippingMethod);- /// <summary>- /// Deletes a shipping method- /// </summary>- /// <param name="shippingMethod">The shipping method</param>- public virtual async Task DeleteShippingMethod(ShippingMethod shippingMethod)- {- ArgumentNullException.ThrowIfNull(shippingMethod);+ await _shippingMethodRepository.DeleteAsync(shippingMethod);- await _shippingMethodRepository.DeleteAsync(shippingMethod);+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY);+ //event notification+ await _mediator.EntityDeleted(shippingMethod);+ }- //event notification- await _mediator.EntityDeleted(shippingMethod);- }+ /// <summary>+ /// Gets a shipping method+ /// </summary>+ /// <param name="shippingMethodId">The shipping method identifier</param>+ /// <returns>Shipping method</returns>+ public virtual Task<ShippingMethod> GetShippingMethodById(string shippingMethodId)+ {+ var key = string.Format(CacheKey.SHIPPINGMETHOD_BY_ID_KEY, shippingMethodId);+ return _cacheBase.GetAsync(key, () => _shippingMethodRepository.GetByIdAsync(shippingMethodId));+ }- /// <summary>- /// Gets a shipping method- /// </summary>- /// <param name="shippingMethodId">The shipping method identifier</param>- /// <returns>Shipping method</returns>- public virtual Task<ShippingMethod> GetShippingMethodById(string shippingMethodId)- {- var key = string.Format(CacheKey.SHIPPINGMETHOD_BY_ID_KEY, shippingMethodId);- return _cacheBase.GetAsync(key, () => _shippingMethodRepository.GetByIdAsync(shippingMethodId));- }-- /// <summary>- /// Gets all shipping methods- /// </summary>- /// <param name="filterByCountryId">The country ident to filter by</param>- /// <param name="customer"></param>- /// <returns>Shipping methods</returns>- public virtual async Task<IList<ShippingMethod>> GetAllShippingMethods(string filterByCountryId = "", Customer customer = null)- {- var shippingMethods = await _cacheBase.GetAsync(CacheKey.SHIPPINGMETHOD_ALL, async () =>- {- var query = from sm in _shippingMethodRepository.Table- orderby sm.DisplayOrder- select sm;- return await Task.FromResult(query.ToList());- });-- if (!string.IsNullOrEmpty(filterByCountryId))- {- shippingMethods = shippingMethods.Where(x => !x.CountryRestrictionExists(filterByCountryId)).ToList();- }- if (customer != null)- {- shippingMethods = shippingMethods.Where(x => !x.CustomerGroupRestrictionExists(customer.Groups.Select(y => y).ToList())).ToList();- }-- return shippingMethods;- }-- /// <summary>- /// Inserts a shipping method- /// </summary>- /// <param name="shippingMethod">Shipping method</param>- public virtual async Task InsertShippingMethod(ShippingMethod shippingMethod)+ /// <summary>+ /// Gets all shipping methods+ /// </summary>+ /// <param name="filterByCountryId">The country ident to filter by</param>+ /// <param name="customer"></param>+ /// <returns>Shipping methods</returns>+ public virtual async Task<IList<ShippingMethod>> GetAllShippingMethods(string filterByCountryId = "",+ Customer customer = null)+ {+ var shippingMethods = await _cacheBase.GetAsync(CacheKey.SHIPPINGMETHOD_ALL, async () =>{- ArgumentNullException.ThrowIfNull(shippingMethod);+ var query = from sm in _shippingMethodRepository.Table+ orderby sm.DisplayOrder+ select sm;+ return await Task.FromResult(query.ToList());+ });++ if (!string.IsNullOrEmpty(filterByCountryId))+ shippingMethods = shippingMethods.Where(x => !x.CountryRestrictionExists(filterByCountryId)).ToList();+ if (customer != null)+ shippingMethods = shippingMethods+ .Where(x => !x.CustomerGroupRestrictionExists(customer.Groups.Select(y => y).ToList())).ToList();++ return shippingMethods;+ }- await _shippingMethodRepository.InsertAsync(shippingMethod);+ /// <summary>+ /// Inserts a shipping method+ /// </summary>+ /// <param name="shippingMethod">Shipping method</param>+ public virtual async Task InsertShippingMethod(ShippingMethod shippingMethod)+ {+ ArgumentNullException.ThrowIfNull(shippingMethod);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY);+ await _shippingMethodRepository.InsertAsync(shippingMethod);- //event notification- await _mediator.EntityInserted(shippingMethod);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY);- /// <summary>- /// Updates the shipping method- /// </summary>- /// <param name="shippingMethod">Shipping method</param>- public virtual async Task UpdateShippingMethod(ShippingMethod shippingMethod)- {- ArgumentNullException.ThrowIfNull(shippingMethod);+ //event notification+ await _mediator.EntityInserted(shippingMethod);+ }- await _shippingMethodRepository.UpdateAsync(shippingMethod);+ /// <summary>+ /// Updates the shipping method+ /// </summary>+ /// <param name="shippingMethod">Shipping method</param>+ public virtual async Task UpdateShippingMethod(ShippingMethod shippingMethod)+ {+ ArgumentNullException.ThrowIfNull(shippingMethod);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY);+ await _shippingMethodRepository.UpdateAsync(shippingMethod);- //event notification- await _mediator.EntityUpdated(shippingMethod);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.SHIPPINGMETHOD_PATTERN_KEY);- #endregion+ //event notification+ await _mediator.EntityUpdated(shippingMethod);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.csindex 8bfed5f0e..4aeee8ca9 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs@@ -1,6 +1,6 @@using Grand.Business.Core.Interfaces.Checkout.Shipping;-using Grand.Business.Core.Utilities.Checkout;using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Utilities.Checkout;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Orders;@@ -10,217 +10,224 @@ using Grand.Infrastructure.Extensions;using Grand.SharedKernel;using Microsoft.Extensions.Logging;-namespace Grand.Business.Checkout.Services.Shipping+namespace Grand.Business.Checkout.Services.Shipping;++/// <summary>+/// Shipping service+/// </summary>+public class ShippingService : IShippingService{+ #region Ctor+/// <summary>- /// Shipping service+ /// Ctor/// </summary>- public class ShippingService : IShippingService+ public ShippingService(+ ILogger<ShippingService> logger,+ ICountryService countryService,+ IEnumerable<IShippingRateCalculationProvider> shippingRateCalculationProvider,+ ShippingProviderSettings shippingProviderSettings,+ ShippingSettings shippingSettings){- #region Fields-- private readonly ILogger<ShippingService> _logger;- private readonly ICountryService _countryService;- private readonly IEnumerable<IShippingRateCalculationProvider> _shippingRateCalculationProvider;- private readonly ShippingSettings _shippingSettings;- private readonly ShippingProviderSettings _shippingProviderSettings;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- public ShippingService(- ILogger<ShippingService> logger,- ICountryService countryService,- IEnumerable<IShippingRateCalculationProvider> shippingRateCalculationProvider,- ShippingProviderSettings shippingProviderSettings,- ShippingSettings shippingSettings)- {- _logger = logger;- _countryService = countryService;- _shippingRateCalculationProvider = shippingRateCalculationProvider;- _shippingProviderSettings = shippingProviderSettings;- _shippingSettings = shippingSettings;- }+ _logger = logger;+ _countryService = countryService;+ _shippingRateCalculationProvider = shippingRateCalculationProvider;+ _shippingProviderSettings = shippingProviderSettings;+ _shippingSettings = shippingSettings;+ }- #endregion+ #endregion- #region Shipping rate methods+ #region Fields- /// <summary>- /// Load active Shipping rate methods- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="storeId">Store ident</param>- /// <param name="cart">Cart</param>- /// <returns>Shipping rate methods</returns>- public virtual async Task<IList<IShippingRateCalculationProvider>> LoadActiveShippingRateCalculationProviders(Customer customer = null, string storeId = "", IList<ShoppingCartItem> cart = null)- {- var shippingMethods = LoadAllShippingRateCalculationProviders(customer, storeId)- .Where(provider => _shippingProviderSettings.ActiveSystemNames.Contains(provider.SystemName, StringComparer.OrdinalIgnoreCase))- .ToList();+ private readonly ILogger<ShippingService> _logger;+ private readonly ICountryService _countryService;+ private readonly IEnumerable<IShippingRateCalculationProvider> _shippingRateCalculationProvider;+ private readonly ShippingSettings _shippingSettings;+ private readonly ShippingProviderSettings _shippingProviderSettings;++ #endregion++ #region Shipping rate methods++ /// <summary>+ /// Load active Shipping rate methods+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="storeId">Store ident</param>+ /// <param name="cart">Cart</param>+ /// <returns>Shipping rate methods</returns>+ public virtual async Task<IList<IShippingRateCalculationProvider>> LoadActiveShippingRateCalculationProviders(+ Customer customer = null, string storeId = "", IList<ShoppingCartItem> cart = null)+ {+ var shippingMethods = LoadAllShippingRateCalculationProviders(customer, storeId)+ .Where(provider =>+ _shippingProviderSettings.ActiveSystemNames.Contains(provider.SystemName,+ StringComparer.OrdinalIgnoreCase))+ .ToList();++ var availableShippingMethods = new List<IShippingRateCalculationProvider>();+ foreach (var sm in shippingMethods)+ if (!await sm.HideShipmentMethods(cart))+ availableShippingMethods.Add(sm);+ return availableShippingMethods;+ }++ /// <summary>+ /// Load Shipping rate method by system name+ /// </summary>+ /// <param name="systemName">System name</param>+ /// <returns>Found Shipping rate method</returns>+ public virtual IShippingRateCalculationProvider LoadShippingRateCalculationProviderBySystemName(string systemName)+ {+ return _shippingRateCalculationProvider.FirstOrDefault(x => x.SystemName == systemName);+ }++ /// <summary>+ /// Load all Shipping rate methods+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="storeId">Store ident</param>+ /// <returns>Shipping rate methods</returns>+ public virtual IList<IShippingRateCalculationProvider> LoadAllShippingRateCalculationProviders(+ Customer customer = null, string storeId = "")+ {+ return _shippingRateCalculationProvider+ .Where(x =>+ x.IsAuthenticateStore(storeId) &&+ x.IsAuthenticateGroup(customer)).OrderBy(x => x.Priority).ToList();+ }++ #endregion- var availableShippingMethods = new List<IShippingRateCalculationProvider>();- foreach (var sm in shippingMethods)- {- if (!await sm.HideShipmentMethods(cart))- availableShippingMethods.Add(sm);- }- return availableShippingMethods;- }- /// <summary>- /// Load Shipping rate method by system name- /// </summary>- /// <param name="systemName">System name</param>- /// <returns>Found Shipping rate method</returns>- public virtual IShippingRateCalculationProvider LoadShippingRateCalculationProviderBySystemName(string systemName)+ #region Workflow++ /// <summary>+ /// Create shipment packages (requests) from shopping cart+ /// </summary>+ /// <param name="customer">Customer</param>+ /// <param name="cart">Shopping cart</param>+ /// <param name="shippingAddress">Shipping address</param>+ /// <param name="store">Store</param>+ /// <returns>Shipment packages (requests)</returns>+ public virtual async Task<GetShippingOptionRequest> CreateShippingOptionRequests(Customer customer,+ IList<ShoppingCartItem> cart, Address shippingAddress, Store store)+ {+ var request = new GetShippingOptionRequest {+ //store+ StoreId = store?.Id,+ //customer+ Customer = customer,++ //ship to+ ShippingAddress = shippingAddress+ };+ //ship from+ var originAddress = _shippingSettings.ShippingOriginAddress;++ if (originAddress != null){- return _shippingRateCalculationProvider.FirstOrDefault(x => x.SystemName == systemName);+ var country = await _countryService.GetCountryById(originAddress.CountryId);+ var state = country?.StateProvinces.FirstOrDefault(x => x.Id == originAddress.StateProvinceId);+ request.CountryFrom = country;+ request.StateProvinceFrom = state;+ request.ZipPostalCodeFrom = originAddress.ZipPostalCode;+ request.CityFrom = originAddress.City;+ request.AddressFrom = originAddress.Address1;}- /// <summary>- /// Load all Shipping rate methods- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="storeId">Store ident</param>- /// <returns>Shipping rate methods</returns>- public virtual IList<IShippingRateCalculationProvider> LoadAllShippingRateCalculationProviders(Customer customer = null, string storeId = "")+ foreach (var sci in cart){- return _shippingRateCalculationProvider- .Where(x =>- x.IsAuthenticateStore(storeId) &&- x.IsAuthenticateGroup(customer)).OrderBy(x => x.Priority).ToList();+ if (!sci.IsShipEnabled)+ continue;+ //add item+ request.Items.Add(new GetShippingOptionRequest.PackageItem(sci));}- #endregion+ return request;+ }+ /// <summary>+ /// Gets available shipping options+ /// </summary>+ /// <param name="customer"></param>+ /// <param name="cart">Shopping cart</param>+ /// <param name="shippingAddress">Shipping address</param>+ /// <param name="allowedShippingRateMethodSystemName">+ /// Filter by Shipping rate method identifier; null to load shipping+ /// options of all Shipping rate methods+ /// </param>+ /// <param name="store">Store</param>+ /// <returns>Shipping options</returns>+ public virtual async Task<GetShippingOptionResponse> GetShippingOptions(Customer customer,+ IList<ShoppingCartItem> cart,+ Address shippingAddress, string allowedShippingRateMethodSystemName = "",+ Store store = null)+ {+ ArgumentNullException.ThrowIfNull(cart);- #region Workflow+ var result = new GetShippingOptionResponse();- /// <summary>- /// Create shipment packages (requests) from shopping cart- /// </summary>- /// <param name="customer">Customer</param>- /// <param name="cart">Shopping cart</param>- /// <param name="shippingAddress">Shipping address</param>- /// <param name="store">Store</param>- /// <returns>Shipment packages (requests)</returns>- public virtual async Task<GetShippingOptionRequest> CreateShippingOptionRequests(Customer customer,- IList<ShoppingCartItem> cart, Address shippingAddress, Store store)- {- var request = new GetShippingOptionRequest {- //store- StoreId = store?.Id,- //customer- Customer = customer,-- //ship to- ShippingAddress = shippingAddress- };- //ship from- Address originAddress = _shippingSettings.ShippingOriginAddress;-- if (originAddress != null)- {- var country = await _countryService.GetCountryById(originAddress.CountryId);- var state = country?.StateProvinces.FirstOrDefault(x => x.Id == originAddress.StateProvinceId);- request.CountryFrom = country;- request.StateProvinceFrom = state;- request.ZipPostalCodeFrom = originAddress.ZipPostalCode;- request.CityFrom = originAddress.City;- request.AddressFrom = originAddress.Address1;- }- foreach (var sci in cart)- {- if (!sci.IsShipEnabled)- continue;- //add item- request.Items.Add(new GetShippingOptionRequest.PackageItem(sci));- }+ //create a package+ var shippingOptionRequest = await CreateShippingOptionRequests(customer, cart, shippingAddress, store);- return request;- }+ var shippingRateMethods = await LoadActiveShippingRateCalculationProviders(customer, store?.Id, cart);+ //filter by system name+ if (!string.IsNullOrWhiteSpace(allowedShippingRateMethodSystemName))+ shippingRateMethods = shippingRateMethods+ .Where(srcm =>+ allowedShippingRateMethodSystemName.Equals(srcm.SystemName, StringComparison.OrdinalIgnoreCase))+ .ToList();+ if (!shippingRateMethods.Any())+ throw new GrandException("Shipping rate method could not be loaded");- /// <summary>- /// Gets available shipping options- /// </summary>- /// <param name="customer"></param>- /// <param name="cart">Shopping cart</param>- /// <param name="shippingAddress">Shipping address</param>- /// <param name="allowedShippingRateMethodSystemName">Filter by Shipping rate method identifier; null to load shipping options of all Shipping rate methods</param>- /// <param name="store">Store</param>- /// <returns>Shipping options</returns>- public virtual async Task<GetShippingOptionResponse> GetShippingOptions(Customer customer, IList<ShoppingCartItem> cart,- Address shippingAddress, string allowedShippingRateMethodSystemName = "",- Store store = null)+ //request shipping options from each Shipping rate methods+ foreach (var shippingRateMethod in shippingRateMethods){- ArgumentNullException.ThrowIfNull(cart);+ //request shipping options (separately for each package-request)+ IList<ShippingOption> shippingRateMethodOptions;+ var getShippingOptionResponse = await shippingRateMethod.GetShippingOptions(shippingOptionRequest);- var result = new GetShippingOptionResponse();-- //create a package- var shippingOptionRequest = await CreateShippingOptionRequests(customer, cart, shippingAddress, store);-- var shippingRateMethods = await LoadActiveShippingRateCalculationProviders(customer, store?.Id, cart);- //filter by system name- if (!string.IsNullOrWhiteSpace(allowedShippingRateMethodSystemName))+ if (getShippingOptionResponse.Success){- shippingRateMethods = shippingRateMethods- .Where(srcm => allowedShippingRateMethodSystemName.Equals(srcm.SystemName, StringComparison.OrdinalIgnoreCase))- .ToList();+ //success+ shippingRateMethodOptions = getShippingOptionResponse.ShippingOptions;}- if (!shippingRateMethods.Any())- throw new GrandException("Shipping rate method could not be loaded");-- //request shipping options from each Shipping rate methods- foreach (var shippingRateMethod in shippingRateMethods)+ else{- //request shipping options (separately for each package-request)- IList<ShippingOption> shippingRateMethodOptions;- var getShippingOptionResponse = await shippingRateMethod.GetShippingOptions(shippingOptionRequest);-- if (getShippingOptionResponse.Success)+ //errors+ foreach (var error in getShippingOptionResponse.Errors){- //success- shippingRateMethodOptions = getShippingOptionResponse.ShippingOptions;+ result.AddError(error);+ _logger.LogWarning("Shipping ({FriendlyName}) {Error}", shippingRateMethod.FriendlyName, error);}- else- {- //errors- foreach (var error in getShippingOptionResponse.Errors)- {- result.AddError(error);- _logger.LogWarning("Shipping ({FriendlyName}) {Error}", shippingRateMethod.FriendlyName, error);- }- //clear the shipping options in this case- break;- }- if (shippingRateMethodOptions == null) continue;- foreach (var so in shippingRateMethodOptions)- {- //set system name if not set yet- if (string.IsNullOrEmpty(so.ShippingRateProviderSystemName))- so.ShippingRateProviderSystemName = shippingRateMethod.SystemName;- result.ShippingOptions.Add(so);- }+ //clear the shipping options in this case+ break;}- //return valid options if there are any (no matter of the errors returned by other shipping rate computation methods).- if (!result.ShippingOptions.Any() && !result.Errors.Any())- result.Errors.Clear();-- //no shipping options loaded- if (result.ShippingOptions.Count == 0 && result.Errors.Count == 0)- result.Errors.Add("Shipping options could not be loaded");+ if (shippingRateMethodOptions == null) continue;+ foreach (var so in shippingRateMethodOptions)+ {+ //set system name if not set yet+ if (string.IsNullOrEmpty(so.ShippingRateProviderSystemName))+ so.ShippingRateProviderSystemName = shippingRateMethod.SystemName;- return result;+ result.ShippingOptions.Add(so);+ }}- #endregion+ //return valid options if there are any (no matter of the errors returned by other shipping rate computation methods).+ if (!result.ShippingOptions.Any() && !result.Errors.Any())+ result.Errors.Clear();++ //no shipping options loaded+ if (result.ShippingOptions.Count == 0 && result.Errors.Count == 0)+ result.Errors.Add("Shipping options could not be loaded");++ return result;}++ #endregion}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.csindex 6d2f7f3d4..15d12b870 100644--- a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs@@ -1,120 +1,120 @@using Grand.Business.Core.Interfaces.Checkout.Shipping;+using Grand.Data;+using Grand.Domain.Shipping;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;-using Grand.Data;-using Grand.Domain.Shipping;using MediatR;-namespace Grand.Business.Checkout.Services.Shipping+namespace Grand.Business.Checkout.Services.Shipping;++public class WarehouseService : IWarehouseService{- public class WarehouseService : IWarehouseService+ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ public WarehouseService(+ IRepository<Warehouse> warehouseRepository,+ IMediator mediator,+ ICacheBase cacheBase){- #region Fields+ _warehouseRepository = warehouseRepository;+ _mediator = mediator;+ _cacheBase = cacheBase;+ }- private readonly IRepository<Warehouse> _warehouseRepository;- private readonly IMediator _mediator;- private readonly ICacheBase _cacheBase;+ #endregion- #endregion+ #region Fields- #region Ctor+ private readonly IRepository<Warehouse> _warehouseRepository;+ private readonly IMediator _mediator;+ private readonly ICacheBase _cacheBase;- /// <summary>- /// Ctor- /// </summary>- public WarehouseService(- IRepository<Warehouse> warehouseRepository,- IMediator mediator,- ICacheBase cacheBase)- {- _warehouseRepository = warehouseRepository;- _mediator = mediator;- _cacheBase = cacheBase;- }+ #endregion- #endregion+ #region Warehouses- #region Warehouses+ /// <summary>+ /// Gets a warehouse+ /// </summary>+ /// <param name="warehouseId">The warehouse identifier</param>+ /// <returns>Warehouse</returns>+ public virtual Task<Warehouse> GetWarehouseById(string warehouseId)+ {+ var key = string.Format(CacheKey.WAREHOUSES_BY_ID_KEY, warehouseId);+ return _cacheBase.GetAsync(key, () => _warehouseRepository.GetByIdAsync(warehouseId));+ }- /// <summary>- /// Gets a warehouse- /// </summary>- /// <param name="warehouseId">The warehouse identifier</param>- /// <returns>Warehouse</returns>- public virtual Task<Warehouse> GetWarehouseById(string warehouseId)- {- var key = string.Format(CacheKey.WAREHOUSES_BY_ID_KEY, warehouseId);- return _cacheBase.GetAsync(key, () => _warehouseRepository.GetByIdAsync(warehouseId));- }-- /// <summary>- /// Gets all warehouses- /// </summary>- /// <returns>Warehouses</returns>- public virtual async Task<IList<Warehouse>> GetAllWarehouses()- {- return await _cacheBase.GetAsync(CacheKey.WAREHOUSES_ALL, async () =>- {- var query = from wh in _warehouseRepository.Table- orderby wh.DisplayOrder- select wh;- return await Task.FromResult(query.ToList());- });- }-- /// <summary>- /// Inserts a warehouse- /// </summary>- /// <param name="warehouse">Warehouse</param>- public virtual async Task InsertWarehouse(Warehouse warehouse)+ /// <summary>+ /// Gets all warehouses+ /// </summary>+ /// <returns>Warehouses</returns>+ public virtual async Task<IList<Warehouse>> GetAllWarehouses()+ {+ return await _cacheBase.GetAsync(CacheKey.WAREHOUSES_ALL, async () =>{- ArgumentNullException.ThrowIfNull(warehouse);+ var query = from wh in _warehouseRepository.Table+ orderby wh.DisplayOrder+ select wh;+ return await Task.FromResult(query.ToList());+ });+ }- await _warehouseRepository.InsertAsync(warehouse);+ /// <summary>+ /// Inserts a warehouse+ /// </summary>+ /// <param name="warehouse">Warehouse</param>+ public virtual async Task InsertWarehouse(Warehouse warehouse)+ {+ ArgumentNullException.ThrowIfNull(warehouse);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.WAREHOUSES_PATTERN_KEY);+ await _warehouseRepository.InsertAsync(warehouse);- //event notification- await _mediator.EntityInserted(warehouse);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.WAREHOUSES_PATTERN_KEY);- /// <summary>- /// Updates the warehouse- /// </summary>- /// <param name="warehouse">Warehouse</param>- public virtual async Task UpdateWarehouse(Warehouse warehouse)- {- ArgumentNullException.ThrowIfNull(warehouse);+ //event notification+ await _mediator.EntityInserted(warehouse);+ }- await _warehouseRepository.UpdateAsync(warehouse);+ /// <summary>+ /// Updates the warehouse+ /// </summary>+ /// <param name="warehouse">Warehouse</param>+ public virtual async Task UpdateWarehouse(Warehouse warehouse)+ {+ ArgumentNullException.ThrowIfNull(warehouse);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.WAREHOUSES_PATTERN_KEY);+ await _warehouseRepository.UpdateAsync(warehouse);- //event notification- await _mediator.EntityUpdated(warehouse);- }+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.WAREHOUSES_PATTERN_KEY);- /// <summary>- /// Deletes a warehouse- /// </summary>- /// <param name="warehouse">The warehouse</param>- public virtual async Task DeleteWarehouse(Warehouse warehouse)- {- ArgumentNullException.ThrowIfNull(warehouse);+ //event notification+ await _mediator.EntityUpdated(warehouse);+ }- await _warehouseRepository.DeleteAsync(warehouse);+ /// <summary>+ /// Deletes a warehouse+ /// </summary>+ /// <param name="warehouse">The warehouse</param>+ public virtual async Task DeleteWarehouse(Warehouse warehouse)+ {+ ArgumentNullException.ThrowIfNull(warehouse);- //clear cache- await _cacheBase.RemoveByPrefix(CacheKey.WAREHOUSES_PATTERN_KEY);- //clear product cache- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);+ await _warehouseRepository.DeleteAsync(warehouse);- //event notification- await _mediator.EntityDeleted(warehouse);- }- #endregion+ //clear cache+ await _cacheBase.RemoveByPrefix(CacheKey.WAREHOUSES_PATTERN_KEY);+ //clear product cache+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);++ //event notification+ await _mediator.EntityDeleted(warehouse);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs b/src/Business/Grand.Business.Checkout/Startup/StartupApplication.csindex 0450b0104..9e1d39ff1 100644--- a/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs@@ -17,60 +17,61 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Business.Checkout.Startup+namespace Grand.Business.Checkout.Startup;++public class StartupApplication : IStartupApplication{- public class StartupApplication : IStartupApplication+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- RegisterOrdersService(services);- RegisterPaymentsService(services);- RegisterShippingService(services);- RegisterExportImport(services);- }- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {+ RegisterOrdersService(services);+ RegisterPaymentsService(services);+ RegisterShippingService(services);+ RegisterExportImport(services);+ }- }- public int Priority => 100;- public bool BeforeConfigure => false;+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ }+ public int Priority => 100;+ public bool BeforeConfigure => false;- private void RegisterOrdersService(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();- serviceCollection.AddScoped<IGiftVoucherService, GiftVoucherService>();- serviceCollection.AddScoped<IOrderService, OrderService>();- serviceCollection.AddScoped<IOrderStatusService, OrderStatusService>();- serviceCollection.AddScoped<IOrderCalculationService, OrderCalculationService>();- serviceCollection.AddScoped<IMerchandiseReturnService, MerchandiseReturnService>();- serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();- serviceCollection.AddScoped<IShoppingCartService, ShoppingCartService>();- serviceCollection.AddScoped<IShoppingCartValidator, ShoppingCartValidator>();- serviceCollection.AddScoped<ICheckoutAttributeFormatter, CheckoutAttributeFormatter>();- serviceCollection.AddScoped<ICheckoutAttributeParser, CheckoutAttributeParser>();- serviceCollection.AddScoped<ICheckoutAttributeService, CheckoutAttributeService>();- serviceCollection.AddScoped<IOrderTagService, OrderTagService>();- }- private void RegisterPaymentsService(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<IPaymentService, PaymentService>();- serviceCollection.AddScoped<IPaymentTransactionService, PaymentTransactionService>();- }- private void RegisterShippingService(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<IShipmentService, ShipmentService>();- serviceCollection.AddScoped<IShippingService, ShippingService>();- serviceCollection.AddScoped<IPickupPointService, PickupPointService>();- serviceCollection.AddScoped<IDeliveryDateService, DeliveryDateService>();- serviceCollection.AddScoped<IWarehouseService, WarehouseService>();- serviceCollection.AddScoped<IShippingMethodService, ShippingMethodService>();- }+ private void RegisterOrdersService(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();+ serviceCollection.AddScoped<IGiftVoucherService, GiftVoucherService>();+ serviceCollection.AddScoped<IOrderService, OrderService>();+ serviceCollection.AddScoped<IOrderStatusService, OrderStatusService>();+ serviceCollection.AddScoped<IOrderCalculationService, OrderCalculationService>();+ serviceCollection.AddScoped<IMerchandiseReturnService, MerchandiseReturnService>();+ serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();+ serviceCollection.AddScoped<IShoppingCartService, ShoppingCartService>();+ serviceCollection.AddScoped<IShoppingCartValidator, ShoppingCartValidator>();+ serviceCollection.AddScoped<ICheckoutAttributeFormatter, CheckoutAttributeFormatter>();+ serviceCollection.AddScoped<ICheckoutAttributeParser, CheckoutAttributeParser>();+ serviceCollection.AddScoped<ICheckoutAttributeService, CheckoutAttributeService>();+ serviceCollection.AddScoped<IOrderTagService, OrderTagService>();+ }- private void RegisterExportImport(IServiceCollection serviceCollection)- {- serviceCollection.AddScoped<ISchemaProperty<Order>, OrderSchemaProperty>();- }+ private void RegisterPaymentsService(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<IPaymentService, PaymentService>();+ serviceCollection.AddScoped<IPaymentTransactionService, PaymentTransactionService>();+ }++ private void RegisterShippingService(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<IShipmentService, ShipmentService>();+ serviceCollection.AddScoped<IShippingService, ShippingService>();+ serviceCollection.AddScoped<IPickupPointService, PickupPointService>();+ serviceCollection.AddScoped<IDeliveryDateService, DeliveryDateService>();+ serviceCollection.AddScoped<IWarehouseService, WarehouseService>();+ serviceCollection.AddScoped<IShippingMethodService, ShippingMethodService>();+ }++ private void RegisterExportImport(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<ISchemaProperty<Order>, OrderSchemaProperty>();}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.csindex 8e617d70d..2543c9b17 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs@@ -4,33 +4,28 @@ using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Orders;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartAuctionValidatorRecord(Customer Customer, Product Product, ShoppingCartItem ShoppingCartItem, double Bid);+public record ShoppingCartAuctionValidatorRecord(+ Customer Customer,+ Product Product,+ ShoppingCartItem ShoppingCartItem,+ double Bid);- public class ShoppingCartAuctionValidator : AbstractValidator<ShoppingCartAuctionValidatorRecord>+public class ShoppingCartAuctionValidator : AbstractValidator<ShoppingCartAuctionValidatorRecord>+{+ public ShoppingCartAuctionValidator(ITranslationService translationService){- public ShoppingCartAuctionValidator(ITranslationService translationService)+ RuleFor(x => x).Custom((value, context) =>{- RuleFor(x => x).Custom((value, context) =>- {- if (value.Bid <= value.Product.HighestBid || value.Bid <= value.Product.StartPrice)- {- context.AddFailure(translationService.GetResource("ShoppingCart.BidMustBeHigher"));- }-- if (!value.Product.AvailableEndDateTimeUtc.HasValue)- {- context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));- }+ if (value.Bid <= value.Product.HighestBid || value.Bid <= value.Product.StartPrice)+ context.AddFailure(translationService.GetResource("ShoppingCart.BidMustBeHigher"));- if (value.Product.AvailableEndDateTimeUtc < DateTime.UtcNow)- {- context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));- }- });- }+ if (!value.Product.AvailableEndDateTimeUtc.HasValue)+ context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));+ if (value.Product.AvailableEndDateTimeUtc < DateTime.UtcNow)+ context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.csindex 70f104d2e..e6427a5e2 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs@@ -7,85 +7,88 @@ using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.Domain.Stores;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartCheckoutAttributesValidatorRecord(Customer Customer, Store Store, IList<ShoppingCartItem> ShoppingCarts, IList<CustomAttribute> CheckoutAttributes);+public record ShoppingCartCheckoutAttributesValidatorRecord(+ Customer Customer,+ Store Store,+ IList<ShoppingCartItem> ShoppingCarts,+ IList<CustomAttribute> CheckoutAttributes);- public class ShoppingCartCheckoutAttributesValidator : AbstractValidator<ShoppingCartCheckoutAttributesValidatorRecord>+public class ShoppingCartCheckoutAttributesValidator : AbstractValidator<ShoppingCartCheckoutAttributesValidatorRecord>+{+ public ShoppingCartCheckoutAttributesValidator(ITranslationService translationService,+ ICheckoutAttributeParser checkoutAttributeParser, ICheckoutAttributeService checkoutAttributeService){- public ShoppingCartCheckoutAttributesValidator(ITranslationService translationService,- ICheckoutAttributeParser checkoutAttributeParser, ICheckoutAttributeService checkoutAttributeService)+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{+ //selected attributes+ var attributes1 = await checkoutAttributeParser.ParseCheckoutAttributes(value.CheckoutAttributes);- RuleFor(x => x).CustomAsync(async (value, context, _) =>+ //existing checkout attributes+ var attributes2 =+ await checkoutAttributeService.GetAllCheckoutAttributes(value.Store.Id,+ !value.ShoppingCarts.RequiresShipping());+ foreach (var a2 in attributes2){- //selected attributes- var attributes1 = await checkoutAttributeParser.ParseCheckoutAttributes(value.CheckoutAttributes);-- //existing checkout attributes- var attributes2 = await checkoutAttributeService.GetAllCheckoutAttributes(value.Store.Id, !value.ShoppingCarts.RequiresShipping());- foreach (var a2 in attributes2)+ var conditionMet = await checkoutAttributeParser.IsConditionMet(a2, value.CheckoutAttributes);+ if (!a2.IsRequired || ((!conditionMet.HasValue || !conditionMet.Value) && conditionMet.HasValue))+ continue;+ var found = false;+ //selected checkout attributes+ foreach (var a1 in attributes1){- var conditionMet = await checkoutAttributeParser.IsConditionMet(a2, value.CheckoutAttributes);- if (!a2.IsRequired || ((!conditionMet.HasValue || !conditionMet.Value) && conditionMet.HasValue))- continue;- var found = false;- //selected checkout attributes- foreach (var a1 in attributes1)- {- if (a1.Id != a2.Id) continue;- var attributeValuesStr = value.CheckoutAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);- foreach (var str1 in attributeValuesStr)- if (!string.IsNullOrEmpty(str1.Trim()))- {- found = true;- break;- }- }-- //if not found- if (!found)- {- context.AddFailure(a2.TextPrompt ?? string.Format(translationService.GetResource("ShoppingCart.SelectAttribute"), a2.Name));- }+ if (a1.Id != a2.Id) continue;+ var attributeValuesStr = value.CheckoutAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);+ foreach (var str1 in attributeValuesStr)+ if (!string.IsNullOrEmpty(str1.Trim()))+ {+ found = true;+ break;+ }}- //now validation rules+ //if not found+ if (!found)+ context.AddFailure(a2.TextPrompt ??+ string.Format(translationService.GetResource("ShoppingCart.SelectAttribute"),+ a2.Name));+ }- //minimum length- foreach (var ca in attributes2)- {- if (ca.ValidationMinLength.HasValue)- {- if (ca.AttributeControlTypeId is AttributeControlType.TextBox or AttributeControlType.MultilineTextbox)- {- var valuesStr = value.CheckoutAttributes.Where(x => x.Key == ca.Id).Select(x => x.Value);- var enteredText = valuesStr.FirstOrDefault();- var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;+ //now validation rules- if (ca.ValidationMinLength.Value > enteredTextLength)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.TextBoxMinimumLength"), ca.Name, ca.ValidationMinLength.Value));- }- }- }- //maximum length- if (!ca.ValidationMaxLength.HasValue) continue;+ //minimum length+ foreach (var ca in attributes2)+ {+ if (ca.ValidationMinLength.HasValue)+ if (ca.AttributeControlTypeId is AttributeControlType.TextBox+ or AttributeControlType.MultilineTextbox){- if (ca.AttributeControlTypeId != AttributeControlType.TextBox &&- ca.AttributeControlTypeId != AttributeControlType.MultilineTextbox) continue;var valuesStr = value.CheckoutAttributes.Where(x => x.Key == ca.Id).Select(x => x.Value);var enteredText = valuesStr.FirstOrDefault();var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;- if (ca.ValidationMaxLength.Value < enteredTextLength)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.TextBoxMaximumLength"), ca.Name, ca.ValidationMaxLength.Value));- }+ if (ca.ValidationMinLength.Value > enteredTextLength)+ context.AddFailure(string.Format(+ translationService.GetResource("ShoppingCart.TextBoxMinimumLength"), ca.Name,+ ca.ValidationMinLength.Value));}++ //maximum length+ if (!ca.ValidationMaxLength.HasValue) continue;+ {+ if (ca.AttributeControlTypeId != AttributeControlType.TextBox &&+ ca.AttributeControlTypeId != AttributeControlType.MultilineTextbox) continue;+ var valuesStr = value.CheckoutAttributes.Where(x => x.Key == ca.Id).Select(x => x.Value);+ var enteredText = valuesStr.FirstOrDefault();+ var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;++ if (ca.ValidationMaxLength.Value < enteredTextLength)+ context.AddFailure(string.Format(+ translationService.GetResource("ShoppingCart.TextBoxMaximumLength"), ca.Name,+ ca.ValidationMaxLength.Value));}- });- }+ }+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.csindex 7f1c73bc8..83f5c9c55 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs@@ -7,57 +7,61 @@ using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.Domain.Stores;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartCommonWarningsValidatorRecord(Customer Customer, Store Store, IList<ShoppingCartItem> ShoppingCarts,- Product Product, ShoppingCartType ShoppingCartType, DateTime? RentalStartDate, DateTime? RentalEndDate,- int Quantity, string ReservationId);+public record ShoppingCartCommonWarningsValidatorRecord(+ Customer Customer,+ Store Store,+ IList<ShoppingCartItem> ShoppingCarts,+ Product Product,+ ShoppingCartType ShoppingCartType,+ DateTime? RentalStartDate,+ DateTime? RentalEndDate,+ int Quantity,+ string ReservationId);- public class ShoppingCartCommonWarningsValidator : AbstractValidator<ShoppingCartCommonWarningsValidatorRecord>+public class ShoppingCartCommonWarningsValidator : AbstractValidator<ShoppingCartCommonWarningsValidatorRecord>+{+ public ShoppingCartCommonWarningsValidator(ITranslationService translationService,+ IPermissionService permissionService, ShoppingCartSettings shoppingCartSettings){- public ShoppingCartCommonWarningsValidator(ITranslationService translationService,- IPermissionService permissionService, ShoppingCartSettings shoppingCartSettings)+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{-- RuleFor(x => x).CustomAsync(async (value, context, _) =>+ //maximum items validation+ switch (value.ShoppingCartType){- //maximum items validation- switch (value.ShoppingCartType)+ case ShoppingCartType.ShoppingCart:{- case ShoppingCartType.ShoppingCart:- {- if (value.ShoppingCarts.Count >= shoppingCartSettings.MaximumShoppingCartItems)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.MaximumShoppingCartItems"), shoppingCartSettings.MaximumShoppingCartItems));- }- }- break;- case ShoppingCartType.Wishlist:- {- if (value.ShoppingCarts.Count >= shoppingCartSettings.MaximumWishlistItems)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.MaximumWishlistItems"), shoppingCartSettings.MaximumWishlistItems));- }- }- break;+ if (value.ShoppingCarts.Count >= shoppingCartSettings.MaximumShoppingCartItems)+ context.AddFailure(string.Format(+ translationService.GetResource("ShoppingCart.MaximumShoppingCartItems"),+ shoppingCartSettings.MaximumShoppingCartItems));}-- switch (value.ShoppingCartType)+ break;+ case ShoppingCartType.Wishlist:{- case ShoppingCartType.ShoppingCart when !await permissionService.Authorize(StandardPermission.EnableShoppingCart, value.Customer):- context.AddFailure("Shopping cart is disabled");- return;- case ShoppingCartType.Wishlist when !await permissionService.Authorize(StandardPermission.EnableWishlist, value.Customer):- context.AddFailure("Wishlist is disabled");- return;+ if (value.ShoppingCarts.Count >= shoppingCartSettings.MaximumWishlistItems)+ context.AddFailure(string.Format(+ translationService.GetResource("ShoppingCart.MaximumWishlistItems"),+ shoppingCartSettings.MaximumWishlistItems));}+ break;+ }- if (value.Quantity <= 0)- {- context.AddFailure(translationService.GetResource("ShoppingCart.QuantityShouldPositive"));- }- });- }+ switch (value.ShoppingCartType)+ {+ case ShoppingCartType.ShoppingCart+ when !await permissionService.Authorize(StandardPermission.EnableShoppingCart, value.Customer):+ context.AddFailure("Shopping cart is disabled");+ return;+ case ShoppingCartType.Wishlist+ when !await permissionService.Authorize(StandardPermission.EnableWishlist, value.Customer):+ context.AddFailure("Wishlist is disabled");+ return;+ }++ if (value.Quantity <= 0)+ context.AddFailure(translationService.GetResource("ShoppingCart.QuantityShouldPositive"));+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.csindex ea1631c50..a98e725c3 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartGiftVoucherValidator.cs@@ -5,40 +5,39 @@ using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.SharedKernel.Extensions;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartGiftVoucherValidatorRecord(Customer Customer, Product Product, ShoppingCartItem ShoppingCartItem);+public record ShoppingCartGiftVoucherValidatorRecord(+ Customer Customer,+ Product Product,+ ShoppingCartItem ShoppingCartItem);- public class ShoppingCartGiftVoucherValidator : AbstractValidator<ShoppingCartGiftVoucherValidatorRecord>+public class ShoppingCartGiftVoucherValidator : AbstractValidator<ShoppingCartGiftVoucherValidatorRecord>+{+ public ShoppingCartGiftVoucherValidator(ITranslationService translationService){- public ShoppingCartGiftVoucherValidator(ITranslationService translationService)+ RuleFor(x => x).Custom((value, context) =>{- RuleFor(x => x).Custom((value, context) =>- {- GiftVoucherExtensions.GetGiftVoucherAttribute(value.ShoppingCartItem.Attributes,- out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out _);-- if (string.IsNullOrEmpty(giftVoucherRecipientName))- context.AddFailure(translationService.GetResource("ShoppingCart.RecipientNameError"));+ GiftVoucherExtensions.GetGiftVoucherAttribute(value.ShoppingCartItem.Attributes,+ out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out _);- if (value.Product.GiftVoucherTypeId == GiftVoucherType.Virtual)- {- //validate for virtual gift vouchers only- if (string.IsNullOrEmpty(giftVoucherRecipientEmail) || !CommonHelper.IsValidEmail(giftVoucherRecipientEmail))- context.AddFailure(translationService.GetResource("ShoppingCart.RecipientEmailError"));- }+ if (string.IsNullOrEmpty(giftVoucherRecipientName))+ context.AddFailure(translationService.GetResource("ShoppingCart.RecipientNameError"));- if (string.IsNullOrEmpty(giftVoucherSenderName))- context.AddFailure(translationService.GetResource("ShoppingCart.SenderNameError"));-- if (value.Product.GiftVoucherTypeId != GiftVoucherType.Virtual) return;+ if (value.Product.GiftVoucherTypeId == GiftVoucherType.Virtual)//validate for virtual gift vouchers only- if (string.IsNullOrEmpty(giftVoucherSenderEmail) || !CommonHelper.IsValidEmail(giftVoucherSenderEmail))- context.AddFailure(translationService.GetResource("ShoppingCart.SenderEmailError"));- });- }-+ if (string.IsNullOrEmpty(giftVoucherRecipientEmail) ||+ !CommonHelper.IsValidEmail(giftVoucherRecipientEmail))+ context.AddFailure(translationService.GetResource("ShoppingCart.RecipientEmailError"));++ if (string.IsNullOrEmpty(giftVoucherSenderName))+ context.AddFailure(translationService.GetResource("ShoppingCart.SenderNameError"));++ if (value.Product.GiftVoucherTypeId != GiftVoucherType.Virtual) return;+ //validate for virtual gift vouchers only+ if (string.IsNullOrEmpty(giftVoucherSenderEmail) || !CommonHelper.IsValidEmail(giftVoucherSenderEmail))+ context.AddFailure(translationService.GetResource("ShoppingCart.SenderEmailError"));+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.csindex d15ce71d5..6373cdb78 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartInventoryProductValidator.cs@@ -5,146 +5,148 @@ using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Orders;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartInventoryProductValidatorRecord(Customer Customer, Product Product, ShoppingCartItem ShoppingCartItem);+public record ShoppingCartInventoryProductValidatorRecord(+ Customer Customer,+ Product Product,+ ShoppingCartItem ShoppingCartItem);- public class ShoppingCartInventoryProductValidator : AbstractValidator<ShoppingCartInventoryProductValidatorRecord>+public class ShoppingCartInventoryProductValidator : AbstractValidator<ShoppingCartInventoryProductValidatorRecord>+{+ public ShoppingCartInventoryProductValidator(ITranslationService translationService, IProductService productService,+ IStockQuantityService stockQuantityService, ShoppingCartSettings shoppingCartSettings){- public ShoppingCartInventoryProductValidator(ITranslationService translationService, IProductService productService,- IStockQuantityService stockQuantityService, ShoppingCartSettings shoppingCartSettings)+ RuleFor(x => x).CustomAsync(async (value, context, ct) =>{+ //quantity validation+ var hasQtyWarnings = false;+ if (value.ShoppingCartItem.Quantity < value.Product.OrderMinimumQuantity)+ {+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.MinimumQuantity"),+ value.Product.OrderMinimumQuantity));+ hasQtyWarnings = true;+ }- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ if (value.ShoppingCartItem.Quantity > value.Product.OrderMaximumQuantity){- //quantity validation- var hasQtyWarnings = false;- if (value.ShoppingCartItem.Quantity < value.Product.OrderMinimumQuantity)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.MinimumQuantity"), value.Product.OrderMinimumQuantity));- hasQtyWarnings = true;- }- if (value.ShoppingCartItem.Quantity > value.Product.OrderMaximumQuantity)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.MaximumQuantity"), value.Product.OrderMaximumQuantity));- hasQtyWarnings = true;- }- var allowedQuantities = value.Product.ParseAllowedQuantities();- if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(value.ShoppingCartItem.Quantity))- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.AllowedQuantities"), string.Join(", ", allowedQuantities)));- }+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.MaximumQuantity"),+ value.Product.OrderMaximumQuantity));+ hasQtyWarnings = true;+ }- if (shoppingCartSettings.AllowToSelectWarehouse && string.IsNullOrEmpty(value.ShoppingCartItem.WarehouseId))- {- context.AddFailure(translationService.GetResource("ShoppingCart.RequiredWarehouse"));- }+ var allowedQuantities = value.Product.ParseAllowedQuantities();+ if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(value.ShoppingCartItem.Quantity))+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.AllowedQuantities"),+ string.Join(", ", allowedQuantities)));++ if (shoppingCartSettings.AllowToSelectWarehouse && string.IsNullOrEmpty(value.ShoppingCartItem.WarehouseId))+ context.AddFailure(translationService.GetResource("ShoppingCart.RequiredWarehouse"));- var warehouseId = !string.IsNullOrEmpty(value.ShoppingCartItem.WarehouseId) ? value.ShoppingCartItem.WarehouseId : "";+ var warehouseId = !string.IsNullOrEmpty(value.ShoppingCartItem.WarehouseId)+ ? value.ShoppingCartItem.WarehouseId+ : "";- if (!hasQtyWarnings)+ if (!hasQtyWarnings)+ switch (value.Product.ManageInventoryMethodId){- switch (value.Product.ManageInventoryMethodId)+ case ManageInventoryMethod.DontManageStock:{- case ManageInventoryMethod.DontManageStock:- {- //do nothing- }- break;- case ManageInventoryMethod.ManageStock:- {- if (value.Product.BackorderModeId == BackorderMode.NoBackorders)- {- var qty = value.ShoppingCartItem.Quantity;+ //do nothing+ }+ break;+ case ManageInventoryMethod.ManageStock:+ {+ if (value.Product.BackorderModeId == BackorderMode.NoBackorders)+ {+ var qty = value.ShoppingCartItem.Quantity;- qty += value.Customer.ShoppingCartItems- .Where(x => x.ShoppingCartTypeId == value.ShoppingCartItem.ShoppingCartTypeId &&+ qty += value.Customer.ShoppingCartItems+ .Where(x => x.ShoppingCartTypeId == value.ShoppingCartItem.ShoppingCartTypeId &&x.WarehouseId == warehouseId &&x.ProductId == value.ShoppingCartItem.ProductId &&x.StoreId == value.ShoppingCartItem.StoreId &&x.Id != value.ShoppingCartItem.Id)- .Sum(x => x.Quantity);+ .Sum(x => x.Quantity);- var maximumQuantityCanBeAdded = stockQuantityService.GetTotalStockQuantity(value.Product, warehouseId: warehouseId);- if (maximumQuantityCanBeAdded < qty)- {- context.AddFailure(maximumQuantityCanBeAdded <= 0- ? translationService.GetResource("ShoppingCart.OutOfStock")- : string.Format(- translationService.GetResource("ShoppingCart.QuantityExceedsStock"),- maximumQuantityCanBeAdded));- }- }- }- break;- case ManageInventoryMethod.ManageStockByBundleProducts:+ var maximumQuantityCanBeAdded =+ stockQuantityService.GetTotalStockQuantity(value.Product, warehouseId: warehouseId);+ if (maximumQuantityCanBeAdded < qty)+ context.AddFailure(maximumQuantityCanBeAdded <= 0+ ? translationService.GetResource("ShoppingCart.OutOfStock")+ : string.Format(+ translationService.GetResource("ShoppingCart.QuantityExceedsStock"),+ maximumQuantityCanBeAdded));+ }+ }+ break;+ case ManageInventoryMethod.ManageStockByBundleProducts:+ {+ foreach (var item in value.Product.BundleProducts)+ {+ var qty = value.ShoppingCartItem.Quantity * item.Quantity;+ var p1 = await productService.GetProductById(item.ProductId);+ if (p1 is not { BackorderModeId: BackorderMode.NoBackorders }) continue;+ if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock){- foreach (var item in value.Product.BundleProducts)- {- var qty = value.ShoppingCartItem.Quantity * item.Quantity;- var p1 = await productService.GetProductById(item.ProductId);- if (p1 is not { BackorderModeId: BackorderMode.NoBackorders }) continue;- if (p1.ManageInventoryMethodId == ManageInventoryMethod.ManageStock)- {- var maximumQuantityCanBeAdded = stockQuantityService.GetTotalStockQuantity(p1, warehouseId: warehouseId);- if (maximumQuantityCanBeAdded < qty)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"), p1.Name));- }- }+ var maximumQuantityCanBeAdded =+ stockQuantityService.GetTotalStockQuantity(p1, warehouseId: warehouseId);+ if (maximumQuantityCanBeAdded < qty)+ context.AddFailure(string.Format(+ translationService.GetResource("ShoppingCart.OutOfStock.BundleProduct"),+ p1.Name));+ }- if (p1.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes)- continue;- var combination = p1.FindProductAttributeCombination(value.ShoppingCartItem.Attributes);- if (combination != null)- {- //combination exists - check stock level- var stockQuantity = stockQuantityService.GetTotalStockQuantityForCombination(p1, combination, warehouseId: warehouseId);- if (!combination.AllowOutOfStockOrders && stockQuantity < qty)- {- context.AddFailure(stockQuantity <= 0- ? string.Format(- translationService.GetResource(- "ShoppingCart.OutOfStock.BundleProduct"), p1.Name)- : string.Format(- translationService.GetResource(- "ShoppingCart.QuantityExceedsStock.BundleProduct"), p1.Name,- stockQuantity));- }- }- else- {- context.AddFailure(translationService.GetResource("ShoppingCart.Combination.NotExist"));- }- }+ if (p1.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes)+ continue;+ var combination = p1.FindProductAttributeCombination(value.ShoppingCartItem.Attributes);+ if (combination != null)+ {+ //combination exists - check stock level+ var stockQuantity =+ stockQuantityService.GetTotalStockQuantityForCombination(p1, combination,+ warehouseId: warehouseId);+ if (!combination.AllowOutOfStockOrders && stockQuantity < qty)+ context.AddFailure(stockQuantity <= 0+ ? string.Format(+ translationService.GetResource(+ "ShoppingCart.OutOfStock.BundleProduct"), p1.Name)+ : string.Format(+ translationService.GetResource(+ "ShoppingCart.QuantityExceedsStock.BundleProduct"), p1.Name,+ stockQuantity));}- break;- case ManageInventoryMethod.ManageStockByAttributes:+ else{- var combination = value.Product.FindProductAttributeCombination(value.ShoppingCartItem.Attributes);- if (combination != null)- {- //combination exists - check stock level- var stockQuantity = stockQuantityService.GetTotalStockQuantityForCombination(value.Product, combination, warehouseId: warehouseId);- if (!combination.AllowOutOfStockOrders && stockQuantity < value.ShoppingCartItem.Quantity)- {- context.AddFailure(stockQuantity <= 0- ? translationService.GetResource("ShoppingCart.OutOfStock")- : string.Format(- translationService.GetResource("ShoppingCart.QuantityExceedsStock"),- stockQuantity));- }- }- else- {- context.AddFailure(translationService.GetResource("ShoppingCart.Combination.NotExist"));- }+ context.AddFailure(translationService.GetResource("ShoppingCart.Combination.NotExist"));}- break;+ }+ }+ break;+ case ManageInventoryMethod.ManageStockByAttributes:+ {+ var combination =+ value.Product.FindProductAttributeCombination(value.ShoppingCartItem.Attributes);+ if (combination != null)+ {+ //combination exists - check stock level+ var stockQuantity =+ stockQuantityService.GetTotalStockQuantityForCombination(value.Product, combination,+ warehouseId: warehouseId);+ if (!combination.AllowOutOfStockOrders && stockQuantity < value.ShoppingCartItem.Quantity)+ context.AddFailure(stockQuantity <= 0+ ? translationService.GetResource("ShoppingCart.OutOfStock")+ : string.Format(+ translationService.GetResource("ShoppingCart.QuantityExceedsStock"),+ stockQuantity));+ }+ else+ {+ context.AddFailure(translationService.GetResource("ShoppingCart.Combination.NotExist"));+ }}+ break;}- });- }+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.csindex 3d6b863d8..4473ef08f 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs@@ -6,227 +6,222 @@ using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.SharedKernel.Extensions;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;++public record ShoppingCartItemAttributeValidatorRecord(+ Customer Customer,+ Product Product,+ ShoppingCartItem ShoppingCartItem,+ bool IgnoreNonCombinableAttributes);- public record ShoppingCartItemAttributeValidatorRecord(Customer Customer, Product Product, ShoppingCartItem ShoppingCartItem, bool IgnoreNonCombinableAttributes);+public class ShoppingCartItemAttributeValidator : AbstractValidator<ShoppingCartItemAttributeValidatorRecord>+{+ private readonly IProductAttributeService _productAttributeService;+ private readonly IProductService _productService;+ private readonly ITranslationService _translationService;- public class ShoppingCartItemAttributeValidator : AbstractValidator<ShoppingCartItemAttributeValidatorRecord>+ public ShoppingCartItemAttributeValidator(ITranslationService translationService, IProductService productService,+ IProductAttributeService productAttributeService){- private readonly ITranslationService _translationService;- private readonly IProductService _productService;- private readonly IProductAttributeService _productAttributeService;+ _translationService = translationService;+ _productService = productService;+ _productAttributeService = productAttributeService;- public ShoppingCartItemAttributeValidator(ITranslationService translationService, IProductService productService, IProductAttributeService productAttributeService)+ RuleFor(x => x).CustomAsync(async (value, context, ct) =>{- _translationService = translationService;- _productService = productService;- _productAttributeService = productAttributeService;-- RuleFor(x => x).CustomAsync(async (value, context, ct) =>+ var warnings = await GetShoppingCartItemWarnings(value);+ if (warnings.Any()){- var warnings = await GetShoppingCartItemWarnings(value);- if (warnings.Any())- {- warnings.ToList().ForEach(context.AddFailure);- return;- }+ warnings.ToList().ForEach(context.AddFailure);+ return;+ }- //validate bundled products- var attributeValues = value.Product.ParseProductAttributeValues(value.ShoppingCartItem.Attributes);- foreach (var attributeValue in attributeValues)+ //validate bundled products+ var attributeValues = value.Product.ParseProductAttributeValues(value.ShoppingCartItem.Attributes);+ foreach (var attributeValue in attributeValues)+ {+ var productAttributeMapping =+ value.Product.ProductAttributeMappings.FirstOrDefault(x =>+ x.ProductAttributeValues.Any(z => z.Id == attributeValue.Id));+ if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct ||+ productAttributeMapping == null) continue;{- var productAttributeMapping = value.Product.ProductAttributeMappings.FirstOrDefault(x => x.ProductAttributeValues.Any(z => z.Id == attributeValue.Id));- if (attributeValue.AttributeValueTypeId != AttributeValueType.AssociatedToProduct ||- productAttributeMapping == null) continue;- {- if (value.IgnoreNonCombinableAttributes && productAttributeMapping.IsNonCombinable())- continue;+ if (value.IgnoreNonCombinableAttributes && productAttributeMapping.IsNonCombinable())+ continue;- //associated product (bundle)- var associatedProduct = await productService.GetProductById(attributeValue.AssociatedProductId);- if (associatedProduct != null)- {- var totalQty = value.ShoppingCartItem.Quantity * attributeValue.Quantity;- var associatedProductWarnings = await GetShoppingCartItemWarnings(- value with { Product = associatedProduct, ShoppingCartItem = new ShoppingCartItem {+ //associated product (bundle)+ var associatedProduct = await productService.GetProductById(attributeValue.AssociatedProductId);+ if (associatedProduct != null)+ {+ var totalQty = value.ShoppingCartItem.Quantity * attributeValue.Quantity;+ var associatedProductWarnings = await GetShoppingCartItemWarnings(+ value with {+ Product = associatedProduct, ShoppingCartItem = new ShoppingCartItem {ShoppingCartTypeId = value.ShoppingCartItem.ShoppingCartTypeId,StoreId = value.ShoppingCartItem.Id,Quantity = totalQty,WarehouseId = value.ShoppingCartItem.WarehouseId,Attributes = value.ShoppingCartItem.Attributes- } });- foreach (var associatedProductWarning in associatedProductWarnings)- {- var productAttribute = await productAttributeService.GetProductAttributeById(productAttributeMapping.ProductAttributeId);- var attributeName = productAttribute.Name;- var attributeValueName = attributeValue.Name;- warnings.Add(string.Format(- translationService.GetResource("ShoppingCart.AssociatedAttributeWarning"),- attributeName, attributeValueName, associatedProductWarning));- }- }- else+ }+ });+ foreach (var associatedProductWarning in associatedProductWarnings){- warnings.Add($"Associated product cannot be loaded - {attributeValue.AssociatedProductId}");+ var productAttribute =+ await productAttributeService.GetProductAttributeById(productAttributeMapping+ .ProductAttributeId);+ var attributeName = productAttribute.Name;+ var attributeValueName = attributeValue.Name;+ warnings.Add(string.Format(+ translationService.GetResource("ShoppingCart.AssociatedAttributeWarning"),+ attributeName, attributeValueName, associatedProductWarning));}-- if (!warnings.Any()) continue;- warnings.ToList().ForEach(context.AddFailure);- return;}- }- });- }--- private async Task<IList<string>> GetShoppingCartItemWarnings(ShoppingCartItemAttributeValidatorRecord value)- {- //ensure it's our attributes- var warnings = new List<string>();-- var attributes1 = value.Product.ParseProductAttributeMappings(value.ShoppingCartItem.Attributes).ToList();- if (value.Product.ProductTypeId == ProductType.BundledProduct)- {- foreach (var bundle in value.Product.BundleProducts)- {- var p1 = await _productService.GetProductById(bundle.ProductId);- if (p1 != null)+ else{- var a1 = p1.ParseProductAttributeMappings(value.ShoppingCartItem.Attributes).ToList();- attributes1.AddRange(a1);+ warnings.Add($"Associated product cannot be loaded - {attributeValue.AssociatedProductId}");}- }+ if (!warnings.Any()) continue;+ warnings.ToList().ForEach(context.AddFailure);+ return;+ }}- if (value.IgnoreNonCombinableAttributes)- {- attributes1 = attributes1.Where(x => !x.IsNonCombinable()).ToList();+ });+ }- }- //foreach (var attribute in attributes1)- //{- // if (string.IsNullOrEmpty(attribute.ProductId))- // {- // warnings.Add("Attribute error");- // return warnings;- // }- //}-- //validate required product attributes (whether they're chosen/selected/entered)- var attributes2 = value.Product.ProductAttributeMappings.ToList();- if (value.Product.ProductTypeId == ProductType.BundledProduct)+ private async Task<IList<string>> GetShoppingCartItemWarnings(ShoppingCartItemAttributeValidatorRecord value)+ {+ //ensure it's our attributes+ var warnings = new List<string>();++ var attributes1 = value.Product.ParseProductAttributeMappings(value.ShoppingCartItem.Attributes).ToList();+ if (value.Product.ProductTypeId == ProductType.BundledProduct)+ foreach (var bundle in value.Product.BundleProducts){- foreach (var bundle in value.Product.BundleProducts)+ var p1 = await _productService.GetProductById(bundle.ProductId);+ if (p1 != null){- var p1 = await _productService.GetProductById(bundle.ProductId);- if (p1 != null && p1.ProductAttributeMappings.Any())- {- attributes2.AddRange(p1.ProductAttributeMappings);- }+ var a1 = p1.ParseProductAttributeMappings(value.ShoppingCartItem.Attributes).ToList();+ attributes1.AddRange(a1);}}- if (value.IgnoreNonCombinableAttributes)++ if (value.IgnoreNonCombinableAttributes) attributes1 = attributes1.Where(x => !x.IsNonCombinable()).ToList();++ //foreach (var attribute in attributes1)+ //{+ // if (string.IsNullOrEmpty(attribute.ProductId))+ // {+ // warnings.Add("Attribute error");+ // return warnings;+ // }+ //}++ //validate required product attributes (whether they're chosen/selected/entered)+ var attributes2 = value.Product.ProductAttributeMappings.ToList();+ if (value.Product.ProductTypeId == ProductType.BundledProduct)+ foreach (var bundle in value.Product.BundleProducts){- attributes2 = attributes2.Where(x => !x.IsNonCombinable()).ToList();+ var p1 = await _productService.GetProductById(bundle.ProductId);+ if (p1 != null && p1.ProductAttributeMappings.Any()) attributes2.AddRange(p1.ProductAttributeMappings);}- //validate conditional attributes only (if specified)- attributes2 = attributes2.Where(x =>- {- var conditionMet = value.Product.IsConditionMet(x, value.ShoppingCartItem.Attributes);- return !conditionMet.HasValue || conditionMet.Value;- }).ToList();- foreach (var a2 in attributes2)++ if (value.IgnoreNonCombinableAttributes) attributes2 = attributes2.Where(x => !x.IsNonCombinable()).ToList();+ //validate conditional attributes only (if specified)+ attributes2 = attributes2.Where(x =>+ {+ var conditionMet = value.Product.IsConditionMet(x, value.ShoppingCartItem.Attributes);+ return !conditionMet.HasValue || conditionMet.Value;+ }).ToList();+ foreach (var a2 in attributes2)+ {+ if (a2.IsRequired){- if (a2.IsRequired)+ var found = false;+ //selected product attributes+ foreach (var attributeValuesStr in from a1 in attributes1+ where a1.Id == a2.Id+ select ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, a1.Id)+ into attributeValuesStr+ where attributeValuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))+ select attributeValuesStr)+ found = true;++ //if not found+ if (!found){- var found = false;- //selected product attributes- foreach (var attributeValuesStr in from a1 in attributes1 where a1.Id == a2.Id- select ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, a1.Id)- into attributeValuesStr- where attributeValuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim())) select attributeValuesStr)- {- found = true;- }-- //if not found- if (!found)+ var paa = await _productAttributeService.GetProductAttributeById(a2.ProductAttributeId);+ if (paa != null){- var paa = await _productAttributeService.GetProductAttributeById(a2.ProductAttributeId);- if (paa != null)- {- var notFoundWarning = !string.IsNullOrEmpty(a2.TextPrompt) ?- a2.TextPrompt :- string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), paa.Name);-- warnings.Add(notFoundWarning);- }- }- }+ var notFoundWarning = !string.IsNullOrEmpty(a2.TextPrompt)+ ? a2.TextPrompt+ : string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), paa.Name);- if (a2.AttributeControlTypeId == AttributeControlType.ReadonlyCheckboxes)- {- //customers cannot edit read-only attributes- var allowedReadOnlyValueIds = a2.ProductAttributeValues- .Where(x => x.IsPreSelected)- .Select(x => x.Id)- .ToArray();-- var selectedReadOnlyValueIds = value.Product.ParseProductAttributeValues(value.ShoppingCartItem.Attributes)- //.Where(x => x.ProductAttributeMappingId == a2.Id)- .Select(x => x.Id)- .ToArray();-- if (!CommonHelper.ArraysEqual(allowedReadOnlyValueIds, selectedReadOnlyValueIds))- {- warnings.Add("You cannot change read-only values");+ warnings.Add(notFoundWarning);}}}- //validation rules- foreach (var pam in attributes2)+ if (a2.AttributeControlTypeId == AttributeControlType.ReadonlyCheckboxes){- if (!pam.ValidationRulesAllowed())- continue;+ //customers cannot edit read-only attributes+ var allowedReadOnlyValueIds = a2.ProductAttributeValues+ .Where(x => x.IsPreSelected)+ .Select(x => x.Id)+ .ToArray();++ var selectedReadOnlyValueIds = value.Product+ .ParseProductAttributeValues(value.ShoppingCartItem.Attributes)+ //.Where(x => x.ProductAttributeMappingId == a2.Id)+ .Select(x => x.Id)+ .ToArray();++ if (!CommonHelper.ArraysEqual(allowedReadOnlyValueIds, selectedReadOnlyValueIds))+ warnings.Add("You cannot change read-only values");+ }+ }- //minimum length- if (pam.ValidationMinLength.HasValue)- {- if (pam.AttributeControlTypeId is AttributeControlType.TextBox or AttributeControlType.MultilineTextbox)- {- var valuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, pam.Id);- var enteredText = valuesStr.FirstOrDefault();- var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;+ //validation rules+ foreach (var pam in attributes2)+ {+ if (!pam.ValidationRulesAllowed())+ continue;- if (pam.ValidationMinLength.Value > enteredTextLength)- {- var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMinimumLength"), productAttribute.Name, pam.ValidationMinLength.Value));- }- }- }- //maximum length- if (!pam.ValidationMaxLength.HasValue) continue;+ //minimum length+ if (pam.ValidationMinLength.HasValue)+ if (pam.AttributeControlTypeId is AttributeControlType.TextBox or AttributeControlType.MultilineTextbox){- if (pam.AttributeControlTypeId != AttributeControlType.TextBox &&- pam.AttributeControlTypeId != AttributeControlType.MultilineTextbox) continue;var valuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, pam.Id);var enteredText = valuesStr.FirstOrDefault();var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;- if (pam.ValidationMaxLength.Value >= enteredTextLength) continue;- var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);- warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMaximumLength"), productAttribute.Name, pam.ValidationMaxLength.Value));+ if (pam.ValidationMinLength.Value > enteredTextLength)+ {+ var productAttribute =+ await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMinimumLength"),+ productAttribute.Name, pam.ValidationMinLength.Value));+ }}- }- return warnings;+ //maximum length+ if (!pam.ValidationMaxLength.HasValue) continue;+ {+ if (pam.AttributeControlTypeId != AttributeControlType.TextBox &&+ pam.AttributeControlTypeId != AttributeControlType.MultilineTextbox) continue;+ var valuesStr = ProductExtensions.ParseValues(value.ShoppingCartItem.Attributes, pam.Id);+ var enteredText = valuesStr.FirstOrDefault();+ var enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;++ if (pam.ValidationMaxLength.Value >= enteredTextLength) continue;+ var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);+ warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMaximumLength"),+ productAttribute.Name, pam.ValidationMaxLength.Value));+ }}-+ return warnings;}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.csindex e55fc5c91..2010053bb 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs@@ -6,35 +6,40 @@ using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.Domain.Stores;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartRequiredProductValidatorRecord(Customer Customer, Store Store, Product Product, ShoppingCartItem ShoppingCartItem);+public record ShoppingCartRequiredProductValidatorRecord(+ Customer Customer,+ Store Store,+ Product Product,+ ShoppingCartItem ShoppingCartItem);- public class ShoppingCartRequiredProductValidator : AbstractValidator<ShoppingCartRequiredProductValidatorRecord>+public class ShoppingCartRequiredProductValidator : AbstractValidator<ShoppingCartRequiredProductValidatorRecord>+{+ public ShoppingCartRequiredProductValidator(ITranslationService translationService, IProductService productService,+ ShoppingCartSettings shoppingCartSettings){- public ShoppingCartRequiredProductValidator(ITranslationService translationService, IProductService productService, ShoppingCartSettings shoppingCartSettings)+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{+ var cart = value.Customer.ShoppingCartItems+ .Where(sci => sci.ShoppingCartTypeId == value.ShoppingCartItem.ShoppingCartTypeId)+ .LimitPerStore(shoppingCartSettings.SharedCartBetweenStores, value.Store.Id)+ .ToList();- RuleFor(x => x).CustomAsync(async (value, context, _) =>+ var requiredProducts = new List<Product>();+ foreach (var id in value.Product.ParseRequiredProductIds()){- var cart = value.Customer.ShoppingCartItems.Where(sci => sci.ShoppingCartTypeId == value.ShoppingCartItem.ShoppingCartTypeId)- .LimitPerStore(shoppingCartSettings.SharedCartBetweenStores, value.Store.Id)- .ToList();-- var requiredProducts = new List<Product>();- foreach (var id in value.Product.ParseRequiredProductIds())- {- var rp = await productService.GetProductById(id);- if (rp != null)- requiredProducts.Add(rp);- }+ var rp = await productService.GetProductById(id);+ if (rp != null)+ requiredProducts.Add(rp);+ }- foreach (var rp in from rp in requiredProducts let alreadyInTheCart = cart.Any(sci => sci.ProductId == rp.Id) where !alreadyInTheCart select rp)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.Name));- }- });- }+ foreach (var rp in from rp in requiredProducts+ let alreadyInTheCart = cart.Any(sci => sci.ProductId == rp.Id)+ where !alreadyInTheCart+ select rp)+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.RequiredProductWarning"),+ rp.Name));+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.csindex 613471b09..9a2e92d27 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartReservationProductValidator.cs@@ -5,148 +5,157 @@ using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Orders;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartReservationProductValidatorRecord(Customer Customer, Product Product, ShoppingCartItem ShoppingCartItem);+public record ShoppingCartReservationProductValidatorRecord(+ Customer Customer,+ Product Product,+ ShoppingCartItem ShoppingCartItem);- public class ShoppingCartReservationProductValidator : AbstractValidator<ShoppingCartReservationProductValidatorRecord>+public class ShoppingCartReservationProductValidator : AbstractValidator<ShoppingCartReservationProductValidatorRecord>+{+ public ShoppingCartReservationProductValidator(ITranslationService translationService,+ IProductReservationService productReservationService){- public ShoppingCartReservationProductValidator(ITranslationService translationService, IProductReservationService productReservationService)+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{+ if (!string.IsNullOrEmpty(value.ShoppingCartItem.ReservationId))+ {+ var reservations = await productReservationService.GetCustomerReservationsHelpers(value.Customer.Id);+ if (value.Customer.ShoppingCartItems.All(x => x.Id != value.ShoppingCartItem.Id))+ if (reservations.Any(x => x.ReservationId == value.ShoppingCartItem.ReservationId))+ context.AddFailure(translationService.GetResource("ShoppingCart.AlreadyReservation"));+ }- RuleFor(x => x).CustomAsync(async (value, context, _) =>+ if (value.ShoppingCartItem.RentalStartDateUtc.HasValue && value.ShoppingCartItem.RentalEndDateUtc.HasValue){- if (!string.IsNullOrEmpty(value.ShoppingCartItem.ReservationId))+ var canBeBook = false;+ var reservations =+ await productReservationService.GetProductReservationsByProductId(value.Product.Id, true, null);+ var reserved = await productReservationService.GetCustomerReservationsHelpers(value.Customer.Id);+ foreach (var item in reserved.Where(x => x.ShoppingCartItemId != value.ShoppingCartItem.Id)){- var reservations = await productReservationService.GetCustomerReservationsHelpers(value.Customer.Id);- if (value.Customer.ShoppingCartItems.All(x => x.Id != value.ShoppingCartItem.Id))- {- if (reservations.Any(x => x.ReservationId == value.ShoppingCartItem.ReservationId))- context.AddFailure(translationService.GetResource("ShoppingCart.AlreadyReservation"));- }+ var match = reservations.FirstOrDefault(x => x.Id == item.ReservationId);+ if (match != null) reservations.Remove(match);}- if (value.ShoppingCartItem.RentalStartDateUtc.HasValue && value.ShoppingCartItem.RentalEndDateUtc.HasValue)+ var grouped = reservations.GroupBy(x => x.Resource);+ foreach (var group in grouped){- var canBeBook = false;- var reservations = await productReservationService.GetProductReservationsByProductId(value.Product.Id, true, null);- var reserved = await productReservationService.GetCustomerReservationsHelpers(value.Customer.Id);- foreach (var item in reserved.Where(x => x.ShoppingCartItemId != value.ShoppingCartItem.Id))- {- var match = reservations.FirstOrDefault(x => x.Id == item.ReservationId);- if (match != null)+ var groupCanBeBooked = true;+ if (value.Product.IncBothDate && value.Product.IntervalUnitId == IntervalUnit.Day)+ for (var iterator = value.ShoppingCartItem.RentalStartDateUtc.Value;+ iterator <= value.ShoppingCartItem.RentalEndDateUtc.Value;+ iterator += new TimeSpan(24, 0, 0)){- reservations.Remove(match);+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}- }-- var grouped = reservations.GroupBy(x => x.Resource);- foreach (var group in grouped)- {- var groupCanBeBooked = true;- if (value.Product.IncBothDate && value.Product.IntervalUnitId == IntervalUnit.Day)- {- for (DateTime iterator = value.ShoppingCartItem.RentalStartDateUtc.Value; iterator <= value.ShoppingCartItem.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0))- {- if (group.Select(x => x.Date).Contains(iterator)) continue;- groupCanBeBooked = false;- break;- }- }- else+ else+ for (var iterator = value.ShoppingCartItem.RentalStartDateUtc.Value;+ iterator < value.ShoppingCartItem.RentalEndDateUtc.Value;+ iterator += new TimeSpan(24, 0, 0)){- for (DateTime iterator = value.ShoppingCartItem.RentalStartDateUtc.Value; iterator < value.ShoppingCartItem.RentalEndDateUtc.Value; iterator += new TimeSpan(24, 0, 0))- {- if (group.Select(x => x.Date).Contains(iterator)) continue;- groupCanBeBooked = false;- break;- }+ if (group.Select(x => x.Date).Contains(iterator)) continue;+ groupCanBeBooked = false;+ break;}- if (!groupCanBeBooked) continue;- canBeBook = true;- break;- }- if (!canBeBook)- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.NoFreeReservationsInThisPeriod"));- return;- }+ if (!groupCanBeBooked) continue;+ canBeBook = true;+ break;}- if (string.IsNullOrEmpty(value.ShoppingCartItem.ReservationId) && value.Product.IntervalUnitId != IntervalUnit.Day)+ if (!canBeBook){- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.NoReservationFound"));+ context.AddFailure(+ translationService.GetResource("ShoppingCart.Reservation.NoFreeReservationsInThisPeriod"));return;}+ }- if (value.Product.IntervalUnitId != IntervalUnit.Day)+ if (string.IsNullOrEmpty(value.ShoppingCartItem.ReservationId) &&+ value.Product.IntervalUnitId != IntervalUnit.Day)+ {+ context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.NoReservationFound"));+ return;+ }++ if (value.Product.IntervalUnitId != IntervalUnit.Day)+ {+ var reservation =+ await productReservationService.GetProductReservation(value.ShoppingCartItem.ReservationId);+ if (reservation == null){- var reservation = await productReservationService.GetProductReservation(value.ShoppingCartItem.ReservationId);- if (reservation == null)- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ReservationDeleted"));- }- else- {- if (!string.IsNullOrEmpty(reservation.OrderId))- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.AlreadyReserved"));- }- }+ context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ReservationDeleted"));+ }+ else+ {+ if (!string.IsNullOrEmpty(reservation.OrderId))+ context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.AlreadyReserved"));+ }+ }+ else+ {+ if (!(value.ShoppingCartItem.RentalStartDateUtc.HasValue &&+ value.ShoppingCartItem.RentalEndDateUtc.HasValue))+ {+ context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ChooseBothDates"));}else{- if (!(value.ShoppingCartItem.RentalStartDateUtc.HasValue && value.ShoppingCartItem.RentalEndDateUtc.HasValue))+ if (!value.Product.IncBothDate){- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ChooseBothDates"));+ if (value.ShoppingCartItem.RentalStartDateUtc.Value >=+ value.ShoppingCartItem.RentalEndDateUtc.Value)+ context.AddFailure(+ translationService.GetResource(+ "ShoppingCart.Reservation.EndDateMustBeLaterThanStartDate"));}else{- if (!value.Product.IncBothDate)- {- if (value.ShoppingCartItem.RentalStartDateUtc.Value >= value.ShoppingCartItem.RentalEndDateUtc.Value)- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.EndDateMustBeLaterThanStartDate"));- }- }- else- {- if (value.ShoppingCartItem.RentalStartDateUtc.Value > value.ShoppingCartItem.RentalEndDateUtc.Value)- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.EndDateMustBeLaterThanStartDate"));- }- }+ if (value.ShoppingCartItem.RentalStartDateUtc.Value >+ value.ShoppingCartItem.RentalEndDateUtc.Value)+ context.AddFailure(+ translationService.GetResource(+ "ShoppingCart.Reservation.EndDateMustBeLaterThanStartDate"));+ }- if (value.ShoppingCartItem.RentalStartDateUtc.Value < DateTime.UtcNow || value.ShoppingCartItem.RentalEndDateUtc.Value < DateTime.UtcNow)- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ReservationDatesMustBeLaterThanToday"));- }+ if (value.ShoppingCartItem.RentalStartDateUtc.Value < DateTime.UtcNow ||+ value.ShoppingCartItem.RentalEndDateUtc.Value < DateTime.UtcNow)+ context.AddFailure(+ translationService.GetResource(+ "ShoppingCart.Reservation.ReservationDatesMustBeLaterThanToday"));- if (value.Customer.ShoppingCartItems.Any(x => x.Id == value.ShoppingCartItem.Id))- {- var reserved = await productReservationService.GetCustomerReservationsHelperBySciId(value.ShoppingCartItem.Id);- if (!reserved.Any())- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ReservationNotExists"));- else- foreach (var item in reserved)+ if (value.Customer.ShoppingCartItems.Any(x => x.Id == value.ShoppingCartItem.Id))+ {+ var reserved =+ await productReservationService.GetCustomerReservationsHelperBySciId(value.ShoppingCartItem+ .Id);+ if (!reserved.Any())+ context.AddFailure(+ translationService.GetResource("ShoppingCart.Reservation.ReservationNotExists"));+ else+ foreach (var item in reserved)+ {+ var reservation =+ await productReservationService.GetProductReservation(item.ReservationId);+ if (reservation == null){- var reservation = await productReservationService.GetProductReservation(item.ReservationId);- if (reservation == null)- {- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.ReservationDeleted"));- break;- }-- if (string.IsNullOrEmpty(reservation.OrderId)) continue;- context.AddFailure(translationService.GetResource("ShoppingCart.Reservation.AlreadyReserved"));+ context.AddFailure(+ translationService.GetResource("ShoppingCart.Reservation.ReservationDeleted"));break;}- }++ if (string.IsNullOrEmpty(reservation.OrderId)) continue;+ context.AddFailure(+ translationService.GetResource("ShoppingCart.Reservation.AlreadyReserved"));+ break;+ }}}- });- }+ }+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.csindex b3913b3ee..89cdc96c9 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartStandardValidator.cs@@ -5,96 +5,85 @@ using Grand.Domain.Catalog;using Grand.Domain.Customers;using Grand.Domain.Orders;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartStandardValidatorRecord(Customer Customer, Product Product, ShoppingCartItem ShoppingCartItem);+public record ShoppingCartStandardValidatorRecord(+ Customer Customer,+ Product Product,+ ShoppingCartItem ShoppingCartItem);- public class ShoppingCartStandardValidator : AbstractValidator<ShoppingCartStandardValidatorRecord>+public class ShoppingCartStandardValidator : AbstractValidator<ShoppingCartStandardValidatorRecord>+{+ public ShoppingCartStandardValidator(ITranslationService translationService, IAclService aclService){- public ShoppingCartStandardValidator(ITranslationService translationService, IAclService aclService)+ RuleFor(x => x).Custom((value, context) =>{- RuleFor(x => x).Custom((value, context) =>- {- if (!value.Product.Published)- {- context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));- }-- //we can't add grouped value.Product- if (value.Product.ProductTypeId == ProductType.GroupedProduct)- {- context.AddFailure("You can't add grouped value.Product");- }+ if (!value.Product.Published)+ context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));- //ACL- if (!aclService.Authorize(value.Product, value.Customer))- {- context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));- }+ //we can't add grouped value.Product+ if (value.Product.ProductTypeId == ProductType.GroupedProduct)+ context.AddFailure("You can't add grouped value.Product");- //Store acl- if (!aclService.Authorize(value.Product, value.ShoppingCartItem.StoreId))- {- context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));- }+ //ACL+ if (!aclService.Authorize(value.Product, value.Customer))+ context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));- switch (value.ShoppingCartItem.ShoppingCartTypeId)- {- //disabled "add to cart" button- case ShoppingCartType.ShoppingCart when value.Product.DisableBuyButton:- context.AddFailure(translationService.GetResource("ShoppingCart.BuyingDisabled"));- break;- //disabled "add to wishlist" button- case ShoppingCartType.Wishlist when value.Product.DisableWishlistButton:- context.AddFailure(translationService.GetResource("ShoppingCart.WishlistDisabled"));- break;- }+ //Store acl+ if (!aclService.Authorize(value.Product, value.ShoppingCartItem.StoreId))+ context.AddFailure(translationService.GetResource("ShoppingCart.ProductUnpublished"));- //call for price- if (value.ShoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart && value.Product.CallForPrice)- {- context.AddFailure(translationService.GetResource("Products.CallForPrice"));- }+ switch (value.ShoppingCartItem.ShoppingCartTypeId)+ {+ //disabled "add to cart" button+ case ShoppingCartType.ShoppingCart when value.Product.DisableBuyButton:+ context.AddFailure(translationService.GetResource("ShoppingCart.BuyingDisabled"));+ break;+ //disabled "add to wishlist" button+ case ShoppingCartType.Wishlist when value.Product.DisableWishlistButton:+ context.AddFailure(translationService.GetResource("ShoppingCart.WishlistDisabled"));+ break;+ }- //customer entered price- if (value.Product.EnteredPrice)- {- var shoppingCartItemEnteredPrice = value.ShoppingCartItem.EnteredPrice ?? 0;- if (shoppingCartItemEnteredPrice < value.Product.MinEnteredPrice ||- shoppingCartItemEnteredPrice > value.Product.MaxEnteredPrice)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.CustomerEnteredPrice.RangeError"),- value.Product.MinEnteredPrice,- value.Product.MaxEnteredPrice));- }- }+ //call for price+ if (value.ShoppingCartItem.ShoppingCartTypeId == ShoppingCartType.ShoppingCart &&+ value.Product.CallForPrice) context.AddFailure(translationService.GetResource("Products.CallForPrice"));- //availability dates- var availableStartDateError = false;- if (value.Product.AvailableStartDateTimeUtc.HasValue)- {- DateTime now = DateTime.UtcNow;- DateTime availableStartDateTime = DateTime.SpecifyKind(value.Product.AvailableStartDateTimeUtc.Value, DateTimeKind.Utc);- if (availableStartDateTime.CompareTo(now) > 0)- {- context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));- availableStartDateError = true;- }- }+ //customer entered price+ if (value.Product.EnteredPrice)+ {+ var shoppingCartItemEnteredPrice = value.ShoppingCartItem.EnteredPrice ?? 0;+ if (shoppingCartItemEnteredPrice < value.Product.MinEnteredPrice ||+ shoppingCartItemEnteredPrice > value.Product.MaxEnteredPrice)+ context.AddFailure(string.Format(+ translationService.GetResource("ShoppingCart.CustomerEnteredPrice.RangeError"),+ value.Product.MinEnteredPrice,+ value.Product.MaxEnteredPrice));+ }- if (!value.Product.AvailableEndDateTimeUtc.HasValue || availableStartDateError ||- value.ShoppingCartItem.ShoppingCartTypeId != ShoppingCartType.ShoppingCart) return;+ //availability dates+ var availableStartDateError = false;+ if (value.Product.AvailableStartDateTimeUtc.HasValue)+ {+ var now = DateTime.UtcNow;+ var availableStartDateTime =+ DateTime.SpecifyKind(value.Product.AvailableStartDateTimeUtc.Value, DateTimeKind.Utc);+ if (availableStartDateTime.CompareTo(now) > 0){- DateTime now = DateTime.UtcNow;- DateTime availableEndDateTime = DateTime.SpecifyKind(value.Product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc);- if (availableEndDateTime.CompareTo(now) < 0)- {- context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));- }+ context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));+ availableStartDateError = true;}- });- }+ }+ if (!value.Product.AvailableEndDateTimeUtc.HasValue || availableStartDateError ||+ value.ShoppingCartItem.ShoppingCartTypeId != ShoppingCartType.ShoppingCart) return;+ {+ var now = DateTime.UtcNow;+ var availableEndDateTime =+ DateTime.SpecifyKind(value.Product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc);+ if (availableEndDateTime.CompareTo(now) < 0)+ context.AddFailure(translationService.GetResource("ShoppingCart.NotAvailable"));+ }+ });}-}+}\ No newline at end of filediff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.csindex 7eae95f67..87823a211 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartTotalAmountValidator.cs@@ -9,7 +9,10 @@ using Grand.Domain.Orders;namespace Grand.Business.Checkout.Validators;-public record ShoppingCartTotalAmountValidatorRecord(Customer Customer, Currency Currency, IList<ShoppingCartItem> Cart);+public record ShoppingCartTotalAmountValidatorRecord(+ Customer Customer,+ Currency Currency,+ IList<ShoppingCartItem> Cart);public class ShoppingCartTotalAmountValidator : AbstractValidator<ShoppingCartTotalAmountValidatorRecord>{@@ -34,21 +37,25 @@ public class ShoppingCartTotalAmountValidator : AbstractValidator<ShoppingCartToif (!value.Cart.Any() || (!(minOrderAmount > 0) && !(maxOrderAmount > 0) &&!(orderSettings.MinOrderTotalAmount > 0))) return;- var shoppingCartTotalBase = (await orderTotalCalculationService.GetShoppingCartTotal(value.Cart)).shoppingCartTotal;-+ 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);+ 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)));+ await currencyService.ConvertFromPrimaryStoreCurrency(orderSettings.MinOrderSubtotalAmount,+ value.Currency);+ context.AddFailure(string.Format(translationService.GetResource("Checkout.MinOrderSubtotalAmount"),+ priceFormatter.FormatPrice(minOrderSubtotalAmount, value.Currency)));}});}diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.csindex 34218cff3..78e747b0d 100644--- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs+++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs@@ -6,57 +6,61 @@ using Grand.Domain.Customers;using Grand.Domain.Orders;using Grand.Domain.Stores;-namespace Grand.Business.Checkout.Validators-{+namespace Grand.Business.Checkout.Validators;- public record ShoppingCartWarningsValidatorRecord(Customer Customer, Store Store, IList<ShoppingCartItem> ShoppingCarts);+public record ShoppingCartWarningsValidatorRecord(+ Customer Customer,+ Store Store,+ IList<ShoppingCartItem> ShoppingCarts);- public class ShoppingCartWarningsValidator : AbstractValidator<ShoppingCartWarningsValidatorRecord>+public class ShoppingCartWarningsValidator : AbstractValidator<ShoppingCartWarningsValidatorRecord>+{+ public ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService){- public ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService)+ RuleFor(x => x).CustomAsync(async (value, context, _) =>{+ var hasStandardProducts = false;+ var hasRecurringProducts = false;+ var hasRecurringProductsMix = false;- RuleFor(x => x).CustomAsync(async (value, context, _) =>- {- var hasStandardProducts = false;- var hasRecurringProducts = false;- var hasRecurringProductsMix = false;+ (RecurringCyclePeriod recurringCyclePeriod, int recurringCycleLength, int recurringTotalCycles)?+ recurringProducts = null;- (RecurringCyclePeriod recurringCyclePeriod, int recurringCycleLength, int recurringTotalCycles)? recurringProducts = null;+ foreach (var sci in value.ShoppingCarts)+ {+ var product = await productService.GetProductById(sci.ProductId);+ if (product == null)+ {+ context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.CannotLoadProduct"),+ sci.ProductId));+ return;+ }- foreach (var sci in value.ShoppingCarts)+ if (product.IsRecurring){- var product = await productService.GetProductById(sci.ProductId);- if (product == null)- {- context.AddFailure(string.Format(translationService.GetResource("ShoppingCart.CannotLoadProduct"), sci.ProductId));- return;- }-- if (product.IsRecurring)- {- hasRecurringProducts = true;- if (!recurringProducts.HasValue)- recurringProducts = (product.RecurringCyclePeriodId, product.RecurringCycleLength, product.RecurringTotalCycles);- else- if (recurringProducts.Value.recurringCyclePeriod != product.RecurringCyclePeriodId ||- recurringProducts.Value.recurringCycleLength != product.RecurringCycleLength ||- recurringProducts.Value.recurringTotalCycles != product.RecurringTotalCycles+ hasRecurringProducts = true;+ if (!recurringProducts.HasValue)+ recurringProducts = (product.RecurringCyclePeriodId, product.RecurringCycleLength,+ product.RecurringTotalCycles);+ else if (recurringProducts.Value.recurringCyclePeriod != product.RecurringCyclePeriodId ||+ recurringProducts.Value.recurringCycleLength != product.RecurringCycleLength ||+ recurringProducts.Value.recurringTotalCycles != product.RecurringTotalCycles)- hasRecurringProductsMix = true;- }- else- hasStandardProducts = true;+ hasRecurringProductsMix = true;+ }+ else+ {+ hasStandardProducts = true;}+ }- //don't mix standard and recurring products- if (hasStandardProducts && hasRecurringProducts)- context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixStandardAndAutoshipProducts"));+ //don't mix standard and recurring products+ if (hasStandardProducts && hasRecurringProducts)+ context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixStandardAndAutoshipProducts"));- //don't mix recurring products- if (hasRecurringProducts && hasRecurringProductsMix)- context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixRecurringProducts"));- });- }+ //don't mix recurring products+ if (hasRecurringProducts && hasRecurringProductsMix)+ context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixRecurringProducts"));+ });}-}+}\ No newline at end of file