diff --git a/.ai/skills/message-notification.md b/.ai/skills/message-notification.md index d3eacfb15..5ea93c79e 100644 --- a/.ai/skills/message-notification.md +++ b/.ai/skills/message-notification.md @@ -32,7 +32,7 @@ Do not use this skill as the primary review for MongoDB queries or security; com 6. Use DotLiquid syntax: `{{Drop.Property}}` for values, `{% if condition %}...{% endif %}` for conditions, `{% for item in Collection %}...{% endfor %}` for loops. #### Sending Messages -7. Add a typed send method to the area interface that owns the recipient's flow, `IMessageProviderService` in `src/Business/Grand.Business.Core/Interfaces/Messages/` (Customer, Order, Newsletter, Catalog, MerchandiseReturn, Vendor, Cms), when the trigger is a recurring, well-defined business event. Follow the signature pattern: +7. Add a typed send method to the area interface that owns the recipient's flow, `IMessageProviderService` in `src/Business/Grand.Business.Core/Interfaces/Messages/` (Customer, Order, Newsletter, Catalog, MerchandiseReturn, RecurringPayment, Vendor, Cms), when the trigger is a recurring, well-defined business event. Follow the signature pattern: ```csharp Task SendXxxMessage(TEntity entity, Store store, string languageId); ``` @@ -94,6 +94,7 @@ Task SendOrderPlacedCustomerMessage(Order order, Customer customer, string | `INewsletterMessageProviderService` | newsletter subscription activation and deactivation | | `ICatalogMessageProviderService` | email a friend, wishlist, product questions and reviews, low stock, back in stock, auctions and bids | | `IMerchandiseReturnMessageProviderService` | merchandise return created, status changed, notes | +| `IRecurringPaymentMessageProviderService` | recurring payment cancelled and cycle failed, for customer and store owner | | `IVendorMessageProviderService` | vendor application, information change, vendor reviews, contact vendor | | `ICmsMessageProviderService` | blog, knowledgebase article and news comments | @@ -167,6 +168,7 @@ public class MessageTokensAddedEvent : INotification { | `LiquidShipment` | `{{Shipment.*}}` | Shipment | | `LiquidProduct` | `{{Product.*}}` | Product | | `LiquidMerchandiseReturn` | `{{MerchandiseReturn.*}}` | MerchandiseReturn | +| `LiquidRecurringPayment` | `{{RecurringPayment.*}}` | RecurringPayment (the initial order comes from `LiquidOrder`) | | `LiquidGiftVoucher` | `{{GiftVoucher.*}}` | GiftVoucher | | `LiquidNewsLetterSubscription` | `{{NewsLetterSubscription.*}}` | NewsLetterSubscription | | `LiquidVendor` | `{{Vendor.*}}` | Vendor | diff --git a/.ai/skills/plugin-payment.md b/.ai/skills/plugin-payment.md index 438634dad..3156649a1 100644 --- a/.ai/skills/plugin-payment.md +++ b/.ai/skills/plugin-payment.md @@ -65,6 +65,7 @@ Do not use this skill for order processing business logic outside the payment fl - 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. +- `CancelRecurringPayment` stops the gateway's schedule for `RecurringPayment.ProviderReference` and returns. The shop cancels through `CancelRecurringPaymentCommand`, which calls it outside the recurring payment's lock and then, under the lock on a fresh read, marks it `Cancelled` only on success; a throw counts as a refusal. Webhooks for the payment are not held up by the call, and a cycle recorded meanwhile is kept. A `Pending` payment with no `ProviderReference` is cancelled without the call: it has no reference to stop yet, the gateway may have started the subscription at checkout already, and the first cycle or failure it reports on the cancelled payment makes the shop stop the gateway, so send `ProviderReference` with the failure command as well. A cycle charged after the payment was cancelled or completed is noted on the initial order for staff to refund. - A provider reports to the shop with three mediator commands (`Grand.Business.Core.Commands.Checkout.Orders`): `RecordRecurringPaymentCycleCommand` (a cycle was paid; the shop places the cycle order from the second cycle on and, whenever the recurring payment is completed or cancelled after the cycle is recorded, calls `CancelRecurringPayment` to stop the gateway), `RecordRecurringPaymentFailureCommand` and `RecordRecurringPaymentEndedCommand` (the gateway ended it). - Pass `RecurringPayment.Id` to the gateway as metadata when the schedule starts, and send it back as `RecurringPaymentId` in every command. The webhook must verify the gateway signature before sending any of them. - `CycleReference` is the gateway's invoice or charge id, so a resent webhook is recorded once and the command returns `false`. `ProviderReference` is the subscription id. diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelRecurringPaymentCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelRecurringPaymentCommandHandler.cs new file mode 100644 index 000000000..9c99c3d26 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelRecurringPaymentCommandHandler.cs @@ -0,0 +1,42 @@ +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.Utilities.Checkout; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class CancelRecurringPaymentCommandHandler( + IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(CancelRecurringPaymentCommand request, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request.RecurringPayment); + ArgumentException.ThrowIfNullOrEmpty(request.CancelledBy); + + return await recurringPaymentService.Cancel(request.RecurringPayment.Id, request.CancelledBy, StopAtGateway); + } + + private async Task StopAtGateway(RecurringPayment recurringPayment) + { + try + { + return await paymentService.CancelRecurringPayment(recurringPayment); + } + catch (Exception e) + { + //a throw is treated as a refusal: the gateway may still be charging, so the status must stay as it is + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", + recurringPayment.Id); + var result = new CancelRecurringPaymentResult(); + result.AddError(e.Message); + return result; + } + } +} diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs index 4ce731fb4..052f75f5d 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -45,7 +45,7 @@ await mediator.Send(new PlaceRecurringCycleOrderCommand { logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order {OrderId} of cycle {CycleNumber} ({CycleReference}) could not be placed or marked paid", claim.RecurringPayment.Id, claim.Cycle.OrderId, claim.Cycle.CycleNumber, request.CycleReference); // the order may exist already (the failure can come after it was inserted), so the note names it - await AddNote(claim.RecurringPayment, + await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment, $"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order {claim.Cycle.OrderId} could not be placed or marked paid: {e.Message}"); // the failure must reach the provider so it can log or report it, but only after the gateway was // asked to stop: the claim is recorded, so a resend is a no-op and would never stop it @@ -54,49 +54,16 @@ await AddNote(claim.RecurringPayment, // a cycle claimed while the payment is already completed or cancelled means the gateway still charges if (claim.RecurringPayment.Status is RecurringPaymentStatus.Completed or RecurringPaymentStatus.Cancelled) - await StopTheGateway(claim.RecurringPayment); - - placementFailure?.Throw(); - - return true; - } - - private async Task StopTheGateway(RecurringPayment recurringPayment) - { - IEnumerable errors; - try - { - var result = await paymentService.CancelRecurringPayment(recurringPayment); - errors = result.Success ? [] : result.Errors; - } - catch (Exception e) { - // a throw is treated as a refusal: the claim is recorded and a resend is a no-op, so the note is the only trace - logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", - recurringPayment.Id); - errors = [e.Message]; + // the last cycle completing the payment is expected; any other was taken after the shop ended it + if (!claim.Completed) + await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment, + $"Cycle {claim.Cycle.CycleNumber} was charged at the payment gateway ({request.CycleReference}) after the recurring payment was {claim.RecurringPayment.Status.ToString().ToLowerInvariant()}: check whether the customer must be refunded"); + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, claim.RecurringPayment); } - // the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run - if (errors.Any()) - await AddNote(recurringPayment, - $"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); - } + placementFailure?.Throw(); - private async Task AddNote(RecurringPayment recurringPayment, string note) - { - try - { - await orderService.InsertOrderNote(new OrderNote { - OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, - CreatedOnUtc = DateTime.UtcNow - }); - } - catch (Exception e) - { - // the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded cycle - logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}", - recurringPayment.Id, note); - } + return true; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs index e2edf074f..2eb78908d 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -1,10 +1,17 @@ using Grand.Business.Core.Commands.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Domain.Orders; using Grand.Mediator; +using Microsoft.Extensions.Logging; namespace Grand.Business.Checkout.Commands.Handlers.Orders; -public class RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentService recurringPaymentService) +public class RecordRecurringPaymentFailureCommandHandler( + IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, + IOrderService orderService, + ILogger logger) : IRequestHandler { public async Task Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken) @@ -12,7 +19,21 @@ public async Task Handle(RecordRecurringPaymentFailureCommand request, Can ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); - return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, - request.Reason); + if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, + request.Reason)) + return true; + + // a failed charge on a payment the shop ended means the gateway still tries to charge, typically a payment + // cancelled while pending, before the gateway's reference was known + var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); + if (recurringPayment?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed && + recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference)) + { + if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) + recurringPayment.ProviderReference = request.ProviderReference; + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); + } + + return false; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs new file mode 100644 index 000000000..35e462790 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs @@ -0,0 +1,53 @@ +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Domain.Orders; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +/// +/// What the provider commands do when the gateway reports on a recurring payment the shop already ended +/// +internal static class RecurringPaymentGateway +{ + public static async Task Stop(IPaymentService paymentService, IOrderService orderService, ILogger logger, + RecurringPayment recurringPayment) + { + IEnumerable errors; + try + { + var result = await paymentService.CancelRecurringPayment(recurringPayment); + errors = result.Success ? [] : result.Errors; + } + catch (Exception e) + { + // a throw is treated as a refusal: the report is recorded and a resend is a no-op, so the note is the only trace + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", + recurringPayment.Id); + errors = [e.Message]; + } + + // the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run + if (errors.Any()) + await AddNote(orderService, logger, recurringPayment, + $"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); + } + + public static async Task AddNote(IOrderService orderService, ILogger logger, RecurringPayment recurringPayment, + string note) + { + try + { + await orderService.InsertOrderNote(new OrderNote { + OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, + CreatedOnUtc = DateTime.UtcNow + }); + } + catch (Exception e) + { + // the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded report + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}", + recurringPayment.Id, note); + } + } +} diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/OrderCancelledRecurringPaymentHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/OrderCancelledRecurringPaymentHandler.cs new file mode 100644 index 000000000..729726f5b --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Events/Orders/OrderCancelledRecurringPaymentHandler.cs @@ -0,0 +1,85 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Events.Orders; + +/// +/// Cancels the recurring payment of an initial order that was cancelled or deleted +/// +public class OrderCancelledRecurringPaymentHandler : INotificationHandler, + INotificationHandler +{ + private readonly ILogger _logger; + private readonly IMediator _mediator; + private readonly IOrderService _orderService; + private readonly IRecurringPaymentService _recurringPaymentService; + + public OrderCancelledRecurringPaymentHandler(IRecurringPaymentService recurringPaymentService, + IOrderService orderService, IMediator mediator, ILogger logger) + { + _recurringPaymentService = recurringPaymentService; + _orderService = orderService; + _mediator = mediator; + _logger = logger; + } + + public Task Handle(OrderCancelledEvent notification, CancellationToken cancellationToken) + { + return CancelRecurringPayment(notification.Order, "cancelled"); + } + + public Task Handle(OrderDeletedEvent notification, CancellationToken cancellationToken) + { + return CancelRecurringPayment(notification.Order, "deleted"); + } + + private async Task CancelRecurringPayment(Order order, string what) + { + // a cycle order or a plain order never owns a recurring payment, and a plain order costs no query + if (order.RecurringCycleNumber != 1) return; + + try + { + var recurringPayment = await _recurringPaymentService.GetRecurringPaymentByInitialOrderId(order.Id); + if (recurringPayment == null) return; + + var result = await _mediator.Send(new CancelRecurringPaymentCommand { + RecurringPayment = recurringPayment, + CancelledBy = $"Order #{order.OrderNumber} {what}" + }); + if (!result.Success) + await AddNote(order, what, string.Join(", ", result.Errors)); + } + catch (Exception ex) + { + // the order is already cancelled or deleted: publishing must complete whatever happens here + _logger.LogError(ex, + "Order {OrderNumber} ({OrderId}) was {What} but its recurring payment could not be cancelled", + order.OrderNumber, order.Id, what); + await AddNote(order, what, ex.Message); + } + } + + private async Task AddNote(Order order, string what, string reason) + { + try + { + await _orderService.InsertOrderNote(new OrderNote { + OrderId = order.Id, + Note = + $"The order was {what}, but its recurring payment could not be cancelled, so the payment gateway may still charge: {reason}", + DisplayToCustomer = false, + CreatedOnUtc = DateTime.UtcNow + }); + } + catch (Exception ex) + { + _logger.LogError(ex, "The note about the recurring payment of order {OrderId} could not be saved", + order.Id); + } + } +} diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs new file mode 100644 index 000000000..6795b10ed --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs @@ -0,0 +1,95 @@ +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Business.Core.Interfaces.Messages; +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Events.Orders; + +/// +/// E-mails the customer and the store when a recurring payment is cancelled or a cycle fails +/// +public class RecurringPaymentMessagesHandler : INotificationHandler, + INotificationHandler +{ + private readonly ICustomerService _customerService; + private readonly LanguageSettings _languageSettings; + private readonly ILogger _logger; + private readonly IRecurringPaymentMessageProviderService _messageProviderService; + private readonly IOrderService _orderService; + + public RecurringPaymentMessagesHandler(IOrderService orderService, ICustomerService customerService, + IRecurringPaymentMessageProviderService messageProviderService, LanguageSettings languageSettings, + ILogger logger) + { + _orderService = orderService; + _customerService = customerService; + _messageProviderService = messageProviderService; + _languageSettings = languageSettings; + _logger = logger; + } + + public Task Handle(RecurringPaymentCancelledEvent notification, CancellationToken cancellationToken) + { + return Send(notification.RecurringPayment, + _messageProviderService.SendRecurringPaymentCancelledCustomerMessage, + _messageProviderService.SendRecurringPaymentCancelledStoreOwnerMessage); + } + + public Task Handle(RecurringPaymentPastDueEvent notification, CancellationToken cancellationToken) + { + return Send(notification.RecurringPayment, + _messageProviderService.SendRecurringPaymentFailedCustomerMessage, + _messageProviderService.SendRecurringPaymentFailedStoreOwnerMessage); + } + + private async Task Send(RecurringPayment recurringPayment, + Func> sendToCustomer, + Func> sendToStoreOwner) + { + try + { + // a deleted order is still loaded, so its number and items stay available + var initialOrder = await _orderService.GetOrderById(recurringPayment.InitialOrderId); + if (initialOrder == null) + { + _logger.LogWarning( + "The initial order {OrderId} of recurring payment {RecurringPaymentId} was not found, no message was sent", + recurringPayment.InitialOrderId, recurringPayment.Id); + return; + } + + var customer = await _customerService.GetCustomerById(recurringPayment.CustomerId); + + // each send has its own try, so a failing customer message still lets the store owner one go + await TrySend(recurringPayment, + () => sendToCustomer(recurringPayment, initialOrder, customer, initialOrder.CustomerLanguageId)); + await TrySend(recurringPayment, + () => sendToStoreOwner(recurringPayment, initialOrder, customer, + _languageSettings.DefaultAdminLanguageId)); + } + catch (Exception ex) + { + // the status is already saved: publishing must complete whatever happens here + _logger.LogError(ex, "The messages about recurring payment {RecurringPaymentId} could not be sent", + recurringPayment.Id); + } + } + + private async Task TrySend(RecurringPayment recurringPayment, Func> send) + { + try + { + await send(); + } + catch (Exception ex) + { + _logger.LogError(ex, "A message about recurring payment {RecurringPaymentId} could not be sent", + recurringPayment.Id); + } + } +} diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index f9f07426e..539194fc2 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -1,3 +1,4 @@ +using Grand.Business.Core.Events.Checkout.Orders; using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Utilities.Checkout; @@ -26,16 +27,6 @@ public virtual async Task InsertRecurringPayment(RecurringPayment recurringPayme 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 async Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc) { @@ -116,6 +107,8 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS //event notification await mediator.EntityUpdated(recurringPayment); + if (enteredPastDue) + await mediator.Publish(new RecurringPaymentPastDueEvent(recurringPayment)); return enteredPastDue; } @@ -140,10 +133,81 @@ public virtual async Task RecordEnded(string recurringPaymentId) //event notification await mediator.EntityUpdated(recurringPayment); + await mediator.Publish(new RecurringPaymentCancelledEvent(recurringPayment)); return true; } + public virtual async Task Cancel(string recurringPaymentId, string cancelledBy, + Func> stopAtGateway) + { + ArgumentException.ThrowIfNullOrEmpty(cancelledBy); + ArgumentNullException.ThrowIfNull(stopAtGateway); + + RecurringPayment recurringPayment; + var cancelled = false; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null) + { + var notFound = new CancelRecurringPaymentResult(); + notFound.AddError("The recurring payment was not found"); + return notFound; + } + + if (recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + return new CancelRecurringPaymentResult(); + + //a pending payment has no reference to stop yet; the gateway may have started the subscription at checkout, + //and the first cycle it reports, recorded on the cancelled payment, stops it + if (recurringPayment.Status == RecurringPaymentStatus.Pending && + string.IsNullOrEmpty(recurringPayment.ProviderReference)) + { + await MarkCancelled(recurringPayment, cancelledBy); + cancelled = true; + } + } + + if (!cancelled) + { + //asked outside the lock: the call can be slow, and webhooks for this payment must not wait for it or + //outlive its lease; every write below is made under the lock on a fresh read + var result = await stopAtGateway(recurringPayment); + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + //a webhook or another cancel ended it meanwhile, which also explains a refusal from the gateway + if (recurringPayment == null || + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + return new CancelRecurringPaymentResult(); + + //never cancelled while the gateway may still charge + if (!result.Success) + return result; + + await MarkCancelled(recurringPayment, cancelledBy); + } + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + await mediator.Publish(new RecurringPaymentCancelledEvent(recurringPayment)); + + return new CancelRecurringPaymentResult(); + } + + private Task MarkCancelled(RecurringPayment recurringPayment, string cancelledBy) + { + recurringPayment.Status = RecurringPaymentStatus.Cancelled; + recurringPayment.CancelledOnUtc = DateTime.UtcNow; + recurringPayment.CancelledBy = cancelledBy; + + return repository.UpdateAsync(recurringPayment); + } + private static string LockKey(string recurringPaymentId) { return $"{nameof(RecurringPayment)}:{recurringPaymentId}"; diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs new file mode 100644 index 000000000..7d4690a44 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs @@ -0,0 +1,19 @@ +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// Cancels a recurring payment, asking the payment provider to stop charging whenever the gateway may be charging. +/// The result carries the provider's errors when it refused, and the recurring payment then keeps its status +/// +public class CancelRecurringPaymentCommand : IRequest +{ + public RecurringPayment RecurringPayment { get; set; } + + /// + /// Who cancelled it: the customer's e-mail, the staff name, or the reason + /// + public string CancelledBy { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs index 60df50ea4..488ceb07b 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -10,6 +10,12 @@ public class RecordRecurringPaymentFailureCommand : IRequest { public string RecurringPaymentId { get; set; } + /// + /// The provider's reference of the recurring payment (for example the subscription id), used to stop the + /// gateway when the failure arrives for a payment the shop cancelled before learning it + /// + public string ProviderReference { get; set; } + /// /// The provider's reference of the cycle that failed /// diff --git a/src/Business/Grand.Business.Core/Events/Checkout/Orders/RecurringPaymentCancelledEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/Orders/RecurringPaymentCancelledEvent.cs new file mode 100644 index 000000000..a19ae8dff --- /dev/null +++ b/src/Business/Grand.Business.Core/Events/Checkout/Orders/RecurringPaymentCancelledEvent.cs @@ -0,0 +1,20 @@ +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Core.Events.Checkout.Orders; + +/// +/// Recurring payment cancelled event +/// +public class RecurringPaymentCancelledEvent : INotification +{ + public RecurringPaymentCancelledEvent(RecurringPayment recurringPayment) + { + RecurringPayment = recurringPayment; + } + + /// + /// Recurring payment + /// + public RecurringPayment RecurringPayment { get; private set; } +} diff --git a/src/Business/Grand.Business.Core/Events/Checkout/Orders/RecurringPaymentPastDueEvent.cs b/src/Business/Grand.Business.Core/Events/Checkout/Orders/RecurringPaymentPastDueEvent.cs new file mode 100644 index 000000000..f90b0c4e6 --- /dev/null +++ b/src/Business/Grand.Business.Core/Events/Checkout/Orders/RecurringPaymentPastDueEvent.cs @@ -0,0 +1,20 @@ +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Core.Events.Checkout.Orders; + +/// +/// Recurring payment past due event +/// +public class RecurringPaymentPastDueEvent : INotification +{ + public RecurringPaymentPastDueEvent(RecurringPayment recurringPayment) + { + RecurringPayment = recurringPayment; + } + + /// + /// Recurring payment + /// + public RecurringPayment RecurringPayment { get; private set; } +} diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index e0e0ba082..c703bba6f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -13,11 +13,6 @@ public interface IRecurringPaymentService /// Task InsertRecurringPayment(RecurringPayment recurringPayment); - /// - /// Updates a recurring payment - /// - Task UpdateRecurringPayment(RecurringPayment recurringPayment); - /// /// Records a cycle the provider reports as paid, once: under a lock, so a gateway resending the event claims /// nothing. Returns null when the recurring payment is unknown or the cycle reference was already recorded @@ -38,6 +33,15 @@ Task ClaimCycle(string recurringPaymentId, string providerR /// Task RecordEnded(string recurringPaymentId); + /// + /// Cancels a recurring payment, writing it under the same lock on a fresh read. Unless it is Pending without a + /// provider reference, stopAtGateway is called first, outside the lock, and the payment is cancelled only when + /// it succeeds; its errors are returned otherwise. Cancelling a Cancelled or Completed recurring payment, or one + /// that became so during the call, succeeds and changes nothing; an unknown one returns an error + /// + Task Cancel(string recurringPaymentId, string cancelledBy, + Func> stopAtGateway); + /// /// Gets a recurring payment /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs new file mode 100644 index 000000000..6f784fc41 --- /dev/null +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs @@ -0,0 +1,54 @@ +using Grand.Domain.Customers; +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Interfaces.Messages; + +/// +/// Messages about a recurring payment; each one carries the initial order's tokens +/// +public interface IRecurringPaymentMessageProviderService +{ + /// + /// Sends a 'Recurring payment cancelled' message to the customer + /// + /// Recurring payment + /// The order the customer placed + /// Customer; the recipient + /// Message language identifier + /// Queued email identifier; 0 when nothing was queued + Task SendRecurringPaymentCancelledCustomerMessage(RecurringPayment recurringPayment, Order initialOrder, + Customer customer, string languageId); + + /// + /// Sends a 'Recurring payment cancelled' message to the store owner + /// + /// Recurring payment + /// The order the customer placed + /// Customer + /// Message language identifier + /// Queued email identifier; 0 when nothing was queued + Task SendRecurringPaymentCancelledStoreOwnerMessage(RecurringPayment recurringPayment, Order initialOrder, + Customer customer, string languageId); + + /// + /// Sends a 'Recurring payment failed' message to the customer + /// + /// Recurring payment + /// The order the customer placed + /// Customer; the recipient + /// Message language identifier + /// Queued email identifier; 0 when nothing was queued + Task SendRecurringPaymentFailedCustomerMessage(RecurringPayment recurringPayment, Order initialOrder, + Customer customer, string languageId); + + /// + /// Sends a 'Recurring payment failed' message to the store owner + /// + /// Recurring payment + /// The order the customer placed + /// Customer + /// Message language identifier + /// Queued email identifier; 0 when nothing was queued + Task SendRecurringPaymentFailedStoreOwnerMessage(RecurringPayment recurringPayment, Order initialOrder, + Customer customer, string languageId); +} diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs new file mode 100644 index 000000000..9d6851fd7 --- /dev/null +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs @@ -0,0 +1,41 @@ +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Common.Localization; +using Grand.Business.Messages.Commands.Tokens; +using Grand.Business.Messages.DotLiquidDrops; +using Grand.Mediator; +using System.Net; + +namespace Grand.Business.Messages.Commands.Handlers.Messages; + +public class GetRecurringPaymentTokensCommandHandler : IRequestHandler +{ + private readonly ITranslationService _translationService; + + public GetRecurringPaymentTokensCommandHandler(ITranslationService translationService) + { + _translationService = translationService; + } + + public Task Handle(GetRecurringPaymentTokensCommand request, + CancellationToken cancellationToken) + { + var recurringPayment = request.RecurringPayment; + var liquidRecurringPayment = new LiquidRecurringPayment { + CycleLength = recurringPayment.CycleLength, + //resource text, used in the subject as well: encoding would turn "AnnĂ©es" into "Années" + CyclePeriod = recurringPayment.CyclePeriodId.GetTranslationEnum(_translationService, request.Language.Id), + CyclesPaid = recurringPayment.CyclesPaid, + TotalCycles = recurringPayment.TotalCycles, + //the gateway and the person who cancelled typed these, so they are encoded like every such value + LastError = Encode(recurringPayment.LastError), + CancelledBy = Encode(recurringPayment.CancelledBy) + }; + return Task.FromResult(liquidRecurringPayment); + } + + private static string Encode(string value) + { + return WebUtility.HtmlEncode(value ?? string.Empty); + } +} diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs new file mode 100644 index 000000000..2df989c05 --- /dev/null +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs @@ -0,0 +1,12 @@ +using Grand.Business.Messages.DotLiquidDrops; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Messages.Commands.Tokens; + +public class GetRecurringPaymentTokensCommand : IRequest +{ + public RecurringPayment RecurringPayment { get; set; } + public Language Language { get; set; } +} diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs index eb8666f9e..d30b4aa1d 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs @@ -94,6 +94,19 @@ public LiquidObjectBuilder AddOrderApprovalTokens(OrderApproval approval, Custom return this; } + public LiquidObjectBuilder AddRecurringPaymentTokens(RecurringPayment recurringPayment, Language language) + { + _chain.Add(async liquidObject => + { + var liquidRecurringPayment = await _mediator.Send(new GetRecurringPaymentTokensCommand { + RecurringPayment = recurringPayment, Language = language + }); + liquidObject.RecurringPayment = liquidRecurringPayment; + await _mediator.EntityTokensAdded(recurringPayment, liquidRecurringPayment, liquidObject); + }); + return this; + } + public LiquidObjectBuilder AddShipmentTokens(Shipment shipment, Order order, Store store, DomainHost host, Language language) { diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs index 954506d11..79cf33078 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs @@ -6,12 +6,14 @@ namespace Grand.Business.Messages.DotLiquidDrops; internal static class LiquidObjectBuilderExtensions { - public static void AddCustomerTokensIfNotNull(this LiquidObjectBuilder builder, Customer customer, Store store, - DomainHost host, Language language) + public static LiquidObjectBuilder AddCustomerTokensIfNotNull(this LiquidObjectBuilder builder, + Customer customer, Store store, DomainHost host, Language language) { if (customer != null) { builder.AddCustomerTokens(customer, store, host, language); } + + return builder; } } diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs new file mode 100644 index 000000000..79e9eebaa --- /dev/null +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs @@ -0,0 +1,41 @@ +using DotLiquid; + +namespace Grand.Business.Messages.DotLiquidDrops; + +/// +/// Tokens of a recurring payment. The command handler fills every value, so the getters never touch a service. +/// The initial order's tokens come from the order drop +/// +public class LiquidRecurringPayment : Drop +{ + public LiquidRecurringPayment() + { + AdditionalTokens = new Dictionary(); + } + + public int CycleLength { get; set; } + + /// + /// The cycle period, translated + /// + public string CyclePeriod { get; set; } + + public int CyclesPaid { get; set; } + + /// + /// The total cycles; 0 means until cancelled + /// + public int TotalCycles { get; set; } + + /// + /// The reason the last cycle failed, as the gateway reported it; HTML-encoded + /// + public string LastError { get; set; } + + /// + /// Who cancelled: the customer, a staff name or the provider; HTML-encoded + /// + public string CancelledBy { get; set; } + + public IDictionary AdditionalTokens { get; set; } +} diff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs index 96d77f80e..83817d7e5 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs @@ -15,6 +15,18 @@ public static class MessageTemplateNames public const string OrderApprovalDecided = "OrderApproval.Decided"; public const string OrderApprovalStaffRequested = "OrderApproval.StaffRequested"; + public const string RecurringPaymentCancelledCustomerNotification = + "RecurringPayment.Cancelled.CustomerNotification"; + + public const string RecurringPaymentCancelledStoreOwnerNotification = + "RecurringPayment.Cancelled.StoreOwnerNotification"; + + public const string RecurringPaymentFailedCustomerNotification = + "RecurringPayment.PaymentFailed.CustomerNotification"; + + public const string RecurringPaymentFailedStoreOwnerNotification = + "RecurringPayment.PaymentFailed.StoreOwnerNotification"; + public const string SendOrderPlacedStoreOwnerMessage = "OrderPlaced.StoreOwnerNotification"; public const string SendOrderPaidStoreOwnerMessage = "OrderPaid.StoreOwnerNotification"; public const string SendOrderCancelledStoreOwnerMessage = "OrderCancelled.StoreOwnerNotification"; diff --git a/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs b/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs index f54f5bf4c..4279912b4 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageTokenProvider.cs @@ -41,6 +41,7 @@ public virtual string[] GetListOfAllowedTokens() typeof(LiquidOrderItem), typeof(LiquidProduct), typeof(LiquidProductReview), + typeof(LiquidRecurringPayment), typeof(LiquidMerchandiseReturn), typeof(LiquidGuestOrderLink), typeof(LiquidShipment), diff --git a/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs new file mode 100644 index 000000000..5290bb4f5 --- /dev/null +++ b/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs @@ -0,0 +1,120 @@ +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Messages; +using Grand.Business.Messages.DotLiquidDrops; +using Grand.Domain.Common; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Stores; +using Grand.Mediator; + +namespace Grand.Business.Messages.Services; + +public class RecurringPaymentMessageProviderService : IRecurringPaymentMessageProviderService +{ + #region Ctor + + public RecurringPaymentMessageProviderService( + IMessageLookupService messageLookupService, + IMessageProviderService messageProviderService, + IMediator mediator) + { + _messageLookupService = messageLookupService; + _messageProviderService = messageProviderService; + _mediator = mediator; + } + + #endregion + + #region Fields + + private readonly IMessageLookupService _messageLookupService; + private readonly IMessageProviderService _messageProviderService; + private readonly IMediator _mediator; + + #endregion + + #region Methods + + /// + /// Sends a recurring payment message to the customer, or to the e-mail account of the template when + /// toStoreOwner is set + /// + protected virtual async Task SendRecurringPaymentMessage(string templateName, + RecurringPayment recurringPayment, Order initialOrder, Customer customer, string languageId, + bool toStoreOwner) + { + ArgumentNullException.ThrowIfNull(recurringPayment); + ArgumentNullException.ThrowIfNull(initialOrder); + + if (!toStoreOwner && string.IsNullOrEmpty(customer?.Email)) + return 0; + + var store = await _messageLookupService.GetStore(recurringPayment.StoreId); + var language = await _messageLookupService.EnsureLanguageIsActive(languageId, store.Id); + + var messageTemplate = await _messageLookupService.GetMessageTemplate(templateName, store.Id); + if (messageTemplate == null) + return 0; + + var emailAccount = await _messageLookupService.GetEmailAccountOfMessageTemplate(messageTemplate, language.Id); + + var host = store.LinkHost(null); + var builder = new LiquidObjectBuilder(_mediator); + builder.AddStoreTokens(store, language, emailAccount) + .AddCustomerTokensIfNotNull(customer, store, host, language) + .AddOrderTokens(initialOrder, customer, store, host) + .AddRecurringPaymentTokens(recurringPayment, language); + + var liquidObject = await builder.BuildAsync(); + await _mediator.MessageTokensAdded(messageTemplate, liquidObject); + + var toEmail = toStoreOwner ? emailAccount.Email : customer.Email; + var toName = toStoreOwner ? emailAccount.DisplayName : customer.GetFullName(); + return await _messageProviderService.SendNotification(messageTemplate, emailAccount, + language.Id, liquidObject, + toEmail, toName, + reference: Reference.Order, objectId: initialOrder.Id); + } + + /// + /// Sends a 'Recurring payment cancelled' message to the customer + /// + public virtual async Task SendRecurringPaymentCancelledCustomerMessage(RecurringPayment recurringPayment, + Order initialOrder, Customer customer, string languageId) + { + return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentCancelledCustomerNotification, + recurringPayment, initialOrder, customer, languageId, toStoreOwner: false); + } + + /// + /// Sends a 'Recurring payment cancelled' message to the store owner + /// + public virtual async Task SendRecurringPaymentCancelledStoreOwnerMessage(RecurringPayment recurringPayment, + Order initialOrder, Customer customer, string languageId) + { + return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentCancelledStoreOwnerNotification, + recurringPayment, initialOrder, customer, languageId, toStoreOwner: true); + } + + /// + /// Sends a 'Recurring payment failed' message to the customer + /// + public virtual async Task SendRecurringPaymentFailedCustomerMessage(RecurringPayment recurringPayment, + Order initialOrder, Customer customer, string languageId) + { + return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentFailedCustomerNotification, + recurringPayment, initialOrder, customer, languageId, toStoreOwner: false); + } + + /// + /// Sends a 'Recurring payment failed' message to the store owner + /// + public virtual async Task SendRecurringPaymentFailedStoreOwnerMessage(RecurringPayment recurringPayment, + Order initialOrder, Customer customer, string languageId) + { + return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentFailedStoreOwnerNotification, + recurringPayment, initialOrder, customer, languageId, toStoreOwner: true); + } + + #endregion +} diff --git a/src/Business/Grand.Business.Messages/Startup/StartupApplication.cs b/src/Business/Grand.Business.Messages/Startup/StartupApplication.cs index 2b2562528..3369e5f2c 100644 --- a/src/Business/Grand.Business.Messages/Startup/StartupApplication.cs +++ b/src/Business/Grand.Business.Messages/Startup/StartupApplication.cs @@ -20,6 +20,7 @@ public void ConfigureServices(IServiceCollection services, IConfiguration config services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.RecurringPayments.cs b/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.RecurringPayments.cs new file mode 100644 index 000000000..fd9832fad --- /dev/null +++ b/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.RecurringPayments.cs @@ -0,0 +1,66 @@ +using Grand.Domain.Messages; + +namespace Grand.Module.Installer.Services.MessageTemplates; + +public static partial class MessageTemplateSeed +{ + private static IEnumerable RecurringPaymentTemplates(string ea) + { + return new List { + new() { + Name = "RecurringPayment.Cancelled.CustomerNotification", + Subject = "{{Store.Name}}: your recurring payment for order #{{Order.OrderNumber}} is cancelled", + Body = Layout( + "Your recurring payment is cancelled.", + "Recurring payment cancelled", + @"

