Skip to content

Recurring payments: provider commands and one order per paid cycle (slice 2 of 5) - #1076

Merged
KrzysztofPajak merged 10 commits into
developfrom
feature/recurring-payments-cycles
Nov 21, 2026
Merged

KrzysztofPajak merged 10 commits into
developfrom
feature/recurring-payments-cycles

Conversation

@KrzysztofPajak

@KrzysztofPajak KrzysztofPajak commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Type: feature

Issue

Slice 1 (#1075) records a Pending recurring 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

  • Three commands a payment provider sends from its webhook, each keyed by 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 → PastDue with the last error. It returns true only on the transition into PastDue, 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 as CancelledBy.
  • A paid cycle is claimed once. RecurringPaymentService.ClaimCycle reads, checks and writes under an IResourceLock key per recurring payment (RecurringPayment:{id}). A resent or concurrent webhook with the same CycleReference does nothing, so one gateway cycle makes one order. The spec asked for a conditional Mongo update. IRepository.UpdateOneAsync returns 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.
  • Cycles and statuses:
    • Cycle 1 is the initial order's own payment: Active, the subscription reference stored, no new order.
    • Each later cycle gets its order id at the claim, PastDue → Active.
    • Reaching a non-zero TotalCycles gives Completed.
    • A cycle the gateway charges after Completed/Cancelled is still recorded with its order, because the money is taken, and the status stays as it is.
  • The cycle order (PlaceRecurringCycleOrderCommand) is a copy of the initial order at its prices, made by RecurringCycleOrder.Copy, a pure function. A reflection test pins every Order and OrderItem property as either copied or deliberately reset, so a new field cannot be skipped by accident. The order has a new id, number, code and OrderGuid, plus InitialOrderId and RecurringCycleNumber. 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:
    • a payment transaction;
    • stock reserved unconditionally through IInventoryManageService.AdjustReserved (low stock never blocks it, since the money is taken);
    • the Sold counter;
    • the "order placed" messages;
    • OrderPlacedEvent;
    • then the payment.
      Discounts, gift vouchers, loyalty point redemption and the order placement rules are not evaluated again.
  • The amount the gateway charged is recorded as is. If it covers the total, the order is marked paid. If it is less, the order is partially paid (PartiallyPaidOfflineCommand). At 0, no payment is recorded. Whenever the amount differs from the total, an order note gives both amounts.
  • Stopping the gateway:
    • The shop calls the new IPaymentService.CancelRecurringPayment whenever a cycle leaves the recurring payment Completed or Cancelled: 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.
    • A refusal or an exception from the provider leaves a note on the initial order. The status is not touched.
  • When the cycle order cannot be placed after the claim (initial order deleted, a handler that throws), the initial order gets a note naming the cycle, the gateway reference and the cycle's order id. The exception still reaches the provider. A resend does not retry, so staff handle it from the note.
  • Once a cycle is claimed, the remaining steps run with CancellationToken.None, so an aborted webhook request cannot leave it half done.
  • .ai/skills/plugin-payment.md describes the provider side: the three commands, the metadata, idempotency by invoice id, the amount units (those of MarkAsPaidCommand.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 RecurringPayment and Order documents only.

Decisions taken in the plan, for review:

  • A lock instead of a conditional update (see above).
  • Cycle orders send the standard "order placed" and "order paid" messages, as the initial order does.
  • Loyalty points and gift vouchers redeemed on the initial order are added back to the cycle total.
  • A charge after Completed/Cancelled is recorded with its order, and the gateway is asked to stop again.
  • Cycle orders generate no gift vouchers and no reservations.

Breaking changes

  • IPaymentService has a new member CancelRecurringPayment(RecurringPayment). This only affects custom implementations of the service, not payment plugins.
  • IRecurringPaymentService has new members ClaimCycle, RecordFailure and RecordEnded. RecurringPaymentService takes a new constructor parameter, IResourceLock. This only affects custom implementations, or code that constructs it by hand.

Follow-ups (not in this PR)

  • Re-placing a cycle order on resend when its order was never created. Today staff create it by hand from the note.
  • Cross-checking the subscription reference a webhook reports against the stored one (Stripe stage).
  • UpdateRecurringPayment is 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 after Cancelled; failure transitions; ended.
  • RecurringCycleOrderTests: copied versus reset fields, loyalty points, gift vouchers, and the reflection pins on Order and OrderItem.
  • PlaceRecurringCycleOrderCommandHandlerTests: transaction, unconditional stock, step order, paid / partially paid / zero, the amount note, a deleted initial order.
  • RecordRecurringPaymentCommandHandlersTests:
    • claim, first and later cycles;
    • the gateway stop after Completed/Cancelled and after a failed last cycle;
    • notes that cannot be written;
    • an exception from the provider;
    • a required CycleReference.

Automated: dotnet build GrandNode.slnx (0 errors); Grand.Business.Checkout.Tests 1034/1034, Grand.Web.Tests 624/624.

Copilot AI balanced review requested due to automatic review settings November 20, 2026 20:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

}, 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);
}
@KrzysztofPajak
KrzysztofPajak merged commit 1179b40 into develop Nov 21, 2026
9 checks passed
@KrzysztofPajak
KrzysztofPajak deleted the feature/recurring-payments-cycles branch November 21, 2026 03:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants