Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .ai/skills/message-notification.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ Do not use this skill as the primary review for MongoDB queries or security; com
6. Use DotLiquid syntax: `{{Drop.Property}}` for values, `{% if condition %}...{% endif %}` for conditions, `{% for item in Collection %}...{% endfor %}` for loops.

#### Sending Messages
7. Add a typed send method to the area interface that owns the recipient's flow, `I<Area>MessageProviderService` in `src/Business/Grand.Business.Core/Interfaces/Messages/` (Customer, Order, Newsletter, Catalog, MerchandiseReturn, Vendor, Cms), when the trigger is a recurring, well-defined business event. Follow the signature pattern:
7. Add a typed send method to the area interface that owns the recipient's flow, `I<Area>MessageProviderService` in `src/Business/Grand.Business.Core/Interfaces/Messages/` (Customer, Order, Newsletter, Catalog, MerchandiseReturn, RecurringPayment, Vendor, Cms), when the trigger is a recurring, well-defined business event. Follow the signature pattern:
```csharp
Task<int> SendXxxMessage(TEntity entity, Store store, string languageId);
```
Expand Down Expand Up @@ -94,6 +94,7 @@ Task<int> SendOrderPlacedCustomerMessage(Order order, Customer customer, string
| `INewsletterMessageProviderService` | newsletter subscription activation and deactivation |
| `ICatalogMessageProviderService` | email a friend, wishlist, product questions and reviews, low stock, back in stock, auctions and bids |
| `IMerchandiseReturnMessageProviderService` | merchandise return created, status changed, notes |
| `IRecurringPaymentMessageProviderService` | recurring payment cancelled and cycle failed, for customer and store owner |
| `IVendorMessageProviderService` | vendor application, information change, vendor reviews, contact vendor |
| `ICmsMessageProviderService` | blog, knowledgebase article and news comments |

Expand Down Expand Up @@ -167,6 +168,7 @@ public class MessageTokensAddedEvent : INotification {
| `LiquidShipment` | `{{Shipment.*}}` | Shipment |
| `LiquidProduct` | `{{Product.*}}` | Product |
| `LiquidMerchandiseReturn` | `{{MerchandiseReturn.*}}` | MerchandiseReturn |
| `LiquidRecurringPayment` | `{{RecurringPayment.*}}` | RecurringPayment (the initial order comes from `LiquidOrder`) |
| `LiquidGiftVoucher` | `{{GiftVoucher.*}}` | GiftVoucher |
| `LiquidNewsLetterSubscription` | `{{NewsLetterSubscription.*}}` | NewsLetterSubscription |
| `LiquidVendor` | `{{Vendor.*}}` | Vendor |
Expand Down
1 change: 1 addition & 0 deletions .ai/skills/plugin-payment.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ 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.
- `CancelRecurringPayment` stops the gateway's schedule for `RecurringPayment.ProviderReference` and returns. The shop cancels through `CancelRecurringPaymentCommand`, which calls it outside the recurring payment's lock and then, under the lock on a fresh read, marks it `Cancelled` only on success; a throw counts as a refusal. Webhooks for the payment are not held up by the call, and a cycle recorded meanwhile is kept. A `Pending` payment with no `ProviderReference` is cancelled without the call: it has no reference to stop yet, the gateway may have started the subscription at checkout already, and the first cycle or failure it reports on the cancelled payment makes the shop stop the gateway, so send `ProviderReference` with the failure command as well. A cycle charged after the payment was cancelled or completed is noted on the initial order for staff to refund.
- 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.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
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;

namespace Grand.Business.Checkout.Commands.Handlers.Orders;

public class CancelRecurringPaymentCommandHandler(
IRecurringPaymentService recurringPaymentService,
IPaymentService paymentService,
ILogger<CancelRecurringPaymentCommandHandler> logger)
: IRequestHandler<CancelRecurringPaymentCommand, CancelRecurringPaymentResult>
{
public async Task<CancelRecurringPaymentResult> Handle(CancelRecurringPaymentCommand request,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request.RecurringPayment);
ArgumentException.ThrowIfNullOrEmpty(request.CancelledBy);

return await recurringPaymentService.Cancel(request.RecurringPayment.Id, request.CancelledBy, StopAtGateway);
}

private async Task<CancelRecurringPaymentResult> StopAtGateway(RecurringPayment recurringPayment)
{
try
{
return await paymentService.CancelRecurringPayment(recurringPayment);
}
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 +32 to +40
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ await mediator.Send(new PlaceRecurringCycleOrderCommand {
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,
await RecurringPaymentGateway.AddNote(orderService, logger, 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
Expand All @@ -54,49 +54,16 @@ await AddNote(claim.RecurringPayment,

// 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);

placementFailure?.Throw();

return true;
}

private async Task StopTheGateway(RecurringPayment recurringPayment)
{
IEnumerable<string> 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 last cycle completing the payment is expected; any other was taken after the shop ended it
if (!claim.Completed)
await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment,
$"Cycle {claim.Cycle.CycleNumber} was charged at the payment gateway ({request.CycleReference}) after the recurring payment was {claim.RecurringPayment.Status.ToString().ToLowerInvariant()}: check whether the customer must be refunded");
await RecurringPaymentGateway.Stop(paymentService, orderService, logger, claim.RecurringPayment);
}

// the status stays as it is: every cycle is paid or the payment ended, only the gateway schedule may still run
if (errors.Any())
await AddNote(recurringPayment,
$"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}");
}
placementFailure?.Throw();

private async Task AddNote(RecurringPayment recurringPayment, string note)
{
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);
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,39 @@
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 RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentService recurringPaymentService)
public class RecordRecurringPaymentFailureCommandHandler(
IRecurringPaymentService recurringPaymentService,
IPaymentService paymentService,
IOrderService orderService,
ILogger<RecordRecurringPaymentFailureCommandHandler> logger)
: IRequestHandler<RecordRecurringPaymentFailureCommand, bool>
{
public async Task<bool> Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId);
ArgumentException.ThrowIfNullOrEmpty(request.CycleReference);

return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference,
request.Reason);
if (await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference,
request.Reason))
return true;

// a failed charge on a payment the shop ended means the gateway still tries to charge, typically a payment
// cancelled while pending, before the gateway's reference was known
var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(request.RecurringPaymentId);
if (recurringPayment?.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed &&
recurringPayment.Cycles.All(x => x.ProviderReference != request.CycleReference))
{
if (string.IsNullOrEmpty(recurringPayment.ProviderReference))
recurringPayment.ProviderReference = request.ProviderReference;
await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment);
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Domain.Orders;
using Microsoft.Extensions.Logging;

namespace Grand.Business.Checkout.Commands.Handlers.Orders;

/// <summary>
/// What the provider commands do when the gateway reports on a recurring payment the shop already ended
/// </summary>
internal static class RecurringPaymentGateway
{
public static async Task Stop(IPaymentService paymentService, IOrderService orderService, ILogger logger,
RecurringPayment recurringPayment)
{
IEnumerable<string> errors;
try
{
var result = await paymentService.CancelRecurringPayment(recurringPayment);
errors = result.Success ? [] : result.Errors;
}
catch (Exception e)
{
// a throw is treated as a refusal: the report is recorded and a resend is a no-op, so the note is the only trace
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the payment gateway could not be asked to stop charging",
recurringPayment.Id);
errors = [e.Message];
}
Comment on lines +22 to +28

// 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(orderService, logger, recurringPayment,
$"The recurring payment is {recurringPayment.Status.ToString().ToLowerInvariant()}, but the payment gateway did not confirm it stopped charging: {string.Join(", ", errors)}");
}