Hello {{Customer.FullName | Escape}},

+

The recurring payment for order #{{Order.OrderNumber}} at {{Store.Name}} is cancelled. You will not be charged for further cycles.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+

Every {{RecurringPayment.CycleLength}} {{RecurringPayment.CyclePeriod}}{% if RecurringPayment.TotalCycles > 0 %}, {{RecurringPayment.CyclesPaid}} of {{RecurringPayment.TotalCycles}} paid{% endif %}

+ " + Button("{{Order.OrderURLForCustomer}}", "View the order") + @" +

To buy again, place a new order.

"), + IsActive = true, + EmailAccountId = ea + }, + new() { + Name = "RecurringPayment.Cancelled.StoreOwnerNotification", + Subject = "{{Store.Name}}: recurring payment for order #{{Order.OrderNumber}} cancelled", + Body = Layout( + "A recurring payment was cancelled.", + "Recurring payment cancelled", + @"

The recurring payment for order #{{Order.OrderNumber}} ({{Customer.Email | Escape}}) was cancelled. Cancelled by: {{RecurringPayment.CancelledBy}}.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+

Every {{RecurringPayment.CycleLength}} {{RecurringPayment.CyclePeriod}}{% if RecurringPayment.TotalCycles > 0 %}, {{RecurringPayment.CyclesPaid}} of {{RecurringPayment.TotalCycles}} paid{% endif %}

