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
5 changes: 5 additions & 0 deletions .ai/skills/plugin-payment.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,11 @@ Do not use this skill for order processing business logic outside the payment fl
10. Return `SupportCapture() => true` only when `Capture` is actually implemented; same for Refund, PartiallyRefund, and Void. Returning `true` causes the admin UI to show the corresponding action button.
11. In `CancelPayment`, update `paymentTransaction.TransactionStatus = TransactionStatus.Canceled` and persist via `IPaymentTransactionService.UpdatePaymentTransaction`.

#### Recurring Payments
- 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.

#### Project Structure
12. Use `Microsoft.NET.Sdk.Razor` as SDK.
13. Set output path to `..\..\Web\Grand.Web\Plugins\{SystemName}\`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place
private readonly IProductAttributeFormatter _productAttributeFormatter;
private readonly IProductReservationService _productReservationService;
private readonly IProductService _productService;
private readonly IRecurringPaymentService _recurringPaymentService;
private readonly ISalesEmployeeService _salesEmployeeService;
private readonly ShippingSettings _shippingSettings;
private readonly ShoppingCartSettings _shoppingCartSettings;
Expand Down Expand Up @@ -107,6 +108,7 @@ public PlaceOrderCommandHandler(
IOrderApprovalService orderApprovalService,
IOrderPlacementService orderPlacementService,
ICheckoutClaimService checkoutClaimService,
IRecurringPaymentService recurringPaymentService,
ITranslationService translationService,
ShippingSettings shippingSettings,
ShoppingCartSettings shoppingCartSettings,
Expand Down Expand Up @@ -147,6 +149,7 @@ public PlaceOrderCommandHandler(
_orderApprovalService = orderApprovalService;
_orderPlacementService = orderPlacementService;
_checkoutClaimService = checkoutClaimService;
_recurringPaymentService = recurringPaymentService;
_translationService = translationService;
_shippingSettings = shippingSettings;
_shoppingCartSettings = shoppingCartSettings;
Expand Down Expand Up @@ -253,6 +256,10 @@ public async Task<PlaceOrderResult> Handle(PlaceOrderCommand command, Cancellati
//from here on what was claimed belongs to the order
orderInserted = true;
await CompleteOrderDetails(details, result.PlacedOrder);
//after the cart is cleared, so a failed write cannot lead to a second paid order; still before the
//provider's post-process step, which starts the gateway's schedule for it
if (details.IsRecurring)
await InsertRecurringPayment(result.PlacedOrder);
result.PaymentTransaction = paymentTransaction;

#endregion
Expand Down Expand Up @@ -322,6 +329,20 @@ await _mediator.Publish(new OrderPlacedEvent(result.PlacedOrder) {
return result;
}

private Task InsertRecurringPayment(Order order)
{
return _recurringPaymentService.InsertRecurringPayment(new RecurringPayment {
StoreId = order.StoreId,
CustomerId = order.CustomerId,
InitialOrderId = order.Id,
PaymentMethodSystemName = order.PaymentMethodSystemName,
CycleLength = order.RecurringCycleLength,
CyclePeriodId = order.RecurringCyclePeriodId,
TotalCycles = order.RecurringTotalCycles,
Status = RecurringPaymentStatus.Pending
});
}

protected virtual async Task<ProcessPaymentResult> ProcessPayment(PlaceOrderContainer details,
PaymentTransaction paymentTransaction)
{
Expand Down Expand Up @@ -1039,7 +1060,8 @@ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction
IsRecurring = details.IsRecurring,
RecurringCycleLength = details.RecurringCycleLength,
RecurringCyclePeriodId = details.RecurringCyclePeriodId,
RecurringTotalCycles = details.RecurringTotalCycles
RecurringTotalCycles = details.RecurringTotalCycles,
RecurringCycleNumber = details.IsRecurring ? 1 : 0
};

foreach (var item in details.Taxes) order.OrderTaxes.Add(item);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Utilities.Checkout;

namespace Grand.Business.Checkout.Services.Orders;

/// <summary>
/// The built-in rule: the payment method runs the schedule of an order billed in cycles, so the order needs a method
/// that can, and something to pay
/// </summary>
public class RecurringPaymentRuleProvider : IOrderPlacementRuleProvider
{
private readonly IPaymentService _paymentService;
private readonly IRecurringPaymentService _recurringPaymentService;
private readonly ITranslationService _translationService;

public RecurringPaymentRuleProvider(IRecurringPaymentService recurringPaymentService,
IPaymentService paymentService, ITranslationService translationService)
{
_recurringPaymentService = recurringPaymentService;
_paymentService = paymentService;
_translationService = translationService;
}

public string ConfigurationUrl => null;
public string SystemName => "OrderPlacementRule.RecurringPayment";
public string FriendlyName => SystemName;
public int Priority => 0;
public IList<string> LimitedToStores => [];
public IList<string> LimitedToGroups => [];

public async Task<OrderPlacementRuleResult> Evaluate(OrderPlacementContext context,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);

// not a recurring cart: returning here keeps every other checkout free of a total calculation
if (!await _recurringPaymentService.HasRecurringProducts(context.Cart))
return OrderPlacementRuleResult.Allow();

// a zero total skips the payment step and clears the method, so nothing would run the schedule
if (await context.GetTotal() is 0)
return OrderPlacementRuleResult.Block(
_translationService.GetResource("Checkout.RecurringPayment.NothingToPay", context.Language.Id));

// a method that charges once would break the promise of a product billed in cycles; none is chosen yet early
// in checkout
if (!string.IsNullOrEmpty(context.PaymentMethodSystemName) &&
!await _paymentService.SupportRecurringPayment(context.PaymentMethodSystemName))
return OrderPlacementRuleResult.Block(_translationService.GetResource(
"Checkout.RecurringPayment.PaymentMethodNotSupported", context.Language.Id));

return OrderPlacementRuleResult.Allow();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Data;
using Grand.Domain.Orders;
using Grand.Infrastructure.Extensions;
using Grand.Mediator;

namespace Grand.Business.Checkout.Services.Orders;

public class RecurringPaymentService(
IRepository<RecurringPayment> repository,
IProductService productService,
IMediator mediator)
: IRecurringPaymentService
{
public virtual async Task InsertRecurringPayment(RecurringPayment recurringPayment)
{
ArgumentNullException.ThrowIfNull(recurringPayment);

await repository.InsertAsync(recurringPayment);

//event notification
await mediator.EntityInserted(recurringPayment);
}

public virtual async Task UpdateRecurringPayment(RecurringPayment recurringPayment)
{
ArgumentNullException.ThrowIfNull(recurringPayment);

await repository.UpdateAsync(recurringPayment);

//event notification
await mediator.EntityUpdated(recurringPayment);
}

public virtual Task<RecurringPayment> GetRecurringPaymentById(string id)
{
return repository.GetByIdAsync(id);
}

public virtual Task<RecurringPayment> GetRecurringPaymentByInitialOrderId(string initialOrderId)
{
return repository.GetOneAsync(x => x.InitialOrderId == initialOrderId);
}

public virtual async Task<bool> HasRecurringProducts(IEnumerable<ShoppingCartItem> cart)
{
ArgumentNullException.ThrowIfNull(cart);

foreach (var sci in cart)
if (await productService.GetProductById(sci.ProductId) is { IsRecurring: true })
return true;

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,19 @@ public virtual async Task<bool> SupportVoid(string paymentMethodSystemName)
return await paymentMethod.SupportVoid();
}

/// <summary>
/// Gets a value indicating whether recurring payments are supported by payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A value indicating whether recurring payments are supported</returns>
public virtual async Task<bool> SupportRecurringPayment(string paymentMethodSystemName)
{
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return false;
return await paymentMethod.SupportRecurringPayment();
}

/// <summary>
/// Voids a payment
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ private static void RegisterOrdersService(IServiceCollection serviceCollection)
serviceCollection.AddScoped<IOrderPlacementService, OrderPlacementService>();
serviceCollection.AddScoped<ICheckoutClaimService, CheckoutClaimService>();
serviceCollection.AddScoped<IOrderPlacementRuleProvider, OrderApprovalLimitRuleProvider>();
serviceCollection.AddScoped<IOrderPlacementRuleProvider, RecurringPaymentRuleProvider>();
serviceCollection.AddScoped<ICompanyCreditService, CompanyCreditService>();
serviceCollection.AddScoped<IPaymentReminderService, PaymentReminderService>();
serviceCollection.AddScoped<IRecurringPaymentService, RecurringPaymentService>();
serviceCollection.AddScoped<ILoyaltyPointsService, LoyaltyPointsService>();
serviceCollection.AddScoped<IShoppingCartService, ShoppingCartService>();
serviceCollection.AddScoped<IShoppingCartValidator, ShoppingCartValidator>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using FluentValidation;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
Expand All @@ -17,7 +18,8 @@ public record ShoppingCartWarningsValidatorRecord(

public class ShoppingCartWarningsValidator : AbstractValidator<ShoppingCartWarningsValidatorRecord>
{
public ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService)
public ShoppingCartWarningsValidator(ITranslationService translationService, IProductService productService,
IGroupService groupService)
{
RuleFor(x => x).CustomAsync(async (value, context, _) =>
{
Expand Down Expand Up @@ -63,6 +65,12 @@ public ShoppingCartWarningsValidator(ITranslationService translationService, IPr
//don't mix recurring products
if (hasRecurringProducts && hasRecurringProductsMix)
context.AddFailure(translationService.GetResource("ShoppingCart.CannotMixRecurringProducts", value.Language.Id));

//a recurring payment is cancelled from My account, so a guest has to log in or register first; a wishlist
//buys nothing
if (hasRecurringProducts && value.ShoppingCarts.Any(x => x.ShoppingCartTypeId != ShoppingCartType.Wishlist) &&
await groupService.IsGuest(value.Customer))
context.AddFailure(translationService.GetResource("ShoppingCart.RecurringProductsRequireAccount", value.Language.Id));
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Grand.Domain.Orders;

namespace Grand.Business.Core.Interfaces.Checkout.Orders;

/// <summary>
/// The recurring payments of orders placed with a recurring product
/// </summary>
public interface IRecurringPaymentService
{
/// <summary>
/// Inserts a recurring payment
/// </summary>
Task InsertRecurringPayment(RecurringPayment recurringPayment);

/// <summary>
/// Updates a recurring payment
/// </summary>
Task UpdateRecurringPayment(RecurringPayment recurringPayment);

/// <summary>
/// Gets a recurring payment
/// </summary>
Task<RecurringPayment> GetRecurringPaymentById(string id);

/// <summary>
/// Gets the recurring payment of the order the customer placed; null when the order is not recurring
/// </summary>
Task<RecurringPayment> GetRecurringPaymentByInitialOrderId(string initialOrderId);

/// <summary>
/// Gets a value indicating whether the cart holds a product billed in cycles
/// </summary>
Task<bool> HasRecurringProducts(IEnumerable<ShoppingCartItem> cart);
}
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,24 @@ public interface IPaymentProvider : IProvider
/// </summary>
Task<bool> SupportVoid();

/// <summary>
/// Gets a value indicating whether the provider runs recurring payments: it starts the gateway's schedule in its
/// payment flow, charges every cycle and reports each one to the shop, the first one (the initial order's
/// payment) included
/// </summary>
Task<bool> SupportRecurringPayment() => Task.FromResult(false);

/// <summary>
/// Cancels a recurring payment at the gateway, so no further cycle is charged
/// </summary>
/// <param name="recurringPayment">Recurring payment</param>
/// <returns>Result</returns>
Task<CancelRecurringPaymentResult> CancelRecurringPayment(RecurringPayment recurringPayment)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment method not supported");
return Task.FromResult(result);
}

#endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,13 @@ Task<IList<IPaymentProvider>> LoadAllPaymentMethods(Customer customer = null, st
/// <returns>A value indicating whether void is supported</returns>
Task<bool> SupportVoid(string paymentMethodSystemName);

/// <summary>
/// Gets a value indicating whether recurring payments are supported by payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A value indicating whether recurring payments are supported</returns>
Task<bool> SupportRecurringPayment(string paymentMethodSystemName);

/// <summary>
/// Voids a payment
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace Grand.Business.Core.Utilities.Checkout;

/// <summary>
/// Represents a CancelRecurringPaymentResult
/// </summary>
public class CancelRecurringPaymentResult
{
/// <summary>
/// Gets a value indicating whether request has been completed successfully
/// </summary>
public bool Success => Errors.Count == 0;

/// <summary>
/// Errors
/// </summary>
public IList<string> Errors { get; set; } = new List<string>();

/// <summary>
/// Add error
/// </summary>
/// <param name="error">Error</param>
public void AddError(string error)
{
Errors.Add(error);
}
}
10 changes: 10 additions & 0 deletions src/Core/Grand.Domain/Orders/Order.cs
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,16 @@ public class Order : BaseEntity
/// </summary>
public int RecurringUseCycles { get; set; }

/// <summary>
/// Gets or sets the order the customer placed, on an order paying a later cycle of its recurring payment
/// </summary>
public string InitialOrderId { get; set; }

/// <summary>
/// Gets or sets the recurring payment cycle the order pays: 1 on the initial order, 0 when not recurring
/// </summary>
public int RecurringCycleNumber { get; set; }

/// <summary>
/// Gets or sets the Shipping Option description (customer friendly string)
/// </summary>
Expand Down
Loading
Loading