public static async Task AddNote(IOrderService orderService, ILogger logger, RecurringPayment recurringPayment,
string note)
{
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 report
logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order note could not be written: {Note}",
recurringPayment.Id, note);
}
Comment on lines +46 to +51
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Events.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Domain.Orders;
using Grand.Mediator;
using Microsoft.Extensions.Logging;

namespace Grand.Business.Checkout.Events.Orders;

/// <summary>
/// Cancels the recurring payment of an initial order that was cancelled or deleted
/// </summary>
public class OrderCancelledRecurringPaymentHandler : INotificationHandler<OrderCancelledEvent>,
INotificationHandler<OrderDeletedEvent>
{
private readonly ILogger<OrderCancelledRecurringPaymentHandler> _logger;
private readonly IMediator _mediator;
private readonly IOrderService _orderService;
private readonly IRecurringPaymentService _recurringPaymentService;

public OrderCancelledRecurringPaymentHandler(IRecurringPaymentService recurringPaymentService,
IOrderService orderService, IMediator mediator, ILogger<OrderCancelledRecurringPaymentHandler> logger)
{
_recurringPaymentService = recurringPaymentService;
_orderService = orderService;
_mediator = mediator;
_logger = logger;
}

public Task Handle(OrderCancelledEvent notification, CancellationToken cancellationToken)
{
return CancelRecurringPayment(notification.Order, "cancelled");
}

public Task Handle(OrderDeletedEvent notification, CancellationToken cancellationToken)
{
return CancelRecurringPayment(notification.Order, "deleted");
}

private async Task CancelRecurringPayment(Order order, string what)
{
// a cycle order or a plain order never owns a recurring payment, and a plain order costs no query
if (order.RecurringCycleNumber != 1) return;

try
{
var recurringPayment = await _recurringPaymentService.GetRecurringPaymentByInitialOrderId(order.Id);
if (recurringPayment == null) return;

var result = await _mediator.Send(new CancelRecurringPaymentCommand {
RecurringPayment = recurringPayment,
CancelledBy = $"Order #{order.OrderNumber} {what}"
});
if (!result.Success)
await AddNote(order, what, string.Join(", ", result.Errors));
}
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 +57 to +64
}

private async Task AddNote(Order order, string what, string reason)
{
try
{
await _orderService.InsertOrderNote(new OrderNote {
OrderId = order.Id,
Note =
$"The order was {what}, but its recurring payment could not be cancelled, so the payment gateway may still charge: {reason}",
DisplayToCustomer = false,
CreatedOnUtc = DateTime.UtcNow
});
}
catch (Exception ex)
{
_logger.LogError(ex, "The note about the recurring payment of order {OrderId} could not be saved",
order.Id);
}
Comment on lines +79 to +83
}
}
Loading
Loading