diff --git a/.ai/skills/plugin-payment.md b/.ai/skills/plugin-payment.md index 7a3e2bbd2..438634dad 100644 --- a/.ai/skills/plugin-payment.md +++ b/.ai/skills/plugin-payment.md @@ -65,6 +65,11 @@ 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. +- 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. +- `Amount` uses the units of `MarkAsPaidCommand.Amount`: the order total in the order's currency, as Stripe Checkout passes it (`paymentIntent.Amount / 100.0`). +- The first paid cycle is the initial order's own payment: the provider still marks that order paid on its existing path and also sends the cycle command, which records cycle 1 and places no order. If placing a later cycle's order throws, the command notes it on the initial order for staff (the order may exist but be unpaid), stops the gateway when the payment is completed, and rethrows so the provider can log or report it. `CycleReference` is required, and `Amount` must not be negative. The cycle is already recorded, so a resend of the same `CycleReference` returns `false` and does not retry the order. A cycle the gateway charged less for is recorded as a partial payment, so its order stays partially paid, and a cycle of 0 records no payment; an order note says so. #### Project Structure 12. Use `Microsoft.NET.Sdk.Razor` as SDK. diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs new file mode 100644 index 000000000..44a8a76b9 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandler.cs @@ -0,0 +1,136 @@ +using System.Globalization; +using Grand.Business.Checkout.Extensions; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Commands.Messages.Common; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.GiftVouchers; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Mediator; +using Grand.SharedKernel; +using Microsoft.Extensions.Logging; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class PlaceRecurringCycleOrderCommandHandler( + IOrderService orderService, + IPaymentTransactionService paymentTransactionService, + IProductService productService, + IInventoryManageService inventoryManageService, + ICustomerService customerService, + IGiftVoucherService giftVoucherService, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(PlaceRecurringCycleOrderCommand request, CancellationToken cancellationToken) + { + var recurringPayment = request.RecurringPayment; + var cycle = request.Cycle; + + var initialOrder = await orderService.GetOrderById(recurringPayment.InitialOrderId); + if (initialOrder == null || initialOrder.Deleted) + throw new GrandException( + $"The initial order {recurringPayment.InitialOrderId} of recurring payment {recurringPayment.Id} was not found"); + + // a gift voucher paid part of the first cycle only + var giftVouchersAmount = (await giftVoucherService.GetAllGiftVoucherUsageHistory(initialOrder.Id)) + .Sum(x => x.UsedValue); + + var code = await mediator.Send(new PrepareOrderCodeCommand(), cancellationToken); + var order = RecurringCycleOrder.Copy(initialOrder, cycle.OrderId, cycle.CycleNumber, code, DateTime.UtcNow, + giftVouchersAmount); + + // the gateway already took the money, so the transaction is a real one from the start + var paymentTransaction = new PaymentTransaction { + TransactionStatus = TransactionStatus.Pending, + OrderGuid = order.OrderGuid, + OrderCode = order.Code, + StoreId = order.StoreId, + CustomerId = order.CustomerId, + CustomerEmail = order.CustomerEmail, + PaymentMethodSystemName = order.PaymentMethodSystemName, + CurrencyCode = order.CustomerCurrencyCode, + CurrencyRate = order.CurrencyRate, + TransactionAmount = order.OrderTotal, + Temp = false + }; + await paymentTransactionService.InsertPaymentTransaction(paymentTransaction); + + await orderService.InsertOrder(order); + + // no stock check: the customer has paid, so low stock never blocks a cycle order + foreach (var item in order.OrderItems) + { + var product = await productService.GetProductById(item.ProductId); + if (product == null) continue; + + await inventoryManageService.AdjustReserved(product, -item.Quantity, item.Attributes, item.WarehouseId); + + // statistics only: the payment is already taken, so a failed write must not stop the order + try + { + await productService.IncrementProductField(product, x => x.Sold, item.Quantity); + } + catch (Exception exc) + { + logger.LogWarning(exc, "Could not update the sold count of product {ProductId}", product.Id); + } + } + + await InsertNote(order.Id, + $"Cycle {cycle.CycleNumber} of the recurring payment of order #{initialOrder.OrderNumber}"); + + // no request context here: the customer comes from the order, and no host falls back to the store's primary one + var customer = await customerService.GetCustomerById(order.CustomerId); + await mediator.Send(new OrderNotificationCommand { Order = order, Customer = customer, Host = null }, + cancellationToken); + + await mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken); + + await mediator.Publish(new OrderPlacedEvent(order), cancellationToken); + + // the order is paid with what the gateway charged: a smaller charge must not show as fully paid + var charged = Math.Round(cycle.Amount, 2); + var total = Math.Round(order.OrderTotal, 2); + if (charged >= total) + await mediator.Send(new MarkAsPaidCommand { + PaymentTransaction = paymentTransaction, + Amount = cycle.Amount, + Reference = cycle.ProviderReference, + CreatedBy = recurringPayment.PaymentMethodSystemName + }, cancellationToken); + else if (charged > 0) + await mediator.Send(new PartiallyPaidOfflineCommand { + PaymentTransaction = paymentTransaction, + AmountToPaid = cycle.Amount, + Reference = cycle.ProviderReference, + CreatedBy = recurringPayment.PaymentMethodSystemName + }, cancellationToken); + + // a price change at the gateway shows here + if (charged != total) + await InsertNote(order.Id, + $"The payment gateway charged {Format(charged, order)} for this cycle; the order total is {Format(total, order)}"); + + return order; + } + + private static string Format(double amount, Order order) + { + return $"{amount.ToString("0.00", CultureInfo.InvariantCulture)} {order.CustomerCurrencyCode}"; + } + + private Task InsertNote(string orderId, string note) + { + return orderService.InsertOrderNote(new OrderNote { + Note = note, + DisplayToCustomer = false, + OrderId = orderId + }); + } +} diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs new file mode 100644 index 000000000..4ce731fb4 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -0,0 +1,102 @@ +using System.Runtime.ExceptionServices; +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 RecordRecurringPaymentCycleCommandHandler( + IRecurringPaymentService recurringPaymentService, + IPaymentService paymentService, + IOrderService orderService, + IMediator mediator, + ILogger logger) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentCycleCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); + if (double.IsNaN(request.Amount) || request.Amount < 0) + throw new ArgumentOutOfRangeException(nameof(request), "The cycle amount must be zero or more"); + + var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, + request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); + if (claim == null) + return false; + + // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable + cancellationToken = CancellationToken.None; + + // the first cycle is the initial order's own payment, which the provider marks paid on its existing path + ExceptionDispatchInfo placementFailure = null; + if (claim.Cycle.CycleNumber > 1) + try + { + await mediator.Send(new PlaceRecurringCycleOrderCommand { + RecurringPayment = claim.RecurringPayment, Cycle = claim.Cycle + }, cancellationToken); + } + 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); + } + + // 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 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 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)}"); + } + + 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); + } + } +} diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs new file mode 100644 index 000000000..14247abe5 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs @@ -0,0 +1,16 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Mediator; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentEndedCommandHandler(IRecurringPaymentService recurringPaymentService) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentEndedCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + + return await recurringPaymentService.RecordEnded(request.RecurringPaymentId); + } +} diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs new file mode 100644 index 000000000..e2edf074f --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -0,0 +1,18 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Mediator; + +namespace Grand.Business.Checkout.Commands.Handlers.Orders; + +public class RecordRecurringPaymentFailureCommandHandler(IRecurringPaymentService recurringPaymentService) + : IRequestHandler +{ + public async Task Handle(RecordRecurringPaymentFailureCommand request, CancellationToken cancellationToken) + { + ArgumentException.ThrowIfNullOrEmpty(request.RecurringPaymentId); + ArgumentException.ThrowIfNullOrEmpty(request.CycleReference); + + return await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.CycleReference, + request.Reason); + } +} diff --git a/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs new file mode 100644 index 000000000..0dfafdc50 --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs @@ -0,0 +1,203 @@ +using Grand.Domain.Common; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Domain.Shipping; + +namespace Grand.Business.Checkout.Extensions; + +public static class RecurringCycleOrder +{ + /// + /// The order that pays one later cycle of a recurring payment: the order the customer placed, at its prices, + /// as a new unpaid order. Everything that describes what was bought and what it costs is copied; identity, + /// dates, statuses, payment and shipping progress and the loyalty points spent are those of a new order. + /// Loyalty points and gift vouchers spent on the initial order are not spent again, so their amounts are added + /// back to the total. + /// + /// The gift voucher amount redeemed on the initial order + public static Order Copy(Order initialOrder, string orderId, int cycleNumber, string orderCode, + DateTime createdOnUtc, double giftVouchersAmount) + { + var order = new Order { + Id = orderId, + OrderGuid = Guid.NewGuid(), + // InsertOrder assigns the number + OrderNumber = 0, + Code = orderCode, + InitialOrderId = initialOrder.Id, + RecurringCycleNumber = cycleNumber, + CreatedOnUtc = createdOnUtc, + OrderStatusId = (int)OrderStatusSystem.Pending, + PaymentStatusId = PaymentStatus.Pending, + PaidAmount = 0, + PaidDateUtc = null, + PaymentDueDateUtc = null, + PaymentReminderSentOnUtc = null, + PaymentOverdueNoticeSentOnUtc = null, + RefundedAmount = 0, + RedeemedLoyaltyPoints = 0, + RedeemedLoyaltyPointsAmount = 0, + LoyaltyPointsWereAdded = false, + CalcLoyaltyPoints = 0, + OrderTotal = Math.Round( + initialOrder.OrderTotal + initialOrder.RedeemedLoyaltyPointsAmount + giftVouchersAmount, 6), + Deleted = false, + Imported = false, + + PurchaseOrderNumber = initialOrder.PurchaseOrderNumber, + StoreId = initialOrder.StoreId, + CustomerId = initialOrder.CustomerId, + OwnerId = initialOrder.OwnerId, + SeId = initialOrder.SeId, + PickUpInStore = initialOrder.PickUpInStore, + PaymentMethodSystemName = initialOrder.PaymentMethodSystemName, + PaymentOptionAttribute = initialOrder.PaymentOptionAttribute, + CustomerCurrencyCode = initialOrder.CustomerCurrencyCode, + PrimaryCurrencyCode = initialOrder.PrimaryCurrencyCode, + CurrencyRate = initialOrder.CurrencyRate, + Rate = initialOrder.Rate, + CustomerTaxDisplayTypeId = initialOrder.CustomerTaxDisplayTypeId, + VatNumber = initialOrder.VatNumber, + VatNumberStatusId = initialOrder.VatNumberStatusId, + CompanyName = initialOrder.CompanyName, + CustomerEmail = initialOrder.CustomerEmail, + FirstName = initialOrder.FirstName, + LastName = initialOrder.LastName, + OrderSubtotalInclTax = initialOrder.OrderSubtotalInclTax, + OrderSubtotalExclTax = initialOrder.OrderSubtotalExclTax, + OrderSubTotalDiscountInclTax = initialOrder.OrderSubTotalDiscountInclTax, + OrderSubTotalDiscountExclTax = initialOrder.OrderSubTotalDiscountExclTax, + OrderShippingInclTax = initialOrder.OrderShippingInclTax, + OrderShippingExclTax = initialOrder.OrderShippingExclTax, + PaymentMethodAdditionalFeeInclTax = initialOrder.PaymentMethodAdditionalFeeInclTax, + PaymentMethodAdditionalFeeExclTax = initialOrder.PaymentMethodAdditionalFeeExclTax, + OrderTax = initialOrder.OrderTax, + OrderDiscount = initialOrder.OrderDiscount, + CheckoutAttributeDescription = initialOrder.CheckoutAttributeDescription, + CheckoutAttributes = CopyAttributes(initialOrder.CheckoutAttributes), + CustomerLanguageId = initialOrder.CustomerLanguageId, + AffiliateId = initialOrder.AffiliateId, + CustomerIp = initialOrder.CustomerIp, + ShippingMethod = initialOrder.ShippingMethod, + ShippingRateProviderSystemName = initialOrder.ShippingRateProviderSystemName, + ShippingOptionAttributeDescription = initialOrder.ShippingOptionAttributeDescription, + ShippingOptionAttribute = initialOrder.ShippingOptionAttribute, + IsRecurring = initialOrder.IsRecurring, + RecurringCycleLength = initialOrder.RecurringCycleLength, + RecurringCyclePeriodId = initialOrder.RecurringCyclePeriodId, + RecurringTotalCycles = initialOrder.RecurringTotalCycles, + RecurringUseCycles = initialOrder.RecurringUseCycles, + BillingAddress = CopyAddress(initialOrder.BillingAddress), + ShippingAddress = CopyAddress(initialOrder.ShippingAddress), + PickupPoint = CopyPickupPoint(initialOrder.PickupPoint) + }; + + // the setters of the three collections are protected, so they are filled in place + foreach (var tax in initialOrder.OrderTaxes) + order.OrderTaxes.Add(new OrderTax { Percent = tax.Percent, Amount = tax.Amount }); + + foreach (var item in initialOrder.OrderItems) + order.OrderItems.Add(CopyItem(item, createdOnUtc)); + + order.ShippingStatusId = order.OrderItems.Any(x => x.IsShipEnabled) + ? ShippingStatus.Pending + : ShippingStatus.ShippingNotRequired; + + return order; + } + + private static OrderItem CopyItem(OrderItem item, DateTime createdOnUtc) + { + return new OrderItem { + OrderItemGuid = Guid.NewGuid(), + ProductId = item.ProductId, + Sku = item.Sku, + VendorId = item.VendorId, + WarehouseId = item.WarehouseId, + SeId = item.SeId, + Quantity = item.Quantity, + IsShipEnabled = item.IsShipEnabled, + // nothing of the new order is open, shipped, cancelled or returned yet + OpenQty = item.Quantity, + ShipQty = 0, + CancelQty = 0, + CancelAmount = 0, + ReturnQty = 0, + Status = OrderItemStatus.Open, + TaxRate = item.TaxRate, + UnitPriceWithoutDiscInclTax = item.UnitPriceWithoutDiscInclTax, + UnitPriceWithoutDiscExclTax = item.UnitPriceWithoutDiscExclTax, + UnitPriceInclTax = item.UnitPriceInclTax, + UnitPriceExclTax = item.UnitPriceExclTax, + PriceInclTax = item.PriceInclTax, + PriceExclTax = item.PriceExclTax, + DiscountAmountInclTax = item.DiscountAmountInclTax, + DiscountAmountExclTax = item.DiscountAmountExclTax, + OriginalProductCost = item.OriginalProductCost, + AttributeDescription = item.AttributeDescription, + Attributes = CopyAttributes(item.Attributes), + DownloadCount = 0, + IsDownloadActivated = false, + LicenseDownloadId = "", + ItemWeight = item.ItemWeight, + RentalStartDateUtc = item.RentalStartDateUtc, + RentalEndDateUtc = item.RentalEndDateUtc, + CreatedOnUtc = createdOnUtc, + Commission = item.Commission, + cId = item.cId + }; + } + + private static IList CopyAttributes(IList attributes) + { + return attributes?.Select(x => new CustomAttribute { Key = x.Key, Value = x.Value }).ToList(); + } + + private static Address CopyAddress(Address address) + { + if (address == null) return null; + return new Address { + Id = address.Id, + Name = address.Name, + FirstName = address.FirstName, + LastName = address.LastName, + Email = address.Email, + Company = address.Company, + VatNumber = address.VatNumber, + CountryId = address.CountryId, + StateProvinceId = address.StateProvinceId, + City = address.City, + Address1 = address.Address1, + Address2 = address.Address2, + ZipPostalCode = address.ZipPostalCode, + PhoneNumber = address.PhoneNumber, + FaxNumber = address.FaxNumber, + Note = address.Note, + Attributes = CopyAttributes(address.Attributes), + AddressType = address.AddressType + }; + } + + private static PickupPoint CopyPickupPoint(PickupPoint point) + { + if (point == null) return null; + return new PickupPoint { + Id = point.Id, + UserFields = point.UserFields?.Select(x => new UserField { Key = x.Key, Value = x.Value }).ToList(), + CreatedOnUtc = point.CreatedOnUtc, + CreatedBy = point.CreatedBy, + UpdatedOnUtc = point.UpdatedOnUtc, + UpdatedBy = point.UpdatedBy, + Name = point.Name, + Description = point.Description, + AdminComment = point.AdminComment, + Address = CopyAddress(point.Address), + WarehouseId = point.WarehouseId, + StoreId = point.StoreId, + PickupFee = point.PickupFee, + Latitude = point.Latitude, + Longitude = point.Longitude, + DisplayOrder = point.DisplayOrder + }; + } +} diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 024feabce..f9f07426e 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -1,6 +1,8 @@ using Grand.Business.Core.Interfaces.Catalog.Products; using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; using Grand.Data; +using Grand.Domain; using Grand.Domain.Orders; using Grand.Infrastructure.Extensions; using Grand.Mediator; @@ -10,7 +12,8 @@ namespace Grand.Business.Checkout.Services.Orders; public class RecurringPaymentService( IRepository repository, IProductService productService, - IMediator mediator) + IMediator mediator, + IResourceLock resourceLock) : IRecurringPaymentService { public virtual async Task InsertRecurringPayment(RecurringPayment recurringPayment) @@ -33,6 +36,119 @@ public virtual async Task UpdateRecurringPayment(RecurringPayment recurringPayme await mediator.EntityUpdated(recurringPayment); } + public virtual async Task ClaimCycle(string recurringPaymentId, string providerReference, + string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc) + { + ArgumentException.ThrowIfNullOrEmpty(cycleReference); + + RecurringPayment recurringPayment; + RecurringPaymentCycle cycle; + var completed = false; + + //the reference is checked and the cycle recorded while no other delivery can do the same + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null || recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + return null; + + recurringPayment.CyclesPaid++; + cycle = new RecurringPaymentCycle { + CycleNumber = recurringPayment.CyclesPaid, + //the first cycle is the order the customer placed + OrderId = recurringPayment.CyclesPaid == 1 ? recurringPayment.InitialOrderId : UniqueIdentifier.New, + ProviderReference = cycleReference, + Amount = amount, + PaidOnUtc = paidOnUtc + }; + recurringPayment.Cycles.Add(cycle); + + if (string.IsNullOrEmpty(recurringPayment.ProviderReference)) + recurringPayment.ProviderReference = providerReference; + if (nextPaymentDateUtc.HasValue) + recurringPayment.NextPaymentDateUtc = nextPaymentDateUtc; + + //LastError stays as history + if (recurringPayment.Status is RecurringPaymentStatus.Pending or RecurringPaymentStatus.PastDue) + recurringPayment.Status = RecurringPaymentStatus.Active; + + //the gateway took the money after a cancel, so the cycle is recorded and the status is left alone + if (recurringPayment.TotalCycles > 0 && recurringPayment.CyclesPaid == recurringPayment.TotalCycles && + recurringPayment.Status is not (RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed)) + { + recurringPayment.Status = RecurringPaymentStatus.Completed; + completed = true; + } + + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return new RecurringCycleClaim { RecurringPayment = recurringPayment, Cycle = cycle, Completed = completed }; + } + + public virtual async Task RecordFailure(string recurringPaymentId, string cycleReference, string reason) + { + ArgumentException.ThrowIfNullOrEmpty(cycleReference); + + RecurringPayment recurringPayment; + bool enteredPastDue; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + //a failure that arrives after the cycle was paid is a late, out of order event + if (recurringPayment == null || + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed || + recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) + return false; + + recurringPayment.LastError = reason; + recurringPayment.LastErrorDateUtc = DateTime.UtcNow; + + enteredPastDue = recurringPayment.Status != RecurringPaymentStatus.PastDue; + recurringPayment.Status = RecurringPaymentStatus.PastDue; + + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return enteredPastDue; + } + + public virtual async Task RecordEnded(string recurringPaymentId) + { + RecurringPayment recurringPayment; + + await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) + { + recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null || + recurringPayment.Status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed) + return false; + + recurringPayment.Status = RecurringPaymentStatus.Cancelled; + recurringPayment.CancelledOnUtc = DateTime.UtcNow; + recurringPayment.CancelledBy = recurringPayment.PaymentMethodSystemName; + + await repository.UpdateAsync(recurringPayment); + } + + //event notification + await mediator.EntityUpdated(recurringPayment); + + return true; + } + + private static string LockKey(string recurringPaymentId) + { + return $"{nameof(RecurringPayment)}:{recurringPaymentId}"; + } + public virtual Task GetRecurringPaymentById(string id) { return repository.GetByIdAsync(id); diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs index 0a80569c4..1a113c056 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs @@ -402,6 +402,26 @@ public virtual async Task SupportRecurringPayment(string paymentMethodSyst return await paymentMethod.SupportRecurringPayment(); } + /// + /// Asks the payment method to stop the gateway schedule of a recurring payment + /// + /// Recurring payment + /// Result; an error when the payment method could not be loaded + public virtual async Task CancelRecurringPayment(RecurringPayment recurringPayment) + { + ArgumentNullException.ThrowIfNull(recurringPayment); + + var paymentMethod = LoadPaymentMethodBySystemName(recurringPayment.PaymentMethodSystemName); + if (paymentMethod == null) + { + var result = new CancelRecurringPaymentResult(); + result.AddError("Payment method couldn't be loaded"); + return result; + } + + return await paymentMethod.CancelRecurringPayment(recurringPayment); + } + /// /// Voids a payment /// diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs new file mode 100644 index 000000000..34c07ab28 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs @@ -0,0 +1,21 @@ +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// Places the paid order of one recurring payment cycle after the first: a copy of the initial order that goes +/// through the paid-order path. The result is the placed order +/// +public class PlaceRecurringCycleOrderCommand : IRequest +{ + /// + /// The recurring payment the cycle belongs to + /// + public RecurringPayment RecurringPayment { get; set; } + + /// + /// The cycle the gateway reported, already claimed: its order identifier is the one the order is inserted with + /// + public RecurringPaymentCycle Cycle { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs new file mode 100644 index 000000000..39cce12c1 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs @@ -0,0 +1,37 @@ +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// A payment provider reports that a cycle of a recurring payment was paid. The result is true when the cycle was +/// recorded now and false when there was nothing to do (an unknown recurring payment, or a cycle already recorded) +/// +public class RecordRecurringPaymentCycleCommand : IRequest +{ + /// + /// The recurring payment the provider was given as gateway metadata + /// + public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of the subscription + /// + public string ProviderReference { get; set; } + + /// + /// The provider's reference of the cycle (the invoice or charge), so a resent report is recorded once + /// + public string CycleReference { get; set; } + + /// + /// The amount paid, in the units of + /// + public double Amount { get; set; } + + public DateTime PaidOnUtc { get; set; } + + /// + /// The next payment date the gateway reports, if any + /// + public DateTime? NextPaymentDateUtc { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs new file mode 100644 index 000000000..453261855 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs @@ -0,0 +1,12 @@ +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// A payment provider reports that a recurring payment ended at the gateway. The result is true when it was +/// cancelled +/// +public class RecordRecurringPaymentEndedCommand : IRequest +{ + public string RecurringPaymentId { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs new file mode 100644 index 000000000..60df50ea4 --- /dev/null +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -0,0 +1,19 @@ +using Grand.Mediator; + +namespace Grand.Business.Core.Commands.Checkout.Orders; + +/// +/// A payment provider reports that a cycle of a recurring payment failed. The result is true when the recurring +/// payment became past due +/// +public class RecordRecurringPaymentFailureCommand : IRequest +{ + public string RecurringPaymentId { get; set; } + + /// + /// The provider's reference of the cycle that failed + /// + public string CycleReference { get; set; } + + public string Reason { get; set; } +} diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index 96c36ca58..e0e0ba082 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -1,3 +1,4 @@ +using Grand.Business.Core.Utilities.Checkout; using Grand.Domain.Orders; namespace Grand.Business.Core.Interfaces.Checkout.Orders; @@ -17,6 +18,26 @@ public interface IRecurringPaymentService /// Task UpdateRecurringPayment(RecurringPayment recurringPayment); + /// + /// Records a cycle the provider reports as paid, once: under a lock, so a gateway resending the event claims + /// nothing. Returns null when the recurring payment is unknown or the cycle reference was already recorded + /// + Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, + double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc); + + /// + /// Records a cycle the provider reports as failed, under the same lock. Returns true only when the status moved + /// into PastDue. Nothing is recorded for an unknown recurring payment, one that is Cancelled or Completed, or a + /// cycle that was paid already + /// + Task RecordFailure(string recurringPaymentId, string cycleReference, string reason); + + /// + /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Returns false + /// for an unknown recurring payment or one that is Cancelled or Completed + /// + Task RecordEnded(string recurringPaymentId); + /// /// Gets a recurring payment /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs index 190862328..5c7b54391 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs @@ -154,6 +154,13 @@ Task> LoadAllPaymentMethods(Customer customer = null, st /// A value indicating whether recurring payments are supported Task SupportRecurringPayment(string paymentMethodSystemName); + /// + /// Asks the payment method to stop the gateway schedule of a recurring payment + /// + /// Recurring payment + /// Result; an error when the payment method could not be loaded + Task CancelRecurringPayment(RecurringPayment recurringPayment); + /// /// Voids a payment /// diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs new file mode 100644 index 000000000..92908ee58 --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs @@ -0,0 +1,24 @@ +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// A paid cycle recorded on a recurring payment +/// +public class RecurringCycleClaim +{ + /// + /// The recurring payment as saved + /// + public RecurringPayment RecurringPayment { get; init; } + + /// + /// The cycle that was recorded + /// + public RecurringPaymentCycle Cycle { get; init; } + + /// + /// Gets a value indicating whether this cycle completed the recurring payment + /// + public bool Completed { get; init; } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs new file mode 100644 index 000000000..0fbbd5254 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceRecurringCycleOrderCommandHandlerTests.cs @@ -0,0 +1,339 @@ +using Grand.Business.Checkout.Commands.Handlers.Orders; +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Commands.Messages.Common; +using Grand.Business.Core.Events.Checkout.Orders; +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.GiftVouchers; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Catalog; +using Grand.Domain.Common; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Mediator; +using Grand.SharedKernel; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders; + +[TestClass] +public class PlaceRecurringCycleOrderCommandHandlerTests +{ + private readonly List _calls = []; + private PlaceRecurringCycleOrderCommandHandler _handler; + private Mock _inventoryMock; + private Mock _mediatorMock; + private Mock _orderServiceMock; + private Mock _paymentTransactionServiceMock; + private Mock _productServiceMock; + private Mock _customerServiceMock; + private Mock _giftVoucherServiceMock; + + private Order _initialOrder; + private Customer _customer; + private RecurringPayment _recurringPayment; + private RecurringPaymentCycle _cycle; + private Order _insertedOrder; + private PaymentTransaction _insertedTransaction; + private readonly List _notes = []; + + [TestInitialize] + public void Init() + { + _calls.Clear(); + _notes.Clear(); + _insertedOrder = null; + _insertedTransaction = null; + + _mediatorMock = new Mock(); + _orderServiceMock = new Mock(); + _paymentTransactionServiceMock = new Mock(); + _productServiceMock = new Mock(); + _inventoryMock = new Mock(); + _customerServiceMock = new Mock(); + _giftVoucherServiceMock = new Mock(); + _giftVoucherServiceMock.Setup(x => x.GetAllGiftVoucherUsageHistory(It.IsAny())) + .ReturnsAsync(new List()); + + _handler = new PlaceRecurringCycleOrderCommandHandler(_orderServiceMock.Object, + _paymentTransactionServiceMock.Object, _productServiceMock.Object, _inventoryMock.Object, + _customerServiceMock.Object, _giftVoucherServiceMock.Object, _mediatorMock.Object, + new Mock>().Object); + + _initialOrder = new Order { + Id = "o1", + OrderNumber = 17, + StoreId = "s1", + CustomerId = "c1", + CustomerEmail = "buyer@shop.com", + PaymentMethodSystemName = "Payments.Stripe", + CustomerCurrencyCode = "EUR", + CurrencyRate = 1.5, + OrderTotal = 100 + }; + _initialOrder.OrderItems.Add(new OrderItem { + ProductId = "p1", Quantity = 2, WarehouseId = "w1", IsShipEnabled = true, + Attributes = [new CustomAttribute { Key = "k", Value = "v" }] + }); + _initialOrder.OrderItems.Add(new OrderItem { ProductId = "p2", Quantity = 3, WarehouseId = "w1" }); + + _customer = new Customer { Id = "c1" }; + _recurringPayment = new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Stripe" + }; + _cycle = new RecurringPaymentCycle { + OrderId = "cycle-order", CycleNumber = 2, ProviderReference = "in_2", Amount = 100 + }; + + _orderServiceMock.Setup(x => x.GetOrderById("o1")).ReturnsAsync(_initialOrder); + _orderServiceMock.Setup(x => x.InsertOrder(It.IsAny())) + .Callback(o => { + _insertedOrder = o; + _calls.Add("InsertOrder"); + }) + .Returns(Task.CompletedTask); + _orderServiceMock.Setup(x => x.InsertOrderNote(It.IsAny())) + .Callback(n => _notes.Add(n)) + .Returns(Task.CompletedTask); + _paymentTransactionServiceMock.Setup(x => x.InsertPaymentTransaction(It.IsAny())) + .Callback(t => { + _insertedTransaction = t; + _calls.Add("InsertPaymentTransaction"); + }) + .Returns(Task.CompletedTask); + _customerServiceMock.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(_customer); + _productServiceMock.Setup(x => x.GetProductById("p1", false)).ReturnsAsync(new Product { Id = "p1" }); + _productServiceMock.Setup(x => x.GetProductById("p2", false)).ReturnsAsync(new Product { Id = "p2" }); + + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync("CODE-1"); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback((_, _) => _calls.Add("OrderNotification")) + .Returns(Task.CompletedTask); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback, CancellationToken>((_, _) => _calls.Add("CheckOrderStatus")) + .ReturnsAsync(true); + _mediatorMock.Setup(x => x.Publish(It.IsAny(), It.IsAny())) + .Callback((_, _) => _calls.Add("OrderPlacedEvent")) + .Returns(Task.CompletedTask); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback, CancellationToken>((_, _) => _calls.Add("MarkAsPaid")) + .ReturnsAsync(true); + _mediatorMock.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .Callback, CancellationToken>((_, _) => _calls.Add("PartiallyPaidOffline")) + .ReturnsAsync(true); + } + + private Task Place() + { + return _handler.Handle(new PlaceRecurringCycleOrderCommand { + RecurringPayment = _recurringPayment, Cycle = _cycle + }, CancellationToken.None); + } + + [TestMethod] + public async Task Handle_InsertsTheCopyWithTheClaimedIdAndAPendingTransaction() + { + var order = await Place(); + + Assert.IsNotNull(_insertedOrder); + Assert.AreSame(_insertedOrder, order); + Assert.AreEqual("cycle-order", _insertedOrder.Id); + Assert.AreEqual("o1", _insertedOrder.InitialOrderId); + Assert.AreEqual(2, _insertedOrder.RecurringCycleNumber); + Assert.AreEqual("CODE-1", _insertedOrder.Code); + + Assert.IsNotNull(_insertedTransaction); + Assert.AreEqual(_insertedOrder.OrderGuid, _insertedTransaction.OrderGuid); + Assert.AreEqual("CODE-1", _insertedTransaction.OrderCode); + Assert.AreEqual(TransactionStatus.Pending, _insertedTransaction.TransactionStatus); + Assert.AreEqual(_insertedOrder.OrderTotal, _insertedTransaction.TransactionAmount); + Assert.IsFalse(_insertedTransaction.Temp); + Assert.AreEqual("s1", _insertedTransaction.StoreId); + Assert.AreEqual("c1", _insertedTransaction.CustomerId); + Assert.AreEqual("buyer@shop.com", _insertedTransaction.CustomerEmail); + Assert.AreEqual("Payments.Stripe", _insertedTransaction.PaymentMethodSystemName); + Assert.AreEqual("EUR", _insertedTransaction.CurrencyCode); + Assert.AreEqual(1.5, _insertedTransaction.CurrencyRate); + // the transaction is written before the order, as in placement + Assert.IsTrue(_calls.IndexOf("InsertPaymentTransaction") < _calls.IndexOf("InsertOrder")); + } + + [TestMethod] + public async Task Handle_ReservesStockWithoutCheckingIt() + { + await Place(); + + _inventoryMock.Verify(x => x.AdjustReserved(It.Is(p => p.Id == "p1"), -2, + It.Is>(a => a.Count == 1 && a[0].Key == "k"), "w1"), Times.Once); + _inventoryMock.Verify(x => x.AdjustReserved(It.Is(p => p.Id == "p2"), -3, + It.IsAny>(), "w1"), Times.Once); + _inventoryMock.Verify(x => x.AdjustReserved(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Exactly(2)); + _inventoryMock.Verify(x => x.TryReserve(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_ASoldCountThatCannotBeWritten_DoesNotStopTheOrder() + { + _productServiceMock.Setup(x => x.IncrementProductField(It.IsAny(), + It.IsAny>>(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("db")); + + var order = await Place(); + + Assert.AreSame(_insertedOrder, order); + Assert.IsTrue(_calls.Contains("MarkAsPaid")); + } + + [TestMethod] + public async Task Handle_AProductThatNoLongerExists_IsSkipped() + { + _productServiceMock.Setup(x => x.GetProductById("p1", false)).ReturnsAsync((Product)null); + + await Place(); + + _inventoryMock.Verify(x => x.AdjustReserved(It.IsAny(), It.IsAny(), + It.IsAny>(), It.IsAny()), Times.Once); + Assert.IsTrue(_calls.Contains("MarkAsPaid")); + } + + [TestMethod] + public async Task Handle_GoesThroughTheNormalPaidOrderPath() + { + await Place(); + + CollectionAssert.AreEqual( + new[] { + "InsertPaymentTransaction", "InsertOrder", "OrderNotification", "CheckOrderStatus", + "OrderPlacedEvent", "MarkAsPaid" + }, _calls); + + _mediatorMock.Verify(x => x.Send(It.Is(c => + c.Order == _insertedOrder && c.Customer == _customer && c.Host == null), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.Is(c => c.Order == _insertedOrder), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Publish(It.Is(e => e.Order == _insertedOrder), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.Is(c => + c.PaymentTransaction == _insertedTransaction && c.Amount == 100 && c.Reference == "in_2" && + c.CreatedBy == "Payments.Stripe"), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task Handle_AddsTheCycleNote() + { + await Place(); + + Assert.AreEqual(1, _notes.Count); + Assert.AreEqual("Cycle 2 of the recurring payment of order #17", _notes[0].Note); + Assert.AreEqual("cycle-order", _notes[0].OrderId); + Assert.IsFalse(_notes[0].DisplayToCustomer); + } + + [TestMethod] + public async Task Handle_GatewayChargedLess_RecordsAPartialPaymentAndANote() + { + _cycle.Amount = 95; + + await Place(); + + Assert.AreEqual(2, _notes.Count); + Assert.AreEqual("The payment gateway charged 95.00 EUR for this cycle; the order total is 100.00 EUR", + _notes[1].Note); + Assert.AreEqual("cycle-order", _notes[1].OrderId); + // the note comes after the payment is recorded + Assert.AreEqual("PartiallyPaidOffline", _calls[^1]); + _mediatorMock.Verify(x => x.Send(It.Is(c => + c.PaymentTransaction == _insertedTransaction && c.AmountToPaid == 95 && c.Reference == "in_2" && + c.CreatedBy == "Payments.Stripe"), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_GatewayChargedNothing_RecordsNoPayment() + { + _cycle.Amount = 0; + + await Place(); + + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), Times.Never); + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + Assert.AreEqual(2, _notes.Count); + Assert.AreEqual("The payment gateway charged 0.00 EUR for this cycle; the order total is 100.00 EUR", + _notes[1].Note); + } + + [TestMethod] + public async Task Handle_GatewayChargedMore_MarksPaidAndAddsANote() + { + _cycle.Amount = 105; + + await Place(); + + _mediatorMock.Verify(x => x.Send(It.Is(c => c.Amount == 105), + It.IsAny()), Times.Once); + _mediatorMock.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + Assert.AreEqual("The payment gateway charged 105.00 EUR for this cycle; the order total is 100.00 EUR", + _notes[1].Note); + } + + [TestMethod] + public async Task Handle_AmountsEqualAfterRounding_AddsOnlyTheCycleNote() + { + _cycle.Amount = 100.004; + + await Place(); + + Assert.AreEqual(1, _notes.Count); + } + + [TestMethod] + public async Task Handle_InitialOrderDeleted_Throws() + { + _initialOrder.Deleted = true; + + await Assert.ThrowsExactlyAsync(Place); + + _orderServiceMock.Verify(x => x.InsertOrder(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_InitialOrderMissing_Throws() + { + _orderServiceMock.Setup(x => x.GetOrderById("o1")).ReturnsAsync((Order)null); + + var exception = await Assert.ThrowsExactlyAsync(Place); + + Assert.AreEqual("The initial order o1 of recurring payment rp1 was not found", exception.Message); + _orderServiceMock.Verify(x => x.InsertOrder(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task Handle_GiftVouchersSpentOnTheInitialOrderAreAddedBackToTheTotal() + { + _giftVoucherServiceMock.Setup(x => x.GetAllGiftVoucherUsageHistory("o1")) + .ReturnsAsync(new List { + new() { UsedWithOrderId = "o1", UsedValue = 15 }, + new() { UsedWithOrderId = "o1", UsedValue = 5 } + }); + _cycle.Amount = 120; + + var order = await Place(); + + Assert.AreEqual(120, order.OrderTotal); + Assert.AreEqual(120, _insertedTransaction.TransactionAmount); + Assert.IsTrue(_calls.Contains("MarkAsPaid")); + Assert.IsFalse(_notes.Any(n => n.Note.Contains("charged"))); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs new file mode 100644 index 000000000..7bedd8994 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RecordRecurringPaymentCommandHandlersTests.cs @@ -0,0 +1,328 @@ +using Grand.Business.Checkout.Commands.Handlers.Orders; +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; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders; + +[TestClass] +public class RecordRecurringPaymentCommandHandlersTests +{ + private Mock _service; + private Mock _paymentService; + private Mock _orderService; + private Mock _mediator; + + [TestInitialize] + public void Init() + { + _service = new Mock(); + _paymentService = new Mock(); + _orderService = new Mock(); + _mediator = new Mock(); + } + + [TestMethod] + public async Task FailureCommand_PassesTheReportToTheService() + { + _service.Setup(x => x.RecordFailure("rp1", "in_2", "declined")).ReturnsAsync(true); + var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + + var result = await handler.Handle(new RecordRecurringPaymentFailureCommand { + RecurringPaymentId = "rp1", CycleReference = "in_2", Reason = "declined" + }, CancellationToken.None); + + Assert.IsTrue(result); + _service.Verify(x => x.RecordFailure("rp1", "in_2", "declined"), Times.Once); + } + + [TestMethod] + public async Task FailureCommand_WithoutRecurringPaymentId_Throws() + { + var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + + await Assert.ThrowsExactlyAsync(() => + handler.Handle(new RecordRecurringPaymentFailureCommand { RecurringPaymentId = "" }, CancellationToken.None)); + } + + [TestMethod] + public async Task EndedCommand_PassesTheReportToTheService() + { + _service.Setup(x => x.RecordEnded("rp1")).ReturnsAsync(true); + var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + + var result = await handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "rp1" }, + CancellationToken.None); + + Assert.IsTrue(result); + _service.Verify(x => x.RecordEnded("rp1"), Times.Once); + } + + [TestMethod] + public async Task EndedCommand_WithoutRecurringPaymentId_Throws() + { + var handler = new RecordRecurringPaymentEndedCommandHandler(_service.Object); + + await Assert.ThrowsExactlyAsync(() => + handler.Handle(new RecordRecurringPaymentEndedCommand { RecurringPaymentId = "" }, CancellationToken.None)); + } + + private RecordRecurringPaymentCycleCommandHandler CycleHandler() + { + return new RecordRecurringPaymentCycleCommandHandler(_service.Object, _paymentService.Object, + _orderService.Object, _mediator.Object, new Mock>().Object); + } + + private static RecordRecurringPaymentCycleCommand CycleCommand() + { + return new RecordRecurringPaymentCycleCommand { + RecurringPaymentId = "rp1", ProviderReference = "sub_1", CycleReference = "in_2", Amount = 10, + PaidOnUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) + }; + } + + private void SetupClaim(int cycleNumber, RecurringPaymentStatus status = RecurringPaymentStatus.Active) + { + var claim = new RecurringCycleClaim { + RecurringPayment = new RecurringPayment { + Id = "rp1", InitialOrderId = "o1", PaymentMethodSystemName = "Payments.Test", Status = status + }, + Cycle = new RecurringPaymentCycle { CycleNumber = cycleNumber, OrderId = "o2" } + }; + _service.Setup(x => x.ClaimCycle("rp1", "sub_1", "in_2", 10, It.IsAny(), null)).ReturnsAsync(claim); + } + + [TestMethod] + public async Task CycleCommand_AlreadyRecorded_DoesNothing() + { + _service.Setup(x => x.ClaimCycle(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync((RecurringCycleClaim)null); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsFalse(result); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task CycleCommand_FirstCycle_PlacesNoOrder() + { + SetupClaim(1); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task CycleCommand_LaterCycle_PlacesTheCycleOrder() + { + SetupClaim(2); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _mediator.Verify(x => x.Send(It.Is(c => + c.RecurringPayment.Id == "rp1" && c.Cycle.CycleNumber == 2), It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task CycleCommand_OrderCannotBeCreated_NotesItOnTheInitialOrderAndThrows() + { + SetupClaim(2); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("boom")); + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == "o1" && !n.DisplayToCustomer && n.Note == + "Cycle 2 was paid at the payment gateway (in_2), but its order o2 could not be placed or marked paid: boom")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_Completed_AsksTheProviderToStop() + { + SetupClaim(3, RecurringPaymentStatus.Completed); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + _orderService.Verify(x => x.InsertOrderNote(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CycleCommand_NotCompleted_DoesNotAskTheProviderToStop() + { + SetupClaim(3); + + await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task CycleCommand_CompletedAndProviderRefuses_NotesItOnTheInitialOrder() + { + SetupClaim(3, RecurringPaymentStatus.Completed); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == "o1" && !n.DisplayToCustomer && + n.Note == "The recurring payment is completed, but the payment gateway did not confirm it stopped charging: no way")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_NoteCannotBeWritten_StillThrowsTheOriginalException() + { + SetupClaim(2); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("boom")); + _orderService.Setup(x => x.InsertOrderNote(It.IsAny())).ThrowsAsync(new TimeoutException("db")); + + var e = await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + Assert.AreEqual("boom", e.Message); + } + + [TestMethod] + public async Task CycleCommand_CompletedAndNoteCannotBeWritten_StillSucceeds() + { + SetupClaim(3, RecurringPaymentStatus.Completed); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + _orderService.Setup(x => x.InsertOrderNote(It.IsAny())).ThrowsAsync(new TimeoutException("db")); + + Assert.IsTrue(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_CompletedAndProviderThrows_NotesItAndDoesNotRethrow() + { + SetupClaim(3, RecurringPaymentStatus.Completed); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ThrowsAsync(new HttpRequestException("network down")); + + var result = await CycleHandler().Handle(CycleCommand(), CancellationToken.None); + + Assert.IsTrue(result); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.OrderId == "o1" && n.Note == + "The recurring payment is completed, but the payment gateway did not confirm it stopped charging: network down")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_ClaimedWhileCancelled_AsksTheProviderToStopAndNotesTheRefusal() + { + SetupClaim(3, RecurringPaymentStatus.Cancelled); + var refusal = new CancelRecurringPaymentResult(); + refusal.AddError("no way"); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())).ReturnsAsync(refusal); + + Assert.IsTrue(await CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + _orderService.Verify(x => x.InsertOrderNote(It.Is(n => + n.Note == "The recurring payment is cancelled, but the payment gateway did not confirm it stopped charging: no way")), + Times.Once); + } + + [TestMethod] + public async Task CycleCommand_FinalOrderCannotBePlaced_StillStopsTheGatewayAndThrowsTheOriginalException() + { + SetupClaim(3, RecurringPaymentStatus.Completed); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("boom")); + _paymentService.Setup(x => x.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + var e = await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(CycleCommand(), CancellationToken.None)); + + Assert.AreEqual("boom", e.Message); + _paymentService.Verify(x => x.CancelRecurringPayment(It.Is(r => r.Id == "rp1")), Times.Once); + } + + [TestMethod] + public async Task CycleCommand_AfterTheClaim_IgnoresTheRequestCancellation() + { + SetupClaim(2); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + + await CycleHandler().Handle(CycleCommand(), cts.Token); + + _mediator.Verify(x => x.Send(It.IsAny(), CancellationToken.None), Times.Once); + } + + [TestMethod] + public async Task CycleCommand_WithoutCycleReference_Throws() + { + var command = CycleCommand(); + command.CycleReference = ""; + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(command, CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_NegativeAmount_Throws() + { + var command = CycleCommand(); + command.Amount = -1; + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(command, CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_NaNAmount_Throws() + { + var command = CycleCommand(); + command.Amount = double.NaN; + + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(command, CancellationToken.None)); + } + + [TestMethod] + public async Task FailureCommand_WithoutCycleReference_Throws() + { + var handler = new RecordRecurringPaymentFailureCommandHandler(_service.Object); + + await Assert.ThrowsExactlyAsync(() => + handler.Handle(new RecordRecurringPaymentFailureCommand { RecurringPaymentId = "rp1", CycleReference = "" }, + CancellationToken.None)); + } + + [TestMethod] + public async Task CycleCommand_WithoutRecurringPaymentId_Throws() + { + await Assert.ThrowsExactlyAsync(() => + CycleHandler().Handle(new RecordRecurringPaymentCycleCommand { RecurringPaymentId = "" }, + CancellationToken.None)); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs new file mode 100644 index 000000000..e0c9c3f94 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/RecurringCycleOrderTests.cs @@ -0,0 +1,395 @@ +using System.Collections; +using System.Reflection; +using Grand.Business.Checkout.Extensions; +using Grand.Domain.Common; +using Grand.Domain.Orders; +using Grand.Domain.Payments; +using Grand.Domain.Shipping; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Business.Checkout.Tests.Extensions; + +[TestClass] +public class RecurringCycleOrderTests +{ + private static readonly DateTime CreatedOn = new(2026, 12, 1, 10, 0, 0, DateTimeKind.Utc); + + // properties the copy sets or resets, with the value it must hold + private static readonly Dictionary ResetProperties = new() { + { nameof(Order.Id), "c2" }, + { nameof(Order.OrderNumber), 0 }, + { nameof(Order.Code), "ABC" }, + { nameof(Order.InitialOrderId), null }, // checked in the loop: the initial order's id + { nameof(Order.RecurringCycleNumber), 2 }, + { nameof(Order.CreatedOnUtc), CreatedOn }, + { nameof(Order.CreatedBy), null }, + { nameof(Order.UpdatedOnUtc), null }, + { nameof(Order.UpdatedBy), null }, + { nameof(Order.OrderStatusId), (int)OrderStatusSystem.Pending }, + { nameof(Order.PaymentStatusId), PaymentStatus.Pending }, + { nameof(Order.ShippingStatusId), ShippingStatus.Pending }, + { nameof(Order.PaidAmount), 0d }, + { nameof(Order.PaidDateUtc), null }, + { nameof(Order.PaymentDueDateUtc), null }, + { nameof(Order.PaymentReminderSentOnUtc), null }, + { nameof(Order.PaymentOverdueNoticeSentOnUtc), null }, + { nameof(Order.RefundedAmount), 0d }, + { nameof(Order.RedeemedLoyaltyPoints), 0 }, + { nameof(Order.RedeemedLoyaltyPointsAmount), 0d }, + { nameof(Order.LoyaltyPointsWereAdded), false }, + { nameof(Order.CalcLoyaltyPoints), 0 }, + { nameof(Order.OrderTotal), 100d }, // the initial total (90) plus the points amount (10) + { nameof(Order.Deleted), false }, + { nameof(Order.Imported), false }, + { nameof(Order.OrderGuid), null }, // checked in the loop: a new guid + { nameof(Order.UserFields), null } // checked in the loop: empty + }; + + private static OrderItem Item(string productId, bool ship = true) + { + return new OrderItem { + OrderItemGuid = Guid.NewGuid(), + ProductId = productId, + Sku = "sku-" + productId, + VendorId = "v1", + WarehouseId = "w1", + SeId = "se1", + Quantity = 3, + IsShipEnabled = ship, + OpenQty = 1, + ShipQty = 2, + CancelQty = 1, + CancelAmount = 5, + ReturnQty = 1, + Status = OrderItemStatus.Close, + TaxRate = 23, + UnitPriceWithoutDiscInclTax = 12.5, + UnitPriceWithoutDiscExclTax = 10.2, + UnitPriceInclTax = 12, + UnitPriceExclTax = 9.76, + PriceInclTax = 36, + PriceExclTax = 29.28, + DiscountAmountInclTax = 1.5, + DiscountAmountExclTax = 1.2, + OriginalProductCost = 4, + AttributeDescription = "Color: red", + Attributes = new List { new() { Key = "color", Value = "red" } }, + DownloadCount = 4, + IsDownloadActivated = true, + LicenseDownloadId = "dl1", + ItemWeight = 2.5, + RentalStartDateUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), + RentalEndDateUtc = new DateTime(2026, 1, 5, 0, 0, 0, DateTimeKind.Utc), + CreatedOnUtc = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc), + Commission = 0.7, + cId = "c-owner" + }; + } + + private static Order Initial() + { + var order = new Order { + Id = "o1", + OrderGuid = Guid.NewGuid(), + OrderNumber = 17, + Code = "INIT", + OrderTotal = 120, + CurrencyRate = 4.3, + PaidAmount = 120, + PaidDateUtc = new DateTime(2026, 11, 2, 0, 0, 0, DateTimeKind.Utc), + OrderStatusId = (int)OrderStatusSystem.Complete, + PaymentStatusId = PaymentStatus.Paid, + ShippingStatusId = ShippingStatus.Delivered, + BillingAddress = new Address { + City = "Warsaw", Attributes = new List { new() { Key = "a", Value = "b" } } + }, + ShippingAddress = new Address { City = "Krakow" }, + IsRecurring = true, + RecurringCycleNumber = 1 + }; + order.OrderItems.Add(Item("p1")); + order.OrderItems.Add(Item("p2")); + return order; + } + + [TestMethod] + public void Copy_KeepsPricesAddressesAndItems() + { + var initial = Initial(); + initial.OrderTaxes.Add(new OrderTax { Percent = 23, Amount = 22.4 }); + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); + + Assert.AreEqual(120, copy.OrderTotal); + Assert.AreEqual(4.3, copy.CurrencyRate); + Assert.AreEqual(2, copy.OrderItems.Count); + var source = initial.OrderItems.ToList(); + var items = copy.OrderItems.ToList(); + for (var i = 0; i < items.Count; i++) + { + Assert.AreNotSame(source[i], items[i]); + Assert.AreNotEqual(source[i].Id, items[i].Id); + Assert.AreEqual(source[i].UnitPriceInclTax, items[i].UnitPriceInclTax); + Assert.AreEqual(source[i].PriceInclTax, items[i].PriceInclTax); + Assert.AreEqual("w1", items[i].WarehouseId); + Assert.AreEqual(source[i].ProductId, items[i].ProductId); + Assert.AreEqual(source[i].cId, items[i].cId); + Assert.AreNotSame(source[i].Attributes, items[i].Attributes); + Assert.AreEqual(1, items[i].Attributes.Count); + Assert.AreEqual("color", items[i].Attributes[0].Key); + Assert.AreEqual("red", items[i].Attributes[0].Value); + Assert.AreEqual(CreatedOn, items[i].CreatedOnUtc); + } + + Assert.AreEqual(1, copy.OrderTaxes.Count); + Assert.AreEqual(23, copy.OrderTaxes.First().Percent); + Assert.AreEqual(22.4, copy.OrderTaxes.First().Amount); + Assert.AreNotSame(initial.OrderTaxes.First(), copy.OrderTaxes.First()); + Assert.AreEqual(0, copy.OrderTags.Count); + + Assert.AreNotSame(initial.BillingAddress, copy.BillingAddress); + Assert.AreEqual("Warsaw", copy.BillingAddress.City); + Assert.AreNotSame(initial.BillingAddress.Attributes, copy.BillingAddress.Attributes); + Assert.AreEqual("a", copy.BillingAddress.Attributes[0].Key); + Assert.AreNotSame(initial.ShippingAddress, copy.ShippingAddress); + Assert.AreEqual("Krakow", copy.ShippingAddress.City); + } + + [TestMethod] + public void Copy_IsANewUnpaidOrderLinkedToTheInitialOne() + { + var initial = Initial(); + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); + + Assert.AreEqual("c2", copy.Id); + Assert.AreEqual("ABC", copy.Code); + Assert.AreEqual(initial.Id, copy.InitialOrderId); + Assert.AreEqual(2, copy.RecurringCycleNumber); + Assert.AreEqual(PaymentStatus.Pending, copy.PaymentStatusId); + Assert.AreEqual(0, copy.PaidAmount); + Assert.IsNull(copy.PaidDateUtc); + Assert.AreEqual((int)OrderStatusSystem.Pending, copy.OrderStatusId); + Assert.AreEqual(0, copy.OrderNumber); + Assert.AreNotEqual(initial.OrderGuid, copy.OrderGuid); + Assert.AreEqual(CreatedOn, copy.CreatedOnUtc); + Assert.AreEqual(ShippingStatus.Pending, copy.ShippingStatusId); + Assert.AreEqual(2, copy.OrderItems.Count); + foreach (var item in copy.OrderItems) + { + Assert.IsFalse(initial.OrderItems.Any(i => i.OrderItemGuid == item.OrderItemGuid)); + Assert.AreEqual(item.Quantity, item.OpenQty); + Assert.AreEqual(0, item.ShipQty); + Assert.AreEqual(0, item.CancelQty); + Assert.AreEqual(0, item.ReturnQty); + Assert.AreEqual(0, item.CancelAmount); + Assert.AreEqual(OrderItemStatus.Open, item.Status); + Assert.AreEqual(0, item.DownloadCount); + Assert.IsFalse(item.IsDownloadActivated); + Assert.AreEqual("", item.LicenseDownloadId); + } + } + + [TestMethod] + public void Copy_LoyaltyPointsSpentOnTheInitialOrderAreNotSpentAgain() + { + var initial = Initial(); + initial.OrderTotal = 90; + initial.RedeemedLoyaltyPoints = 100; + initial.RedeemedLoyaltyPointsAmount = 10; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); + + Assert.AreEqual(100, copy.OrderTotal); + Assert.AreEqual(0, copy.RedeemedLoyaltyPoints); + Assert.AreEqual(0, copy.RedeemedLoyaltyPointsAmount); + } + + [TestMethod] + public void Copy_GiftVouchersSpentOnTheInitialOrderAreNotSpentAgain() + { + var initial = Initial(); + initial.OrderTotal = 75; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 25); + + Assert.AreEqual(100, copy.OrderTotal); + } + + [TestMethod] + public void Copy_NothingToShip_ShippingNotRequired() + { + var initial = Initial(); + foreach (var item in initial.OrderItems) item.IsShipEnabled = false; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); + + Assert.AreEqual(ShippingStatus.ShippingNotRequired, copy.ShippingStatusId); + } + + [TestMethod] + public void Copy_EveryOrderPropertyIsCopiedOrDeliberatelyReset() + { + // OrderItems, OrderTaxes and OrderTags have protected setters; the explicit tests cover them + var properties = typeof(Order).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.SetMethod is { IsPublic: true }).ToList(); + foreach (var name in ResetProperties.Keys) + Assert.IsTrue(properties.Any(p => p.Name == name), $"{name} is not a settable Order property"); + + var initial = new Order(); + var n = 1; + foreach (var property in properties) + property.SetValue(initial, Distinct(property.PropertyType, property.Name, n++)); + initial.OrderItems.Add(Item("p1")); + initial.OrderTotal = 90; + initial.RedeemedLoyaltyPointsAmount = 10; + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0); + + foreach (var property in properties) + { + var actual = property.GetValue(copy); + if (!ResetProperties.TryGetValue(property.Name, out var expected)) + { + AssertSameValue(property.GetValue(initial), actual, property.Name); + continue; + } + + switch (property.Name) + { + case nameof(Order.OrderGuid): + Assert.AreNotEqual(Guid.Empty, actual); + Assert.AreNotEqual(initial.OrderGuid, actual); + break; + case nameof(Order.UserFields): + Assert.AreEqual(0, ((ICollection)actual).Count); + break; + case nameof(Order.InitialOrderId): + Assert.AreEqual(initial.Id, actual); + break; + default: + Assert.AreEqual(expected, actual, property.Name); + break; + } + } + } + + [TestMethod] + public void Copy_EveryOrderItemPropertyIsCopiedOrDeliberatelyReset() + { + var properties = typeof(OrderItem).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.SetMethod is { IsPublic: true }).ToList(); + var reset = new[] { + nameof(OrderItem.Id), nameof(OrderItem.OrderItemGuid), nameof(OrderItem.OpenQty), + nameof(OrderItem.ShipQty), nameof(OrderItem.CancelQty), nameof(OrderItem.CancelAmount), + nameof(OrderItem.Status), nameof(OrderItem.ReturnQty), nameof(OrderItem.DownloadCount), + nameof(OrderItem.IsDownloadActivated), nameof(OrderItem.LicenseDownloadId), + nameof(OrderItem.CreatedOnUtc) + }; + foreach (var name in reset) + Assert.IsTrue(properties.Any(p => p.Name == name), $"{name} is not a settable OrderItem property"); + + var source = new OrderItem(); + var n = 1; + foreach (var property in properties) + property.SetValue(source, Distinct(property.PropertyType, property.Name, n++)); + var initial = new Order(); + initial.OrderItems.Add(source); + + var copy = RecurringCycleOrder.Copy(initial, "c2", 2, "ABC", CreatedOn, 0).OrderItems.Single(); + + foreach (var property in properties) + { + var actual = property.GetValue(copy); + switch (property.Name) + { + case nameof(OrderItem.Id): + Assert.IsFalse(string.IsNullOrEmpty((string)actual)); + Assert.AreNotEqual(source.Id, actual); + break; + case nameof(OrderItem.OrderItemGuid): + Assert.AreNotEqual(Guid.Empty, actual); + Assert.AreNotEqual(source.OrderItemGuid, actual); + break; + case nameof(OrderItem.OpenQty): + Assert.AreEqual(source.Quantity, actual); + break; + case nameof(OrderItem.ShipQty): + case nameof(OrderItem.CancelQty): + case nameof(OrderItem.ReturnQty): + case nameof(OrderItem.DownloadCount): + Assert.AreEqual(0, actual, property.Name); + break; + case nameof(OrderItem.CancelAmount): + Assert.AreEqual(0d, actual); + break; + case nameof(OrderItem.Status): + Assert.AreEqual(OrderItemStatus.Open, actual); + break; + case nameof(OrderItem.IsDownloadActivated): + Assert.AreEqual(false, actual); + break; + case nameof(OrderItem.LicenseDownloadId): + Assert.AreEqual("", actual); + break; + case nameof(OrderItem.CreatedOnUtc): + Assert.AreEqual(CreatedOn, actual); + break; + default: + AssertSameValue(property.GetValue(source), actual, property.Name); + break; + } + } + } + + private static object Distinct(Type type, string name, int n) + { + type = Nullable.GetUnderlyingType(type) ?? type; + if (type == typeof(string)) return $"{name}-{n}"; + if (type == typeof(int)) return n + 1000; + if (type == typeof(double)) return n + 0.5; + if (type == typeof(bool)) return true; + if (type == typeof(Guid)) return Guid.NewGuid(); + if (type == typeof(DateTime)) return new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(n); + if (type.IsEnum) return Enum.GetValues(type).Cast().Last(); + if (type == typeof(IList)) + return new List { new() { Key = $"{name}-k", Value = $"{name}-v" } }; + if (type == typeof(IList)) + return new List { new() { Key = $"{name}-k", Value = $"{name}-v" } }; + if (type == typeof(Address) || type == typeof(PickupPoint)) + { + var value = Activator.CreateInstance(type)!; + var i = 1; + foreach (var p in type.GetProperties().Where(p => p.SetMethod is { IsPublic: true })) + p.SetValue(value, Distinct(p.PropertyType, $"{name}.{p.Name}", n * 100 + i++)); + return value; + } + + // a new property of another type must teach this test how to fill and compare it + throw new NotSupportedException($"Order.{name} has a type this test cannot fill: {type}"); + } + + private static void AssertSameValue(object expected, object actual, string path) + { + if (expected is null || expected is string || expected.GetType().IsValueType) + { + Assert.AreEqual(expected, actual, path); + return; + } + + Assert.IsNotNull(actual, path); + Assert.AreNotSame(expected, actual, path); + if (expected is IEnumerable expectedList) + { + var e = expectedList.Cast().ToList(); + var a = ((IEnumerable)actual).Cast().ToList(); + Assert.AreEqual(e.Count, a.Count, path); + for (var i = 0; i < e.Count; i++) AssertSameValue(e[i], a[i], $"{path}[{i}]"); + return; + } + + // an entity or address: a new instance holding the same values + foreach (var p in expected.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + AssertSameValue(p.GetValue(expected), p.GetValue(actual), $"{path}.{p.Name}"); + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs index 9c9d6456b..dbb56ddee 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -3,6 +3,7 @@ using Grand.Data; using Grand.Data.Tests.MongoDb; using Grand.Domain.Catalog; +using Grand.Domain; using Grand.Domain.Orders; using Grand.Mediator; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -15,6 +16,8 @@ public class RecurringPaymentServiceTests { private Mock _productService; private IRepository _repository; + private IMediator _mediator; + private IResourceLock _resourceLock; private RecurringPaymentService _service; [TestInitialize] @@ -25,7 +28,9 @@ public void Init() _productService.Setup(x => x.GetProductById("standard", false)).ReturnsAsync(new Product { Id = "standard" }); _productService.Setup(x => x.GetProductById("recurring", false)) .ReturnsAsync(new Product { Id = "recurring", IsRecurring = true }); - _service = new RecurringPaymentService(_repository, _productService.Object, new Mock().Object); + _mediator = new Mock().Object; + _resourceLock = new MongoResourceLockTest(); + _service = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); } [TestMethod] @@ -82,4 +87,234 @@ public async Task InsertRecurringPayment_Null_Throws() { await Assert.ThrowsExactlyAsync(() => _service.InsertRecurringPayment(null)); } + + private async Task Insert(RecurringPaymentStatus status, int cyclesPaid, int totalCycles = 12, + string lastError = null) + { + var rp = new RecurringPayment { + InitialOrderId = "o1", Status = status, CyclesPaid = cyclesPaid, TotalCycles = totalCycles, + LastError = lastError + }; + for (var i = 1; i <= cyclesPaid; i++) + rp.Cycles.Add(new RecurringPaymentCycle { + CycleNumber = i, OrderId = $"o{i}", ProviderReference = $"in_{i}" + }); + await _service.InsertRecurringPayment(rp); + return rp; + } + + [TestMethod] + public async Task ClaimCycle_FirstCycle_IsTheInitialOrderAndActivates() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + var paid = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc); + var next = paid.AddMonths(1); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, paid, next); + + Assert.IsNotNull(claim); + Assert.AreEqual(1, claim.Cycle.CycleNumber); + Assert.AreEqual("o1", claim.Cycle.OrderId); + Assert.AreEqual("in_1", claim.Cycle.ProviderReference); + Assert.AreEqual(10, claim.Cycle.Amount); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.AreEqual(1, saved.CyclesPaid); + Assert.AreEqual("sub_1", saved.ProviderReference); + Assert.AreEqual(next, saved.NextPaymentDateUtc); + } + + [TestMethod] + public async Task ClaimCycle_LaterCycle_GetsANewOrderIdAndLeavesPastDue() + { + var rp = await Insert(RecurringPaymentStatus.PastDue, 1, lastError: "card declined"); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.AreEqual(2, claim.Cycle.CycleNumber); + Assert.IsFalse(string.IsNullOrEmpty(claim.Cycle.OrderId)); + Assert.AreNotEqual("o1", claim.Cycle.OrderId); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.AreEqual("card declined", saved.LastError); + } + + [TestMethod] + public async Task ClaimCycle_SameCycleReferenceAgain_ReturnsNull() + { + var rp = await Insert(RecurringPaymentStatus.Pending, 0); + + Assert.IsNotNull(await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + Assert.IsNull(await _service.ClaimCycle(rp.Id, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(1, saved.Cycles.Count); + Assert.AreEqual(1, saved.CyclesPaid); + } + + [TestMethod] + public async Task ClaimCycle_ConcurrentDeliveries_ClaimOnce() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + var other = new RecurringPaymentService(_repository, _productService.Object, _mediator, _resourceLock); + + var claims = await Task.WhenAll( + _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null), + other.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null)); + + Assert.AreEqual(1, claims.Count(c => c != null)); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(1, saved.Cycles.Count(c => c.ProviderReference == "in_2")); + } + + [TestMethod] + public async Task ClaimCycle_ReachingTotalCycles_Completes() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1, 2); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsTrue(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Completed, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_TotalCyclesZero_NeverCompletes() + { + var rp = await Insert(RecurringPaymentStatus.Active, 11, 0); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_12", 10, DateTime.UtcNow, null); + + Assert.IsFalse(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Active, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_AfterCancelled_RecordsTheCycleAndKeepsTheStatus() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsNotNull(claim); + Assert.AreEqual(2, claim.Cycle.CycleNumber); + Assert.IsFalse(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_ReachingTotalCyclesAfterCancelled_KeepsTheStatusAndIsNotCompleted() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 1, 2); + + var claim = await _service.ClaimCycle(rp.Id, "sub_1", "in_2", 10, DateTime.UtcNow, null); + + Assert.IsNotNull(claim); + Assert.IsFalse(claim.Completed); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, (await _service.GetRecurringPaymentById(rp.Id)).Status); + } + + [TestMethod] + public async Task ClaimCycle_WithoutCycleReference_Throws() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + await Assert.ThrowsExactlyAsync(() => + _service.ClaimCycle(rp.Id, "sub_1", "", 10, DateTime.UtcNow, null)); + } + + [TestMethod] + public async Task RecordFailure_WithoutCycleReference_Throws() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + await Assert.ThrowsExactlyAsync(() => _service.RecordFailure(rp.Id, "", "declined")); + } + + [TestMethod] + public async Task ClaimCycle_UnknownRecurringPayment_ReturnsNull() + { + Assert.IsNull(await _service.ClaimCycle(UniqueIdentifier.New, "sub_1", "in_1", 10, DateTime.UtcNow, null)); + } + + [TestMethod] + public async Task RecordFailure_Active_EntersPastDueOnlyOnce() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + + Assert.IsTrue(await _service.RecordFailure(rp.Id, "in_2", "declined")); + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); + Assert.AreEqual("declined", saved.LastError); + Assert.IsNotNull(saved.LastErrorDateUtc); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "expired")); + saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.PastDue, saved.Status); + Assert.AreEqual("expired", saved.LastError); + } + + [TestMethod] + public async Task RecordFailure_ForACyclePaidAlready_IsIgnored() + { + var rp = await Insert(RecurringPaymentStatus.Active, 2); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "late")); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Active, saved.Status); + Assert.IsNull(saved.LastError); + } + + [TestMethod] + public async Task RecordFailure_Cancelled_ChangesNothing() + { + var rp = await Insert(RecurringPaymentStatus.Cancelled, 1); + + Assert.IsFalse(await _service.RecordFailure(rp.Id, "in_2", "declined")); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.IsNull(saved.LastError); + } + + [TestMethod] + public async Task RecordFailure_UnknownRecurringPayment_ReturnsFalse() + { + Assert.IsFalse(await _service.RecordFailure(UniqueIdentifier.New, "in_2", "declined")); + } + + [TestMethod] + public async Task RecordEnded_Active_CancelsByTheProvider() + { + var rp = await Insert(RecurringPaymentStatus.Active, 1); + rp.PaymentMethodSystemName = "Payments.Test"; + await _repository.UpdateAsync(rp); + + Assert.IsTrue(await _service.RecordEnded(rp.Id)); + + var saved = await _service.GetRecurringPaymentById(rp.Id); + Assert.AreEqual(RecurringPaymentStatus.Cancelled, saved.Status); + Assert.AreEqual("Payments.Test", saved.CancelledBy); + Assert.IsNotNull(saved.CancelledOnUtc); + } + + [TestMethod] + public async Task RecordEnded_CompletedOrCancelled_ChangesNothing() + { + var completed = await Insert(RecurringPaymentStatus.Completed, 12); + Assert.IsFalse(await _service.RecordEnded(completed.Id)); + Assert.AreEqual(RecurringPaymentStatus.Completed, + (await _service.GetRecurringPaymentById(completed.Id)).Status); + + var active = await Insert(RecurringPaymentStatus.Active, 1); + Assert.IsTrue(await _service.RecordEnded(active.Id)); + Assert.IsFalse(await _service.RecordEnded(active.Id)); + } + + [TestMethod] + public async Task RecordEnded_UnknownRecurringPayment_ReturnsFalse() + { + Assert.IsFalse(await _service.RecordEnded(UniqueIdentifier.New)); + } } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs index c073c65a1..db18ad385 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs @@ -322,6 +322,31 @@ public async Task PaymentService_SupportRecurringPayment_AsksTheProvider() Assert.IsTrue(await _paymentService.SupportRecurringPayment("Payments.Test")); } + [TestMethod] + public async Task PaymentService_CancelRecurringPayment_UnknownMethod_ReturnsError() + { + _paymentProviderMock.Setup(c => c.SystemName).Returns("Payments.Test"); + + var result = await _paymentService.CancelRecurringPayment(new RecurringPayment + { PaymentMethodSystemName = "Missing" }); + + Assert.IsFalse(result.Success); + CollectionAssert.AreEqual(new[] { "Payment method couldn't be loaded" }, result.Errors.ToArray()); + } + + [TestMethod] + public async Task PaymentService_CancelRecurringPayment_AsksTheProvider() + { + _paymentProviderMock.Setup(c => c.SystemName).Returns("Payments.Test"); + _paymentProviderMock.Setup(c => c.CancelRecurringPayment(It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + var result = await _paymentService.CancelRecurringPayment(new RecurringPayment + { PaymentMethodSystemName = "Payments.Test" }); + + Assert.IsTrue(result.Success); + } + //a provider written before the recurring contract existed keeps its defaults private class LegacyProvider : IPaymentProvider {