From eddd793ab75525a5b9ec66ec231f671f159203c9 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 19:57:41 +0100 Subject: [PATCH 01/10] Claim a paid recurring payment cycle once, even when the gateway resends it --- .../Orders/RecurringPaymentService.cs | 61 ++++++++- .../Orders/IRecurringPaymentService.cs | 8 ++ .../Utilities/Checkout/RecurringCycleClaim.cs | 24 ++++ .../Orders/RecurringPaymentServiceTests.cs | 127 +++++++++++++++++- 4 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 024feabce..5c98762fc 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -1,6 +1,8 @@ using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Data; +using Grand.Domain; using Grand.Domain.Orders; using Grand.Infrastructure.Extensions; using Grand.Mediator; @@ -10,7 +12,8 @@ namespace Grand.Business.Checkout.Services.Orders; public class RecurringPaymentService( IRepository repository, IProductService productService, - IMediator mediator) + IMediator mediator, + IResourceLock resourceLock) : IRecurringPaymentService { public virtual async Task InsertRecurringPayment(RecurringPayment recurringPayment) @@ -33,6 +36,62 @@ public virtual async Task UpdateRecurringPayment(RecurringPayment recurringPayme await mediator.EntityUpdated(recurringPayment); } + public virtual async Task ClaimCycle(string recurringPaymentId, string providerReference, + string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc) + { + RecurringPayment recurringPayment; + RecurringPaymentCycle cycle; + var completed = false; + + //the reference is checked and the cycle recorded while no other delivery can do the same + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + return null; + + recurringPayment.CyclesPaid++; + cycle = new RecurringPaymentCycle { + CycleNumber = recurringPayment.CyclesPaid, + //the first cycle is the order the customer placed + OrderId = recurringPayment.CyclesPaid == 1 ? recurringPayment.InitialOrderId : UniqueIdentifier.New, + ProviderReference = cycleReference, + Amount = amount, + PaidOnUtc = paidOnUtc + }; + recurringPayment.Cycles.Add(cycle); + + if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) + recurringPayment.ProviderReference = providerReference; + if (nextPaymentDateUtc.HasValue) + recurringPayment.NextPaymentDateUtc = nextPaymentDateUtc; + + //LastError stays as history + if (recurringPayment.Status is RecurringPaymentStatus.Pending or RecurringPaymentStatus.PastDue) + recurringPayment.Status = RecurringPaymentStatus.Active; + + //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 = RecurringPaymentStatus.Completed; + completed = true; + } + + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return new RecurringCycleClaim { RecurringPayment = recurringPayment, Cycle = cycle, Completed = completed }; + } + + private static string LockKey(string recurringPaymentId) + { + return $"{nameof(RecurringPayment)}:{recurringPaymentId}"; + } + public virtual Task GetRecurringPaymentById(string id) { return repository.GetByIdAsync(id); 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 96c36ca58..ddb440447 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -1,3 +1,4 @@ +using Grand.Business.Core.Utilities.Checkout; using Grand.Domain.Orders; namespace Grand.Business.Core.Interfaces.Checkout.Orders; @@ -17,6 +18,13 @@ public interface IRecurringPaymentService /// Task UpdateRecurringPayment(RecurringPayment recurringPayment); + /// + /// Records a cycle the provider reports as paid, once: under a lock, so a gateway resending the event claims + /// nothing. Returns null when the recurring payment is unknown or the cycle reference was already recorded + /// + Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, + double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc); + /// /// Gets a recurring payment /// diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs new file mode 100644 index 000000000..92908ee58 --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs @@ -0,0 +1,24 @@ +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// A paid cycle recorded on a recurring payment +/// +public class RecurringCycleClaim +{ + /// + /// The recurring payment as saved + /// + public RecurringPayment RecurringPayment { get; init; } + + /// + /// The cycle that was recorded + /// + public RecurringPaymentCycle Cycle { get; init; } + + /// + /// Gets a value indicating whether this cycle completed the recurring payment + /// + public bool Completed { get; init; } +} 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 9c9d6456b..aa1b7ce92 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -3,6 +3,7 @@ using Grand.Data; using Grand.Data.Tests.MongoDb; using Grand.Domain.Catalog; +using Grand.Domain; using Grand.Domain.Orders; using Grand.Mediator; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -15,6 +16,8 @@ public class RecurringPaymentServiceTests { private Mock _productService; private IRepository _repository; + private IMediator _mediator; + private IResourceLock _resourceLock; private RecurringPaymentService _service; [TestInitialize] @@ -25,7 +28,9 @@ public void Init() _productService.Setup(x => x.GetProductById("standard", false)).ReturnsAsync(new Product { Id = "standard" }); _productService.Setup(x => x.GetProductById("recurring", false)) .ReturnsAsync(new Product { Id = "recurring", IsRecurring = true }); - _service = new RecurringPaymentService(_repository, _productService.Object, new Mock().Object); + _mediator = new Mock().Object; + _resourceLock = new MongoResourceLockTest(); + _service = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); } [TestMethod] @@ -82,4 +87,124 @@ public async Task InsertRecurringPayment_Null_Throws() { await Assert.ThrowsExactlyAsync(() => _service.InsertRecurringPayment(null)); } + + private async Task Insert(RecurringPaymentStatus status, int cyclesPaid, int totalCycles = 12, + string lastError = null) + { + var rp = new RecurringPayment { + InitialOrderId = "o1", Status = status, CyclesPaid = cyclesPaid, TotalCycles = totalCycles, + LastError = lastError + }; + for (var i = 1; i <= cyclesPaid; i++) + rp.Cycles.Add(new RecurringPaymentCycle { + CycleNumber = i, OrderId = $"o{i}", ProviderReference = $"in_{i}" + }); + await _service.InsertRecurringPayment(rp); + return rp; + } + + [TestMethod] + public async Task ClaimCycle_FirstCycle_IsTheInitialOrderAndActivates() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + var paid = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc); + var next = paid.AddMonths(1); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, paid, next); + + Assert.IsNotNull(claim); + Assert.AreEqual(1, claim.Cycle.CycleNumber); + Assert.AreEqual("o1", claim.Cycle.OrderId); + Assert.AreEqual("in_1", claim.Cycle.ProviderReference); + Assert.AreEqual(10, claim.Cycle.Amount); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.AreEqual(1, saved.CyclesPaid); + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(next, saved.NextPaymentDateUtc); + } + + [TestMethod] + public async Task ClaimCycle_LaterCycle_GetsANewOrderIdAndLeavesPastDue() + { + var rp = await Insert(RecurringPaymentStatus.PastDue, 1, lastError: "card declined"); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.AreEqual(2, claim.Cycle.CycleNumber); + Assert.IsFalse(string.IsNullOrEmpty(claim.Cycle.OrderId)); + Assert.AreNotEqual("o1", claim.Cycle.OrderId); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.AreEqual("card declined", saved.LastError); + } + + [TestMethod] + public async Task ClaimCycle_SameCycleReferenceAgain_ReturnsNull() + { + 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)); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(1, saved.Cycles.Count); + Assert.AreEqual(1, saved.CyclesPaid); + } + + [TestMethod] + public async Task ClaimCycle_ConcurrentDeliveries_ClaimOnce() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); + + var claims = await Task.WhenAll( + _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)); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(1, saved.Cycles.Count(c => c.ProviderReference == "in_2")); + } + + [TestMethod] + public async Task ClaimCycle_ReachingTotalCycles_Completes() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, 2); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsTrue(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Completed, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_TotalCyclesZero_NeverCompletes() + { + var rp = await Insert(RecurringPaymentStatus.Active, 11, 0); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_12", 10, DateTime.UtcNow, null); + + Assert.IsFalse(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Active, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_AfterCancelled_RecordsTheCycleAndKeepsTheStatus() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsNotNull(claim); + Assert.AreEqual(2, claim.Cycle.CycleNumber); + Assert.IsFalse(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_UnknownRecurringPayment_ReturnsNull() + { + Assert.IsNull(await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + } } From 86e1de6390b59ae48833c901dec3725414cdd156 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:02:52 +0100 Subject: [PATCH 02/10] Record a failed recurring payment cycle and a recurring payment ended at the gateway --- ...cordRecurringPaymentEndedCommandHandler.cs | 16 ++++ ...rdRecurringPaymentFailureCommandHandler.cs | 17 ++++ .../Orders/RecurringPaymentService.cs | 53 ++++++++++++ .../RecordRecurringPaymentEndedCommand.cs | 12 +++ .../RecordRecurringPaymentFailureCommand.cs | 19 +++++ .../Orders/IRecurringPaymentService.cs | 13 +++ ...ordRecurringPaymentCommandHandlersTests.cs | 64 +++++++++++++++ .../Orders/RecurringPaymentServiceTests.cs | 81 +++++++++++++++++++ 8 files changed, 275 insertions(+) create mode 100644 src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs create mode 100644 src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs create mode 100644 src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs create mode 100644 src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs create mode 100644 src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs new file mode 100644 index 000000000..14247abe5 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs @@ -0,0 +1,16 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Mediator; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentEndedCommandHandler(IRecurringPaymentService recurringPaymentService) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentEndedCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + + return await recurringPaymentService.RecordEnded(request.RecurringPaymentId); + } +} diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs new file mode 100644 index 000000000..78dc06ee7 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -0,0 +1,17 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Mediator; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentService recurringPaymentService) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + + return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, + request.Reason); + } +} diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 5c98762fc..358940094 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -87,6 +87,59 @@ 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) + { + RecurringPayment recurringPayment; + bool enteredPastDue; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + //a failure that arrives after the cycle was paid is a late, out of order event + if (recurringPayment == null || + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || + recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + return false; + + recurringPayment.LastError = reason; + recurringPayment.LastErrorDateUtc = DateTime.UtcNow; + + enteredPastDue = recurringPayment.Status != RecurringPaymentStatus.PastDue; + recurringPayment.Status = RecurringPaymentStatus.PastDue; + + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return enteredPastDue; + } + + public virtual async Task RecordEnded(string recurringPaymentId) + { + RecurringPayment recurringPayment; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null || + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + return false; + + recurringPayment.Status = RecurringPaymentStatus.Cancelled; + recurringPayment.CancelledOnUtc = DateTime.UtcNow; + recurringPayment.CancelledBy = recurringPayment.PaymentMethodSystemName; + + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return true; + } + private static string LockKey(string recurringPaymentId) { return $"{nameof(RecurringPayment)}:{recurringPaymentId}"; diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs new file mode 100644 index 000000000..453261855 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs @@ -0,0 +1,12 @@ +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// A payment provider reports that a recurring payment ended at the gateway. The result is true when it was +/// cancelled +/// +public class RecordRecurringPaymentEndedCommand : IRequest +{ + public string RecurringPaymentId { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs new file mode 100644 index 000000000..60df50ea4 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -0,0 +1,19 @@ +using Grand.Mediator; + +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 +/// +public class RecordRecurringPaymentFailureCommand : IRequest +{ + public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of the cycle that failed + /// + public string CycleReference { get; set; } + + public string Reason { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index ddb440447..e0e0ba082 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -25,6 +25,19 @@ public interface IRecurringPaymentService 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 + /// + Task RecordFailure(string recurringPaymentId, 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 + /// + Task RecordEnded(string recurringPaymentId); + /// /// Gets a recurring payment /// 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 new file mode 100644 index 000000000..2bd9762fc --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs @@ -0,0 +1,64 @@ +using Grand.Business.Checkout.Commands.Handlers.Orders; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders; + +[TestClass] +public class RecordRecurringPaymentCommandHandlersTests +{ + private Mock _service; + + [TestInitialize] + public void Init() + { + _service = new Mock(); + } + + [TestMethod] + public async Task FailureCommand_PassesTheReportToTheService() + { + _service.Setup(x => x.RecordFailure("rp1", "in_2", "declined")).ReturnsAsync(true); + var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + + var result = await handler.Handle(new RecordRecurringPaymentFailureCommand { + RecurringPaymentId = "rp1", CycleReference = "in_2", Reason = "declined" + }, CancellationToken.None); + + Assert.IsTrue(result); + _service.Verify(x => x.RecordFailure("rp1", "in_2", "declined"), Times.Once); + } + + [TestMethod] + public async Task FailureCommand_WithoutRecurringPaymentId_Throws() + { + var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + + await Assert.ThrowsExactlyAsync(() => + handler.Handle(new RecordRecurringPaymentFailureCommand { RecurringPaymentId = "" }, CancellationToken.None)); + } + + [TestMethod] + public async Task EndedCommand_PassesTheReportToTheService() + { + _service.Setup(x => x.RecordEnded("rp1")).ReturnsAsync(true); + var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + + var result = await handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1" }, + CancellationToken.None); + + Assert.IsTrue(result); + _service.Verify(x => x.RecordEnded("rp1"), Times.Once); + } + + [TestMethod] + public async Task EndedCommand_WithoutRecurringPaymentId_Throws() + { + var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + + await Assert.ThrowsExactlyAsync(() => + handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "" }, 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 aa1b7ce92..dee261f6e 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -207,4 +207,85 @@ public async Task ClaimCycle_UnknownRecurringPayment_ReturnsNull() { Assert.IsNull(await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)); } + + [TestMethod] + public async Task RecordFailure_Active_EntersPastDueOnlyOnce() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + Assert.IsTrue(await _service.RecordFailure(rp.Id, "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")); + saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); + Assert.AreEqual("expired", saved.LastError); + } + + [TestMethod] + public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() + { + var rp = await Insert(RecurringPaymentStatus.Active, 2); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "late")); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.IsNull(saved.LastError); + } + + [TestMethod] + public async Task RecordFailure_Cancelled_ChangesNothing() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "declined")); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.IsNull(saved.LastError); + } + + [TestMethod] + public async Task RecordFailure_UnknownRecurringPayment_ReturnsFalse() + { + Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "in_2", "declined")); + } + + [TestMethod] + public async Task RecordEnded_Active_CancelsByTheProvider() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + rp.PaymentMethodSystemName = "Payments.Test"; + await _repository.UpdateAsync(rp); + + Assert.IsTrue(await _service.RecordEnded(rp.Id)); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("Payments.Test", saved.CancelledBy); + Assert.IsNotNull(saved.CancelledOnUtc); + } + + [TestMethod] + public async Task RecordEnded_CompletedOrCancelled_ChangesNothing() + { + var completed = await Insert(RecurringPaymentStatus.Completed, 12); + Assert.IsFalse(await _service.RecordEnded(completed.Id)); + 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)); + } + + [TestMethod] + public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() + { + Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New)); + } } From 94eb0a3b82de97c47daeaab03789bd7f22fa32a8 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:08:02 +0100 Subject: [PATCH 03/10] Copy the initial order for a paid recurring payment cycle --- .../Extensions/RecurringCycleOrder.cs | 200 +++++++++++ .../Extensions/RecurringCycleOrderTests.cs | 316 ++++++++++++++++++ 2 files changed, 516 insertions(+) create mode 100644 src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs create mode 100644 src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs diff --git a/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs new file mode 100644 index 000000000..f63c81a6a --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs @@ -0,0 +1,200 @@ +using Grand.Domain.Common; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Domain.Shipping; + +namespace Grand.Business.Checkout.Extensions; + +public static class RecurringCycleOrder +{ + /// + /// The order that pays one later cycle of a recurring payment: the order the customer placed, at its prices, + /// as a new unpaid order. Everything that describes what was bought and what it costs is copied; identity, + /// dates, statuses, payment and shipping progress and the loyalty points spent are those of a new order. + /// Loyalty points spent on the initial order are not spent again, so their amount is added back to the total. + /// + public static Order Copy(Order initialOrder, string orderId, int cycleNumber, string orderCode, + DateTime createdOnUtc) + { + var order = new Order { + Id = orderId, + OrderGuid = Guid.NewGuid(), + // InsertOrder assigns the number + OrderNumber = 0, + Code = orderCode, + InitialOrderId = initialOrder.Id, + RecurringCycleNumber = cycleNumber, + CreatedOnUtc = createdOnUtc, + OrderStatusId = (int)OrderStatusSystem.Pending, + PaymentStatusId = PaymentStatus.Pending, + PaidAmount = 0, + PaidDateUtc = null, + PaymentDueDateUtc = null, + PaymentReminderSentOnUtc = null, + PaymentOverdueNoticeSentOnUtc = null, + RefundedAmount = 0, + RedeemedLoyaltyPoints = 0, + RedeemedLoyaltyPointsAmount = 0, + LoyaltyPointsWereAdded = false, + CalcLoyaltyPoints = 0, + OrderTotal = Math.Round(initialOrder.OrderTotal + initialOrder.RedeemedLoyaltyPointsAmount, 6), + Deleted = false, + Imported = false, + + PurchaseOrderNumber = initialOrder.PurchaseOrderNumber, + StoreId = initialOrder.StoreId, + CustomerId = initialOrder.CustomerId, + OwnerId = initialOrder.OwnerId, + SeId = initialOrder.SeId, + PickUpInStore = initialOrder.PickUpInStore, + PaymentMethodSystemName = initialOrder.PaymentMethodSystemName, + PaymentOptionAttribute = initialOrder.PaymentOptionAttribute, + CustomerCurrencyCode = initialOrder.CustomerCurrencyCode, + PrimaryCurrencyCode = initialOrder.PrimaryCurrencyCode, + CurrencyRate = initialOrder.CurrencyRate, + Rate = initialOrder.Rate, + CustomerTaxDisplayTypeId = initialOrder.CustomerTaxDisplayTypeId, + VatNumber = initialOrder.VatNumber, + VatNumberStatusId = initialOrder.VatNumberStatusId, + CompanyName = initialOrder.CompanyName, + CustomerEmail = initialOrder.CustomerEmail, + FirstName = initialOrder.FirstName, + LastName = initialOrder.LastName, + OrderSubtotalInclTax = initialOrder.OrderSubtotalInclTax, + OrderSubtotalExclTax = initialOrder.OrderSubtotalExclTax, + OrderSubTotalDiscountInclTax = initialOrder.OrderSubTotalDiscountInclTax, + OrderSubTotalDiscountExclTax = initialOrder.OrderSubTotalDiscountExclTax, + OrderShippingInclTax = initialOrder.OrderShippingInclTax, + OrderShippingExclTax = initialOrder.OrderShippingExclTax, + PaymentMethodAdditionalFeeInclTax = initialOrder.PaymentMethodAdditionalFeeInclTax, + PaymentMethodAdditionalFeeExclTax = initialOrder.PaymentMethodAdditionalFeeExclTax, + OrderTax = initialOrder.OrderTax, + OrderDiscount = initialOrder.OrderDiscount, + CheckoutAttributeDescription = initialOrder.CheckoutAttributeDescription, + CheckoutAttributes = CopyAttributes(initialOrder.CheckoutAttributes), + CustomerLanguageId = initialOrder.CustomerLanguageId, + AffiliateId = initialOrder.AffiliateId, + CustomerIp = initialOrder.CustomerIp, + ShippingMethod = initialOrder.ShippingMethod, + ShippingRateProviderSystemName = initialOrder.ShippingRateProviderSystemName, + ShippingOptionAttributeDescription = initialOrder.ShippingOptionAttributeDescription, + ShippingOptionAttribute = initialOrder.ShippingOptionAttribute, + IsRecurring = initialOrder.IsRecurring, + RecurringCycleLength = initialOrder.RecurringCycleLength, + RecurringCyclePeriodId = initialOrder.RecurringCyclePeriodId, + RecurringTotalCycles = initialOrder.RecurringTotalCycles, + RecurringUseCycles = initialOrder.RecurringUseCycles, + BillingAddress = CopyAddress(initialOrder.BillingAddress), + ShippingAddress = CopyAddress(initialOrder.ShippingAddress), + PickupPoint = CopyPickupPoint(initialOrder.PickupPoint) + }; + + // the setters of the three collections are protected, so they are filled in place + foreach (var tax in initialOrder.OrderTaxes) + order.OrderTaxes.Add(new OrderTax { Percent = tax.Percent, Amount = tax.Amount }); + + foreach (var item in initialOrder.OrderItems) + order.OrderItems.Add(CopyItem(item, createdOnUtc)); + + order.ShippingStatusId = order.OrderItems.Any(x => x.IsShipEnabled) + ? ShippingStatus.Pending + : ShippingStatus.ShippingNotRequired; + + return order; + } + + private static OrderItem CopyItem(OrderItem item, DateTime createdOnUtc) + { + return new OrderItem { + OrderItemGuid = Guid.NewGuid(), + ProductId = item.ProductId, + Sku = item.Sku, + VendorId = item.VendorId, + WarehouseId = item.WarehouseId, + SeId = item.SeId, + Quantity = item.Quantity, + IsShipEnabled = item.IsShipEnabled, + // nothing of the new order is open, shipped, cancelled or returned yet + OpenQty = item.Quantity, + ShipQty = 0, + CancelQty = 0, + CancelAmount = 0, + ReturnQty = 0, + Status = OrderItemStatus.Open, + TaxRate = item.TaxRate, + UnitPriceWithoutDiscInclTax = item.UnitPriceWithoutDiscInclTax, + UnitPriceWithoutDiscExclTax = item.UnitPriceWithoutDiscExclTax, + UnitPriceInclTax = item.UnitPriceInclTax, + UnitPriceExclTax = item.UnitPriceExclTax, + PriceInclTax = item.PriceInclTax, + PriceExclTax = item.PriceExclTax, + DiscountAmountInclTax = item.DiscountAmountInclTax, + DiscountAmountExclTax = item.DiscountAmountExclTax, + OriginalProductCost = item.OriginalProductCost, + AttributeDescription = item.AttributeDescription, + Attributes = CopyAttributes(item.Attributes), + DownloadCount = 0, + IsDownloadActivated = false, + LicenseDownloadId = "", + ItemWeight = item.ItemWeight, + RentalStartDateUtc = item.RentalStartDateUtc, + RentalEndDateUtc = item.RentalEndDateUtc, + CreatedOnUtc = createdOnUtc, + Commission = item.Commission, + cId = item.cId + }; + } + + private static IList CopyAttributes(IList attributes) + { + return attributes?.Select(x => new CustomAttribute { Key = x.Key, Value = x.Value }).ToList(); + } + + private static Address CopyAddress(Address address) + { + if (address == null) return null; + return new Address { + Id = address.Id, + Name = address.Name, + FirstName = address.FirstName, + LastName = address.LastName, + Email = address.Email, + Company = address.Company, + VatNumber = address.VatNumber, + CountryId = address.CountryId, + StateProvinceId = address.StateProvinceId, + City = address.City, + Address1 = address.Address1, + Address2 = address.Address2, + ZipPostalCode = address.ZipPostalCode, + PhoneNumber = address.PhoneNumber, + FaxNumber = address.FaxNumber, + Note = address.Note, + Attributes = CopyAttributes(address.Attributes), + AddressType = address.AddressType + }; + } + + private static PickupPoint CopyPickupPoint(PickupPoint point) + { + if (point == null) return null; + return new PickupPoint { + Id = point.Id, + UserFields = point.UserFields?.Select(x => new UserField { Key = x.Key, Value = x.Value }).ToList(), + CreatedOnUtc = point.CreatedOnUtc, + CreatedBy = point.CreatedBy, + UpdatedOnUtc = point.UpdatedOnUtc, + UpdatedBy = point.UpdatedBy, + Name = point.Name, + Description = point.Description, + AdminComment = point.AdminComment, + Address = CopyAddress(point.Address), + WarehouseId = point.WarehouseId, + StoreId = point.StoreId, + PickupFee = point.PickupFee, + Latitude = point.Latitude, + Longitude = point.Longitude, + DisplayOrder = point.DisplayOrder + }; + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs new file mode 100644 index 000000000..913c59fb8 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs @@ -0,0 +1,316 @@ +using System.Collections; +using System.Reflection; +using Grand.Business.Checkout.Extensions; +using Grand.Domain.Common; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Domain.Shipping; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Business.Checkout.Tests.Extensions; + +[TestClass] +public class RecurringCycleOrderTests +{ + private static readonly DateTime CreatedOn = new(2026, 12, 1, 10, 0, 0, DateTimeKind.Utc); + + // properties the copy sets or resets, with the value it must hold + private static readonly Dictionary ResetProperties = new() { + { nameof(Order.Id), "c2" }, + { nameof(Order.OrderNumber), 0 }, + { nameof(Order.Code), "ABC" }, + { nameof(Order.InitialOrderId), null }, // checked in the loop: the initial order's id + { nameof(Order.RecurringCycleNumber), 2 }, + { nameof(Order.CreatedOnUtc), CreatedOn }, + { nameof(Order.CreatedBy), null }, + { nameof(Order.UpdatedOnUtc), null }, + { nameof(Order.UpdatedBy), null }, + { nameof(Order.OrderStatusId), (int)OrderStatusSystem.Pending }, + { nameof(Order.PaymentStatusId), PaymentStatus.Pending }, + { nameof(Order.ShippingStatusId), ShippingStatus.Pending }, + { nameof(Order.PaidAmount), 0d }, + { nameof(Order.PaidDateUtc), null }, + { nameof(Order.PaymentDueDateUtc), null }, + { nameof(Order.PaymentReminderSentOnUtc), null }, + { nameof(Order.PaymentOverdueNoticeSentOnUtc), null }, + { nameof(Order.RefundedAmount), 0d }, + { nameof(Order.RedeemedLoyaltyPoints), 0 }, + { nameof(Order.RedeemedLoyaltyPointsAmount), 0d }, + { nameof(Order.LoyaltyPointsWereAdded), false }, + { nameof(Order.CalcLoyaltyPoints), 0 }, + { nameof(Order.OrderTotal), 100d }, // the initial total (90) plus the points amount (10) + { nameof(Order.Deleted), false }, + { nameof(Order.Imported), false }, + { nameof(Order.OrderGuid), null }, // checked in the loop: a new guid + { nameof(Order.UserFields), null } // checked in the loop: empty + }; + + private static OrderItem Item(string productId, bool ship = true) + { + return new OrderItem { + OrderItemGuid = Guid.NewGuid(), + ProductId = productId, + Sku = "sku-" + productId, + VendorId = "v1", + WarehouseId = "w1", + SeId = "se1", + Quantity = 3, + IsShipEnabled = ship, + OpenQty = 1, + ShipQty = 2, + CancelQty = 1, + CancelAmount = 5, + ReturnQty = 1, + Status = OrderItemStatus.Close, + TaxRate = 23, + UnitPriceWithoutDiscInclTax = 12.5, + UnitPriceWithoutDiscExclTax = 10.2, + UnitPriceInclTax = 12, + UnitPriceExclTax = 9.76, + PriceInclTax = 36, + PriceExclTax = 29.28, + DiscountAmountInclTax = 1.5, + DiscountAmountExclTax = 1.2, + OriginalProductCost = 4, + AttributeDescription = "Color: red", + Attributes = new List { new() { Key = "color", Value = "red" } }, + DownloadCount = 4, + IsDownloadActivated = true, + LicenseDownloadId = "dl1", + ItemWeight = 2.5, + RentalStartDateUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), + RentalEndDateUtc = new DateTime(2026, 1, 5, 0, 0, 0, DateTimeKind.Utc), + CreatedOnUtc = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc), + Commission = 0.7, + cId = "c-owner" + }; + } + + private static Order Initial() + { + var order = new Order { + Id = "o1", + OrderGuid = Guid.NewGuid(), + OrderNumber = 17, + Code = "INIT", + OrderTotal = 120, + CurrencyRate = 4.3, + PaidAmount = 120, + PaidDateUtc = new DateTime(2026, 11, 2, 0, 0, 0, DateTimeKind.Utc), + OrderStatusId = (int)OrderStatusSystem.Complete, + PaymentStatusId = PaymentStatus.Paid, + ShippingStatusId = ShippingStatus.Delivered, + BillingAddress = new Address { + City = "Warsaw", Attributes = new List { new() { Key = "a", Value = "b" } } + }, + ShippingAddress = new Address { City = "Krakow" }, + IsRecurring = true, + RecurringCycleNumber = 1 + }; + order.OrderItems.Add(Item("p1")); + order.OrderItems.Add(Item("p2")); + return order; + } + + [TestMethod] + public void Copy_KeepsPricesAddressesAndItems() + { + var initial = Initial(); + initial.OrderTaxes.Add(new OrderTax { Percent = 23, Amount = 22.4 }); + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + + Assert.AreEqual(120, copy.OrderTotal); + Assert.AreEqual(4.3, copy.CurrencyRate); + Assert.AreEqual(2, copy.OrderItems.Count); + var source = initial.OrderItems.ToList(); + var items = copy.OrderItems.ToList(); + for (var i = 0; i < items.Count; i++) + { + Assert.AreNotSame(source[i], items[i]); + Assert.AreNotEqual(source[i].Id, items[i].Id); + Assert.AreEqual(source[i].UnitPriceInclTax, items[i].UnitPriceInclTax); + Assert.AreEqual(source[i].PriceInclTax, items[i].PriceInclTax); + Assert.AreEqual("w1", items[i].WarehouseId); + Assert.AreEqual(source[i].ProductId, items[i].ProductId); + Assert.AreEqual(source[i].cId, items[i].cId); + Assert.AreNotSame(source[i].Attributes, items[i].Attributes); + Assert.AreEqual(1, items[i].Attributes.Count); + Assert.AreEqual("color", items[i].Attributes[0].Key); + Assert.AreEqual("red", items[i].Attributes[0].Value); + Assert.AreEqual(CreatedOn, items[i].CreatedOnUtc); + } + + Assert.AreEqual(1, copy.OrderTaxes.Count); + Assert.AreEqual(23, copy.OrderTaxes.First().Percent); + Assert.AreEqual(22.4, copy.OrderTaxes.First().Amount); + Assert.AreNotSame(initial.OrderTaxes.First(), copy.OrderTaxes.First()); + Assert.AreEqual(0, copy.OrderTags.Count); + + Assert.AreNotSame(initial.BillingAddress, copy.BillingAddress); + Assert.AreEqual("Warsaw", copy.BillingAddress.City); + Assert.AreNotSame(initial.BillingAddress.Attributes, copy.BillingAddress.Attributes); + Assert.AreEqual("a", copy.BillingAddress.Attributes[0].Key); + Assert.AreNotSame(initial.ShippingAddress, copy.ShippingAddress); + Assert.AreEqual("Krakow", copy.ShippingAddress.City); + } + + [TestMethod] + public void Copy_IsANewUnpaidOrderLinkedToTheInitialOne() + { + var initial = Initial(); + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + + Assert.AreEqual("c2", copy.Id); + Assert.AreEqual("ABC", copy.Code); + Assert.AreEqual(initial.Id, copy.InitialOrderId); + Assert.AreEqual(2, copy.RecurringCycleNumber); + Assert.AreEqual(PaymentStatus.Pending, copy.PaymentStatusId); + Assert.AreEqual(0, copy.PaidAmount); + Assert.IsNull(copy.PaidDateUtc); + Assert.AreEqual((int)OrderStatusSystem.Pending, copy.OrderStatusId); + Assert.AreEqual(0, copy.OrderNumber); + Assert.AreNotEqual(initial.OrderGuid, copy.OrderGuid); + Assert.AreEqual(CreatedOn, copy.CreatedOnUtc); + Assert.AreEqual(ShippingStatus.Pending, copy.ShippingStatusId); + Assert.AreEqual(2, copy.OrderItems.Count); + foreach (var item in copy.OrderItems) + { + Assert.IsFalse(initial.OrderItems.Any(i => i.OrderItemGuid == item.OrderItemGuid)); + Assert.AreEqual(item.Quantity, item.OpenQty); + Assert.AreEqual(0, item.ShipQty); + Assert.AreEqual(0, item.CancelQty); + Assert.AreEqual(0, item.ReturnQty); + Assert.AreEqual(0, item.CancelAmount); + Assert.AreEqual(OrderItemStatus.Open, item.Status); + Assert.AreEqual(0, item.DownloadCount); + Assert.IsFalse(item.IsDownloadActivated); + Assert.AreEqual("", item.LicenseDownloadId); + } + } + + [TestMethod] + public void Copy_LoyaltyPointsSpentOnTheInitialOrderAreNotSpentAgain() + { + var initial = Initial(); + initial.OrderTotal = 90; + initial.RedeemedLoyaltyPoints = 100; + initial.RedeemedLoyaltyPointsAmount = 10; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + + Assert.AreEqual(100, copy.OrderTotal); + Assert.AreEqual(0, copy.RedeemedLoyaltyPoints); + Assert.AreEqual(0, copy.RedeemedLoyaltyPointsAmount); + } + + [TestMethod] + public void Copy_NothingToShip_ShippingNotRequired() + { + var initial = Initial(); + foreach (var item in initial.OrderItems) item.IsShipEnabled = false; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + + Assert.AreEqual(ShippingStatus.ShippingNotRequired, copy.ShippingStatusId); + } + + [TestMethod] + public void Copy_EveryOrderPropertyIsCopiedOrDeliberatelyReset() + { + // OrderItems, OrderTaxes and OrderTags have protected setters; the explicit tests cover them + var properties = typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.SetMethod is { IsPublic: true }).ToList(); + foreach (var name in ResetProperties.Keys) + Assert.IsTrue(properties.Any(p => p.Name == name), $"{name} is not a settable Order property"); + + var initial = new Order(); + var n = 1; + foreach (var property in properties) + property.SetValue(initial, Distinct(property.PropertyType, property.Name, n++)); + initial.OrderItems.Add(Item("p1")); + initial.OrderTotal = 90; + initial.RedeemedLoyaltyPointsAmount = 10; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + + foreach (var property in properties) + { + var actual = property.GetValue(copy); + if (!ResetProperties.TryGetValue(property.Name, out var expected)) + { + AssertSameValue(property.GetValue(initial), actual, property.Name); + continue; + } + + switch (property.Name) + { + case nameof(Order.OrderGuid): + Assert.AreNotEqual(Guid.Empty, actual); + Assert.AreNotEqual(initial.OrderGuid, actual); + break; + case nameof(Order.UserFields): + Assert.AreEqual(0, ((ICollection)actual).Count); + break; + case nameof(Order.InitialOrderId): + Assert.AreEqual(initial.Id, actual); + break; + default: + Assert.AreEqual(expected, actual, property.Name); + break; + } + } + } + + private static object Distinct(Type type, string name, int n) + { + type = Nullable.GetUnderlyingType(type) ?? type; + if (type == typeof(string)) return $"{name}-{n}"; + if (type == typeof(int)) return n + 1000; + if (type == typeof(double)) return n + 0.5; + if (type == typeof(bool)) return true; + if (type == typeof(Guid)) return Guid.NewGuid(); + if (type == typeof(DateTime)) return new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(n); + if (type.IsEnum) return Enum.GetValues(type).Cast().Last(); + if (type == typeof(IList)) + return new List { new() { Key = $"{name}-k", Value = $"{name}-v" } }; + if (type == typeof(IList)) + return new List { new() { Key = $"{name}-k", Value = $"{name}-v" } }; + if (type == typeof(Address) || type == typeof(PickupPoint)) + { + var value = Activator.CreateInstance(type)!; + var i = 1; + foreach (var p in type.GetProperties().Where(p => p.SetMethod is { IsPublic: true })) + p.SetValue(value, Distinct(p.PropertyType, $"{name}.{p.Name}", n * 100 + i++)); + return value; + } + + // a new property of another type must teach this test how to fill and compare it + throw new NotSupportedException($"Order.{name} has a type this test cannot fill: {type}"); + } + + private static void AssertSameValue(object expected, object actual, string path) + { + if (expected is null || expected is string || expected.GetType().IsValueType) + { + Assert.AreEqual(expected, actual, path); + return; + } + + Assert.IsNotNull(actual, path); + Assert.AreNotSame(expected, actual, path); + if (expected is IEnumerable expectedList) + { + var e = expectedList.Cast().ToList(); + var a = ((IEnumerable)actual).Cast().ToList(); + Assert.AreEqual(e.Count, a.Count, path); + for (var i = 0; i < e.Count; i++) AssertSameValue(e[i], a[i], $"{path}[{i}]"); + return; + } + + // an entity or address: a new instance holding the same values + foreach (var p in expected.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + AssertSameValue(p.GetValue(expected), p.GetValue(actual), $"{path}.{p.Name}"); + } +} From 000225bd2d457fa2c7df43173a3e310217c176d6 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:14:08 +0100 Subject: [PATCH 04/10] Place a paid order for each recurring payment cycle after the first --- .../PlaceRecurringCycleOrderCommandHandler.cs | 112 +++++++ .../Orders/PlaceRecurringCycleOrderCommand.cs | 21 ++ ...eRecurringCycleOrderCommandHandlerTests.cs | 277 ++++++++++++++++++ 3 files changed, 410 insertions(+) create mode 100644 src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs create mode 100644 src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs create mode 100644 src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs new file mode 100644 index 000000000..9a3391080 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs @@ -0,0 +1,112 @@ +using Grand.Business.Checkout.Extensions; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Commands.Messages.Common; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Mediator; +using Grand.SharedKernel; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class PlaceRecurringCycleOrderCommandHandler( + IOrderService orderService, + IPaymentTransactionService paymentTransactionService, + IProductService productService, + IInventoryManageService inventoryManageService, + ICustomerService customerService, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(PlaceRecurringCycleOrderCommand request, CancellationToken cancellationToken) + { + var recurringPayment = request.RecurringPayment; + var cycle = request.Cycle; + + var initialOrder = await orderService.GetOrderById(recurringPayment.InitialOrderId); + if (initialOrder == null || initialOrder.Deleted) + throw new GrandException( + $"The initial order {recurringPayment.InitialOrderId} of recurring payment {recurringPayment.Id} was not found"); + + var code = await mediator.Send(new PrepareOrderCodeCommand(), cancellationToken); + var order = RecurringCycleOrder.Copy(initialOrder, cycle.OrderId, cycle.CycleNumber, code, DateTime.UtcNow); + + // the gateway already took the money, so the transaction is a real one from the start + var paymentTransaction = new PaymentTransaction { + TransactionStatus = TransactionStatus.Pending, + OrderGuid = order.OrderGuid, + OrderCode = order.Code, + StoreId = order.StoreId, + CustomerId = order.CustomerId, + CustomerEmail = order.CustomerEmail, + PaymentMethodSystemName = order.PaymentMethodSystemName, + CurrencyCode = order.CustomerCurrencyCode, + CurrencyRate = order.CurrencyRate, + TransactionAmount = order.OrderTotal, + Temp = false + }; + await paymentTransactionService.InsertPaymentTransaction(paymentTransaction); + + await orderService.InsertOrder(order); + + // no stock check: the customer has paid, so low stock never blocks a cycle order + foreach (var item in order.OrderItems) + { + var product = await productService.GetProductById(item.ProductId); + if (product == null) continue; + + await inventoryManageService.AdjustReserved(product, -item.Quantity, item.Attributes, item.WarehouseId); + + // statistics only: the payment is already taken, so a failed write must not stop the order + try + { + await productService.IncrementProductField(product, x => x.Sold, item.Quantity); + } + catch (Exception exc) + { + logger.LogWarning(exc, "Could not update the sold count of product {ProductId}", product.Id); + } + } + + await InsertNote(order.Id, + $"Cycle {cycle.CycleNumber} of the recurring payment of order #{initialOrder.OrderNumber}"); + + // no request context here: the customer comes from the order, and no host falls back to the store's primary one + var customer = await customerService.GetCustomerById(order.CustomerId); + await mediator.Send(new OrderNotificationCommand { Order = order, Customer = customer, Host = null }, + cancellationToken); + + await mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken); + + await mediator.Publish(new OrderPlacedEvent(order), cancellationToken); + + await mediator.Send(new MarkAsPaidCommand { + PaymentTransaction = paymentTransaction, + Amount = cycle.Amount, + Reference = cycle.ProviderReference, + CreatedBy = recurringPayment.PaymentMethodSystemName + }, cancellationToken); + + // the order is paid with what the gateway charged; a price change at the gateway shows here + if (Math.Round(cycle.Amount, 2) != Math.Round(order.OrderTotal, 2)) + await InsertNote(order.Id, + $"The payment gateway charged {cycle.Amount} for this cycle; the order total is {order.OrderTotal}"); + + return order; + } + + private Task InsertNote(string orderId, string note) + { + return orderService.InsertOrderNote(new OrderNote { + Note = note, + DisplayToCustomer = false, + OrderId = orderId + }); + } +} diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs new file mode 100644 index 000000000..34c07ab28 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs @@ -0,0 +1,21 @@ +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// Places the paid order of one recurring payment cycle after the first: a copy of the initial order that goes +/// through the paid-order path. The result is the placed order +/// +public class PlaceRecurringCycleOrderCommand : IRequest +{ + /// + /// The recurring payment the cycle belongs to + /// + public RecurringPayment RecurringPayment { get; set; } + + /// + /// The cycle the gateway reported, already claimed: its order identifier is the one the order is inserted with + /// + public RecurringPaymentCycle Cycle { get; set; } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs new file mode 100644 index 000000000..db611ea6e --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs @@ -0,0 +1,277 @@ +using Grand.Business.Checkout.Commands.Handlers.Orders; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Commands.Messages.Common; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Catalog; +using Grand.Domain.Common; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Mediator; +using Grand.SharedKernel; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders; + +[TestClass] +public class PlaceRecurringCycleOrderCommandHandlerTests +{ + private readonly List _calls = []; + private PlaceRecurringCycleOrderCommandHandler _handler; + private Mock _inventoryMock; + private Mock _mediatorMock; + private Mock _orderServiceMock; + private Mock _paymentTransactionServiceMock; + private Mock _productServiceMock; + private Mock _customerServiceMock; + + private Order _initialOrder; + private Customer _customer; + private RecurringPayment _recurringPayment; + private RecurringPaymentCycle _cycle; + private Order _insertedOrder; + private PaymentTransaction _insertedTransaction; + private readonly List _notes = []; + + [TestInitialize] + public void Init() + { + _calls.Clear(); + _notes.Clear(); + _insertedOrder = null; + _insertedTransaction = null; + + _mediatorMock = new Mock(); + _orderServiceMock = new Mock(); + _paymentTransactionServiceMock = new Mock(); + _productServiceMock = new Mock(); + _inventoryMock = new Mock(); + _customerServiceMock = new Mock(); + + _handler = new PlaceRecurringCycleOrderCommandHandler(_orderServiceMock.Object, + _paymentTransactionServiceMock.Object, _productServiceMock.Object, _inventoryMock.Object, + _customerServiceMock.Object, _mediatorMock.Object, + new Mock>().Object); + + _initialOrder = new Order { + Id = "o1", + OrderNumber = 17, + StoreId = "s1", + CustomerId = "c1", + CustomerEmail = "buyer@shop.com", + PaymentMethodSystemName = "Payments.Stripe", + CustomerCurrencyCode = "EUR", + CurrencyRate = 1.5, + OrderTotal = 100 + }; + _initialOrder.OrderItems.Add(new OrderItem { + ProductId = "p1", Quantity = 2, WarehouseId = "w1", IsShipEnabled = true, + Attributes = [new CustomAttribute { Key = "k", Value = "v" }] + }); + _initialOrder.OrderItems.Add(new OrderItem { ProductId = "p2", Quantity = 3, WarehouseId = "w1" }); + + _customer = new Customer { Id = "c1" }; + _recurringPayment = new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Stripe" + }; + _cycle = new RecurringPaymentCycle { + OrderId = "cycle-order", CycleNumber = 2, ProviderReference = "in_2", Amount = 100 + }; + + _orderServiceMock.Setup(x => x.GetOrderById("o1")).ReturnsAsync(_initialOrder); + _orderServiceMock.Setup(x => x.InsertOrder(It.IsAny())) + .Callback(o => { + _insertedOrder = o; + _calls.Add("InsertOrder"); + }) + .Returns(Task.CompletedTask); + _orderServiceMock.Setup(x => x.InsertOrderNote(It.IsAny())) + .Callback(n => _notes.Add(n)) + .Returns(Task.CompletedTask); + _paymentTransactionServiceMock.Setup(x => x.InsertPaymentTransaction(It.IsAny())) + .Callback(t => { + _insertedTransaction = t; + _calls.Add("InsertPaymentTransaction"); + }) + .Returns(Task.CompletedTask); + _customerServiceMock.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(_customer); + _productServiceMock.Setup(x => x.GetProductById("p1", false)).ReturnsAsync(new Product { Id = "p1" }); + _productServiceMock.Setup(x => x.GetProductById("p2", false)).ReturnsAsync(new Product { Id = "p2" }); + + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync("CODE-1"); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback((_, _) => _calls.Add("OrderNotification")) + .Returns(Task.CompletedTask); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback, CancellationToken>((_, _) => _calls.Add("CheckOrderStatus")) + .ReturnsAsync(true); + _mediatorMock.Setup(x => x.Publish(It.IsAny(), It.IsAny())) + .Callback((_, _) => _calls.Add("OrderPlacedEvent")) + .Returns(Task.CompletedTask); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback, CancellationToken>((_, _) => _calls.Add("MarkAsPaid")) + .ReturnsAsync(true); + } + + private Task Place() + { + return _handler.Handle(new PlaceRecurringCycleOrderCommand { + RecurringPayment = _recurringPayment, Cycle = _cycle + }, CancellationToken.None); + } + + [TestMethod] + public async Task Handle_InsertsTheCopyWithTheClaimedIdAndAPendingTransaction() + { + var order = await Place(); + + Assert.IsNotNull(_insertedOrder); + Assert.AreSame(_insertedOrder, order); + Assert.AreEqual("cycle-order", _insertedOrder.Id); + Assert.AreEqual("o1", _insertedOrder.InitialOrderId); + Assert.AreEqual(2, _insertedOrder.RecurringCycleNumber); + Assert.AreEqual("CODE-1", _insertedOrder.Code); + + Assert.IsNotNull(_insertedTransaction); + Assert.AreEqual(_insertedOrder.OrderGuid, _insertedTransaction.OrderGuid); + Assert.AreEqual("CODE-1", _insertedTransaction.OrderCode); + Assert.AreEqual(TransactionStatus.Pending, _insertedTransaction.TransactionStatus); + Assert.AreEqual(_insertedOrder.OrderTotal, _insertedTransaction.TransactionAmount); + Assert.IsFalse(_insertedTransaction.Temp); + Assert.AreEqual("s1", _insertedTransaction.StoreId); + Assert.AreEqual("c1", _insertedTransaction.CustomerId); + Assert.AreEqual("buyer@shop.com", _insertedTransaction.CustomerEmail); + Assert.AreEqual("Payments.Stripe", _insertedTransaction.PaymentMethodSystemName); + Assert.AreEqual("EUR", _insertedTransaction.CurrencyCode); + Assert.AreEqual(1.5, _insertedTransaction.CurrencyRate); + // the transaction is written before the order, as in placement + Assert.IsTrue(_calls.IndexOf("InsertPaymentTransaction") < _calls.IndexOf("InsertOrder")); + } + + [TestMethod] + public async Task Handle_ReservesStockWithoutCheckingIt() + { + await Place(); + + _inventoryMock.Verify(x => x.AdjustReserved(It.Is(p => p.Id == "p1"), -2, + It.Is>(a => a.Count == 1 && a[0].Key == "k"), "w1"), Times.Once); + _inventoryMock.Verify(x => x.AdjustReserved(It.Is(p => p.Id == "p2"), -3, + It.IsAny>(), "w1"), Times.Once); + _inventoryMock.Verify(x => x.AdjustReserved(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Exactly(2)); + _inventoryMock.Verify(x => x.TryReserve(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_ASoldCountThatCannotBeWritten_DoesNotStopTheOrder() + { + _productServiceMock.Setup(x => x.IncrementProductField(It.IsAny(), + It.IsAny>>(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("db")); + + var order = await Place(); + + Assert.AreSame(_insertedOrder, order); + Assert.IsTrue(_calls.Contains("MarkAsPaid")); + } + + [TestMethod] + public async Task Handle_AProductThatNoLongerExists_IsSkipped() + { + _productServiceMock.Setup(x => x.GetProductById("p1", false)).ReturnsAsync((Product)null); + + await Place(); + + _inventoryMock.Verify(x => x.AdjustReserved(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Once); + Assert.IsTrue(_calls.Contains("MarkAsPaid")); + } + + [TestMethod] + public async Task Handle_GoesThroughTheNormalPaidOrderPath() + { + await Place(); + + CollectionAssert.AreEqual( + new[] { + "InsertPaymentTransaction", "InsertOrder", "OrderNotification", "CheckOrderStatus", + "OrderPlacedEvent", "MarkAsPaid" + }, _calls); + + _mediatorMock.Verify(x => x.Send(It.Is(c => + c.Order == _insertedOrder && c.Customer == _customer && c.Host == null), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.Is(c => c.Order == _insertedOrder), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Publish(It.Is(e => e.Order == _insertedOrder), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.Is(c => + c.PaymentTransaction == _insertedTransaction && c.Amount == 100 && c.Reference == "in_2" && + c.CreatedBy == "Payments.Stripe"), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task Handle_AddsTheCycleNote() + { + await Place(); + + Assert.AreEqual(1, _notes.Count); + Assert.AreEqual("Cycle 2 of the recurring payment of order #17", _notes[0].Note); + Assert.AreEqual("cycle-order", _notes[0].OrderId); + Assert.IsFalse(_notes[0].DisplayToCustomer); + } + + [TestMethod] + public async Task Handle_GatewayAmountDiffers_AddsANote() + { + _cycle.Amount = 95; + + await Place(); + + Assert.AreEqual(2, _notes.Count); + Assert.AreEqual("The payment gateway charged 95 for this cycle; the order total is 100", _notes[1].Note); + Assert.AreEqual("cycle-order", _notes[1].OrderId); + // the note comes after the payment is recorded + Assert.AreEqual("MarkAsPaid", _calls[^1]); + } + + [TestMethod] + public async Task Handle_AmountsEqualAfterRounding_AddsOnlyTheCycleNote() + { + _cycle.Amount = 100.004; + + await Place(); + + Assert.AreEqual(1, _notes.Count); + } + + [TestMethod] + public async Task Handle_InitialOrderDeleted_Throws() + { + _initialOrder.Deleted = true; + + await Assert.ThrowsExactlyAsync(Place); + + _orderServiceMock.Verify(x => x.InsertOrder(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_InitialOrderMissing_Throws() + { + _orderServiceMock.Setup(x => x.GetOrderById("o1")).ReturnsAsync((Order)null); + + var exception = await Assert.ThrowsExactlyAsync(Place); + + Assert.AreEqual("The initial order o1 of recurring payment rp1 was not found", exception.Message); + _orderServiceMock.Verify(x => x.InsertOrder(It.IsAny()), Times.Never); + } +} From ae0aad7de773c0278ddbe481443271ba0a5ab65a Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:24:30 +0100 Subject: [PATCH 05/10] Record a paid recurring payment cycle and stop the gateway once every cycle is paid --- .ai/skills/plugin-payment.md | 5 + ...cordRecurringPaymentCycleCommandHandler.cs | 64 ++++++++ .../Services/Payments/PaymentService.cs | 20 +++ .../RecordRecurringPaymentCycleCommand.cs | 37 +++++ .../Checkout/Payments/IPaymentService.cs | 7 + ...ordRecurringPaymentCommandHandlersTests.cs | 138 ++++++++++++++++++ .../Services/Payments/PaymentServiceTests.cs | 25 ++++ 7 files changed, 296 insertions(+) create mode 100644 src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs create mode 100644 src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs diff --git a/.ai/skills/plugin-payment.md b/.ai/skills/plugin-payment.md index 7a3e2bbd2..46843f0a4 100644 --- a/.ai/skills/plugin-payment.md +++ b/.ai/skills/plugin-payment.md @@ -65,6 +65,11 @@ Do not use this skill for order processing business logic outside the payment fl - The provider, not the shop, runs the schedule: the gateway charges every cycle, retries failures and reports each cycle to the shop, the first one (the initial order's payment) included: `CyclesPaid` stays 0 until it does. A cart with a recurring product is offered only methods whose `SupportRecurringPayment()` returns `true`, and the order is refused for any other method. - Return `SupportRecurringPayment() => true` only when the payment flow starts the gateway's schedule for a recurring order and `CancelRecurringPayment` stops it. Both members have defaults (`false`, and an error result), so a provider without recurring support implements neither. - Never report "cancelled" from `CancelRecurringPayment` unless the gateway confirmed it: on an error result the shop keeps the recurring payment running. +- A provider reports to the shop with three mediator commands (`Grand.Business.Core.Commands.Checkout.Orders`): `RecordRecurringPaymentCycleCommand` (a cycle was paid; the shop places the cycle order from the second cycle on and, once every cycle is paid, calls `CancelRecurringPayment` to stop the gateway), `RecordRecurringPaymentFailureCommand` and `RecordRecurringPaymentEndedCommand` (the gateway ended it). +- Pass `RecurringPayment.Id` to the gateway as metadata when the schedule starts, and send it back as `RecurringPaymentId` in every command. The webhook must verify the gateway signature before sending any of them. +- `CycleReference` is the gateway's invoice or charge id, so a resent webhook is recorded once and the command returns `false`. `ProviderReference` is the subscription id. +- `Amount` uses the units of `MarkAsPaidCommand.Amount`: the order total in the order's currency, as Stripe Checkout passes it (`paymentIntent.Amount / 100.0`). +- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order and rethrows so the gateway resends. #### Project Structure 12. Use `Microsoft.NET.Sdk.Razor` as SDK. diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs new file mode 100644 index 000000000..43ced73d4 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -0,0 +1,64 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentCycleCommandHandler( + IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, + IOrderService orderService, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentCycleCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + + var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, + request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); + if (claim == null) + return false; + + // the first cycle is the initial order's own payment, which the provider marks paid on its existing path + if (claim.Cycle.CycleNumber > 1) + try + { + await mediator.Send(new PlaceRecurringCycleOrderCommand { + RecurringPayment = claim.RecurringPayment, Cycle = claim.Cycle + }, cancellationToken); + } + catch (Exception e) + { + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order of cycle {CycleNumber} ({CycleReference}) could not be created", + claim.RecurringPayment.Id, claim.Cycle.CycleNumber, request.CycleReference); + await AddNote(claim.RecurringPayment, + $"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order could not be created: {e.Message}"); + // the failure must reach the provider, so the gateway resends and an operator sees it + throw; + } + + if (claim.Completed) + { + var result = await paymentService.CancelRecurringPayment(claim.RecurringPayment); + // the status stays Completed: every cycle is paid, only the gateway schedule may still run + if (!result.Success) + await AddNote(claim.RecurringPayment, + $"The recurring payment is completed, but the payment gateway did not confirm it stopped charging: {string.Join(", ", result.Errors)}"); + } + + return true; + } + + private Task AddNote(RecurringPayment recurringPayment, string note) + { + return orderService.InsertOrderNote(new OrderNote { + OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, + CreatedOnUtc = DateTime.UtcNow + }); + } +} diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs index 0a80569c4..1a113c056 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs @@ -402,6 +402,26 @@ public virtual async Task SupportRecurringPayment(string paymentMethodSyst return await paymentMethod.SupportRecurringPayment(); } + /// + /// Asks the payment method to stop the gateway schedule of a recurring payment + /// + /// Recurring payment + /// Result; an error when the payment method could not be loaded + public virtual async Task CancelRecurringPayment(RecurringPayment recurringPayment) + { + ArgumentNullException.ThrowIfNull(recurringPayment); + + var paymentMethod = LoadPaymentMethodBySystemName(recurringPayment.PaymentMethodSystemName); + if (paymentMethod == null) + { + var result = new CancelRecurringPaymentResult(); + result.AddError("Payment method couldn't be loaded"); + return result; + } + + return await paymentMethod.CancelRecurringPayment(recurringPayment); + } + /// /// Voids a payment /// diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs new file mode 100644 index 000000000..39cce12c1 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs @@ -0,0 +1,37 @@ +using Grand.Mediator; + +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) +/// +public class RecordRecurringPaymentCycleCommand : IRequest +{ + /// + /// The recurring payment the provider was given as gateway metadata + /// + public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of the subscription + /// + public string ProviderReference { get; set; } + + /// + /// The provider's reference of the cycle (the invoice or charge), so a resent report is recorded once + /// + public string CycleReference { get; set; } + + /// + /// The amount paid, in the units of + /// + public double Amount { get; set; } + + public DateTime PaidOnUtc { get; set; } + + /// + /// The next payment date the gateway reports, if any + /// + public DateTime? NextPaymentDateUtc { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs index 190862328..5c7b54391 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs @@ -154,6 +154,13 @@ Task> LoadAllPaymentMethods(Customer customer = null, st /// A value indicating whether recurring payments are supported Task SupportRecurringPayment(string paymentMethodSystemName); + /// + /// Asks the payment method to stop the gateway schedule of a recurring payment + /// + /// Recurring payment + /// Result; an error when the payment method could not be loaded + Task CancelRecurringPayment(RecurringPayment recurringPayment); + /// /// Voids a payment /// 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 2bd9762fc..5e32dab52 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 @@ -1,6 +1,11 @@ using Grand.Business.Checkout.Commands.Handlers.Orders; using Grand.Business.Core.Commands.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Orders; +using Grand.Mediator; +using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -10,11 +15,17 @@ namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders; public class RecordRecurringPaymentCommandHandlersTests { private Mock _service; + private Mock _paymentService; + private Mock _orderService; + private Mock _mediator; [TestInitialize] public void Init() { _service = new Mock(); + _paymentService = new Mock(); + _orderService = new Mock(); + _mediator = new Mock(); } [TestMethod] @@ -61,4 +72,131 @@ public async Task EndedCommand_WithoutRecurringPaymentId_Throws() await Assert.ThrowsExactlyAsync(() => handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "" }, CancellationToken.None)); } + + private RecordRecurringPaymentCycleCommandHandler CycleHandler() + { + return new RecordRecurringPaymentCycleCommandHandler(_service.Object, _paymentService.Object, + _orderService.Object, _mediator.Object, new Mock>().Object); + } + + private static RecordRecurringPaymentCycleCommand CycleCommand() + { + return new RecordRecurringPaymentCycleCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1", CycleReference = "in_2", Amount = 10, + PaidOnUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) + }; + } + + private void SetupClaim(int cycleNumber, bool completed) + { + var claim = new RecurringCycleClaim { + RecurringPayment = new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test" + }, + Cycle = new RecurringPaymentCycle { CycleNumber = cycleNumber, OrderId = "o2" }, + Completed = completed + }; + _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)).ReturnsAsync(claim); + } + + [TestMethod] + 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); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsFalse(result); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task CycleCommand_FirstCycle_PlacesNoOrder() + { + SetupClaim(1, false); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task CycleCommand_LaterCycle_PlacesTheCycleOrder() + { + SetupClaim(2, false); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPayment.Id == "rp1" && c.Cycle.CycleNumber == 2), It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task CycleCommand_OrderCannotBeCreated_NotesItOnTheInitialOrderAndThrows() + { + SetupClaim(2, false); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("boom")); + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == "o1" && n.Note.Contains("in_2") && n.Note.Contains("boom") && !n.DisplayToCustomer)), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_Completed_AsksTheProviderToStop() + { + SetupClaim(3, true); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CycleCommand_NotCompleted_DoesNotAskTheProviderToStop() + { + SetupClaim(3, false); + + await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CycleCommand_CompletedAndProviderRefuses_NotesItOnTheInitialOrder() + { + SetupClaim(3, true); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == "o1" && !n.DisplayToCustomer && + n.Note == "The recurring payment is completed, but the payment gateway did not confirm it stopped charging: no way")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_WithoutRecurringPaymentId_Throws() + { + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(new RecordRecurringPaymentCycleCommand { RecurringPaymentId = "" }, + CancellationToken.None)); + } } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs index c073c65a1..db18ad385 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs @@ -322,6 +322,31 @@ public async Task PaymentService_SupportRecurringPayment_AsksTheProvider() Assert.IsTrue(await _paymentService.SupportRecurringPayment("Payments.Test")); } + [TestMethod] + public async Task PaymentService_CancelRecurringPayment_UnknownMethod_ReturnsError() + { + _paymentProviderMock.Setup(c => c.SystemName).Returns("Payments.Test"); + + var result = await _paymentService.CancelRecurringPayment(new RecurringPayment + { PaymentMethodSystemName = "Missing" }); + + Assert.IsFalse(result.Success); + CollectionAssert.AreEqual(new[] { "Payment method couldn't be loaded" }, result.Errors.ToArray()); + } + + [TestMethod] + public async Task PaymentService_CancelRecurringPayment_AsksTheProvider() + { + _paymentProviderMock.Setup(c => c.SystemName).Returns("Payments.Test"); + _paymentProviderMock.Setup(c => c.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + var result = await _paymentService.CancelRecurringPayment(new RecurringPayment + { PaymentMethodSystemName = "Payments.Test" }); + + Assert.IsTrue(result.Success); + } + //a provider written before the recurring contract existed keeps its defaults private class LegacyProvider : IPaymentProvider { From b2e9d719c1aedf75df6225c3e6aea7f1f39524d0 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:26:58 +0100 Subject: [PATCH 06/10] Keep the original failure when a recurring cycle note cannot be written --- .ai/skills/plugin-payment.md | 2 +- ...cordRecurringPaymentCycleCommandHandler.cs | 41 ++++++++++++++---- ...ordRecurringPaymentCommandHandlersTests.cs | 42 +++++++++++++++++++ 3 files changed, 75 insertions(+), 10 deletions(-) diff --git a/.ai/skills/plugin-payment.md b/.ai/skills/plugin-payment.md index 46843f0a4..ea43a187b 100644 --- a/.ai/skills/plugin-payment.md +++ b/.ai/skills/plugin-payment.md @@ -69,7 +69,7 @@ Do not use this skill for order processing business logic outside the payment fl - Pass `RecurringPayment.Id` to the gateway as metadata when the schedule starts, and send it back as `RecurringPaymentId` in every command. The webhook must verify the gateway signature before sending any of them. - `CycleReference` is the gateway's invoice or charge id, so a resent webhook is recorded once and the command returns `false`. `ProviderReference` is the subscription id. - `Amount` uses the units of `MarkAsPaidCommand.Amount`: the order total in the order's currency, as Stripe Checkout passes it (`paymentIntent.Amount / 100.0`). -- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order and rethrows so the gateway resends. +- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order for staff and rethrows so the provider can log or report it. The cycle is already recorded, so a resend of the same `CycleReference` returns `false` and does not retry the order. #### Project Structure 12. Use `Microsoft.NET.Sdk.Razor` as SDK. 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 43ced73d4..68bfc0fff 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -38,27 +38,50 @@ await mediator.Send(new PlaceRecurringCycleOrderCommand { claim.RecurringPayment.Id, claim.Cycle.CycleNumber, request.CycleReference); await AddNote(claim.RecurringPayment, $"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order could not be created: {e.Message}"); - // the failure must reach the provider, so the gateway resends and an operator sees it + // the failure must reach the provider so it can log or report it; the claim is already + // recorded, so a resend of the same cycle is a no-op and does not retry the order throw; } if (claim.Completed) { - var result = await paymentService.CancelRecurringPayment(claim.RecurringPayment); + IEnumerable errors; + try + { + var result = await paymentService.CancelRecurringPayment(claim.RecurringPayment); + errors = result.Success ? [] : result.Errors; + } + catch (Exception e) + { + // a throw is treated as a refusal: the claim is recorded and a resend is a no-op, so the note is the only trace + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", + claim.RecurringPayment.Id); + errors = [e.Message]; + } + // the status stays Completed: every cycle is paid, only the gateway schedule may still run - if (!result.Success) + if (errors.Any()) await AddNote(claim.RecurringPayment, - $"The recurring payment is completed, but the payment gateway did not confirm it stopped charging: {string.Join(", ", result.Errors)}"); + $"The recurring payment is completed, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); } return true; } - private Task AddNote(RecurringPayment recurringPayment, string note) + private async Task AddNote(RecurringPayment recurringPayment, string note) { - return orderService.InsertOrderNote(new OrderNote { - OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, - CreatedOnUtc = DateTime.UtcNow - }); + try + { + await orderService.InsertOrderNote(new OrderNote { + OrderId = recurringPayment.InitialOrderId, Note = note, DisplayToCustomer = false, + CreatedOnUtc = DateTime.UtcNow + }); + } + catch (Exception e) + { + // the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded cycle + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}", + recurringPayment.Id, note); + } } } 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 5e32dab52..37e2abd47 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 @@ -192,6 +192,48 @@ public async Task CycleCommand_CompletedAndProviderRefuses_NotesItOnTheInitialOr Times.Once); } + [TestMethod] + public async Task CycleCommand_NoteCannotBeWritten_StillThrowsTheOriginalException() + { + SetupClaim(2, false); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("boom")); + _orderService.Setup(x => x.InsertOrderNote(It.IsAny())).ThrowsAsync(new TimeoutException("db")); + + var e = await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + Assert.AreEqual("boom", e.Message); + } + + [TestMethod] + public async Task CycleCommand_CompletedAndNoteCannotBeWritten_StillSucceeds() + { + SetupClaim(3, true); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + _orderService.Setup(x => x.InsertOrderNote(It.IsAny())).ThrowsAsync(new TimeoutException("db")); + + Assert.IsTrue(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_CompletedAndProviderThrows_NotesItAndDoesNotRethrow() + { + SetupClaim(3, true); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ThrowsAsync(new HttpRequestException("network down")); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == "o1" && n.Note == + "The recurring payment is completed, but the payment gateway did not confirm it stopped charging: network down")), + Times.Once); + } + [TestMethod] public async Task CycleCommand_WithoutRecurringPaymentId_Throws() { From 97862b6d41ee4851b23c6cc6e2b1631cfb481e86 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:50:33 +0100 Subject: [PATCH 07/10] Record a recurring cycle the gateway charged less for as a partial payment --- .../PlaceRecurringCycleOrderCommandHandler.cs | 37 ++++++++++----- ...eRecurringCycleOrderCommandHandlerTests.cs | 45 +++++++++++++++++-- 2 files changed, 69 insertions(+), 13 deletions(-) diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs index 9a3391080..fe5b01fa3 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Grand.Business.Checkout.Extensions; using Grand.Business.Core.Commands.Checkout.Orders; using Grand.Business.Core.Commands.Messages.Common; @@ -86,21 +87,37 @@ await mediator.Send(new OrderNotificationCommand { Order = order, Customer = cus await mediator.Publish(new OrderPlacedEvent(order), cancellationToken); - await mediator.Send(new MarkAsPaidCommand { - PaymentTransaction = paymentTransaction, - Amount = cycle.Amount, - Reference = cycle.ProviderReference, - CreatedBy = recurringPayment.PaymentMethodSystemName - }, cancellationToken); - - // the order is paid with what the gateway charged; a price change at the gateway shows here - if (Math.Round(cycle.Amount, 2) != Math.Round(order.OrderTotal, 2)) + // the order is paid with what the gateway charged: a smaller charge must not show as fully paid + var charged = Math.Round(cycle.Amount, 2); + var total = Math.Round(order.OrderTotal, 2); + if (charged >= total) + await mediator.Send(new MarkAsPaidCommand { + PaymentTransaction = paymentTransaction, + Amount = cycle.Amount, + Reference = cycle.ProviderReference, + CreatedBy = recurringPayment.PaymentMethodSystemName + }, cancellationToken); + else if (charged > 0) + await mediator.Send(new PartiallyPaidOfflineCommand { + PaymentTransaction = paymentTransaction, + AmountToPaid = cycle.Amount, + Reference = cycle.ProviderReference, + CreatedBy = recurringPayment.PaymentMethodSystemName + }, cancellationToken); + + // a price change at the gateway shows here + if (charged != total) await InsertNote(order.Id, - $"The payment gateway charged {cycle.Amount} for this cycle; the order total is {order.OrderTotal}"); + $"The payment gateway charged {Format(charged, order)} for this cycle; the order total is {Format(total, order)}"); return order; } + private static string Format(double amount, Order order) + { + return $"{amount.ToString("0.00", CultureInfo.InvariantCulture)} {order.CustomerCurrencyCode}"; + } + private Task InsertNote(string orderId, string note) { return orderService.InsertOrderNote(new OrderNote { diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs index db611ea6e..7afe7b82d 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs @@ -118,6 +118,9 @@ public void Init() _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) .Callback, CancellationToken>((_, _) => _calls.Add("MarkAsPaid")) .ReturnsAsync(true); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback, CancellationToken>((_, _) => _calls.Add("PartiallyPaidOffline")) + .ReturnsAsync(true); } private Task Place() @@ -231,17 +234,53 @@ public async Task Handle_AddsTheCycleNote() } [TestMethod] - public async Task Handle_GatewayAmountDiffers_AddsANote() + public async Task Handle_GatewayChargedLess_RecordsAPartialPaymentAndANote() { _cycle.Amount = 95; await Place(); Assert.AreEqual(2, _notes.Count); - Assert.AreEqual("The payment gateway charged 95 for this cycle; the order total is 100", _notes[1].Note); + Assert.AreEqual("The payment gateway charged 95.00 EUR for this cycle; the order total is 100.00 EUR", + _notes[1].Note); Assert.AreEqual("cycle-order", _notes[1].OrderId); // the note comes after the payment is recorded - Assert.AreEqual("MarkAsPaid", _calls[^1]); + Assert.AreEqual("PartiallyPaidOffline", _calls[^1]); + _mediatorMock.Verify(x => x.Send(It.Is(c => + c.PaymentTransaction == _insertedTransaction && c.AmountToPaid == 95 && c.Reference == "in_2" && + c.CreatedBy == "Payments.Stripe"), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_GatewayChargedNothing_RecordsNoPayment() + { + _cycle.Amount = 0; + + await Place(); + + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + Assert.AreEqual(2, _notes.Count); + Assert.AreEqual("The payment gateway charged 0.00 EUR for this cycle; the order total is 100.00 EUR", + _notes[1].Note); + } + + [TestMethod] + public async Task Handle_GatewayChargedMore_MarksPaidAndAddsANote() + { + _cycle.Amount = 105; + + await Place(); + + _mediatorMock.Verify(x => x.Send(It.Is(c => c.Amount == 105), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + Assert.AreEqual("The payment gateway charged 105.00 EUR for this cycle; the order total is 100.00 EUR", + _notes[1].Note); } [TestMethod] From 9a21d37f8ee3d2f95aaeef889a93fb50307d3755 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:50:33 +0100 Subject: [PATCH 08/10] Pin every order item property in the recurring cycle copy test --- .../Extensions/RecurringCycleOrderTests.cs | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs index 913c59fb8..bdf63a6bd 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs @@ -263,6 +263,74 @@ public void Copy_EveryOrderPropertyIsCopiedOrDeliberatelyReset() } } + [TestMethod] + public void Copy_EveryOrderItemPropertyIsCopiedOrDeliberatelyReset() + { + var properties = typeof(OrderItem).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.SetMethod is { IsPublic: true }).ToList(); + var reset = new[] { + nameof(OrderItem.Id), nameof(OrderItem.OrderItemGuid), nameof(OrderItem.OpenQty), + nameof(OrderItem.ShipQty), nameof(OrderItem.CancelQty), nameof(OrderItem.CancelAmount), + nameof(OrderItem.Status), nameof(OrderItem.ReturnQty), nameof(OrderItem.DownloadCount), + nameof(OrderItem.IsDownloadActivated), nameof(OrderItem.LicenseDownloadId), + nameof(OrderItem.CreatedOnUtc) + }; + foreach (var name in reset) + Assert.IsTrue(properties.Any(p => p.Name == name), $"{name} is not a settable OrderItem property"); + + var source = new OrderItem(); + var n = 1; + foreach (var property in properties) + property.SetValue(source, Distinct(property.PropertyType, property.Name, n++)); + var initial = new Order(); + initial.OrderItems.Add(source); + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn).OrderItems.Single(); + + foreach (var property in properties) + { + var actual = property.GetValue(copy); + switch (property.Name) + { + case nameof(OrderItem.Id): + Assert.IsFalse(string.IsNullOrEmpty((string)actual)); + Assert.AreNotEqual(source.Id, actual); + break; + case nameof(OrderItem.OrderItemGuid): + Assert.AreNotEqual(Guid.Empty, actual); + Assert.AreNotEqual(source.OrderItemGuid, actual); + break; + case nameof(OrderItem.OpenQty): + Assert.AreEqual(source.Quantity, actual); + break; + case nameof(OrderItem.ShipQty): + case nameof(OrderItem.CancelQty): + case nameof(OrderItem.ReturnQty): + case nameof(OrderItem.DownloadCount): + Assert.AreEqual(0, actual, property.Name); + break; + case nameof(OrderItem.CancelAmount): + Assert.AreEqual(0d, actual); + break; + case nameof(OrderItem.Status): + Assert.AreEqual(OrderItemStatus.Open, actual); + break; + case nameof(OrderItem.IsDownloadActivated): + Assert.AreEqual(false, actual); + break; + case nameof(OrderItem.LicenseDownloadId): + Assert.AreEqual("", actual); + break; + case nameof(OrderItem.CreatedOnUtc): + Assert.AreEqual(CreatedOn, actual); + break; + default: + AssertSameValue(property.GetValue(source), actual, property.Name); + break; + } + } + } + private static object Distinct(Type type, string name, int n) { type = Nullable.GetUnderlyingType(type) ?? type; From b588791a9b4d796d0b88204d5e348e8792abdeef Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 20:50:34 +0100 Subject: [PATCH 09/10] Stop the gateway even when the last recurring cycle cannot be placed, and require a cycle reference --- .ai/skills/plugin-payment.md | 4 +- ...cordRecurringPaymentCycleCommandHandler.cs | 67 +++++++---- ...rdRecurringPaymentFailureCommandHandler.cs | 1 + .../Orders/RecurringPaymentService.cs | 4 + ...ordRecurringPaymentCommandHandlersTests.cs | 112 +++++++++++++++--- .../Orders/RecurringPaymentServiceTests.cs | 29 +++++ 6 files changed, 175 insertions(+), 42 deletions(-) diff --git a/.ai/skills/plugin-payment.md b/.ai/skills/plugin-payment.md index ea43a187b..438634dad 100644 --- a/.ai/skills/plugin-payment.md +++ b/.ai/skills/plugin-payment.md @@ -65,11 +65,11 @@ Do not use this skill for order processing business logic outside the payment fl - The provider, not the shop, runs the schedule: the gateway charges every cycle, retries failures and reports each cycle to the shop, the first one (the initial order's payment) included: `CyclesPaid` stays 0 until it does. A cart with a recurring product is offered only methods whose `SupportRecurringPayment()` returns `true`, and the order is refused for any other method. - Return `SupportRecurringPayment() => true` only when the payment flow starts the gateway's schedule for a recurring order and `CancelRecurringPayment` stops it. Both members have defaults (`false`, and an error result), so a provider without recurring support implements neither. - Never report "cancelled" from `CancelRecurringPayment` unless the gateway confirmed it: on an error result the shop keeps the recurring payment running. -- A provider reports to the shop with three mediator commands (`Grand.Business.Core.Commands.Checkout.Orders`): `RecordRecurringPaymentCycleCommand` (a cycle was paid; the shop places the cycle order from the second cycle on and, once every cycle is paid, calls `CancelRecurringPayment` to stop the gateway), `RecordRecurringPaymentFailureCommand` and `RecordRecurringPaymentEndedCommand` (the gateway ended it). +- A provider reports to the shop with three mediator commands (`Grand.Business.Core.Commands.Checkout.Orders`): `RecordRecurringPaymentCycleCommand` (a cycle was paid; the shop places the cycle order from the second cycle on and, whenever the recurring payment is completed or cancelled after the cycle is recorded, calls `CancelRecurringPayment` to stop the gateway), `RecordRecurringPaymentFailureCommand` and `RecordRecurringPaymentEndedCommand` (the gateway ended it). - Pass `RecurringPayment.Id` to the gateway as metadata when the schedule starts, and send it back as `RecurringPaymentId` in every command. The webhook must verify the gateway signature before sending any of them. - `CycleReference` is the gateway's invoice or charge id, so a resent webhook is recorded once and the command returns `false`. `ProviderReference` is the subscription id. - `Amount` uses the units of `MarkAsPaidCommand.Amount`: the order total in the order's currency, as Stripe Checkout passes it (`paymentIntent.Amount / 100.0`). -- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order for staff and rethrows so the provider can log or report it. The cycle is already recorded, so a resend of the same `CycleReference` returns `false` and does not retry the order. +- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order for staff (the order may exist but be unpaid), stops the gateway when the payment is completed, and rethrows so the provider can log or report it. `CycleReference` is required, and `Amount` must not be negative. The cycle is already recorded, so a resend of the same `CycleReference` returns `false` and does not retry the order. A cycle the gateway charged less for is recorded as a partial payment, so its order stays partially paid, and a cycle of 0 records no payment; an order note says so. #### Project Structure 12. Use `Microsoft.NET.Sdk.Razor` as SDK. 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 68bfc0fff..4ce731fb4 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -1,3 +1,4 @@ +using System.Runtime.ExceptionServices; using Grand.Business.Core.Commands.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; @@ -18,13 +19,20 @@ public class RecordRecurringPaymentCycleCommandHandler( public async Task Handle(RecordRecurringPaymentCycleCommand request, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); + if (double.IsNaN(request.Amount) || request.Amount < 0) + throw new ArgumentOutOfRangeException(nameof(request), "The cycle amount must be zero or more"); var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); if (claim == null) return false; + // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable + cancellationToken = CancellationToken.None; + // the first cycle is the initial order's own payment, which the provider marks paid on its existing path + ExceptionDispatchInfo placementFailure = null; if (claim.Cycle.CycleNumber > 1) try { @@ -34,40 +42,47 @@ await mediator.Send(new PlaceRecurringCycleOrderCommand { } catch (Exception e) { - logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order of cycle {CycleNumber} ({CycleReference}) could not be created", - claim.RecurringPayment.Id, claim.Cycle.CycleNumber, request.CycleReference); + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order {OrderId} of cycle {CycleNumber} ({CycleReference}) could not be placed or marked paid", + claim.RecurringPayment.Id, claim.Cycle.OrderId, claim.Cycle.CycleNumber, request.CycleReference); + // the order may exist already (the failure can come after it was inserted), so the note names it await AddNote(claim.RecurringPayment, - $"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order could not be created: {e.Message}"); - // the failure must reach the provider so it can log or report it; the claim is already - // recorded, so a resend of the same cycle is a no-op and does not retry the order - throw; + $"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order {claim.Cycle.OrderId} could not be placed or marked paid: {e.Message}"); + // the failure must reach the provider so it can log or report it, but only after the gateway was + // asked to stop: the claim is recorded, so a resend is a no-op and would never stop it + placementFailure = ExceptionDispatchInfo.Capture(e); } - if (claim.Completed) - { - IEnumerable errors; - try - { - var result = await paymentService.CancelRecurringPayment(claim.RecurringPayment); - errors = result.Success ? [] : result.Errors; - } - catch (Exception e) - { - // a throw is treated as a refusal: the claim is recorded and a resend is a no-op, so the note is the only trace - logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", - claim.RecurringPayment.Id); - errors = [e.Message]; - } + // a cycle claimed while the payment is already completed or cancelled means the gateway still charges + if (claim.RecurringPayment.Status is RecurringPaymentStatus.Completed or RecurringPaymentStatus.Cancelled) + await StopTheGateway(claim.RecurringPayment); - // the status stays Completed: every cycle is paid, only the gateway schedule may still run - if (errors.Any()) - await AddNote(claim.RecurringPayment, - $"The recurring payment is completed, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); - } + placementFailure?.Throw(); return true; } + private async Task StopTheGateway(RecurringPayment recurringPayment) + { + IEnumerable errors; + try + { + var result = await paymentService.CancelRecurringPayment(recurringPayment); + errors = result.Success ? [] : result.Errors; + } + catch (Exception e) + { + // a throw is treated as a refusal: the claim is recorded and a resend is a no-op, so the note is the only trace + logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging", + recurringPayment.Id); + errors = [e.Message]; + } + + // the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run + if (errors.Any()) + await AddNote(recurringPayment, + $"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}"); + } + private async Task AddNote(RecurringPayment recurringPayment, string note) { try 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 78dc06ee7..e2edf074f 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -10,6 +10,7 @@ public class RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentServic public async Task Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, request.Reason); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 358940094..f9f07426e 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -39,6 +39,8 @@ public virtual async Task UpdateRecurringPayment(RecurringPayment recurringPayme public virtual async Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc) { + ArgumentException.ThrowIfNullOrEmpty(cycleReference); + RecurringPayment recurringPayment; RecurringPaymentCycle cycle; var completed = false; @@ -89,6 +91,8 @@ recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPay public virtual async Task RecordFailure(string recurringPaymentId, string cycleReference, string reason) { + ArgumentException.ThrowIfNullOrEmpty(cycleReference); + RecurringPayment recurringPayment; bool enteredPastDue; 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 37e2abd47..7bedd8994 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 @@ -87,14 +87,13 @@ private static RecordRecurringPaymentCycleCommand CycleCommand() }; } - private void SetupClaim(int cycleNumber, bool completed) + private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = RecurringPaymentStatus.Active) { var claim = new RecurringCycleClaim { RecurringPayment = new RecurringPayment { - Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test" + Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test", Status = status }, - Cycle = new RecurringPaymentCycle { CycleNumber = cycleNumber, OrderId = "o2" }, - Completed = completed + Cycle = new RecurringPaymentCycle { CycleNumber = cycleNumber, OrderId = "o2" } }; _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)).ReturnsAsync(claim); } @@ -115,7 +114,7 @@ public async Task CycleCommand_AlreadyRecorded_DoesNothing() [TestMethod] public async Task CycleCommand_FirstCycle_PlacesNoOrder() { - SetupClaim(1, false); + SetupClaim(1); var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); @@ -127,7 +126,7 @@ public async Task CycleCommand_FirstCycle_PlacesNoOrder() [TestMethod] public async Task CycleCommand_LaterCycle_PlacesTheCycleOrder() { - SetupClaim(2, false); + SetupClaim(2); var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); @@ -139,7 +138,7 @@ public async Task CycleCommand_LaterCycle_PlacesTheCycleOrder() [TestMethod] public async Task CycleCommand_OrderCannotBeCreated_NotesItOnTheInitialOrderAndThrows() { - SetupClaim(2, false); + SetupClaim(2); _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("boom")); @@ -147,14 +146,15 @@ await Assert.ThrowsExactlyAsync(() => CycleHandler().Handle(CycleCommand(), CancellationToken.None)); _orderService.Verify(x => x.InsertOrderNote(It.Is(n => - n.OrderId == "o1" && n.Note.Contains("in_2") && n.Note.Contains("boom") && !n.DisplayToCustomer)), + n.OrderId == "o1" && !n.DisplayToCustomer && n.Note == + "Cycle 2 was paid at the payment gateway (in_2), but its order o2 could not be placed or marked paid: boom")), Times.Once); } [TestMethod] public async Task CycleCommand_Completed_AsksTheProviderToStop() { - SetupClaim(3, true); + SetupClaim(3, RecurringPaymentStatus.Completed); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) .ReturnsAsync(new CancelRecurringPaymentResult()); @@ -168,7 +168,7 @@ public async Task CycleCommand_Completed_AsksTheProviderToStop() [TestMethod] public async Task CycleCommand_NotCompleted_DoesNotAskTheProviderToStop() { - SetupClaim(3, false); + SetupClaim(3); await CycleHandler().Handle(CycleCommand(), CancellationToken.None); @@ -178,7 +178,7 @@ public async Task CycleCommand_NotCompleted_DoesNotAskTheProviderToStop() [TestMethod] public async Task CycleCommand_CompletedAndProviderRefuses_NotesItOnTheInitialOrder() { - SetupClaim(3, true); + SetupClaim(3, RecurringPaymentStatus.Completed); var refusal = new CancelRecurringPaymentResult(); refusal.AddError("no way"); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); @@ -195,7 +195,7 @@ public async Task CycleCommand_CompletedAndProviderRefuses_NotesItOnTheInitialOr [TestMethod] public async Task CycleCommand_NoteCannotBeWritten_StillThrowsTheOriginalException() { - SetupClaim(2, false); + SetupClaim(2); _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("boom")); _orderService.Setup(x => x.InsertOrderNote(It.IsAny())).ThrowsAsync(new TimeoutException("db")); @@ -209,7 +209,7 @@ public async Task CycleCommand_NoteCannotBeWritten_StillThrowsTheOriginalExcepti [TestMethod] public async Task CycleCommand_CompletedAndNoteCannotBeWritten_StillSucceeds() { - SetupClaim(3, true); + SetupClaim(3, RecurringPaymentStatus.Completed); var refusal = new CancelRecurringPaymentResult(); refusal.AddError("no way"); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); @@ -221,7 +221,7 @@ public async Task CycleCommand_CompletedAndNoteCannotBeWritten_StillSucceeds() [TestMethod] public async Task CycleCommand_CompletedAndProviderThrows_NotesItAndDoesNotRethrow() { - SetupClaim(3, true); + SetupClaim(3, RecurringPaymentStatus.Completed); _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) .ThrowsAsync(new HttpRequestException("network down")); @@ -234,6 +234,90 @@ public async Task CycleCommand_CompletedAndProviderThrows_NotesItAndDoesNotRethr Times.Once); } + [TestMethod] + public async Task CycleCommand_ClaimedWhileCancelled_AsksTheProviderToStopAndNotesTheRefusal() + { + SetupClaim(3, RecurringPaymentStatus.Cancelled); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + + Assert.IsTrue(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.Note == "The recurring payment is cancelled, but the payment gateway did not confirm it stopped charging: no way")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_FinalOrderCannotBePlaced_StillStopsTheGatewayAndThrowsTheOriginalException() + { + SetupClaim(3, RecurringPaymentStatus.Completed); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("boom")); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + var e = await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + Assert.AreEqual("boom", e.Message); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + } + + [TestMethod] + public async Task CycleCommand_AfterTheClaim_IgnoresTheRequestCancellation() + { + SetupClaim(2); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + await CycleHandler().Handle(CycleCommand(), cts.Token); + + _mediator.Verify(x => x.Send(It.IsAny(), CancellationToken.None), Times.Once); + } + + [TestMethod] + public async Task CycleCommand_WithoutCycleReference_Throws() + { + var command = CycleCommand(); + command.CycleReference = ""; + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(command, CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_NegativeAmount_Throws() + { + var command = CycleCommand(); + command.Amount = -1; + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(command, CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_NaNAmount_Throws() + { + var command = CycleCommand(); + command.Amount = double.NaN; + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(command, CancellationToken.None)); + } + + [TestMethod] + public async Task FailureCommand_WithoutCycleReference_Throws() + { + var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + + await Assert.ThrowsExactlyAsync(() => + handler.Handle(new RecordRecurringPaymentFailureCommand { RecurringPaymentId = "rp1", CycleReference = "" }, + CancellationToken.None)); + } + [TestMethod] public async Task CycleCommand_WithoutRecurringPaymentId_Throws() { 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 dee261f6e..dbb56ddee 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -202,6 +202,35 @@ public async Task ClaimCycle_AfterCancelled_RecordsTheCycleAndKeepsTheStatus() Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); } + [TestMethod] + public async Task ClaimCycle_ReachingTotalCyclesAfterCancelled_KeepsTheStatusAndIsNotCompleted() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 1, 2); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsNotNull(claim); + Assert.IsFalse(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_WithoutCycleReference_Throws() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + await Assert.ThrowsExactlyAsync(() => + _service.ClaimCycle(rp.Id, "sub_1", "", 10, DateTime.UtcNow, null)); + } + + [TestMethod] + public async Task RecordFailure_WithoutCycleReference_Throws() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + await Assert.ThrowsExactlyAsync(() => _service.RecordFailure(rp.Id, "", "declined")); + } + [TestMethod] public async Task ClaimCycle_UnknownRecurringPayment_ReturnsNull() { From 08d72917d2873d57d1f13cc5bf5b154f8d6b9099 Mon Sep 17 00:00:00 2001 From: support Date: Fri, 20 Nov 2026 23:17:49 +0100 Subject: [PATCH 10/10] Add the gift vouchers spent on the initial order back to a recurring cycle order total --- .../PlaceRecurringCycleOrderCommandHandler.cs | 9 ++++++- .../Extensions/RecurringCycleOrder.cs | 9 ++++--- ...eRecurringCycleOrderCommandHandlerTests.cs | 25 ++++++++++++++++++- .../Extensions/RecurringCycleOrderTests.cs | 23 ++++++++++++----- 4 files changed, 55 insertions(+), 11 deletions(-) diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs index fe5b01fa3..44a8a76b9 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs @@ -4,6 +4,7 @@ using Grand.Business.Core.Commands.Messages.Common; using Grand.Business.Core.Events.Checkout.Orders; using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.GiftVouchers; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Customers; @@ -21,6 +22,7 @@ public class PlaceRecurringCycleOrderCommandHandler( IProductService productService, IInventoryManageService inventoryManageService, ICustomerService customerService, + IGiftVoucherService giftVoucherService, IMediator mediator, ILogger logger) : IRequestHandler @@ -35,8 +37,13 @@ public async Task Handle(PlaceRecurringCycleOrderCommand request, Cancell throw new GrandException( $"The initial order {recurringPayment.InitialOrderId} of recurring payment {recurringPayment.Id} was not found"); + // a gift voucher paid part of the first cycle only + var giftVouchersAmount = (await giftVoucherService.GetAllGiftVoucherUsageHistory(initialOrder.Id)) + .Sum(x => x.UsedValue); + var code = await mediator.Send(new PrepareOrderCodeCommand(), cancellationToken); - var order = RecurringCycleOrder.Copy(initialOrder, cycle.OrderId, cycle.CycleNumber, code, DateTime.UtcNow); + var order = RecurringCycleOrder.Copy(initialOrder, cycle.OrderId, cycle.CycleNumber, code, DateTime.UtcNow, + giftVouchersAmount); // the gateway already took the money, so the transaction is a real one from the start var paymentTransaction = new PaymentTransaction { diff --git a/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs index f63c81a6a..0dfafdc50 100644 --- a/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs +++ b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs @@ -11,10 +11,12 @@ public static class RecurringCycleOrder /// The order that pays one later cycle of a recurring payment: the order the customer placed, at its prices, /// as a new unpaid order. Everything that describes what was bought and what it costs is copied; identity, /// dates, statuses, payment and shipping progress and the loyalty points spent are those of a new order. - /// Loyalty points spent on the initial order are not spent again, so their amount is added back to the total. + /// Loyalty points and gift vouchers spent on the initial order are not spent again, so their amounts are added + /// back to the total. /// + /// The gift voucher amount redeemed on the initial order public static Order Copy(Order initialOrder, string orderId, int cycleNumber, string orderCode, - DateTime createdOnUtc) + DateTime createdOnUtc, double giftVouchersAmount) { var order = new Order { Id = orderId, @@ -37,7 +39,8 @@ public static Order Copy(Order initialOrder, string orderId, int cycleNumber, st RedeemedLoyaltyPointsAmount = 0, LoyaltyPointsWereAdded = false, CalcLoyaltyPoints = 0, - OrderTotal = Math.Round(initialOrder.OrderTotal + initialOrder.RedeemedLoyaltyPointsAmount, 6), + OrderTotal = Math.Round( + initialOrder.OrderTotal + initialOrder.RedeemedLoyaltyPointsAmount + giftVouchersAmount, 6), Deleted = false, Imported = false, diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs index 7afe7b82d..0fbbd5254 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs @@ -3,6 +3,7 @@ using Grand.Business.Core.Commands.Messages.Common; using Grand.Business.Core.Events.Checkout.Orders; using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.GiftVouchers; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Customers; @@ -30,6 +31,7 @@ public class PlaceRecurringCycleOrderCommandHandlerTests private Mock _paymentTransactionServiceMock; private Mock _productServiceMock; private Mock _customerServiceMock; + private Mock _giftVoucherServiceMock; private Order _initialOrder; private Customer _customer; @@ -53,10 +55,13 @@ public void Init() _productServiceMock = new Mock(); _inventoryMock = new Mock(); _customerServiceMock = new Mock(); + _giftVoucherServiceMock = new Mock(); + _giftVoucherServiceMock.Setup(x => x.GetAllGiftVoucherUsageHistory(It.IsAny())) + .ReturnsAsync(new List()); _handler = new PlaceRecurringCycleOrderCommandHandler(_orderServiceMock.Object, _paymentTransactionServiceMock.Object, _productServiceMock.Object, _inventoryMock.Object, - _customerServiceMock.Object, _mediatorMock.Object, + _customerServiceMock.Object, _giftVoucherServiceMock.Object, _mediatorMock.Object, new Mock>().Object); _initialOrder = new Order { @@ -313,4 +318,22 @@ public async Task Handle_InitialOrderMissing_Throws() Assert.AreEqual("The initial order o1 of recurring payment rp1 was not found", exception.Message); _orderServiceMock.Verify(x => x.InsertOrder(It.IsAny()), Times.Never); } + + [TestMethod] + public async Task Handle_GiftVouchersSpentOnTheInitialOrderAreAddedBackToTheTotal() + { + _giftVoucherServiceMock.Setup(x => x.GetAllGiftVoucherUsageHistory("o1")) + .ReturnsAsync(new List { + new() { UsedWithOrderId = "o1", UsedValue = 15 }, + new() { UsedWithOrderId = "o1", UsedValue = 5 } + }); + _cycle.Amount = 120; + + var order = await Place(); + + Assert.AreEqual(120, order.OrderTotal); + Assert.AreEqual(120, _insertedTransaction.TransactionAmount); + Assert.IsTrue(_calls.Contains("MarkAsPaid")); + Assert.IsFalse(_notes.Any(n => n.Note.Contains("charged"))); + } } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs index bdf63a6bd..e0c9c3f94 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs @@ -118,7 +118,7 @@ public void Copy_KeepsPricesAddressesAndItems() var initial = Initial(); initial.OrderTaxes.Add(new OrderTax { Percent = 23, Amount = 22.4 }); - var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); Assert.AreEqual(120, copy.OrderTotal); Assert.AreEqual(4.3, copy.CurrencyRate); @@ -160,7 +160,7 @@ public void Copy_IsANewUnpaidOrderLinkedToTheInitialOne() { var initial = Initial(); - var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); Assert.AreEqual("c2", copy.Id); Assert.AreEqual("ABC", copy.Code); @@ -198,20 +198,31 @@ public void Copy_LoyaltyPointsSpentOnTheInitialOrderAreNotSpentAgain() initial.RedeemedLoyaltyPoints = 100; initial.RedeemedLoyaltyPointsAmount = 10; - var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); Assert.AreEqual(100, copy.OrderTotal); Assert.AreEqual(0, copy.RedeemedLoyaltyPoints); Assert.AreEqual(0, copy.RedeemedLoyaltyPointsAmount); } + [TestMethod] + public void Copy_GiftVouchersSpentOnTheInitialOrderAreNotSpentAgain() + { + var initial = Initial(); + initial.OrderTotal = 75; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 25); + + Assert.AreEqual(100, copy.OrderTotal); + } + [TestMethod] public void Copy_NothingToShip_ShippingNotRequired() { var initial = Initial(); foreach (var item in initial.OrderItems) item.IsShipEnabled = false; - var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); Assert.AreEqual(ShippingStatus.ShippingNotRequired, copy.ShippingStatusId); } @@ -233,7 +244,7 @@ public void Copy_EveryOrderPropertyIsCopiedOrDeliberatelyReset() initial.OrderTotal = 90; initial.RedeemedLoyaltyPointsAmount = 10; - var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn); + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); foreach (var property in properties) { @@ -285,7 +296,7 @@ public void Copy_EveryOrderItemPropertyIsCopiedOrDeliberatelyReset() var initial = new Order(); initial.OrderItems.Add(source); - var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn).OrderItems.Single(); + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0).OrderItems.Single(); foreach (var property in properties) {