Repository navigation
Recurring payments: provider commands and one order per paid cycle (slice 2 of 5) - #1076
Merged
Merged
Conversation
added 9 commits
November 20, 2026 19:57
… and require a cycle reference
| }, cancellationToken); | ||
|
|
||
| // a price change at the gateway shows here | ||
| if (charged != total) |
| // the note comes after the payment is recorded | ||
| Assert.AreEqual("PartiallyPaidOffline", _calls[^1]); | ||
| _mediatorMock.Verify(x => x.Send(It.Is<PartiallyPaidOfflineCommand>(c => | ||
| c.PaymentTransaction == _insertedTransaction && c.AmountToPaid == 95 && c.Reference == "in_2" && |
Comment on lines
+72
to
+75
| catch (Exception exc) | ||
| { | ||
| logger.LogWarning(exc, "Could not update the sold count of product {ProductId}", product.Id); | ||
| } |
Comment on lines
+43
to
+53
| catch (Exception e) | ||
| { | ||
| 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 {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); | ||
| } |
Comment on lines
+72
to
+78
| 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]; | ||
| } |
Comment on lines
+95
to
+100
| 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); | ||
| } |
…cycle order total
This was referenced Nov 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Type: feature
Issue
Slice 1 (#1075) records a
Pendingrecurring payment when a recurring order is placed, but nothing can report what the gateway does afterwards: a paid cycle, a failed one, or a subscription the gateway ended. No order is created for a cycle the gateway charges, so revenue, stock, shipping and invoices for later cycles live outside the shop.This is slice 2 of 5 of recurring payments (payments roadmap P5). The gateway runs the schedule; this slice is how the shop reacts.
Solution
RecurringPaymentId(the provider passes the recurring payment's id to the gateway as metadata):RecordRecurringPaymentCycleCommand: a paid cycle (subscription reference,CycleReference= the gateway's invoice id, amount, paid date, next payment date).RecordRecurringPaymentFailureCommand: a failed cycle →PastDuewith the last error. It returnstrueonly on the transition intoPastDue, so slice 3 can e-mail once rather than on every gateway retry. A failure for a cycle that is already paid (an out-of-order webhook) is ignored.RecordRecurringPaymentEndedCommand: the gateway ended it →Cancelled, with the payment method asCancelledBy.RecurringPaymentService.ClaimCyclereads, checks and writes under anIResourceLockkey per recurring payment (RecurringPayment:{id}). A resent or concurrent webhook with the sameCycleReferencedoes nothing, so one gateway cycle makes one order. The spec asked for a conditional Mongo update.IRepository.UpdateOneAsyncreturns no match count, and the lock works on Mongo and LiteDB, across instances. The failure and ended commands take the same lock, so their whole-document writes cannot drop a cycle claimed at the same moment.Active, the subscription reference stored, no new order.PastDue→Active.TotalCyclesgivesCompleted.Completed/Cancelledis still recorded with its order, because the money is taken, and the status stays as it is.PlaceRecurringCycleOrderCommand) is a copy of the initial order at its prices, made byRecurringCycleOrder.Copy, a pure function. A reflection test pins everyOrderandOrderItemproperty as either copied or deliberately reset, so a new field cannot be skipped by accident. The order has a new id, number, code andOrderGuid, plusInitialOrderIdandRecurringCycleNumber. Loyalty points and gift vouchers spent on the initial order are not spent again (the total adds their amounts back). The copy then takes the normal path:IInventoryManageService.AdjustReserved(low stock never blocks it, since the money is taken);Soldcounter;OrderPlacedEvent;Discounts, gift vouchers, loyalty point redemption and the order placement rules are not evaluated again.
PartiallyPaidOfflineCommand). At 0, no payment is recorded. Whenever the amount differs from the total, an order note gives both amounts.IPaymentService.CancelRecurringPaymentwhenever a cycle leaves the recurring paymentCompletedorCancelled: the cycle that completes it, or a charge after the fact. It does so even when that cycle's order could not be placed, so the shop's count wins.CancellationToken.None, so an aborted webhook request cannot leave it half done..ai/skills/plugin-payment.mddescribes the provider side: the three commands, the metadata, idempotency by invoice id, the amount units (those ofMarkAsPaidCommand.Amount), and that the first cycle is the initial order's own payment.Nothing calls these commands yet: the first provider that charges in cycles is the Stripe stage, after slice 5. Recurring products stay unbuyable until then.
Persisted data: no new collection or index (every read is by id), no migration, no resources. New writes to existing
RecurringPaymentandOrderdocuments only.Decisions taken in the plan, for review:
Completed/Cancelledis recorded with its order, and the gateway is asked to stop again.Breaking changes
IPaymentServicehas a new memberCancelRecurringPayment(RecurringPayment). This only affects custom implementations of the service, not payment plugins.IRecurringPaymentServicehas new membersClaimCycle,RecordFailureandRecordEnded.RecurringPaymentServicetakes a new constructor parameter,IResourceLock. This only affects custom implementations, or code that constructs it by hand.Follow-ups (not in this PR)
UpdateRecurringPaymentis still a public whole-document write without the lock. Nothing calls it. Slice 3's cancel must write under the lock, and the method should then be locked or removed.Testing
No shipped provider sends these commands yet, so this slice is checked by tests only:
RecurringPaymentServiceTests, on a real Mongo repository and lock: first cycle; later cycle; resend; two concurrent deliveries claiming once; completion;TotalCycles = 0; a charge afterCancelled; failure transitions; ended.RecurringCycleOrderTests: copied versus reset fields, loyalty points, gift vouchers, and the reflection pins onOrderandOrderItem.PlaceRecurringCycleOrderCommandHandlerTests: transaction, unconditional stock, step order, paid / partially paid / zero, the amount note, a deleted initial order.RecordRecurringPaymentCommandHandlersTests:Completed/Cancelledand after a failed last cycle;CycleReference.Automated:
dotnet build GrandNode.slnx(0 errors);Grand.Business.Checkout.Tests1034/1034,Grand.Web.Tests624/624.