diff --git a/.ai/skills/plugin-payment.md b/.ai/skills/plugin-payment.md index 04f312dca..7a3e2bbd2 100644 --- a/.ai/skills/plugin-payment.md +++ b/.ai/skills/plugin-payment.md @@ -61,6 +61,11 @@ Do not use this skill for order processing business logic outside the payment fl 10. Return `SupportCapture() => true` only when `Capture` is actually implemented; same for Refund, PartiallyRefund, and Void. Returning `true` causes the admin UI to show the corresponding action button. 11. In `CancelPayment`, update `paymentTransaction.TransactionStatus = TransactionStatus.Canceled` and persist via `IPaymentTransactionService.UpdatePaymentTransaction`. +#### Recurring Payments +- The provider, not the shop, runs the schedule: the gateway charges every cycle, retries failures and reports each cycle to the shop, the first one (the initial order's payment) included: `CyclesPaid` stays 0 until it does. A cart with a recurring product is offered only methods whose `SupportRecurringPayment()` returns `true`, and the order is refused for any other method. +- Return `SupportRecurringPayment() => true` only when the payment flow starts the gateway's schedule for a recurring order and `CancelRecurringPayment` stops it. Both members have defaults (`false`, and an error result), so a provider without recurring support implements neither. +- Never report "cancelled" from `CancelRecurringPayment` unless the gateway confirmed it: on an error result the shop keeps the recurring payment running. + #### Project Structure 12. Use `Microsoft.NET.Sdk.Razor` as SDK. 13. Set output path to `..\..\Web\Grand.Web\Plugins\{SystemName}\`. diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs index 218f84d84..7e16f8915 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs @@ -66,6 +66,7 @@ public class PlaceOrderCommandHandler : IRequestHandler Handle(PlaceOrderCommand command, Cancellati //from here on what was claimed belongs to the order orderInserted = true; await CompleteOrderDetails(details, result.PlacedOrder); + //after the cart is cleared, so a failed write cannot lead to a second paid order; still before the + //provider's post-process step, which starts the gateway's schedule for it + if (details.IsRecurring) + await InsertRecurringPayment(result.PlacedOrder); result.PaymentTransaction = paymentTransaction; #endregion @@ -322,6 +329,20 @@ await _mediator.Publish(new OrderPlacedEvent(result.PlacedOrder) { return result; } + private Task InsertRecurringPayment(Order order) + { + return _recurringPaymentService.InsertRecurringPayment(new RecurringPayment { + StoreId = order.StoreId, + CustomerId = order.CustomerId, + InitialOrderId = order.Id, + PaymentMethodSystemName = order.PaymentMethodSystemName, + CycleLength = order.RecurringCycleLength, + CyclePeriodId = order.RecurringCyclePeriodId, + TotalCycles = order.RecurringTotalCycles, + Status = RecurringPaymentStatus.Pending + }); + } + protected virtual async Task ProcessPayment(PlaceOrderContainer details, PaymentTransaction paymentTransaction) { @@ -1039,7 +1060,8 @@ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction IsRecurring = details.IsRecurring, RecurringCycleLength = details.RecurringCycleLength, RecurringCyclePeriodId = details.RecurringCyclePeriodId, - RecurringTotalCycles = details.RecurringTotalCycles + RecurringTotalCycles = details.RecurringTotalCycles, + RecurringCycleNumber = details.IsRecurring ? 1 : 0 }; foreach (var item in details.Taxes) order.OrderTaxes.Add(item); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs new file mode 100644 index 000000000..6d2f870ce --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs @@ -0,0 +1,56 @@ +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Common.Localization; +using Grand.Business.Core.Utilities.Checkout; + +namespace Grand.Business.Checkout.Services.Orders; + +/// +/// The built-in rule: the payment method runs the schedule of an order billed in cycles, so the order needs a method +/// that can, and something to pay +/// +public class RecurringPaymentRuleProvider : IOrderPlacementRuleProvider +{ + private readonly IPaymentService _paymentService; + private readonly IRecurringPaymentService _recurringPaymentService; + private readonly ITranslationService _translationService; + + public RecurringPaymentRuleProvider(IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, ITranslationService translationService) + { + _recurringPaymentService = recurringPaymentService; + _paymentService = paymentService; + _translationService = translationService; + } + + public string ConfigurationUrl => null; + public string SystemName => "OrderPlacementRule.RecurringPayment"; + public string FriendlyName => SystemName; + public int Priority => 0; + public IList LimitedToStores => []; + public IList LimitedToGroups => []; + + public async Task Evaluate(OrderPlacementContext context, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + + // not a recurring cart: returning here keeps every other checkout free of a total calculation + if (!await _recurringPaymentService.HasRecurringProducts(context.Cart)) + return OrderPlacementRuleResult.Allow(); + + // a zero total skips the payment step and clears the method, so nothing would run the schedule + if (await context.GetTotal() is 0) + return OrderPlacementRuleResult.Block( + _translationService.GetResource("Checkout.RecurringPayment.NothingToPay", context.Language.Id)); + + // a method that charges once would break the promise of a product billed in cycles; none is chosen yet early + // in checkout + if (!string.IsNullOrEmpty(context.PaymentMethodSystemName) && + !await _paymentService.SupportRecurringPayment(context.PaymentMethodSystemName)) + return OrderPlacementRuleResult.Block(_translationService.GetResource( + "Checkout.RecurringPayment.PaymentMethodNotSupported", context.Language.Id)); + + return OrderPlacementRuleResult.Allow(); + } +} diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs new file mode 100644 index 000000000..024feabce --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -0,0 +1,56 @@ +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Data; +using Grand.Domain.Orders; +using Grand.Infrastructure.Extensions; +using Grand.Mediator; + +namespace Grand.Business.Checkout.Services.Orders; + +public class RecurringPaymentService( + IRepository repository, + IProductService productService, + IMediator mediator) + : IRecurringPaymentService +{ + public virtual async Task InsertRecurringPayment(RecurringPayment recurringPayment) + { + ArgumentNullException.ThrowIfNull(recurringPayment); + + await repository.InsertAsync(recurringPayment); + + //event notification + await mediator.EntityInserted(recurringPayment); + } + + public virtual async Task UpdateRecurringPayment(RecurringPayment recurringPayment) + { + ArgumentNullException.ThrowIfNull(recurringPayment); + + await repository.UpdateAsync(recurringPayment); + + //event notification + await mediator.EntityUpdated(recurringPayment); + } + + public virtual Task GetRecurringPaymentById(string id) + { + return repository.GetByIdAsync(id); + } + + public virtual Task GetRecurringPaymentByInitialOrderId(string initialOrderId) + { + return repository.GetOneAsync(x => x.InitialOrderId == initialOrderId); + } + + public virtual async Task HasRecurringProducts(IEnumerable cart) + { + ArgumentNullException.ThrowIfNull(cart); + + foreach (var sci in cart) + if (await productService.GetProductById(sci.ProductId) is { IsRecurring: true }) + return true; + + return false; + } +} diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs index 0c2b91862..0a80569c4 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs @@ -389,6 +389,19 @@ public virtual async Task SupportVoid(string paymentMethodSystemName) return await paymentMethod.SupportVoid(); } + /// + /// Gets a value indicating whether recurring payments are supported by payment method + /// + /// Payment method system name + /// A value indicating whether recurring payments are supported + public virtual async Task SupportRecurringPayment(string paymentMethodSystemName) + { + var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); + if (paymentMethod == null) + return false; + return await paymentMethod.SupportRecurringPayment(); + } + /// /// Voids a payment /// diff --git a/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs b/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs index a5b9fcee2..c38c997db 100644 --- a/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs +++ b/src/Business/Grand.Business.Checkout/Startup/StartupApplication.cs @@ -52,8 +52,10 @@ private static void RegisterOrdersService(IServiceCollection serviceCollection) serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); + serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); + serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); serviceCollection.AddScoped(); diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs index 738f8f716..fec791296 100644 --- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs +++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartWarningsValidator.cs @@ -1,5 +1,6 @@ using FluentValidation; using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Common.Directory; using Grand.Business.Core.Interfaces.Common.Localization; using Grand.Domain.Catalog; using Grand.Domain.Customers; @@ -17,7 +18,8 @@ public record ShoppingCartWarningsValidatorRecord( public class ShoppingCartWarningsValidator : AbstractValidator { - public ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService) + public ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService, + IGroupService groupService) { RuleFor(x => x).CustomAsync(async (value, context, _) => { @@ -63,6 +65,12 @@ public ShoppingCartWarningsValidator(ITranslationService translationService, IPr //don't mix recurring products if (hasRecurringProducts && hasRecurringProductsMix) context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixRecurringProducts", value.Language.Id)); + + //a recurring payment is cancelled from My account, so a guest has to log in or register first; a wishlist + //buys nothing + if (hasRecurringProducts && value.ShoppingCarts.Any(x => x.ShoppingCartTypeId != ShoppingCartType.Wishlist) && + await groupService.IsGuest(value.Customer)) + context.AddFailure(translationService.GetResource("ShoppingCart.RecurringProductsRequireAccount", value.Language.Id)); }); } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs new file mode 100644 index 000000000..96c36ca58 --- /dev/null +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -0,0 +1,34 @@ +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Interfaces.Checkout.Orders; + +/// +/// The recurring payments of orders placed with a recurring product +/// +public interface IRecurringPaymentService +{ + /// + /// Inserts a recurring payment + /// + Task InsertRecurringPayment(RecurringPayment recurringPayment); + + /// + /// Updates a recurring payment + /// + Task UpdateRecurringPayment(RecurringPayment recurringPayment); + + /// + /// Gets a recurring payment + /// + Task GetRecurringPaymentById(string id); + + /// + /// Gets the recurring payment of the order the customer placed; null when the order is not recurring + /// + Task GetRecurringPaymentByInitialOrderId(string initialOrderId); + + /// + /// Gets a value indicating whether the cart holds a product billed in cycles + /// + Task HasRecurringProducts(IEnumerable cart); +} diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs index f624ae4e2..8e8c4bde2 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentProvider.cs @@ -162,5 +162,24 @@ public interface IPaymentProvider : IProvider /// Task SupportVoid(); + /// + /// Gets a value indicating whether the provider runs recurring payments: it starts the gateway's schedule in its + /// payment flow, charges every cycle and reports each one to the shop, the first one (the initial order's + /// payment) included + /// + Task SupportRecurringPayment() => Task.FromResult(false); + + /// + /// Cancels a recurring payment at the gateway, so no further cycle is charged + /// + /// Recurring payment + /// Result + Task CancelRecurringPayment(RecurringPayment recurringPayment) + { + var result = new CancelRecurringPaymentResult(); + result.AddError("Recurring payment method not supported"); + return Task.FromResult(result); + } + #endregion } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs index 838a1e4ea..190862328 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs @@ -147,6 +147,13 @@ Task> LoadAllPaymentMethods(Customer customer = null, st /// A value indicating whether void is supported Task SupportVoid(string paymentMethodSystemName); + /// + /// Gets a value indicating whether recurring payments are supported by payment method + /// + /// Payment method system name + /// A value indicating whether recurring payments are supported + Task SupportRecurringPayment(string paymentMethodSystemName); + /// /// Voids a payment /// diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/CancelRecurringPaymentResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/CancelRecurringPaymentResult.cs new file mode 100644 index 000000000..84a8383cc --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/CancelRecurringPaymentResult.cs @@ -0,0 +1,26 @@ +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// Represents a CancelRecurringPaymentResult +/// +public class CancelRecurringPaymentResult +{ + /// + /// Gets a value indicating whether request has been completed successfully + /// + public bool Success => Errors.Count == 0; + + /// + /// Errors + /// + public IList Errors { get; set; } = new List(); + + /// + /// Add error + /// + /// Error + public void AddError(string error) + { + Errors.Add(error); + } +} diff --git a/src/Core/Grand.Domain/Orders/Order.cs b/src/Core/Grand.Domain/Orders/Order.cs index 0918e3f36..22f82cdd9 100644 --- a/src/Core/Grand.Domain/Orders/Order.cs +++ b/src/Core/Grand.Domain/Orders/Order.cs @@ -315,6 +315,16 @@ public class Order : BaseEntity /// public int RecurringUseCycles { get; set; } + /// + /// Gets or sets the order the customer placed, on an order paying a later cycle of its recurring payment + /// + public string InitialOrderId { get; set; } + + /// + /// Gets or sets the recurring payment cycle the order pays: 1 on the initial order, 0 when not recurring + /// + public int RecurringCycleNumber { get; set; } + /// /// Gets or sets the Shipping Option description (customer friendly string) /// diff --git a/src/Core/Grand.Domain/Orders/RecurringPayment.cs b/src/Core/Grand.Domain/Orders/RecurringPayment.cs new file mode 100644 index 000000000..532aae91c --- /dev/null +++ b/src/Core/Grand.Domain/Orders/RecurringPayment.cs @@ -0,0 +1,97 @@ +using Grand.Domain.Audit; +using Grand.Domain.Catalog; +using Grand.Domain.Customers; +using Grand.Domain.Stores; + +namespace Grand.Domain.Orders; + +/// +/// Represents a recurring payment: the cycles a payment provider charges for an order placed with a recurring +/// product. The provider runs the schedule; the shop records what it reports +/// +public class RecurringPayment : BaseEntity +{ + /// + /// Gets or sets the store identifier + /// + [AuditReference(typeof(Store))] + public string StoreId { get; set; } + + /// + /// Gets or sets the customer identifier + /// + [AuditReference(typeof(Customer))] + public string CustomerId { get; set; } + + /// + /// Gets or sets the order the customer placed + /// + [AuditReference(typeof(Order))] + public string InitialOrderId { get; set; } + + /// + /// Gets or sets the system name of the payment method that runs the schedule + /// + public string PaymentMethodSystemName { get; set; } + + /// + /// Gets or sets the cycle length + /// + public int CycleLength { get; set; } + + /// + /// Gets or sets the cycle period + /// + public RecurringCyclePeriod CyclePeriodId { get; set; } + + /// + /// Gets or sets the total cycles; 0 means until cancelled + /// + public int TotalCycles { get; set; } + + /// + /// Gets or sets the number of paid cycles the provider reported, the initial order's included: 0 until the + /// provider reports the first one, even when the initial order is already paid + /// + public int CyclesPaid { get; set; } + + /// + /// Gets or sets the status + /// + public RecurringPaymentStatus Status { get; set; } + + /// + /// Gets or sets the gateway's subscription identifier + /// + public string ProviderReference { get; set; } + + /// + /// Gets or sets the next payment date as reported by the provider; informational only + /// + public DateTime? NextPaymentDateUtc { get; set; } + + /// + /// Gets or sets the reason the last cycle failed + /// + public string LastError { get; set; } + + /// + /// Gets or sets the date and time the last cycle failed + /// + public DateTime? LastErrorDateUtc { get; set; } + + /// + /// Gets or sets the date and time of cancellation + /// + public DateTime? CancelledOnUtc { get; set; } + + /// + /// Gets or sets who cancelled: the customer, a staff name or the provider + /// + public string CancelledBy { get; set; } + + /// + /// Gets or sets the paid cycles + /// + public IList Cycles { get; set; } = new List(); +} diff --git a/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs b/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs new file mode 100644 index 000000000..26c02ee93 --- /dev/null +++ b/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs @@ -0,0 +1,32 @@ +namespace Grand.Domain.Orders; + +/// +/// Represents one paid cycle of a recurring payment +/// +public class RecurringPaymentCycle : SubBaseEntity +{ + /// + /// Gets or sets the cycle number; 1 is the initial order + /// + public int CycleNumber { get; set; } + + /// + /// Gets or sets the order the cycle was paid with + /// + public string OrderId { get; set; } + + /// + /// Gets or sets the gateway's invoice or charge identifier + /// + public string ProviderReference { get; set; } + + /// + /// Gets or sets the amount the gateway charged + /// + public double Amount { get; set; } + + /// + /// Gets or sets the date and time the gateway charged the cycle + /// + public DateTime PaidOnUtc { get; set; } +} diff --git a/src/Core/Grand.Domain/Orders/RecurringPaymentStatus.cs b/src/Core/Grand.Domain/Orders/RecurringPaymentStatus.cs new file mode 100644 index 000000000..d4f32a3cc --- /dev/null +++ b/src/Core/Grand.Domain/Orders/RecurringPaymentStatus.cs @@ -0,0 +1,32 @@ +namespace Grand.Domain.Orders; + +/// +/// Represents a recurring payment status +/// +public enum RecurringPaymentStatus +{ + /// + /// The order is placed, the provider has not reported the first paid cycle yet + /// + Pending = 0, + + /// + /// The provider charges the cycles + /// + Active = 10, + + /// + /// The last cycle failed; the provider may still retry it + /// + PastDue = 20, + + /// + /// Cancelled by the customer, staff, the initial order or the provider; never resumed + /// + Cancelled = 30, + + /// + /// Every cycle of a limited number of cycles is paid + /// + Completed = 40 +} diff --git a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs index e9f2afe4f..f1ed821bf 100644 --- a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs +++ b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs @@ -937,6 +937,10 @@ await dbContext.CreateIndex(_serviceProvider.GetRequiredService.Create().Ascending(x => x.PaymentTransactionId) .Ascending(x => x.CreatedOnUtc), "PaymentTransactionId_CreatedOnUtc"); + //the recurring payment of an order, found by the order the customer placed; unique, so an order never has two + await dbContext.CreateIndex(_serviceProvider.GetRequiredService>(), + OrderBuilder.Create().Ascending(x => x.InitialOrderId), "InitialOrderId", true); + //queuemail await dbContext.CreateIndex(_queuedEmailRepository, OrderBuilder.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc"); diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentIndex.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentIndex.cs new file mode 100644 index 000000000..63c944ff5 --- /dev/null +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentIndex.cs @@ -0,0 +1,39 @@ +using Grand.Data; +using Grand.Domain.Orders; +using Grand.Infrastructure.Migrations; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Grand.Module.Migration.Migrations._2._5; + +public class MigrationRecurringPaymentIndex : IMigration +{ + private const string IndexName = "InitialOrderId"; + + public int Priority => 1; + public DbVersion Version => new(2, 5); + public Guid Identity => new("eada9902-2f77-483a-b70b-42ca679ee016"); + public string Name => "Index on Recurring payment 2.5"; + + public async Task UpgradeProcess(IServiceProvider serviceProvider) + { + var repository = serviceProvider.GetRequiredService>(); + var databaseContext = serviceProvider.GetRequiredService(); + var logService = serviceProvider.GetRequiredService>(); + + try + { + //every order screen and every provider webhook finds the recurring payment by the order the customer placed; + //unique, so an order never has two + await databaseContext.CreateIndex(repository, + OrderBuilder.Create().Ascending(x => x.InitialOrderId), IndexName, true); + } + catch (Exception ex) + { + logService.LogError(ex, "UpgradeProcess - RecurringPaymentIndex (2.5)"); + return false; + } + + return true; + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs index f82ab16c1..897756fbb 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs @@ -279,7 +279,7 @@ public TestHandler(PlaceOrderContainer details, Mock appr new Mock().Object, new Mock().Object, mediator.Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, approval.Object, - placement.Object, Claims(), translation.Object, new ShippingSettings(), new ShoppingCartSettings(), new PaymentSettings(), + placement.Object, Claims(), new Mock().Object, translation.Object, new ShippingSettings(), new ShoppingCartSettings(), new PaymentSettings(), new OrderSettings(), new OidcLoginConfig(), new TaxSettings()) { _details = details; diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs index 669e06c8d..df5b5f28e 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs @@ -164,7 +164,7 @@ public TestHandler(PlaceOrderContainer details, Mock pla new Mock().Object, new Mock().Object, mediator.Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, - new Mock().Object, placement.Object, Claims(), + new Mock().Object, placement.Object, Claims(), new Mock().Object, translation.Object, new ShippingSettings(), new ShoppingCartSettings(), new PaymentSettings(), new OrderSettings(), new OidcLoginConfig(), new TaxSettings()) { diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs index 0d7c81464..1f4640a23 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs @@ -61,6 +61,7 @@ public void Init() new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, new ShippingSettings(), new ShoppingCartSettings(), new PaymentSettings(), new OrderSettings(), new OidcLoginConfig(), new TaxSettings()); @@ -186,10 +187,11 @@ public async Task Handle_PreparesDetailsFromTheCommand() _paymentTransactions = new Mock(); _history = new Mock(); + _recurringPayments = new Mock(); var handler = new ClaimTestHandler(details, calls, orders.Object, products.Object, inventory.Object, giftVouchers.Object, customers.Object, reservations.Object, placement.Object, claims.Object, - translation.Object, _paymentTransactions.Object, _history.Object); + translation.Object, _paymentTransactions.Object, _history.Object, _recurringPayments.Object); return (handler, claims, orders, inventory, giftVouchers, customers, details, calls); } @@ -373,6 +375,65 @@ public async Task Handle_PendingAtCheckout_RecordsNothing() It.IsAny()), Times.Never); } + private Mock _recurringPayments; + + //a product billed every month until cancelled; the payment method is checked by an order placement rule + private (ClaimTestHandler handler, Mock orders, Mock customers, + PlaceOrderContainer details) RecurringSetup() + { + var (handler, _, orders, _, _, customers, details, _) = ClaimSetup(); + details.IsRecurring = true; + details.RecurringCycleLength = 1; + details.RecurringCyclePeriodId = RecurringCyclePeriod.Months; + details.RecurringTotalCycles = 0; + return (handler, orders, customers, details); + } + + [TestMethod] + public async Task Handle_RecurringOrder_CreatesPendingRecurringPaymentForTheOrder() + { + var (handler, orders, _, details) = RecurringSetup(); + Order inserted = null; + orders.Setup(x => x.InsertOrder(It.IsAny())).Callback(o => inserted = o); + + var result = await handler.Handle(ClaimCommand(details), CancellationToken.None); + + Assert.IsEmpty(result.Errors); + Assert.AreEqual(1, inserted.RecurringCycleNumber); + _recurringPayments.Verify(x => x.InsertRecurringPayment(It.Is(rp => + rp.InitialOrderId == inserted.Id && rp.StoreId == "store" && rp.CustomerId == "buyer" && + rp.PaymentMethodSystemName == "Payments.Card" && rp.CycleLength == 1 && + rp.CyclePeriodId == RecurringCyclePeriod.Months && rp.TotalCycles == 0 && rp.CyclesPaid == 0 && + rp.Status == RecurringPaymentStatus.Pending)), Times.Once); + } + + [TestMethod] + public async Task Handle_StandardOrder_CreatesNoRecurringPayment() + { + var (handler, _, orders, _, _, _, details, _) = ClaimSetup(); + Order inserted = null; + orders.Setup(x => x.InsertOrder(It.IsAny())).Callback(o => inserted = o); + + await handler.Handle(ClaimCommand(details), CancellationToken.None); + + Assert.AreEqual(0, inserted.RecurringCycleNumber); + _recurringPayments.Verify(x => x.InsertRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_RecurringPaymentWriteFails_CartIsAlreadyCleared() + { + //an error shown with the cart still full would let the buyer place and pay a second order + var (handler, _, customers, details) = RecurringSetup(); + _recurringPayments.Setup(x => x.InsertRecurringPayment(It.IsAny())) + .ThrowsAsync(new Exception("write failed")); + + var result = await handler.Handle(ClaimCommand(details), CancellationToken.None); + + Assert.IsNotEmpty(result.Errors); + customers.Verify(x => x.ClearShoppingCartItem("buyer", details.Cart), Times.Once); + } + private class ClaimTestHandler : PlaceOrderCommandHandler { private readonly List _calls; @@ -384,7 +445,8 @@ public ClaimTestHandler(PlaceOrderContainer details, List calls, IOrderS IProductReservationService productReservationService, IOrderPlacementService orderPlacementService, ICheckoutClaimService checkoutClaimService, ITranslationService translationService, IPaymentTransactionService paymentTransactionService, - IPaymentTransactionHistoryService paymentTransactionHistoryService) : base(orderService, + IPaymentTransactionHistoryService paymentTransactionHistoryService, + IRecurringPaymentService recurringPaymentService) : base(orderService, new Mock().Object, productService, inventoryManageService, new Mock().Object, paymentTransactionService, paymentTransactionHistoryService, new Mock>().Object, new Mock().Object, @@ -397,7 +459,8 @@ public ClaimTestHandler(PlaceOrderContainer details, List calls, IOrderS new Mock().Object, new Mock().Object, new Mock().Object, productReservationService, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, - orderPlacementService, checkoutClaimService, translationService, new ShippingSettings(), + orderPlacementService, checkoutClaimService, recurringPaymentService, translationService, + new ShippingSettings(), new ShoppingCartSettings(), new PaymentSettings(), new OrderSettings(), new OidcLoginConfig(), new TaxSettings()) { diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentRuleProviderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentRuleProviderTests.cs new file mode 100644 index 000000000..a29449bba --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentRuleProviderTests.cs @@ -0,0 +1,118 @@ +using Grand.Business.Checkout.Services.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Common.Localization; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Customers; +using Grand.Domain.Directory; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Grand.Domain.Stores; +using Grand.Domain.Tax; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Services.Orders; + +[TestClass] +public class RecurringPaymentRuleProviderTests +{ + private Mock _paymentService; + private Mock _recurringPaymentService; + private RecurringPaymentRuleProvider _rule; + private double? _total; + private int _totalCalls; + + [TestInitialize] + public void Init() + { + _total = 30; + _totalCalls = 0; + _recurringPaymentService = new Mock(); + _recurringPaymentService.Setup(x => x.HasRecurringProducts(It.IsAny>())) + .ReturnsAsync(true); + _paymentService = new Mock(); + _paymentService.Setup(x => x.SupportRecurringPayment("Payments.Card")).ReturnsAsync(true); + var translation = new Mock(); + translation.Setup(x => x.GetResource("Checkout.RecurringPayment.NothingToPay", "pl", It.IsAny(), + It.IsAny())).Returns("Nothing to pay"); + translation.Setup(x => x.GetResource("Checkout.RecurringPayment.PaymentMethodNotSupported", "pl", + It.IsAny(), It.IsAny())).Returns("Method cannot charge in cycles"); + + _rule = new RecurringPaymentRuleProvider(_recurringPaymentService.Object, _paymentService.Object, + translation.Object); + } + + private OrderPlacementContext Context(string paymentMethod) + { + var calculation = new CalculationContext(new Customer { Id = "buyer1" }, new Store { Id = "s1" }, + new Currency { CurrencyCode = "EUR" }, TaxDisplayType.IncludingTax); + return new OrderPlacementContext([new ShoppingCartItem { ProductId = "p1" }], calculation, + new Language { Id = "pl" }, paymentMethod, () => + { + _totalCalls++; + return Task.FromResult(_total); + }); + } + + [TestMethod] + public async Task Evaluate_StandardCart_AllowsWithoutAskingForTotal() + { + _recurringPaymentService.Setup(x => x.HasRecurringProducts(It.IsAny>())) + .ReturnsAsync(false); + + var result = await _rule.Evaluate(Context("Payments.CashOnDelivery")); + + Assert.AreEqual(OrderPlacementDecision.Allow, result.Decision); + Assert.AreEqual(0, _totalCalls); + } + + [TestMethod] + public async Task Evaluate_RecurringCartWithCapableMethod_Allows() + { + var result = await _rule.Evaluate(Context("Payments.Card")); + + Assert.AreEqual(OrderPlacementDecision.Allow, result.Decision); + } + + [TestMethod] + public async Task Evaluate_RecurringCartWithMethodWithoutRecurringSupport_Blocks() + { + //a method chosen in a stale tab or posted by hand + var result = await _rule.Evaluate(Context("Payments.CashOnDelivery")); + + Assert.AreEqual(OrderPlacementDecision.Block, result.Decision); + Assert.AreEqual("Method cannot charge in cycles", result.Reason); + } + + [TestMethod] + public async Task Evaluate_RecurringCartBeforeMethodIsChosen_Allows() + { + var result = await _rule.Evaluate(Context(null)); + + Assert.AreEqual(OrderPlacementDecision.Allow, result.Decision); + _paymentService.Verify(x => x.SupportRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Evaluate_RecurringCartWithZeroTotal_Blocks() + { + //a full discount, a gift voucher or loyalty points: the payment step is skipped and the method cleared + _total = 0; + + var result = await _rule.Evaluate(Context(null)); + + Assert.AreEqual(OrderPlacementDecision.Block, result.Decision); + Assert.AreEqual("Nothing to pay", result.Reason); + } + + [TestMethod] + public async Task Evaluate_RecurringCartBeforeShippingIsChosen_Allows() + { + _total = null; + + var result = await _rule.Evaluate(Context(null)); + + Assert.AreEqual(OrderPlacementDecision.Allow, result.Decision); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs new file mode 100644 index 000000000..9c9d6456b --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -0,0 +1,85 @@ +using Grand.Business.Checkout.Services.Orders; +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Data; +using Grand.Data.Tests.MongoDb; +using Grand.Domain.Catalog; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Services.Orders; + +[TestClass] +public class RecurringPaymentServiceTests +{ + private Mock _productService; + private IRepository _repository; + private RecurringPaymentService _service; + + [TestInitialize] + public void Init() + { + _repository = new MongoDBRepositoryTest(); + _productService = new Mock(); + _productService.Setup(x => x.GetProductById("standard", false)).ReturnsAsync(new Product { Id = "standard" }); + _productService.Setup(x => x.GetProductById("recurring", false)) + .ReturnsAsync(new Product { Id = "recurring", IsRecurring = true }); + _service = new RecurringPaymentService(_repository, _productService.Object, new Mock().Object); + } + + [TestMethod] + public async Task InsertRecurringPayment_CanBeReadByIdAndByInitialOrder() + { + var rp = new RecurringPayment { + InitialOrderId = "o1", CycleLength = 1, CyclePeriodId = RecurringCyclePeriod.Months, TotalCycles = 12 + }; + await _service.InsertRecurringPayment(rp); + + Assert.AreEqual("o1", (await _service.GetRecurringPaymentById(rp.Id)).InitialOrderId); + Assert.AreEqual(rp.Id, (await _service.GetRecurringPaymentByInitialOrderId("o1")).Id); + } + + [TestMethod] + public async Task GetRecurringPaymentByInitialOrderId_OtherOrder_ReturnsNull() + { + await _service.InsertRecurringPayment(new RecurringPayment { InitialOrderId = "o1" }); + Assert.IsNull(await _service.GetRecurringPaymentByInitialOrderId("o2")); + } + + [TestMethod] + public async Task UpdateRecurringPayment_SavesStatusAndCycles() + { + var rp = new RecurringPayment { InitialOrderId = "o1" }; + await _service.InsertRecurringPayment(rp); + rp.Status = RecurringPaymentStatus.Active; + rp.Cycles.Add(new RecurringPaymentCycle { CycleNumber = 1, OrderId = "o1", ProviderReference = "in_1" }); + await _service.UpdateRecurringPayment(rp); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.AreEqual("in_1", saved.Cycles.Single().ProviderReference); + } + + [TestMethod] + public async Task HasRecurringProducts_CartWithRecurringProduct_ReturnsTrue() + { + Assert.IsTrue(await _service.HasRecurringProducts([ + new ShoppingCartItem { ProductId = "standard" }, new ShoppingCartItem { ProductId = "recurring" } + ])); + } + + [TestMethod] + public async Task HasRecurringProducts_StandardOrMissingProducts_ReturnsFalse() + { + Assert.IsFalse(await _service.HasRecurringProducts([ + new ShoppingCartItem { ProductId = "standard" }, new ShoppingCartItem { ProductId = "deleted" } + ])); + } + + [TestMethod] + public async Task InsertRecurringPayment_Null_Throws() + { + await Assert.ThrowsExactlyAsync(() => _service.InsertRecurringPayment(null)); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs index e761b10bf..c073c65a1 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs @@ -2,6 +2,7 @@ using Grand.Business.Core.Enums.Checkout; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Configuration; +using Grand.Business.Core.Utilities.Checkout; using Grand.Domain.Orders; using Grand.Domain.Payments; using Grand.SharedKernel; @@ -292,4 +293,65 @@ public async Task GetAdditionalHandlingFee_SystemnameNull_ReturnZero() }; Assert.AreEqual(0, await _paymentService.GetAdditionalHandlingFee(cart, null)); } + + [TestMethod] + public async Task SupportRecurringPayment_ProviderWithoutOverride_IsFalse() + { + Assert.IsFalse(await ((IPaymentProvider)new LegacyProvider()).SupportRecurringPayment()); + } + + [TestMethod] + public async Task CancelRecurringPayment_ProviderWithoutOverride_ReturnsError() + { + var result = await ((IPaymentProvider)new LegacyProvider()).CancelRecurringPayment(new RecurringPayment()); + Assert.IsFalse(result.Success); + } + + [TestMethod] + public async Task PaymentService_SupportRecurringPayment_UnknownMethod_IsFalse() + { + _paymentProviderMock.Setup(c => c.SystemName).Returns("Payments.Test"); + Assert.IsFalse(await _paymentService.SupportRecurringPayment("Missing")); + } + + [TestMethod] + public async Task PaymentService_SupportRecurringPayment_AsksTheProvider() + { + _paymentProviderMock.Setup(c => c.SystemName).Returns("Payments.Test"); + _paymentProviderMock.Setup(c => c.SupportRecurringPayment()).ReturnsAsync(true); + Assert.IsTrue(await _paymentService.SupportRecurringPayment("Payments.Test")); + } + + //a provider written before the recurring contract existed keeps its defaults + private class LegacyProvider : IPaymentProvider + { + public string ConfigurationUrl => throw new NotImplementedException(); + public string SystemName => "Legacy"; + public string FriendlyName => throw new NotImplementedException(); + public int Priority => throw new NotImplementedException(); + public IList LimitedToStores => throw new NotImplementedException(); + public IList LimitedToGroups => throw new NotImplementedException(); + public PaymentMethodType PaymentMethodType => throw new NotImplementedException(); + public string LogoURL => throw new NotImplementedException(); + public Task InitPaymentTransaction() => throw new NotImplementedException(); + public Task ProcessPayment(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task PostProcessPayment(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task PostRedirectPayment(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task HidePaymentMethod(IList cart) => throw new NotImplementedException(); + public Task GetAdditionalHandlingFee(IList cart) => throw new NotImplementedException(); + public Task Capture(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task Refund(RefundPaymentRequest refundPaymentRequest) => throw new NotImplementedException(); + public Task Void(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task CancelPayment(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task CanRePostRedirectPayment(PaymentTransaction paymentTransaction) => throw new NotImplementedException(); + public Task> ValidatePaymentForm(IDictionary model) => throw new NotImplementedException(); + public Task SavePaymentInfo(IDictionary model) => throw new NotImplementedException(); + public Task GetControllerRouteName() => throw new NotImplementedException(); + public Task SkipPaymentInfo() => throw new NotImplementedException(); + public Task Description() => throw new NotImplementedException(); + public Task SupportCapture() => throw new NotImplementedException(); + public Task SupportPartiallyRefund() => throw new NotImplementedException(); + public Task SupportRefund() => throw new NotImplementedException(); + public Task SupportVoid() => throw new NotImplementedException(); + } } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs index fdfc497d3..86459d2f7 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs @@ -2,6 +2,7 @@ using Grand.Business.Checkout.Validators; using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes; +using Grand.Business.Core.Interfaces.Common.Directory; using Grand.Business.Core.Interfaces.Common.Localization; using Grand.Business.Core.Interfaces.Common.Security; using Grand.Business.Core.Utilities.Catalog; @@ -23,6 +24,7 @@ public class ShoppingCartValidatorsTests { private static readonly Language Language = new() { Id = "lang1" }; private Mock _aclServiceMock; + private Mock _groupServiceMock; private Mock _checkoutAttributeParserMock; private Mock _checkoutAttributeServiceMock; private Mock _permissionServiceMock; @@ -40,6 +42,7 @@ public void Init() _checkoutAttributeServiceMock = new Mock(); _productServiceMock = new Mock(); _aclServiceMock = new Mock(); + _groupServiceMock = new Mock(); _productAttributeService = new Mock(); _productReservationServiceMock = new Mock(); _permissionServiceMock = new Mock(); @@ -710,7 +713,8 @@ public async Task ShoppingCartWarningsValidator_Success() { //Arrange var shoppingCartWarningsValidator = - new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object); + new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object, + _groupServiceMock.Object); _productServiceMock.Setup(x => x.GetProductById(It.IsAny(), false)) .Returns(() => Task.FromResult(new Product())); @@ -747,7 +751,8 @@ public async Task ShoppingCartWarningsValidator_Fail() { //Arrange var shoppingCartWarningsValidator = - new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object); + new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object, + _groupServiceMock.Object); _productServiceMock.Setup(x => x.GetProductById("1", false)) .Returns(() => Task.FromResult(new Product @@ -782,4 +787,59 @@ public async Task ShoppingCartWarningsValidator_Fail() //Assert Assert.IsFalse(result.IsValid); } -} \ No newline at end of file + + [TestMethod] + public async Task ShoppingCartWarningsValidator_GuestWithRecurringProduct_AddsAccountWarning() + { + var result = await ValidateRecurringAccount(isRecurring: true, isGuest: true); + + Assert.AreEqual("Log in to buy it", result.Errors.Single().ErrorMessage); + } + + [TestMethod] + public async Task ShoppingCartWarningsValidator_RegisteredWithRecurringProduct_NoAccountWarning() + { + var result = await ValidateRecurringAccount(isRecurring: true, isGuest: false); + + Assert.IsTrue(result.IsValid); + } + + [TestMethod] + public async Task ShoppingCartWarningsValidator_GuestWithStandardProduct_NoAccountWarning() + { + var result = await ValidateRecurringAccount(isRecurring: false, isGuest: true); + + Assert.IsTrue(result.IsValid); + } + + [TestMethod] + public async Task ShoppingCartWarningsValidator_GuestWishlistWithRecurringProduct_NoAccountWarning() + { + //a wishlist buys nothing + var result = await ValidateRecurringAccount(isRecurring: true, isGuest: true, ShoppingCartType.Wishlist); + + Assert.IsTrue(result.IsValid); + } + + private async Task ValidateRecurringAccount(bool isRecurring, + bool isGuest, ShoppingCartType cartType = ShoppingCartType.ShoppingCart) + { + var customer = new Customer(); + _groupServiceMock.Setup(x => x.IsGuest(customer)).ReturnsAsync(isGuest); + _translationServiceMock.Setup(x => x.GetResource("ShoppingCart.RecurringProductsRequireAccount", "lang1", + It.IsAny(), It.IsAny())).Returns("Log in to buy it"); + _productServiceMock.Setup(x => x.GetProductById(It.IsAny(), false)) + .ReturnsAsync(new Product { + IsRecurring = isRecurring, RecurringCycleLength = 1, RecurringCyclePeriodId = RecurringCyclePeriod.Months + }); + var validator = new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object, + _groupServiceMock.Object); + + //two items, so a warning added per item would show twice + return await validator.ValidateAsync(new ShoppingCartWarningsValidatorRecord(customer, new Store(), + new List { + new() { ProductId = "1", ShoppingCartTypeId = cartType }, + new() { ProductId = "2", ShoppingCartTypeId = cartType } + }, Language)); + } +} diff --git a/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerConfirmOrderTests.cs b/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerConfirmOrderTests.cs index d3f1477ec..c2f087f43 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerConfirmOrderTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerConfirmOrderTests.cs @@ -69,7 +69,8 @@ public void Init() new Mock().Object, new Mock().Object, new Mock>().Object, new Mock().Object, _mediator.Object, new Mock().Object, new Mock().Object, - new Mock().Object, new Mock().Object, new OrderSettings(), + new Mock().Object, new Mock().Object, + new Mock().Object, new OrderSettings(), new OidcLoginConfig(), new LoyaltyPointsSettings(), new PaymentSettings(), new ShippingSettings(), new AddressSettings()) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } diff --git a/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerOrderApprovalTests.cs b/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerOrderApprovalTests.cs index a967f5c13..af0d4d217 100644 --- a/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerOrderApprovalTests.cs +++ b/src/Tests/Grand.Web.Tests/Controllers/CheckoutControllerOrderApprovalTests.cs @@ -36,11 +36,13 @@ public class CheckoutControllerOrderApprovalTests private List _cart; private CheckoutController _controller; private Mock _customerService; + private Mock _groupService; private Language _language; private Mock _mediator; private Mock _paymentService; private PaymentSettings _paymentSettings; private Mock _placement; + private Mock _recurringPaymentService; private Mock _shippingService; [TestInitialize] @@ -83,19 +85,33 @@ public void Init() _paymentService = new Mock(); _shippingService = new Mock(); _paymentSettings = new PaymentSettings(); + _groupService = new Mock(); + _recurringPaymentService = new Mock(); _controller = new CheckoutController(context.Object, translation.Object, _customerService.Object, - new Mock().Object, cartService.Object, _shippingService.Object, + _groupService.Object, cartService.Object, _shippingService.Object, new Mock().Object, _paymentService.Object, new Mock().Object, new Mock>().Object, new Mock().Object, _mediator.Object, new Mock().Object, - new Mock().Object, _approval.Object, _placement.Object, new OrderSettings(), + new Mock().Object, _approval.Object, _placement.Object, + _recurringPaymentService.Object, new OrderSettings { AnonymousCheckoutAllowed = true }, new OidcLoginConfig(), new LoyaltyPointsSettings(), _paymentSettings, new ShippingSettings(), new AddressSettings()) { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; } + [TestMethod] + public async Task Index_GuestWithRecurringCart_IsSentToLogIn() + { + //guest checkout is allowed, but a recurring payment is cancelled from My account + _groupService.Setup(g => g.IsGuest(It.IsAny())).ReturnsAsync(true); + _recurringPaymentService.Setup(r => r.HasRecurringProducts(_cart)).ReturnsAsync(true); + + Assert.IsInstanceOfType(await _controller.Index()); + Assert.IsInstanceOfType(await _controller.Start()); + } + [TestMethod] public async Task SavePaymentMethod_ApprovalRequiredAndMethodNotAllowed_RefusesWithoutSaving() { diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Checkout/CheckoutOrderApprovalHandlersTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Checkout/CheckoutOrderApprovalHandlersTests.cs index fb9f4edd3..0f666887d 100644 --- a/src/Tests/Grand.Web.Tests/Features/Handlers/Checkout/CheckoutOrderApprovalHandlersTests.cs +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Checkout/CheckoutOrderApprovalHandlersTests.cs @@ -33,6 +33,8 @@ public class CheckoutOrderApprovalHandlersTests private readonly Language _language = new() { Id = "pl" }; private Mock _paymentService; private Mock _placement; + private Mock _recurringPaymentService; + private readonly HashSet _recurringMethods = []; private Grand.Domain.Stores.Store _store; private Mock _translation; @@ -53,6 +55,7 @@ public void Init() _translation.Setup(t => t.GetResource("Checkout.TradeCredit.Available")).Returns("Available {0} of {1}."); _translation.Setup(t => t.GetResource("Checkout.TradeCredit.Overdue")).Returns("Overdue."); _placement = new Mock(); + _recurringPaymentService = new Mock(); } private void Evaluates(OrderPlacementDecision decision, params string[] reasons) => @@ -64,9 +67,10 @@ private void State(bool required) => Evaluates(required ? OrderPlacementDecision.RequireApproval : OrderPlacementDecision.Allow, required ? ["Over the limit."] : []); - private static Mock Provider(string systemName) + private static Mock Provider(string systemName, bool supportRecurringPayment = false) { var provider = new Mock(); + provider.Setup(p => p.SupportRecurringPayment()).ReturnsAsync(supportRecurringPayment); provider.Setup(p => p.SystemName).Returns(systemName); provider.Setup(p => p.FriendlyName).Returns(systemName); provider.Setup(p => p.PaymentMethodType).Returns(PaymentMethodType.Standard); @@ -78,7 +82,7 @@ private static Mock Provider(string systemName) private GetPaymentMethodHandler PaymentHandler(params string[] methods) { _paymentService.Setup(p => p.LoadActivePaymentMethods(It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync(methods.Select(m => Provider(m).Object).ToList()); + .ReturnsAsync(methods.Select(m => Provider(m, _recurringMethods.Contains(m)).Object).ToList()); var tax = new Mock(); tax.Setup(t => t.GetPaymentMethodAdditionalFee(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync((0d, 0d)); @@ -91,6 +95,7 @@ private GetPaymentMethodHandler PaymentHandler(params string[] methods) new Mock().Object, new Mock().Object, currencyService.Object, priceFormatter.Object, _paymentService.Object, tax.Object, _approval.Object, _placement.Object, _credit.Object, _translation.Object, + _recurringPaymentService.Object, new LoyaltyPointsSettings(), new PaymentSettings()); } @@ -155,6 +160,62 @@ public async Task PaymentMethods_ApprovalNotRequired_KeepsEveryMethod() _approval.Verify(a => a.IsPaymentMethodAllowed(It.IsAny()), Times.Never); } + [TestMethod] + public async Task PaymentMethods_RecurringCart_KeepsOnlyRecurringCapableMethods() + { + State(false); + RecurringCart(); + _recurringMethods.Add("Payments.Card"); + + var model = await PaymentHandler("Payments.Card", "Payments.CashOnDelivery") + .Handle(PaymentRequest(), CancellationToken.None); + + CollectionAssert.AreEqual(new[] { "Payments.Card" }, + model.PaymentMethods.Select(pm => pm.PaymentMethodSystemName).ToArray()); + Assert.IsNull(model.NoPaymentMethodMessage); + } + + [TestMethod] + public async Task PaymentMethods_RecurringCartAndNoCapableMethod_ShowsTheMessage() + { + State(false); + RecurringCart(); + + var model = await PaymentHandler("Payments.Card", "Payments.CashOnDelivery") + .Handle(PaymentRequest(), CancellationToken.None); + + Assert.IsEmpty(model.PaymentMethods); + Assert.AreEqual("Checkout.RecurringPayment.NoPaymentMethod", model.NoPaymentMethodMessage); + } + + [TestMethod] + public async Task PaymentMethods_StandardCart_KeepsEveryMethod() + { + State(false); + + var model = await PaymentHandler("Payments.Card", "Payments.CashOnDelivery") + .Handle(PaymentRequest(), CancellationToken.None); + + Assert.HasCount(2, model.PaymentMethods); + Assert.IsNull(model.NoPaymentMethodMessage); + } + + [TestMethod] + public async Task PaymentMethods_RecurringCartAndNoCapableMethodAndApproval_KeepsTheRecurringMessage() + { + State(true); + RecurringCart(); + + var model = await PaymentHandler("Payments.Card").Handle(PaymentRequest(), CancellationToken.None); + + Assert.IsEmpty(model.PaymentMethods); + Assert.AreEqual("Checkout.RecurringPayment.NoPaymentMethod", model.NoPaymentMethodMessage); + } + + private void RecurringCart() => + _recurringPaymentService.Setup(p => p.HasRecurringProducts(It.IsAny>())) + .ReturnsAsync(true); + [TestMethod] public async Task PaymentMethods_NoTradeCredit_ShowsNoNotice() { diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 9d6a22a7d..5bac00d05 100644 Binary files a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml and b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml differ diff --git a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml index ff26c780e..35709eb7d 100644 --- a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml +++ b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml @@ -2592,4 +2592,16 @@ Billed to + + Log in or register to buy a product billed in cycles: you will manage and cancel it in your account. + + + None of the available payment methods can charge in cycles, so this order cannot be paid. + + + The selected payment method cannot charge in cycles. Choose another payment method. + + + An order billed in cycles must have something to pay. + diff --git a/src/Web/Grand.Web/Controllers/CheckoutController.cs b/src/Web/Grand.Web/Controllers/CheckoutController.cs index 93e2c89c1..b958edde7 100644 --- a/src/Web/Grand.Web/Controllers/CheckoutController.cs +++ b/src/Web/Grand.Web/Controllers/CheckoutController.cs @@ -55,6 +55,7 @@ public CheckoutController( IShoppingCartValidator shoppingCartValidator, IOrderApprovalService orderApprovalService, IOrderPlacementService orderPlacementService, + IRecurringPaymentService recurringPaymentService, OrderSettings orderSettings, OidcLoginConfig oidcLoginConfig, LoyaltyPointsSettings loyaltyPointsSettings, @@ -78,6 +79,7 @@ public CheckoutController( _shoppingCartValidator = shoppingCartValidator; _orderApprovalService = orderApprovalService; _orderPlacementService = orderPlacementService; + _recurringPaymentService = recurringPaymentService; _orderSettings = orderSettings; _oidcLoginConfig = oidcLoginConfig; _loyaltyPointsSettings = loyaltyPointsSettings; @@ -99,7 +101,7 @@ public virtual async Task Index() if (!cart.Any()) return RedirectToRoute("ShoppingCart"); - if (await _groupService.IsGuest(customer) && !_orderSettings.AnonymousCheckoutAllowed(_oidcLoginConfig)) + if (await _groupService.IsGuest(customer) && !await GuestCanCheckOut(cart)) return Challenge(); //reset checkout data @@ -136,7 +138,7 @@ public virtual async Task Start() if (!cart.Any()) return RedirectToRoute("ShoppingCart"); - if (await _groupService.IsGuest(_contextAccessor.WorkContext.CurrentCustomer) && !_orderSettings.AnonymousCheckoutAllowed(_oidcLoginConfig)) + if (await _groupService.IsGuest(_contextAccessor.WorkContext.CurrentCustomer) && !await GuestCanCheckOut(cart)) return Challenge(); //validation (checkout attributes) @@ -849,6 +851,7 @@ public virtual async Task CompleteRedirectionPayment(string payme private readonly IShoppingCartValidator _shoppingCartValidator; private readonly IOrderApprovalService _orderApprovalService; private readonly IOrderPlacementService _orderPlacementService; + private readonly IRecurringPaymentService _recurringPaymentService; private readonly OrderSettings _orderSettings; private readonly OidcLoginConfig _oidcLoginConfig; private readonly LoyaltyPointsSettings _loyaltyPointsSettings; @@ -891,6 +894,16 @@ private static IList SerializeModelState(ModelStateDictionary modelState #region Private methods + /// + /// A guest is sent to log in when the store has no guest checkout, or when the cart holds a recurring product: + /// a recurring payment is cancelled from My account + /// + private async Task GuestCanCheckOut(IList cart) + { + return _orderSettings.AnonymousCheckoutAllowed(_oidcLoginConfig) && + !await _recurringPaymentService.HasRecurringProducts(cart); + } + private async Task CartValidate(IList cart) { if (!cart.Any()) diff --git a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs index c8f75e43e..0b339c77e 100644 --- a/src/Web/Grand.Web/Controllers/ShoppingCartController.cs +++ b/src/Web/Grand.Web/Controllers/ShoppingCartController.cs @@ -23,6 +23,7 @@ using Grand.Web.Features.Models.ShoppingCart; using Grand.Web.Models.ShoppingCart; using Grand.Mediator; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using Grand.SharedKernel.Extensions; using Grand.Web.Common.Localization; @@ -45,6 +46,7 @@ public ShoppingCartController( IRequestPermissionService permissionService, IMediator mediator, IShoppingCartValidator shoppingCartValidator, + IRecurringPaymentService recurringPaymentService, ShoppingCartSettings shoppingCartSettings, OrderSettings orderSettings, OidcLoginConfig oidcLoginConfig) @@ -59,6 +61,7 @@ public ShoppingCartController( _permissionService = permissionService; _mediator = mediator; _shoppingCartValidator = shoppingCartValidator; + _recurringPaymentService = recurringPaymentService; _shoppingCartSettings = shoppingCartSettings; _orderSettings = orderSettings; _oidcLoginConfig = oidcLoginConfig; @@ -110,6 +113,7 @@ private ShoppingCartType[] PrepareCartTypes() private readonly IRequestPermissionService _permissionService; private readonly IMediator _mediator; private readonly IShoppingCartValidator _shoppingCartValidator; + private readonly IRecurringPaymentService _recurringPaymentService; private readonly ShoppingCartSettings _shoppingCartSettings; private readonly OrderSettings _orderSettings; private readonly OidcLoginConfig _oidcLoginConfig; @@ -472,6 +476,12 @@ public virtual async Task StartCheckout(CheckoutAttributeSelected _contextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity>( SystemCustomerFieldNames.CheckoutAttributes, _contextAccessor.StoreContext.CurrentStore.Id); + //a recurring payment is cancelled from My account: a guest logs in or registers first and comes back to the cart, + //where the cart warning stops a guest who did not + if (await _groupService.IsGuest(_contextAccessor.WorkContext.CurrentCustomer) && + await _recurringPaymentService.HasRecurringProducts(cart)) + return Challenge(new AuthenticationProperties { RedirectUri = Url.RouteUrl("ShoppingCart") }); + var checkoutAttributeWarnings = await _shoppingCartValidator.GetShoppingCartWarnings(cart, checkoutAttributes, _contextAccessor.CalculationContext(), _contextAccessor.WorkContext.WorkingLanguage, true, true); diff --git a/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs b/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs index ebf8bc3ba..59d25b2e2 100644 --- a/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs +++ b/src/Web/Grand.Web/Features/Handlers/Checkout/GetPaymentMethodHandler.cs @@ -32,6 +32,7 @@ public class GetPaymentMethodHandler : IRequestHandler(); + foreach (var pm in availablepaymentMethods) + if (await pm.SupportRecurringPayment()) + recurringPaymentMethods.Add(pm); + availablepaymentMethods = recurringPaymentMethods; + if (availablepaymentMethods.Count == 0) + model.NoPaymentMethodMessage = _translationService.GetResource("Checkout.RecurringPayment.NoPaymentMethod"); + } + //a blocked order has nothing to pay with; one that needs an approval may only use the payment methods the admin chose var evaluation = await _orderPlacementService.Evaluate(request.Cart, new CalculationContext(request.Customer, request.Store, request.Currency, request.TaxDisplayType), @@ -111,8 +126,9 @@ await _loyaltyPointsCalculationService.ConvertLoyaltyPointsToAmount(loyaltyPoint { availablepaymentMethods = availablepaymentMethods .Where(pm => _orderApprovalService.IsPaymentMethodAllowed(pm.SystemName)).ToList(); + //a list already emptied by the recurring filter keeps its own reason if (availablepaymentMethods.Count == 0) - model.NoPaymentMethodMessage = _translationService.GetResource("Checkout.OrderApproval.NoPaymentMethod"); + model.NoPaymentMethodMessage ??= _translationService.GetResource("Checkout.OrderApproval.NoPaymentMethod"); } model.TradeCreditNotice = await GetTradeCreditNotice(request);