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.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
fix(arch001): restore Store/Vendor EditUserFields via BaseShipmentController (C1)
KrzysztofPajak41218d49e861
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.csindex d599c1569..d2955608d 100644--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseShipmentControllerTests.cs@@ -4,6 +4,7 @@ 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.Common;using Grand.Domain.Localization;using Grand.Domain.Orders;using Grand.Domain.Shipping;@@ -52,6 +53,7 @@ public class BaseShipmentControllerTestsprivate Mock<IAdminDataScope<Shipment>> _scopeMock;private Mock<IAdminDataScope<Order>> _orderScopeMock;private Mock<IMediator> _mediatorMock;+ private Mock<IPdfService> _pdfServiceMock;[TestInitialize]public void Setup()@@ -71,7 +73,7 @@ public class BaseShipmentControllerTestsvar workContextMock = new Mock<IWorkContext>();workContextMock.Setup(w => w.WorkingLanguage).Returns(new Language { Id = "lang-1" });contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);- var pdfServiceMock = new Mock<IPdfService>();+ _pdfServiceMock = new Mock<IPdfService>();var dateTimeServiceMock = new Mock<IDateTimeService>();_mediatorMock = new Mock<IMediator>();@@ -80,7 +82,7 @@ public class BaseShipmentControllerTests_orderServiceMock.Object,translationServiceMock.Object,contextAccessorMock.Object,- pdfServiceMock.Object,+ _pdfServiceMock.Object,_shipmentServiceMock.Object,dateTimeServiceMock.Object,_mediatorMock.Object,@@ -634,6 +636,12 @@ public class BaseShipmentControllerTestsAssert.AreEqual("packagingslips.pdf", fileResult.FileDownloadName);_scopeMock.Verify(s => s.HasAccess(accessibleShipment), Times.Once);_scopeMock.Verify(s => s.HasAccess(deniedShipment), Times.Once);+ _pdfServiceMock.Verify(+ p => p.PrintPackagingSlipsToPdf(+ It.IsAny<Stream>(),+ It.Is<IList<Shipment>>(list => list.Count == 1 && list.Contains(accessibleShipment) && !list.Contains(deniedShipment)),+ It.IsAny<string>()),+ Times.Once);}[TestMethod]@@ -777,4 +785,40 @@ public class BaseShipmentControllerTestsAssert.AreEqual("", jsonResult.Value);_shipmentViewModelServiceMock.Verify(v => v.DeleteShipmentNote(shipment, "n1"), Times.Once);}++ [TestMethod]+ public async Task EditUserFields_Denied_RedirectsToList_UpdateShipmentNeverCalled()+ {+ _shipmentServiceMock.Setup(s => s.GetShipmentById("s1")).ReturnsAsync((Shipment)null);++ var result = await _controller.EditUserFields("s1", new ShipmentModel { Id = "s1" });++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ _shipmentServiceMock.Verify(s => s.UpdateShipment(It.IsAny<Shipment>()), Times.Never);+ }++ [TestMethod]+ public async Task EditUserFields_Authorized_UpdatesUserFieldsAndRedirectsToShipmentDetails()+ {+ var shipment = new Shipment { Id = "s1", OrderId = "o1" };+ _shipmentServiceMock.Setup(s => s.GetShipmentById("s1")).ReturnsAsync(shipment);+ _scopeMock.Setup(s => s.HasAccess(shipment)).ReturnsAsync(true);++ var userFields = new List<UserField> { new() { Key = "k1", Value = "v1" } };+ var model = new ShipmentModel { Id = "s1", UserFields = userFields };++ // SaveSelectedTabIndex() reads Request.Form; give it a well-formed empty form body.+ _controller.ControllerContext.HttpContext.Request.ContentType = "application/x-www-form-urlencoded";++ var result = await _controller.EditUserFields("s1", model);++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("ShipmentDetails", redirect.ActionName);+ Assert.AreEqual("s1", redirect.RouteValues["id"]);+ Assert.AreSame(userFields, shipment.UserFields);+ _shipmentServiceMock.Verify(s => s.UpdateShipment(shipment), Times.Once);+ }}diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreShipmentDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreShipmentDataScopeTests.csindex 3fc769762..9ba5e8f5f 100644--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreShipmentDataScopeTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreShipmentDataScopeTests.cs@@ -41,6 +41,20 @@ public class StoreShipmentDataScopeTestsAssert.IsFalse(await scope.HasAccess(null));}+ [TestMethod]+ public async Task HasAccess_EmptyStaffStoreIdAndEmptyEntityStoreId_False()+ {+ var scope = Build(string.Empty);+ Assert.IsFalse(await scope.HasAccess(new Shipment { StoreId = string.Empty }));+ }++ [TestMethod]+ public async Task HasAccess_NullStaffStoreIdAndNullEntityStoreId_False()+ {+ var scope = Build(null);+ Assert.IsFalse(await scope.HasAccess(new Shipment { StoreId = null }));+ }+[TestMethod]public void DefaultStoreId_ReturnsStaffStoreId(){diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/VendorShipmentDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/VendorShipmentDataScopeTests.csindex 030c44194..ffa3cea1d 100644--- a/src/Tests/Grand.Web.Admin.Tests/Controllers/VendorShipmentDataScopeTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/VendorShipmentDataScopeTests.cs@@ -41,6 +41,20 @@ public class VendorShipmentDataScopeTestsAssert.IsFalse(await scope.HasAccess(null));}+ [TestMethod]+ public async Task HasAccess_EmptyCurrentVendorIdAndEmptyEntityVendorId_False()+ {+ var scope = Build(string.Empty);+ Assert.IsFalse(await scope.HasAccess(new Shipment { VendorId = string.Empty }));+ }++ [TestMethod]+ public async Task HasAccess_NullCurrentVendorIdAndNullEntityVendorId_False()+ {+ var scope = Build(null);+ Assert.IsFalse(await scope.HasAccess(new Shipment { VendorId = null }));+ }+[TestMethod]public void FilterOrderItems_MixedVendorOrder_ReturnsOnlyOwnItems(){diff --git a/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs b/src/Web/Grand.Web.Admin/Controllers/ShipmentController.csindex eac3cbc0d..483fc6fd3 100644--- a/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/ShipmentController.cs@@ -4,14 +4,12 @@ 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.Admin.Extensions;using Grand.Web.AdminShared.Controllers;using Grand.Web.AdminShared.Interfaces;-using Grand.Web.AdminShared.Models.Orders;using Grand.Web.Common.Filters;using Grand.Web.Common.Security.Authorization;using Microsoft.AspNetCore.Mvc;@@ -39,22 +37,4 @@ public class ShipmentController(IAdminDataScope<Shipment> scope,IAdminDataScope<Order> orderScope): BaseShipmentController(shipmentViewModelService, orderService, translationService,- contextAccessor, pdfService, shipmentService, dateTimeService, mediator, scope, orderScope)-{- // Admin-exclusive action - not shared via BaseShipmentController per the consolidation spec.- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> EditUserFields(string id, ShipmentModel model)- {- var (shipment, denied) = await LoadAuthorizedShipment(id);- if (denied != null) return denied;-- shipment.UserFields = model.UserFields;- await ShipmentService.UpdateShipment(shipment);-- //selected tab- await SaveSelectedTabIndex();-- return RedirectToAction("ShipmentDetails", new { id = shipment.Id });- }-}+ contextAccessor, pdfService, shipmentService, dateTimeService, mediator, scope, orderScope);diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.csindex 5df1f1bf9..5193a2f16 100644--- a/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.cs+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseShipmentController.cs@@ -91,11 +91,11 @@ public abstract class BaseShipmentController(/// <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>+ /// always shares that order's StoreId (PrepareShipment always sets StoreId = order.StoreId),+ /// 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)@@ -124,11 +124,11 @@ public abstract class BaseShipmentController(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>+ /// <summary>Deliberate 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, since a+ /// redirect response is meaningless to the AJAX grid caller expecting JSON).</summary>[PermissionAuthorizeAction(PermissionActionName.List)][HttpPost]public async Task<IActionResult> ShipmentsItemsByShipmentId(string shipmentId, DataSourceRequest command)@@ -360,6 +360,24 @@ public abstract class BaseShipmentController(}}+ /// <summary>Shared across all 3 hosts: the "User fields" tab on ShipmentDetails.cshtml posts+ /// here with no host gating, so Store and Vendor need this action too, not just Admin.</summary>+ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> EditUserFields(string id, ShipmentModel model)+ {+ var (shipment, denied) = await LoadAuthorizedShipment(id);+ if (denied != null) return denied;++ shipment.UserFields = model.UserFields;+ await shipmentService.UpdateShipment(shipment);++ //selected tab+ await SaveSelectedTabIndex();++ return RedirectToAction("ShipmentDetails", new { id = shipment.Id });+ }+#endregion#region PDF export and bulk actions@@ -400,7 +418,7 @@ public abstract class BaseShipmentController(//ensure that we at least one shipment selectedif (shipments.totalCount == 0){- Error(translationService.GetResource("Admin.Orders.Shipments.NoShipmentsSelected"));+ Error(translationService.GetResource($"{scope.ResourceKeyPrefix}.Orders.Shipments.NoShipmentsSelected"));return RedirectToAction("List");}@@ -434,12 +452,13 @@ public abstract class BaseShipmentController(if (await scope.HasAccess(s))accessibleShipments.Add(s);- //ensure that we at least one shipment selected — checks the unfiltered count, matching- //all 3 originals' pre-existing (and slightly inconsistent) behavior; see the disclosed,- //not-fixed note below this method+ //ensure that we at least one shipment selected — checks the unfiltered count (not+ //accessibleShipments.Count) so a request that only names shipments the caller can't+ //access reports "no shipments selected" rather than silently producing an empty PDF,+ //matching all 3 originals' pre-existing (and slightly inconsistent) behaviorif (shipments.Count == 0){- Error(translationService.GetResource("Admin.Orders.Shipments.NoShipmentsSelected"));+ Error(translationService.GetResource($"{scope.ResourceKeyPrefix}.Orders.Shipments.NoShipmentsSelected"));return RedirectToAction("List");}diff --git a/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.cs b/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.csindex 9310c9829..32fcbaf95 100644--- a/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.cs+++ b/src/Web/Grand.Web.AdminShared/Interfaces/IAdminDataScope.cs@@ -54,7 +54,8 @@ public interface IAdminDataScope<TEntity>/// <summary>Order line items visible to the current host — e.g. Vendor sees only its own/// items within a mixed-vendor order. Identity (no filtering) for hosts with no such/// restriction (Admin, Store, and every non-Order entity). Only- /// <see cref="Grand.Web.AdminShared.Services.VendorOrderDataScope"/> overrides this. Lives on+ /// <see cref="Grand.Web.AdminShared.Services.VendorOrderDataScope"/> and+ /// <see cref="Grand.Web.AdminShared.Services.VendorShipmentDataScope"/> override this. Lives on/// the shared interface rather than a separate Order-only interface because/// IAdminDataScope<TEntity> is already the single per-host strategy object injected/// into BaseOrderController/OrderViewModelService — see ARCH-001 Order consolidation specdiff --git a/src/Web/Grand.Web.AdminShared/Services/StoreShipmentDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/StoreShipmentDataScope.csindex 6a6ffeb21..2d1684726 100644--- a/src/Web/Grand.Web.AdminShared/Services/StoreShipmentDataScope.cs+++ b/src/Web/Grand.Web.AdminShared/Services/StoreShipmentDataScope.cs@@ -13,13 +13,16 @@ namespace Grand.Web.AdminShared.Services;/// <c>LimitedToStores</c> list), so the generic class's <c>where TEntity : BaseEntity,/// IStoreLinkEntity</c> constraint doesn't apply. Mirrors Store's original controller's/// <c>shipment.StoreId != StaffStoreId</c> check, repeated at every action site in that file.-/// No <see cref="CanView" /> override: Store's original code has one uniform check for both-/// viewing and mutating, unlike Category/Product's loose/strict split.+/// No <see cref="IAdminDataScope{TEntity}.CanView" /> override: Store's original code has one+/// uniform check for both viewing and mutating, unlike Category/Product's loose/strict split —+/// <see cref="IAdminDataScope{TEntity}.CanView" /> is simply inherited from the interface+/// default, which delegates to <see cref="HasAccess" />./// </summary>public class StoreShipmentDataScope(IContextAccessor contextAccessor) : IAdminDataScope<Shipment>{public Task<bool> HasAccess(Shipment entity) =>Task.FromResult(entity is not null &&+ !string.IsNullOrEmpty(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&entity.StoreId == contextAccessor.WorkContext.CurrentCustomer.StaffStoreId);public string? DefaultStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;diff --git a/src/Web/Grand.Web.AdminShared/Services/VendorShipmentDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/VendorShipmentDataScope.csindex edaa95d3a..b51bce154 100644--- a/src/Web/Grand.Web.AdminShared/Services/VendorShipmentDataScope.cs+++ b/src/Web/Grand.Web.AdminShared/Services/VendorShipmentDataScope.cs@@ -24,6 +24,7 @@ public class VendorShipmentDataScope(IContextAccessor contextAccessor) : IAdminD{public Task<bool> HasAccess(Shipment entity) =>Task.FromResult(entity is not null &&+ !string.IsNullOrEmpty(contextAccessor.WorkContext.CurrentVendor.Id) &&entity.VendorId == contextAccessor.WorkContext.CurrentVendor.Id);public IEnumerable<OrderItem> FilterOrderItems(IEnumerable<OrderItem> orderItems) =>