From 354662a44a410fa5a77e480bf563cff6d4a701a2 Mon Sep 17 00:00:00 2001 From: support Date: Sun, 22 Nov 2026 07:32:26 +0100 Subject: [PATCH 1/2] Recurring payments: record the gateway reference at checkout and ignore reports on another one A provider can now record the gateway's reference of a recurring payment as soon as it learns it (RecordRecurringPaymentReferenceCommand), under the recurring payment's lock. A cancel made before the first paid cycle then stops the gateway at once; a payment cancelled before the reference was known is stopped when the reference arrives. The cycle, failure and ended reports are checked against the recorded reference: a report on another subscription (for example a second one started for the same order) records nothing and leaves a note on the initial order. RecordRecurringPaymentEndedCommand gains ProviderReference. --- ...cordRecurringPaymentCycleCommandHandler.cs | 8 + ...cordRecurringPaymentEndedCommandHandler.cs | 17 +- ...rdRecurringPaymentFailureCommandHandler.cs | 12 +- ...RecurringPaymentReferenceCommandHandler.cs | 40 +++++ .../Orders/RecurringPaymentGateway.cs | 9 + .../Orders/RecurringPaymentService.cs | 39 ++++- .../RecordRecurringPaymentEndedCommand.cs | 6 + .../RecordRecurringPaymentReferenceCommand.cs | 21 +++ .../Extensions/RecurringPaymentExtensions.cs | 10 ++ .../Orders/IRecurringPaymentService.cs | 22 ++- ...ordRecurringPaymentCommandHandlersTests.cs | 154 +++++++++++++++++- .../Orders/RecurringPaymentServiceTests.cs | 134 +++++++++++++-- 12 files changed, 433 insertions(+), 39 deletions(-) create mode 100644 src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs create mode 100644 src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs 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..ba55bdf80 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -1,5 +1,6 @@ using System.Runtime.ExceptionServices; 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.Domain.Orders; @@ -26,7 +27,14 @@ 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) + { + // a resend is the usual reason; a report on another subscription is the one staff must hear about + var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); + if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); return false; + } // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable cancellationToken = CancellationToken.None; 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..8552aeab8 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,29 @@ using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Mediator; +using Microsoft.Extensions.Logging; namespace Grand.Business.Checkout.Commands.Handlers.Orders; -public class RecordRecurringPaymentEndedCommandHandler(IRecurringPaymentService recurringPaymentService) +public class RecordRecurringPaymentEndedCommandHandler( + IRecurringPaymentService recurringPaymentService, + IOrderService orderService, + ILogger logger) : IRequestHandler { public async Task Handle(RecordRecurringPaymentEndedCommand request, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); - return await recurringPaymentService.RecordEnded(request.RecurringPaymentId); + if (await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference)) + return true; + + var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); + if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); + + return false; } } 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..1c440a76a 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -1,4 +1,5 @@ using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Domain.Orders; @@ -19,13 +20,20 @@ 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)) + if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.ProviderReference, + 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 != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + { + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); + return false; + } + if (recurringPayment?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed && recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference)) { 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..5be63bb56 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs @@ -0,0 +1,40 @@ +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.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 recurringPayment = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, + request.ProviderReference); + if (recurringPayment == null) + return false; + + if (recurringPayment.HasOtherProviderReference(request.ProviderReference)) + { + await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, + request.ProviderReference); + return false; + } + + // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped now + if (recurringPayment.Status.HasEnded()) + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); + + return true; + } +} 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..f28215a63 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs @@ -33,6 +33,15 @@ 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 Task NoteOtherReference(IOrderService orderService, ILogger logger, + RecurringPayment recurringPayment, string providerReference) + { + logger.LogWarning("Recurring payment {RecurringPaymentId} runs on {ProviderReference}, but the payment gateway reported on {ReportedReference}", + recurringPayment.Id, recurringPayment.ProviderReference, providerReference); + return AddNote(orderService, logger, recurringPayment, + $"The payment gateway reported on {providerReference}, but the recurring payment runs on {recurringPayment.ProviderReference}, so nothing was recorded: check the payment gateway for a second subscription charging the customer"); + } + public static async Task AddNote(IOrderService orderService, ILogger logger, RecurringPayment recurringPayment, string note) { diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 0496ecdf0..29ec1ee16 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,7 +41,8 @@ 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)) + if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference) || + recurringPayment.HasOtherProviderReference(providerReference)) return null; recurringPayment.CyclesPaid++; @@ -80,7 +82,8 @@ recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPay return new RecurringCycleClaim { 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); @@ -93,7 +96,8 @@ public virtual async Task RecordFailure(string recurringPaymentId, string //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)) + recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference) || + recurringPayment.HasOtherProviderReference(providerReference)) return false; recurringPayment.LastError = reason; @@ -113,15 +117,17 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS return enteredPastDue; } - 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); + //another subscription ending says nothing about the one this payment runs on if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || + recurringPayment.HasOtherProviderReference(providerReference)) return false; recurringPayment.Status = RecurringPaymentStatus.Cancelled; @@ -138,6 +144,29 @@ public virtual async Task RecordEnded(string recurringPaymentId) return true; } + 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); + if (recurringPayment == null || !string.IsNullOrEmpty(recurringPayment.ProviderReference)) + return recurringPayment; + + recurringPayment.ProviderReference = providerReference; + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return recurringPayment; + } + public virtual async Task Cancel(string recurringPaymentId, string cancelledBy, Func> stopAtGateway) { 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/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..42b85ab34 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,33 @@ 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. Returns null when the recurring payment is unknown, the cycle reference was already recorded or + /// the provider reference is not the one the recurring payment runs on /// 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 + /// into PastDue. Nothing is recorded for an unknown recurring payment, one that is Cancelled or Completed, a + /// cycle that was paid already, or another provider reference than the one the recurring payment runs on /// - 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 + /// for an unknown recurring payment, one that is Cancelled or Completed, or another provider reference than + /// the one the recurring payment runs on /// - 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. Returns the + /// recurring payment as saved, or null when it is unknown + /// + 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/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs index 249285722..7719dfee1 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 @@ -44,12 +44,12 @@ 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(true); 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); } @@ -117,25 +117,163 @@ 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(true); - 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, _orderService.Object, + new Mock>().Object); + } + + private void SetupOtherReference() + { + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" + }); + } + + private void VerifyOtherReferenceNoted() + { + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && + n.Note.StartsWith("The payment gateway reported on sub_1, but the recurring payment runs on sub_9"))), + Times.Once); + } + + [TestMethod] + public async Task EndedCommand_OtherProviderReference_NotesItOnTheInitialOrder() + { + SetupOtherReference(); + + var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1" + }, CancellationToken.None); + + Assert.IsFalse(result); + VerifyOtherReferenceNoted(); + } + + [TestMethod] + public async Task EndedCommand_AlreadyEnded_WritesNoNote() + { + _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(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_NotesItAndDoesNotStopTheRecordedOne() + { + SetupOtherReference(); + + Assert.IsFalse(await FailureHandler().Handle(FailureCommand(), CancellationToken.None)); + + VerifyOtherReferenceNoted(); + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CycleCommand_OtherProviderReference_NotesItOnTheInitialOrder() + { + SetupOtherReference(); + + Assert.IsFalse(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + VerifyOtherReferenceNoted(); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + 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(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(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] + public async Task ReferenceCommand_OtherReferenceRecorded_NotesItAndStopsNothing() + { + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" + }); + + Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); + + VerifyOtherReferenceNoted(); + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task ReferenceCommand_UnknownRecurringPayment_ReturnsFalse() + { + 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, 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..7aa9d3042 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -218,7 +218,8 @@ 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] @@ -232,13 +233,13 @@ public async Task RecordFailure_Active_EntersPastDueOnlyOnce() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordFailure(rp.Id, "in_2", "declined")); + Assert.IsTrue(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")); 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.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "expired")); 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.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "late")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); @@ -261,7 +262,7 @@ public async Task RecordFailure_Cancelled_ChangesNothing() { var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "declined")); + Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "in_2", "declined")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); @@ -271,7 +272,7 @@ public async Task RecordFailure_Cancelled_ChangesNothing() [TestMethod] public async Task RecordFailure_UnknownRecurringPayment_ReturnsFalse() { - Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "in_2", "declined")); + Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "sub_1", "in_2", "declined")); } [TestMethod] @@ -281,7 +282,7 @@ public async Task RecordEnded_Active_CancelsByTheProvider() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); - Assert.IsTrue(await _service.RecordEnded(rp.Id)); + Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); var saved = await _service.GetRecurringPaymentById(rp.Id); Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); @@ -293,19 +294,120 @@ 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.IsFalse(await _service.RecordEnded(completed.Id, "sub_1")); 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.IsTrue(await _service.RecordEnded(active.Id, "sub_1")); + Assert.IsFalse(await _service.RecordEnded(active.Id, "sub_1")); } [TestMethod] public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() { - Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New)); + Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New, "sub_1")); + } + + [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.IsNull(await _service.ClaimCycle(rp.Id, "sub_2", "in_9", 10, DateTime.UtcNow, null)); + + 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.IsNotNull(await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)); + } + + [TestMethod] + public async Task RecordFailure_OtherProviderReference_ChangesNothing() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_2", "in_9", "declined")); + + 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.IsFalse(await _service.RecordEnded(rp.Id, "sub_2")); + + 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 saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Pending, saved.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 RecordProviderReference_AlreadyRecorded_KeepsIt() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); + + var saved = await _service.RecordProviderReference(rp.Id, "sub_2"); + + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual("sub_1", (await _service.GetRecurringPaymentById(rp.Id)).ProviderReference); + } + + [TestMethod] + public async Task RecordProviderReference_Cancelled_RecordsItAndKeepsTheStatus() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 0); + + var saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + } + + [TestMethod] + public async Task RecordProviderReference_UnknownRecurringPayment_ReturnsNull() + { + Assert.IsNull(await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")); + } + + [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) @@ -486,7 +588,7 @@ public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() 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(); }); @@ -557,8 +659,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.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); + Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_1")); var published = Published(); Assert.AreEqual(1, published.Count); @@ -570,8 +672,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); From c3777cb0e8d1e7a3b0ec4e06464c87165045d31f Mon Sep 17 00:00:00 2001 From: support Date: Sun, 22 Nov 2026 08:20:49 +0100 Subject: [PATCH 2/2] Recurring payments: say why a gateway report was refused, and stop another subscription The recurring payment service now returns the outcome of every gateway report (Recorded, NotFound, Duplicate, OtherReference, Ended) with the payment it read under the lock, so the provider commands no longer read it again to guess why nothing was recorded. - The first reported reference is recorded whichever report brings it: a failure or an end reported before the reference was known now records it, as a paid cycle already did. - The reference command stops the gateway of an ended payment only when it records the reference, so a resent checkout event no longer asks the gateway to cancel again. - A failure on an ended payment records the missing reference under the lock before the gateway is asked to stop, instead of patching it in memory. - A paid cycle, a failure or a reference reported on another subscription asks the provider to stop that subscription and leaves one note per report on the initial order; another subscription that ended is only logged. - RecordRecurringPaymentFailureCommand returns true when the failure was recorded, also while the payment is already past due. --- ...cordRecurringPaymentCycleCommandHandler.cs | 16 +- ...cordRecurringPaymentEndedCommandHandler.cs | 16 +- ...rdRecurringPaymentFailureCommandHandler.cs | 40 ++-- ...RecurringPaymentReferenceCommandHandler.cs | 30 +-- .../Orders/RecurringPaymentGateway.cs | 74 +++++-- .../Orders/RecurringPaymentService.cs | 99 +++++++--- .../RecordRecurringPaymentCycleCommand.cs | 3 +- .../RecordRecurringPaymentFailureCommand.cs | 4 +- .../Orders/IRecurringPaymentService.cs | 32 +-- .../Utilities/Checkout/RecurringCycleClaim.cs | 11 +- .../Checkout/RecurringReportOutcome.cs | 32 +++ .../Checkout/RecurringReportResult.cs | 16 ++ ...ordRecurringPaymentCommandHandlersTests.cs | 185 +++++++++++++----- .../Orders/RecurringPaymentServiceTests.cs | 126 ++++++++---- 14 files changed, 460 insertions(+), 224 deletions(-) create mode 100644 src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportOutcome.cs create mode 100644 src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs 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 ba55bdf80..26939f488 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -1,8 +1,8 @@ using System.Runtime.ExceptionServices; 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.Domain.Orders; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -26,16 +26,18 @@ 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) { - // a resend is the usual reason; a report on another subscription is the one staff must hear about - var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); - if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); + 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 cancellationToken = CancellationToken.None; 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 8552aeab8..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,6 +1,6 @@ using Grand.Business.Core.Commands.Checkout.Orders; -using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -8,7 +8,6 @@ namespace Grand.Business.Checkout.Commands.Handlers.Orders; public class RecordRecurringPaymentEndedCommandHandler( IRecurringPaymentService recurringPaymentService, - IOrderService orderService, ILogger logger) : IRequestHandler { @@ -16,14 +15,13 @@ public async Task Handle(RecordRecurringPaymentEndedCommand request, Cance { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); - if (await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference)) - return true; + var report = await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference); - var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId); - if (recurringPayment != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - 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 false; + 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 1c440a76a..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,8 +1,7 @@ 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.Domain.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Mediator; using Microsoft.Extensions.Logging; @@ -20,28 +19,25 @@ public async Task Handle(RecordRecurringPaymentFailureCommand request, Can ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); - if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.ProviderReference, - 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 != null && recurringPayment.HasOtherProviderReference(request.ProviderReference)) + switch (report.Outcome) { - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); - return false; + 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; } - - 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/RecordRecurringPaymentReferenceCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs index 5be63bb56..d861d1d29 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs @@ -2,6 +2,7 @@ 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; @@ -19,22 +20,25 @@ public async Task Handle(RecordRecurringPaymentReferenceCommand request, C ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); ArgumentException.ThrowIfNullOrEmpty(request.ProviderReference); - var recurringPayment = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, + var report = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, request.ProviderReference); - if (recurringPayment == null) - return false; - if (recurringPayment.HasOtherProviderReference(request.ProviderReference)) + switch (report.Outcome) { - await RecurringPaymentGateway.NoteOtherReference(orderService, logger, recurringPayment, - request.ProviderReference); - return false; + 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; } - - // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped now - if (recurringPayment.Status.HasEnded()) - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); - - return true; } } 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 f28215a63..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,26 +6,15 @@ 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; - 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]; - } + 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()) @@ -33,20 +22,63 @@ 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 Task NoteOtherReference(IOrderService orderService, ILogger logger, - RecurringPayment recurringPayment, string providerReference) + /// + /// 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 on {ReportedReference}", - recurringPayment.Id, recurringPayment.ProviderReference, providerReference); - return AddNote(orderService, logger, recurringPayment, - $"The payment gateway reported on {providerReference}, but the recurring payment runs on {recurringPayment.ProviderReference}, so nothing was recorded: check the payment gateway for a second subscription charging the customer"); + 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); + 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 {ProviderReference}", + recurringPayment.Id, recurringPayment.ProviderReference); + return [e.Message]; + } } 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 29ec1ee16..1b39dcce7 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -41,9 +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) || - recurringPayment.HasOtherProviderReference(providerReference)) - 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 { @@ -56,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; @@ -67,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; @@ -79,11 +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 providerReference, - string cycleReference, string reason) + public virtual async Task RecordFailure(string recurringPaymentId, + string providerReference, string cycleReference, string reason) { ArgumentException.ThrowIfNullOrEmpty(cycleReference); @@ -93,13 +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) || - recurringPayment.HasOtherProviderReference(providerReference)) - 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; @@ -114,10 +128,10 @@ 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, string providerReference) + public virtual async Task RecordEnded(string recurringPaymentId, string providerReference) { RecurringPayment recurringPayment; @@ -125,11 +139,13 @@ public virtual async Task RecordEnded(string recurringPaymentId, string pr { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); //another subscription ending says nothing about the one this payment runs on - if (recurringPayment == null || - recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || - recurringPayment.HasOtherProviderReference(providerReference)) - return false; + 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; @@ -141,10 +157,10 @@ recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentS await mediator.EntityUpdated(recurringPayment); await mediator.Publish(new RecurringPaymentCancelledEvent(recurringPayment)); - return true; + return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; } - public virtual async Task RecordProviderReference(string recurringPaymentId, + public virtual async Task RecordProviderReference(string recurringPaymentId, string providerReference) { ArgumentException.ThrowIfNullOrEmpty(providerReference); @@ -154,8 +170,11 @@ public virtual async Task RecordProviderReference(string recur await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); - if (recurringPayment == null || !string.IsNullOrEmpty(recurringPayment.ProviderReference)) - return recurringPayment; + 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); @@ -164,7 +183,28 @@ public virtual async Task RecordProviderReference(string recur //event notification await mediator.EntityUpdated(recurringPayment); - return 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; } public virtual async Task Cancel(string recurringPaymentId, string cancelledBy, @@ -186,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)) { @@ -209,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/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/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index 42b85ab34..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,33 +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, the cycle reference was already recorded or - /// the provider reference is not the one the recurring payment runs on + /// 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, a - /// cycle that was paid already, or another provider reference than the one the recurring payment runs on + /// 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 providerReference, 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, one that is Cancelled or Completed, or another provider reference than - /// the one the recurring payment runs on + /// 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, string providerReference); + 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. Returns the - /// recurring payment as saved, or null when it is unknown + /// 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); + 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 7719dfee1..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,7 +50,8 @@ private static RecordRecurringPaymentFailureCommand FailureCommand() [TestMethod] public async Task FailureCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordFailure("rp1", "sub_1", "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); @@ -56,13 +63,12 @@ public async Task FailureCommand_PassesTheReportToTheService() [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,7 +126,8 @@ await Assert.ThrowsExactlyAsync(() => [TestMethod] public async Task EndedCommand_PassesTheReportToTheService() { - _service.Setup(x => x.RecordEnded("rp1", "sub_1")).ReturnsAsync(true); + _service.Setup(x => x.RecordEnded("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.Recorded, new RecurringPayment { Id = "rp1" })); var result = await EndedHandler().Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1", ProviderReference = "sub_1" @@ -138,43 +148,58 @@ await Assert.ThrowsExactlyAsync(() => private RecordRecurringPaymentEndedCommandHandler EndedHandler() { - return new RecordRecurringPaymentEndedCommandHandler(_service.Object, _orderService.Object, + return new RecordRecurringPaymentEndedCommandHandler(_service.Object, new Mock>().Object); } - private void SetupOtherReference() + // the recurring payment runs on sub_9, and a second subscription sub_1 reports on it + private static RecurringPayment RunsOnAnotherReference() { - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" - }); + return new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", StoreId = "s1", PaymentMethodSystemName = "Payments.Test", + Status = RecurringPaymentStatus.Active, ProviderReference = "sub_9" + }; } - private void VerifyOtherReferenceNoted() + private void SetupStop() { - _orderService.Verify(x => x.InsertOrderNote(It.Is(n => n.OrderId == "o1" && - n.Note.StartsWith("The payment gateway reported on sub_1, but the recurring payment runs on sub_9"))), + _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_NotesItOnTheInitialOrder() + public async Task EndedCommand_OtherProviderReference_WritesNoNote() { - SetupOtherReference(); + // 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); - VerifyOtherReferenceNoted(); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); } [TestMethod] public async Task EndedCommand_AlreadyEnded_WritesNoNote() { - _service.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_1" - }); + _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" @@ -184,28 +209,57 @@ public async Task EndedCommand_AlreadyEnded_WritesNoNote() } [TestMethod] - public async Task FailureCommand_OtherProviderReference_NotesItAndDoesNotStopTheRecordedOne() + public async Task FailureCommand_OtherProviderReference_StopsTheOtherOneAndNotesIt() { - SetupOtherReference(); + _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)); - VerifyOtherReferenceNoted(); - _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + 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_NotesItOnTheInitialOrder() + public async Task CycleCommand_OtherProviderReference_StopsTheOtherOneAndNotesARefund() { - SetupOtherReference(); + _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)); - VerifyOtherReferenceNoted(); + 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, @@ -220,9 +274,9 @@ private static RecordRecurringPaymentReferenceCommand ReferenceCommand() [TestMethod] public async Task ReferenceCommand_Pending_RecordsItWithoutTheGateway() { - _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", Status = RecurringPaymentStatus.Pending, ProviderReference = "sub_1" - }); + _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)); @@ -235,9 +289,9 @@ public async Task ReferenceCommand_Pending_RecordsItWithoutTheGateway() public async Task ReferenceCommand_CancelledBeforeTheReferenceWasKnown_StopsTheGateway( RecurringPaymentStatus status) { - _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")).ReturnsAsync(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = status, ProviderReference = "sub_1" - }); + _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()); @@ -248,21 +302,41 @@ public async Task ReferenceCommand_CancelledBeforeTheReferenceWasKnown_StopsTheG } [TestMethod] - public async Task ReferenceCommand_OtherReferenceRecorded_NotesItAndStopsNothing() + [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(new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", Status = RecurringPaymentStatus.Cancelled, ProviderReference = "sub_9" - }); + _service.Setup(x => x.RecordProviderReference("rp1", "sub_1")) + .ReturnsAsync(Report(RecurringReportOutcome.OtherReference, RunsOnAnotherReference())); + SetupStop(); Assert.IsFalse(await ReferenceHandler().Handle(ReferenceCommand(), CancellationToken.None)); - VerifyOtherReferenceNoted(); - _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + 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)); } @@ -292,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 }, @@ -305,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 7aa9d3042..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); } @@ -223,23 +223,23 @@ await Assert.ThrowsExactlyAsync(() => } [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, "sub_1", "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, "sub_1", "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); @@ -250,7 +250,7 @@ public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() { var rp = await Insert(RecurringPaymentStatus.Active, 2); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_1", "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); @@ -258,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, "sub_1", "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, "sub_1", "in_2", "declined")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordFailure(UniqueIdentifier.New, "sub_1", "in_2", "declined")).Outcome); } [TestMethod] @@ -282,10 +286,11 @@ public async Task RecordEnded_Active_CancelsByTheProvider() rp.PaymentMethodSystemName = "Payments.Test"; await _repository.UpdateAsync(rp); - Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); + 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); } @@ -294,19 +299,19 @@ 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, "sub_1")); + 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, "sub_1")); - Assert.IsFalse(await _service.RecordEnded(active.Id, "sub_1")); + 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_ReturnsFalse() + public async Task RecordEnded_UnknownRecurringPayment_IsNotFound() { - Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordEnded(UniqueIdentifier.New, "sub_1")).Outcome); } [TestMethod] @@ -315,7 +320,7 @@ 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.IsNull(await _service.ClaimCycle(rp.Id, "sub_2", "in_9", 10, DateTime.UtcNow, null)); + 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); @@ -327,7 +332,7 @@ public async Task ClaimCycle_ProviderReferenceNotGiven_IsNotChecked() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsNotNull(await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)); + Assert.AreEqual(RecurringReportOutcome.Recorded, (await _service.ClaimCycle(rp.Id, null, "in_2", 10, DateTime.UtcNow, null)).Outcome); } [TestMethod] @@ -335,7 +340,7 @@ public async Task RecordFailure_OtherProviderReference_ChangesNothing() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsFalse(await _service.RecordFailure(rp.Id, "sub_2", "in_9", "declined")); + 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); @@ -347,7 +352,7 @@ public async Task RecordEnded_OtherProviderReference_KeepsThePaymentRunning() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_2")); + 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()), @@ -359,10 +364,11 @@ public async Task RecordProviderReference_Pending_RecordsItSoACancelAsksTheGatew { var rp = await Insert(RecurringPaymentStatus.Pending, 0); - var saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + var report = await _service.RecordProviderReference(rp.Id, "sub_1"); - Assert.AreEqual("sub_1", saved.ProviderReference); - Assert.AreEqual(RecurringPaymentStatus.Pending, saved.Status); + 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; @@ -375,31 +381,65 @@ await _service.Cancel(rp.Id, "customer", _ => } [TestMethod] - public async Task RecordProviderReference_AlreadyRecorded_KeepsIt() + public async Task RecordProviderReference_AnotherOneRecorded_KeepsIt() { var rp = await Insert(RecurringPaymentStatus.Active, 1, providerReference: "sub_1"); - var saved = await _service.RecordProviderReference(rp.Id, "sub_2"); + var report = await _service.RecordProviderReference(rp.Id, "sub_2"); - Assert.AreEqual("sub_1", saved.ProviderReference); + 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 saved = await _service.RecordProviderReference(rp.Id, "sub_1"); + var report = await _service.RecordProviderReference(rp.Id, "sub_1"); - Assert.AreEqual("sub_1", saved.ProviderReference); - Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + 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_ReturnsNull() + public async Task RecordProviderReference_UnknownRecurringPayment_IsNotFound() { - Assert.IsNull(await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")); + Assert.AreEqual(RecurringReportOutcome.NotFound, (await _service.RecordProviderReference(UniqueIdentifier.New, "sub_1")).Outcome); } [TestMethod] @@ -569,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); @@ -584,7 +624,7 @@ 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 _ => { @@ -594,7 +634,7 @@ public async Task Cancel_EndedAtTheGatewayDuringTheCall_PublishesOnce() }); 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); @@ -659,8 +699,8 @@ public async Task RecordEnded_PublishesCancelledOnlyOnTheTransition() { var rp = await Insert(RecurringPaymentStatus.Active, 1); - Assert.IsTrue(await _service.RecordEnded(rp.Id, "sub_1")); - Assert.IsFalse(await _service.RecordEnded(rp.Id, "sub_1")); + 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);