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 BaseShipmentController List region

KrzysztofPajakc01b8d8b1a6e
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.cs
new file mode 100644
index 000000000..6044c0002
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.cs
@@ -0,0 +1,194 @@
+using Grand.Business.Core.Interfaces.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Pdf;
+using Grand.Domain.Orders;
+using Grand.Domain.Shipping;
+using Grand.Infrastructure;
+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 Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Routing;
+using Microsoft.AspNetCore.Mvc.ViewFeatures;
+using Microsoft.Extensions.Logging;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class BaseShipmentControllerTests
+{
+ // BaseShipmentController is abstract; minimal subclass so actions can be invoked directly.
+ private class TestShipmentController(
+ IShipmentViewModelService shipmentViewModelService,
+ IOrderService orderService,
+ ITranslationService translationService,
+ IContextAccessor contextAccessor,
+ IPdfService pdfService,
+ IShipmentService shipmentService,
+ IDateTimeService dateTimeService,
+ IMediator mediator,
+ IAdminDataScope<Shipment> scope)
+ : BaseShipmentController(shipmentViewModelService, orderService, translationService,
+ contextAccessor, pdfService, shipmentService, dateTimeService, mediator, scope)
+ {
+ public Task<(Shipment shipment, IActionResult denied)> LoadAuthorizedShipmentPublic(string id) =>
+ LoadAuthorizedShipment(id);
+ }
+
+ private TestShipmentController _controller;
+ private Mock<IShipmentViewModelService> _shipmentViewModelServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+ private Mock<IAdminDataScope<Shipment>> _scopeMock;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ _shipmentViewModelServiceMock = new Mock<IShipmentViewModelService>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _scopeMock = new Mock<IAdminDataScope<Shipment>>();
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ _scopeMock.Setup(s => s.DefaultVendorId).Returns((string)null);
+
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");
+ var contextAccessorMock = new Mock<IContextAccessor>();
+ var pdfServiceMock = new Mock<IPdfService>();
+ var dateTimeServiceMock = new Mock<IDateTimeService>();
+ var mediatorMock = new Mock<IMediator>();
+
+ _controller = new TestShipmentController(
+ _shipmentViewModelServiceMock.Object,
+ _orderServiceMock.Object,
+ translationServiceMock.Object,
+ contextAccessorMock.Object,
+ pdfServiceMock.Object,
+ _shipmentServiceMock.Object,
+ dateTimeServiceMock.Object,
+ mediatorMock.Object,
+ _scopeMock.Object);
+
+ var httpContext = new DefaultHttpContext();
+ var loggerFactoryMock = new Mock<ILoggerFactory>();
+ loggerFactoryMock.Setup(l => l.CreateLogger(It.IsAny<string>())).Returns(new Mock<ILogger>().Object);
+ var urlHelperFactoryMock = new Mock<IUrlHelperFactory>();
+ urlHelperFactoryMock.Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())).Returns(new Mock<IUrlHelper>().Object);
+ var requestServicesMock = new Mock<IServiceProvider>();
+ requestServicesMock.Setup(s => s.GetService(typeof(ILoggerFactory))).Returns(loggerFactoryMock.Object);
+ requestServicesMock.Setup(s => s.GetService(typeof(IUrlHelperFactory))).Returns(urlHelperFactoryMock.Object);
+ httpContext.RequestServices = requestServicesMock.Object;
+ _controller.ControllerContext = new ControllerContext { HttpContext = httpContext };
+ _controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);
+ }
+
+ [TestMethod]
+ public async Task List_ReturnsViewWithPreparedModel()
+ {
+ var model = new ShipmentListModel();
+ _shipmentViewModelServiceMock.Setup(v => v.PrepareShipmentListModel()).ReturnsAsync(model);
+
+ var result = await _controller.List();
+
+ var viewResult = result as ViewResult;
+ Assert.IsNotNull(viewResult);
+ Assert.AreSame(model, viewResult.Model);
+ _shipmentViewModelServiceMock.Verify(v => v.PrepareShipmentListModel(), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task ShipmentListSelect_GlobalScope_DoesNotForceStoreOrVendorId()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ _scopeMock.Setup(s => s.DefaultVendorId).Returns((string)null);
+ _shipmentViewModelServiceMock
+ .Setup(v => v.PrepareShipments(It.IsAny<ShipmentListModel>(), 1, 10))
+ .ReturnsAsync((Enumerable.Empty<Shipment>(), 0));
+
+ var model = new ShipmentListModel { StoreId = "submitted-store", VendorId = "submitted-vendor" };
+ await _controller.ShipmentListSelect(new DataSourceRequest { Page = 1, PageSize = 10 }, model);
+
+ Assert.AreEqual("submitted-store", model.StoreId);
+ Assert.AreEqual("submitted-vendor", model.VendorId);
+ }
+
+ [TestMethod]
+ public async Task ShipmentListSelect_StoreScope_ForcesStoreId()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ _scopeMock.Setup(s => s.DefaultVendorId).Returns((string)null);
+ _shipmentViewModelServiceMock
+ .Setup(v => v.PrepareShipments(It.IsAny<ShipmentListModel>(), 1, 10))
+ .ReturnsAsync((Enumerable.Empty<Shipment>(), 0));
+
+ var model = new ShipmentListModel { StoreId = "attacker-supplied" };
+ await _controller.ShipmentListSelect(new DataSourceRequest { Page = 1, PageSize = 10 }, model);
+
+ Assert.AreEqual("store-1", model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task ShipmentListSelect_VendorScope_ForcesVendorId()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ _scopeMock.Setup(s => s.DefaultVendorId).Returns("vendor-1");
+ _shipmentViewModelServiceMock
+ .Setup(v => v.PrepareShipments(It.IsAny<ShipmentListModel>(), 1, 10))
+ .ReturnsAsync((Enumerable.Empty<Shipment>(), 0));
+
+ var model = new ShipmentListModel { VendorId = "attacker-supplied" };
+ await _controller.ShipmentListSelect(new DataSourceRequest { Page = 1, PageSize = 10 }, model);
+
+ Assert.AreEqual("vendor-1", model.VendorId);
+ }
+
+ [TestMethod]
+ public async Task ShipmentsByOrder_FiltersToAccessibleShipmentsOnly()
+ {
+ var order = new Order { Id = "o1" };
+ _orderServiceMock.Setup(s => s.GetOrderById("o1")).ReturnsAsync(order);
+
+ var accessibleShipment = new Shipment { Id = "s1", OrderId = "o1", CreatedOnUtc = DateTime.UtcNow };
+ var deniedShipment = new Shipment { Id = "s2", OrderId = "o1", CreatedOnUtc = DateTime.UtcNow.AddMinutes(1) };
+ _shipmentServiceMock.Setup(s => s.GetShipmentsByOrder("o1"))
+ .ReturnsAsync((IList<Shipment>)new List<Shipment> { accessibleShipment, deniedShipment });
+
+ _scopeMock.Setup(s => s.HasAccess(accessibleShipment)).ReturnsAsync(true);
+ _scopeMock.Setup(s => s.HasAccess(deniedShipment)).ReturnsAsync(false);
+
+ _shipmentViewModelServiceMock
+ .Setup(v => v.PrepareShipmentModel(accessibleShipment, false, false))
+ .ReturnsAsync(new ShipmentModel { Id = "s1" });
+
+ var result = await _controller.ShipmentsByOrder("o1", new DataSourceRequest());
+
+ var jsonResult = result as JsonResult;
+ Assert.IsNotNull(jsonResult);
+ var gridModel = jsonResult.Value as DataSourceResult;
+ Assert.IsNotNull(gridModel);
+ Assert.AreEqual(1, gridModel.Total);
+ var data = gridModel.Data as List<ShipmentModel>;
+ Assert.IsNotNull(data);
+ Assert.AreEqual(1, data.Count);
+ Assert.AreEqual("s1", data[0].Id);
+ _shipmentViewModelServiceMock.Verify(v => v.PrepareShipmentModel(deniedShipment, false, false), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ShipmentsItemsByShipmentId_DeniedAccess_Throws()
+ {
+ var shipment = new Shipment { Id = "s1", OrderId = "o1" };
+ _shipmentServiceMock.Setup(s => s.GetShipmentById("s1")).ReturnsAsync(shipment);
+ _scopeMock.Setup(s => s.HasAccess(shipment)).ReturnsAsync(false);
+
+ await Assert.ThrowsExactlyAsync<ArgumentException>(() =>
+ _controller.ShipmentsItemsByShipmentId("s1", new DataSourceRequest()));
+ }
+}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.cs
new file mode 100644
index 000000000..844c1958a
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.cs
@@ -0,0 +1,150 @@
+using Grand.Business.Core.Commands.Checkout.Shipping;
+using Grand.Business.Core.Interfaces.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Pdf;
+using Grand.Domain.Orders;
+using Grand.Domain.Permissions;
+using Grand.Domain.Shipping;
+using Grand.Infrastructure;
+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.Extensions;
+using Grand.Web.Common.Filters;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+[PermissionAuthorize(PermissionSystemName.Shipments)]
+[AutoValidateAntiforgeryToken]
+public abstract class BaseShipmentController(
+ IShipmentViewModelService shipmentViewModelService,
+ IOrderService orderService,
+ ITranslationService translationService,
+ IContextAccessor contextAccessor,
+ IPdfService pdfService,
+ IShipmentService shipmentService,
+ IDateTimeService dateTimeService,
+ IMediator mediator,
+ IAdminDataScope<Shipment> scope)
+ : BaseController
+{
+ // Exposed for host-specific concrete subclasses (Admin's EditUserFields action needs these
+ // same fields — primary-constructor parameters aren't visible to derived classes by name in
+ // C#).
+ protected IShipmentViewModelService ShipmentViewModelService => shipmentViewModelService;
+ protected IOrderService OrderService => orderService;
+ protected ITranslationService TranslationService => translationService;
+ protected IContextAccessor ContextAccessor => contextAccessor;
+ protected IPdfService PdfService => pdfService;
+ protected IShipmentService ShipmentService => shipmentService;
+ protected IDateTimeService DateTimeService => dateTimeService;
+ protected IMediator Mediator => mediator;
+ protected IAdminDataScope<Shipment> Scope => scope;
+
+ /// <summary>DRY replacement for the repeated "load shipment, redirect to List if not found or
+ /// not authorized" pattern found in all 3 original controllers. Not a behavior change — every
+ /// call site below still individually returns RedirectToAction("List") exactly as the
+ /// originals did.</summary>
+ protected async Task<(Shipment shipment, IActionResult denied)> LoadAuthorizedShipment(string id)
+ {
+ var shipment = await shipmentService.GetShipmentById(id);
+ if (shipment == null) return (null, RedirectToAction("List"));
+ if (!await scope.HasAccess(shipment)) return (null, RedirectToAction("List"));
+ return (shipment, null);
+ }
+
+ #region Shipments
+
+ public async Task<IActionResult> List()
+ {
+ var model = await shipmentViewModelService.PrepareShipmentListModel();
+ return View(model);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.List)]
+ [HttpPost]
+ public async Task<IActionResult> ShipmentListSelect(DataSourceRequest command, ShipmentListModel model)
+ {
+ if (scope.DefaultStoreId is not null) model.StoreId = scope.DefaultStoreId;
+ if (scope.DefaultVendorId is not null) model.VendorId = scope.DefaultVendorId;
+
+ var shipments = await shipmentViewModelService.PrepareShipments(model, command.Page, command.PageSize);
+ var items = new List<ShipmentModel>();
+ foreach (var item in shipments.shipments)
+ items.Add(await shipmentViewModelService.PrepareShipmentModel(item, false));
+
+ var gridModel = new DataSourceResult {
+ Data = items,
+ Total = shipments.totalCount
+ };
+ return Json(gridModel);
+ }
+
+ /// <summary>Filters per-shipment via scope.HasAccess rather than gating on the parent order.
+ /// Admin: GlobalAdminDataScope.HasAccess is always true, so this is a no-op filter — matches
+ /// Admin's original, which had no check at all. Store: every shipment under a given order
+ /// always shares that order's StoreId (PrepareShipment always sets StoreId = order.StoreId,
+ /// see Task 3 Step 5), so per-shipment filtering produces the same user-visible result as
+ /// Store's original whole-order Content("") denial, with no possible mixed-store shipment set
+ /// under one order. Vendor: this is the literal mechanical equivalent of Vendor's original
+ /// per-shipment HasAccessToShipment loop.</summary>
+ [PermissionAuthorizeAction(PermissionActionName.List)]
+ [HttpPost]
+ public async Task<IActionResult> ShipmentsByOrder(string orderId, DataSourceRequest command)
+ {
+ var order = await orderService.GetOrderById(orderId);
+ if (order == null || order.Deleted)
+ throw new ArgumentException("No order found with the specified id");
+
+ //shipments
+ var shipmentModels = new List<ShipmentModel>();
+ var shipments = (await shipmentService.GetShipmentsByOrder(orderId))
+ .OrderBy(s => s.CreatedOnUtc)
+ .ToList();
+ var accessibleShipments = new List<Shipment>();
+ foreach (var shipment in shipments)
+ if (await scope.HasAccess(shipment))
+ accessibleShipments.Add(shipment);
+
+ foreach (var shipment in accessibleShipments)
+ shipmentModels.Add(await shipmentViewModelService.PrepareShipmentModel(shipment, false));
+
+ var gridModel = new DataSourceResult {
+ Data = shipmentModels,
+ Total = shipmentModels.Count
+ };
+ return Json(gridModel);
+ }
+
+ /// <summary>Deliberate, disclosed behavior change for Store only: Store's original returned a
+ /// soft Content("") on a store mismatch; Admin/Vendor's originals both threw
+ /// ArgumentException. Unified on the throwing form (2 of 3 hosts' original shape) rather than
+ /// using LoadAuthorizedShipment (which redirects — wrong fit for a JSON-grid endpoint). Flag
+ /// this explicitly in this task's commit message and for the final review.</summary>
+ [PermissionAuthorizeAction(PermissionActionName.List)]
+ [HttpPost]
+ public async Task<IActionResult> ShipmentsItemsByShipmentId(string shipmentId, DataSourceRequest command)
+ {
+ var shipment = await shipmentService.GetShipmentById(shipmentId) ?? throw new ArgumentException("No shipment found with the specified id");
+ if (!await scope.HasAccess(shipment))
+ throw new ArgumentException("No shipment found with the specified id");
+ var order = await orderService.GetOrderById(shipment.OrderId) ?? throw new ArgumentException("No order found with the specified id");
+
+ //shipments
+ var shipmentModel = await shipmentViewModelService.PrepareShipmentModel(shipment, true);
+ var gridModel = new DataSourceResult {
+ Data = shipmentModel.Items,
+ Total = shipmentModel.Items.Count
+ };
+
+ return Json(gridModel);
+ }
+
+ #endregion
+}