Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<GetRecurringPaymentsQuery, IPagedList<RecurringPayment>>
{
private readonly IRepository<Customer> _customerRepository;
private readonly IRepository<Order> _orderRepository;
private readonly IRepository<RecurringPayment> _recurringPaymentRepository;

public GetRecurringPaymentsQueryHandler(IRepository<RecurringPayment> recurringPaymentRepository,
IRepository<Customer> customerRepository, IRepository<Order> orderRepository)
{
_recurringPaymentRepository = recurringPaymentRepository;
_customerRepository = customerRepository;
_orderRepository = orderRepository;
}

public async Task<IPagedList<RecurringPayment>> 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);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Grand.Domain;
using Grand.Domain.Orders;
using Grand.Mediator;

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

/// <summary>
/// Recurring payments for the panels, newest first
/// </summary>
public class GetRecurringPaymentsQuery : IRequest<IPagedList<RecurringPayment>>
{
public string StoreId { get; set; }

/// <summary>Only the recurring payments of the customers with this e-mail, matched exactly.</summary>
public string CustomerEmail { get; set; }

public RecurringPaymentStatus? Status { get; set; }

/// <summary>Only the recurring payments whose initial order belongs to this sales employee.</summary>
public string SalesEmployeeId { get; set; }

public int PageIndex { get; set; }
public int PageSize { get; set; } = int.MaxValue;
}
Original file line number Diff line number Diff line change
Expand Up @@ -944,6 +944,9 @@ await dbContext.CreateIndex(_serviceProvider.GetRequiredService<IRepository<Recu
await dbContext.CreateIndex(_serviceProvider.GetRequiredService<IRepository<RecurringPayment>>(),
OrderBuilder<RecurringPayment>.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<IRepository<RecurringPayment>>(),
OrderBuilder<RecurringPayment>.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc");

//queuemail
await dbContext.CreateIndex(_queuedEmailRepository,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> { PermissionSystemName.Orders },
ControllerName = "RecurringPayment",
ActionName = "List",
DisplayOrder = 4,
IconClass = "bi bi-record-circle"
},
new() {
SystemName = "OrderTags",
ResourceName = "Admin.Orders.OrderTags",
PermissionNames = new List<string> { PermissionSystemName.OrderTags },
ControllerName = "OrderTags",
ActionName = "List",
DisplayOrder = 4,
DisplayOrder = 5,
IconClass = "bi bi-record-circle"
},
new() {
Expand All @@ -257,7 +266,7 @@ public static class StandardAdminSiteMap
ControllerName = "CheckoutAttribute",
ActionName = "List",
PermissionNames = new List<string> { PermissionSystemName.CheckoutAttributes },
DisplayOrder = 5,
DisplayOrder = 6,
IconClass = "bi bi-record-circle"
},
new() {
Expand All @@ -266,7 +275,7 @@ public static class StandardAdminSiteMap
ControllerName = "OrderStatus",
PermissionNames = new List<string> { PermissionSystemName.OrderStatus },
ActionName = "Index",
DisplayOrder = 6,
DisplayOrder = 7,
IconClass = "bi bi-record-circle"
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<bool> UpgradeProcess(IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<RecurringPayment>>();
var databaseContext = serviceProvider.GetRequiredService<IDatabaseContext>();
var logService = serviceProvider.GetRequiredService<ILogger<MigrationRecurringPaymentCreatedOnIndex>>();

try
{
//the Admin and Store panels list recurring payments newest first
await databaseContext.CreateIndex(repository,
OrderBuilder<RecurringPayment>.Create().Descending(x => x.CreatedOnUtc), IndexName);
}
catch (Exception ex)
{
logService.LogError(ex, "UpgradeProcess - RecurringPaymentCreatedOnIndex (2.5)");
return false;
}
Comment on lines +30 to +34

return true;
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// "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
/// </summary>
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<bool> UpgradeProcess(IServiceProvider serviceProvider)
{
var repository = serviceProvider.GetRequiredService<IRepository<AdminSiteMap>>();
var logService = serviceProvider.GetRequiredService<ILogger<MigrationRecurringPaymentMenu>>();

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<string> { 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;
}
Comment on lines +53 to +57

return true;
}
}
Original file line number Diff line number Diff line change
@@ -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<Customer> _customerRepository;
private GetRecurringPaymentsQueryHandler _handler;
private MongoDBRepositoryTest<Order> _orderRepository;
private MongoDBRepositoryTest<RecurringPayment> _repository;

[TestInitialize]
public void Init()
{
_repository = new MongoDBRepositoryTest<RecurringPayment>();
_customerRepository = new MongoDBRepositoryTest<Customer>();
_orderRepository = new MongoDBRepositoryTest<Order>();
_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);
}
}
Original file line number Diff line number Diff line change
@@ -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<IDatabaseContext> _context = new();
private readonly LiteDBRepositoryMock<RecurringPayment> _repository = new();
private IServiceProvider _serviceProvider;

[TestInitialize]
public void Init()
{
var services = new ServiceCollection();
services.AddSingleton<IRepository<RecurringPayment>>(_repository);
services.AddSingleton(_context.Object);
services.AddSingleton<ILogger<MigrationRecurringPaymentCreatedOnIndex>>(
NullLogger<MigrationRecurringPaymentCreatedOnIndex>.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<OrderBuilder<RecurringPayment>>(), "CreatedOnUtc",
false), Times.Once);
}

[TestMethod]
public async Task UpgradeProcess_IndexFails_ReturnsFalse()
{
_context.Setup(x => x.CreateIndex(_repository, It.IsAny<OrderBuilder<RecurringPayment>>(), "CreatedOnUtc",
false)).ThrowsAsync(new InvalidOperationException());

Assert.IsFalse(await new MigrationRecurringPaymentCreatedOnIndex().UpgradeProcess(_serviceProvider));
}
}
Loading
Loading