Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

feat(arch001): add BasePaymentTransactionController skeleton with List region

KrzysztofPajak8f549be572c5
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs
new file mode 100644
index 000000000..a3130cc2e
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BasePaymentTransactionControllerTests.cs
@@ -0,0 +1,137 @@
+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.Localization;
+using Grand.Domain;
+using Grand.Domain.Orders;
+using Grand.Domain.Payments;
+using Grand.Mediator;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Models.Orders;
+using Grand.Web.Common.DataSource;
+using Grand.Web.Common.Localization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Rendering;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class BasePaymentTransactionControllerTests
+{
+ private class TestPaymentTransactionController(
+ IPaymentTransactionService paymentTransactionService,
+ IOrderService orderService,
+ ITranslationService translationService,
+ IDateTimeService dateTimeService,
+ IMediator mediator,
+ IEnumTranslationService enumTranslationService,
+ IAdminDataScope<PaymentTransaction> scope)
+ : BasePaymentTransactionController(paymentTransactionService, orderService, translationService,
+ dateTimeService, mediator, enumTranslationService, scope);
+
+ private TestPaymentTransactionController _controller;
+ private Mock<IPaymentTransactionService> _paymentTransactionServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IAdminDataScope<PaymentTransaction>> _scopeMock;
+ // Declared as a field (not a local in Setup()) because later tasks in this plan (Task 3, Task
+ // 4) add further .Setup() calls on it from their own test methods for Capture/Refund/Void/
+ // partial-refund-and-paid commands.
+ private Mock<IMediator> _mediatorMock;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ _paymentTransactionServiceMock = new Mock<IPaymentTransactionService>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _scopeMock = new Mock<IAdminDataScope<PaymentTransaction>>();
+ _scopeMock.Setup(s => s.HasAccess(It.IsAny<PaymentTransaction>())).ReturnsAsync(true);
+
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");
+ var dateTimeServiceMock = new Mock<IDateTimeService>();
+ dateTimeServiceMock.Setup(d => d.ConvertToUserTime(It.IsAny<DateTime>(), It.IsAny<DateTimeKind>()))
+ .Returns((DateTime dt, DateTimeKind _) => dt);
+ _mediatorMock = new Mock<IMediator>();
+ var enumTranslationServiceMock = new Mock<IEnumTranslationService>();
+ // ToSelectList<TEnum> is generic with a `where TEnum : struct` constraint, so the setup must
+ // target the concrete enum actually passed at the List() call site (TransactionStatus), not
+ // the abstract System.Enum base class - Enum doesn't satisfy `struct` and won't compile as a
+ // type argument here. The three-argument overload (with the optional valuesToExclude) is the
+ // one the compiler binds to, so the setup must match all three.
+ enumTranslationServiceMock
+ .Setup(e => e.ToSelectList(It.IsAny<TransactionStatus>(), It.IsAny<bool>(), It.IsAny<int[]>()))
+ .Returns(new SelectList(new List<SelectListItem>()));
+
+ _controller = new TestPaymentTransactionController(
+ _paymentTransactionServiceMock.Object, _orderServiceMock.Object, translationServiceMock.Object,
+ dateTimeServiceMock.Object, _mediatorMock.Object, enumTranslationServiceMock.Object, _scopeMock.Object);
+ }
+
+ [TestMethod]
+ public void List_ReturnsViewWithPreparedModel()
+ {
+ var result = _controller.List() as ViewResult;
+
+ Assert.IsNotNull(result);
+ Assert.IsInstanceOfType(result.Model, typeof(PaymentTransactionListModel));
+ }
+
+ [TestMethod]
+ public async Task List_Post_AdminScope_DoesNotForceStoreId()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ _paymentTransactionServiceMock
+ .Setup(s => s.SearchPaymentTransactions(null, null, null, null, 0, int.MaxValue, null, null))
+ .ReturnsAsync(new PagedList<PaymentTransaction>(new List<PaymentTransaction>(), 0, 10));
+
+ var model = new PaymentTransactionListModel();
+ await _controller.List(new DataSourceRequest { Page = 1, PageSize = int.MaxValue }, model);
+
+ Assert.IsNull(model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task List_Post_StoreScope_ForcesStoreId()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ _paymentTransactionServiceMock
+ .Setup(s => s.SearchPaymentTransactions(null, "store-1", It.IsAny<string>(), null, 0, int.MaxValue, null, null))
+ .ReturnsAsync(new PagedList<PaymentTransaction>(new List<PaymentTransaction>(), 0, 10));
+
+ var model = new PaymentTransactionListModel { StoreId = "some-other-store" };
+ await _controller.List(new DataSourceRequest { Page = 1, PageSize = int.MaxValue }, model);
+
+ Assert.AreEqual("store-1", model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task GoToOrderNumber_DeniedByScope_RedirectsToList()
+ {
+ _orderServiceMock.Setup(s => s.GetOrderByNumber(It.IsAny<int>())).ReturnsAsync(new Order { OrderGuid = Guid.NewGuid() });
+ _paymentTransactionServiceMock.Setup(s => s.GetOrderByGuid(It.IsAny<Guid>()))
+ .ReturnsAsync(new PaymentTransaction { Id = "pt-1" });
+ _scopeMock.Setup(s => s.HasAccess(It.IsAny<PaymentTransaction>())).ReturnsAsync(false);
+
+ var result = await _controller.GoToOrderNumber(new PaymentTransactionListModel { OrderNumber = "123" }) as RedirectToActionResult;
+
+ Assert.IsNotNull(result);
+ Assert.AreEqual("List", result.ActionName);
+ }
+
+ [TestMethod]
+ public async Task GoToOrderNumber_Authorized_RedirectsToEdit()
+ {
+ _orderServiceMock.Setup(s => s.GetOrderByNumber(It.IsAny<int>())).ReturnsAsync(new Order { OrderGuid = Guid.NewGuid() });
+ _paymentTransactionServiceMock.Setup(s => s.GetOrderByGuid(It.IsAny<Guid>()))
+ .ReturnsAsync(new PaymentTransaction { Id = "pt-1" });
+
+ var result = await _controller.GoToOrderNumber(new PaymentTransactionListModel { OrderNumber = "123" }) as RedirectToActionResult;
+
+ Assert.IsNotNull(result);
+ Assert.AreEqual("Edit", result.ActionName);
+ Assert.AreEqual("pt-1", result.RouteValues["id"]);
+ }
+}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs
new file mode 100644
index 000000000..e172e3d04
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BasePaymentTransactionController.cs
@@ -0,0 +1,167 @@
+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.Localization;
+using Grand.Domain.Payments;
+using Grand.Domain.Permissions;
+using Grand.Mediator;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Models.Orders;
+using Grand.Web.Common.Controllers;
+using Grand.Web.Common.DataSource;
+using Grand.Web.Common.Localization;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Rendering;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+[PermissionAuthorize(PermissionSystemName.PaymentTransactions)]
+public abstract class BasePaymentTransactionController(
+ IPaymentTransactionService paymentTransactionService,
+ IOrderService orderService,
+ ITranslationService translationService,
+ IDateTimeService dateTimeService,
+ IMediator mediator,
+ IEnumTranslationService enumTranslationService,
+ IAdminDataScope<PaymentTransaction> scope)
+ : BaseController
+{
+ // Exposed for host-specific concrete subclasses (none currently need extra actions, unlike
+ // Shipment's Admin-only EditUserFields, but the accessors are added for consistency with
+ // every other Base*Controller and so Task 3/4's own file sections can reference them).
+ protected IPaymentTransactionService PaymentTransactionService => paymentTransactionService;
+ protected IOrderService OrderService => orderService;
+ protected ITranslationService TranslationService => translationService;
+ protected IDateTimeService DateTimeService => dateTimeService;
+ protected IMediator Mediator => mediator;
+ protected IEnumTranslationService EnumTranslationService => enumTranslationService;
+ protected IAdminDataScope<PaymentTransaction> Scope => scope;
+
+ /// <summary>DRY replacement for the repeated "load payment transaction, redirect to List if not
+ /// found or not authorized" pattern found in both original controllers (Admin never denied;
+ /// Store denied on StoreId mismatch at every single action). Not a behavior change — every call
+ /// site below still individually returns RedirectToAction("List") exactly as the originals
+ /// did.</summary>
+ protected async Task<(PaymentTransaction paymentTransaction, IActionResult denied)> LoadAuthorizedPaymentTransaction(string id)
+ {
+ var paymentTransaction = await paymentTransactionService.GetById(id);
+ if (paymentTransaction == null) return (null, RedirectToAction("List", "PaymentTransaction"));
+ if (!await scope.HasAccess(paymentTransaction)) return (null, RedirectToAction("List", "PaymentTransaction"));
+ return (paymentTransaction, null);
+ }
+
+ #region List
+
+ public IActionResult Index() => RedirectToAction("List");
+
+ public IActionResult List()
+ {
+ var model = new PaymentTransactionListModel {
+ PaymentTransactionStatus = enumTranslationService.ToSelectList(TransactionStatus.Pending, false)
+ .ToList()
+ };
+ model.PaymentTransactionStatus.Insert(0,
+ new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "-1", Selected = true });
+ return View(model);
+ }
+
+ /// <summary>Store's original forced <c>model.StoreId = StaffStoreId</c> unconditionally at the
+ /// top of this action, overwriting whatever the posted grid model carried — not the usual
+ /// "default when null" forcing pattern, because the List grid never lets a Store user pick a
+ /// different store to begin with (there's no store selector on this screen for Store; compare
+ /// Order's list, which does have one). Admin's original had no such line at all. Reproduced here
+ /// as an unconditional assignment gated on <c>scope.DefaultStoreId</c> being non-null, which is
+ /// exactly true for Store and exactly false (null) for Admin — same observable behavior as
+ /// both originals, expressed once.</summary>
+ [PermissionAuthorizeAction(PermissionActionName.List)]
+ [HttpPost]
+ public async Task<IActionResult> List(DataSourceRequest command, PaymentTransactionListModel model)
+ {
+ if (scope.DefaultStoreId is not null) model.StoreId = scope.DefaultStoreId;
+
+ DateTime? startDateValue = model.StartDate == null
+ ? null
+ : dateTimeService.ConvertToUtcTime(model.StartDate.Value, dateTimeService.CurrentTimeZone);
+
+ DateTime? endDateValue = model.EndDate == null
+ ? null
+ : dateTimeService.ConvertToUtcTime(model.EndDate.Value, dateTimeService.CurrentTimeZone);
+
+ 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 paymentTransactions = await paymentTransactionService.SearchPaymentTransactions(
+ customerEmail: model.SearchCustomerEmail,
+ ts: model.SearchTransactionStatus >= 0 ? (TransactionStatus)model.SearchTransactionStatus : null,
+ createdFromUtc: startDateValue,
+ createdToUtc: endDateValue,
+ storeId: model.StoreId,
+ orderGuid: orderGuid,
+ pageIndex: command.Page - 1,
+ pageSize: command.PageSize);
+
+ var dataModel = new List<PaymentTransactionModel>();
+
+ foreach (var item in paymentTransactions)
+ {
+ var order = await orderService.GetOrderByGuid(item.OrderGuid);
+ var trmodel = new PaymentTransactionModel {
+ Id = item.Id,
+ OrderCode = item.OrderCode,
+ CustomerEmail = item.CustomerEmail,
+ CustomerId = item.CustomerId,
+ CurrencyCode = item.CurrencyCode,
+ TransactionAmount = item.TransactionAmount,
+ PaidAmount = item.PaidAmount,
+ PaymentMethodSystemName = item.PaymentMethodSystemName,
+ RefundedAmount = item.RefundedAmount,
+ OrderId = order?.Id,
+ OrderNumber = order?.OrderNumber,
+ CreatedOn = dateTimeService.ConvertToUserTime(item.CreatedOnUtc, DateTimeKind.Utc),
+ TransactionStatus = item.TransactionStatus,
+ Status = enumTranslationService.GetTranslationEnum(item.TransactionStatus)
+ };
+ dataModel.Add(trmodel);
+ }
+
+ var gridModel = new DataSourceResult {
+ Data = dataModel.ToList(),
+ Total = paymentTransactions.TotalCount
+ };
+
+ return Json(gridModel);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Preview)]
+ [HttpPost]
+ public async Task<IActionResult> GoToOrderNumber(PaymentTransactionListModel model)
+ {
+ if (model.OrderNumber == null)
+ return RedirectToAction("List", "PaymentTransaction");
+
+ int.TryParse(model.OrderNumber, out var id);
+
+ var order = await orderService.GetOrderByNumber(id);
+ if (order == null)
+ return RedirectToAction("List", "PaymentTransaction");
+
+ var paymentTransaction = await paymentTransactionService.GetOrderByGuid(order.OrderGuid);
+ if (paymentTransaction == null)
+ //not found
+ return RedirectToAction("List", "PaymentTransaction");
+
+ if (!await scope.HasAccess(paymentTransaction))
+ return RedirectToAction("List", "PaymentTransaction");
+
+ return RedirectToAction("Edit", "PaymentTransaction", new { id = paymentTransaction.Id });
+ }
+
+ #endregion
+}