"), + IsActive = true, + EmailAccountId = ea + }, + new() { + Name = "RecurringPayment.PaymentFailed.CustomerNotification", + Subject = "{{Store.Name}}: the payment for order #{{Order.OrderNumber}} could not be taken", + Body = Layout( + "A payment for your recurring order could not be taken.", + "Payment failed", + @"

Hello {{Customer.FullName | Escape}},

+

The payment for the next cycle of your recurring payment for order #{{Order.OrderNumber}} could not be taken{% if RecurringPayment.LastError != '' %}: {{RecurringPayment.LastError}}{% endif %}.

+

The payment provider may try again. Please check that your payment details are up to date.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+ " + Button("{{Order.OrderURLForCustomer}}", "View the order")), + IsActive = true, + EmailAccountId = ea + }, + new() { + Name = "RecurringPayment.PaymentFailed.StoreOwnerNotification", + Subject = "{{Store.Name}}: a recurring payment for order #{{Order.OrderNumber}} failed", + Body = Layout( + "A cycle of a recurring payment failed.", + "Recurring payment failed", + @"

A cycle of the recurring payment for order #{{Order.OrderNumber}} ({{Customer.Email | Escape}}) failed{% if RecurringPayment.LastError != '' %}: {{RecurringPayment.LastError}}{% endif %}.

