From 9187322f6f5d59aeff5565c1ad5f1e0dda2864d9 Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 17:21:34 +0100 Subject: [PATCH 1/7] Find payment transactions by payment method, PO number and overdue The PO number and the due date live on the order, so the handler finds the matching orders first and keeps the payments of those orders; overdue is the same rule as the order list. --- .../GetPaymentTransactionQueryHandler.cs | 45 ++++++++++- .../Orders/GetPaymentTransactionQuery.cs | 8 ++ .../GetPaymentTransactionQueryHandlerTests.cs | 74 ++++++++++++++++++- 3 files changed, 124 insertions(+), 3 deletions(-) diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs index 16ea065e1..325300e8f 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs @@ -1,6 +1,8 @@ -using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Data; using Grand.Domain; +using Grand.Domain.Orders; using Grand.Domain.Payments; using Grand.Mediator; @@ -9,11 +11,14 @@ namespace Grand.Business.Checkout.Queries.Handlers.Orders; public class GetPaymentTransactionQueryHandler : IRequestHandler> { + private readonly IRepository _orderRepository; private readonly IRepository _paymentTransactionRepository; - public GetPaymentTransactionQueryHandler(IRepository paymentTransactionRepository) + public GetPaymentTransactionQueryHandler(IRepository paymentTransactionRepository, + IRepository orderRepository) { _paymentTransactionRepository = paymentTransactionRepository; + _orderRepository = orderRepository; } public async Task> Handle(GetPaymentTransactionQuery request, @@ -43,8 +48,44 @@ public async Task> Handle(GetPaymentTransactionQu if (!request.IncludeTemp) query = query.Where(rr => !rr.Temp); + if (!string.IsNullOrEmpty(request.PaymentMethodSystemName)) + query = query.Where(rr => rr.PaymentMethodSystemName == request.PaymentMethodSystemName); + + if (!string.IsNullOrWhiteSpace(request.PurchaseOrderNumber) || request.OverdueOnly) + { + var orderGuids = await MatchingOrderGuids(request, cancellationToken); + query = query.Where(rr => orderGuids.Contains(rr.OrderGuid)); + } + query = query.OrderByDescending(rr => rr.CreatedOnUtc); return await _paymentTransactionRepository.PagedAsync(query, request.PageIndex, request.PageSize, cancellationToken); } + + /// + /// The purchase order number and the due date live on the order, so the orders matching them are found first + /// + private Task> MatchingOrderGuids(GetPaymentTransactionQuery request, + CancellationToken cancellationToken) + { + var orders = _orderRepository.Table.Where(o => !o.Deleted); + + if (!string.IsNullOrEmpty(request.StoreId)) + orders = orders.Where(o => o.StoreId == request.StoreId); + + if (!string.IsNullOrWhiteSpace(request.PurchaseOrderNumber)) + { + var purchaseOrderNumber = request.PurchaseOrderNumber.Trim(); + orders = orders.Where(o => o.PurchaseOrderNumber == purchaseOrderNumber); + } + + //the same rule as PaymentExtensions.IsPaymentOverdue + if (request.OverdueOnly) + { + var today = DateTime.UtcNow.Date; + orders = orders.Where(PaymentExtensions.UnpaidOnCredit).Where(o => o.PaymentDueDateUtc < today); + } + + return _orderRepository.ToListAsync(orders.Select(o => o.OrderGuid), cancellationToken); + } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs index 3ff313f7b..fc111d55e 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs @@ -18,4 +18,12 @@ public class GetPaymentTransactionQuery : IRequestFalse leaves out transactions of a checkout that never got a payment through: still in progress, /// failed or abandoned. public bool IncludeTemp { get; set; } = true; + + public string PaymentMethodSystemName { get; set; } + + /// Only the payments of orders carrying this purchase order number, matched exactly. + public string PurchaseOrderNumber { get; set; } + + /// Only the payments of orders bought on credit and past their due date. + public bool OverdueOnly { get; set; } } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetPaymentTransactionQueryHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetPaymentTransactionQueryHandlerTests.cs index bb7cd494b..b8a319c8a 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetPaymentTransactionQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/GetPaymentTransactionQueryHandlerTests.cs @@ -1,6 +1,7 @@ using Grand.Business.Checkout.Queries.Handlers.Orders; using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Data.Tests.MongoDb; +using Grand.Domain.Orders; using Grand.Domain.Payments; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -10,13 +11,15 @@ namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders; public class GetPaymentTransactionQueryHandlerTests { private GetPaymentTransactionQueryHandler _handler; + private MongoDBRepositoryTest _orderRepository; private MongoDBRepositoryTest _repository; [TestInitialize] public void Init() { _repository = new MongoDBRepositoryTest(); - _handler = new GetPaymentTransactionQueryHandler(_repository); + _orderRepository = new MongoDBRepositoryTest(); + _handler = new GetPaymentTransactionQueryHandler(_repository, _orderRepository); } [TestMethod] @@ -41,4 +44,73 @@ public async Task Handle_ByDefault_IncludesAbandonedCheckouts() Assert.AreEqual(2, result.Count); } + + [TestMethod] + public async Task Handle_ByPaymentMethod_ReturnsOnlyThatMethod() + { + await _repository.Collection.InsertOneAsync(new PaymentTransaction { PaymentMethodSystemName = "Payments.OnAccount" }); + await _repository.Collection.InsertOneAsync(new PaymentTransaction { PaymentMethodSystemName = "Payments.CashOnDelivery" }); + + var result = await _handler.Handle( + new GetPaymentTransactionQuery { PaymentMethodSystemName = "Payments.OnAccount" }, CancellationToken.None); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual("Payments.OnAccount", result[0].PaymentMethodSystemName); + } + + [TestMethod] + public async Task Handle_ByPurchaseOrderNumber_MatchesTrimmedOrderInStore() + { + var inStore = Guid.NewGuid(); + var otherStore = Guid.NewGuid(); + await _orderRepository.Collection.InsertOneAsync(new Order { OrderGuid = inStore, StoreId = "s1", PurchaseOrderNumber = "PO-7" }); + await _orderRepository.Collection.InsertOneAsync(new Order { OrderGuid = otherStore, StoreId = "s2", PurchaseOrderNumber = "PO-7" }); + await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderGuid = inStore, StoreId = "s1" }); + await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderGuid = otherStore, StoreId = "s2" }); + + var result = await _handler.Handle( + new GetPaymentTransactionQuery { StoreId = "s1", PurchaseOrderNumber = " PO-7 " }, CancellationToken.None); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual(inStore, result[0].OrderGuid); + } + + [TestMethod] + public async Task Handle_OverdueOnly_LeavesOutDueTodayAndPaid() + { + var today = DateTime.UtcNow.Date; + var overdue = Guid.NewGuid(); + var dueToday = Guid.NewGuid(); + var paid = Guid.NewGuid(); + await _orderRepository.Collection.InsertOneAsync(new Order { + OrderGuid = overdue, PaymentDueDateUtc = today.AddDays(-1), PaymentStatusId = PaymentStatus.Pending, + OrderStatusId = (int)OrderStatusSystem.Pending + }); + await _orderRepository.Collection.InsertOneAsync(new Order { + OrderGuid = dueToday, PaymentDueDateUtc = today, PaymentStatusId = PaymentStatus.Pending, + OrderStatusId = (int)OrderStatusSystem.Pending + }); + await _orderRepository.Collection.InsertOneAsync(new Order { + OrderGuid = paid, PaymentDueDateUtc = today.AddDays(-1), PaymentStatusId = PaymentStatus.Paid, + OrderStatusId = (int)OrderStatusSystem.Pending + }); + foreach (var orderGuid in new[] { overdue, dueToday, paid }) + await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderGuid = orderGuid }); + + var result = await _handler.Handle(new GetPaymentTransactionQuery { OverdueOnly = true }, CancellationToken.None); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual(overdue, result[0].OrderGuid); + } + + [TestMethod] + public async Task Handle_OrderCriteriaMatchingNoOrder_ReturnsNothing() + { + await _repository.Collection.InsertOneAsync(new PaymentTransaction { OrderGuid = Guid.NewGuid() }); + + var result = await _handler.Handle(new GetPaymentTransactionQuery { PurchaseOrderNumber = "NONE" }, + CancellationToken.None); + + Assert.AreEqual(0, result.Count); + } } From 9f699789ac93cba896265cd7ade75d71b4ce1b03 Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 17:28:45 +0100 Subject: [PATCH 2/7] Filter the payment transaction list by method, PO number and overdue An order number that finds no order now finds no payment, instead of listing every payment. --- .../BasePaymentTransactionControllerTests.cs | 64 +++++++++++++++++-- .../PaymentTransactionController.cs | 6 +- .../BasePaymentTransactionController.cs | 29 ++++++--- .../Orders/PaymentTransactionListModel.cs | 10 +++ .../PaymentTransaction/List.cshtml | 6 ++ .../PaymentTransactionController.cs | 6 +- 6 files changed, 104 insertions(+), 17 deletions(-) diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs index 5b5598e08..2e2e77b1c 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs @@ -38,13 +38,15 @@ private class TestPaymentTransactionController( IEnumTranslationService enumTranslationService, IAdminDataScope scope, IContextAccessor contextAccessor, - IPaymentTransactionHistoryService paymentTransactionHistoryService) + IPaymentTransactionHistoryService paymentTransactionHistoryService, + IPaymentService paymentService) : BasePaymentTransactionController(paymentTransactionService, orderService, translationService, dateTimeService, mediator, enumTranslationService, scope, contextAccessor, - paymentTransactionHistoryService); + paymentTransactionHistoryService, paymentService); private TestPaymentTransactionController _controller; private Mock _historyMock; + private Mock _paymentServiceMock; private Mock _paymentTransactionServiceMock; private Mock _orderServiceMock; private Mock> _scopeMock; @@ -88,10 +90,18 @@ public void Setup() _historyMock = new Mock(); _historyMock.Setup(h => h.GetEntries(It.IsAny())).ReturnsAsync(new List()); + var onAccount = new Mock(); + onAccount.Setup(p => p.SystemName).Returns("Payments.OnAccount"); + onAccount.Setup(p => p.FriendlyName).Returns("On account"); + _paymentServiceMock = new Mock(); + _paymentServiceMock + .Setup(p => p.LoadAllPaymentMethods(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new List { onAccount.Object }); + _controller = new TestPaymentTransactionController( _paymentTransactionServiceMock.Object, _orderServiceMock.Object, _translationServiceMock.Object, dateTimeServiceMock.Object, _mediatorMock.Object, enumTranslationServiceMock.Object, _scopeMock.Object, - contextAccessorMock.Object, _historyMock.Object); + contextAccessorMock.Object, _historyMock.Object, _paymentServiceMock.Object); // Error()/Success() (used by this task's popup and Delete actions) reach into // HttpContext.RequestServices for ILoggerFactory and into TempData - wire up the same @@ -110,9 +120,9 @@ public void Setup() } [TestMethod] - public void List_ReturnsViewWithPreparedModel() + public async Task List_ReturnsViewWithPreparedModel() { - var result = _controller.List() as ViewResult; + var result = await _controller.List() as ViewResult; Assert.IsNotNull(result); Assert.IsInstanceOfType(result!.Model, typeof(PaymentTransactionListModel)); @@ -130,6 +140,50 @@ public async Task List_Post_AdminScope_DoesNotForceStoreId() Assert.IsNull(model.StoreId); } + [TestMethod] + public async Task List_ListsPaymentMethodsAfterAll() + { + var model = (PaymentTransactionListModel)((ViewResult)await _controller.List()).Model; + + Assert.AreEqual(2, model.AvailablePaymentMethods.Count); + Assert.AreEqual(" ", model.AvailablePaymentMethods[0].Value); + Assert.AreEqual("Payments.OnAccount", model.AvailablePaymentMethods[1].Value); + Assert.AreEqual("On account", model.AvailablePaymentMethods[1].Text); + } + + [TestMethod] + public async Task List_Post_PassesTheNewFilters() + { + SetupSearch(); + + await _controller.List(new DataSourceRequest { Page = 1, PageSize = int.MaxValue }, + new PaymentTransactionListModel { + PaymentMethodSystemName = "Payments.OnAccount", PurchaseOrderNumber = "PO-7", OverdueOnly = true + }); + + _mediatorMock.Verify(m => m.Send(It.Is(q => + q.PaymentMethodSystemName == "Payments.OnAccount" && q.PurchaseOrderNumber == "PO-7" && q.OverdueOnly), + It.IsAny()), Times.Once); + } + + [TestMethod] + public async Task List_Post_UnknownOrderNumber_ReturnsEmptyWithoutSearching() + { + SetupSearch(); + _orderServiceMock.Setup(s => s.GetOrderByNumber(999)).ReturnsAsync((Order)null); + var command = new DataSourceRequest { Page = 1, PageSize = int.MaxValue }; + + foreach (var orderNumber in new[] { "999", "abc" }) + { + var result = await _controller.List(command, new PaymentTransactionListModel { OrderNumber = orderNumber }); + + Assert.AreEqual(0, ((DataSourceResult)((JsonResult)result).Value!).Total); + } + + _mediatorMock.Verify(m => m.Send(It.IsAny(), It.IsAny()), + Times.Never); + } + private void SetupSearch() { _mediatorMock diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs index 2438113f6..aa117779a 100644 --- a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs +++ b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs @@ -26,6 +26,8 @@ public class PaymentTransactionController( IEnumTranslationService enumTranslationService, IAdminDataScope scope, IContextAccessor contextAccessor, - IPaymentTransactionHistoryService paymentTransactionHistoryService) + IPaymentTransactionHistoryService paymentTransactionHistoryService, + IPaymentService paymentService) : BasePaymentTransactionController(paymentTransactionService, orderService, translationService, - dateTimeService, mediator, enumTranslationService, scope, contextAccessor, paymentTransactionHistoryService); + dateTimeService, mediator, enumTranslationService, scope, contextAccessor, paymentTransactionHistoryService, + paymentService); diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs index 298e04f15..16506d765 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs @@ -33,7 +33,8 @@ public abstract class BasePaymentTransactionController( IEnumTranslationService enumTranslationService, IAdminDataScope scope, IContextAccessor contextAccessor, - IPaymentTransactionHistoryService paymentTransactionHistoryService) + IPaymentTransactionHistoryService paymentTransactionHistoryService, + IPaymentService paymentService) : BaseController { // Exposed for host-specific concrete subclasses (none currently need extra actions, unlike @@ -48,6 +49,7 @@ public abstract class BasePaymentTransactionController( protected IAdminDataScope Scope => scope; protected IContextAccessor ContextAccessor => contextAccessor; protected IPaymentTransactionHistoryService PaymentTransactionHistoryService => paymentTransactionHistoryService; + protected IPaymentService PaymentService => paymentService; /// Who the payment operation history and order notes name for an operation made here private string StaffName => contextAccessor.WorkContext.CurrentCustomer.StatusChangedBy(); @@ -69,7 +71,7 @@ public abstract class BasePaymentTransactionController( public IActionResult Index() => RedirectToAction("List"); - public IActionResult List() + public async Task List() { var model = new PaymentTransactionListModel { PaymentTransactionStatus = enumTranslationService.ToSelectList(TransactionStatus.Pending, false) @@ -77,6 +79,11 @@ public IActionResult List() }; model.PaymentTransactionStatus.Insert(0, new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "-1", Selected = true }); + + model.AvailablePaymentMethods.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " }); + foreach (var pm in await paymentService.LoadAllPaymentMethods()) + model.AvailablePaymentMethods.Add(new SelectListItem { Text = pm.FriendlyName, Value = pm.SystemName }); + return View(model); } @@ -104,12 +111,15 @@ public async Task List(DataSourceRequest command, PaymentTransact Guid? orderGuid = null; if (!string.IsNullOrEmpty(model.OrderNumber)) - if (int.TryParse(model.OrderNumber, out var ordernumber)) - { - var order = await orderService.GetOrderByNumber(ordernumber); - if (order != null) - orderGuid = order.OrderGuid; - } + { + var order = int.TryParse(model.OrderNumber, out var ordernumber) + ? await orderService.GetOrderByNumber(ordernumber) + : null; + //an order number that finds no order finds no payment, rather than every payment + if (order == null) + return Json(new DataSourceResult { Data = new List(), Total = 0 }); + orderGuid = order.OrderGuid; + } var paymentTransactions = await mediator.Send(new GetPaymentTransactionQuery { CustomerEmail = model.SearchCustomerEmail, @@ -118,6 +128,9 @@ public async Task List(DataSourceRequest command, PaymentTransact CreatedToUtc = endDateValue, StoreId = model.StoreId, OrderGuid = orderGuid, + PaymentMethodSystemName = model.PaymentMethodSystemName, + PurchaseOrderNumber = model.PurchaseOrderNumber, + OverdueOnly = model.OverdueOnly, PageIndex = command.Page - 1, PageSize = command.PageSize, //the payment of an order searched for by its number is shown whatever state its checkout left it in diff --git a/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionListModel.cs b/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionListModel.cs index d82584bc3..90c46d914 100644 --- a/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionListModel.cs +++ b/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionListModel.cs @@ -24,10 +24,20 @@ public class PaymentTransactionListModel : BaseModel [UIHint("DateNullable")] public DateTime? EndDate { get; set; } + [GrandResourceDisplayName("Admin.Orders.List.PaymentMethod")] + public string PaymentMethodSystemName { get; set; } + + [GrandResourceDisplayName("Admin.Orders.List.PurchaseOrderNumber")] + public string PurchaseOrderNumber { get; set; } + + [GrandResourceDisplayName("Admin.Orders.PaymentTransaction.List.OverdueOnly")] + public bool OverdueOnly { get; set; } + [GrandResourceDisplayName("Admin.Orders.PaymentTransaction.List.ShowAbandoned")] public bool ShowAbandoned { get; set; } public string StoreId { get; set; } public IList PaymentTransactionStatus { get; set; } = new List(); + public IList AvailablePaymentMethods { get; set; } = new List(); } \ No newline at end of file diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/List.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/List.cshtml index 32686f78c..aa8d96d9c 100644 --- a/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/List.cshtml +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/List.cshtml @@ -26,8 +26,11 @@ + + + @@ -79,6 +82,9 @@ OrderNumber: $('#@Html.IdFor(model => model.OrderNumber)').val(), StartDate: $('#@Html.IdFor(model => model.StartDate)').val(), EndDate: $('#@Html.IdFor(model => model.EndDate)').val(), + PaymentMethodSystemName: $('#@Html.IdFor(model => model.PaymentMethodSystemName)').val(), + PurchaseOrderNumber: $('#@Html.IdFor(model => model.PurchaseOrderNumber)').val(), + OverdueOnly: $('#@Html.IdFor(model => model.OverdueOnly)').is(':checked'), ShowAbandoned: $('#@Html.IdFor(model => model.ShowAbandoned)').is(':checked') }; addAntiForgeryToken(data); diff --git a/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs b/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs index bae57cb54..939653e71 100644 --- a/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs +++ b/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs @@ -26,6 +26,8 @@ public class PaymentTransactionController( IEnumTranslationService enumTranslationService, IAdminDataScope scope, IContextAccessor contextAccessor, - IPaymentTransactionHistoryService paymentTransactionHistoryService) + IPaymentTransactionHistoryService paymentTransactionHistoryService, + IPaymentService paymentService) : BasePaymentTransactionController(paymentTransactionService, orderService, translationService, - dateTimeService, mediator, enumTranslationService, scope, contextAccessor, paymentTransactionHistoryService); + dateTimeService, mediator, enumTranslationService, scope, contextAccessor, paymentTransactionHistoryService, + paymentService); From 77b03b1ede8c3cd0de134b2c328ecad45f88ad45 Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 17:41:54 +0100 Subject: [PATCH 3/7] Show the gateway data, amounts and order on the payment transaction The authorization code and result, the capture id and result, the currency rate and the store were in the view but never filled. The screen now also shows the payment errors, the gateway's custom values, what is left to pay and to refund, an abandoned-checkout chip, the last change, and an order card with its status, payment status, total and billing name. --- .../BasePaymentTransactionControllerTests.cs | 109 ++++++++++++- .../PaymentTransactionController.cs | 7 +- .../BasePaymentTransactionController.cs | 44 +++++- .../Models/Orders/PaymentTransactionModel.cs | 43 +++++ .../PaymentTransaction/Partials/Update.cshtml | 148 +++++++++++++++--- .../PaymentTransactionController.cs | 7 +- 6 files changed, 326 insertions(+), 32 deletions(-) diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs index 2e2e77b1c..9491e0c52 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs @@ -2,11 +2,14 @@ using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain; using Grand.Domain.Orders; using Grand.Domain.Payments; +using Grand.Domain.Stores; using Grand.Infrastructure; using Grand.Mediator; using Grand.SharedKernel; @@ -39,14 +42,17 @@ private class TestPaymentTransactionController( IAdminDataScope scope, IContextAccessor contextAccessor, IPaymentTransactionHistoryService paymentTransactionHistoryService, - IPaymentService paymentService) + IPaymentService paymentService, + IStoreService storeService, + IOrderStatusService orderStatusService) : BasePaymentTransactionController(paymentTransactionService, orderService, translationService, dateTimeService, mediator, enumTranslationService, scope, contextAccessor, - paymentTransactionHistoryService, paymentService); + paymentTransactionHistoryService, paymentService, storeService, orderStatusService); private TestPaymentTransactionController _controller; private Mock _historyMock; private Mock _paymentServiceMock; + private Mock _storeServiceMock; private Mock _paymentTransactionServiceMock; private Mock _orderServiceMock; private Mock> _scopeMock; @@ -98,10 +104,17 @@ public void Setup() .Setup(p => p.LoadAllPaymentMethods(It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(new List { onAccount.Object }); + _paymentServiceMock.Setup(p => p.LoadPaymentMethodBySystemName("Payments.OnAccount")).Returns(onAccount.Object); + _storeServiceMock = new Mock(); + _storeServiceMock.Setup(s => s.GetStoreById("s1")).ReturnsAsync(new Store { Id = "s1", Name = "Main" }); + var orderStatusServiceMock = new Mock(); + orderStatusServiceMock.Setup(s => s.GetByStatusId(10)).ReturnsAsync(new OrderStatus { StatusId = 10, Name = "Pending" }); + _controller = new TestPaymentTransactionController( _paymentTransactionServiceMock.Object, _orderServiceMock.Object, _translationServiceMock.Object, dateTimeServiceMock.Object, _mediatorMock.Object, enumTranslationServiceMock.Object, _scopeMock.Object, - contextAccessorMock.Object, _historyMock.Object, _paymentServiceMock.Object); + contextAccessorMock.Object, _historyMock.Object, _paymentServiceMock.Object, _storeServiceMock.Object, + orderStatusServiceMock.Object); // Error()/Success() (used by this task's popup and Delete actions) reach into // HttpContext.RequestServices for ILoggerFactory and into TempData - wire up the same @@ -288,6 +301,96 @@ public async Task Edit_Authorized_ReturnsViewWithModel() Assert.AreEqual(80, model.MaxAmountToRefund); } + private async Task EditModel(PaymentTransaction transaction, Order order) + { + _paymentTransactionServiceMock.Setup(s => s.GetById(transaction.Id)).ReturnsAsync(transaction); + _orderServiceMock.Setup(s => s.GetOrderByGuid(transaction.OrderGuid)).ReturnsAsync(order); + + var result = await _controller.Edit(transaction.Id) as ViewResult; + + Assert.IsNotNull(result); + return (PaymentTransactionModel)result!.Model; + } + + [TestMethod] + public async Task Edit_MapsGatewayFieldsAmountsAndErrors() + { + var model = await EditModel(new PaymentTransaction { + Id = "pt-1", OrderGuid = Guid.NewGuid(), PaymentMethodSystemName = "Payments.OnAccount", + TransactionAmount = 100, PaidAmount = 40, RefundedAmount = 10, CurrencyRate = 4.2, + AuthorizationTransactionCode = "A1", AuthorizationTransactionResult = "ok", + CaptureTransactionId = "C1", CaptureTransactionResult = "done", + Errors = new List { "declined" }, CustomValues = new Dictionary { ["IBAN"] = "PL61" }, + Temp = true, UpdatedOnUtc = new DateTime(2026, 11, 19, 8, 0, 0, DateTimeKind.Utc) + }, null); + + Assert.AreEqual(60, model.AmountDue); + Assert.AreEqual(30, model.AmountRefundable); + Assert.AreEqual(4.2, model.CurrencyRate); + Assert.AreEqual("A1", model.AuthorizationTransactionCode); + Assert.AreEqual("ok", model.AuthorizationTransactionResult); + Assert.AreEqual("C1", model.CaptureTransactionId); + Assert.AreEqual("done", model.CaptureTransactionResult); + Assert.AreEqual("declined", model.Errors.Single()); + Assert.AreEqual("PL61", model.CustomValues["IBAN"]); + Assert.IsTrue(model.Abandoned); + Assert.IsNotNull(model.UpdatedOn); + Assert.AreEqual("On account", model.PaymentMethodName); + } + + [TestMethod] + public async Task Edit_MapsOrderData() + { + _enumTranslationServiceMock.Setup(e => e.GetTranslationEnum(PaymentStatus.PartiallyPaid)).Returns("Partially paid"); + + var model = await EditModel(new PaymentTransaction { Id = "pt-1", OrderGuid = Guid.NewGuid() }, new Order { + Id = "order-1", OrderStatusId = 10, PaymentStatusId = PaymentStatus.PartiallyPaid, OrderTotal = 100, + CustomerCurrencyCode = "PLN", + BillingAddress = new Address { Company = "", FirstName = "Jan", LastName = "Nowak" } + }); + + Assert.AreEqual("Pending", model.OrderStatus); + Assert.AreEqual("Partially paid", model.OrderPaymentStatus); + Assert.AreEqual(100, model.OrderTotal); + Assert.AreEqual("PLN", model.OrderCurrencyCode); + Assert.AreEqual("Jan Nowak", model.BillingName); + } + + [TestMethod] + public async Task Edit_BillingName_PrefersTheCompany() + { + var model = await EditModel(new PaymentTransaction { Id = "pt-1", OrderGuid = Guid.NewGuid() }, new Order { + Id = "order-1", BillingAddress = new Address { Company = "ACME", FirstName = "Jan", LastName = "Nowak" } + }); + + Assert.AreEqual("ACME", model.BillingName); + } + + [TestMethod] + public async Task Edit_StoreName_OnlyWithoutStoreScope() + { + var transaction = new PaymentTransaction { Id = "pt-1", StoreId = "s1" }; + + _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null); + Assert.AreEqual("Main", (await EditModel(transaction, null)).StoreName); + + _scopeMock.Setup(s => s.DefaultStoreId).Returns("s1"); + Assert.IsNull((await EditModel(transaction, null)).StoreName); + } + + [TestMethod] + public async Task Edit_WithoutOrderOrPaymentPlugin_StillRenders() + { + var model = await EditModel( + new PaymentTransaction { Id = "pt-1", OrderGuid = Guid.NewGuid(), PaymentMethodSystemName = "Payments.Gone" }, + null); + + Assert.IsNull(model.OrderStatus); + Assert.IsNull(model.OrderTotal); + Assert.IsNull(model.BillingName); + Assert.AreEqual("Payments.Gone", model.PaymentMethodName); + } + [TestMethod] public async Task CapturePaymentTransaction_DeniedByScope_RedirectsToList() { diff --git a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs index aa117779a..59f545294 100644 --- a/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs +++ b/src/Web/Grand.Web.Admin/Controllers/PaymentTransactionController.cs @@ -1,6 +1,7 @@ using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; using Grand.Domain.Payments; using Grand.Infrastructure; using Grand.Mediator; @@ -27,7 +28,9 @@ public class PaymentTransactionController( IAdminDataScope scope, IContextAccessor contextAccessor, IPaymentTransactionHistoryService paymentTransactionHistoryService, - IPaymentService paymentService) + IPaymentService paymentService, + IStoreService storeService, + IOrderStatusService orderStatusService) : BasePaymentTransactionController(paymentTransactionService, orderService, translationService, dateTimeService, mediator, enumTranslationService, scope, contextAccessor, paymentTransactionHistoryService, - paymentService); + paymentService, storeService, orderStatusService); diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs index 16506d765..7e47a9b33 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs @@ -3,8 +3,10 @@ using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Business.Core.Utilities.Checkout; +using Grand.Domain.Common; using Grand.Domain.Orders; using Grand.Domain.Payments; using Grand.Domain.Permissions; @@ -34,7 +36,9 @@ public abstract class BasePaymentTransactionController( IAdminDataScope scope, IContextAccessor contextAccessor, IPaymentTransactionHistoryService paymentTransactionHistoryService, - IPaymentService paymentService) + IPaymentService paymentService, + IStoreService storeService, + IOrderStatusService orderStatusService) : BaseController { // Exposed for host-specific concrete subclasses (none currently need extra actions, unlike @@ -50,6 +54,8 @@ public abstract class BasePaymentTransactionController( protected IContextAccessor ContextAccessor => contextAccessor; protected IPaymentTransactionHistoryService PaymentTransactionHistoryService => paymentTransactionHistoryService; protected IPaymentService PaymentService => paymentService; + protected IStoreService StoreService => storeService; + protected IOrderStatusService OrderStatusService => orderStatusService; /// Who the payment operation history and order notes name for an operation made here private string StaffName => contextAccessor.WorkContext.CurrentCustomer.StatusChangedBy(); @@ -216,21 +222,46 @@ public async Task Edit(string id) TransactionAmount = paymentTransaction.TransactionAmount, PaidAmount = paymentTransaction.PaidAmount, PaymentMethodSystemName = paymentTransaction.PaymentMethodSystemName, + PaymentMethodName = + paymentService.LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName)?.FriendlyName ?? + paymentTransaction.PaymentMethodSystemName, + Abandoned = paymentTransaction.Temp, RefundedAmount = paymentTransaction.RefundedAmount, + AmountDue = Math.Max(paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount, 0), + AmountRefundable = Math.Max(paymentTransaction.PaidAmount - paymentTransaction.RefundedAmount, 0), + CurrencyRate = paymentTransaction.CurrencyRate, + //the store panel shows its own store only, so naming it says nothing + StoreName = scope.DefaultStoreId is null + ? (await storeService.GetStoreById(paymentTransaction.StoreId))?.Name + : null, OrderId = order?.Id, OrderNumber = order?.OrderNumber, + OrderStatus = order != null ? (await orderStatusService.GetByStatusId(order.OrderStatusId))?.Name : null, + OrderPaymentStatus = order != null ? enumTranslationService.GetTranslationEnum(order.PaymentStatusId) : null, + OrderTotal = order?.OrderTotal, + OrderCurrencyCode = order?.CustomerCurrencyCode, + BillingName = BillingName(order?.BillingAddress), PurchaseOrderNumber = order?.PurchaseOrderNumber, PaymentDueDate = order?.PaymentDueDateUtc?.Date, IsPaymentOverdue = order?.IsPaymentOverdue(DateTime.UtcNow) ?? false, BoughtOnCredit = order?.PaymentDueDateUtc != null, CanEditPaymentTerms = HasPaymentTerms(order), CreatedOn = dateTimeService.ConvertToUserTime(paymentTransaction.CreatedOnUtc, DateTimeKind.Utc), + UpdatedOn = paymentTransaction.UpdatedOnUtc.HasValue + ? dateTimeService.ConvertToUserTime(paymentTransaction.UpdatedOnUtc.Value, DateTimeKind.Utc) + : null, TransactionStatus = paymentTransaction.TransactionStatus, Status = enumTranslationService.GetTranslationEnum(paymentTransaction.TransactionStatus), IPAddress = paymentTransaction.IPAddress, Description = paymentTransaction.Description, AdditionalInfo = paymentTransaction.AdditionalInfo, AuthorizationTransactionId = paymentTransaction.AuthorizationTransactionId, + AuthorizationTransactionCode = paymentTransaction.AuthorizationTransactionCode, + AuthorizationTransactionResult = paymentTransaction.AuthorizationTransactionResult, + CaptureTransactionId = paymentTransaction.CaptureTransactionId, + CaptureTransactionResult = paymentTransaction.CaptureTransactionResult, + Errors = paymentTransaction.Errors ?? new List(), + CustomValues = paymentTransaction.CustomValues ?? new Dictionary(), CanCapture = await mediator.Send(new CanCaptureQuery { PaymentTransaction = paymentTransaction }), CanMarkAsPaid = await mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction }), CanRefund = await mediator.Send(new CanRefundQuery { PaymentTransaction = paymentTransaction }), @@ -257,6 +288,17 @@ public async Task Edit(string id) return View(model); } + private static string BillingName(Address address) + { + if (address == null) + return null; + if (!string.IsNullOrWhiteSpace(address.Company)) + return address.Company; + + var name = $"{address.FirstName} {address.LastName}".Trim(); + return string.IsNullOrEmpty(name) ? null : name; + } + [PermissionAuthorizeAction(PermissionActionName.Edit)] [HttpPost] public async Task CapturePaymentTransaction(string id) diff --git a/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs b/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs index 0b5291781..4b5f783d6 100644 --- a/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs +++ b/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs @@ -10,6 +10,17 @@ public class PaymentTransactionModel : BaseEntityModel [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.PaymentMethodSystemName")] public string PaymentMethodSystemName { get; set; } + /// + /// The payment method's friendly name, or its system name when the plugin is gone + /// + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.PaymentMethodSystemName")] + public string PaymentMethodName { get; set; } + + /// + /// A checkout whose payment never went through: failed, left unfinished or still in progress + /// + public bool Abandoned { get; set; } + public TransactionStatus TransactionStatus { get; set; } [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.Status")] @@ -28,6 +39,23 @@ public class PaymentTransactionModel : BaseEntityModel public int? OrderNumber { get; set; } public string OrderCode { get; set; } + [GrandResourceDisplayName("Admin.Orders.Fields.OrderStatus")] + public string OrderStatus { get; set; } + + [GrandResourceDisplayName("Admin.Orders.Fields.PaymentStatus")] + public string OrderPaymentStatus { get; set; } + + [GrandResourceDisplayName("Admin.Orders.Fields.OrderTotal")] + public double? OrderTotal { get; set; } + + public string OrderCurrencyCode { get; set; } + + /// + /// The billing company, or the billing first and last name when there is none + /// + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.BillingName")] + public string BillingName { get; set; } + [GrandResourceDisplayName("Admin.Orders.Fields.PurchaseOrderNumber")] public string PurchaseOrderNumber { get; set; } @@ -67,6 +95,18 @@ public class PaymentTransactionModel : BaseEntityModel [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.RefundedAmount")] public double RefundedAmount { get; set; } + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.AmountDue")] + public double AmountDue { get; set; } + + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.AmountRefundable")] + public double AmountRefundable { get; set; } + + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.Errors")] + public IList Errors { get; set; } = new List(); + + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.CustomValues")] + public Dictionary CustomValues { get; set; } = new(); + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.IPAddress")] public string IPAddress { get; set; } @@ -94,6 +134,9 @@ public class PaymentTransactionModel : BaseEntityModel [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.CreatedOn")] public DateTime CreatedOn { get; set; } + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.UpdatedOn")] + public DateTime? UpdatedOn { get; set; } + [GrandResourceDisplayName("Admin.PaymentTransaction.Fields.PartialRefund.MaxAmountToRefund")] public double MaxAmountToRefund { get; set; } diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml index 970718b7a..f02d2a41f 100644 --- a/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml @@ -3,17 +3,23 @@
-@* a transaction is read, not edited: what it is and what the gateway said, as facts *@ +@* a transaction is read, not edited: what it is, the order it pays for and what the gateway said, as facts *@
- -
@Model.PaymentMethodSystemName
+ +
@Model.PaymentMethodName
-
@Model.Status
+
+ @Model.Status + @if (Model.Abandoned) + { + @Loc["Admin.PaymentTransaction.Abandoned"] + } +
@@ -23,6 +29,13 @@
@Model.PaidAmount [@Model.CurrencyCode]
+ @if (Model.AmountDue > 0) + { +
+ +
@Model.AmountDue [@Model.CurrencyCode]
+
+ } @if (Model.RefundedAmount > 0) {
@@ -30,44 +43,104 @@
@Model.RefundedAmount [@Model.CurrencyCode]
} -
- -
@Html.ActionLink(Model.CustomerEmail, "Edit", "Customer", new { id = Model.CustomerId }, new { })
-
-
- -
@Html.ActionLink(Model.OrderNumber.ToString(), "Edit", "Order", new { id = Model.OrderId }, new { })
-
- @if (!string.IsNullOrEmpty(Model.PurchaseOrderNumber)) + @if (Model.AmountRefundable > 0) {
- -
@Model.PurchaseOrderNumber
+ +
@Model.AmountRefundable [@Model.CurrencyCode]
} - @if (Model.PaymentDueDate.HasValue) + @if (Model.CurrencyRate > 0 && Model.CurrencyRate != 1) {
- -
- @Model.PaymentDueDate.Value.ToString("D") - @if (Model.IsPaymentOverdue) - { - @Loc["Admin.Orders.Fields.PaymentOverdue"] - } -
+ +
@Model.CurrencyRate
+
+ } +
+ +
@Html.ActionLink(Model.CustomerEmail, "Edit", "Customer", new { id = Model.CustomerId }, new { })
+
+ @if (!string.IsNullOrEmpty(Model.StoreName)) + { +
+ +
@Model.StoreName
}
@Html.DisplayFor(model => model.CreatedOn)
+ @if (Model.UpdatedOn.HasValue) + { +
+ +
@Model.UpdatedOn.Value.ToString("G")
+
+ }
@Model.IPAddress
+@if (!string.IsNullOrEmpty(Model.OrderId)) +{ + +
+
+ +
@Html.ActionLink(Model.OrderNumber.ToString(), "Edit", "Order", new { id = Model.OrderId }, new { })
+
+ @if (!string.IsNullOrEmpty(Model.OrderStatus)) + { +
+ +
@Model.OrderStatus
+
+ } +
+ +
@Model.OrderPaymentStatus
+
+ @if (Model.OrderTotal.HasValue) + { +
+ +
@Model.OrderTotal [@Model.OrderCurrencyCode]
+
+ } + @if (!string.IsNullOrEmpty(Model.BillingName)) + { +
+ +
@Model.BillingName
+
+ } + @if (!string.IsNullOrEmpty(Model.PurchaseOrderNumber)) + { +
+ +
@Model.PurchaseOrderNumber
+
+ } + @if (Model.PaymentDueDate.HasValue) + { +
+ +
+ @Model.PaymentDueDate.Value.ToString("D") + @if (Model.IsPaymentOverdue) + { + @Loc["Admin.Orders.Fields.PaymentOverdue"] + } +
+
+ } +
+
+}
@if (!string.IsNullOrEmpty(Model.AdditionalInfo)) @@ -119,5 +192,32 @@
@Model.AuthorizationTransactionResult
} + @if (Model.Errors.Count > 0) + { +
+ +
+ @foreach (var error in Model.Errors) + { +
@error
+ } +
+
+ } + @if (Model.CustomValues.Count > 0) + { +
+ + + @foreach (var item in Model.CustomValues) + { + + + + + } +
@item.Key:@(item.Value != null ? item.Value.ToString() : "")
+
+ }
diff --git a/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs b/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs index 939653e71..922718608 100644 --- a/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs +++ b/src/Web/Grand.Web.Store/Controllers/PaymentTransactionController.cs @@ -1,6 +1,7 @@ using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Stores; using Grand.Domain.Payments; using Grand.Infrastructure; using Grand.Mediator; @@ -27,7 +28,9 @@ public class PaymentTransactionController( IAdminDataScope scope, IContextAccessor contextAccessor, IPaymentTransactionHistoryService paymentTransactionHistoryService, - IPaymentService paymentService) + IPaymentService paymentService, + IStoreService storeService, + IOrderStatusService orderStatusService) : BasePaymentTransactionController(paymentTransactionService, orderService, translationService, dateTimeService, mediator, enumTranslationService, scope, contextAccessor, paymentTransactionHistoryService, - paymentService); + paymentService, storeService, orderStatusService); From 8dc321a9e599c8c1dce828f3d77d8a176f279e2f Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 17:49:13 +0100 Subject: [PATCH 4/7] Add the texts of the payment transaction filters and details --- .../App_Data/Resources/DefaultLanguage.xml | Bin 1815296 -> 1817672 bytes .../App_Data/Resources/Upgrade/en_250.xml | 27 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 0f8a0594ea0d7409d9d3c6688bce78ca42399618..0ebb35398ca34dcf011ab6d3ed483a14c02e9b04 100644 GIT binary patch delta 391 zcmYLDJxfAi7=3TvQty4QnVMg>!3vB%27`tq6)S5i#3g7-^V$b=6)PHAj2;@pa5#lR zOFtkanw%P>9}u)UgnL_4bgzXi&&PSrbIz%B_17=GLIMqtg+v;pA+nN<>?Dy)oD_1< zFga<2T;wJXjgpsqk9D3y;(<$OuksE$4Ib{VUbIs@gHVclgaXb#N;Yg Enter from 0 to 365 days. + + Overdue payments only + + + Show only payments of orders bought on trade credit that are past their due date. + + + Abandoned checkout + + + Last changed + + + Left to pay + + + Refundable + + + Payment errors + + + Payment method data + + + Billed to + From f7e297885f5f9a332bcbbd0face4579148aa9003 Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 18:04:34 +0100 Subject: [PATCH 5/7] Round what is left to pay and to refund to the cent Amounts paid in parts add up with floating-point residue, so a 123.45 payment with 100 paid showed 23.450000000000003 left. --- .../BasePaymentTransactionControllerTests.cs | 15 +++++++++++++++ .../BasePaymentTransactionController.cs | 9 +++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs index 9491e0c52..baaa917d6 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs @@ -338,6 +338,21 @@ public async Task Edit_MapsGatewayFieldsAmountsAndErrors() Assert.AreEqual("On account", model.PaymentMethodName); } + [TestMethod] + public async Task Edit_AmountsLeftAreRoundedToCents() + { + var model = await EditModel(new PaymentTransaction { + Id = "pt-1", TransactionAmount = 123.45, PaidAmount = 100, RefundedAmount = 76.55 + }, null); + Assert.AreEqual(23.45, model.AmountDue); + Assert.AreEqual(23.45, model.AmountRefundable); + + //paid in two parts that add up to a hair below the amount: nothing is left to pay + model = await EditModel(new PaymentTransaction { Id = "pt-1", TransactionAmount = 0.1 + 0.2, PaidAmount = 0.3 }, + null); + Assert.AreEqual(0, model.AmountDue); + } + [TestMethod] public async Task Edit_MapsOrderData() { diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs index 7e47a9b33..43840d477 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs @@ -227,8 +227,8 @@ public async Task Edit(string id) paymentTransaction.PaymentMethodSystemName, Abandoned = paymentTransaction.Temp, RefundedAmount = paymentTransaction.RefundedAmount, - AmountDue = Math.Max(paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount, 0), - AmountRefundable = Math.Max(paymentTransaction.PaidAmount - paymentTransaction.RefundedAmount, 0), + AmountDue = AmountLeft(paymentTransaction.TransactionAmount, paymentTransaction.PaidAmount), + AmountRefundable = AmountLeft(paymentTransaction.PaidAmount, paymentTransaction.RefundedAmount), CurrencyRate = paymentTransaction.CurrencyRate, //the store panel shows its own store only, so naming it says nothing StoreName = scope.DefaultStoreId is null @@ -288,6 +288,11 @@ public async Task Edit(string id) return View(model); } + /// + /// What is left of an amount, to the cent: amounts paid in parts add up with floating-point residue + /// + private static double AmountLeft(double amount, double used) => Math.Max(Math.Round(amount - used, 2), 0); + private static string BillingName(Address address) { if (address == null) From 96ce0bb29983152caef2647c6fc39f2f7f563766 Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 18:34:27 +0100 Subject: [PATCH 6/7] Share what is left to pay and refund, and the overdue and PO number filters The payment rules, the popups and the details screen now count what is left the same way, with the floating-point residue of part payments rounded off. The order list and the payment transaction list filter overdue orders and purchase order numbers through one rule. --- .../Handlers/Orders/CaptureCommandHandler.cs | 2 +- .../Orders/MarkAsPaidCommandHandler.cs | 3 +- .../CanPartiallyPaidOfflineQueryHandler.cs | 5 +- .../CanPartiallyRefundOfflineQueryHandler.cs | 5 +- .../Orders/CanPartiallyRefundQueryHandler.cs | 5 +- .../Handlers/Orders/GetOrderQueryHandler.cs | 11 +--- .../GetPaymentTransactionQueryHandler.cs | 11 +--- .../Extensions/PaymentExtensions.cs | 55 +++++++++++++++++++ .../Extensions/PaymentExtensionsTests.cs | 52 ++++++++++++++++++ 9 files changed, 123 insertions(+), 26 deletions(-) diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs index bdaac76eb..b588dfdc6 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs @@ -59,7 +59,7 @@ public async Task> Handle(CaptureCommand command, CancellationToke paymentTransaction = await _paymentTransaction.GetById(paymentTransaction.Id); //a capture the gateway settles later is not money in yet: it is paid, and recorded, when it is var captured = result.NewPaymentStatus == TransactionStatus.Paid - ? paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount + ? paymentTransaction.AmountLeftToPay() : 0; paymentTransaction.PaidAmount += captured; paymentTransaction.CaptureTransactionId = result.CaptureTransactionId; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs index f3651f965..aef02b6c5 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs @@ -1,4 +1,5 @@ using Grand.Business.Core.Commands.Checkout.Orders; +using Grand.Business.Core.Extensions; using Grand.Business.Core.Interfaces.Checkout.Orders; using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Queries.Checkout.Orders; @@ -40,7 +41,7 @@ await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransacti throw new GrandException("You can't mark this Payment Transaction as paid"); //what the payment method reports it took, else what was still to pay - var paid = request.Amount ?? paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount; + var paid = request.Amount ?? paymentTransaction.AmountLeftToPay(); paymentTransaction.TransactionStatus = TransactionStatus.Paid; paymentTransaction.PaidAmount = paymentTransaction.TransactionAmount; diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs index cfea3b883..67b418a23 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs @@ -1,4 +1,5 @@ -using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Domain.Payments; using Grand.Mediator; @@ -16,7 +17,7 @@ public Task Handle(CanPartiallyPaidOfflineQuery request, CancellationToken if (paymentTransaction.TransactionAmount == 0) return Task.FromResult(false); - var canBePaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount; + var canBePaid = paymentTransaction.AmountLeftToPay(); if (canBePaid <= 0) return Task.FromResult(false); diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs index 8bea950d2..88b0061cf 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs @@ -1,4 +1,5 @@ -using Grand.Business.Core.Queries.Checkout.Orders; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Domain.Payments; using Grand.Mediator; @@ -16,7 +17,7 @@ public Task Handle(CanPartiallyRefundOfflineQuery request, CancellationTok if (paymentTransaction.TransactionAmount == 0) return Task.FromResult(false); - var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount; + var canBeRefunded = paymentTransaction.AmountLeftToRefund(); if (canBeRefunded <= 0) return Task.FromResult(false); diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs index 1bb47807c..6fdffd36c 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs @@ -1,4 +1,5 @@ -using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Business.Core.Extensions; +using Grand.Business.Core.Interfaces.Checkout.Payments; using Grand.Business.Core.Queries.Checkout.Orders; using Grand.Domain.Payments; using Grand.Mediator; @@ -28,7 +29,7 @@ public async Task Handle(CanPartiallyRefundQuery request, CancellationToke //if (order.OrderStatus == OrderStatus.Cancelled) // return false; - var canBeRefunded = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount; + var canBeRefunded = paymentTransaction.AmountLeftToRefund(); if (canBeRefunded <= 0) return false; diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs index c38b5ebba..69c76adf3 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetOrderQueryHandler.cs @@ -95,17 +95,10 @@ public async Task> Handle(GetOrderQuery request, CancellationT query = query.Where(o => o.OrderTags.Any(y => y == request.OrderTagId)); if (!string.IsNullOrWhiteSpace(request.PurchaseOrderNumber)) - { - var purchaseOrderNumber = request.PurchaseOrderNumber.Trim(); - query = query.Where(o => o.PurchaseOrderNumber == purchaseOrderNumber); - } + query = query.WherePurchaseOrderNumber(request.PurchaseOrderNumber); - //the same rule as PaymentExtensions.IsPaymentOverdue if (request.OverdueOnly) - { - var today = DateTime.UtcNow.Date; - query = query.Where(PaymentExtensions.UnpaidOnCredit).Where(o => o.PaymentDueDateUtc < today); - } + query = query.WherePaymentOverdue(DateTime.UtcNow); query = query.Where(o => !o.Deleted); query = query.OrderByDescending(o => o.CreatedOnUtc); diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs index 325300e8f..19706c867 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPaymentTransactionQueryHandler.cs @@ -74,17 +74,10 @@ private Task> MatchingOrderGuids(GetPaymentTransactionQuery request, orders = orders.Where(o => o.StoreId == request.StoreId); if (!string.IsNullOrWhiteSpace(request.PurchaseOrderNumber)) - { - var purchaseOrderNumber = request.PurchaseOrderNumber.Trim(); - orders = orders.Where(o => o.PurchaseOrderNumber == purchaseOrderNumber); - } + orders = orders.WherePurchaseOrderNumber(request.PurchaseOrderNumber); - //the same rule as PaymentExtensions.IsPaymentOverdue if (request.OverdueOnly) - { - var today = DateTime.UtcNow.Date; - orders = orders.Where(PaymentExtensions.UnpaidOnCredit).Where(o => o.PaymentDueDateUtc < today); - } + orders = orders.WherePaymentOverdue(DateTime.UtcNow); return _orderRepository.ToListAsync(orders.Select(o => o.OrderGuid), cancellationToken); } diff --git a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs index 2981c6222..4130f4950 100644 --- a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs @@ -80,4 +80,59 @@ public static bool IsPaymentOverdue(this Order order, DateTime utcNow) return IsUnpaidOnCredit(order) && order.PaymentDueDateUtc!.Value < utcNow.Date; } + + /// + /// Filters orders to those whose payment is overdue, by the same rule as + /// + /// Orders + /// Current date and time in UTC + /// Orders bought on credit, not paid yet and past their due date + public static IQueryable WherePaymentOverdue(this IQueryable orders, DateTime utcNow) + { + var today = utcNow.Date; + return orders.Where(UnpaidOnCredit).Where(o => o.PaymentDueDateUtc < today); + } + + /// + /// Filters orders to those carrying a purchase order number, matched exactly once trimmed + /// + /// Orders + /// Purchase order number + /// Orders carrying the number + public static IQueryable WherePurchaseOrderNumber(this IQueryable orders, + string purchaseOrderNumber) + { + var number = purchaseOrderNumber.Trim(); + return orders.Where(o => o.PurchaseOrderNumber == number); + } + + /// + /// Gets what is left to pay of a payment transaction + /// + /// Payment transaction + /// The amount, never below zero + public static double AmountLeftToPay(this PaymentTransaction paymentTransaction) + { + ArgumentNullException.ThrowIfNull(paymentTransaction); + + return AmountLeft(paymentTransaction.TransactionAmount, paymentTransaction.PaidAmount); + } + + /// + /// Gets what is left to refund of a payment transaction + /// + /// Payment transaction + /// The amount, never below zero + public static double AmountLeftToRefund(this PaymentTransaction paymentTransaction) + { + ArgumentNullException.ThrowIfNull(paymentTransaction); + + return AmountLeft(paymentTransaction.TransactionAmount, paymentTransaction.RefundedAmount); + } + + /// + /// Amounts paid or refunded in parts add up with floating-point residue (0.1 + 0.2 is not 0.3), which is + /// rounded off so that a transaction settled in full has nothing left. No currency has six decimals. + /// + private static double AmountLeft(double amount, double used) => Math.Max(Math.Round(amount - used, 6), 0); } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs index 0570bb140..c03374a22 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs @@ -87,4 +87,56 @@ public void GetPaymentMethodName_NullProvider_ReturnSystemName() var order = new Order { PaymentMethodSystemName = "Payments.Test" }; Assert.AreEqual("Payments.Test", provider.GetPaymentMethodName(order)); } + + [TestMethod] + public void AmountLeftToPay_PaidInPartsToTheFullAmount_NothingLeft() + { + //0.7 + 0.1 + 0.1 + 0.1 adds up to a hair below 1 + var paymentTransaction = new PaymentTransaction { TransactionAmount = 1, PaidAmount = 0.7 + 0.1 + 0.1 + 0.1 }; + Assert.AreEqual(0, paymentTransaction.AmountLeftToPay()); + } + + [TestMethod] + public void AmountLeftToPay_KeepsAThirdDecimal() + { + var paymentTransaction = new PaymentTransaction { TransactionAmount = 10.005, PaidAmount = 10 }; + Assert.AreEqual(0.005, paymentTransaction.AmountLeftToPay(), 1e-9); + } + + [TestMethod] + public void AmountLeftToRefund_IsTheTransactionAmountLessTheRefunds_NeverBelowZero() + { + Assert.AreEqual(90, new PaymentTransaction { TransactionAmount = 100, PaidAmount = 40, RefundedAmount = 10 } + .AmountLeftToRefund()); + Assert.AreEqual(0, new PaymentTransaction { TransactionAmount = 100, RefundedAmount = 120 }.AmountLeftToRefund()); + } + + [TestMethod] + public void WherePaymentOverdue_MatchesIsPaymentOverdue() + { + var now = new DateTime(2026, 11, 19, 10, 0, 0, DateTimeKind.Utc); + var orders = new List { + new() { Id = "overdue", PaymentDueDateUtc = now.Date.AddDays(-1), PaymentStatusId = PaymentStatus.Pending }, + new() { Id = "dueToday", PaymentDueDateUtc = now.Date, PaymentStatusId = PaymentStatus.Pending }, + new() { Id = "paid", PaymentDueDateUtc = now.Date.AddDays(-1), PaymentStatusId = PaymentStatus.Paid }, + new() { Id = "paidAtOnce", PaymentStatusId = PaymentStatus.Pending } + }; + + var overdue = orders.AsQueryable().WherePaymentOverdue(now).Select(o => o.Id).ToList(); + + CollectionAssert.AreEqual(new[] { "overdue" }, overdue); + CollectionAssert.AreEqual(orders.Where(o => o.IsPaymentOverdue(now)).Select(o => o.Id).ToList(), overdue); + } + + [TestMethod] + public void WherePurchaseOrderNumber_MatchesTheTrimmedNumberExactly() + { + var orders = new List { + new() { Id = "a", PurchaseOrderNumber = "PO-7" }, + new() { Id = "b", PurchaseOrderNumber = "PO-77" } + }; + + CollectionAssert.AreEqual(new[] { "a" }, + orders.AsQueryable().WherePurchaseOrderNumber(" PO-7 ").Select(o => o.Id).ToList()); + } } From ef1755fccd3de37aee4e31351c8df78363bd7c2d Mon Sep 17 00:00:00 2001 From: support Date: Thu, 19 Nov 2026 18:34:27 +0100 Subject: [PATCH 7/7] Fix the review findings on the payment transaction screens - the store panel lists only its own store's payment methods (payment transactions and orders), built in one place - left to pay is shown only while the transaction can still be paid; refundable is the refund limit, shown only while a refund can be made - a Temp transaction is marked 'Checkout not completed' rather than abandoned: it may still be in progress at the gateway - last changed is formatted like created on - Go to order number ignores a number that is not a number --- .../BasePaymentTransactionControllerTests.cs | 68 +++++++++++++++--- .../BasePaymentTransactionController.cs | 39 +++++----- .../Extensions/PaymentServiceExtensions.cs | 27 +++++++ .../Models/Orders/PaymentTransactionModel.cs | 4 +- .../Services/OrderViewModelService.cs | 5 +- .../PaymentTransaction/Partials/Update.cshtml | 6 +- .../App_Data/Resources/DefaultLanguage.xml | Bin 1817672 -> 1817702 bytes .../App_Data/Resources/Upgrade/en_250.xml | 4 +- 8 files changed, 113 insertions(+), 40 deletions(-) create mode 100644 src/Web/Grand.Web.AdminShared/Extensions/PaymentServiceExtensions.cs diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs index baaa917d6..7bb325344 100644 --- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs @@ -164,6 +164,18 @@ public async Task List_ListsPaymentMethodsAfterAll() Assert.AreEqual("On account", model.AvailablePaymentMethods[1].Text); } + [TestMethod] + [DataRow(null, "")] + [DataRow("store-1", "store-1")] + public async Task List_ListsThePaymentMethodsOfTheScopedStore(string defaultStoreId, string storeId) + { + _scopeMock.Setup(s => s.DefaultStoreId).Returns(defaultStoreId); + + await _controller.List(); + + _paymentServiceMock.Verify(p => p.LoadAllPaymentMethods(null, storeId, ""), Times.Once); + } + [TestMethod] public async Task List_Post_PassesTheNewFilters() { @@ -273,6 +285,16 @@ public async Task GoToOrderNumber_Authorized_RedirectsToEdit() Assert.AreEqual("pt-1", result!.RouteValues["id"]); } + [TestMethod] + public async Task GoToOrderNumber_UnreadableNumber_RedirectsToListWithoutLookingItUp() + { + var result = await _controller.GoToOrderNumber(new PaymentTransactionListModel { OrderNumber = "abc" }) as RedirectToActionResult; + + Assert.IsNotNull(result); + Assert.AreEqual("List", result!.ActionName); + _orderServiceMock.Verify(s => s.GetOrderByNumber(It.IsAny()), Times.Never); + } + [TestMethod] public async Task Edit_DeniedByScope_RedirectsToList() { @@ -324,8 +346,6 @@ public async Task Edit_MapsGatewayFieldsAmountsAndErrors() Temp = true, UpdatedOnUtc = new DateTime(2026, 11, 19, 8, 0, 0, DateTimeKind.Utc) }, null); - Assert.AreEqual(60, model.AmountDue); - Assert.AreEqual(30, model.AmountRefundable); Assert.AreEqual(4.2, model.CurrencyRate); Assert.AreEqual("A1", model.AuthorizationTransactionCode); Assert.AreEqual("ok", model.AuthorizationTransactionResult); @@ -333,24 +353,50 @@ public async Task Edit_MapsGatewayFieldsAmountsAndErrors() Assert.AreEqual("done", model.CaptureTransactionResult); Assert.AreEqual("declined", model.Errors.Single()); Assert.AreEqual("PL61", model.CustomValues["IBAN"]); - Assert.IsTrue(model.Abandoned); + Assert.IsTrue(model.CheckoutNotCompleted); Assert.IsNotNull(model.UpdatedOn); Assert.AreEqual("On account", model.PaymentMethodName); } [TestMethod] - public async Task Edit_AmountsLeftAreRoundedToCents() + public async Task Edit_AmountDue_OnlyWhileTheTransactionCanBePaid() { - var model = await EditModel(new PaymentTransaction { - Id = "pt-1", TransactionAmount = 123.45, PaidAmount = 100, RefundedAmount = 76.55 - }, null); - Assert.AreEqual(23.45, model.AmountDue); - Assert.AreEqual(23.45, model.AmountRefundable); + var transaction = new PaymentTransaction { Id = "pt-1", TransactionAmount = 100, PaidAmount = 40 }; - //paid in two parts that add up to a hair below the amount: nothing is left to pay - model = await EditModel(new PaymentTransaction { Id = "pt-1", TransactionAmount = 0.1 + 0.2, PaidAmount = 0.3 }, + Assert.AreEqual(0, (await EditModel(transaction, null)).AmountDue); + + _mediatorMock.Setup(m => m.Send(It.IsAny(), default)).ReturnsAsync(true); + Assert.AreEqual(60, (await EditModel(transaction, null)).AmountDue); + + //a checkout never completed owes nothing + transaction.Temp = true; + Assert.AreEqual(0, (await EditModel(transaction, null)).AmountDue); + } + + [TestMethod] + public async Task Edit_AmountRefundable_IsTheRefundLimit_OnlyWhileARefundCanBeMade() + { + var transaction = new PaymentTransaction { Id = "pt-1", TransactionAmount = 100, PaidAmount = 40, RefundedAmount = 10 }; + + Assert.AreEqual(0, (await EditModel(transaction, null)).AmountRefundable); + + _mediatorMock.Setup(m => m.Send(It.IsAny(), default)).ReturnsAsync(true); + var model = await EditModel(transaction, null); + Assert.AreEqual(90, model.AmountRefundable); + Assert.AreEqual(model.MaxAmountToRefund, model.AmountRefundable); + } + + [TestMethod] + public async Task Edit_PaidInPartsToTheFullAmount_LeavesNothingToPay() + { + _mediatorMock.Setup(m => m.Send(It.IsAny(), default)).ReturnsAsync(true); + + //0.7 + 0.1 + 0.1 + 0.1 adds up to a hair below 1 + var model = await EditModel(new PaymentTransaction { Id = "pt-1", TransactionAmount = 1, PaidAmount = 0.7 + 0.1 + 0.1 + 0.1 }, null); + Assert.AreEqual(0, model.AmountDue); + Assert.AreEqual(0, model.MaxAmountToPaid); } [TestMethod] diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs index 43840d477..abd0398c7 100644 --- a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs +++ b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs @@ -13,6 +13,7 @@ using Grand.Infrastructure; using Grand.Mediator; using Grand.SharedKernel; +using Grand.Web.AdminShared.Extensions; using Grand.Web.AdminShared.Interfaces; using Grand.Web.AdminShared.Models.Orders; using Grand.Web.Common.Controllers; @@ -86,9 +87,9 @@ public async Task List() model.PaymentTransactionStatus.Insert(0, new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "-1", Selected = true }); - model.AvailablePaymentMethods.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = " " }); - foreach (var pm in await paymentService.LoadAllPaymentMethods()) - model.AvailablePaymentMethods.Add(new SelectListItem { Text = pm.FriendlyName, Value = pm.SystemName }); + //the store panel lists the methods its own store can use + model.AvailablePaymentMethods = + await paymentService.PaymentMethodSelectList(translationService, scope.DefaultStoreId); return View(model); } @@ -182,9 +183,10 @@ public async Task GoToOrderNumber(PaymentTransactionListModel mod if (model.OrderNumber == null) return RedirectToAction("List", "PaymentTransaction"); - int.TryParse(model.OrderNumber, out var id); + if (!int.TryParse(model.OrderNumber, out var orderNumber)) + return RedirectToAction("List", "PaymentTransaction"); - var order = await orderService.GetOrderByNumber(id); + var order = await orderService.GetOrderByNumber(orderNumber); if (order == null) return RedirectToAction("List", "PaymentTransaction"); @@ -225,10 +227,8 @@ public async Task Edit(string id) PaymentMethodName = paymentService.LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName)?.FriendlyName ?? paymentTransaction.PaymentMethodSystemName, - Abandoned = paymentTransaction.Temp, + CheckoutNotCompleted = paymentTransaction.Temp, RefundedAmount = paymentTransaction.RefundedAmount, - AmountDue = AmountLeft(paymentTransaction.TransactionAmount, paymentTransaction.PaidAmount), - AmountRefundable = AmountLeft(paymentTransaction.PaidAmount, paymentTransaction.RefundedAmount), CurrencyRate = paymentTransaction.CurrencyRate, //the store panel shows its own store only, so naming it says nothing StoreName = scope.DefaultStoreId is null @@ -272,8 +272,8 @@ public async Task Edit(string id) CanVoid = await mediator.Send(new CanVoidQuery { PaymentTransaction = paymentTransaction }), CanVoidOffline = await mediator.Send(new CanVoidOfflineQuery { PaymentTransaction = paymentTransaction }), CanDelete = await mediator.Send(new CanDeletePaymentTransactionQuery { PaymentTransaction = paymentTransaction }), - MaxAmountToRefund = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount, - MaxAmountToPaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount, + MaxAmountToRefund = paymentTransaction.AmountLeftToRefund(), + MaxAmountToPaid = paymentTransaction.AmountLeftToPay(), Entries = (await paymentTransactionHistoryService.GetEntries(paymentTransaction.Id)).Select(x => new PaymentTransactionEntryModel { Operation = enumTranslationService.GetTranslationEnum(x.EntryType), @@ -284,15 +284,16 @@ public async Task Edit(string id) Note = x.Note }).ToList() }; + //what is left is shown only while it can still be paid or refunded: a voided, cancelled or + //never completed transaction owes nothing + if (model.CanMarkAsPaid && !paymentTransaction.Temp) + model.AmountDue = paymentTransaction.AmountLeftToPay(); + if (model.CanRefund || model.CanRefundOffline || model.CanPartiallyRefund || model.CanPartiallyRefundOffline) + model.AmountRefundable = paymentTransaction.AmountLeftToRefund(); return View(model); } - /// - /// What is left of an amount, to the cent: amounts paid in parts add up with floating-point residue - /// - private static double AmountLeft(double amount, double used) => Math.Max(Math.Round(amount - used, 2), 0); - private static string BillingName(Address address) { if (address == null) @@ -475,7 +476,7 @@ public async Task PartiallyRefundPopup(string id, bool online) var model = new PaymentTransactionModel { Id = paymentTransaction.Id, - MaxAmountToRefund = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount, + MaxAmountToRefund = paymentTransaction.AmountLeftToRefund(), CurrencyCode = paymentTransaction.CurrencyCode, Online = online }; @@ -497,7 +498,7 @@ public async Task PartiallyRefundPopup(string id, bool online, Pa if (amountToRefund <= 0) throw new GrandException("Enter amount to refund"); - var maxAmountToRefund = paymentTransaction.TransactionAmount - paymentTransaction.RefundedAmount; + var maxAmountToRefund = paymentTransaction.AmountLeftToRefund(); if (amountToRefund > maxAmountToRefund) amountToRefund = maxAmountToRefund; @@ -543,7 +544,7 @@ public async Task PartiallyPaidPopup(string id, bool online) var model = new PaymentTransactionModel { Id = paymentTransaction.Id, - MaxAmountToPaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount, + MaxAmountToPaid = paymentTransaction.AmountLeftToPay(), CurrencyCode = paymentTransaction.CurrencyCode }; @@ -563,7 +564,7 @@ public async Task PartiallyPaidPopup(string id, bool online, Paym if (amountToPaid <= 0) throw new GrandException("Enter amount to refund"); - var maxAmountToPaid = paymentTransaction.TransactionAmount - paymentTransaction.PaidAmount; + var maxAmountToPaid = paymentTransaction.AmountLeftToPay(); if (amountToPaid > maxAmountToPaid) amountToPaid = maxAmountToPaid; diff --git a/src/Web/Grand.Web.AdminShared/Extensions/PaymentServiceExtensions.cs b/src/Web/Grand.Web.AdminShared/Extensions/PaymentServiceExtensions.cs new file mode 100644 index 000000000..156626b27 --- /dev/null +++ b/src/Web/Grand.Web.AdminShared/Extensions/PaymentServiceExtensions.cs @@ -0,0 +1,27 @@ +using Grand.Business.Core.Interfaces.Checkout.Payments; +using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.Mvc.Rendering; + +namespace Grand.Web.AdminShared.Extensions; + +public static class PaymentServiceExtensions +{ + /// + /// Get the payment methods a list can be filtered by, after an "All" item + /// + /// Payment service + /// Translation service + /// The store whose methods are listed; empty for the methods of every store + /// Select list items whose value is the method's system name + public static async Task> PaymentMethodSelectList(this IPaymentService paymentService, + IRequestTranslationService translationService, string storeId) + { + var items = new List { + new() { Text = translationService.GetResource("Admin.Common.All"), Value = " " } + }; + foreach (var pm in await paymentService.LoadAllPaymentMethods(storeId: storeId ?? "")) + items.Add(new SelectListItem { Text = pm.FriendlyName, Value = pm.SystemName }); + + return items; + } +} diff --git a/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs b/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs index 4b5f783d6..7a49a1295 100644 --- a/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs +++ b/src/Web/Grand.Web.AdminShared/Models/Orders/PaymentTransactionModel.cs @@ -17,9 +17,9 @@ public class PaymentTransactionModel : BaseEntityModel public string PaymentMethodName { get; set; } /// - /// A checkout whose payment never went through: failed, left unfinished or still in progress + /// A checkout whose payment never went through: failed, abandoned or still in progress at the gateway /// - public bool Abandoned { get; set; } + public bool CheckoutNotCompleted { get; set; } public TransactionStatus TransactionStatus { get; set; } diff --git a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs index 2308d53fe..6fbaf370e 100644 --- a/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs +++ b/src/Web/Grand.Web.AdminShared/Services/OrderViewModelService.cs @@ -22,6 +22,7 @@ using Grand.Domain.Shipping; using Grand.Domain.Tax; using Grand.Infrastructure; +using Grand.Web.AdminShared.Extensions; using Grand.Web.AdminShared.Extensions.Mapping; using Grand.Web.AdminShared.Interfaces; using Grand.Web.AdminShared.Models.Orders; @@ -218,9 +219,7 @@ public virtual async Task PrepareOrderListModel( model.AvailableWarehouses.Add(new SelectListItem { Text = w.Name, Value = w.Id }); //payment methods - model.AvailablePaymentMethods.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " }); - foreach (var pm in await _paymentService.LoadAllPaymentMethods()) - model.AvailablePaymentMethods.Add(new SelectListItem { Text = pm.FriendlyName, Value = pm.SystemName }); + model.AvailablePaymentMethods = await _paymentService.PaymentMethodSelectList(_translationService, storeId); //billing countries foreach (var c in await _countryService.GetAllCountriesForBilling(showHidden: true)) diff --git a/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml index f02d2a41f..11f24dc88 100644 --- a/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml +++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/PaymentTransaction/Partials/Update.cshtml @@ -15,9 +15,9 @@
@Model.Status - @if (Model.Abandoned) + @if (Model.CheckoutNotCompleted) { - @Loc["Admin.PaymentTransaction.Abandoned"] + @Loc["Admin.PaymentTransaction.CheckoutNotCompleted"] }
@@ -76,7 +76,7 @@ {
-
@Model.UpdatedOn.Value.ToString("G")
+
@Html.DisplayFor(model => model.UpdatedOn)
}
diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml index 0ebb35398ca34dcf011ab6d3ed483a14c02e9b04..52d9fe4ad567d7ccc468be6f55037732c46c051c 100644 GIT binary patch delta 138 zcmX@{Bk$RdyoMIW7N!>F7M2#)7Pc1l7LFFq7OocV7M>Q~7QPn#7J(MQ7NHj57LgXw z7O@ub7Ks+g7O5@LceYM9Il?Hwn#YjOP%_=nQd)TWyx9^0(;e~{)utDiNpMW>;}c?I oS73lBXta_RonCW9AZ~hq9k0psIR)ZM(;t*`sBKr+F0H`|0I4f1#sB~S delta 109 zcmV-z0FwXa_-@GfZh(XVgaU*Egam{Iga(8Mgb0KQgbIWUgbaiYgbsucgb;)ggc5`k zgcO7ogcgJsgcyVwgc`IP+_jg6n;S-#JOm0Bmu{IG4wpO&5>l6NKMg>aoNyN+m*95@ PCYO*+2?)1Fw;Lb@RC^^q 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 0c36a4f17..34a9bfb07 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 @@ -2565,8 +2565,8 @@ Show only payments of orders bought on trade credit that are past their due date. - - Abandoned checkout + + Checkout not completed Last changed