Skip to content

Recurring payments: cancelling and messages (slice 3 of 5) - #1077

Merged
KrzysztofPajak merged 12 commits into
developfrom
feature/recurring-payments-cancel
Nov 21, 2026
Merged

KrzysztofPajak merged 12 commits into
developfrom
feature/recurring-payments-cancel

Conversation

@KrzysztofPajak

@KrzysztofPajak KrzysztofPajak commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Type: feature

Issue

After slices 1 and 2 (#1075, #1076) a recurring payment can be recorded and the gateway can report paid cycles, failed cycles and a schedule ended at its end. The shop still cannot cancel a recurring payment, and nobody is told when a cycle fails or a recurring payment ends. Cancelling or deleting the order the customer placed leaves its recurring payment running. The gateway can then keep charging for an order the shop has cancelled.

This is slice 3 of 5 of recurring payments (payments roadmap P5): cancelling and the messages. The cancel is not reachable from a screen yet. The My account tab is slice 4; the Admin and Store screens are slice 5.

Solution

Cancel (CancelRecurringPaymentCommand, RecurringPaymentService.Cancel)

  • The cancel takes the same lock as the cycle claim (RecurringPayment:{id}) and reads the record again inside it.
  • Cancelled or Completed → success, and nothing changes. A double click, or a cancel followed by a delete, does one cancel.
  • Pending with no gateway reference yet → Cancelled without calling the gateway. If the gateway did start a subscription at checkout, its first reported cycle is recorded on the cancelled payment, and slice 2 then asks the gateway to stop. A test pins this path.
  • Otherwise the provider's CancelRecurringPayment is called first. A refusal or an exception returns the errors and keeps the status, so the shop never shows Cancelled while the gateway may still charge.
  • The gateway call is passed into the service as a callback. RecurringPaymentService must not depend on IPaymentService: a provider will inject IRecurringPaymentService in the Stripe stage, and the reverse dependency would be a DI cycle.
  • The gateway call runs outside the lock, between two short locked sections: the first checks the status, the second re-reads the record and writes the cancel. A slow gateway does not hold up webhooks for the payment, and a cycle recorded meanwhile is kept. A refusal after another cancel already ended the payment counts as success.
  • A failure reported for a payment the shop already ended (for example one cancelled while Pending, before the gateway reference was known) asks the gateway to stop. RecordRecurringPaymentFailureCommand gained an optional ProviderReference for this. A cycle charged after the payment was cancelled or completed adds an order note on the initial order so staff can refund it.
  • UpdateRecurringPayment is removed. Nothing called it, and it was a whole-document write without the lock (a follow-up from slice 2).

Initial order cancelled or deleted

  • A handler of OrderCancelledEvent / OrderDeletedEvent cancels the recurring payment of an initial order (RecurringCycleNumber == 1). This is the same pattern as OrderCancelledOrderApprovalHandler. The two order command handlers are unchanged.
  • The order is cancelled or deleted regardless. If the gateway refuses, the order gets a note and the recurring payment keeps running.
  • Cancelling a cycle order does not touch the recurring payment.
  • CancelledBy is Order #N cancelled or Order #N deleted.

Messages

  • RecurringPaymentService publishes RecurringPaymentCancelledEvent only when the status changes to Cancelled (by Cancel or by RecordEnded). It publishes RecurringPaymentPastDueEvent only when the status changes to PastDue. A gateway retrying the same failure therefore sends nothing new.
  • RecurringPaymentMessagesHandler sends the customer and the store owner their e-mails:
    • RecurringPayment.Cancelled.CustomerNotification
    • RecurringPayment.Cancelled.StoreOwnerNotification
    • RecurringPayment.PaymentFailed.CustomerNotification
    • RecurringPayment.PaymentFailed.StoreOwnerNotification
  • A message that cannot be sent is logged and never fails the cancel or a webhook.
  • The e-mails carry the initial order's tokens ({{Order.*}}). The new LiquidRecurringPayment drop, in the existing LiquidObject.RecurringPayment slot, holds CycleLength, CyclePeriod, CyclesPaid, TotalCycles, LastError and CancelledBy. LastError and CancelledBy come from a gateway or a person, so they are HTML-encoded.
  • The customer's language is the initial order's. The store owner's is the default admin language.
  • New IRecurringPaymentMessageProviderService.
  • E-mails are also sent for a Pending recurring payment that never charged.

Persisted data

  • The four templates are seeded for new installations, and MigrationRecurringPaymentTemplates (2.5) adds them to existing ones. It adds only the templates that are missing, so an edited one is left alone, and a test keeps the seed and the migration equal.
  • Four resources go into DefaultLanguage.xml and en_250.xml: Enums.Grand.Domain.Catalog.RecurringCyclePeriod.*. The existing ...RecurringProductCyclePeriod.* keys name an enum that does not exist.
  • There is no new collection or index.

Docs: .ai/skills/plugin-payment.md describes what CancelRecurringPayment must do and its time budget. .ai/skills/message-notification.md lists the new interface and drop.

Breaking changes

  • IRecurringPaymentService: UpdateRecurringPayment is removed and Cancel is added. This only affects custom implementations of the service.
  • Payment plugins are not affected: IPaymentProvider.CancelRecurringPayment already has a default.

Testing

Automated:

  • dotnet build GrandNode.slnx → 0 errors.
  • Grand.Business.Checkout.Tests 1072/1072, Grand.Business.Messages.Tests 168/168, Grand.Modules.Tests 427/427, Grand.Web.Tests 624/624.

The new tests cover:

  • the cancel rules on a real Mongo repository and lock, including a webhook and another cancel arriving during the gateway call;
  • a failure or a cycle reported on an ended payment (gateway asked to stop, refund note);
  • events on transitions only;
  • the order hook (initial, cycle and plain order, refusal note, failures);
  • tokens and HTML encoding;
  • every send method against its own template name, and a language that is not published;
  • the migration (idempotent, keeps an edited template, equal to the seed).

E2E on a throwaway installation (Mongo, sample data). No shipped provider charges in cycles yet, so a temporary controller, not part of this PR, inserted an initial order with its recurring payment and sent the commands:

  1. Cancel a Pending recurring payment with no reference → Cancelled. Two e-mails are queued, one to the customer and one to the store, with no {{ left in the body. A second cancel succeeds and queues nothing.
  2. Cancel an Active one with a reference, paid by Cash on delivery (which cannot cancel) → error "Recurring payment method not supported". The status stays Active and nothing is queued.
  3. Failure reported twice for the same invoice → PastDue, with e-mails on the first report only. A <script> reason arrives in the e-mail encoded.
  4. Ended at the gateway → Cancelled by Payments.CashOnDelivery, two e-mails. A second ended event does nothing.
  5. Admin → Order → Cancel order on an initial order → the recurring payment is Cancelled with Order #12 cancelled. The customer gets the standard "order cancelled" e-mail plus the two recurring payment e-mails.
  6. Cancelling an initial order whose method refuses → the order is cancelled, the recurring payment stays Active, and the order has the note.
  7. Cancelling a cycle order → the recurring payment is untouched.
  8. Cancel and then delete the initial order → one cancel, one set of e-mails. Deleting a never-cancelled initial order → Cancelled with Order #N deleted.
  9. Migration:
    • Setup: deleted three of the templates, edited the fourth's subject, set GrandNodeVersion back to 2.4 and removed this migration's record.
    • Restart → "Recurring payment e-mails 2.5" ran: three templates are back, and the edited one is unchanged.

E2E after the review fixes (new throwaway install, same temporary controller):
10. Active payment, a gateway that takes 5 s to confirm the cancel. A cycle webhook sent 1 s in is recorded at once (cycle 2, still Active). The cancel then finishes at about 5.2 s as Cancelled and keeps both cycles. Two e-mails.
11. Pending payment cancelled, then the gateway reports cycle 1 → recorded on the cancelled payment. The initial order gets the note "Cycle 1 was charged at the payment gateway (in_1) after the recurring payment was cancelled: check whether the customer must be refunded", and the gateway is asked to stop (Cash on delivery refuses, so a second note says so).
12. Pending payment cancelled, then the gateway reports a failed charge with a reference → status unchanged, no e-mails, gateway asked to stop (refusal note).
13. A failure on an Active payment, reported twice → PastDue once and no gateway call. A cancel refused by the gateway → still Active, no e-mails. Admin → Cancel order on a Pending initial order → Cancelled with Order #7 cancelled, plus three e-mails.

Follow-ups (not in this PR):

  • Slice 4 should map provider errors before showing them to a customer. The cancel returns the provider's or exception's text, which is fine for staff and order notes.
  • Stripe stage: a locked way to record the gateway reference at checkout, so a cancel before the first webhook stops the subscription directly.
  • The cycle line reads "Every 1 Months", like the shop's existing cart text. Slice 4 owns this phrase.
  • After the initial order is deleted, the customer's "View the order" button leads to a missing order.

support added 11 commits November 21, 2026 05:03
…g it

The lock's lease can end while the gateway is asked to stop, and a webhook may
record a cycle or end the payment meanwhile. Cancel now applies to a fresh copy
and writes nothing when it is already cancelled or completed.
…cancelled-by line for any caller

The store owner message now reads "Cancelled by: ...", which fits a staff name,
a customer e-mail and the order hook's "Order #12 cancelled" alike. The plugin
guide notes the lock's 30 s lease and the re-read after the gateway call.
Copilot AI balanced review requested due to automatic review settings November 21, 2026 05:03

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.

Comment on lines +32 to +40
catch (Exception e)
{
//a throw is treated as a refusal: the gateway may still be charging, so the status must stay as it is
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging",
recurringPayment.Id);
var result = new CancelRecurringPaymentResult();
result.AddError(e.Message);
return result;
}
Comment on lines +57 to +64
catch (Exception ex)
{
// the order is already cancelled or deleted: publishing must complete whatever happens here
_logger.LogError(ex,
"Order {OrderNumber} ({OrderId}) was {What} but its recurring payment could not be cancelled",
order.OrderNumber, order.Id, what);
await AddNote(order, what, ex.Message);
}
Comment on lines +79 to +83
catch (Exception ex)
{
_logger.LogError(ex, "The note about the recurring payment of order {OrderId} could not be saved",
order.Id);
}
Comment on lines +75 to +80
catch (Exception ex)
{
// the status is already saved: publishing must complete whatever happens here
_logger.LogError(ex, "The messages about recurring payment {RecurringPaymentId} could not be sent",
recurringPayment.Id);
}
Comment on lines +89 to +93
catch (Exception ex)
{
_logger.LogError(ex, "A message about recurring payment {RecurringPaymentId} could not be sent",
recurringPayment.Id);
}
Comment on lines +46 to +50
catch (Exception ex)
{
logService.LogError(ex, "UpgradeProcess - RecurringPaymentTemplates (2.5)");
return false;
}
… it on late reports

The cancel held the lock across the gateway call, so a slow call stalled every webhook for
the payment and, past the lease, let a cycle claim and the cancel overwrite each other.
The call now runs between two short locked sections, and the cancel is written on a fresh read.

A failure reported for a payment the shop already ended now asks the gateway to stop, using
the reference the failure command can now carry, and a cycle charged after the payment ended
is noted on the initial order for a refund.
Comment on lines +22 to +28
catch (Exception e)
{
// a throw is treated as a refusal: the report is recorded and a resend is a no-op, so the note is the only trace
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging",
recurringPayment.Id);
errors = [e.Message];
}
Comment on lines +46 to +51
catch (Exception e)
{
// the note is a courtesy to staff; losing it must not hide the original failure or fail a recorded report
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}",
recurringPayment.Id, note);
}
@KrzysztofPajak
KrzysztofPajak merged commit a1dc85a into develop Nov 21, 2026
9 checks passed
@KrzysztofPajak
KrzysztofPajak deleted the feature/recurring-payments-cancel branch November 25, 2026 09:10
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