diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 539194fc2..0496ecdf0 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -223,6 +223,28 @@ public virtual Task GetRecurringPaymentByInitialOrderId(string return repository.GetOneAsync(x => x.InitialOrderId == initialOrderId); } + public virtual async Task> GetCustomerRecurringPayments(string customerId, + string storeId, int pageIndex = 0, int pageSize = int.MaxValue) + { + if (string.IsNullOrEmpty(customerId) || string.IsNullOrEmpty(storeId)) + return new PagedList([], pageIndex, pageSize); + + var query = repository.Table + .Where(x => x.CustomerId == customerId && x.StoreId == storeId) + .OrderByDescending(x => x.CreatedOnUtc); + + return await repository.PagedAsync(query, pageIndex, pageSize); + } + + public virtual async Task HasCustomerRecurringPayments(string customerId, string storeId) + { + if (string.IsNullOrEmpty(customerId) || string.IsNullOrEmpty(storeId)) + return false; + + return await repository.AnyAsync(repository.Table + .Where(x => x.CustomerId == customerId && x.StoreId == storeId)); + } + public virtual async Task HasRecurringProducts(IEnumerable cart) { ArgumentNullException.ThrowIfNull(cart); diff --git a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs new file mode 100644 index 000000000..a4bb5e2bd --- /dev/null +++ b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs @@ -0,0 +1,15 @@ +using Grand.Domain.Orders; + +namespace Grand.Business.Core.Extensions; + +public static class RecurringPaymentExtensions +{ + /// + /// Whether a recurring payment in this status has ended: a Cancelled or Completed one charges nothing more and + /// cannot be cancelled + /// + public static bool HasEnded(this RecurringPaymentStatus status) + { + return status is RecurringPaymentStatus.Cancelled or RecurringPaymentStatus.Completed; + } +} 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 c703bba6f..495004fa6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -1,4 +1,5 @@ using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain; using Grand.Domain.Orders; namespace Grand.Business.Core.Interfaces.Checkout.Orders; @@ -52,6 +53,18 @@ Task Cancel(string recurringPaymentId, string canc /// Task GetRecurringPaymentByInitialOrderId(string initialOrderId); + /// + /// Gets a customer's recurring payments in a store, newest first; nothing for an empty customer or store + /// + Task> GetCustomerRecurringPayments(string customerId, string storeId, + int pageIndex = 0, int pageSize = int.MaxValue); + + /// + /// Gets a value indicating whether a customer has a recurring payment in a store; false for an empty customer + /// or store + /// + Task HasCustomerRecurringPayments(string customerId, string storeId); + /// /// Gets a value indicating whether the cart holds a product billed in cycles /// diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleText.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleText.cs new file mode 100644 index 000000000..ff061339c --- /dev/null +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleText.cs @@ -0,0 +1,24 @@ +using Grand.Domain.Catalog; + +namespace Grand.Business.Core.Utilities.Checkout; + +/// +/// The words for a recurring payment's cycle: "Every month" for one, "Every 3 months" for more; the enum +/// resources are plural, so "Every {0} {1}" reads "Every 1 Months" +/// +public static class RecurringCycleText +{ + /// + /// Gets the resource key of the cycle; the resource takes the cycle length as {0} + /// + public static string ResourceKey(int cycleLength, RecurringCyclePeriod period) + { + var (one, many) = period switch { + RecurringCyclePeriod.Weeks => ("Week", "Weeks"), + RecurringCyclePeriod.Months => ("Month", "Months"), + RecurringCyclePeriod.Years => ("Year", "Years"), + _ => ("Day", "Days") + }; + return $"RecurringPayment.Cycle.{(cycleLength == 1 ? one : many)}"; + } +} diff --git a/src/Core/Grand.Domain/Customers/CustomerSettings.cs b/src/Core/Grand.Domain/Customers/CustomerSettings.cs index 78175f36a..3d8cb525c 100644 --- a/src/Core/Grand.Domain/Customers/CustomerSettings.cs +++ b/src/Core/Grand.Domain/Customers/CustomerSettings.cs @@ -96,6 +96,11 @@ public class CustomerSettings : ISettings /// public bool HideSubAccountsTab { get; set; } + /// + /// Gets or sets a value indicating whether to hide 'Recurring payments' tab on 'My account' page + /// + public bool HideRecurringPaymentsTab { get; set; } + /// /// Gets or sets a value indicating whether to validate user when downloading products /// diff --git a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs index f1ed821bf..e73fd1752 100644 --- a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs +++ b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs @@ -940,6 +940,10 @@ await dbContext.CreateIndex(_serviceProvider.GetRequiredService>(), OrderBuilder.Create().Ascending(x => x.InitialOrderId), "InitialOrderId", true); + //the My account tab lists a customer's recurring payments in a store + await dbContext.CreateIndex(_serviceProvider.GetRequiredService>(), + OrderBuilder.Create().Ascending(x => x.CustomerId).Ascending(x => x.StoreId) + .Descending(x => x.CreatedOnUtc), "CustomerId_StoreId_CreatedOnUtc"); //queuemail await dbContext.CreateIndex(_queuedEmailRepository, diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentCustomerIndex.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentCustomerIndex.cs new file mode 100644 index 000000000..9cfe366b5 --- /dev/null +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationRecurringPaymentCustomerIndex.cs @@ -0,0 +1,39 @@ +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 MigrationRecurringPaymentCustomerIndex : IMigration +{ + private const string IndexName = "CustomerId_StoreId_CreatedOnUtc"; + + public int Priority => 1; + public DbVersion Version => new(2, 5); + public Guid Identity => new("5b0c2f3e-8d4a-4e61-9a7f-2c1e6d8b3f04"); + public string Name => "Customer 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 My account tab lists a customer's recurring payments in a store, newest first + await databaseContext.CreateIndex(repository, + OrderBuilder.Create().Ascending(x => x.CustomerId).Ascending(x => x.StoreId) + .Descending(x => x.CreatedOnUtc), IndexName); + } + catch (Exception ex) + { + logService.LogError(ex, "UpgradeProcess - RecurringPaymentCustomerIndex (2.5)"); + return false; + } + + return true; + } +} 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 0223056cf..7993dcf0f 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/RecurringPaymentServiceTests.cs @@ -589,4 +589,48 @@ public async Task ClaimCycle_Completing_PublishesNeitherEvent() Assert.AreEqual(0, Published().Count); Assert.AreEqual(0, Published().Count); } + + [TestMethod] + public async Task GetCustomerRecurringPayments_ReturnsOnlyTheCustomersInTheStore_NewestFirst() + { + await _repository.InsertAsync(new RecurringPayment { + Id = "old", CustomerId = "c1", StoreId = "s1", CreatedOnUtc = new DateTime(2026, 1, 1) + }); + await _repository.InsertAsync(new RecurringPayment { + Id = "new", CustomerId = "c1", StoreId = "s1", CreatedOnUtc = new DateTime(2026, 2, 1) + }); + await _repository.InsertAsync(new RecurringPayment { Id = "other-customer", CustomerId = "c2", StoreId = "s1" }); + await _repository.InsertAsync(new RecurringPayment { Id = "other-store", CustomerId = "c1", StoreId = "s2" }); + + var result = await _service.GetCustomerRecurringPayments("c1", "s1"); + + CollectionAssert.AreEqual(new[] { "new", "old" }, result.Select(x => x.Id).ToArray()); + } + + [TestMethod] + public async Task HasCustomerRecurringPayments_OnlyTheCustomersInTheStore() + { + await _repository.InsertAsync(new RecurringPayment { Id = "rp1", CustomerId = "c1", StoreId = "s1" }); + + Assert.IsTrue(await _service.HasCustomerRecurringPayments("c1", "s1")); + Assert.IsFalse(await _service.HasCustomerRecurringPayments("c1", "s2")); + Assert.IsFalse(await _service.HasCustomerRecurringPayments("c2", "s1")); + } + + [TestMethod] + public async Task HasCustomerRecurringPayments_EmptyCustomerOrStore_False() + { + await _repository.InsertAsync(new RecurringPayment { CustomerId = "", StoreId = "" }); + + Assert.IsFalse(await _service.HasCustomerRecurringPayments("", "")); + } + + [TestMethod] + public async Task GetCustomerRecurringPayments_EmptyCustomerOrStore_ReturnsNothing() + { + await _repository.InsertAsync(new RecurringPayment { CustomerId = "", StoreId = "" }); + + Assert.AreEqual(0, (await _service.GetCustomerRecurringPayments("", "s1")).Count); + Assert.AreEqual(0, (await _service.GetCustomerRecurringPayments("c1", "")).Count); + } } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Utilities/RecurringCycleTextTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Utilities/RecurringCycleTextTests.cs new file mode 100644 index 000000000..7bd2e8987 --- /dev/null +++ b/src/Tests/Grand.Business.Checkout.Tests/Utilities/RecurringCycleTextTests.cs @@ -0,0 +1,24 @@ +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Catalog; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Grand.Business.Checkout.Tests.Utilities; + +[TestClass] +public class RecurringCycleTextTests +{ + [DataTestMethod] + [DataRow(1, RecurringCyclePeriod.Days, "RecurringPayment.Cycle.Day")] + [DataRow(3, RecurringCyclePeriod.Days, "RecurringPayment.Cycle.Days")] + [DataRow(1, RecurringCyclePeriod.Weeks, "RecurringPayment.Cycle.Week")] + [DataRow(2, RecurringCyclePeriod.Weeks, "RecurringPayment.Cycle.Weeks")] + [DataRow(1, RecurringCyclePeriod.Months, "RecurringPayment.Cycle.Month")] + [DataRow(12, RecurringCyclePeriod.Months, "RecurringPayment.Cycle.Months")] + [DataRow(1, RecurringCyclePeriod.Years, "RecurringPayment.Cycle.Year")] + [DataRow(2, RecurringCyclePeriod.Years, "RecurringPayment.Cycle.Years")] + public void ResourceKey_OneCycleIsSingular_MoreArePlural(int cycleLength, RecurringCyclePeriod period, + string expected) + { + Assert.AreEqual(expected, RecurringCycleText.ResourceKey(cycleLength, period)); + } +} diff --git a/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettingsModel_ToDomain.verified.txt b/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettingsModel_ToDomain.verified.txt index 90d3c60d1..0c7b23895 100644 --- a/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettingsModel_ToDomain.verified.txt +++ b/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettingsModel_ToDomain.verified.txt @@ -12,6 +12,7 @@ HideNotesTab: false, HideDocumentsTab: false, HideSubAccountsTab: false, + HideRecurringPaymentsTab: false, DownloadableProductsValidateUser: false, NewsletterEnabled: false, NewsletterTickedByDefault: false, diff --git a/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettings_ToModel.verified.txt b/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettings_ToModel.verified.txt index fedc56195..ac2dcc141 100644 --- a/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettings_ToModel.verified.txt +++ b/src/Tests/Grand.Mapping.Tests/AdminShared/SettingsMappingTests.CustomerSettings_ToModel.verified.txt @@ -44,5 +44,6 @@ HideCoursesTab: false, TwoFactorAuthenticationEnabled: false, HideSubAccountsTab: false, + HideRecurringPaymentsTab: false, HideDocumentsTab: false } \ No newline at end of file diff --git a/src/Tests/Grand.Web.Tests/Controllers/RecurringPaymentControllerTests.cs b/src/Tests/Grand.Web.Tests/Controllers/RecurringPaymentControllerTests.cs new file mode 100644 index 000000000..12b197729 --- /dev/null +++ b/src/Tests/Grand.Web.Tests/Controllers/RecurringPaymentControllerTests.cs @@ -0,0 +1,223 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.Web.Common.Localization; +using Grand.Web.Controllers; +using Grand.Web.Features.Models.Orders; +using Grand.Web.Models.Orders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Web.Tests.Controllers; + +[TestClass] +public class RecurringPaymentControllerTests +{ + private Customer _customer; + private CustomerSettings _customerSettings; + private Grand.Domain.Stores.Store _store; + private Mock _mediator; + private Mock _recurringPaymentService; + private RecurringPaymentController _controller; + + [TestInitialize] + public void Init() + { + _customer = new Customer { Id = "buyer", Email = "buyer@shop.test" }; + _store = new Grand.Domain.Stores.Store { Id = "s1" }; + + var work = new Mock(); + work.Setup(w => w.CurrentCustomer).Returns(() => _customer); + work.Setup(w => w.WorkingLanguage).Returns(new Language { Id = "en" }); + var storeContext = new Mock(); + storeContext.Setup(s => s.CurrentStore).Returns(() => _store); + var context = new Mock(); + context.Setup(c => c.WorkContext).Returns(work.Object); + context.Setup(c => c.StoreContext).Returns(storeContext.Object); + + var translation = new Mock(); + translation.Setup(t => t.GetResource(It.IsAny())).Returns((string key) => key); + + _mediator = new Mock(); + _mediator.Setup(m => m.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync(new RecurringPaymentListModel()); + _recurringPaymentService = new Mock(); + _customerSettings = new CustomerSettings(); + _controller = new RecurringPaymentController(context.Object, _mediator.Object, + _recurringPaymentService.Object, translation.Object, _customerSettings, + new Mock>().Object) { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } + }; + _controller.TempData = new TempDataDictionary(_controller.HttpContext, new Mock().Object); + } + + private static void AssertRedirectTo(IActionResult result, string routeName) + { + Assert.IsInstanceOfType(result); + Assert.AreEqual(routeName, ((RedirectToRouteResult)result).RouteName); + } + + private IList Notifications(string type) + { + return _controller.TempData[$"grand.notifications.{type}"] as IList ?? []; + } + + [TestMethod] + public async Task List_TabOff_RedirectsToCustomerInfo() + { + _customerSettings.HideRecurringPaymentsTab = true; + + var result = await _controller.List(new OrderPagingModel()); + + AssertRedirectTo(result, "CustomerInfo"); + _mediator.Verify(m => m.Send(It.IsAny(), It.IsAny()), Times.Never); + } + + [TestMethod] + public async Task List_SendsTheCurrentCustomerAndStore() + { + var result = await _controller.List(new OrderPagingModel()); + + Assert.IsInstanceOfType(result); + _mediator.Verify(m => m.Send( + It.Is(q => q.Customer.Id == "buyer" && q.Store.Id == "s1" && q.Language.Id == "en"), + It.IsAny()), Times.Once); + } + + //cancelling + + private void Stored(RecurringPayment recurringPayment) + { + _recurringPaymentService.Setup(x => x.GetRecurringPaymentById(recurringPayment.Id)) + .ReturnsAsync(recurringPayment); + } + + private void GatewayAnswers(params string[] errors) + { + var result = new CancelRecurringPaymentResult(); + foreach (var error in errors) + result.AddError(error); + _mediator.Setup(m => m.Send(It.IsAny(), It.IsAny())) + .ReturnsAsync(result); + } + + private void AssertNotCancelled() + { + _mediator.Verify(m => m.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + + [TestMethod] + public async Task Cancel_OwnPayment_SendsTheCommandWithTheCustomersEmail() + { + var recurringPayment = new RecurringPayment { Id = "rp1", CustomerId = "buyer", StoreId = "s1" }; + Stored(recurringPayment); + GatewayAnswers(); + + var result = await _controller.Cancel("rp1"); + + AssertRedirectTo(result, "CustomerRecurringPayments"); + _mediator.Verify(m => m.Send( + It.Is(c => + c.RecurringPayment == recurringPayment && c.CancelledBy == "buyer@shop.test"), + It.IsAny()), Times.Once); + CollectionAssert.Contains(Notifications("success").ToList(), "RecurringPayment.Cancel.Success"); + } + + [TestMethod] + public async Task Cancel_OtherCustomersPayment_Refused() + { + Stored(new RecurringPayment { Id = "rp1", CustomerId = "someone-else", StoreId = "s1" }); + + var result = await _controller.Cancel("rp1"); + + AssertRedirectTo(result, "CustomerRecurringPayments"); + AssertNotCancelled(); + CollectionAssert.Contains(Notifications("error").ToList(), "RecurringPayment.Cancel.Refused"); + } + + [TestMethod] + public async Task Cancel_OtherStoresPayment_Refused() + { + Stored(new RecurringPayment { Id = "rp1", CustomerId = "buyer", StoreId = "s2" }); + + var result = await _controller.Cancel("rp1"); + + AssertRedirectTo(result, "CustomerRecurringPayments"); + AssertNotCancelled(); + CollectionAssert.Contains(Notifications("error").ToList(), "RecurringPayment.Cancel.Refused"); + } + + [TestMethod] + [DataRow(RecurringPaymentStatus.Cancelled)] + [DataRow(RecurringPaymentStatus.Completed)] + public async Task Cancel_EndedPayment_Refused(RecurringPaymentStatus status) + { + Stored(new RecurringPayment { Id = "rp1", CustomerId = "buyer", StoreId = "s1", Status = status }); + + var result = await _controller.Cancel("rp1"); + + AssertRedirectTo(result, "CustomerRecurringPayments"); + AssertNotCancelled(); + CollectionAssert.Contains(Notifications("error").ToList(), "RecurringPayment.Cancel.Refused"); + Assert.IsFalse(Notifications("success").Any()); + } + + [TestMethod] + public async Task Cancel_CustomerWithoutEmail_CancelledByTheirId() + { + _customer.Email = null; + Stored(new RecurringPayment { Id = "rp1", CustomerId = "buyer", StoreId = "s1" }); + GatewayAnswers(); + + await _controller.Cancel("rp1"); + + _mediator.Verify(m => m.Send(It.Is(c => c.CancelledBy == "buyer"), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task Cancel_UnknownId_Refused() + { + var result = await _controller.Cancel("missing"); + + AssertRedirectTo(result, "CustomerRecurringPayments"); + AssertNotCancelled(); + CollectionAssert.Contains(Notifications("error").ToList(), "RecurringPayment.Cancel.Refused"); + } + + [TestMethod] + public async Task Cancel_ProviderRefuses_ShowsTheGenericMessageNotTheProviderText() + { + Stored(new RecurringPayment { Id = "rp1", CustomerId = "buyer", StoreId = "s1" }); + GatewayAnswers("stripe: resource_missing"); + + var result = await _controller.Cancel("rp1"); + + AssertRedirectTo(result, "CustomerRecurringPayments"); + CollectionAssert.Contains(Notifications("error").ToList(), "RecurringPayment.Cancel.Failed"); + Assert.IsFalse(Notifications("error").Concat(Notifications("success")).Any(x => x.Contains("stripe"))); + } + + [TestMethod] + public async Task Cancel_TabOff_RedirectsToCustomerInfo() + { + _customerSettings.HideRecurringPaymentsTab = true; + Stored(new RecurringPayment { Id = "rp1", CustomerId = "buyer", StoreId = "s1" }); + + var result = await _controller.Cancel("rp1"); + + AssertRedirectTo(result, "CustomerInfo"); + _recurringPaymentService.Verify(x => x.GetRecurringPaymentById(It.IsAny()), Times.Never); + AssertNotCancelled(); + } +} diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Customers/GetNavigationHandlerTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Customers/GetNavigationHandlerTests.cs index 13eb166ff..660f03ee3 100644 --- a/src/Tests/Grand.Web.Tests/Features/Handlers/Customers/GetNavigationHandlerTests.cs +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Customers/GetNavigationHandlerTests.cs @@ -1,3 +1,4 @@ +using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Customers; using Grand.Domain; using Grand.Domain.Customers; @@ -28,10 +29,17 @@ private static Mock CustomerServiceWith(int subAccounts) return customers; } + private static Mock RecurringPaymentsWith(int recurringPayments) + { + var recurring = new Mock(); + recurring.Setup(x => x.HasCustomerRecurringPayments("c1", "s1")).ReturnsAsync(recurringPayments > 0); + return recurring; + } + private static async Task HideChangePassword(OidcLoginConfig config) { var handler = new GetNavigationHandler(new CustomerSettings(), new LoyaltyPointsSettings(), - new OrderSettings(), new VendorSettings(), config, CustomerServiceWith(0).Object); + new OrderSettings(), new VendorSettings(), config, CustomerServiceWith(0).Object, RecurringPaymentsWith(0).Object); var model = await handler.Handle(new GetNavigation { Customer = new Customer() }, CancellationToken.None); return model.HideChangePassword; } @@ -54,7 +62,7 @@ private static async Task HideOrderApprovals(Customer customer, int subAcc var customers = CustomerServiceWith(subAccounts); var handler = new GetNavigationHandler(new CustomerSettings { HideSubAccountsTab = featureOff }, new LoyaltyPointsSettings(), new OrderSettings(), new VendorSettings(), new OidcLoginConfig(), - customers.Object); + customers.Object, RecurringPaymentsWith(0).Object); var model = await handler.Handle(new GetNavigation { Customer = customer }, CancellationToken.None); return model.HideOrderApprovals; } @@ -82,4 +90,41 @@ public async Task Navigation_FeatureOff_HidesOrderApprovals() { Assert.IsTrue(await HideOrderApprovals(new Customer { Id = "sub", OwnerId = "owner" }, 0, true)); } + + private static async Task HideRecurringPayments(int recurringPayments, bool featureOff = false, + bool withStore = true) + { + var handler = new GetNavigationHandler(new CustomerSettings { HideRecurringPaymentsTab = featureOff }, + new LoyaltyPointsSettings(), new OrderSettings(), new VendorSettings(), new OidcLoginConfig(), + CustomerServiceWith(0).Object, RecurringPaymentsWith(recurringPayments).Object); + var model = await handler.Handle(new GetNavigation { + Customer = new Customer { Id = "c1" }, + Store = withStore ? new Grand.Domain.Stores.Store { Id = "s1" } : null + }, CancellationToken.None); + return model.HideRecurringPayments; + } + + [TestMethod] + public async Task Navigation_CustomerWithRecurringPayment_ShowsRecurringPayments() + { + Assert.IsFalse(await HideRecurringPayments(1)); + } + + [TestMethod] + public async Task Navigation_CustomerWithoutRecurringPayments_HidesRecurringPayments() + { + Assert.IsTrue(await HideRecurringPayments(0)); + } + + [TestMethod] + public async Task Navigation_RecurringPaymentsTabOff_HidesRecurringPayments() + { + Assert.IsTrue(await HideRecurringPayments(1, featureOff: true)); + } + + [TestMethod] + public async Task Navigation_NoStore_HidesRecurringPayments() + { + Assert.IsTrue(await HideRecurringPayments(1, withStore: false)); + } } diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerApprovalTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerApprovalTests.cs index 2dac56e86..56cd77eb8 100644 --- a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerApprovalTests.cs +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerApprovalTests.cs @@ -54,7 +54,8 @@ public void Init() orderService.Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, new CatalogSettings(), new OrderSettings(), new PdfSettings(), - new TaxSettings(), new Mock().Object, approvals.Object); + new TaxSettings(), new Mock().Object, approvals.Object, + new CustomerSettings()); } private Task Details(string customerId) diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerPaymentTermsTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerPaymentTermsTests.cs index 5e1bbcea9..2bdfcfb9c 100644 --- a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerPaymentTermsTests.cs +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerPaymentTermsTests.cs @@ -8,6 +8,7 @@ using Grand.Business.Core.Interfaces.Storage; using Grand.Domain.Catalog; using Grand.Domain.Common; +using Grand.Domain.Customers; using Grand.Domain.Localization; using Grand.Domain.Orders; using Grand.Domain.Payments; @@ -48,7 +49,8 @@ public void Init() orderService.Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, new CatalogSettings(), new OrderSettings(), new PdfSettings(), - new TaxSettings(), new Mock().Object, new Mock().Object); + new TaxSettings(), new Mock().Object, new Mock().Object, + new CustomerSettings()); } private Task Details(Order order) diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerRecurringTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerRecurringTests.cs new file mode 100644 index 000000000..d5e6213a4 --- /dev/null +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerRecurringTests.cs @@ -0,0 +1,151 @@ +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.Directory; +using Grand.Business.Core.Interfaces.Storage; +using Grand.Domain.Catalog; +using Grand.Domain.Common; +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Grand.Domain.Tax; +using Grand.Mediator; +using Grand.Web.Common.Localization; +using Grand.Web.Features.Handlers.Orders; +using Grand.Web.Features.Models.Orders; +using Grand.Web.Models.Orders; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Web.Tests.Features.Handlers.Orders; + +[TestClass] +public class GetOrderDetailsHandlerRecurringTests +{ + private CustomerSettings _customerSettings; + private Order _initialOrder; + private Mock _orderService; + private GetOrderDetailsHandler _handler; + + [TestInitialize] + public void Init() + { + _initialOrder = new Order { Id = "o1", OrderNumber = 1001, CustomerId = "buyer", StoreId = "s1" }; + _customerSettings = new CustomerSettings(); + + var dateTimeService = new Mock(); + dateTimeService.Setup(x => x.ConvertToUserTime(It.IsAny(), It.IsAny())) + .Returns((DateTime d, DateTimeKind _) => d); + var giftVoucherService = new Mock(); + giftVoucherService.Setup(x => x.GetAllGiftVoucherUsageHistory(It.IsAny())) + .ReturnsAsync(new List()); + _orderService = new Mock(); + _orderService.Setup(x => x.GetOrderNotes(It.IsAny())).ReturnsAsync(new List()); + _orderService.Setup(x => x.GetOrderById("o1")).ReturnsAsync(() => _initialOrder); + + _handler = new GetOrderDetailsHandler(dateTimeService.Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, giftVoucherService.Object, + _orderService.Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new CatalogSettings(), new OrderSettings(), new PdfSettings(), + new TaxSettings(), new Mock().Object, new Mock().Object, + _customerSettings); + } + + private Task Details(Order order, string viewerId = "buyer", string storeId = "s1") + { + return _handler.Handle(new GetOrderDetails { + Order = order, + Customer = new Customer { Id = viewerId }, + Store = new Domain.Stores.Store { Id = storeId }, + Language = new Language { Id = "en" } + }, CancellationToken.None); + } + + private static Order CycleOrder() + { + return new Order { Id = "o3", CustomerId = "buyer", RecurringCycleNumber = 3, InitialOrderId = "o1" }; + } + + [TestMethod] + public async Task GetOrderDetails_CycleOrder_LinksTheInitialOrder() + { + var model = await Details(CycleOrder()); + + Assert.AreEqual(3, model.RecurringCycleNumber); + Assert.AreEqual("o1", model.InitialOrderId); + Assert.AreEqual(1001, model.InitialOrderNumber); + Assert.IsFalse(model.ShowRecurringPaymentsLink); + } + + [TestMethod] + public async Task GetOrderDetails_CycleOrderOfDeletedInitialOrder_ShowsTheCycleWithoutTheLink() + { + _initialOrder.Deleted = true; + + var model = await Details(CycleOrder()); + + Assert.IsNull(model.InitialOrderId); + Assert.AreEqual(1001, model.InitialOrderNumber); + } + + [TestMethod] + public async Task GetOrderDetails_InitialOrder_ViewedByItsCustomer_LinksTheTab() + { + _initialOrder.RecurringCycleNumber = 1; + + var model = await Details(_initialOrder); + + Assert.AreEqual(1, model.RecurringCycleNumber); + Assert.IsTrue(model.ShowRecurringPaymentsLink); + Assert.IsNull(model.InitialOrderId); + } + + [TestMethod] + public async Task GetOrderDetails_InitialOrder_ViewedByTheCompanyOwner_NoTabLink() + { + _initialOrder.RecurringCycleNumber = 1; + + var model = await Details(_initialOrder, "owner"); + + Assert.IsFalse(model.ShowRecurringPaymentsLink); + } + + [TestMethod] + public async Task GetOrderDetails_InitialOrder_ViewedInAnotherStore_NoTabLink() + { + _initialOrder.RecurringCycleNumber = 1; + + var model = await Details(_initialOrder, storeId: "s2"); + + Assert.IsFalse(model.ShowRecurringPaymentsLink); + } + + [TestMethod] + public async Task GetOrderDetails_InitialOrder_TabOff_NoTabLink() + { + _initialOrder.RecurringCycleNumber = 1; + _customerSettings.HideRecurringPaymentsTab = true; + + var model = await Details(_initialOrder); + + Assert.IsFalse(model.ShowRecurringPaymentsLink); + } + + [TestMethod] + public async Task GetOrderDetails_OrdinaryOrder_NoRecurringFields() + { + var model = await Details(new Order { Id = "o9", CustomerId = "buyer" }); + + Assert.AreEqual(0, model.RecurringCycleNumber); + Assert.IsNull(model.InitialOrderId); + Assert.AreEqual(0, model.InitialOrderNumber); + Assert.IsFalse(model.ShowRecurringPaymentsLink); + _orderService.Verify(x => x.GetOrderById(It.IsAny()), Times.Never); + } +} diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerUnitsTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerUnitsTests.cs index 404002631..d71cf4824 100644 --- a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerUnitsTests.cs +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetOrderDetailsHandlerUnitsTests.cs @@ -55,7 +55,8 @@ public void Init() orderService.Object, new Mock().Object, new Mock().Object, new Mock().Object, new Mock().Object, new CatalogSettings(), new OrderSettings(), new PdfSettings(), - new TaxSettings(), new Mock().Object, new Mock().Object); + new TaxSettings(), new Mock().Object, new Mock().Object, + new CustomerSettings()); } private void Shipped(DateTime? shippedDateUtc, ShipmentItem item) diff --git a/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetRecurringPaymentsHandlerTests.cs b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetRecurringPaymentsHandlerTests.cs new file mode 100644 index 000000000..d710dc72b --- /dev/null +++ b/src/Tests/Grand.Web.Tests/Features/Handlers/Orders/GetRecurringPaymentsHandlerTests.cs @@ -0,0 +1,183 @@ +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Utilities.Catalog; +using Grand.Domain; +using Grand.Domain.Catalog; +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Domain.Orders; +using Grand.Web.Common.Localization; +using Grand.Web.Features.Handlers.Orders; +using Grand.Web.Features.Models.Orders; +using Grand.Web.Models.Orders; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Web.Tests.Features.Handlers.Orders; + +[TestClass] +public class GetRecurringPaymentsHandlerTests +{ + private List _payments; + private List _orders; + private GetRecurringPaymentsHandler _handler; + + [TestInitialize] + public void Init() + { + _payments = []; + _orders = []; + + var recurring = new Mock(); + recurring.Setup(x => x.GetCustomerRecurringPayments("buyer", "s1", 0, 10)) + .ReturnsAsync(() => new PagedList(_payments, 0, 10, _payments.Count)); + var orders = new Mock(); + orders.Setup(x => x.GetOrdersByIds(It.IsAny())) + .ReturnsAsync((string[] ids) => _orders.Where(o => ids.Contains(o.Id)).ToList()); + var products = new Mock(); + products.Setup(x => x.GetProductsByIds(It.IsAny(), It.IsAny())) + .ReturnsAsync((string[] ids, CatalogAccess _) => + ids.Contains("p1") ? [new Product { Id = "p1", Name = "Studio Membership" }] : []); + var dates = new Mock(); + dates.Setup(x => x.ConvertToUserTime(It.IsAny(), DateTimeKind.Utc)) + .Returns((DateTime d, DateTimeKind _) => d); + var enums = new Mock(); + enums.Setup(x => x.GetTranslationEnum(It.IsAny())) + .Returns((RecurringPaymentStatus s) => s.ToString()); + var translation = new Mock(); + translation.Setup(x => x.GetResource(It.IsAny())).Returns((string key) => key switch { + "RecurringPayment.CyclesPaid.Of" => "{0} of {1}", + "RecurringPayment.CyclesPaid.UntilCancelled" => "{0}, until cancelled", + "RecurringPayment.Cycle.Months" => "Every {0} months", + _ => key + }); + + _handler = new GetRecurringPaymentsHandler(recurring.Object, orders.Object, products.Object, dates.Object, + enums.Object, translation.Object); + } + + private static RecurringPayment Payment(RecurringPaymentStatus status, string initialOrderId = "o1") + { + return new RecurringPayment { + Id = "rp-" + status + "-" + initialOrderId, CustomerId = "buyer", StoreId = "s1", + InitialOrderId = initialOrderId, Status = status, CycleLength = 1, + CyclePeriodId = RecurringCyclePeriod.Months, TotalCycles = 12, CyclesPaid = 3, + NextPaymentDateUtc = new DateTime(2026, 12, 1) + }; + } + + private static Order Placed(string id, int number, bool deleted = false) + { + return new Order { + Id = id, OrderNumber = number, Deleted = deleted, + OrderItems = { new OrderItem { ProductId = "p1", Quantity = 1 } } + }; + } + + private async Task List() + { + return await _handler.Handle(new GetRecurringPayments { + Customer = new Customer { Id = "buyer" }, + Store = new Grand.Domain.Stores.Store { Id = "s1" }, + Language = new Language { Id = "en" } + }, CancellationToken.None); + } + + [TestMethod] + public async Task GetRecurringPayments_ActiveMonthly_FillsTheRow() + { + _payments.Add(Payment(RecurringPaymentStatus.Active)); + _orders.Add(Placed("o1", 1001)); + + var row = (await List()).RecurringPayments.Single(); + + Assert.AreEqual("RecurringPayment.Cycle.Month", row.Cycle); + Assert.AreEqual("3 of 12", row.CyclesPaid); + Assert.AreEqual(new DateTime(2026, 12, 1), row.NextPaymentDate); + Assert.AreEqual("o1", row.InitialOrderId); + Assert.AreEqual(1001, row.InitialOrderNumber); + Assert.IsTrue(row.CanViewInitialOrder); + CollectionAssert.AreEqual(new[] { "Studio Membership" }, row.Products.ToArray()); + Assert.IsTrue(row.CanCancel); + Assert.AreEqual((int)RecurringPaymentStatus.Active, row.StatusId); + Assert.AreEqual("Active", row.Status); + } + + [TestMethod] + public async Task GetRecurringPayments_LongerCycle_UsesThePluralText() + { + var payment = Payment(RecurringPaymentStatus.Active); + payment.CycleLength = 3; + _payments.Add(payment); + + var row = (await List()).RecurringPayments.Single(); + + Assert.AreEqual("Every 3 months", row.Cycle); + } + + [TestMethod] + public async Task GetRecurringPayments_UntilCancelled_UsesTheUnlimitedText() + { + var payment = Payment(RecurringPaymentStatus.Active); + payment.TotalCycles = 0; + _payments.Add(payment); + + var row = (await List()).RecurringPayments.Single(); + + Assert.AreEqual("3, until cancelled", row.CyclesPaid); + } + + [TestMethod] + public async Task GetRecurringPayments_CancelledOrCompleted_CannotCancelAndHasNoNextPayment() + { + _payments.Add(Payment(RecurringPaymentStatus.Cancelled)); + _payments.Add(Payment(RecurringPaymentStatus.Completed)); + _orders.Add(Placed("o1", 1001)); + + foreach (var row in (await List()).RecurringPayments) + { + Assert.IsFalse(row.CanCancel); + Assert.IsNull(row.NextPaymentDate); + } + } + + [TestMethod] + public async Task GetRecurringPayments_PendingAndPastDue_CanCancel() + { + _payments.Add(Payment(RecurringPaymentStatus.Pending)); + _payments.Add(Payment(RecurringPaymentStatus.PastDue)); + + Assert.IsTrue((await List()).RecurringPayments.All(x => x.CanCancel)); + } + + [TestMethod] + public async Task GetRecurringPayments_InitialOrderMissingOrDeleted_RowWithoutOrderLink() + { + _payments.Add(Payment(RecurringPaymentStatus.Active, "missing")); + _payments.Add(Payment(RecurringPaymentStatus.Active, "deleted")); + _orders.Add(Placed("deleted", 1002, deleted: true)); + + var rows = (await List()).RecurringPayments; + + Assert.AreEqual(2, rows.Count); + Assert.IsTrue(rows.All(x => !x.CanViewInitialOrder && x.Products.Count == 0)); + Assert.AreEqual(0, rows.Single(x => x.Id == "rp-Active-missing").InitialOrderNumber); + } + + [TestMethod] + public async Task GetRecurringPayments_PastDue_FlagsTheRowWithoutTheProviderError() + { + var payment = Payment(RecurringPaymentStatus.PastDue); + payment.LastError = "card_declined: raw"; + _payments.Add(payment); + _orders.Add(Placed("o1", 1001)); + + var row = (await List()).RecurringPayments.Single(); + + Assert.IsTrue(row.IsPastDue); + var texts = row.GetType().GetProperties().Where(p => p.PropertyType == typeof(string)) + .Select(p => (string)p.GetValue(row)).Concat(row.Products); + Assert.IsFalse(texts.Any(x => x != null && x.Contains("card_declined"))); + } +} diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml index 26b2b1687..a861172ac 100644 --- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml +++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml @@ -49,6 +49,7 @@ + @* unsubscribing is offered only while the block is shown, so the two share a row; the Customer form fields tab's script toggles it *@ diff --git a/src/Web/Grand.Web.AdminShared/Models/Settings/CustomerSettingsModel.cs b/src/Web/Grand.Web.AdminShared/Models/Settings/CustomerSettingsModel.cs index 9b4deebd4..f641b2902 100644 --- a/src/Web/Grand.Web.AdminShared/Models/Settings/CustomerSettingsModel.cs +++ b/src/Web/Grand.Web.AdminShared/Models/Settings/CustomerSettingsModel.cs @@ -183,6 +183,9 @@ public class CustomersSettingsModel : BaseModel [GrandResourceDisplayName("Admin.Settings.Customer.HideSubaccountsTab")] public bool HideSubAccountsTab { get; set; } + [GrandResourceDisplayName("Admin.Settings.Customer.HideRecurringPaymentsTab")] + public bool HideRecurringPaymentsTab { get; set; } + [GrandResourceDisplayName("Admin.Settings.Customer.HideDocumentsTab")] public bool HideDocumentsTab { get; set; } diff --git a/src/Web/Grand.Web.Models/Customer/CustomerNavigationModel.cs b/src/Web/Grand.Web.Models/Customer/CustomerNavigationModel.cs index 994b9bae9..eb22b1d2c 100644 --- a/src/Web/Grand.Web.Models/Customer/CustomerNavigationModel.cs +++ b/src/Web/Grand.Web.Models/Customer/CustomerNavigationModel.cs @@ -20,6 +20,7 @@ public class CustomerNavigationModel : BaseModel public bool HideCourses { get; set; } public bool HideSubAccounts { get; set; } public bool HideOrderApprovals { get; set; } + public bool HideRecurringPayments { get; set; } public AccountNavigationEnum SelectedTab { get; set; } } @@ -28,6 +29,7 @@ public enum AccountNavigationEnum Info = 0, Addresses = 10, Orders = 20, + RecurringPayments = 25, OutOfStockSubscriptions = 30, MerchandiseReturns = 40, DownloadableProducts = 50, diff --git a/src/Web/Grand.Web.Models/Orders/OrderDetailsModel.cs b/src/Web/Grand.Web.Models/Orders/OrderDetailsModel.cs index 45762082a..dfc48f862 100644 --- a/src/Web/Grand.Web.Models/Orders/OrderDetailsModel.cs +++ b/src/Web/Grand.Web.Models/Orders/OrderDetailsModel.cs @@ -13,6 +13,25 @@ public class OrderDetailsModel : BaseEntityModel /// public bool GuestLink { get; set; } + /// + /// Gets or sets the recurring payment cycle: 1 on the order the customer placed, 2 and more on the orders + /// the payment provider charged afterwards, 0 on an ordinary order + /// + public int RecurringCycleNumber { get; set; } + + /// + /// Gets or sets the initial order of a cycle order; empty when it cannot be opened + /// + public string InitialOrderId { get; set; } + + public int InitialOrderNumber { get; set; } + + /// + /// Gets or sets a value indicating whether the order's own customer is shown the way to the recurring + /// payments tab + /// + public bool ShowRecurringPaymentsLink { get; set; } + /// /// Whether the order has returns, which a guest who came with the link reaches from the page /// diff --git a/src/Web/Grand.Web.Models/Orders/RecurringPaymentListModel.cs b/src/Web/Grand.Web.Models/Orders/RecurringPaymentListModel.cs new file mode 100644 index 000000000..4ed68caea --- /dev/null +++ b/src/Web/Grand.Web.Models/Orders/RecurringPaymentListModel.cs @@ -0,0 +1,52 @@ +using Grand.Infrastructure.Models; + +namespace Grand.Web.Models.Orders; + +public class RecurringPaymentListModel : BaseModel +{ + public OrderPagingModel PagingContext { get; set; } = new(); + + public IList RecurringPayments { get; set; } = new List(); + + public class RecurringPaymentRowModel : BaseEntityModel + { + public DateTime CreatedOn { get; set; } + public int StatusId { get; set; } + public string Status { get; set; } + + /// + /// Gets or sets a value indicating whether the customer may cancel it: Pending, Active or PastDue + /// + public bool CanCancel { get; set; } + + /// + /// Gets or sets a value indicating whether the last cycle failed; the provider's reason is not shown + /// + public bool IsPastDue { get; set; } + + /// + /// Gets or sets the cycle, e.g. "Every month" + /// + public string Cycle { get; set; } + + /// + /// Gets or sets the paid cycles, e.g. "3 of 12" + /// + public string CyclesPaid { get; set; } + + /// + /// Gets or sets the next payment date reported by the provider, while it still charges + /// + public DateTime? NextPaymentDate { get; set; } + + public string InitialOrderId { get; set; } + public int InitialOrderNumber { get; set; } + + /// + /// Gets or sets a value indicating whether the initial order exists and can be opened + /// + public bool CanViewInitialOrder { get; set; } + + public IList Products { get; set; } = new List(); + } +} diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml index 26b2b1687..a861172ac 100644 --- a/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml +++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Setting/Partials/Customer.TabCustomerSettings.cshtml @@ -49,6 +49,7 @@ + @* unsubscribing is offered only while the block is shown, so the two share a row; the Customer form fields tab's script toggles it *@ diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 77c693bd9..5b755764e 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 42ea7efde..2a6cb338e 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 @@ -2616,4 +2616,103 @@ Years + + Every day + + + Every {0} days + + + Every week + + + Every {0} weeks + + + Every month + + + Every {0} months + + + Every year + + + Every {0} years + + + Waiting for the first payment + + + Active + + + Payment failed + + + Cancelled + + + Completed + + + Recurring payments + + + Hide 'Recurring payments' tab + + + Products + + + Billed + + + Payments + + + {0} of {1} + + + {0}, until cancelled + + + Next payment + + + Status + + + Order + + + The last payment failed. The payment provider will try again; check the card you pay with. + + + You have no recurring payments. + + + Cancel + + + Cancel this recurring payment? No further payments will be taken, and it cannot be resumed. + + + The recurring payment has been cancelled. + + + This recurring payment cannot be cancelled. + + + The payment provider could not cancel this recurring payment. Please try again later or contact us. + + + Payment {0} of a recurring order + + + placed as order + + + Manage the recurring payment + diff --git a/src/Web/Grand.Web/Controllers/OrderController.cs b/src/Web/Grand.Web/Controllers/OrderController.cs index 6ee3b3e1d..bcb04eba1 100644 --- a/src/Web/Grand.Web/Controllers/OrderController.cs +++ b/src/Web/Grand.Web/Controllers/OrderController.cs @@ -116,6 +116,7 @@ public virtual async Task> Details(string orderI { Order = order, Customer = customer, + Store = _contextAccessor.StoreContext.CurrentStore, Language = _contextAccessor.WorkContext.WorkingLanguage }); model.GuestLink = guestLink; diff --git a/src/Web/Grand.Web/Controllers/RecurringPaymentController.cs b/src/Web/Grand.Web/Controllers/RecurringPaymentController.cs new file mode 100644 index 000000000..1c50765a7 --- /dev/null +++ b/src/Web/Grand.Web/Controllers/RecurringPaymentController.cs @@ -0,0 +1,101 @@ +using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Domain.Customers; +using Grand.Infrastructure; +using Grand.Mediator; +using Grand.SharedKernel.Attributes; +using Grand.Web.Common.Controllers; +using Grand.Web.Common.Filters; +using Grand.Web.Common.Localization; +using Grand.Web.Common.Security.Authorization; +using Grand.Web.Features.Models.Orders; +using Grand.Web.Models.Orders; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; + +namespace Grand.Web.Controllers; + +/// +/// The customer's recurring payments: what a payment provider charges in cycles, and cancelling it +/// +[DenySystemAccount] +[ApiGroup(SharedKernel.Extensions.ApiConstants.ApiGroupNameV2)] +public class RecurringPaymentController : BasePublicController +{ + private readonly IContextAccessor _contextAccessor; + private readonly CustomerSettings _customerSettings; + private readonly ILogger _logger; + private readonly IMediator _mediator; + private readonly IRecurringPaymentService _recurringPaymentService; + private readonly IRequestTranslationService _translationService; + + public RecurringPaymentController(IContextAccessor contextAccessor, IMediator mediator, + IRecurringPaymentService recurringPaymentService, IRequestTranslationService translationService, + CustomerSettings customerSettings, ILogger logger) + { + _contextAccessor = contextAccessor; + _mediator = mediator; + _recurringPaymentService = recurringPaymentService; + _translationService = translationService; + _customerSettings = customerSettings; + _logger = logger; + } + + //My account / Recurring payments + [HttpGet] + [CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)] + public virtual async Task List(OrderPagingModel command) + { + if (_customerSettings.HideRecurringPaymentsTab) + return RedirectToRoute("CustomerInfo"); + + var model = await _mediator.Send(new GetRecurringPayments { + Customer = _contextAccessor.WorkContext.CurrentCustomer, + Store = _contextAccessor.StoreContext.CurrentStore, + Language = _contextAccessor.WorkContext.WorkingLanguage, + Command = command + }); + return View(model); + } + + /// Recurring payment identifier + [HttpPost] + [CustomerGroupAuthorize(SystemCustomerGroupNames.Registered)] + public virtual async Task Cancel(string id) + { + if (_customerSettings.HideRecurringPaymentsTab) + return RedirectToRoute("CustomerInfo"); + + var customer = _contextAccessor.WorkContext.CurrentCustomer; + var recurringPayment = await _recurringPaymentService.GetRecurringPaymentById(id); + //a missing, foreign, other-store or ended recurring payment is answered alike + if (recurringPayment == null || recurringPayment.CustomerId != customer.Id || + recurringPayment.StoreId != _contextAccessor.StoreContext.CurrentStore.Id || + recurringPayment.Status.HasEnded()) + { + Error(_translationService.GetResource("RecurringPayment.Cancel.Refused")); + return RedirectToRoute("CustomerRecurringPayments"); + } + + var result = await _mediator.Send(new CancelRecurringPaymentCommand { + RecurringPayment = recurringPayment, + //a registered customer may have no e-mail, while the cancel must name who asked + CancelledBy = string.IsNullOrEmpty(customer.Email) ? customer.Id : customer.Email + }); + + if (result.Success) + { + Success(_translationService.GetResource("RecurringPayment.Cancel.Success")); + } + else + { + //the provider's words are for the store, not the customer + _logger.LogWarning("Recurring payment {RecurringPaymentId}: the customer's cancel was refused: {Errors}", + recurringPayment.Id, string.Join("; ", result.Errors)); + Error(_translationService.GetResource("RecurringPayment.Cancel.Failed")); + } + + return RedirectToRoute("CustomerRecurringPayments"); + } +} diff --git a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs b/src/Web/Grand.Web/Endpoints/EndpointProvider.cs index fb0fbd505..964ae821b 100644 --- a/src/Web/Grand.Web/Endpoints/EndpointProvider.cs +++ b/src/Web/Grand.Web/Endpoints/EndpointProvider.cs @@ -172,6 +172,14 @@ private void RegisterAccountRoute(IEndpointRouteBuilder endpointRouteBuilder, st pattern + "orderapproval/decide", new { controller = "OrderApproval", action = "Decide" }); + endpointRouteBuilder.MapControllerRoute("CustomerRecurringPayments", + pattern + "account/recurringpayments", + new { controller = "RecurringPayment", action = "List" }); + + endpointRouteBuilder.MapControllerRoute("RecurringPaymentCancel", + pattern + "recurringpayment/cancel", + new { controller = "RecurringPayment", action = "Cancel" }); + endpointRouteBuilder.MapControllerRoute("OrderApprovalWithdraw", pattern + "orderapproval/withdraw", new { controller = "OrderApproval", action = "Withdraw" }); diff --git a/src/Web/Grand.Web/Features/Handlers/Customers/GetNavigationHandler.cs b/src/Web/Grand.Web/Features/Handlers/Customers/GetNavigationHandler.cs index b580e92a6..7de81cc35 100644 --- a/src/Web/Grand.Web/Features/Handlers/Customers/GetNavigationHandler.cs +++ b/src/Web/Grand.Web/Features/Handlers/Customers/GetNavigationHandler.cs @@ -1,4 +1,5 @@ -using Grand.Business.Core.Interfaces.Customers; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Customers; using Grand.Domain.Orders; using Grand.Domain.Vendors; @@ -16,6 +17,7 @@ public class GetNavigationHandler : IRequestHandler Handle(GetNavigation request, CancellationToken cancellationToken) @@ -50,6 +54,8 @@ public async Task Handle(GetNavigation request, Cancell HideCourses = _customerSettings.HideCoursesTab, HideSubAccounts = _customerSettings.HideSubAccountsTab || !string.IsNullOrEmpty(request.Customer.OwnerId), HideOrderApprovals = _customerSettings.HideSubAccountsTab || !await IsInCompany(request.Customer), + HideRecurringPayments = _customerSettings.HideRecurringPaymentsTab || + !await HasRecurringPayments(request.Customer, request.Store), SelectedTab = (AccountNavigationEnum)request.SelectedTabId }; @@ -67,4 +73,16 @@ private async Task IsInCompany(Customer customer) var subAccounts = await _customerService.GetAllCustomers(ownerId: customer.Id, pageSize: 1); return subAccounts.TotalCount > 0; } + + /// + /// Recurring products cannot be bought until a payment provider charges in cycles, so a tab every customer + /// would find empty is shown only to those who have a recurring payment + /// + private async Task HasRecurringPayments(Customer customer, Domain.Stores.Store store) + { + if (store == null) + return false; + + return await _recurringPaymentService.HasCustomerRecurringPayments(customer.Id, store.Id); + } } \ No newline at end of file diff --git a/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs index 72c5723e1..504703af9 100644 --- a/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs +++ b/src/Web/Grand.Web/Features/Handlers/Orders/GetOrderDetailsHandler.cs @@ -11,6 +11,7 @@ using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Domain.Catalog; using Grand.Domain.Common; +using Grand.Domain.Customers; using Grand.Domain.Directory; using Grand.Domain.Orders; using Grand.Domain.Payments; @@ -29,6 +30,7 @@ namespace Grand.Web.Features.Handlers.Orders; public class GetOrderDetailsHandler : IRequestHandler { private readonly CatalogSettings _catalogSettings; + private readonly CustomerSettings _customerSettings; private readonly ICurrencyService _currencyService; private readonly IDateTimeService _dateTimeService; private readonly IGiftVoucherService _giftVoucherService; @@ -69,8 +71,10 @@ public GetOrderDetailsHandler( PdfSettings pdfSettings, TaxSettings taxSettings, IEnumTranslationService enumTranslationService, - IOrderApprovalService orderApprovalService) + IOrderApprovalService orderApprovalService, + CustomerSettings customerSettings) { + _customerSettings = customerSettings; _orderApprovalService = orderApprovalService; _dateTimeService = dateTimeService; _productService = productService; @@ -154,6 +158,9 @@ await _mediator.Send(new IsMerchandiseReturnAllowedQuery { Order = request.Order //a request the store decides: the storefront's approvals screen only carries the company's await PrepareOrderApproval(request, model); + //the link between a cycle order and the order the customer placed + await PrepareRecurringPayment(request, model); + //allow cancel order if (_orderSettings.UserCanCancelUnpaidOrder) if (request.Order.OrderStatusId == (int)OrderStatusSystem.Pending && request.Order.PaymentStatusId == @@ -348,6 +355,30 @@ private Task PrepareLoyaltyPoints(GetOrderDetails request, OrderDetailsModel mod return Task.CompletedTask; } + private async Task PrepareRecurringPayment(GetOrderDetails request, OrderDetailsModel model) + { + model.RecurringCycleNumber = request.Order.RecurringCycleNumber; + switch (request.Order.RecurringCycleNumber) + { + //the tab lists the customer's own recurring payments in the current store, so a company owner viewing a + //sub-account's order, or an order placed in another store, has nowhere to go + case 1: + model.ShowRecurringPaymentsLink = !_customerSettings.HideRecurringPaymentsTab && + request.Customer.Id == request.Order.CustomerId && + request.Store?.Id == request.Order.StoreId; + break; + //a cycle order copies the initial order's customer and owner, so whoever opens one can open the other + case > 1 when !string.IsNullOrEmpty(request.Order.InitialOrderId): + var initialOrder = await _orderService.GetOrderById(request.Order.InitialOrderId); + if (initialOrder == null) + break; + model.InitialOrderNumber = initialOrder.OrderNumber; + if (!initialOrder.Deleted) + model.InitialOrderId = initialOrder.Id; + break; + } + } + private async Task PrepareOrderApproval(GetOrderDetails request, OrderDetailsModel model) { var approval = await _orderApprovalService.GetByOrderId(request.Order.Id); diff --git a/src/Web/Grand.Web/Features/Handlers/Orders/GetRecurringPaymentsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Orders/GetRecurringPaymentsHandler.cs new file mode 100644 index 000000000..60ce87b43 --- /dev/null +++ b/src/Web/Grand.Web/Features/Handlers/Orders/GetRecurringPaymentsHandler.cs @@ -0,0 +1,107 @@ +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Catalog.Products; +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Utilities.Catalog; +using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Catalog; +using Grand.Domain.Orders; +using Grand.Mediator; +using Grand.Web.Common.Localization; +using Grand.Web.Features.Models.Orders; +using Grand.Web.Models.Orders; + +namespace Grand.Web.Features.Handlers.Orders; + +public class GetRecurringPaymentsHandler : IRequestHandler +{ + private const int DefaultPageSize = 10; + private const int MaxPageSize = 50; + + private readonly IDateTimeService _dateTimeService; + private readonly IEnumTranslationService _enumTranslationService; + private readonly IOrderService _orderService; + private readonly IProductService _productService; + private readonly IRecurringPaymentService _recurringPaymentService; + private readonly IRequestTranslationService _translationService; + + public GetRecurringPaymentsHandler(IRecurringPaymentService recurringPaymentService, IOrderService orderService, + IProductService productService, IDateTimeService dateTimeService, + IEnumTranslationService enumTranslationService, IRequestTranslationService translationService) + { + _recurringPaymentService = recurringPaymentService; + _orderService = orderService; + _productService = productService; + _dateTimeService = dateTimeService; + _enumTranslationService = enumTranslationService; + _translationService = translationService; + } + + public async Task Handle(GetRecurringPayments request, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request.Customer); + ArgumentNullException.ThrowIfNull(request.Store); + + var pageIndex = Math.Max(request.Command.PageNumber, 1) - 1; + var pageSize = request.Command.PageSize <= 0 ? DefaultPageSize : Math.Min(request.Command.PageSize, MaxPageSize); + + var recurringPayments = await _recurringPaymentService.GetCustomerRecurringPayments(request.Customer.Id, + request.Store.Id, pageIndex, pageSize); + + var model = new RecurringPaymentListModel(); + model.PagingContext.LoadPagedList(recurringPayments); + + var orders = new Dictionary(); + var orderIds = recurringPayments.Select(x => x.InitialOrderId).Where(x => !string.IsNullOrEmpty(x)) + .Distinct().ToArray(); + if (orderIds.Length > 0) + foreach (var order in await _orderService.GetOrdersByIds(orderIds)) + orders[order.Id] = order; + + //a deleted order is not opened, so its products are not listed either + var products = new Dictionary(); + var productIds = orders.Values.Where(x => !x.Deleted).SelectMany(x => x.OrderItems) + .Select(x => x.ProductId).Distinct().ToArray(); + if (productIds.Length > 0) + foreach (var product in await _productService.GetProductsByIds(productIds, CatalogAccess.IncludingHidden())) + products[product.Id] = product; + + foreach (var recurringPayment in recurringPayments) + { + var order = orders.GetValueOrDefault(recurringPayment.InitialOrderId ?? ""); + var canViewOrder = order is { Deleted: false }; + //the date the provider reported means nothing once it stopped charging + var charging = recurringPayment.Status is RecurringPaymentStatus.Active or RecurringPaymentStatus.PastDue; + + model.RecurringPayments.Add(new RecurringPaymentListModel.RecurringPaymentRowModel { + Id = recurringPayment.Id, + CreatedOn = _dateTimeService.ConvertToUserTime(recurringPayment.CreatedOnUtc, DateTimeKind.Utc), + StatusId = (int)recurringPayment.Status, + Status = _enumTranslationService.GetTranslationEnum(recurringPayment.Status), + CanCancel = !recurringPayment.Status.HasEnded(), + IsPastDue = recurringPayment.Status == RecurringPaymentStatus.PastDue, + 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, + InitialOrderId = recurringPayment.InitialOrderId, + InitialOrderNumber = order?.OrderNumber ?? 0, + CanViewInitialOrder = canViewOrder, + Products = canViewOrder + ? order.OrderItems.Where(x => products.ContainsKey(x.ProductId)) + .Select(x => products[x.ProductId].GetTranslation(p => p.Name, request.Language.Id)).ToList() + : [] + }); + } + + return model; + } +} diff --git a/src/Web/Grand.Web/Features/Models/Orders/GetOrderDetails.cs b/src/Web/Grand.Web/Features/Models/Orders/GetOrderDetails.cs index f416be2ad..5e3c3b6cd 100644 --- a/src/Web/Grand.Web/Features/Models/Orders/GetOrderDetails.cs +++ b/src/Web/Grand.Web/Features/Models/Orders/GetOrderDetails.cs @@ -10,5 +10,6 @@ public class GetOrderDetails : IRequest { public Order Order { get; set; } public Customer Customer { get; set; } + public Domain.Stores.Store Store { get; set; } public Language Language { get; set; } } \ No newline at end of file diff --git a/src/Web/Grand.Web/Features/Models/Orders/GetRecurringPayments.cs b/src/Web/Grand.Web/Features/Models/Orders/GetRecurringPayments.cs new file mode 100644 index 000000000..8f69f38ef --- /dev/null +++ b/src/Web/Grand.Web/Features/Models/Orders/GetRecurringPayments.cs @@ -0,0 +1,14 @@ +using Grand.Domain.Customers; +using Grand.Domain.Localization; +using Grand.Mediator; +using Grand.Web.Models.Orders; + +namespace Grand.Web.Features.Models.Orders; + +public class GetRecurringPayments : IRequest +{ + public Customer Customer { get; set; } + public Domain.Stores.Store Store { get; set; } + public Language Language { get; set; } + public OrderPagingModel Command { get; set; } = new(); +} diff --git a/src/Web/Grand.Web/Views/Order/Details.cshtml b/src/Web/Grand.Web/Views/Order/Details.cshtml index f5089e5b7..ac05b0ded 100644 --- a/src/Web/Grand.Web/Views/Order/Details.cshtml +++ b/src/Web/Grand.Web/Views/Order/Details.cshtml @@ -91,6 +91,30 @@
  • @Loc["Order.OrderStatus"]:@Model.OrderStatus
  • + @if (Model.RecurringCycleNumber > 1) + { +
  • + @string.Format(Loc["Order.RecurringCycle"].Value, Model.RecurringCycleNumber) + @if (Model.InitialOrderNumber > 0) + { + @Loc["Order.RecurringCycle.InitialOrder"] + @if (!string.IsNullOrEmpty(Model.InitialOrderId)) + { + @Model.InitialOrderNumber + } + else + { + @Model.InitialOrderNumber + } + } +
  • + } + @if (Model.ShowRecurringPaymentsLink && !Model.GuestLink) + { +
  • + @Loc["Order.RecurringPayment.Manage"] +
  • + } @if (Model.OrderApprovalReasons.Any()) {
  • diff --git a/src/Web/Grand.Web/Views/RecurringPayment/List.cshtml b/src/Web/Grand.Web/Views/RecurringPayment/List.cshtml new file mode 100644 index 000000000..9a8114e53 --- /dev/null +++ b/src/Web/Grand.Web/Views/RecurringPayment/List.cshtml @@ -0,0 +1,96 @@ +@using Grand.Domain.Orders +@model RecurringPaymentListModel +@inject IPageHeadBuilder pagebuilder +@{ + Layout = "_TwoColumns"; + + //title + pagebuilder.AddTitleParts(Loc["Account.RecurringPayments"]); + + // a double click must not post the cancel twice + const string submitOnce = "if (this.dataset.sent) { return false; } this.dataset.sent = '1'; var f = this; setTimeout(function () { f.querySelectorAll('button[type=submit]').forEach(function (b) { b.disabled = true; }); }, 0);"; + var confirmCancel = System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(Loc["RecurringPayment.Cancel.Confirm"].Value); +} + +@section left +{ + @await Component.InvokeAsync("CustomerNavigation", new { selectedTabId = AccountNavigationEnum.RecurringPayments }) +} + + diff --git a/src/Web/Grand.Web/Views/Shared/Components/CustomerNavigation/Default.cshtml b/src/Web/Grand.Web/Views/Shared/Components/CustomerNavigation/Default.cshtml index 23e6c7a90..3e8852b1d 100644 --- a/src/Web/Grand.Web/Views/Shared/Components/CustomerNavigation/Default.cshtml +++ b/src/Web/Grand.Web/Views/Shared/Components/CustomerNavigation/Default.cshtml @@ -29,6 +29,14 @@
  • } + @if (!Model.HideRecurringPayments) + { +
  • + + @Loc["Account.RecurringPayments"] + +
  • + } @if (!Model.HideCourses) {