Skip to content

Commit 2af0e74

Browse files
Recurring payments: Admin and Store screens, order links and menu (slice 5 of 5) (#1079)
1 parent 709f4b9 commit 2af0e74

27 files changed

Lines changed: 1703 additions & 6 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
using Grand.Business.Core.Queries.Checkout.Orders;
2+
using Grand.Data;
3+
using Grand.Domain;
4+
using Grand.Domain.Customers;
5+
using Grand.Domain.Orders;
6+
using Grand.Mediator;
7+
8+
namespace Grand.Business.Checkout.Queries.Handlers.Orders;
9+
10+
public class GetRecurringPaymentsQueryHandler : IRequestHandler<GetRecurringPaymentsQuery, IPagedList<RecurringPayment>>
11+
{
12+
private readonly IRepository<Customer> _customerRepository;
13+
private readonly IRepository<Order> _orderRepository;
14+
private readonly IRepository<RecurringPayment> _recurringPaymentRepository;
15+
16+
public GetRecurringPaymentsQueryHandler(IRepository<RecurringPayment> recurringPaymentRepository,
17+
IRepository<Customer> customerRepository, IRepository<Order> orderRepository)
18+
{
19+
_recurringPaymentRepository = recurringPaymentRepository;
20+
_customerRepository = customerRepository;
21+
_orderRepository = orderRepository;
22+
}
23+
24+
public async Task<IPagedList<RecurringPayment>> Handle(GetRecurringPaymentsQuery request,
25+
CancellationToken cancellationToken)
26+
{
27+
var query = from p in _recurringPaymentRepository.Table
28+
select p;
29+
30+
if (!string.IsNullOrEmpty(request.StoreId))
31+
query = query.Where(x => x.StoreId == request.StoreId);
32+
33+
if (request.Status.HasValue)
34+
query = query.Where(x => x.Status == request.Status.Value);
35+
36+
//the recurring payment keeps the customer only, and with per-store identity one e-mail may have an account
37+
//in every store
38+
if (!string.IsNullOrWhiteSpace(request.CustomerEmail))
39+
{
40+
var email = request.CustomerEmail.Trim().ToLowerInvariant();
41+
var customerIds = await _customerRepository.ToListAsync(
42+
_customerRepository.Table.Where(c => c.Email == email).Select(c => c.Id), cancellationToken);
43+
query = query.Where(x => customerIds.Contains(x.CustomerId));
44+
}
45+
46+
//the sales employee is on the order, the same one the order list narrows by
47+
if (!string.IsNullOrEmpty(request.SalesEmployeeId))
48+
{
49+
var orderIds = await _orderRepository.ToListAsync(
50+
_orderRepository.Table.Where(o => o.SeId == request.SalesEmployeeId && o.RecurringCycleNumber == 1)
51+
.Select(o => o.Id), cancellationToken);
52+
query = query.Where(x => orderIds.Contains(x.InitialOrderId));
53+
}
54+
55+
query = query.OrderByDescending(x => x.CreatedOnUtc);
56+
57+
return await _recurringPaymentRepository.PagedAsync(query, request.PageIndex, request.PageSize,
58+
cancellationToken);
59+
}
60+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using Grand.Domain;
2+
using Grand.Domain.Orders;
3+
using Grand.Mediator;
4+
5+
namespace Grand.Business.Core.Queries.Checkout.Orders;
6+
7+
/// <summary>
8+
/// Recurring payments for the panels, newest first
9+
/// </summary>
10+
public class GetRecurringPaymentsQuery : IRequest<IPagedList<RecurringPayment>>
11+
{
12+
public string StoreId { get; set; }
13+
14+
/// <summary>Only the recurring payments of the customers with this e-mail, matched exactly.</summary>
15+
public string CustomerEmail { get; set; }
16+
17+
public RecurringPaymentStatus? Status { get; set; }
18+
19+
/// <summary>Only the recurring payments whose initial order belongs to this sales employee.</summary>
20+
public string SalesEmployeeId { get; set; }
21+
22+
public int PageIndex { get; set; }
23+
public int PageSize { get; set; } = int.MaxValue;
24+
}

‎src/Modules/Grand.Module.Installer/Services/InstallationService.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,9 @@ await dbContext.CreateIndex(_serviceProvider.GetRequiredService<IRepository<Recu
944944
await dbContext.CreateIndex(_serviceProvider.GetRequiredService<IRepository<RecurringPayment>>(),
945945
OrderBuilder<RecurringPayment>.Create().Ascending(x => x.CustomerId).Ascending(x => x.StoreId)
946946
.Descending(x => x.CreatedOnUtc), "CustomerId_StoreId_CreatedOnUtc");
947+
//the Admin and Store panels list recurring payments newest first
948+
await dbContext.CreateIndex(_serviceProvider.GetRequiredService<IRepository<RecurringPayment>>(),
949+
OrderBuilder<RecurringPayment>.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc");
947950

948951
//queuemail
949952
await dbContext.CreateIndex(_queuedEmailRepository,

‎src/Modules/Grand.Module.Installer/Utilities/StandardAdminSiteMap.cs‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -242,13 +242,22 @@ public static class StandardAdminSiteMap
242242
DisplayOrder = 3,
243243
IconClass = "bi bi-record-circle"
244244
},
245+
new() {
246+
SystemName = "Recurring payments",
247+
ResourceName = "Admin.Orders.RecurringPayments",
248+
PermissionNames = new List<string> { PermissionSystemName.Orders },
249+
ControllerName = "RecurringPayment",
250+
ActionName = "List",
251+
DisplayOrder = 4,
252+
IconClass = "bi bi-record-circle"
253+
},
245254
new() {
246255
SystemName = "OrderTags",
247256
ResourceName = "Admin.Orders.OrderTags",
248257
PermissionNames = new List<string> { PermissionSystemName.OrderTags },
249258
ControllerName = "OrderTags",
250259
ActionName = "List",
251-
DisplayOrder = 4,
260+
DisplayOrder = 5,
252261
IconClass = "bi bi-record-circle"
253262
},
254263
new() {
@@ -257,7 +266,7 @@ public static class StandardAdminSiteMap
257266
ControllerName = "CheckoutAttribute",
258267
ActionName = "List",
259268
PermissionNames = new List<string> { PermissionSystemName.CheckoutAttributes },
260-
DisplayOrder = 5,
269+
DisplayOrder = 6,
261270
IconClass = "bi bi-record-circle"
262271
},
263272
new() {
@@ -266,7 +275,7 @@ public static class StandardAdminSiteMap
266275
ControllerName = "OrderStatus",
267276
PermissionNames = new List<string> { PermissionSystemName.OrderStatus },
268277
ActionName = "Index",
269-
DisplayOrder = 6,
278+
DisplayOrder = 7,
270279
IconClass = "bi bi-record-circle"
271280
}
272281
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
using Grand.Data;
2+
using Grand.Domain.Orders;
3+
using Grand.Infrastructure.Migrations;
4+
using Microsoft.Extensions.DependencyInjection;
5+
using Microsoft.Extensions.Logging;
6+
7+
namespace Grand.Module.Migration.Migrations._2._5;
8+
9+
public class MigrationRecurringPaymentCreatedOnIndex : IMigration
10+
{
11+
private const string IndexName = "CreatedOnUtc";
12+
13+
public int Priority => 1;
14+
public DbVersion Version => new(2, 5);
15+
public Guid Identity => new("2571362b-ae02-4118-b14f-eb91d15cd91f");
16+
public string Name => "Created on index on Recurring payment 2.5";
17+
18+
public async Task<bool> UpgradeProcess(IServiceProvider serviceProvider)
19+
{
20+
var repository = serviceProvider.GetRequiredService<IRepository<RecurringPayment>>();
21+
var databaseContext = serviceProvider.GetRequiredService<IDatabaseContext>();
22+
var logService = serviceProvider.GetRequiredService<ILogger<MigrationRecurringPaymentCreatedOnIndex>>();
23+
24+
try
25+
{
26+
//the Admin and Store panels list recurring payments newest first
27+
await databaseContext.CreateIndex(repository,
28+
OrderBuilder<RecurringPayment>.Create().Descending(x => x.CreatedOnUtc), IndexName);
29+
}
30+
catch (Exception ex)
31+
{
32+
logService.LogError(ex, "UpgradeProcess - RecurringPaymentCreatedOnIndex (2.5)");
33+
return false;
34+
}
35+
36+
return true;
37+
}
38+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using Grand.Data;
2+
using Grand.Domain.Admin;
3+
using Grand.Domain.Permissions;
4+
using Grand.Infrastructure.Migrations;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Logging;
7+
8+
namespace Grand.Module.Migration.Migrations._2._5;
9+
10+
/// <summary>
11+
/// "Recurring payments" in the menu, under Sales right after Payment transactions, as the installer seeds it.
12+
/// Idempotent: an existing entry is left alone, and a menu without the Sales section gets nothing
13+
/// </summary>
14+
public class MigrationRecurringPaymentMenu : IMigration
15+
{
16+
private const string NodeName = "Recurring payments";
17+
18+
public int Priority => 3;
19+
public DbVersion Version => new(2, 5);
20+
public Guid Identity => new("5b0e7d1a-3c4f-4a8e-9f21-6d7c2e8b4a90");
21+
public string Name => "Recurring payments in the admin menu 2.5";
22+
23+
public async Task<bool> UpgradeProcess(IServiceProvider serviceProvider)
24+
{
25+
var repository = serviceProvider.GetRequiredService<IRepository<AdminSiteMap>>();
26+
var logService = serviceProvider.GetRequiredService<ILogger<MigrationRecurringPaymentMenu>>();
27+
28+
try
29+
{
30+
var sales = await repository.FirstOrDefaultAsync(repository.Table.Where(x => x.SystemName == "Sales"));
31+
if (sales == null || sales.ChildNodes.Any(x => x.SystemName == NodeName))
32+
return true;
33+
34+
//right after Payment transactions, the entries below it move down by one
35+
var paymentTransactions = sales.ChildNodes.FirstOrDefault(x => x.SystemName == "Payment transaction");
36+
var displayOrder = paymentTransactions != null
37+
? paymentTransactions.DisplayOrder + 1
38+
: sales.ChildNodes.Count == 0 ? 0 : sales.ChildNodes.Max(x => x.DisplayOrder) + 1;
39+
foreach (var node in sales.ChildNodes.Where(x => x.DisplayOrder >= displayOrder))
40+
node.DisplayOrder++;
41+
42+
sales.ChildNodes.Add(new AdminSiteMap {
43+
SystemName = NodeName,
44+
ResourceName = "Admin.Orders.RecurringPayments",
45+
PermissionNames = new List<string> { PermissionSystemName.Orders },
46+
ControllerName = "RecurringPayment",
47+
ActionName = "List",
48+
DisplayOrder = displayOrder,
49+
IconClass = "bi bi-record-circle"
50+
});
51+
await repository.UpdateAsync(sales);
52+
}
53+
catch (Exception ex)
54+
{
55+
logService.LogError(ex, "UpgradeProcess - RecurringPaymentMenu (2.5)");
56+
return false;
57+
}
58+
59+
return true;
60+
}
61+
}
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
using Grand.Business.Checkout.Queries.Handlers.Orders;
2+
using Grand.Business.Core.Queries.Checkout.Orders;
3+
using Grand.Data.Tests.MongoDb;
4+
using Grand.Domain.Customers;
5+
using Grand.Domain.Orders;
6+
using Microsoft.VisualStudio.TestTools.UnitTesting;
7+
8+
namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders;
9+
10+
[TestClass]
11+
public class GetRecurringPaymentsQueryHandlerTests
12+
{
13+
private MongoDBRepositoryTest<Customer> _customerRepository;
14+
private GetRecurringPaymentsQueryHandler _handler;
15+
private MongoDBRepositoryTest<Order> _orderRepository;
16+
private MongoDBRepositoryTest<RecurringPayment> _repository;
17+
18+
[TestInitialize]
19+
public void Init()
20+
{
21+
_repository = new MongoDBRepositoryTest<RecurringPayment>();
22+
_customerRepository = new MongoDBRepositoryTest<Customer>();
23+
_orderRepository = new MongoDBRepositoryTest<Order>();
24+
_handler = new GetRecurringPaymentsQueryHandler(_repository, _customerRepository, _orderRepository);
25+
}
26+
27+
[TestMethod]
28+
public async Task Handle_ByStore_ReturnsOnlyThatStore()
29+
{
30+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", StoreId = "s1" });
31+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp2", StoreId = "s2" });
32+
33+
var result = await _handler.Handle(new GetRecurringPaymentsQuery { StoreId = "s1" }, CancellationToken.None);
34+
35+
Assert.AreEqual(1, result.Count);
36+
Assert.AreEqual("rp1", result[0].Id);
37+
}
38+
39+
[TestMethod]
40+
public async Task Handle_ByStatus_ReturnsOnlyThatStatus()
41+
{
42+
await _repository.Collection.InsertOneAsync(new RecurringPayment
43+
{ Id = "rp1", Status = RecurringPaymentStatus.PastDue });
44+
await _repository.Collection.InsertOneAsync(new RecurringPayment
45+
{ Id = "rp2", Status = RecurringPaymentStatus.Active });
46+
47+
var result = await _handler.Handle(
48+
new GetRecurringPaymentsQuery { Status = RecurringPaymentStatus.PastDue }, CancellationToken.None);
49+
50+
Assert.AreEqual(1, result.Count);
51+
Assert.AreEqual("rp1", result[0].Id);
52+
}
53+
54+
[TestMethod]
55+
public async Task Handle_ByCustomerEmail_MatchesEveryAccountWithThatEmailExactly()
56+
{
57+
await _customerRepository.Collection.InsertOneAsync(new Customer { Id = "c1", Email = "jan@example.com", StoreId = "s1" });
58+
await _customerRepository.Collection.InsertOneAsync(new Customer { Id = "c2", Email = "jan@example.com", StoreId = "s2" });
59+
await _customerRepository.Collection.InsertOneAsync(new Customer { Id = "c3", Email = "xjan@example.com" });
60+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", CustomerId = "c1" });
61+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp2", CustomerId = "c2" });
62+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp3", CustomerId = "c3" });
63+
64+
var result = await _handler.Handle(
65+
new GetRecurringPaymentsQuery { CustomerEmail = " Jan@Example.com " }, CancellationToken.None);
66+
67+
CollectionAssert.AreEquivalent(new[] { "rp1", "rp2" }, result.Select(x => x.Id).ToArray());
68+
}
69+
70+
[TestMethod]
71+
public async Task Handle_ByUnknownCustomerEmail_ReturnsNothing()
72+
{
73+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", CustomerId = "c1" });
74+
75+
var result = await _handler.Handle(
76+
new GetRecurringPaymentsQuery { CustomerEmail = "nobody@example.com" }, CancellationToken.None);
77+
78+
Assert.AreEqual(0, result.Count);
79+
}
80+
81+
[TestMethod]
82+
public async Task Handle_BySalesEmployee_ReturnsOnlyPaymentsOfTheirInitialOrders()
83+
{
84+
await _orderRepository.Collection.InsertOneAsync(new Order { Id = "o1", SeId = "se1", RecurringCycleNumber = 1 });
85+
await _orderRepository.Collection.InsertOneAsync(new Order { Id = "o2", SeId = "se2", RecurringCycleNumber = 1 });
86+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp1", InitialOrderId = "o1" });
87+
await _repository.Collection.InsertOneAsync(new RecurringPayment { Id = "rp2", InitialOrderId = "o2" });
88+
89+
var result = await _handler.Handle(
90+
new GetRecurringPaymentsQuery { SalesEmployeeId = "se1" }, CancellationToken.None);
91+
92+
Assert.AreEqual(1, result.Count);
93+
Assert.AreEqual("rp1", result[0].Id);
94+
}
95+
96+
[TestMethod]
97+
public async Task Handle_ReturnsNewestFirst()
98+
{
99+
await _repository.Collection.InsertOneAsync(new RecurringPayment
100+
{ Id = "old", CreatedOnUtc = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc) });
101+
await _repository.Collection.InsertOneAsync(new RecurringPayment
102+
{ Id = "new", CreatedOnUtc = new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc) });
103+
104+
var result = await _handler.Handle(new GetRecurringPaymentsQuery(), CancellationToken.None);
105+
106+
Assert.AreEqual("new", result[0].Id);
107+
Assert.AreEqual("old", result[1].Id);
108+
}
109+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using Grand.Data;
2+
using Grand.Data.Tests.LiteDb;
3+
using Grand.Domain.Orders;
4+
using Grand.Module.Migration.Migrations._2._5;
5+
using Microsoft.Extensions.DependencyInjection;
6+
using Microsoft.Extensions.Logging;
7+
using Microsoft.Extensions.Logging.Abstractions;
8+
using Microsoft.VisualStudio.TestTools.UnitTesting;
9+
using Moq;
10+
11+
namespace Grand.Modules.Tests.Services.Migrations;
12+
13+
[TestClass]
14+
public class MigrationRecurringPaymentCreatedOnIndexTests
15+
{
16+
private readonly Mock<IDatabaseContext> _context = new();
17+
private readonly LiteDBRepositoryMock<RecurringPayment> _repository = new();
18+
private IServiceProvider _serviceProvider;
19+
20+
[TestInitialize]
21+
public void Init()
22+
{
23+
var services = new ServiceCollection();
24+
services.AddSingleton<IRepository<RecurringPayment>>(_repository);
25+
services.AddSingleton(_context.Object);
26+
services.AddSingleton<ILogger<MigrationRecurringPaymentCreatedOnIndex>>(
27+
NullLogger<MigrationRecurringPaymentCreatedOnIndex>.Instance);
28+
_serviceProvider = services.BuildServiceProvider();
29+
}
30+
31+
[TestMethod]
32+
public async Task UpgradeProcess_CreatesCreatedOnIndex()
33+
{
34+
Assert.IsTrue(await new MigrationRecurringPaymentCreatedOnIndex().UpgradeProcess(_serviceProvider));
35+
36+
_context.Verify(x => x.CreateIndex(_repository, It.IsAny<OrderBuilder<RecurringPayment>>(), "CreatedOnUtc",
37+
false), Times.Once);
38+
}
39+
40+
[TestMethod]
41+
public async Task UpgradeProcess_IndexFails_ReturnsFalse()
42+
{
43+
_context.Setup(x => x.CreateIndex(_repository, It.IsAny<OrderBuilder<RecurringPayment>>(), "CreatedOnUtc",
44+
false)).ThrowsAsync(new InvalidOperationException());
45+
46+
Assert.IsFalse(await new MigrationRecurringPaymentCreatedOnIndex().UpgradeProcess(_serviceProvider));
47+
}
48+
}

0 commit comments

Comments
 (0)