diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs new file mode 100644 index 000000000..e6d84b9ef --- /dev/null +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs @@ -0,0 +1,60 @@ +using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Data; +using Grand.Domain; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Checkout.Queries.Handlers.Orders; + +public class GetRecurringPaymentsQueryHandler : IRequestHandler> +{ + private readonly IRepository _customerRepository; + private readonly IRepository _orderRepository; + private readonly IRepository _recurringPaymentRepository; + + public GetRecurringPaymentsQueryHandler(IRepository recurringPaymentRepository, + IRepository customerRepository, IRepository orderRepository) + { + _recurringPaymentRepository = recurringPaymentRepository; + _customerRepository = customerRepository; + _orderRepository = orderRepository; + } + + public async Task> Handle(GetRecurringPaymentsQuery request, + CancellationToken cancellationToken) + { + var query = from p in _recurringPaymentRepository.Table + select p; + + if (!string.IsNullOrEmpty(request.StoreId)) + query = query.Where(x => x.StoreId == request.StoreId); + + if (request.Status.HasValue) + query = query.Where(x => x.Status == request.Status.Value); + + //the recurring payment keeps the customer only, and with per-store identity one e-mail may have an account + //in every store + if (!string.IsNullOrWhiteSpace(request.CustomerEmail)) + { + var email = request.CustomerEmail.Trim().ToLowerInvariant(); + var customerIds = await _customerRepository.ToListAsync( + _customerRepository.Table.Where(c => c.Email == email).Select(c => c.Id), cancellationToken); + query = query.Where(x => customerIds.Contains(x.CustomerId)); + } + + //the sales employee is on the order, the same one the order list narrows by + if (!string.IsNullOrEmpty(request.SalesEmployeeId)) + { + var orderIds = await _orderRepository.ToListAsync( + _orderRepository.Table.Where(o => o.SeId == request.SalesEmployeeId && o.RecurringCycleNumber == 1) + .Select(o => o.Id), cancellationToken); + query = query.Where(x => orderIds.Contains(x.InitialOrderId)); + } + + query = query.OrderByDescending(x => x.CreatedOnUtc); + + return await _recurringPaymentRepository.PagedAsync(query, request.PageIndex, request.PageSize, + cancellationToken); + } +} diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs new file mode 100644 index 000000000..16ed8dd39 --- /dev/null +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs @@ -0,0 +1,24 @@ +using Grand.Domain; +using Grand.Domain.Orders; +using Grand.Mediator; + +namespace Grand.Business.Core.Queries.Checkout.Orders; + +/// +/// Recurring payments for the panels, newest first +/// +public class GetRecurringPaymentsQuery : IRequest> +{ + public string StoreId { get; set; } + + /// Only the recurring payments of the customers with this e-mail, matched exactly. + public string CustomerEmail { get; set; } + + public RecurringPaymentStatus? Status { get; set; } + + /// Only the recurring payments whose initial order belongs to this sales employee. + public string SalesEmployeeId { get; set; } + + public int PageIndex { get; set; } + public int PageSize { get; set; } = int.MaxValue; +} diff --git a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs index e73fd1752..e61758231 100644 --- a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs +++ b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs @@ -944,6 +944,9 @@ await dbContext.CreateIndex(_serviceProvider.GetRequiredService>(), OrderBuilder.Create().Ascending(x => x.CustomerId).Ascending(x => x.StoreId) .Descending(x => x.CreatedOnUtc), "CustomerId_StoreId_CreatedOnUtc"); + //the Admin and Store panels list recurring payments newest first + await dbContext.CreateIndex(_serviceProvider.GetRequiredService>(), + OrderBuilder.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc"); //queuemail await dbContext.CreateIndex(_queuedEmailRepository, diff --git a/src/Modules/Grand.Module.Installer/Utilities/StandardAdminSiteMap.cs b/src/Modules/Grand.Module.Installer/Utilities/StandardAdminSiteMap.cs index 2a04c10b7..2500b7c3a 100644 --- a/src/Modules/Grand.Module.Installer/Utilities/StandardAdminSiteMap.cs +++ b/src/Modules/Grand.Module.Installer/Utilities/StandardAdminSiteMap.cs @@ -242,13 +242,22 @@ public static class StandardAdminSiteMap DisplayOrder = 3, IconClass = "bi bi-record-circle" }, + new() { + SystemName = "Recurring payments", + ResourceName = "Admin.Orders.RecurringPayments", + PermissionNames = new List { PermissionSystemName.Orders }, + ControllerName = "RecurringPayment", + ActionName = "List", + DisplayOrder = 4, + IconClass = "bi bi-record-circle" + }, new() { SystemName = "OrderTags", ResourceName = "Admin.Orders.OrderTags", PermissionNames = new List { PermissionSystemName.OrderTags }, ControllerName = "OrderTags", ActionName = "List", - DisplayOrder = 4, + DisplayOrder = 5, IconClass = "bi bi-record-circle" }, new() { @@ -257,7 +266,7 @@ public static class StandardAdminSiteMap ControllerName = "CheckoutAttribute", ActionName = "List", PermissionNames = new List { PermissionSystemName.CheckoutAttributes }, - DisplayOrder = 5, + DisplayOrder = 6, IconClass = "bi bi-record-circle" }, new() { @@ -266,7 +275,7 @@ public static class StandardAdminSiteMap ControllerName = "OrderStatus", PermissionNames = new List { PermissionSystemName.OrderStatus }, ActionName = "Index", - DisplayOrder = 6, + DisplayOrder = 7, IconClass = "bi bi-record-circle" } } diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentCreatedOnIndex.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentCreatedOnIndex.cs new file mode 100644 index 000000000..9772327ee --- /dev/null +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentCreatedOnIndex.cs @@ -0,0 +1,38 @@ +using Grand.Data; +using Grand.Domain.Orders; +using Grand.Infrastructure.Migrations; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Grand.Module.Migration.Migrations._2._5; + +public class MigrationRecurringPaymentCreatedOnIndex : IMigration +{ + private const string IndexName = "CreatedOnUtc"; + + public int Priority => 1; + public DbVersion Version => new(2, 5); + public Guid Identity => new("2571362b-ae02-4118-b14f-eb91d15cd91f"); + public string Name => "Created on index on Recurring payment 2.5"; + + public async Task UpgradeProcess(IServiceProvider serviceProvider) + { + var repository = serviceProvider.GetRequiredService>(); + var databaseContext = serviceProvider.GetRequiredService(); + var logService = serviceProvider.GetRequiredService>(); + + try + { + //the Admin and Store panels list recurring payments newest first + await databaseContext.CreateIndex(repository, + OrderBuilder.Create().Descending(x => x.CreatedOnUtc), IndexName); + } + catch (Exception ex) + { + logService.LogError(ex, "UpgradeProcess - RecurringPaymentCreatedOnIndex (2.5)"); + return false; + } + + return true; + } +} diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentMenu.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentMenu.cs new file mode 100644 index 000000000..789315c3b --- /dev/null +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentMenu.cs @@ -0,0 +1,61 @@ +using Grand.Data; +using Grand.Domain.Admin; +using Grand.Domain.Permissions; +using Grand.Infrastructure.Migrations; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Grand.Module.Migration.Migrations._2._5; + +/// +/// "Recurring payments" in the menu, under Sales right after Payment transactions, as the installer seeds it. +/// Idempotent: an existing entry is left alone, and a menu without the Sales section gets nothing +/// +public class MigrationRecurringPaymentMenu : IMigration +{ + private const string NodeName = "Recurring payments"; + + public int Priority => 3; + public DbVersion Version => new(2, 5); + public Guid Identity => new("5b0e7d1a-3c4f-4a8e-9f21-6d7c2e8b4a90"); + public string Name => "Recurring payments in the admin menu 2.5"; + + public async Task UpgradeProcess(IServiceProvider serviceProvider) + { + var repository = serviceProvider.GetRequiredService>(); + var logService = serviceProvider.GetRequiredService>(); + + try + { + var sales = await repository.FirstOrDefaultAsync(repository.Table.Where(x => x.SystemName == "Sales")); + if (sales == null || sales.ChildNodes.Any(x => x.SystemName == NodeName)) + return true; + + //right after Payment transactions, the entries below it move down by one + var paymentTransactions = sales.ChildNodes.FirstOrDefault(x => x.SystemName == "Payment transaction"); + var displayOrder = paymentTransactions != null + ? paymentTransactions.DisplayOrder + 1 + : sales.ChildNodes.Count == 0 ? 0 : sales.ChildNodes.Max(x => x.DisplayOrder) + 1; + foreach (var node in sales.ChildNodes.Where(x => x.DisplayOrder >= displayOrder)) + node.DisplayOrder++; + + sales.ChildNodes.Add(new AdminSiteMap { + SystemName = NodeName, + ResourceName = "Admin.Orders.RecurringPayments", + PermissionNames = new List { PermissionSystemName.Orders }, + ControllerName = "RecurringPayment", + ActionName = "List", + DisplayOrder = displayOrder, + IconClass = "bi bi-record-circle" + }); + await repository.UpdateAsync(sales); + } + catch (Exception ex) + { + logService.LogError(ex, "UpgradeProcess - RecurringPaymentMenu (2.5)"); + return false; + } + + return true; + } +} diff --git a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandlerTests.cs new file mode 100644 index 000000000..fe518c33e --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandlerTests.cs @@ -0,0 +1,109 @@ +using Grand.Business.Checkout.Queries.Handlers.Orders; +using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Data.Tests.MongoDb; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders; + +[TestClass] +public class GetRecurringPaymentsQueryHandlerTests +{ + private MongoDBRepositoryTest _customerRepository; + private GetRecurringPaymentsQueryHandler _handler; + private MongoDBRepositoryTest _orderRepository; + private MongoDBRepositoryTest _repository; + + [TestInitialize] + public void Init() + { + _repository = new MongoDBRepositoryTest(); + _customerRepository = new MongoDBRepositoryTest(); + _orderRepository = new MongoDBRepositoryTest(); + _handler = new GetRecurringPaymentsQueryHandler(_repository, _customerRepository, _orderRepository); + } + + [TestMethod] + public async Task Handle_ByStore_ReturnsOnlyThatStore() + { + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", StoreId = "s1" }); + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp2", StoreId = "s2" }); + + var result = await _handler.Handle(new GetRecurringPaymentsQuery { StoreId = "s1" }, CancellationToken.None); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual("rp1", result[0].Id); + } + + [TestMethod] + public async Task Handle_ByStatus_ReturnsOnlyThatStatus() + { + await _repository.Collection.InsertOneAsync(new RecurringPayment + { Id = "rp1", Status = RecurringPaymentStatus.PastDue }); + await _repository.Collection.InsertOneAsync(new RecurringPayment + { Id = "rp2", Status = RecurringPaymentStatus.Active }); + + var result = await _handler.Handle( + new GetRecurringPaymentsQuery { Status = RecurringPaymentStatus.PastDue }, CancellationToken.None); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual("rp1", result[0].Id); + } + + [TestMethod] + public async Task Handle_ByCustomerEmail_MatchesEveryAccountWithThatEmailExactly() + { + await _customerRepository.Collection.InsertOneAsync(new Customer { Id = "c1", Email = "jan@example.com", StoreId = "s1" }); + await _customerRepository.Collection.InsertOneAsync(new Customer { Id = "c2", Email = "jan@example.com", StoreId = "s2" }); + await _customerRepository.Collection.InsertOneAsync(new Customer { Id = "c3", Email = "xjan@example.com" }); + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", CustomerId = "c1" }); + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp2", CustomerId = "c2" }); + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp3", CustomerId = "c3" }); + + var result = await _handler.Handle( + new GetRecurringPaymentsQuery { CustomerEmail = " Jan@Example.com " }, CancellationToken.None); + + CollectionAssert.AreEquivalent(new[] { "rp1", "rp2" }, result.Select(x => x.Id).ToArray()); + } + + [TestMethod] + public async Task Handle_ByUnknownCustomerEmail_ReturnsNothing() + { + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", CustomerId = "c1" }); + + var result = await _handler.Handle( + new GetRecurringPaymentsQuery { CustomerEmail = "nobody@example.com" }, CancellationToken.None); + + Assert.AreEqual(0, result.Count); + } + + [TestMethod] + public async Task Handle_BySalesEmployee_ReturnsOnlyPaymentsOfTheirInitialOrders() + { + await _orderRepository.Collection.InsertOneAsync(new Order { Id = "o1", SeId = "se1", RecurringCycleNumber = 1 }); + await _orderRepository.Collection.InsertOneAsync(new Order { Id = "o2", SeId = "se2", RecurringCycleNumber = 1 }); + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", InitialOrderId = "o1" }); + await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp2", InitialOrderId = "o2" }); + + var result = await _handler.Handle( + new GetRecurringPaymentsQuery { SalesEmployeeId = "se1" }, CancellationToken.None); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual("rp1", result[0].Id); + } + + [TestMethod] + public async Task Handle_ReturnsNewestFirst() + { + await _repository.Collection.InsertOneAsync(new RecurringPayment + { Id = "old", CreatedOnUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) }); + await _repository.Collection.InsertOneAsync(new RecurringPayment + { Id = "new", CreatedOnUtc = new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc) }); + + var result = await _handler.Handle(new GetRecurringPaymentsQuery(), CancellationToken.None); + + Assert.AreEqual("new", result[0].Id); + Assert.AreEqual("old", result[1].Id); + } +} diff --git a/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentCreatedOnIndexTests.cs b/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentCreatedOnIndexTests.cs new file mode 100644 index 000000000..5441a783b --- /dev/null +++ b/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentCreatedOnIndexTests.cs @@ -0,0 +1,48 @@ +using Grand.Data; +using Grand.Data.Tests.LiteDb; +using Grand.Domain.Orders; +using Grand.Module.Migration.Migrations._2._5; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Modules.Tests.Services.Migrations; + +[TestClass] +public class MigrationRecurringPaymentCreatedOnIndexTests +{ + private readonly Mock _context = new(); + private readonly LiteDBRepositoryMock _repository = new(); + private IServiceProvider _serviceProvider; + + [TestInitialize] + public void Init() + { + var services = new ServiceCollection(); + services.AddSingleton>(_repository); + services.AddSingleton(_context.Object); + services.AddSingleton>( + NullLogger.Instance); + _serviceProvider = services.BuildServiceProvider(); + } + + [TestMethod] + public async Task UpgradeProcess_CreatesCreatedOnIndex() + { + Assert.IsTrue(await new MigrationRecurringPaymentCreatedOnIndex().UpgradeProcess(_serviceProvider)); + + _context.Verify(x => x.CreateIndex(_repository, It.IsAny>(), "CreatedOnUtc", + false), Times.Once); + } + + [TestMethod] + public async Task UpgradeProcess_IndexFails_ReturnsFalse() + { + _context.Setup(x => x.CreateIndex(_repository, It.IsAny>(), "CreatedOnUtc", + false)).ThrowsAsync(new InvalidOperationException()); + + Assert.IsFalse(await new MigrationRecurringPaymentCreatedOnIndex().UpgradeProcess(_serviceProvider)); + } +} diff --git a/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentMenuTests.cs b/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentMenuTests.cs new file mode 100644 index 000000000..ef446d36f --- /dev/null +++ b/src/Tests/Grand.Modules.Tests/Services/Migrations/MigrationRecurringPaymentMenuTests.cs @@ -0,0 +1,70 @@ +using Grand.Data; +using Grand.Data.Tests.LiteDb; +using Grand.Domain.Admin; +using Grand.Module.Installer.Utilities; +using Grand.Module.Migration.Migrations._2._5; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Modules.Tests.Services.Migrations; + +[TestClass] +public class MigrationRecurringPaymentMenuTests +{ + private const string NodeName = "Recurring payments"; + private readonly MigrationRecurringPaymentMenu _migration = new(); + private readonly LiteDBRepositoryMock _siteMap = new(); + private IServiceProvider _serviceProvider; + + [TestInitialize] + public void Init() + { + var services = new ServiceCollection(); + services.AddSingleton>(_siteMap); + services.AddSingleton>( + NullLogger.Instance); + _serviceProvider = services.BuildServiceProvider(); + } + + [TestMethod] + public async Task Adds_EntryUnderSalesAfterPaymentTransactions_Once() + { + _siteMap.Insert(new AdminSiteMap { + SystemName = "Sales", + ChildNodes = new List { + new() { SystemName = "Orders", DisplayOrder = 0 }, + new() { SystemName = "Payment transaction", DisplayOrder = 3 }, + new() { SystemName = "OrderTags", DisplayOrder = 4 }, + new() { SystemName = "Order status", DisplayOrder = 6 } + } + }); + + Assert.IsTrue(await _migration.UpgradeProcess(_serviceProvider)); + Assert.IsTrue(await _migration.UpgradeProcess(_serviceProvider)); + + var nodes = _siteMap.Table.Single().ChildNodes; + var node = nodes.Single(x => x.SystemName == NodeName); + var installed = StandardAdminSiteMap.SiteMap.Single(x => x.SystemName == "Sales").ChildNodes + .Single(x => x.SystemName == NodeName); + Assert.AreEqual(installed.ResourceName, node.ResourceName); + Assert.AreEqual(installed.ControllerName, node.ControllerName); + Assert.AreEqual(installed.ActionName, node.ActionName); + CollectionAssert.AreEqual(installed.PermissionNames.ToArray(), node.PermissionNames.ToArray()); + CollectionAssert.AreEqual(new[] { "Orders", "Payment transaction", NodeName, "OrderTags", "Order status" }, + nodes.OrderBy(x => x.DisplayOrder).Select(x => x.SystemName).ToArray()); + Assert.AreEqual(4, node.DisplayOrder); + Assert.AreEqual(5, nodes.Single(x => x.SystemName == "OrderTags").DisplayOrder); + } + + [TestMethod] + public async Task NoSalesNode_NothingAdded() + { + _siteMap.Insert(new AdminSiteMap { SystemName = "Configuration", ChildNodes = new List() }); + + Assert.IsTrue(await _migration.UpgradeProcess(_serviceProvider)); + + Assert.IsEmpty(_siteMap.Table.Single().ChildNodes); + } +} diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseRecurringPaymentControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseRecurringPaymentControllerTests.cs new file mode 100644 index 000000000..760ac7458 --- /dev/null +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseRecurringPaymentControllerTests.cs @@ -0,0 +1,230 @@ +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.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Stores; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.Web.AdminShared.Controllers; +using Grand.Web.AdminShared.Interfaces; +using Grand.Web.AdminShared.Models.Orders; +using Grand.Web.Common.DataSource; +using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Web.Admin.Tests.Controllers; + +[TestClass] +public class BaseRecurringPaymentControllerTests +{ + private class TestRecurringPaymentController( + IRecurringPaymentService recurringPaymentService, + IOrderService orderService, + ICustomerService customerService, + IStoreService storeService, + IPaymentService paymentService, + IRequestTranslationService translationService, + IEnumTranslationService enumTranslationService, + IDateTimeService dateTimeService, + IMediator mediator, + IAdminDataScope scope, + IContextAccessor contextAccessor) + : BaseRecurringPaymentController(recurringPaymentService, orderService, customerService, storeService, + paymentService, translationService, enumTranslationService, dateTimeService, mediator, scope, + contextAccessor); + + private TestRecurringPaymentController _controller; + private Customer _staff; + private Mock _mediator; + private Order _initialOrder; + private RecurringPayment _recurringPayment; + private Mock> _scope; + + [TestInitialize] + public void Setup() + { + _initialOrder = new Order { Id = "o1", OrderNumber = 1042, StoreId = "s1", CustomerCurrencyCode = "USD" }; + _recurringPayment = new RecurringPayment { + Id = "rp1", StoreId = "s1", CustomerId = "c1", InitialOrderId = "o1", + Status = RecurringPaymentStatus.Active, CycleLength = 1, CyclePeriodId = Domain.Catalog.RecurringCyclePeriod.Months, + Cycles = [new RecurringPaymentCycle { CycleNumber = 2, OrderId = "o2", Amount = 9.5 }] + }; + + var recurringPaymentService = new Mock(); + recurringPaymentService.Setup(x => x.GetRecurringPaymentById("rp1")).ReturnsAsync(() => _recurringPayment); + var orderService = new Mock(); + orderService.Setup(x => x.GetOrderById("o1")).ReturnsAsync(() => _initialOrder); + orderService.Setup(x => x.GetOrdersByIds(It.IsAny())).ReturnsAsync((string[] ids) => + new[] { _initialOrder, new Order { Id = "o2", OrderNumber = 1043 } }.Where(x => ids.Contains(x.Id)).ToList()); + var customerService = new Mock(); + customerService.Setup(x => x.GetCustomerById("c1")).ReturnsAsync(new Customer { Id = "c1", Email = "jan@example.com" }); + customerService.Setup(x => x.GetCustomersByIds(It.IsAny())) + .ReturnsAsync(new List { new() { Id = "c1", Email = "jan@example.com" } }); + var storeService = new Mock(); + storeService.Setup(x => x.GetAllStores()).ReturnsAsync(new List { new() { Id = "s1", Shortcut = "Main" } }); + var translationService = new Mock(); + translationService.Setup(x => x.GetResource(It.IsAny())).Returns((string key) => key); + var dateTimeService = new Mock(); + dateTimeService.Setup(d => d.ConvertToUserTime(It.IsAny(), It.IsAny())) + .Returns((DateTime dt, DateTimeKind _) => dt); + + _mediator = new Mock(); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync(new PagedList([_recurringPayment], 0, 15)); + _mediator.Setup(x => x.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync(new CancelRecurringPaymentResult()); + + _scope = new Mock>(); + _scope.Setup(x => x.HasAccess(It.IsAny())).ReturnsAsync(true); + + _staff = new Customer { Id = "staff", Email = "staff@shop.com" }; + var workContext = new Mock(); + workContext.Setup(w => w.CurrentCustomer).Returns(() => _staff); + var contextAccessor = new Mock(); + contextAccessor.Setup(c => c.WorkContext).Returns(workContext.Object); + + _controller = new TestRecurringPaymentController(recurringPaymentService.Object, orderService.Object, + customerService.Object, storeService.Object, new Mock().Object, translationService.Object, + new Mock().Object, dateTimeService.Object, _mediator.Object, _scope.Object, + contextAccessor.Object); + + var httpContext = new DefaultHttpContext(); + var loggerFactory = new Mock(); + loggerFactory.Setup(l => l.CreateLogger(It.IsAny())).Returns(new Mock().Object); + var urlHelperFactory = new Mock(); + urlHelperFactory.Setup(f => f.GetUrlHelper(It.IsAny())).Returns(new Mock().Object); + var requestServices = new Mock(); + requestServices.Setup(s => s.GetService(typeof(ILoggerFactory))).Returns(loggerFactory.Object); + requestServices.Setup(s => s.GetService(typeof(IUrlHelperFactory))).Returns(urlHelperFactory.Object); + httpContext.RequestServices = requestServices.Object; + _controller.ControllerContext = new ControllerContext { HttpContext = httpContext }; + _controller.TempData = new TempDataDictionary(httpContext, new Mock().Object); + } + + [TestMethod] + public async Task List_StorePanel_SearchesItsOwnStoreWhateverIsPosted() + { + _scope.Setup(x => x.DefaultStoreId).Returns("s1"); + + await _controller.List(new DataSourceRequest { Page = 1, PageSize = 15 }, + new RecurringPaymentListModel { StoreId = "s2" }); + + _mediator.Verify(x => x.Send(It.Is(q => q.StoreId == "s1"), + It.IsAny())); + } + + [TestMethod] + public async Task List_Admin_SearchesThePostedStoreAndStatus() + { + await _controller.List(new DataSourceRequest { Page = 2, PageSize = 15 }, + new RecurringPaymentListModel { StoreId = " s2 ", SearchStatusId = 20, SearchCustomerEmail = "jan@example.com" }); + + _mediator.Verify(x => x.Send(It.Is(q => + q.StoreId == "s2" && q.Status == RecurringPaymentStatus.PastDue && q.CustomerEmail == "jan@example.com" && + q.PageIndex == 1), It.IsAny())); + } + + [TestMethod] + public async Task List_SalesEmployee_SearchesTheirOwnOrdersOnly() + { + _staff.SeId = "se1"; + + await _controller.List(new DataSourceRequest { Page = 1, PageSize = 15 }, new RecurringPaymentListModel()); + + _mediator.Verify(x => x.Send(It.Is(q => q.SalesEmployeeId == "se1"), + It.IsAny())); + } + + [TestMethod] + public async Task List_MapsTheRows() + { + var result = (JsonResult)await _controller.List(new DataSourceRequest { Page = 1, PageSize = 15 }, + new RecurringPaymentListModel()); + + var row = ((IEnumerable)((DataSourceResult)result.Value!).Data).Single(); + Assert.AreEqual("jan@example.com", row.CustomerEmail); + Assert.AreEqual(1042, row.InitialOrderNumber); + Assert.AreEqual("Main", row.StoreName); + Assert.AreEqual(RecurringCycleText.ResourceKey(1, Domain.Catalog.RecurringCyclePeriod.Months), row.Cycle); + Assert.IsTrue(row.CanCancel); + } + + [TestMethod] + public async Task Edit_ListsTheCyclesWithTheirOrders() + { + var model = (RecurringPaymentModel)((ViewResult)await _controller.Edit("rp1")).Model!; + + var cycle = model.Cycles.Single(); + Assert.AreEqual("o2", cycle.OrderId); + Assert.AreEqual(1043, cycle.OrderNumber); + Assert.IsTrue(cycle.CanViewOrder); + StringAssert.EndsWith(cycle.Amount, "USD"); + } + + [TestMethod] + public async Task Edit_StorePanel_OtherStore_RedirectsToList() + { + _scope.Setup(x => x.DefaultStoreId).Returns("s2"); + + var result = await _controller.Edit("rp1"); + + Assert.AreEqual("List", ((RedirectToActionResult)result).ActionName); + } + + [TestMethod] + public async Task Edit_InitialOrderOutOfScope_RedirectsToList() + { + _scope.Setup(x => x.HasAccess(_initialOrder)).ReturnsAsync(false); + + var result = await _controller.Edit("rp1"); + + Assert.AreEqual("List", ((RedirectToActionResult)result).ActionName); + } + + [TestMethod] + public async Task Cancel_OutOfScope_DoesNotCancel() + { + _scope.Setup(x => x.HasAccess(_initialOrder)).ReturnsAsync(false); + + await _controller.Cancel("rp1"); + + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task Cancel_Ended_DoesNotCancel() + { + _recurringPayment.Status = RecurringPaymentStatus.Cancelled; + + await _controller.Cancel("rp1"); + + _mediator.Verify(x => x.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task Cancel_NamesTheStaffMember() + { + var result = await _controller.Cancel("rp1"); + + _mediator.Verify(x => x.Send( + It.Is(c => c.RecurringPayment == _recurringPayment && + c.CancelledBy == "staff@shop.com"), + It.IsAny())); + Assert.AreEqual("Edit", ((RedirectToActionResult)result).ActionName); + } +} diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/RecurringPaymentControllerRoutingTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/RecurringPaymentControllerRoutingTests.cs new file mode 100644 index 000000000..31e1ad638 --- /dev/null +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/RecurringPaymentControllerRoutingTests.cs @@ -0,0 +1,35 @@ +using Grand.Web.Admin.Controllers; +using Grand.Web.Admin.Extensions; +using Grand.Web.AdminShared.Controllers; +using Grand.Web.Common.Filters; +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Web.Admin.Tests.Controllers; + +[TestClass] +public class RecurringPaymentControllerRoutingTests +{ + [TestMethod] + public void AdminRecurringPaymentController_InheritsBaseRecurringPaymentController() => + Assert.IsTrue(typeof(BaseRecurringPaymentController).IsAssignableFrom(typeof(RecurringPaymentController))); + + [TestMethod] + public void AdminRecurringPaymentController_HasAutoValidateAntiforgeryToken() => + Assert.IsTrue(typeof(RecurringPaymentController) + .GetCustomAttributes(typeof(Microsoft.AspNetCore.Mvc.AutoValidateAntiforgeryTokenAttribute), false) + .Length > 0); + + [TestMethod] + public void AdminRecurringPaymentController_HasAreaAttributeWithAdminArea() + { + var areaAttr = (AreaAttribute)Attribute.GetCustomAttribute(typeof(RecurringPaymentController), typeof(AreaAttribute), false); + Assert.IsNotNull(areaAttr, "Missing [Area]."); + Assert.AreEqual(Constants.AreaAdmin, areaAttr.RouteValue); + } + + [TestMethod] + public void AdminRecurringPaymentController_HasAuthorizeAdminAttribute() => + Assert.IsTrue(typeof(RecurringPaymentController).IsDefined(typeof(AuthorizeAdminAttribute), false), + "Missing [AuthorizeAdmin]."); +} diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceApprovalTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceApprovalTests.cs index 264a109a4..4133cdfc2 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceApprovalTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceApprovalTests.cs @@ -71,7 +71,7 @@ public void Init() new Mock().Object, new CurrencySettings(), new TaxSettings(), new AddressSettings(), new Mock().Object, new Mock().Object, new Mock().Object, enums.Object, _scope.Object, approvals.Object, new Mock().Object, - new Mock>().Object); + new Mock>().Object, new Mock().Object); } private async Task Details() diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceMerchandiseReturnsTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceMerchandiseReturnsTests.cs index b8f9c9231..edb69f3ea 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceMerchandiseReturnsTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceMerchandiseReturnsTests.cs @@ -64,7 +64,7 @@ public void Init() new Mock().Object, new CurrencySettings(), new TaxSettings(), new AddressSettings(), new Mock().Object, new Mock().Object, _mediator.Object, enums.Object, new Mock>().Object, new Mock().Object, - new Mock().Object, _returnScope.Object); + new Mock().Object, _returnScope.Object, new Mock().Object); } private async Task Prepare() diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceRecurringTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceRecurringTests.cs new file mode 100644 index 000000000..447809c9d --- /dev/null +++ b/src/Tests/Grand.Web.Admin.Tests/Services/OrderViewModelServiceRecurringTests.cs @@ -0,0 +1,127 @@ +using Grand.Business.Core.Interfaces.Catalog.Discounts; +using Grand.Business.Core.Interfaces.Catalog.Prices; +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.Checkout.Shipping; +using Grand.Business.Core.Interfaces.Common.Addresses; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Business.Core.Interfaces.Storage; +using Grand.Domain.Common; +using Grand.Domain.Directory; +using Grand.Domain.Orders; +using Grand.Domain.Tax; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.Web.AdminShared.Interfaces; +using Grand.Web.AdminShared.Models.Orders; +using Grand.Web.AdminShared.Services; +using Grand.Web.Common.Localization; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Web.Admin.Tests.Services; + +[TestClass] +public class OrderViewModelServiceRecurringTests +{ + private Mock _orderService; + private Mock _recurringPaymentService; + private Mock> _scope; + private OrderViewModelService _service; + + [TestInitialize] + public void Init() + { + _orderService = new Mock(); + _recurringPaymentService = new Mock(); + _scope = new Mock>(); + + _service = new OrderViewModelService(_orderService.Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, + new Mock().Object, new CurrencySettings(), new TaxSettings(), new AddressSettings(), + new Mock().Object, new Mock().Object, new Mock().Object, + new Mock().Object, _scope.Object, new Mock().Object, + new Mock().Object, new Mock>().Object, + _recurringPaymentService.Object); + } + + private async Task Prepare(Order order) + { + var model = new OrderModel(); + await _service.PrepareOrderRecurringPayment(model, order); + return model; + } + + [TestMethod] + public async Task InitialOrder_LinksItsRecurringPayment() + { + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")) + .ReturnsAsync(new RecurringPayment { Id = "rp1" }); + + var model = await Prepare(new Order { Id = "o1", RecurringCycleNumber = 1 }); + + Assert.AreEqual("rp1", model.RecurringPaymentId); + Assert.AreEqual(0, model.InitialOrderNumber); + } + + [TestMethod] + public async Task CycleOrder_LinksTheInitialOrder() + { + _orderService.Setup(x => x.GetOrderById("o1")).ReturnsAsync(new Order { Id = "o1", OrderNumber = 1042 }); + + var model = await Prepare(new Order { Id = "o3", RecurringCycleNumber = 3, InitialOrderId = "o1" }); + + Assert.AreEqual(3, model.RecurringCycleNumber); + Assert.AreEqual(1042, model.InitialOrderNumber); + Assert.AreEqual("o1", model.InitialOrderId); + Assert.IsNull(model.RecurringPaymentId); + } + + [TestMethod] + public async Task CycleOrder_DeletedInitialOrder_ShowsTheNumberWithoutALink() + { + _orderService.Setup(x => x.GetOrderById("o1")) + .ReturnsAsync(new Order { Id = "o1", OrderNumber = 1042, Deleted = true }); + + var model = await Prepare(new Order { Id = "o3", RecurringCycleNumber = 3, InitialOrderId = "o1" }); + + Assert.AreEqual(1042, model.InitialOrderNumber); + Assert.IsNull(model.InitialOrderId); + } + + [TestMethod] + public async Task OrdinaryOrder_LinksNothing() + { + var model = await Prepare(new Order { Id = "o1" }); + + Assert.IsNull(model.RecurringPaymentId); + Assert.AreEqual(0, model.InitialOrderNumber); + _recurringPaymentService.Verify(x => x.GetRecurringPaymentByInitialOrderId(It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task VendorPanel_LinksNothing() + { + _scope.Setup(x => x.DefaultVendorId).Returns("vendor"); + _recurringPaymentService.Setup(x => x.GetRecurringPaymentByInitialOrderId("o1")) + .ReturnsAsync(new RecurringPayment { Id = "rp1" }); + + var model = await Prepare(new Order { Id = "o1", RecurringCycleNumber = 1 }); + + Assert.IsNull(model.RecurringPaymentId); + Assert.AreEqual(0, model.RecurringCycleNumber); + } +} diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/RecurringPaymentControllerRoutingTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/RecurringPaymentControllerRoutingTests.cs new file mode 100644 index 000000000..284cfc772 --- /dev/null +++ b/src/Tests/Grand.Web.Store.Tests/Controllers/RecurringPaymentControllerRoutingTests.cs @@ -0,0 +1,35 @@ +using Grand.Web.AdminShared.Controllers; +using Grand.Web.Common.Filters; +using Grand.Web.Store.Controllers; +using Grand.Web.Store.Extensions; +using Microsoft.AspNetCore.Mvc; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Web.Store.Tests.Controllers; + +[TestClass] +public class RecurringPaymentControllerRoutingTests +{ + [TestMethod] + public void StoreRecurringPaymentController_InheritsBaseRecurringPaymentController() => + Assert.IsTrue(typeof(BaseRecurringPaymentController).IsAssignableFrom(typeof(RecurringPaymentController))); + + [TestMethod] + public void StoreRecurringPaymentController_HasAutoValidateAntiforgeryToken() => + Assert.IsTrue(typeof(RecurringPaymentController) + .GetCustomAttributes(typeof(Microsoft.AspNetCore.Mvc.AutoValidateAntiforgeryTokenAttribute), false) + .Length > 0); + + [TestMethod] + public void StoreRecurringPaymentController_HasAreaAttributeWithStoreArea() + { + var areaAttr = (AreaAttribute)Attribute.GetCustomAttribute(typeof(RecurringPaymentController), typeof(AreaAttribute), false); + Assert.IsNotNull(areaAttr, "Missing [Area]."); + Assert.AreEqual(Constants.AreaStore, areaAttr.RouteValue); + } + + [TestMethod] + public void StoreRecurringPaymentController_HasAuthorizeStoreAttribute() => + Assert.IsTrue(typeof(RecurringPaymentController).IsDefined(typeof(AuthorizeStoreAttribute), false), + "Missing [AuthorizeStore]."); +} diff --git a/src/Web/Grand.Web.Admin/Controllers/RecurringPaymentController.cs b/src/Web/Grand.Web.Admin/Controllers/RecurringPaymentController.cs new file mode 100644 index 000000000..02e71d76d --- /dev/null +++ b/src/Web/Grand.Web.Admin/Controllers/RecurringPaymentController.cs @@ -0,0 +1,36 @@ +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Orders; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.Web.Admin.Extensions; +using Grand.Web.AdminShared.Controllers; +using Grand.Web.AdminShared.Interfaces; +using Grand.Web.Common.Filters; +using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.Mvc; + +namespace Grand.Web.Admin.Controllers; + +[AuthorizeAdmin] +[AutoValidateAntiforgeryToken] +[Area(Constants.AreaAdmin)] +[AuthorizeMenu] +public class RecurringPaymentController( + IRecurringPaymentService recurringPaymentService, + IOrderService orderService, + ICustomerService customerService, + IStoreService storeService, + IPaymentService paymentService, + IRequestTranslationService translationService, + IEnumTranslationService enumTranslationService, + IDateTimeService dateTimeService, + IMediator mediator, + IAdminDataScope scope, + IContextAccessor contextAccessor) + : BaseRecurringPaymentController(recurringPaymentService, orderService, customerService, storeService, + paymentService, translationService, enumTranslationService, dateTimeService, mediator, scope, + contextAccessor); diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseRecurringPaymentController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseRecurringPaymentController.cs new file mode 100644 index 000000000..587892738 --- /dev/null +++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseRecurringPaymentController.cs @@ -0,0 +1,227 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Customers; +using Grand.Domain.Orders; +using Grand.Domain.Permissions; +using Grand.Domain.Stores; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.Web.AdminShared.Interfaces; +using Grand.Web.AdminShared.Models.Orders; +using Grand.Web.Common.Controllers; +using Grand.Web.Common.DataSource; +using Grand.Web.Common.Localization; +using Grand.Web.Common.Security.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Rendering; + +namespace Grand.Web.AdminShared.Controllers; + +/// +/// Sales / Recurring payments in the Admin and Store panels. A recurring payment comes with an order, so the orders +/// permission covers it and the order's scope decides who sees it: the store panel its own store, a sales manager +/// the orders of their own customers +/// +[PermissionAuthorize(PermissionSystemName.Orders)] +[AutoValidateAntiforgeryToken] +public abstract class BaseRecurringPaymentController( + IRecurringPaymentService recurringPaymentService, + IOrderService orderService, + ICustomerService customerService, + IStoreService storeService, + IPaymentService paymentService, + IRequestTranslationService translationService, + IEnumTranslationService enumTranslationService, + IDateTimeService dateTimeService, + IMediator mediator, + IAdminDataScope scope, + IContextAccessor contextAccessor) + : BaseController +{ + /// A missing recurring payment and one the panel may not see are answered alike + protected async Task<(RecurringPayment recurringPayment, Order initialOrder, IActionResult denied)> + LoadAuthorizedRecurringPayment(string id) + { + var recurringPayment = await recurringPaymentService.GetRecurringPaymentById(id); + if (recurringPayment == null) return (null, null, RedirectToAction("List")); + if (scope.DefaultStoreId is not null && recurringPayment.StoreId != scope.DefaultStoreId) + return (null, null, RedirectToAction("List")); + + //a deleted order is kept, so a missing one is a broken record and is shown to no one + var initialOrder = string.IsNullOrEmpty(recurringPayment.InitialOrderId) + ? null + : await orderService.GetOrderById(recurringPayment.InitialOrderId); + if (initialOrder == null || !await scope.HasAccess(initialOrder)) + return (null, null, RedirectToAction("List")); + + return (recurringPayment, initialOrder, null); + } + + #region List + + public IActionResult Index() => RedirectToAction("List"); + + public async Task List() + { + var model = new RecurringPaymentListModel { + AvailableStatuses = enumTranslationService.ToSelectList(RecurringPaymentStatus.Pending, false).ToList(), + ShowStoreFilter = scope.DefaultStoreId is null + }; + model.AvailableStatuses.Insert(0, + new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "-1", Selected = true }); + + if (model.ShowStoreFilter) + { + model.AvailableStores.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " }); + foreach (var store in await storeService.GetAllStores()) + model.AvailableStores.Add(new SelectListItem { Text = store.Shortcut, Value = store.Id }); + } + + return View(model); + } + + [PermissionAuthorizeAction(PermissionActionName.List)] + [HttpPost] + public async Task List(DataSourceRequest command, RecurringPaymentListModel model) + { + var recurringPayments = await mediator.Send(new GetRecurringPaymentsQuery { + StoreId = scope.DefaultStoreId ?? model.StoreId?.Trim(), + CustomerEmail = model.SearchCustomerEmail, + Status = model.SearchStatusId >= 0 ? (RecurringPaymentStatus)model.SearchStatusId : null, + //the order list narrows a sales employee to their own orders the same way + SalesEmployeeId = contextAccessor.WorkContext.CurrentCustomer.SeId, + PageIndex = command.Page - 1, + PageSize = command.PageSize + }); + + var orders = (await orderService.GetOrdersByIds(recurringPayments.Select(x => x.InitialOrderId) + .Where(x => !string.IsNullOrEmpty(x)).Distinct().ToArray())) + .ToDictionary(x => x.Id); + var customers = (await customerService.GetCustomersByIds(recurringPayments.Select(x => x.CustomerId) + .Where(x => !string.IsNullOrEmpty(x)).Distinct().ToArray())) + .ToDictionary(x => x.Id); + var stores = await storeService.GetAllStores(); + + var data = recurringPayments.Select(x => PrepareRecurringPaymentModel(x, + orders.GetValueOrDefault(x.InitialOrderId ?? ""), customers.GetValueOrDefault(x.CustomerId ?? ""), + stores)).ToList(); + + return Json(new DataSourceResult { Data = data, Total = recurringPayments.TotalCount }); + } + + #endregion + + #region Details + + [PermissionAuthorizeAction(PermissionActionName.Preview)] + public async Task Edit(string id) + { + var (recurringPayment, initialOrder, denied) = await LoadAuthorizedRecurringPayment(id); + if (denied != null) return denied; + + var customer = await customerService.GetCustomerById(recurringPayment.CustomerId); + var model = PrepareRecurringPaymentModel(recurringPayment, initialOrder, customer, + await storeService.GetAllStores()); + model.ProviderReference = recurringPayment.ProviderReference; + model.LastError = recurringPayment.LastError; + model.LastErrorDate = recurringPayment.LastErrorDateUtc.HasValue + ? dateTimeService.ConvertToUserTime(recurringPayment.LastErrorDateUtc.Value, DateTimeKind.Utc) + : null; + model.CancelledOn = recurringPayment.CancelledOnUtc.HasValue + ? dateTimeService.ConvertToUserTime(recurringPayment.CancelledOnUtc.Value, DateTimeKind.Utc) + : null; + model.CancelledBy = recurringPayment.CancelledBy; + + var cycleOrders = (await orderService.GetOrdersByIds(recurringPayment.Cycles.Select(x => x.OrderId) + .Where(x => !string.IsNullOrEmpty(x)).Distinct().ToArray())) + .ToDictionary(x => x.Id); + foreach (var cycle in recurringPayment.Cycles.OrderBy(x => x.CycleNumber)) + { + var order = cycleOrders.GetValueOrDefault(cycle.OrderId ?? ""); + model.Cycles.Add(new RecurringPaymentModel.CycleModel { + CycleNumber = cycle.CycleNumber, + OrderId = order?.Id, + OrderNumber = order?.OrderNumber ?? 0, + CanViewOrder = order is { Deleted: false }, + //the gateway charges in the currency the customer ordered in + Amount = $"{cycle.Amount:N2} {initialOrder.CustomerCurrencyCode}", + PaidOn = dateTimeService.ConvertToUserTime(cycle.PaidOnUtc, DateTimeKind.Utc), + ProviderReference = cycle.ProviderReference + }); + } + + return View(model); + } + + [PermissionAuthorizeAction(PermissionActionName.Cancel)] + [HttpPost] + public async Task Cancel(string id) + { + var (recurringPayment, _, denied) = await LoadAuthorizedRecurringPayment(id); + if (denied != null) return denied; + + if (recurringPayment.Status.HasEnded()) + { + Error(translationService.GetResource("Admin.Orders.RecurringPayments.Cancel.Ended")); + return RedirectToAction("Edit", new { id }); + } + + var result = await mediator.Send(new CancelRecurringPaymentCommand { + RecurringPayment = recurringPayment, + CancelledBy = contextAccessor.WorkContext.CurrentCustomer.StatusChangedBy() + }); + + //staff see the provider's own words, they are the ones who can act on them + if (result.Success) + Success(translationService.GetResource("Admin.Orders.RecurringPayments.Cancel.Success")); + else + Error(string.Join(" ", result.Errors)); + + return RedirectToAction("Edit", new { id }); + } + + #endregion + + private RecurringPaymentModel PrepareRecurringPaymentModel(RecurringPayment recurringPayment, Order initialOrder, + Customer customer, IList stores) + { + //the date the provider reported means nothing once it stopped charging + var charging = recurringPayment.Status is RecurringPaymentStatus.Active or RecurringPaymentStatus.PastDue; + return new RecurringPaymentModel { + Id = recurringPayment.Id, + CustomerId = recurringPayment.CustomerId, + CustomerEmail = customer?.Email ?? "", + StoreName = scope.DefaultStoreId is null + ? stores.FirstOrDefault(x => x.Id == recurringPayment.StoreId)?.Shortcut + : null, + StatusId = (int)recurringPayment.Status, + Status = enumTranslationService.GetTranslationEnum(recurringPayment.Status), + Cycle = string.Format( + translationService.GetResource(RecurringCycleText.ResourceKey(recurringPayment.CycleLength, + recurringPayment.CyclePeriodId)), recurringPayment.CycleLength), + CyclesPaid = recurringPayment.TotalCycles > 0 + ? string.Format(translationService.GetResource("RecurringPayment.CyclesPaid.Of"), + recurringPayment.CyclesPaid, recurringPayment.TotalCycles) + : string.Format(translationService.GetResource("RecurringPayment.CyclesPaid.UntilCancelled"), + recurringPayment.CyclesPaid), + NextPaymentDate = charging && recurringPayment.NextPaymentDateUtc.HasValue + ? dateTimeService.ConvertToUserTime(recurringPayment.NextPaymentDateUtc.Value, DateTimeKind.Utc) + : null, + PaymentMethodName = + paymentService.LoadPaymentMethodBySystemName(recurringPayment.PaymentMethodSystemName)?.FriendlyName ?? + recurringPayment.PaymentMethodSystemName, + InitialOrderId = initialOrder?.Id, + InitialOrderNumber = initialOrder?.OrderNumber ?? 0, + CanViewInitialOrder = initialOrder is { Deleted: false }, + CreatedOn = dateTimeService.ConvertToUserTime(recurringPayment.CreatedOnUtc, DateTimeKind.Utc), + CanCancel = !recurringPayment.Status.HasEnded() + }; + } +} diff --git a/src/Web/Grand.Web.AdminShared/Models/Orders/OrderModel.cs b/src/Web/Grand.Web.AdminShared/Models/Orders/OrderModel.cs index 46e7336be..8fcbbc9db 100644 --- a/src/Web/Grand.Web.AdminShared/Models/Orders/OrderModel.cs +++ b/src/Web/Grand.Web.AdminShared/Models/Orders/OrderModel.cs @@ -32,6 +32,26 @@ public class OrderModel : BaseEntityModel /// public bool CanDecideApproval { get; set; } + /// + /// 1 for the order a recurring payment started with, 2 and up for the orders of its next cycles, 0 otherwise + /// + [GrandResourceDisplayName("Admin.Orders.Fields.RecurringCycleNumber")] + public int RecurringCycleNumber { get; set; } + + /// + /// The recurring payment the order started; null for any other order, and in the vendor panel + /// + [GrandResourceDisplayName("Admin.Orders.Fields.RecurringPayment")] + public string RecurringPaymentId { get; set; } + + /// + /// The order a cycle order repeats; null when that order was deleted + /// + public string InitialOrderId { get; set; } + + [GrandResourceDisplayName("Admin.Orders.Fields.InitialOrder")] + public int InitialOrderNumber { get; set; } + //identifiers [GrandResourceDisplayName("Admin.Orders.Fields.ID")] public override string Id { get; set; } diff --git a/src/Web/Grand.Web.AdminShared/Models/Orders/RecurringPaymentListModel.cs b/src/Web/Grand.Web.AdminShared/Models/Orders/RecurringPaymentListModel.cs new file mode 100644 index 000000000..e6e007e35 --- /dev/null +++ b/src/Web/Grand.Web.AdminShared/Models/Orders/RecurringPaymentListModel.cs @@ -0,0 +1,25 @@ +using Grand.Infrastructure.ModelBinding; +using Grand.Infrastructure.Models; +using Microsoft.AspNetCore.Mvc.Rendering; + +namespace Grand.Web.AdminShared.Models.Orders; + +public class RecurringPaymentListModel : BaseModel +{ + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.List.SearchCustomerEmail")] + public string SearchCustomerEmail { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.List.SearchStatus")] + public int SearchStatusId { get; set; } = -1; + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.List.SearchStore")] + public string StoreId { get; set; } + + /// + /// False in the store panel, which sees its own store only + /// + public bool ShowStoreFilter { get; set; } + + public IList AvailableStatuses { get; set; } = new List(); + public IList AvailableStores { get; set; } = new List(); +} diff --git a/src/Web/Grand.Web.AdminShared/Models/Orders/RecurringPaymentModel.cs b/src/Web/Grand.Web.AdminShared/Models/Orders/RecurringPaymentModel.cs new file mode 100644 index 000000000..025a7be08 --- /dev/null +++ b/src/Web/Grand.Web.AdminShared/Models/Orders/RecurringPaymentModel.cs @@ -0,0 +1,83 @@ +using Grand.Infrastructure.ModelBinding; +using Grand.Infrastructure.Models; + +namespace Grand.Web.AdminShared.Models.Orders; + +/// +/// A recurring payment: a row of the list, and with its cycles the details screen +/// +public class RecurringPaymentModel : BaseEntityModel +{ + public string CustomerId { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.Customer")] + public string CustomerEmail { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.Store")] + public string StoreName { get; set; } + + public int StatusId { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.Status")] + public string Status { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.Cycle")] + public string Cycle { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.CyclesPaid")] + public string CyclesPaid { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.NextPaymentDate")] + public DateTime? NextPaymentDate { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.PaymentMethod")] + public string PaymentMethodName { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.ProviderReference")] + public string ProviderReference { get; set; } + + public string InitialOrderId { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.InitialOrder")] + public int InitialOrderNumber { get; set; } + + /// + /// False for a deleted initial order, which has no screen to open + /// + public bool CanViewInitialOrder { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.CreatedOn")] + public DateTime CreatedOn { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.LastError")] + public string LastError { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.LastErrorDate")] + public DateTime? LastErrorDate { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.CancelledOn")] + public DateTime? CancelledOn { get; set; } + + [GrandResourceDisplayName("Admin.Orders.RecurringPayments.Fields.CancelledBy")] + public string CancelledBy { get; set; } + + public bool CanCancel { get; set; } + + public IList Cycles { get; set; } = new List(); + + public class CycleModel + { + public int CycleNumber { get; set; } + public string OrderId { get; set; } + public int OrderNumber { get; set; } + + /// + /// False when the cycle's order was deleted, or was never created + /// + public bool CanViewOrder { get; set; } + + public string Amount { get; set; } + public DateTime PaidOn { get; set; } + public string ProviderReference { get; set; } + } +} diff --git a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs index 6fbaf370e..ed3f03b1c 100644 --- a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs +++ b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs @@ -71,6 +71,7 @@ public class OrderViewModelService : IOrderViewModelService private readonly IOrderApprovalService _orderApprovalService; private readonly IShipmentService _shipmentService; private readonly IAdminDataScope _merchandiseReturnScope; + private readonly IRecurringPaymentService _recurringPaymentService; #endregion @@ -107,8 +108,10 @@ public OrderViewModelService(IOrderService orderService, IAdminDataScope scope, IOrderApprovalService orderApprovalService, IShipmentService shipmentService, - IAdminDataScope merchandiseReturnScope) + IAdminDataScope merchandiseReturnScope, + IRecurringPaymentService recurringPaymentService) { + _recurringPaymentService = recurringPaymentService; _orderApprovalService = orderApprovalService; _shipmentService = shipmentService; _orderService = orderService; @@ -323,6 +326,31 @@ public virtual async Task PrepareOrderListModel( /// /// The order's approval request, for the panels that own the whole order: a vendor sees neither it nor its reasons /// + public virtual async Task PrepareOrderRecurringPayment(OrderModel model, Order order) + { + //the vendor panel has no recurring payment screens + if (_scope.DefaultVendorId is not null) + return; + + model.RecurringCycleNumber = order.RecurringCycleNumber; + switch (order.RecurringCycleNumber) + { + case 1: + model.RecurringPaymentId = + (await _recurringPaymentService.GetRecurringPaymentByInitialOrderId(order.Id))?.Id; + break; + //a cycle order copies the initial order's store and sales employee, so whoever opens one can open the other + case > 1 when !string.IsNullOrEmpty(order.InitialOrderId): + var initialOrder = await _orderService.GetOrderById(order.InitialOrderId); + if (initialOrder == null) + break; + model.InitialOrderNumber = initialOrder.OrderNumber; + if (!initialOrder.Deleted) + model.InitialOrderId = initialOrder.Id; + break; + } + } + public virtual async Task PrepareOrderApprovalDetails(OrderModel model, Order order) { if (_scope.DefaultVendorId is not null) @@ -415,6 +443,7 @@ public virtual async Task PrepareOrderDetailsModel(OrderModel model, Order order if (_scope.DefaultVendorId is null) model.CanCancelOrder = await _mediator.Send(new CanCancelOrderQuery { Order = order }); await PrepareOrderApprovalDetails(model, order); + await PrepareOrderRecurringPayment(model, order); await PrepareOrderMerchandiseReturns(model, order); var store = await _storeService.GetStoreById(order.StoreId); diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/Order/Partials/OrderDetails.Info.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Order/Partials/OrderDetails.Info.cshtml index d98ef2e96..7fce1538e 100644 --- a/src/Web/Grand.Web.AdminShared/Views/AdminShared/Order/Partials/OrderDetails.Info.cshtml +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Order/Partials/OrderDetails.Info.cshtml @@ -180,6 +180,35 @@
@Model.Code
} + @if (!string.IsNullOrEmpty(Model.RecurringPaymentId)) + { + + } + @if (Model.InitialOrderNumber > 0) + { +
+ +
+ @if (!string.IsNullOrEmpty(Model.InitialOrderId)) + { + @Model.InitialOrderNumber + } + else + { + @Model.InitialOrderNumber + } +
+
+
+ +
@Model.RecurringCycleNumber
+
+ } @if (!string.IsNullOrEmpty(Model.PurchaseOrderNumber)) {
diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/RecurringPayment/Edit.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/RecurringPayment/Edit.cshtml new file mode 100644 index 000000000..2ed9389a7 --- /dev/null +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/RecurringPayment/Edit.cshtml @@ -0,0 +1,178 @@ +@using Grand.Domain.Orders +@model RecurringPaymentModel +@{ + //page title + ViewBag.Title = Loc["Admin.Orders.RecurringPayments.Details"]; + var area = ViewContext.RouteData.Values["area"]?.ToString(); + var statusChip = Model.StatusId switch { + (int)RecurringPaymentStatus.Active => "grand-chip--green", + (int)RecurringPaymentStatus.PastDue => "grand-chip--red", + (int)RecurringPaymentStatus.Pending => "grand-chip--amber", + _ => "" + }; +} +
+ + + @* the payment transaction screen's shell: the provider runs the schedule, so there is nothing to save and + Cancel, which asks first, is the one operation *@ + + + + @if (Model.CanCancel) + { + + } + + + +
+
+ +
@Model.Status
+
+ +
+ +
+ @if (Model.CanViewInitialOrder) + { + @Model.InitialOrderNumber + } + else + { + @Model.InitialOrderNumber + } +
+
+ @if (!string.IsNullOrEmpty(Model.StoreName)) + { +
+ +
@Model.StoreName
+
+ } +
+ +
@Model.PaymentMethodName
+
+ @if (!string.IsNullOrEmpty(Model.ProviderReference)) + { +
+ +
@Model.ProviderReference
+
+ } +
+ +
@Model.Cycle
+
+
+ +
@Model.CyclesPaid
+
+ @if (Model.NextPaymentDate.HasValue) + { +
+ +
@Model.NextPaymentDate.Value.ToString("d")
+
+ } +
+ +
@Model.CreatedOn
+
+ @if (Model.CancelledOn.HasValue) + { +
+ +
@Model.CancelledOn
+
+
+ +
@Model.CancelledBy
+
+ } +
+
+ + @if (!string.IsNullOrEmpty(Model.LastError)) + { + +
+ @if (Model.LastErrorDate.HasValue) + { +
+ +
@Model.LastErrorDate
+
+ } +
+ +
@Model.LastError
+
+
+
+ } + + @* every cycle the provider reported as paid, the initial order's included *@ + + @if (Model.Cycles.Count == 0) + { +
+ +
@Loc["Admin.Orders.RecurringPayments.Cycles.Empty"]
+
+ } + else + { +
+ + + + + + + + + + + + @foreach (var cycle in Model.Cycles) + { + + + + + + + + } + +
@Loc["Admin.Orders.RecurringPayments.Cycles.CycleNumber"]@Loc["Admin.Orders.RecurringPayments.Cycles.Order"]@Loc["Admin.Orders.RecurringPayments.Cycles.Amount"]@Loc["Admin.Orders.RecurringPayments.Cycles.PaidOn"]@Loc["Admin.Orders.RecurringPayments.Fields.ProviderReference"]
@cycle.CycleNumber + @if (cycle.CanViewOrder) + { + @cycle.OrderNumber + } + else if (cycle.OrderNumber > 0) + { + @cycle.OrderNumber + } + @cycle.Amount@cycle.PaidOn@cycle.ProviderReference
+
+ } +
+
+
diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/RecurringPayment/List.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/RecurringPayment/List.cshtml new file mode 100644 index 000000000..60bda8c4d --- /dev/null +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/RecurringPayment/List.cshtml @@ -0,0 +1,83 @@ +@model RecurringPaymentListModel +@{ + //page title + ViewBag.Title = Loc["Admin.Orders.RecurringPayments"]; + var area = ViewContext.RouteData.Values["area"]?.ToString(); +} +
+ + @* the payment transactions list's shape: the customer's e-mail as the quick search, the status and the + store behind the Filters toggle. Recurring payments come from orders, so there is no primary action *@ + + + + + + + @if (Model.ShowStoreFilter) + { + + } + + + + + + + {{ CustomerEmail }} + + + + + {{ Status }} + {{ Status }} + {{ Status }} + {{ Status }} + + + + + + + + {{ InitialOrderNumber }} + {{ InitialOrderNumber }} + + + @if (Model.ShowStoreFilter) + { + + } + + + + +
+ + diff --git a/src/Web/Grand.Web.Store/Controllers/RecurringPaymentController.cs b/src/Web/Grand.Web.Store/Controllers/RecurringPaymentController.cs new file mode 100644 index 000000000..f1665797f --- /dev/null +++ b/src/Web/Grand.Web.Store/Controllers/RecurringPaymentController.cs @@ -0,0 +1,36 @@ +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; +using Grand.Business.Core.Interfaces.Customers; +using Grand.Domain.Orders; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.Web.AdminShared.Controllers; +using Grand.Web.AdminShared.Interfaces; +using Grand.Web.Common.Filters; +using Grand.Web.Common.Localization; +using Grand.Web.Store.Extensions; +using Microsoft.AspNetCore.Mvc; + +namespace Grand.Web.Store.Controllers; + +[AutoValidateAntiforgeryToken] +[Area(Constants.AreaStore)] +[AuthorizeStore] +[AuthorizeMenu] +public class RecurringPaymentController( + IRecurringPaymentService recurringPaymentService, + IOrderService orderService, + ICustomerService customerService, + IStoreService storeService, + IPaymentService paymentService, + IRequestTranslationService translationService, + IEnumTranslationService enumTranslationService, + IDateTimeService dateTimeService, + IMediator mediator, + IAdminDataScope scope, + IContextAccessor contextAccessor) + : BaseRecurringPaymentController(recurringPaymentService, orderService, customerService, storeService, + paymentService, translationService, enumTranslationService, dateTimeService, mediator, scope, + contextAccessor); diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 5b755764e..889fadc80 100644 Binary files a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml and b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml differ diff --git a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml index 2a6cb338e..071964f37 100644 --- a/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml +++ b/src/Web/Grand.Web/App_Data/Resources/Upgrade/en_250.xml @@ -2715,4 +2715,106 @@ Manage the recurring payment + + Recurring payments + + + Recurring payment details + + + back to the recurring payments list + + + Search by customer email + + + Status + + + Store + + + Customer + + + Store + + + Status + + + Billed + + + Payments + + + Next payment + + + Payment method + + + Provider reference + + + Initial order + + + Created on + + + Last error + + + Failed on + + + Cancelled on + + + Cancelled by + + + Paid cycles + + + The payment provider has not reported a paid cycle yet. + + + Cycle + + + Order + + + Amount + + + Paid on + + + Cancel recurring payment + + + Cancel this recurring payment? The payment provider will take no further payments, and it cannot be resumed. + + + The recurring payment has been cancelled. + + + This recurring payment has already ended. + + + Recurring payment + + + View the recurring payment + + + Recurring payment of order + + + Cycle +