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 052f75f5d..26939f488 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -2,6 +2,7 @@ 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; @@ -25,7 +26,16 @@ public async Task Handle(RecordRecurringPaymentCycleCommand request, Cance var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); - if (claim == null) + if (claim.Outcome == RecurringReportOutcome.OtherReference) + { + await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, + claim.RecurringPayment, request.ProviderReference, + $"a paid cycle ({request.CycleReference})", "check whether the customer must be refunded"); + return false; + } + + // a resend is the usual reason + if (claim.Outcome != RecurringReportOutcome.Recorded) return false; // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs index 14247abe5..a3ffb1ccb 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs @@ -1,16 +1,27 @@ using Grand.Business.Core.Commands.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Mediator; +using Microsoft.Extensions.Logging; namespace Grand.Business.Checkout.Commands.Handlers.Orders; -public class RecordRecurringPaymentEndedCommandHandler(IRecurringPaymentService recurringPaymentService) +public class RecordRecurringPaymentEndedCommandHandler( + IRecurringPaymentService recurringPaymentService, + ILogger logger) : IRequestHandler { public async Task Handle(RecordRecurringPaymentEndedCommand request, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); - return await recurringPaymentService.RecordEnded(request.RecurringPaymentId); + var report = await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference); + + // another subscription that ended charges nothing more, typically one the shop stopped: nothing for staff to do + if (report.Outcome == RecurringReportOutcome.OtherReference) + logger.LogInformation("Recurring payment {RecurringPaymentId} runs on {ProviderReference}; {ReportedReference} ended at the payment gateway", + report.RecurringPayment.Id, report.RecurringPayment.ProviderReference, request.ProviderReference); + + return report.Outcome == RecurringReportOutcome.Recorded; } } 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 2eb78908d..a5d567eb2 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -1,7 +1,7 @@ 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.Business.Core.Utilities.Checkout; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -19,21 +19,25 @@ public async Task Handle(RecordRecurringPaymentFailureCommand request, Can ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); - if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, - request.Reason)) - return true; + var report = await recurringPaymentService.RecordFailure(request.RecurringPaymentId, + request.ProviderReference, request.CycleReference, request.Reason); - // 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)) + switch (report.Outcome) { - if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) - recurringPayment.ProviderReference = request.ProviderReference; - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); + case RecurringReportOutcome.Recorded: + return true; + case RecurringReportOutcome.OtherReference: + await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, + report.RecurringPayment, request.ProviderReference, + $"a failed cycle ({request.CycleReference})"); + return false; + case RecurringReportOutcome.Ended: + // a failed charge on a payment the shop ended means the gateway still tries to charge, typically a + // payment cancelled while pending; the service recorded the reported reference so it can be stopped + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, report.RecurringPayment); + return false; + default: + return false; } - - return false; } } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs new file mode 100644 index 000000000..d861d1d29 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs @@ -0,0 +1,44 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Mediator; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentReferenceCommandHandler( + IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, + IOrderService orderService, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentReferenceCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + ArgumentException.ThrowIfNullOrEmpty(request.ProviderReference); + + var report = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, + request.ProviderReference); + + switch (report.Outcome) + { + case RecurringReportOutcome.Recorded: + // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped + // now, once, as a resend finds the reference recorded + if (report.RecurringPayment.Status.HasEnded()) + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, report.RecurringPayment); + return true; + case RecurringReportOutcome.Duplicate: + return true; + case RecurringReportOutcome.OtherReference: + await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, + report.RecurringPayment, request.ProviderReference, "a second subscription"); + return false; + default: + 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 index 35e462790..832edcd32 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs @@ -6,38 +6,79 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders; /// -/// What the provider commands do when the gateway reports on a recurring payment the shop already ended +/// What the provider commands do when the gateway reports on a recurring payment the shop already ended, or on +/// another reference than the one it runs on /// internal static class RecurringPaymentGateway { public static async Task Stop(IPaymentService paymentService, IOrderService orderService, ILogger logger, RecurringPayment recurringPayment) { - IEnumerable errors; + var errors = await AskToStop(paymentService, logger, 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(orderService, logger, recurringPayment, + $"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); + } + + /// + /// Stops another subscription the gateway reported on for the same recurring payment (for example a second + /// checkout of the order): the recurring payment runs on the reference recorded first, so the other one must + /// not charge the customer + /// + public static async Task StopOtherReference(IPaymentService paymentService, IOrderService orderService, + ILogger logger, RecurringPayment recurringPayment, string providerReference, string reported, + string advice = null) + { + logger.LogWarning("Recurring payment {RecurringPaymentId} runs on {ProviderReference}, but the payment gateway reported {Reported} on {ReportedReference}", + recurringPayment.Id, recurringPayment.ProviderReference, reported, providerReference); + + // only the reference differs: the store and the payment method decide how the provider stops it + var errors = await AskToStop(paymentService, logger, new RecurringPayment { + Id = recurringPayment.Id, + StoreId = recurringPayment.StoreId, + CustomerId = recurringPayment.CustomerId, + InitialOrderId = recurringPayment.InitialOrderId, + PaymentMethodSystemName = recurringPayment.PaymentMethodSystemName, + Status = recurringPayment.Status, + ProviderReference = providerReference + }); + + var outcome = errors.Any() + ? $"could not be stopped ({string.Join(", ", errors)}): cancel it at the payment gateway" + : "was stopped"; + // a gateway resends its reports, so the same note is written once + await AddNote(orderService, logger, recurringPayment, + $"The payment gateway reported {reported} on {providerReference}, but the recurring payment runs on {recurringPayment.ProviderReference}, so nothing was recorded and {providerReference} {outcome}{(advice == null ? "" : $"; {advice}")}", + once: true); + } + + private static async Task> AskToStop(IPaymentService paymentService, ILogger logger, + RecurringPayment recurringPayment) + { try { var result = await paymentService.CancelRecurringPayment(recurringPayment); - errors = result.Success ? [] : result.Errors; + return 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]; + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging {ProviderReference}", + recurringPayment.Id, recurringPayment.ProviderReference); + return [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) + string note, bool once = false) { try { + if (once && (await orderService.GetOrderNotes(recurringPayment.InitialOrderId)).Any(x => x.Note == note)) + return; + await orderService.InsertOrderNote(new OrderNote { OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, CreatedOnUtc = DateTime.UtcNow diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 0496ecdf0..1b39dcce7 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -1,4 +1,5 @@ using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Utilities.Checkout; @@ -40,8 +41,11 @@ public virtual async Task ClaimCycle(string recurringPaymen await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); - if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) - return null; + var refused = Refusal(recurringPayment, providerReference); + if (refused == null && recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + refused = RecurringReportOutcome.Duplicate; + if (refused.HasValue) + return new RecurringCycleClaim { Outcome = refused.Value, RecurringPayment = recurringPayment }; recurringPayment.CyclesPaid++; cycle = new RecurringPaymentCycle { @@ -54,8 +58,7 @@ public virtual async Task ClaimCycle(string recurringPaymen }; recurringPayment.Cycles.Add(cycle); - if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) - recurringPayment.ProviderReference = providerReference; + KeepFirstReference(recurringPayment, providerReference); if (nextPaymentDateUtc.HasValue) recurringPayment.NextPaymentDateUtc = nextPaymentDateUtc; @@ -65,7 +68,7 @@ public virtual async Task ClaimCycle(string recurringPaymen //the gateway took the money after a cancel, so the cycle is recorded and the status is left alone if (recurringPayment.TotalCycles > 0 && recurringPayment.CyclesPaid == recurringPayment.TotalCycles && - recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed)) + !recurringPayment.Status.HasEnded()) { recurringPayment.Status = RecurringPaymentStatus.Completed; completed = true; @@ -77,10 +80,14 @@ recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPay //event notification await mediator.EntityUpdated(recurringPayment); - return new RecurringCycleClaim { RecurringPayment = recurringPayment, Cycle = cycle, Completed = completed }; + return new RecurringCycleClaim { + Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment, Cycle = cycle, + Completed = completed + }; } - public virtual async Task RecordFailure(string recurringPaymentId, string cycleReference, string reason) + public virtual async Task RecordFailure(string recurringPaymentId, + string providerReference, string cycleReference, string reason) { ArgumentException.ThrowIfNullOrEmpty(cycleReference); @@ -90,12 +97,23 @@ public virtual async Task RecordFailure(string recurringPaymentId, string await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + var refused = Refusal(recurringPayment, providerReference); //a failure that arrives after the cycle was paid is a late, out of order event - if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || - recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) - return false; + if (refused == null && recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + refused = RecurringReportOutcome.Duplicate; + if (refused == null && recurringPayment.Status.HasEnded()) + { + //the gateway still tries to charge a payment the shop ended, typically one cancelled while pending: + //its reference is kept so the gateway can be stopped + if (KeepFirstReference(recurringPayment, providerReference)) + await repository.UpdateAsync(recurringPayment); + refused = RecurringReportOutcome.Ended; + } + if (refused.HasValue) + return new RecurringReportResult { Outcome = refused.Value, RecurringPayment = recurringPayment }; + + KeepFirstReference(recurringPayment, providerReference); recurringPayment.LastError = reason; recurringPayment.LastErrorDateUtc = DateTime.UtcNow; @@ -110,20 +128,24 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS if (enteredPastDue) await mediator.Publish(new RecurringPaymentPastDueEvent(recurringPayment)); - return enteredPastDue; + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; } - public virtual async Task RecordEnded(string recurringPaymentId) + public virtual async Task RecordEnded(string recurringPaymentId, string providerReference) { RecurringPayment recurringPayment; await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); - if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) - return false; - + //another subscription ending says nothing about the one this payment runs on + var refused = Refusal(recurringPayment, providerReference); + if (refused == null && recurringPayment.Status.HasEnded()) + refused = RecurringReportOutcome.Ended; + if (refused.HasValue) + return new RecurringReportResult { Outcome = refused.Value, RecurringPayment = recurringPayment }; + + KeepFirstReference(recurringPayment, providerReference); recurringPayment.Status = RecurringPaymentStatus.Cancelled; recurringPayment.CancelledOnUtc = DateTime.UtcNow; recurringPayment.CancelledBy = recurringPayment.PaymentMethodSystemName; @@ -135,6 +157,53 @@ public virtual async Task RecordEnded(string recurringPaymentId) await mediator.EntityUpdated(recurringPayment); await mediator.Publish(new RecurringPaymentCancelledEvent(recurringPayment)); + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; + } + + public virtual async Task RecordProviderReference(string recurringPaymentId, + string providerReference) + { + ArgumentException.ThrowIfNullOrEmpty(providerReference); + + RecurringPayment recurringPayment; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + var refused = Refusal(recurringPayment, providerReference); + if (refused == null && recurringPayment.ProviderReference == providerReference) + refused = RecurringReportOutcome.Duplicate; + if (refused.HasValue) + return new RecurringReportResult { Outcome = refused.Value, RecurringPayment = recurringPayment }; + + recurringPayment.ProviderReference = providerReference; + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; + } + + //why a report is refused whatever it reports, or null + private static RecurringReportOutcome? Refusal(RecurringPayment recurringPayment, string providerReference) + { + if (recurringPayment == null) + return RecurringReportOutcome.NotFound; + + return recurringPayment.HasOtherProviderReference(providerReference) + ? RecurringReportOutcome.OtherReference + : null; + } + + //the first reference reported is the one the payment runs on, whichever report brings it + private static bool KeepFirstReference(RecurringPayment recurringPayment, string providerReference) + { + if (!string.IsNullOrEmpty(recurringPayment.ProviderReference) || string.IsNullOrEmpty(providerReference)) + return false; + + recurringPayment.ProviderReference = providerReference; return true; } @@ -157,11 +226,11 @@ public virtual async Task Cancel(string recurringP return notFound; } - if (recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + if (recurringPayment.Status.HasEnded()) 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 + //a pending payment whose reference is not known yet has nothing to stop: the gateway is stopped when the + //provider reports the reference (RecordRecurringPaymentReferenceCommand) or a first cycle on it if (recurringPayment.Status == RecurringPaymentStatus.Pending && string.IsNullOrEmpty(recurringPayment.ProviderReference)) { @@ -180,8 +249,7 @@ public virtual async Task Cancel(string recurringP { 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) + if (recurringPayment == null || recurringPayment.Status.HasEnded()) return new CancelRecurringPaymentResult(); //never cancelled while the gateway may still charge diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs index 39cce12c1..299d0f3bb 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs @@ -4,7 +4,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// /// A payment provider reports that a cycle of a recurring payment was paid. The result is true when the cycle was -/// recorded now and false when there was nothing to do (an unknown recurring payment, or a cycle already recorded) +/// recorded now and false when there was nothing to do (an unknown recurring payment, a cycle already recorded, or +/// another subscription than the one the recurring payment runs on, which is asked to stop) /// public class RecordRecurringPaymentCycleCommand : IRequest { diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs index 453261855..32c207c15 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs @@ -9,4 +9,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class RecordRecurringPaymentEndedCommand : IRequest { public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of what ended (for example the subscription id), so the end of another + /// subscription started for the same order does not cancel the one the recurring payment runs on + /// + public string ProviderReference { 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 488ceb07b..891b22a72 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -3,8 +3,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// -/// A payment provider reports that a cycle of a recurring payment failed. The result is true when the recurring -/// payment became past due +/// A payment provider reports that a cycle of a recurring payment failed. The result is true when the failure was +/// recorded and the recurring payment is past due /// public class RecordRecurringPaymentFailureCommand : IRequest { diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs new file mode 100644 index 000000000..dfcdfe083 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs @@ -0,0 +1,21 @@ +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// A payment provider reports the gateway's reference of a recurring payment as soon as it learns it, typically when +/// the customer completes the checkout and before the first cycle is reported, so a cancel stops the gateway at +/// once. The result is true when the recurring payment runs on this reference +/// +public class RecordRecurringPaymentReferenceCommand : IRequest +{ + /// + /// The recurring payment the provider was given as gateway metadata + /// + public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of the recurring payment (for example the subscription id) + /// + public string ProviderReference { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs index a4bb5e2bd..526878712 100644 --- a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs @@ -12,4 +12,14 @@ public static bool HasEnded(this RecurringPaymentStatus status) { return status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed; } + + /// + /// Whether a gateway report names another reference than the one the recurring payment runs on, for example a + /// second subscription started for the same order. False while either reference is unknown + /// + public static bool HasOtherProviderReference(this RecurringPayment recurringPayment, string providerReference) + { + return !string.IsNullOrEmpty(recurringPayment.ProviderReference) && !string.IsNullOrEmpty(providerReference) && + recurringPayment.ProviderReference != providerReference; + } } 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 495004fa6..616c8346e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -16,23 +16,37 @@ public interface IRecurringPaymentService /// /// 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 + /// nothing. The cycle is recorded on a cancelled or completed recurring payment too, as the gateway took the + /// money; otherwise the outcome says why nothing was recorded (unknown, cycle reference recorded already, or + /// another provider reference than the one the recurring payment runs on). The first reported reference is + /// recorded /// Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc); /// - /// Records a cycle the provider reports as failed, under the same lock. Returns true only when the status moved - /// into PastDue. Nothing is recorded for an unknown recurring payment, one that is Cancelled or Completed, or a - /// cycle that was paid already + /// Records a cycle the provider reports as failed, under the same lock, moving the recurring payment into + /// PastDue. Nothing is recorded for an unknown recurring payment, a cycle that was paid already, another + /// provider reference than the one the recurring payment runs on, or a payment that is Cancelled or Completed, + /// whose missing reference is still recorded so the gateway can be stopped. The first reported reference is + /// recorded /// - Task RecordFailure(string recurringPaymentId, string cycleReference, string reason); + Task RecordFailure(string recurringPaymentId, string providerReference, + string cycleReference, string reason); /// - /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Returns false - /// for an unknown recurring payment or one that is Cancelled or Completed + /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Nothing is + /// recorded for an unknown recurring payment, another provider reference than the one the recurring payment + /// runs on, or one that is Cancelled or Completed. The first reported reference is recorded /// - Task RecordEnded(string recurringPaymentId); + Task RecordEnded(string recurringPaymentId, string providerReference); + + /// + /// Records the gateway's reference as soon as the provider learns it (at checkout), under the same lock, so a + /// cancel made before the first paid cycle stops the gateway. A reference recorded already is kept: the + /// outcome is Duplicate for the same one and OtherReference for another + /// + Task RecordProviderReference(string recurringPaymentId, string providerReference); /// /// Cancels a recurring payment, writing it under the same lock on a fresh read. Unless it is Pending without a diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs index 92908ee58..2f18bda21 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs @@ -3,17 +3,12 @@ namespace Grand.Business.Core.Utilities.Checkout; /// -/// A paid cycle recorded on a recurring payment +/// A paid cycle reported on a recurring payment /// -public class RecurringCycleClaim +public class RecurringCycleClaim : RecurringReportResult { /// - /// The recurring payment as saved - /// - public RecurringPayment RecurringPayment { get; init; } - - /// - /// The cycle that was recorded + /// The cycle that was recorded; null unless the outcome is Recorded /// public RecurringPaymentCycle Cycle { get; init; } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs new file mode 100644 index 000000000..056135527 --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs @@ -0,0 +1,32 @@ +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// What the recurring payment service did with a gateway report +/// +public enum RecurringReportOutcome +{ + /// + /// The report was recorded on the recurring payment + /// + Recorded = 0, + + /// + /// Nothing was recorded: the recurring payment is unknown + /// + NotFound = 10, + + /// + /// Nothing was recorded: the same report was recorded already, typically a resend + /// + Duplicate = 20, + + /// + /// Nothing was recorded: the report names another reference than the one the recurring payment runs on + /// + OtherReference = 30, + + /// + /// Nothing was recorded: the recurring payment is cancelled or completed + /// + Ended = 40 +} diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs new file mode 100644 index 000000000..3866ce8a1 --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs @@ -0,0 +1,16 @@ +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// A gateway report on a recurring payment, as the recurring payment service handled it under the lock +/// +public class RecurringReportResult +{ + public RecurringReportOutcome Outcome { get; init; } + + /// + /// The recurring payment as read under the lock, or as saved; null when it is unknown + /// + public RecurringPayment RecurringPayment { get; init; } +} 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 249285722..b12493881 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 @@ -26,6 +26,12 @@ public void Init() _paymentService = new Mock(); _orderService = new Mock(); _mediator = new Mock(); + _orderService.Setup(x => x.GetOrderNotes(It.IsAny())).ReturnsAsync(new List()); + } + + private static RecurringReportResult Report(RecurringReportOutcome outcome, RecurringPayment recurringPayment = null) + { + return new RecurringReportResult { Outcome = outcome, RecurringPayment = recurringPayment }; } private RecordRecurringPaymentFailureCommandHandler FailureHandler() @@ -44,25 +50,25 @@ private static RecordRecurringPaymentFailureCommand FailureCommand() [TestMethod] public async Task FailureCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordFailure("rp1", "in_2", "declined")).ReturnsAsync(true); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")) + .ReturnsAsync(Report(RecurringReportOutcome.Recorded, new RecurringPayment { Id = "rp1" })); var result = await FailureHandler().Handle(FailureCommand(), CancellationToken.None); Assert.IsTrue(result); - _service.Verify(x => x.RecordFailure("rp1", "in_2", "declined"), Times.Once); + _service.Verify(x => x.RecordFailure("rp1", "sub_1", "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) + public async Task FailureCommand_OnAnEndedPayment_AsksTheProviderToStop(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 - }); + // cancelled while pending: the service recorded the reported reference so the gateway can be stopped + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(Report( + RecurringReportOutcome.Ended, + new RecurringPayment { Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" })); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) .ReturnsAsync(new CancelRecurringPaymentResult()); @@ -75,9 +81,11 @@ public async Task FailureCommand_OnAnEndedPayment_AsksTheProviderToStopWithTheRe [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" - }); + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(Report( + RecurringReportOutcome.Ended, + 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); @@ -90,19 +98,20 @@ public async Task FailureCommand_OnAnEndedPaymentAndProviderRefuses_NotesItOnThe } [TestMethod] - public async Task FailureCommand_ForACyclePaidAlreadyOrAnActivePayment_DoesNotAskTheProviderToStop() + [DataRow(RecurringReportOutcome.Duplicate)] + [DataRow(RecurringReportOutcome.NotFound)] + public async Task FailureCommand_ForACyclePaidAlreadyOrAnUnknownPayment_DoesNotAskTheProviderToStop( + RecurringReportOutcome outcome) { - 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.RecordFailure("rp1", "sub_1", "in_2", "declined")).ReturnsAsync(Report(outcome, + outcome == RecurringReportOutcome.NotFound + ? null + : new RecurringPayment { Id = "rp1", Status = RecurringPaymentStatus.Cancelled })); - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", Status = RecurringPaymentStatus.PastDue - }); - await FailureHandler().Handle(FailureCommand(), CancellationToken.None); + Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); } [TestMethod] @@ -117,25 +126,228 @@ await Assert.ThrowsExactlyAsync(() => [TestMethod] public async Task EndedCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordEnded("rp1")).ReturnsAsync(true); - var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + _service.Setup(x => x.RecordEnded("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.Recorded, new RecurringPayment { Id = "rp1" })); - var result = await handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1" }, - CancellationToken.None); + var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None); Assert.IsTrue(result); - _service.Verify(x => x.RecordEnded("rp1"), Times.Once); + _service.Verify(x => x.RecordEnded("rp1", "sub_1"), Times.Once); } [TestMethod] public async Task EndedCommand_WithoutRecurringPaymentId_Throws() { - var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + var handler = EndedHandler(); await Assert.ThrowsExactlyAsync(() => handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "" }, CancellationToken.None)); } + private RecordRecurringPaymentEndedCommandHandler EndedHandler() + { + return new RecordRecurringPaymentEndedCommandHandler(_service.Object, + new Mock>().Object); + } + + // the recurring payment runs on sub_9, and a second subscription sub_1 reports on it + private static RecurringPayment RunsOnAnotherReference() + { + return new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", StoreId = "s1", PaymentMethodSystemName = "Payments.Test", + Status = RecurringPaymentStatus.Active, ProviderReference = "sub_9" + }; + } + + private void SetupStop() + { + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + } + + private void VerifyOtherReferenceStopped(string note) + { + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1" && + r.ProviderReference == "sub_1" && r.StoreId == "s1" && r.PaymentMethodSystemName == "Payments.Test")), + Times.Once); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => + r.ProviderReference == "sub_9")), Times.Never); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && + !n.DisplayToCustomer && n.Note == note)), Times.Once); + } + + [TestMethod] + public async Task EndedCommand_OtherProviderReference_WritesNoNote() + { + // another subscription that ended charges nothing more + _service.Setup(x => x.RecordEnded("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); + + var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None); + + Assert.IsFalse(result); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task EndedCommand_AlreadyEnded_WritesNoNote() + { + _service.Setup(x => x.RecordEnded("rp1", "sub_1")).ReturnsAsync(Report(RecurringReportOutcome.Ended, + new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" + })); + + Assert.IsFalse(await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None)); + + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task FailureCommand_OtherProviderReference_StopsTheOtherOneAndNotesIt() + { + _service.Setup(x => x.RecordFailure("rp1", "sub_1", "in_2", "declined")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); + SetupStop(); + + Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); + + VerifyOtherReferenceStopped( + "The payment gateway reported a failed cycle (in_2) on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 was stopped"); + } + + [TestMethod] + public async Task CycleCommand_OtherProviderReference_StopsTheOtherOneAndNotesARefund() + { + _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)) + .ReturnsAsync(new RecurringCycleClaim { + Outcome = RecurringReportOutcome.OtherReference, RecurringPayment = RunsOnAnotherReference() + }); + SetupStop(); + + Assert.IsFalse(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + VerifyOtherReferenceStopped( + "The payment gateway reported a paid cycle (in_2) on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 was stopped; check whether the customer must be refunded"); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task CycleCommand_OtherProviderReferenceAndProviderRefuses_NotesItOnce() + { + _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)) + .ReturnsAsync(new RecurringCycleClaim { + Outcome = RecurringReportOutcome.OtherReference, RecurringPayment = RunsOnAnotherReference() + }); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + const string note = + "The payment gateway reported a paid cycle (in_2) on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 could not be stopped (no way): cancel it at the payment gateway; check whether the customer must be refunded"; + + await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + // the gateway resends the report, and the note is already there + _orderService.Setup(x => x.GetOrderNotes("o1")) + .ReturnsAsync(new List { new() { OrderId = "o1", Note = note } }); + await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.Note == note)), Times.Once); + } + + private RecordRecurringPaymentReferenceCommandHandler ReferenceHandler() + { + return new RecordRecurringPaymentReferenceCommandHandler(_service.Object, _paymentService.Object, + _orderService.Object, new Mock>().Object); + } + + private static RecordRecurringPaymentReferenceCommand ReferenceCommand() + { + return new RecordRecurringPaymentReferenceCommand { RecurringPaymentId = "rp1", ProviderReference = "sub_1" }; + } + + [TestMethod] + public async Task ReferenceCommand_Pending_RecordsItWithoutTheGateway() + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(Report( + RecurringReportOutcome.Recorded, + new RecurringPayment { Id = "rp1", Status = RecurringPaymentStatus.Pending, ProviderReference = "sub_1" })); + + Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task ReferenceCommand_CancelledBeforeTheReferenceWasKnown_StopsTheGateway( + RecurringPaymentStatus status) + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(Report( + RecurringReportOutcome.Recorded, + new RecurringPayment { Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" })); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => + r.ProviderReference == "sub_1")), Times.Once); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task ReferenceCommand_ResentOnAnEndedPayment_DoesNotAskTheProviderToStopAgain( + RecurringPaymentStatus status) + { + // the gateway was stopped when the reference was recorded, or by the cancel that came after it + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(Report( + RecurringReportOutcome.Duplicate, + new RecurringPayment { Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" })); + + Assert.IsTrue(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task ReferenceCommand_OtherReferenceRecorded_StopsTheOtherOneAndNotesIt() + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); + SetupStop(); + + Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + VerifyOtherReferenceStopped( + "The payment gateway reported a second subscription on sub_1, but the recurring payment runs on sub_9, so nothing was recorded and sub_1 was stopped"); + } + + [TestMethod] + public async Task ReferenceCommand_UnknownRecurringPayment_ReturnsFalse() + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.NotFound)); + + Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + } + + [TestMethod] + public async Task ReferenceCommand_WithoutReference_Throws() + { + await Assert.ThrowsExactlyAsync(() => ReferenceHandler().Handle( + new RecordRecurringPaymentReferenceCommand { RecurringPaymentId = "rp1", ProviderReference = "" }, + CancellationToken.None)); + } + private RecordRecurringPaymentCycleCommandHandler CycleHandler() { return new RecordRecurringPaymentCycleCommandHandler(_service.Object, _paymentService.Object, @@ -154,6 +366,7 @@ private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = Recurri bool completed = false) { var claim = new RecurringCycleClaim { + Outcome = RecurringReportOutcome.Recorded, RecurringPayment = new RecurringPayment { Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test", Status = status }, @@ -167,7 +380,9 @@ private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = Recurri public async Task CycleCommand_AlreadyRecorded_DoesNothing() { _service.Setup(x => x.ClaimCycle(It.IsAny(), It.IsAny(), It.IsAny(), - It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync((RecurringCycleClaim)null); + It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(new RecurringCycleClaim { + Outcome = RecurringReportOutcome.Duplicate, RecurringPayment = new RecurringPayment { Id = "rp1" } + }); var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); 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 7993dcf0f..2cb8293fd 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -102,7 +102,7 @@ public async Task ClaimCycle_FirstCycle_IsTheInitialOrderAndActivates() var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, paid, next); - Assert.IsNotNull(claim); + Assert.AreEqual(RecurringReportOutcome.Recorded, claim.Outcome); Assert.AreEqual(1, claim.Cycle.CycleNumber); Assert.AreEqual("o1", claim.Cycle.OrderId); Assert.AreEqual("in_1", claim.Cycle.ProviderReference); @@ -130,12 +130,12 @@ public async Task ClaimCycle_LaterCycle_GetsANewOrderIdAndLeavesPastDue() } [TestMethod] - public async Task ClaimCycle_SameCycleReferenceAgain_ReturnsNull() + public async Task ClaimCycle_SameCycleReferenceAgain_IsADuplicate() { var rp = await Insert(RecurringPaymentStatus.Pending, 0); - Assert.IsNotNull(await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)); - Assert.IsNull(await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); + Assert.AreEqual(RecurringReportOutcome.Duplicate, (await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(1, saved.Cycles.Count); @@ -152,7 +152,7 @@ public async Task ClaimCycle_ConcurrentDeliveries_ClaimOnce() _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null), other.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null)); - Assert.AreEqual(1, claims.Count(c => c != null)); + Assert.AreEqual(1, claims.Count(c => c.Outcome == RecurringReportOutcome.Recorded)); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(1, saved.Cycles.Count(c => c.ProviderReference == "in_2")); } @@ -186,7 +186,7 @@ public async Task ClaimCycle_AfterCancelled_RecordsTheCycleAndKeepsTheStatus() var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); - Assert.IsNotNull(claim); + Assert.AreEqual(RecurringReportOutcome.Recorded, claim.Outcome); Assert.AreEqual(2, claim.Cycle.CycleNumber); Assert.IsFalse(claim.Completed); Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); @@ -199,7 +199,7 @@ public async Task ClaimCycle_ReachingTotalCyclesAfterCancelled_KeepsTheStatusAnd var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); - Assert.IsNotNull(claim); + Assert.AreEqual(RecurringReportOutcome.Recorded, claim.Outcome); Assert.IsFalse(claim.Completed); Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); } @@ -218,27 +218,28 @@ public async Task RecordFailure_WithoutCycleReference_Throws() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - await Assert.ThrowsExactlyAsync(() => _service.RecordFailure(rp.Id, "", "declined")); + await Assert.ThrowsExactlyAsync(() => + _service.RecordFailure(rp.Id, "sub_1", "", "declined")); } [TestMethod] - public async Task ClaimCycle_UnknownRecurringPayment_ReturnsNull() + public async Task ClaimCycle_UnknownRecurringPayment_IsNotFound() { - Assert.IsNull(await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); } [TestMethod] - public async Task RecordFailure_Active_EntersPastDueOnlyOnce() + public async Task RecordFailure_Active_EntersPastDueAndKeepsTheLastError() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordFailure(rp.Id, "in_2", "declined")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); Assert.AreEqual("declined", saved.LastError); Assert.IsNotNull(saved.LastErrorDateUtc); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "expired")); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordFailure(rp.Id, "sub_1", "in_2", "expired")).Outcome); saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); Assert.AreEqual("expired", saved.LastError); @@ -249,7 +250,7 @@ public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() { var rp = await Insert(RecurringPaymentStatus.Active, 2); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "late")); + Assert.AreEqual(RecurringReportOutcome.Duplicate, (await _service.RecordFailure(rp.Id, "sub_1", "in_2", "late")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); @@ -257,21 +258,25 @@ public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() } [TestMethod] - public async Task RecordFailure_Cancelled_ChangesNothing() + public async Task RecordFailure_Cancelled_RecordsOnlyTheMissingReference() { + // cancelled while pending: the gateway still charges, and its reference is needed to stop it var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "declined")); + var report = await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined"); + Assert.AreEqual(RecurringReportOutcome.Ended, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("sub_1", saved.ProviderReference); Assert.IsNull(saved.LastError); } [TestMethod] - public async Task RecordFailure_UnknownRecurringPayment_ReturnsFalse() + public async Task RecordFailure_UnknownRecurringPayment_IsNotFound() { - Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "in_2", "declined")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordFailure(UniqueIdentifier.New, "sub_1", "in_2", "declined")).Outcome); } [TestMethod] @@ -281,10 +286,11 @@ public async Task RecordEnded_Active_CancelsByTheProvider() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); - Assert.IsTrue(await _service.RecordEnded(rp.Id)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(rp.Id, "sub_1")).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("sub_1", saved.ProviderReference); Assert.AreEqual("Payments.Test", saved.CancelledBy); Assert.IsNotNull(saved.CancelledOnUtc); } @@ -293,19 +299,155 @@ public async Task RecordEnded_Active_CancelsByTheProvider() public async Task RecordEnded_CompletedOrCancelled_ChangesNothing() { var completed = await Insert(RecurringPaymentStatus.Completed, 12); - Assert.IsFalse(await _service.RecordEnded(completed.Id)); + Assert.AreEqual(RecurringReportOutcome.Ended, (await _service.RecordEnded(completed.Id, "sub_1")).Outcome); Assert.AreEqual(RecurringPaymentStatus.Completed, (await _service.GetRecurringPaymentById(completed.Id)).Status); var active = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordEnded(active.Id)); - Assert.IsFalse(await _service.RecordEnded(active.Id)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(active.Id, "sub_1")).Outcome); + Assert.AreEqual(RecurringReportOutcome.Ended, (await _service.RecordEnded(active.Id, "sub_1")).Outcome); + } + + [TestMethod] + public async Task RecordEnded_UnknownRecurringPayment_IsNotFound() + { + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordEnded(UniqueIdentifier.New, "sub_1")).Outcome); + } + + [TestMethod] + public async Task ClaimCycle_OtherProviderReference_RecordsNothing() + { + // a second subscription started for the same order reports with the same recurring payment id + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.ClaimCycle(rp.Id, "sub_2", "in_9", 10, DateTime.UtcNow, null)).Outcome); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(1, saved.CyclesPaid); + Assert.AreEqual("sub_1", saved.ProviderReference); + } + + [TestMethod] + public async Task ClaimCycle_ProviderReferenceNotGiven_IsNotChecked() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)).Outcome); + } + + [TestMethod] + public async Task RecordFailure_OtherProviderReference_ChangesNothing() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.RecordFailure(rp.Id, "sub_2", "in_9", "declined")).Outcome); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.IsNull(saved.LastError); + } + + [TestMethod] + public async Task RecordEnded_OtherProviderReference_KeepsThePaymentRunning() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.RecordEnded(rp.Id, "sub_2")).Outcome); + + Assert.AreEqual(RecurringPaymentStatus.Active, (await _service.GetRecurringPaymentById(rp.Id)).Status); + _mediatorMock.Verify(x => x.Publish(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task RecordProviderReference_Pending_RecordsItSoACancelAsksTheGateway() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + var report = await _service.RecordProviderReference(rp.Id, "sub_1"); + + Assert.AreEqual(RecurringReportOutcome.Recorded, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Pending, report.RecurringPayment.Status); + Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + + var asked = false; + await _service.Cancel(rp.Id, "customer", _ => + { + asked = true; + return Task.FromResult(new CancelRecurringPaymentResult()); + }); + Assert.IsTrue(asked); } [TestMethod] - public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() + public async Task RecordProviderReference_AnotherOneRecorded_KeepsIt() { - Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New)); + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + var report = await _service.RecordProviderReference(rp.Id, "sub_2"); + + Assert.AreEqual(RecurringReportOutcome.OtherReference, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); + Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + } + + [TestMethod] + public async Task RecordProviderReference_SameOneAgain_IsADuplicate() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 0); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordProviderReference(rp.Id, "sub_1")).Outcome); + Assert.AreEqual(RecurringReportOutcome.Duplicate, (await _service.RecordProviderReference(rp.Id, "sub_1")).Outcome); + } + + [TestMethod] + public async Task RecordEnded_BeforeTheReferenceIsKnown_RunsOnTheReportedOne() + { + // the first reference reported is the one the payment runs on, whichever report brings it + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(rp.Id, "sub_2")).Outcome); + + Assert.AreEqual("sub_2", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.RecordProviderReference(rp.Id, "sub_1")).Outcome); + } + + [TestMethod] + public async Task RecordFailure_BeforeTheReferenceIsKnown_RunsOnTheReportedOne() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordFailure(rp.Id, "sub_2", "in_1", "declined")).Outcome); + + Assert.AreEqual("sub_2", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + Assert.AreEqual(RecurringReportOutcome.OtherReference, (await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)).Outcome); + } + + [TestMethod] + public async Task RecordProviderReference_Cancelled_RecordsItAndKeepsTheStatus() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 0); + + var report = await _service.RecordProviderReference(rp.Id, "sub_1"); + + Assert.AreEqual(RecurringReportOutcome.Recorded, report.Outcome); + Assert.AreEqual("sub_1", report.RecurringPayment.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, report.RecurringPayment.Status); + } + + [TestMethod] + public async Task RecordProviderReference_UnknownRecurringPayment_IsNotFound() + { + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")).Outcome); + } + + [TestMethod] + public async Task RecordProviderReference_Empty_Throws() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + await Assert.ThrowsExactlyAsync(() => _service.RecordProviderReference(rp.Id, "")); } private static CancelRecurringPaymentResult Refusal(string error) @@ -467,7 +609,7 @@ public async Task Cancel_CycleWebhookDuringTheGatewayCall_IsNotHeldUpAndIsKept() }); Assert.IsTrue(result.Success); - Assert.IsNotNull(await claimTask); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await claimTask).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); Assert.AreEqual(2, saved.Cycles.Count); @@ -482,17 +624,17 @@ public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); - Task endedTask = null; + Task endedTask = null; var result = await _service.Cancel(rp.Id, "jane@example.com", async _ => { - endedTask = other.RecordEnded(rp.Id); + endedTask = other.RecordEnded(rp.Id, "sub_1"); await endedTask.WaitAsync(ConcurrentTimeout); return new CancelRecurringPaymentResult(); }); Assert.IsTrue(result.Success); - Assert.IsTrue(await endedTask); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await endedTask).Outcome); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); Assert.AreEqual("Payments.Test", saved.CancelledBy); @@ -557,8 +699,8 @@ 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)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.RecordEnded(rp.Id, "sub_1")).Outcome); + Assert.AreEqual(RecurringReportOutcome.Ended, (await _service.RecordEnded(rp.Id, "sub_1")).Outcome); var published = Published(); Assert.AreEqual(1, published.Count); @@ -570,8 +712,8 @@ 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"); + await _service.RecordFailure(rp.Id, "sub_1", "in_2", "a"); + await _service.RecordFailure(rp.Id, "sub_1", "in_2", "b"); var published = Published(); Assert.AreEqual(1, published.Count);