+

The payment provider may retry it.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+

Every {{RecurringPayment.CycleLength}} {{RecurringPayment.CyclePeriod}}{% if RecurringPayment.TotalCycles > 0 %}, {{RecurringPayment.CyclesPaid}} of {{RecurringPayment.TotalCycles}} paid{% endif %}

"), + IsActive = true, + EmailAccountId = ea + } + }; + } +} diff --git a/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.cs b/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.cs index 692f494f5..459866574 100644 --- a/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.cs +++ b/src/Modules/Grand.Module.Installer/Services/MessageTemplates/MessageTemplateSeed.cs @@ -15,6 +15,7 @@ public static List Build(string emailAccountId) templates.AddRange(ServiceTemplates(emailAccountId)); templates.AddRange(OrderApprovalTemplates(emailAccountId)); templates.AddRange(PaymentReminderTemplates(emailAccountId)); + templates.AddRange(RecurringPaymentTemplates(emailAccountId)); return templates; } diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentTemplates.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentTemplates.cs new file mode 100644 index 000000000..636e9b9e6 --- /dev/null +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentTemplates.cs @@ -0,0 +1,117 @@ +using Grand.Data; +using Grand.Domain.Messages; +using Grand.Infrastructure.Caching; +using Grand.Infrastructure.Caching.Constants; +using Grand.Infrastructure.Migrations; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using static Grand.Module.Migration.Migrations._2._5.MigrationOrderApproval; + +namespace Grand.Module.Migration.Migrations._2._5; + +/// +/// Adds the e-mails for a recurring payment cancelled and for a cycle that failed, to the customer and to the +/// store. The installer creates the same for new installations (it is not referenced from here, so the bodies +/// are repeated below - a test keeps them equal). Idempotent: a template that exists (the operator may have +/// created or edited one) is never touched. +/// +public class MigrationRecurringPaymentTemplates : IMigration +{ + public int Priority => 2; + public DbVersion Version => new(2, 5); + public Guid Identity => new("4967620a-f03f-45bc-aa56-b53fba5d0862"); + public string Name => "Recurring payment e-mails 2.5"; + + public async Task UpgradeProcess(IServiceProvider serviceProvider) + { + var logService = serviceProvider.GetRequiredService>(); + + try + { + var repository = serviceProvider.GetRequiredService>(); + var emailAccountId = await GetEmailAccountId(serviceProvider); + foreach (var template in Templates(emailAccountId)) + { + var existing = + await repository.FirstOrDefaultAsync(repository.Table.Where(x => x.Name == template.Name)); + if (existing == null) + await repository.InsertAsync(template); + } + + //a lookup made before the upgrade may have cached "no such template" + var cache = serviceProvider.GetService(); + if (cache != null) + await cache.RemoveByPrefix(CacheKey.MESSAGETEMPLATES_PATTERN_KEY); + } + catch (Exception ex) + { + logService.LogError(ex, "UpgradeProcess - RecurringPaymentTemplates (2.5)"); + return false; + } + + return true; + } + + /// + /// The templates, as the installer seeds them: same names, subjects and tokens + /// + public static IList Templates(string emailAccountId) + { + return new List { + new() { + Name = "RecurringPayment.Cancelled.CustomerNotification", + Subject = "{{Store.Name}}: your recurring payment for order #{{Order.OrderNumber}} is cancelled", + Body = Layout( + "Your recurring payment is cancelled.", + "Recurring payment cancelled", + @"

Hello {{Customer.FullName | Escape}},

+

The recurring payment for order #{{Order.OrderNumber}} at {{Store.Name}} is cancelled. You will not be charged for further cycles.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+

Every {{RecurringPayment.CycleLength}} {{RecurringPayment.CyclePeriod}}{% if RecurringPayment.TotalCycles > 0 %}, {{RecurringPayment.CyclesPaid}} of {{RecurringPayment.TotalCycles}} paid{% endif %}

+ " + Button("{{Order.OrderURLForCustomer}}", "View the order") + @" +

To buy again, place a new order.

"), + IsActive = true, + EmailAccountId = emailAccountId + }, + new() { + Name = "RecurringPayment.Cancelled.StoreOwnerNotification", + Subject = "{{Store.Name}}: recurring payment for order #{{Order.OrderNumber}} cancelled", + Body = Layout( + "A recurring payment was cancelled.", + "Recurring payment cancelled", + @"

The recurring payment for order #{{Order.OrderNumber}} ({{Customer.Email | Escape}}) was cancelled. Cancelled by: {{RecurringPayment.CancelledBy}}.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+

Every {{RecurringPayment.CycleLength}} {{RecurringPayment.CyclePeriod}}{% if RecurringPayment.TotalCycles > 0 %}, {{RecurringPayment.CyclesPaid}} of {{RecurringPayment.TotalCycles}} paid{% endif %}

"), + IsActive = true, + EmailAccountId = emailAccountId + }, + new() { + Name = "RecurringPayment.PaymentFailed.CustomerNotification", + Subject = "{{Store.Name}}: the payment for order #{{Order.OrderNumber}} could not be taken", + Body = Layout( + "A payment for your recurring order could not be taken.", + "Payment failed", + @"

Hello {{Customer.FullName | Escape}},

+

The payment for the next cycle of your recurring payment for order #{{Order.OrderNumber}} could not be taken{% if RecurringPayment.LastError != '' %}: {{RecurringPayment.LastError}}{% endif %}.

+

The payment provider may try again. Please check that your payment details are up to date.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+ " + Button("{{Order.OrderURLForCustomer}}", "View the order")), + IsActive = true, + EmailAccountId = emailAccountId + }, + new() { + Name = "RecurringPayment.PaymentFailed.StoreOwnerNotification", + Subject = "{{Store.Name}}: a recurring payment for order #{{Order.OrderNumber}} failed", + Body = Layout( + "A cycle of a recurring payment failed.", + "Recurring payment failed", + @"

A cycle of the recurring payment for order #{{Order.OrderNumber}} ({{Customer.Email | Escape}}) failed{% if RecurringPayment.LastError != '' %}: {{RecurringPayment.LastError}}{% endif %}.

+

The payment provider may retry it.

+
    {% for item in Order.OrderItems %}
  • {{item.ProductName}}
  • {% endfor %}
+

Every {{RecurringPayment.CycleLength}} {{RecurringPayment.CyclePeriod}}{% if RecurringPayment.TotalCycles > 0 %}, {{RecurringPayment.CyclesPaid}} of {{RecurringPayment.TotalCycles}} paid{% endif %}

"), + IsActive = true, + EmailAccountId = emailAccountId + } + }; + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelRecurringPaymentCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelRecurringPaymentCommandHandlerTests.cs new file mode 100644 index 000000000..bf43e89cb --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelRecurringPaymentCommandHandlerTests.cs @@ -0,0 +1,106 @@ +using Grand.Business.Checkout.Commands.Handlers.Orders; +using Grand.Business.Checkout.Services.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.Payments; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Data.Tests.MongoDb; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders; + +[TestClass] +public class CancelRecurringPaymentCommandHandlerTests +{ + private Mock _service; + private Mock _paymentService; + private RecurringPayment _recurringPayment; + + [TestInitialize] + public void Init() + { + _recurringPayment = new RecurringPayment { + Id = "rp1", Status = RecurringPaymentStatus.Active, ProviderReference = "sub_1" + }; + _service = new Mock(); + // the service asks the gateway through the callback it is given + _service.Setup(x => x.Cancel(It.IsAny(), It.IsAny(), + It.IsAny>>())) + .Returns((string _, string _, Func> stopAtGateway) => + stopAtGateway(_recurringPayment)); + _paymentService = new Mock(); + } + + private CancelRecurringPaymentCommandHandler Handler(IRecurringPaymentService service) + { + return new CancelRecurringPaymentCommandHandler(service, _paymentService.Object, + new Mock>().Object); + } + + private CancelRecurringPaymentCommand Command() + { + return new CancelRecurringPaymentCommand { RecurringPayment = _recurringPayment, CancelledBy = "staff" }; + } + + [TestMethod] + public async Task Handle_PassesTheProviderResult() + { + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no"); + _paymentService.Setup(x => x.CancelRecurringPayment(_recurringPayment)).ReturnsAsync(refusal); + + var result = await Handler(_service.Object).Handle(Command(), CancellationToken.None); + + CollectionAssert.AreEqual(new[] { "no" }, result.Errors.ToList()); + _service.Verify(x => x.Cancel("rp1", "staff", + It.IsAny>>()), Times.Once); + } + + [TestMethod] + public async Task Handle_ProviderThrows_ReturnsTheMessageAsAnError() + { + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ThrowsAsync(new HttpRequestException("timeout")); + + var result = await Handler(_service.Object).Handle(Command(), CancellationToken.None); + + Assert.IsFalse(result.Success); + CollectionAssert.AreEqual(new[] { "timeout" }, result.Errors.ToList()); + } + + [TestMethod] + public async Task Handle_ProviderThrows_TheLockIsReleased() + { + var repository = new MongoDBRepositoryTest(); + var service = new RecurringPaymentService(repository, new Mock().Object, + new Mock().Object, new MongoResourceLockTest()); + var rp = new RecurringPayment { Status = RecurringPaymentStatus.Active, ProviderReference = "sub_1" }; + await service.InsertRecurringPayment(rp); + var command = new CancelRecurringPaymentCommand { RecurringPayment = rp, CancelledBy = "staff" }; + + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ThrowsAsync(new HttpRequestException("timeout")); + Assert.IsFalse((await Handler(service).Handle(command, CancellationToken.None)).Success); + Assert.AreEqual(RecurringPaymentStatus.Active, (await service.GetRecurringPaymentById(rp.Id)).Status); + + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + Assert.IsTrue((await Handler(service).Handle(command, CancellationToken.None)).Success); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task Handle_NoCancelledBy_Throws() + { + var command = Command(); + command.CancelledBy = ""; + + await Assert.ThrowsExactlyAsync(() => + Handler(_service.Object).Handle(command, CancellationToken.None)); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs index 7bedd8994..249285722 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs @@ -28,24 +28,87 @@ public void Init() _mediator = new Mock(); } + private RecordRecurringPaymentFailureCommandHandler FailureHandler() + { + return new RecordRecurringPaymentFailureCommandHandler(_service.Object, _paymentService.Object, + _orderService.Object, new Mock>().Object); + } + + private static RecordRecurringPaymentFailureCommand FailureCommand() + { + return new RecordRecurringPaymentFailureCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1", CycleReference = "in_2", Reason = "declined" + }; + } + [TestMethod] public async Task FailureCommand_PassesTheReportToTheService() { _service.Setup(x => x.RecordFailure("rp1", "in_2", "declined")).ReturnsAsync(true); - var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); - var result = await handler.Handle(new RecordRecurringPaymentFailureCommand { - RecurringPaymentId = "rp1", CycleReference = "in_2", Reason = "declined" - }, CancellationToken.None); + var result = await FailureHandler().Handle(FailureCommand(), CancellationToken.None); Assert.IsTrue(result); _service.Verify(x => x.RecordFailure("rp1", "in_2", "declined"), Times.Once); + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task FailureCommand_OnAnEndedPayment_AsksTheProviderToStopWithTheReportedReference( + RecurringPaymentStatus status) + { + // cancelled while pending, so the shop never learnt the gateway's reference + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = status + }); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => + r.Id == "rp1" && r.ProviderReference == "sub_1")), Times.Once); + } + + [TestMethod] + public async Task FailureCommand_OnAnEndedPaymentAndProviderRefuses_NotesItOnTheInitialOrder() + { + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" + }); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + + await FailureHandler().Handle(FailureCommand(), CancellationToken.None); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && + n.Note == "The recurring payment is cancelled, but the payment gateway did not confirm it stopped charging: no way")), + Times.Once); + } + + [TestMethod] + public async Task FailureCommand_ForACyclePaidAlreadyOrAnActivePayment_DoesNotAskTheProviderToStop() + { + var cancelled = new RecurringPayment { Id = "rp1", Status = RecurringPaymentStatus.Cancelled }; + cancelled.Cycles.Add(new RecurringPaymentCycle { CycleNumber = 2, ProviderReference = "in_2" }); + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(cancelled); + await FailureHandler().Handle(FailureCommand(), CancellationToken.None); + + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", Status = RecurringPaymentStatus.PastDue + }); + await FailureHandler().Handle(FailureCommand(), CancellationToken.None); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); } [TestMethod] public async Task FailureCommand_WithoutRecurringPaymentId_Throws() { - var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + var handler = FailureHandler(); await Assert.ThrowsExactlyAsync(() => handler.Handle(new RecordRecurringPaymentFailureCommand { RecurringPaymentId = "" }, CancellationToken.None)); @@ -87,13 +150,15 @@ private static RecordRecurringPaymentCycleCommand CycleCommand() }; } - private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = RecurringPaymentStatus.Active) + private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = RecurringPaymentStatus.Active, + bool completed = false) { var claim = new RecurringCycleClaim { RecurringPayment = new RecurringPayment { Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test", Status = status }, - Cycle = new RecurringPaymentCycle { CycleNumber = cycleNumber, OrderId = "o2" } + Cycle = new RecurringPaymentCycle { CycleNumber = cycleNumber, OrderId = "o2" }, + Completed = completed }; _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)).ReturnsAsync(claim); } @@ -154,7 +219,7 @@ await Assert.ThrowsExactlyAsync(() => [TestMethod] public async Task CycleCommand_Completed_AsksTheProviderToStop() { - SetupClaim(3, RecurringPaymentStatus.Completed); + SetupClaim(3, RecurringPaymentStatus.Completed, completed: true); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) .ReturnsAsync(new CancelRecurringPaymentResult()); @@ -165,6 +230,38 @@ public async Task CycleCommand_Completed_AsksTheProviderToStop() _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); } + [TestMethod] + public async Task CycleCommand_FirstCycleClaimedAfterCancel_AsksTheProviderToStop() + { + // a payment cancelled before its first cycle was reported is still charged once at the gateway + SetupClaim(1, RecurringPaymentStatus.Cancelled); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + Assert.IsTrue(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && !n.DisplayToCustomer && + n.Note == "Cycle 1 was charged at the payment gateway (in_2) after the recurring payment was cancelled: check whether the customer must be refunded")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_ChargedAfterCompleted_NotesItForARefund() + { + SetupClaim(4, RecurringPaymentStatus.Completed); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + Assert.IsTrue(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.Note == "Cycle 4 was charged at the payment gateway (in_2) after the recurring payment was completed: check whether the customer must be refunded")), + Times.Once); + } + [TestMethod] public async Task CycleCommand_NotCompleted_DoesNotAskTheProviderToStop() { @@ -311,7 +408,7 @@ await Assert.ThrowsExactlyAsync(() => [TestMethod] public async Task FailureCommand_WithoutCycleReference_Throws() { - var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + var handler = FailureHandler(); await Assert.ThrowsExactlyAsync(() => handler.Handle(new RecordRecurringPaymentFailureCommand { RecurringPaymentId = "rp1", CycleReference = "" }, diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderCancelledRecurringPaymentHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderCancelledRecurringPaymentHandlerTests.cs new file mode 100644 index 000000000..59d446352 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderCancelledRecurringPaymentHandlerTests.cs @@ -0,0 +1,138 @@ +using Grand.Business.Checkout.Events.Orders; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Events.Orders; + +[TestClass] +public class OrderCancelledRecurringPaymentHandlerTests +{ + private OrderCancelledRecurringPaymentHandler _handler; + private Mock> _logger; + private Mock _mediator; + private Mock _orderService; + private Order _order; + private RecurringPayment _recurringPayment; + private Mock _recurringPaymentService; + + [TestInitialize] + public void Init() + { + _recurringPaymentService = new Mock(); + _orderService = new Mock(); + _mediator = new Mock(); + _logger = new Mock>(); + _handler = new OrderCancelledRecurringPaymentHandler(_recurringPaymentService.Object, _orderService.Object, + _mediator.Object, _logger.Object); + _order = new Order { Id = "o1", OrderNumber = 12, RecurringCycleNumber = 1 }; + _recurringPayment = new RecurringPayment { Id = "r1", InitialOrderId = "o1" }; + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")) + .ReturnsAsync(_recurringPayment); + _mediator.Setup(x => x.Send(It.IsAny(), default)) + .ReturnsAsync(new CancelRecurringPaymentResult()); + } + + private void CommandNeverSent() + { + _mediator.Verify(x => x.Send(It.IsAny(), default), Times.Never); + } + + [TestMethod] + public async Task OrderCancelled_InitialOrder_CancelsItsRecurringPayment() + { + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPayment == _recurringPayment && c.CancelledBy == "Order #12 cancelled"), default), Times.Once); + } + + [TestMethod] + public async Task OrderDeleted_InitialOrder_CancelsItsRecurringPayment() + { + await _handler.Handle(new OrderDeletedEvent(_order), CancellationToken.None); + + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPayment == _recurringPayment && c.CancelledBy == "Order #12 deleted"), default), Times.Once); + } + + [TestMethod] + public async Task OrderCancelled_CycleOrder_LeavesTheRecurringPaymentAlone() + { + _order.RecurringCycleNumber = 2; + _order.InitialOrderId = "o1"; + + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + _recurringPaymentService.Verify(x => x.GetRecurringPaymentByInitialOrderId(It.IsAny()), Times.Never); + CommandNeverSent(); + } + + [TestMethod] + public async Task OrderCancelled_NotRecurring_DoesNotLookItUp() + { + _order.RecurringCycleNumber = 0; + + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + _recurringPaymentService.Verify(x => x.GetRecurringPaymentByInitialOrderId(It.IsAny()), Times.Never); + CommandNeverSent(); + } + + [TestMethod] + public async Task OrderCancelled_NoRecurringPayment_SendsNothing() + { + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")) + .ReturnsAsync((RecurringPayment)null); + + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + CommandNeverSent(); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task OrderCancelled_ProviderRefuses_NotesItOnTheOrder() + { + var result = new CancelRecurringPaymentResult(); + result.AddError("declined"); + _mediator.Setup(x => x.Send(It.IsAny(), default)).ReturnsAsync(result); + + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == _order.Id && !n.DisplayToCustomer && n.Note.Contains("declined") && + n.Note.Contains("cancelled"))), Times.Once); + } + + [TestMethod] + public async Task OrderCancelled_CancelThrows_NotesItAndDoesNotThrow() + { + _mediator.Setup(x => x.Send(It.IsAny(), default)) + .ThrowsAsync(new Exception("gateway down")); + + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == _order.Id && !n.DisplayToCustomer && n.Note.Contains("gateway down"))), Times.Once); + } + + [TestMethod] + public async Task OrderCancelled_NoteFails_DoesNotThrow() + { + _mediator.Setup(x => x.Send(It.IsAny(), default)) + .ThrowsAsync(new Exception("gateway down")); + _orderService.Setup(x => x.InsertOrderNote(It.IsAny())).ThrowsAsync(new Exception("db down")); + + await _handler.Handle(new OrderCancelledEvent(_order), CancellationToken.None); + + _logger.Verify(x => x.Log(LogLevel.Error, It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny>()), Times.Exactly(2)); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/RecurringPaymentMessagesHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/RecurringPaymentMessagesHandlerTests.cs new file mode 100644 index 000000000..3e9f41002 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/RecurringPaymentMessagesHandlerTests.cs @@ -0,0 +1,92 @@ +using Grand.Business.Checkout.Events.Orders; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Business.Core.Interfaces.Messages; +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Events.Orders; + +[TestClass] +public class RecurringPaymentMessagesHandlerTests +{ + private Customer _customer; + private RecurringPaymentMessagesHandler _handler; + private Mock _messages; + private Order _order; + private RecurringPayment _recurringPayment; + + [TestInitialize] + public void Init() + { + var orderService = new Mock(); + var customerService = new Mock(); + _messages = new Mock(); + _handler = new RecurringPaymentMessagesHandler(orderService.Object, customerService.Object, + _messages.Object, new LanguageSettings { DefaultAdminLanguageId = "admin-lang" }, + new Mock>().Object); + _order = new Order { Id = "o1", CustomerLanguageId = "customer-lang" }; + _customer = new Customer { Id = "c1" }; + _recurringPayment = new RecurringPayment { Id = "r1", InitialOrderId = "o1", CustomerId = "c1" }; + orderService.Setup(x => x.GetOrderById("o1")).ReturnsAsync(_order); + customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(_customer); + } + + [TestMethod] + public async Task Cancelled_SendsBothCancelledMessages() + { + await _handler.Handle(new RecurringPaymentCancelledEvent(_recurringPayment), default); + + _messages.Verify(x => x.SendRecurringPaymentCancelledCustomerMessage(_recurringPayment, _order, + _customer, "customer-lang"), Times.Once); + _messages.Verify(x => x.SendRecurringPaymentCancelledStoreOwnerMessage(_recurringPayment, _order, + _customer, "admin-lang"), Times.Once); + _messages.Verify(x => x.SendRecurringPaymentFailedCustomerMessage(It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _messages.Verify(x => x.SendRecurringPaymentFailedStoreOwnerMessage(It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task PastDue_SendsBothFailedMessages() + { + await _handler.Handle(new RecurringPaymentPastDueEvent(_recurringPayment), default); + + _messages.Verify(x => x.SendRecurringPaymentFailedCustomerMessage(_recurringPayment, _order, + _customer, "customer-lang"), Times.Once); + _messages.Verify(x => x.SendRecurringPaymentFailedStoreOwnerMessage(_recurringPayment, _order, + _customer, "admin-lang"), Times.Once); + _messages.Verify(x => x.SendRecurringPaymentCancelledCustomerMessage(It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _messages.Verify(x => x.SendRecurringPaymentCancelledStoreOwnerMessage(It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CustomerMessageThrows_StoreOwnerStillGetsItsMessage_AndNothingThrows() + { + _messages.Setup(x => x.SendRecurringPaymentCancelledCustomerMessage(It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny())).ThrowsAsync(new Exception("smtp")); + + await _handler.Handle(new RecurringPaymentCancelledEvent(_recurringPayment), default); + + _messages.Verify(x => x.SendRecurringPaymentCancelledStoreOwnerMessage(_recurringPayment, _order, + _customer, "admin-lang"), Times.Once); + } + + [TestMethod] + public async Task InitialOrderMissing_SendsNothing() + { + _recurringPayment.InitialOrderId = "gone"; + + await _handler.Handle(new RecurringPaymentCancelledEvent(_recurringPayment), default); + await _handler.Handle(new RecurringPaymentPastDueEvent(_recurringPayment), default); + + _messages.VerifyNoOtherCalls(); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs index dbb56ddee..0223056cf 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -1,5 +1,7 @@ using Grand.Business.Checkout.Services.Orders; +using Grand.Business.Core.Events.Checkout.Orders; using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Utilities.Checkout; using Grand.Data; using Grand.Data.Tests.MongoDb; using Grand.Domain.Catalog; @@ -16,6 +18,7 @@ public class RecurringPaymentServiceTests { private Mock _productService; private IRepository _repository; + private Mock _mediatorMock; private IMediator _mediator; private IResourceLock _resourceLock; private RecurringPaymentService _service; @@ -28,7 +31,8 @@ public void Init() _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 }); - _mediator = new Mock().Object; + _mediatorMock = new Mock(); + _mediator = _mediatorMock.Object; _resourceLock = new MongoResourceLockTest(); _service = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); } @@ -52,20 +56,6 @@ public async Task GetRecurringPaymentByInitialOrderId_OtherOrder_ReturnsNull() 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() { @@ -89,11 +79,11 @@ public async Task InsertRecurringPayment_Null_Throws() } private async Task Insert(RecurringPaymentStatus status, int cyclesPaid, int totalCycles = 12, - string lastError = null) + string lastError = null, string providerReference = null) { var rp = new RecurringPayment { InitialOrderId = "o1", Status = status, CyclesPaid = cyclesPaid, TotalCycles = totalCycles, - LastError = lastError + LastError = lastError, ProviderReference = providerReference }; for (var i = 1; i <= cyclesPaid; i++) rp.Cycles.Add(new RecurringPaymentCycle { @@ -317,4 +307,286 @@ public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() { Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New)); } + + private static CancelRecurringPaymentResult Refusal(string error) + { + var result = new CancelRecurringPaymentResult(); + result.AddError(error); + return result; + } + + [TestMethod] + public async Task Cancel_PendingWithoutProviderReference_CancelsWithoutTheGateway() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + var calls = 0; + + var result = await _service.Cancel(rp.Id, "jane@example.com", _ => + { + calls++; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + + Assert.IsTrue(result.Success); + Assert.AreEqual(0, calls); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("jane@example.com", saved.CancelledBy); + Assert.IsNotNull(saved.CancelledOnUtc); + } + + [TestMethod] + public async Task Cancel_Active_AsksTheGatewayFirst() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + RecurringPayment asked = null; + + var result = await _service.Cancel(rp.Id, "jane@example.com", r => + { + asked = r; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + + Assert.IsTrue(result.Success); + Assert.AreEqual(rp.Id, asked?.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task Cancel_PendingWithProviderReference_AsksTheGateway() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0, providerReference: "sub_1"); + var calls = 0; + + var result = await _service.Cancel(rp.Id, "jane@example.com", _ => + { + calls++; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + + Assert.IsTrue(result.Success); + Assert.AreEqual(1, calls); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task Cancel_ActiveWithoutProviderReference_AsksTheGateway() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + var calls = 0; + + var result = await _service.Cancel(rp.Id, "jane@example.com", _ => + { + calls++; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + + Assert.IsTrue(result.Success); + Assert.AreEqual(1, calls); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task Cancel_CallbackThrows_ReleasesTheLock() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + await Assert.ThrowsExactlyAsync(() => _service.Cancel(rp.Id, "jane@example.com", + _ => throw new InvalidOperationException("boom"))); + Assert.AreEqual(RecurringPaymentStatus.Active, (await _service.GetRecurringPaymentById(rp.Id)).Status); + + var result = await _service.Cancel(rp.Id, "jane@example.com", + _ => Task.FromResult(new CancelRecurringPaymentResult())); + + Assert.IsTrue(result.Success); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task Cancel_GatewayRefuses_ReturnsTheErrorsAndKeepsTheStatus() + { + var rp = await Insert(RecurringPaymentStatus.PastDue, 1, providerReference: "sub_1"); + + var result = await _service.Cancel(rp.Id, "jane@example.com", + _ => Task.FromResult(Refusal("declined by gateway"))); + + Assert.IsFalse(result.Success); + CollectionAssert.Contains(result.Errors.ToList(), "declined by gateway"); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); + Assert.IsNull(saved.CancelledOnUtc); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task Cancel_CancelledOrCompleted_IsANoOp(RecurringPaymentStatus status) + { + var rp = await Insert(status, 1, providerReference: "sub_1"); + rp.CancelledBy = "earlier"; + await _repository.UpdateAsync(rp); + var calls = 0; + + var result = await _service.Cancel(rp.Id, "jane@example.com", _ => + { + calls++; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + + Assert.IsTrue(result.Success); + Assert.AreEqual(0, calls); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(status, saved.Status); + Assert.AreEqual("earlier", saved.CancelledBy); + } + + [TestMethod] + public async Task Cancel_UnknownRecurringPayment_ReturnsAnError() + { + var result = await _service.Cancel(UniqueIdentifier.New, "jane@example.com", + _ => Task.FromResult(new CancelRecurringPaymentResult())); + + CollectionAssert.AreEqual(new[] { "The recurring payment was not found" }, result.Errors.ToList()); + } + + private static readonly TimeSpan ConcurrentTimeout = TimeSpan.FromSeconds(30); + + [TestMethod] + public async Task Cancel_CycleWebhookDuringTheGatewayCall_IsNotHeldUpAndIsKept() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); + Task claimTask = null; + + var result = await _service.Cancel(rp.Id, "jane@example.com", async _ => + { + //the gateway has not answered yet, and the webhook must not wait for it + claimTask = other.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + await claimTask.WaitAsync(ConcurrentTimeout); + return new CancelRecurringPaymentResult(); + }); + + Assert.IsTrue(result.Success); + Assert.IsNotNull(await claimTask); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual(2, saved.Cycles.Count); + Assert.AreEqual(2, saved.CyclesPaid); + Assert.AreEqual(1, Published().Count); + } + + [TestMethod] + public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + rp.PaymentMethodSystemName = "Payments.Test"; + await _repository.UpdateAsync(rp); + var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); + Task endedTask = null; + + var result = await _service.Cancel(rp.Id, "jane@example.com", async _ => + { + endedTask = other.RecordEnded(rp.Id); + await endedTask.WaitAsync(ConcurrentTimeout); + return new CancelRecurringPaymentResult(); + }); + + Assert.IsTrue(result.Success); + Assert.IsTrue(await endedTask); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("Payments.Test", saved.CancelledBy); + Assert.AreEqual(1, Published().Count); + } + + [TestMethod] + public async Task Cancel_GatewayRefusesBecauseAnotherCancelStoppedItFirst_Succeeds() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); + + var result = await _service.Cancel(rp.Id, "jane@example.com", async _ => + { + var first = await other.Cancel(rp.Id, "staff@example.com", + _ => Task.FromResult(new CancelRecurringPaymentResult())).WaitAsync(ConcurrentTimeout); + Assert.IsTrue(first.Success); + return Refusal("the subscription is already cancelled"); + }); + + Assert.IsTrue(result.Success); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("staff@example.com", saved.CancelledBy); + Assert.AreEqual(1, Published().Count); + } + + private List Published() + { + return _mediatorMock.Invocations.Where(x => x.Method.Name == nameof(IMediator.Publish)) + .Select(x => x.Arguments[0]).OfType().ToList(); + } + + [TestMethod] + public async Task Cancel_PublishesCancelledOnce() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.IsTrue((await _service.Cancel(rp.Id, "jane@example.com", _ => Task.FromResult(new CancelRecurringPaymentResult()))).Success); + Assert.IsTrue((await _service.Cancel(rp.Id, "jane@example.com", _ => Task.FromResult(new CancelRecurringPaymentResult()))).Success); + + var published = Published(); + Assert.AreEqual(1, published.Count); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, published[0].RecurringPayment.Status); + Assert.AreEqual(0, Published().Count); + } + + [TestMethod] + public async Task Cancel_GatewayRefuses_PublishesNothing() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + var result = await _service.Cancel(rp.Id, "jane@example.com", _ => Task.FromResult(Refusal("declined"))); + + Assert.IsFalse(result.Success); + Assert.AreEqual(0, Published().Count); + Assert.AreEqual(0, Published().Count); + } + + [TestMethod] + public async Task RecordEnded_PublishesCancelledOnlyOnTheTransition() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + Assert.IsTrue(await _service.RecordEnded(rp.Id)); + Assert.IsFalse(await _service.RecordEnded(rp.Id)); + + var published = Published(); + Assert.AreEqual(1, published.Count); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, published[0].RecurringPayment.Status); + } + + [TestMethod] + public async Task RecordFailure_PublishesPastDueOnlyWhenEnteringIt() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + await _service.RecordFailure(rp.Id, "in_2", "a"); + await _service.RecordFailure(rp.Id, "in_2", "b"); + + var published = Published(); + Assert.AreEqual(1, published.Count); + Assert.AreEqual("a", published[0].RecurringPayment.LastError); + } + + [TestMethod] + public async Task ClaimCycle_Completing_PublishesNeitherEvent() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, 2); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsTrue(claim.Completed); + Assert.AreEqual(0, Published().Count); + Assert.AreEqual(0, Published().Count); + } } diff --git a/src/Tests/Grand.Business.Messages.Tests/Commands/GetRecurringPaymentTokensCommandHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Commands/GetRecurringPaymentTokensCommandHandlerTests.cs new file mode 100644 index 000000000..b29a028c3 --- /dev/null +++ b/src/Tests/Grand.Business.Messages.Tests/Commands/GetRecurringPaymentTokensCommandHandlerTests.cs @@ -0,0 +1,72 @@ +using Grand.Business.Core.Interfaces.Common.Localization; +using Grand.Business.Messages.Commands.Handlers.Messages; +using Grand.Business.Messages.Commands.Tokens; +using Grand.Domain.Catalog; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Messages.Tests.Commands; + +[TestClass] +public class GetRecurringPaymentTokensCommandHandlerTests +{ + private GetRecurringPaymentTokensCommandHandler _handler; + private Dictionary _resources; + + [TestInitialize] + public void Init() + { + //resources the language has; a missing one gives the default, or an empty string when asked for that + _resources = new Dictionary(); + var translationService = new Mock(); + translationService + .Setup(x => x.GetResource(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((string key, string _, string defaultValue, bool returnEmpty) => + _resources.TryGetValue(key, out var value) ? value : returnEmpty ? string.Empty : defaultValue); + _handler = new GetRecurringPaymentTokensCommandHandler(translationService.Object); + } + + private static GetRecurringPaymentTokensCommand Command(RecurringPayment recurringPayment) + { + return new GetRecurringPaymentTokensCommand { + RecurringPayment = recurringPayment, + Language = new Language { Id = "lang1" } + }; + } + + [TestMethod] + public async Task Tokens_TranslateThePeriodAndEncodeWhatOthersTyped() + { + _resources["Enums.Grand.Domain.Catalog.RecurringCyclePeriod.Months"] = "Monate"; + var recurringPayment = new RecurringPayment { + CycleLength = 1, + CyclePeriodId = RecurringCyclePeriod.Months, + CyclesPaid = 3, + TotalCycles = 12, + LastError = "card", + CancelledBy = "O'Neil & co" + }; + + var tokens = await _handler.Handle(Command(recurringPayment), default); + + Assert.AreEqual(1, tokens.CycleLength); + Assert.AreEqual("Monate", tokens.CyclePeriod); + Assert.AreEqual(3, tokens.CyclesPaid); + Assert.AreEqual(12, tokens.TotalCycles); + Assert.AreEqual("<b>card</b>", tokens.LastError); + Assert.AreEqual("O'Neil & co", tokens.CancelledBy); + } + + [TestMethod] + public async Task Tokens_NullTextsAreEmpty() + { + var recurringPayment = new RecurringPayment { LastError = null, CancelledBy = null }; + + var tokens = await _handler.Handle(Command(recurringPayment), default); + + Assert.AreEqual(string.Empty, tokens.LastError); + Assert.AreEqual(string.Empty, tokens.CancelledBy); + } +} diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/RecurringPaymentMessageProviderServiceTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/RecurringPaymentMessageProviderServiceTests.cs new file mode 100644 index 000000000..ed6c15978 --- /dev/null +++ b/src/Tests/Grand.Business.Messages.Tests/Services/RecurringPaymentMessageProviderServiceTests.cs @@ -0,0 +1,194 @@ +using Grand.Business.Core.Interfaces.Common.Localization; +using Grand.Business.Core.Interfaces.Common.Stores; +using Grand.Business.Core.Interfaces.Messages; +using Grand.Business.Messages.Commands.Tokens; +using Grand.Business.Messages.DotLiquidDrops; +using Grand.Business.Messages.Services; +using Grand.Domain.Common; +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Domain.Messages; +using Grand.Domain.Orders; +using Grand.Domain.Stores; +using Grand.Mediator; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Messages.Tests.Services; + +[TestClass] +public class RecurringPaymentMessageProviderServiceTests +{ + private readonly Customer _customer = new() { + Id = "c1", + Email = "customer@example.com", + UserFields = { + new UserField { Key = SystemCustomerFieldNames.FirstName, Value = "Anna", StoreId = "" }, + new UserField { Key = SystemCustomerFieldNames.LastName, Value = "Nowak", StoreId = "" } + } + }; + private readonly Order _initialOrder = new() { Id = "o1", StoreId = "store1", OrderNumber = 1042 }; + private readonly RecurringPayment _recurringPayment = + new() { Id = "rp1", StoreId = "store1", InitialOrderId = "o1" }; + private Mock _messageTemplateServiceMock; + private Mock _languageServiceMock; + private List _queued; + private RecurringPaymentMessageProviderService _service; + + [TestInitialize] + public void Init() + { + _queued = []; + _messageTemplateServiceMock = new Mock(); + var queuedEmailService = new Mock(); + queuedEmailService.Setup(x => x.InsertQueuedEmail(It.IsAny())).Callback(_queued.Add); + + _languageServiceMock = new Mock(); + _languageServiceMock.Setup(x => x.GetLanguageById(It.IsAny())) + .ReturnsAsync(new Language { Id = "en", Published = true }); + var emailAccountService = new Mock(); + emailAccountService.Setup(x => x.GetEmailAccountById(It.IsAny())) + .ReturnsAsync(new EmailAccount { Id = "ea", Email = "shop@example.com", DisplayName = "Shop" }); + var storeService = new Mock(); + storeService.Setup(x => x.GetStoreById("store1")) + .ReturnsAsync(new Store { Id = "store1", Url = "https://store.example/" }); + + var mediator = new Mock(); + mediator.Setup(x => x.Send(It.Is(c => c.RecurringPayment == _recurringPayment), + default)) + .ReturnsAsync(new LiquidRecurringPayment { CyclePeriod = "Months" }); + + var lookup = new MessageLookupService(_messageTemplateServiceMock.Object, _languageServiceMock.Object, + emailAccountService.Object, storeService.Object, new EmailAccountSettings()); + _service = new RecurringPaymentMessageProviderService(lookup, + new MessageProviderService(queuedEmailService.Object), mediator.Object); + } + + private void TemplateExists(string name) + { + _messageTemplateServiceMock.Setup(x => x.GetMessageTemplateByName(name, "store1")) + .ReturnsAsync(new MessageTemplate { + Name = name, IsActive = true, Subject = "Every {{RecurringPayment.CyclePeriod}}", Body = "Body" + }); + } + + private Task Send(string method) + { + return method switch { + nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentCancelledCustomerMessage) => + _service.SendRecurringPaymentCancelledCustomerMessage(_recurringPayment, _initialOrder, _customer, "en"), + nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentCancelledStoreOwnerMessage) => + _service.SendRecurringPaymentCancelledStoreOwnerMessage(_recurringPayment, _initialOrder, _customer, + "en"), + nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentFailedCustomerMessage) => + _service.SendRecurringPaymentFailedCustomerMessage(_recurringPayment, _initialOrder, _customer, "en"), + nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentFailedStoreOwnerMessage) => + _service.SendRecurringPaymentFailedStoreOwnerMessage(_recurringPayment, _initialOrder, _customer, "en"), + _ => throw new ArgumentOutOfRangeException(nameof(method), method, null) + }; + } + + [TestMethod] + [DataRow(nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentCancelledCustomerMessage), + "RecurringPayment.Cancelled.CustomerNotification")] + [DataRow(nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentCancelledStoreOwnerMessage), + "RecurringPayment.Cancelled.StoreOwnerNotification")] + [DataRow(nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentFailedCustomerMessage), + "RecurringPayment.PaymentFailed.CustomerNotification")] + [DataRow(nameof(RecurringPaymentMessageProviderService.SendRecurringPaymentFailedStoreOwnerMessage), + "RecurringPayment.PaymentFailed.StoreOwnerNotification")] + public async Task EachMessage_UsesItsOwnTemplate(string method, string templateName) + { + //only this one name has a template, so a method that looks up another name queues nothing + TemplateExists(templateName); + + var result = await Send(method); + + Assert.IsTrue(result > 0); + Assert.AreEqual(1, _queued.Count); + } + + [TestMethod] + public async Task CancelledCustomerMessage_QueuesToTheCustomer() + { + TemplateExists(MessageTemplateNames.RecurringPaymentCancelledCustomerNotification); + + var result = await _service.SendRecurringPaymentCancelledCustomerMessage(_recurringPayment, _initialOrder, + _customer, "en"); + + Assert.IsTrue(result > 0); + var email = _queued.Single(); + Assert.AreEqual("customer@example.com", email.To); + Assert.AreEqual("Anna Nowak", email.ToName); + Assert.AreEqual(_customer.GetFullName(), email.ToName); + Assert.AreEqual("Every Months", email.Subject); + Assert.AreEqual(Reference.Order, email.Reference); + Assert.AreEqual("o1", email.ObjectId); + } + + [TestMethod] + public async Task FailedStoreOwnerMessage_QueuesToTheEmailAccount() + { + TemplateExists(MessageTemplateNames.RecurringPaymentFailedStoreOwnerNotification); + + var result = await _service.SendRecurringPaymentFailedStoreOwnerMessage(_recurringPayment, _initialOrder, + _customer, "en"); + + Assert.IsTrue(result > 0); + var email = _queued.Single(); + Assert.AreEqual("shop@example.com", email.To); + Assert.AreEqual("Shop", email.ToName); + Assert.AreEqual("Every Months", email.Subject); + Assert.AreEqual(Reference.Order, email.Reference); + Assert.AreEqual("o1", email.ObjectId); + } + + [TestMethod] + public async Task Message_TemplateMissing_ReturnsZero() + { + var result = await _service.SendRecurringPaymentCancelledStoreOwnerMessage(_recurringPayment, _initialOrder, + _customer, "en"); + + Assert.AreEqual(0, result); + Assert.AreEqual(0, _queued.Count); + } + + [TestMethod] + public async Task CustomerMessage_CustomerWithoutEmail_ReturnsZero() + { + TemplateExists(MessageTemplateNames.RecurringPaymentFailedCustomerNotification); + + var withoutEmail = await _service.SendRecurringPaymentFailedCustomerMessage(_recurringPayment, _initialOrder, + new Customer { Id = "c2" }, "en"); + var withoutCustomer = await _service.SendRecurringPaymentFailedCustomerMessage(_recurringPayment, + _initialOrder, null, "en"); + + Assert.AreEqual(0, withoutEmail); + Assert.AreEqual(0, withoutCustomer); + Assert.AreEqual(0, _queued.Count); + } + + [TestMethod] + public async Task Message_LanguageNotPublished_IsWrittenInTheStoreLanguage() + { + _languageServiceMock.Setup(x => x.GetLanguageById("hidden")) + .ReturnsAsync(new Language { Id = "hidden", Published = false }); + _languageServiceMock.Setup(x => x.GetAllLanguages(false, "store1")) + .ReturnsAsync([new Language { Id = "pl", Published = true }]); + _messageTemplateServiceMock.Setup(x => + x.GetMessageTemplateByName(MessageTemplateNames.RecurringPaymentCancelledCustomerNotification, "store1")) + .ReturnsAsync(new MessageTemplate { + Name = MessageTemplateNames.RecurringPaymentCancelledCustomerNotification, IsActive = true, + Subject = "Cancelled", Body = "Body", + Locales = { + new TranslationEntity { LanguageId = "hidden", LocaleKey = "Subject", LocaleValue = "Hidden" }, + new TranslationEntity { LanguageId = "pl", LocaleKey = "Subject", LocaleValue = "Anulowano" } + } + }); + + await _service.SendRecurringPaymentCancelledCustomerMessage(_recurringPayment, _initialOrder, _customer, + "hidden"); + + Assert.AreEqual("Anulowano", _queued.Single().Subject); + } +} diff --git a/src/Tests/Grand.Modules.Tests/Installer/MessageTemplateSeedTests.cs b/src/Tests/Grand.Modules.Tests/Installer/MessageTemplateSeedTests.cs index a8fb88c7a..2685b7c38 100644 --- a/src/Tests/Grand.Modules.Tests/Installer/MessageTemplateSeedTests.cs +++ b/src/Tests/Grand.Modules.Tests/Installer/MessageTemplateSeedTests.cs @@ -18,11 +18,11 @@ internal static SortedSet Tokens(string text) => .Concat(TagVar.Matches(text).Select(m => m.Groups[1].Value))); [TestMethod] - public void Build_Returns63UniqueTemplates() + public void Build_Returns67UniqueTemplates() { var templates = MessageTemplateSeed.Build("ea"); - Assert.AreEqual(63, templates.Count); - Assert.AreEqual(63, templates.Select(t => t.Name).Distinct().Count()); + Assert.AreEqual(67, templates.Count); + Assert.AreEqual(67, templates.Select(t => t.Name).Distinct().Count()); Assert.IsTrue(templates.All(t => t.EmailAccountId == "ea")); } diff --git a/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentTemplatesTests.cs b/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentTemplatesTests.cs new file mode 100644 index 000000000..6a94a4ec3 --- /dev/null +++ b/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentTemplatesTests.cs @@ -0,0 +1,121 @@ +using Grand.Business.Messages.DotLiquidDrops; +using Grand.Data; +using Grand.Data.Tests.LiteDb; +using Grand.Domain.Configuration; +using Grand.Domain.Messages; +using Grand.Infrastructure.Caching; +using Grand.Infrastructure.Caching.Constants; +using Grand.Module.Installer.Services.MessageTemplates; +using Grand.Module.Migration.Migrations._2._5; +using Grand.Modules.Tests.Installer; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; +using System.Text.RegularExpressions; + +namespace Grand.Modules.Tests.Services.Migrations; + +[TestClass] +public class MigrationRecurringPaymentTemplatesTests +{ + private const string Edited = "RecurringPayment.Cancelled.CustomerNotification"; + + private static readonly string[] Names = [ + Edited, "RecurringPayment.Cancelled.StoreOwnerNotification", + "RecurringPayment.PaymentFailed.CustomerNotification", + "RecurringPayment.PaymentFailed.StoreOwnerNotification" + ]; + + private Mock _cache; + private MigrationRecurringPaymentTemplates _migration; + private IServiceProvider _serviceProvider; + private LiteDBRepositoryMock _templates; + + [TestInitialize] + public void Init() + { + _templates = new LiteDBRepositoryMock(); + _serviceProvider = BuildProvider(_templates); + _migration = new MigrationRecurringPaymentTemplates(); + } + + private IServiceProvider BuildProvider(IRepository templates) + { + var emailAccounts = new LiteDBRepositoryMock(); + emailAccounts.Insert(new EmailAccount { Email = "shop@example.com" }); + _cache = new Mock(); + + var services = new ServiceCollection(); + services.AddSingleton(templates); + services.AddSingleton>(emailAccounts); + services.AddSingleton>(new LiteDBRepositoryMock()); + services.AddSingleton(_cache.Object); + services.AddSingleton>( + NullLogger.Instance); + return services.BuildServiceProvider(); + } + + [TestMethod] + public async Task Migration_InsertsTheMissingTemplates_LeavesExistingOnes() + { + _templates.Insert(new MessageTemplate { Name = Edited, Subject = "mine" }); + + Assert.IsTrue(await _migration.UpgradeProcess(_serviceProvider)); + Assert.IsTrue(await _migration.UpgradeProcess(_serviceProvider)); + + CollectionAssert.AreEquivalent(Names, _templates.Table.Select(x => x.Name).ToArray()); + Assert.AreEqual("mine", _templates.Table.Single(x => x.Name == Edited).Subject); + Assert.IsTrue(_templates.Table.Where(x => x.Name != Edited) + .All(x => x.IsActive && !string.IsNullOrEmpty(x.EmailAccountId))); + _cache.Verify(x => x.RemoveByPrefix(CacheKey.MESSAGETEMPLATES_PATTERN_KEY, It.IsAny()), + Times.AtLeastOnce); + } + + [TestMethod] + public async Task Migration_RepositoryFails_ReturnsFalseWithoutThrowing() + { + var failing = new Mock>(); + failing.Setup(x => x.Table).Throws(new InvalidOperationException("db down")); + var provider = BuildProvider(failing.Object); + + Assert.IsFalse(await _migration.UpgradeProcess(provider)); + } + + [TestMethod] + [DataRow("RecurringPayment.Cancelled.CustomerNotification")] + [DataRow("RecurringPayment.Cancelled.StoreOwnerNotification")] + [DataRow("RecurringPayment.PaymentFailed.CustomerNotification")] + [DataRow("RecurringPayment.PaymentFailed.StoreOwnerNotification")] + public void Template_UsesTheSubjectAndTokensOfTheInstallerSeed(string name) + { + var seed = MessageTemplateSeed.Build("ea").Single(x => x.Name == name); + var template = MigrationRecurringPaymentTemplates.Templates("ea").Single(x => x.Name == name); + + Assert.AreEqual(seed.Subject, template.Subject); + CollectionAssert.AreEqual(MessageTemplateSeedTests.Tokens(seed.Body).ToList(), + MessageTemplateSeedTests.Tokens(template.Body).ToList()); + Assert.AreEqual(Normalize(seed.Body), Normalize(template.Body)); + } + + [TestMethod] + public void Templates_UseOnlyTokensTheDropsHave() + { + var properties = typeof(LiquidRecurringPayment).GetProperties().Select(x => x.Name).ToHashSet(); + var used = MigrationRecurringPaymentTemplates.Templates("ea") + .SelectMany(x => MessageTemplateSeedTests.Tokens(x.Subject + x.Body)) + .Where(x => x.StartsWith("RecurringPayment.")) + .Select(x => x["RecurringPayment.".Length..]) + .ToList(); + + Assert.IsTrue(used.Count > 0); + foreach (var token in used) + Assert.IsTrue(properties.Contains(token), $"{token} is not a property of LiquidRecurringPayment"); + } + + private static string Normalize(string body) + { + return Regex.Replace(body, @"\s+", " "); + } +} diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 5bac00d05..77c693bd9 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 35709eb7d..42ea7efde 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 @@ -2604,4 +2604,16 @@ An order billed in cycles must have something to pay. + + Days + + + Months + + + Weeks + + + Years +