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.

ARCH-001 Phase 13: Brand controller/service consolidation (Admin/Store) (#806)

Krzysztof Pajak4a4e96cb4e77
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseBrandControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseBrandControllerTests.cs
new file mode 100644
index 000000000..f8d2716c7
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseBrandControllerTests.cs
@@ -0,0 +1,454 @@
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Domain;
+using Grand.Domain.Catalog;
+using Grand.Domain.Stores;
+using Grand.Infrastructure.Mapper;
+using Grand.Mapping;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Mapper;
+using Grand.Web.AdminShared.Models.Catalog;
+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;
+
+// Characterization tests for the merged Brand access-check behavior (ARCH-001 Brand
+// consolidation). Parameterized over a mocked IAdminDataScope<Brand> instead of the two different
+// concrete access mechanisms Admin (none) and Store (AccessToEntityByStore) used before.
+[TestClass]
+public class BaseBrandControllerTests
+{
+ // BaseBrandController is abstract; this minimal subclass exists only so actions under test can
+ // be invoked directly. No EditWarningCheck override here (Task 3's tests exercise the base's
+ // no-op default; Task 6 adds a real override on the Store subclass) - the base's default is
+ // exercised.
+ private class TestBrandController(
+ IBrandViewModelService brandViewModelService,
+ IBrandService brandService,
+ IStoreService storeService,
+ ILanguageService languageService,
+ ITranslationService translationService,
+ IPictureViewModelService pictureViewModelService,
+ IAdminDataScope<Brand> scope)
+ : BaseBrandController(brandViewModelService, brandService, storeService, languageService,
+ translationService, pictureViewModelService, scope);
+
+ private TestBrandController _controller;
+ private Mock<IBrandService> _brandServiceMock;
+ private Mock<IBrandViewModelService> _brandViewModelServiceMock;
+ private Mock<IStoreService> _storeServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
+ private Mock<IAdminDataScope<Brand>> _scopeMock;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<BrandProfile>());
+ AutoMapperConfig.Init(mapperConfig);
+
+ _brandServiceMock = new Mock<IBrandService>();
+ _brandViewModelServiceMock = new Mock<IBrandViewModelService>();
+ _storeServiceMock = new Mock<IStoreService>();
+ _storeServiceMock.Setup(s => s.GetAllStores()).ReturnsAsync(new List<Store>());
+ _translationServiceMock = new Mock<ITranslationService>();
+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");
+
+ _scopeMock = new Mock<IAdminDataScope<Brand>>();
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+
+ var languageServiceMock = new Mock<ILanguageService>();
+ languageServiceMock.Setup(l => l.GetAllLanguages(true, It.IsAny<string>())).ReturnsAsync(new List<Grand.Domain.Localization.Language>());
+
+ _controller = new TestBrandController(
+ _brandViewModelServiceMock.Object,
+ _brandServiceMock.Object,
+ _storeServiceMock.Object,
+ languageServiceMock.Object,
+ _translationServiceMock.Object,
+ new Mock<IPictureViewModelService>().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 ListGet_GlobalScope_PopulatesAvailableStores()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ _storeServiceMock.Setup(s => s.GetAllStores())
+ .ReturnsAsync(new List<Store> { new() { Id = "s1", Shortcut = "Store 1" } });
+
+ var result = await _controller.List();
+
+ var view = result as ViewResult;
+ Assert.IsNotNull(view);
+ var model = (BrandListModel)view.Model;
+ // "All" placeholder + the one real store
+ Assert.AreEqual(2, model.AvailableStores.Count);
+ }
+
+ [TestMethod]
+ public async Task ListGet_StoreScope_SkipsAvailableStores()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+
+ var result = await _controller.List();
+
+ var view = result as ViewResult;
+ Assert.IsNotNull(view);
+ var model = (BrandListModel)view.Model;
+ Assert.AreEqual(0, model.AvailableStores.Count);
+ _storeServiceMock.Verify(s => s.GetAllStores(), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ListPost_ForcesScopeDefaultStoreIdOntoSearchModel()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ _brandServiceMock
+ .Setup(b => b.GetAllBrands(It.IsAny<string>(), "store-1", 0, 10, true))
+ .ReturnsAsync(new PagedList<Brand>(new List<Brand>(), 0, 10));
+
+ var model = new BrandListModel { SearchStoreId = "attacker-supplied-store" };
+ await _controller.List(new DataSourceRequest { Page = 1, PageSize = 10 }, model);
+
+ Assert.AreEqual("store-1", model.SearchStoreId);
+ }
+
+ [TestMethod]
+ public async Task ListPost_GlobalScope_LeavesSubmittedSearchStoreIdUntouched()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ _brandServiceMock
+ .Setup(b => b.GetAllBrands(It.IsAny<string>(), "admin-submitted-store", 0, 10, true))
+ .ReturnsAsync(new PagedList<Brand>(new List<Brand>(), 0, 10));
+
+ var model = new BrandListModel { SearchStoreId = "admin-submitted-store" };
+ await _controller.List(new DataSourceRequest { Page = 1, PageSize = 10 }, model);
+
+ Assert.AreEqual("admin-submitted-store", model.SearchStoreId);
+ }
+
+ // --- Edit (GET) --------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task EditGet_BrandNotFound_RedirectsToList()
+ {
+ _brandServiceMock.Setup(b => b.GetBrandById("missing")).ReturnsAsync((Brand)null);
+
+ var result = await _controller.Edit("missing");
+
+ var redirect = result as RedirectToActionResult;
+ Assert.IsNotNull(redirect);
+ Assert.AreEqual("List", redirect.ActionName);
+ _scopeMock.Verify(s => s.CanView(It.IsAny<Brand>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task EditGet_ScopeDeniesView_RedirectsToList()
+ {
+ var brand = new Brand { Id = "b1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.CanView(brand)).ReturnsAsync(false);
+
+ var result = await _controller.Edit("b1");
+
+ var redirect = result as RedirectToActionResult;
+ Assert.IsNotNull(redirect);
+ Assert.AreEqual("List", redirect.ActionName);
+ }
+
+ [TestMethod]
+ public async Task EditGet_ScopeAllowsView_ReturnsViewWithModel()
+ {
+ var brand = new Brand { Id = "b1", Name = "Acme" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.CanView(brand)).ReturnsAsync(true);
+
+ var result = await _controller.Edit("b1");
+
+ var view = result as ViewResult;
+ Assert.IsNotNull(view);
+ Assert.AreEqual("Acme", ((BrandModel)view.Model).Name);
+ }
+
+ // --- Edit (POST) -------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task EditPost_ScopeDeniesAccess_RedirectsToEdit()
+ {
+ var brand = new Brand { Id = "b1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(false);
+
+ var result = await _controller.Edit(new BrandModel { Id = "b1" }, false);
+
+ var redirect = result as RedirectToActionResult;
+ Assert.IsNotNull(redirect);
+ Assert.AreEqual("Edit", redirect.ActionName);
+ _brandViewModelServiceMock.Verify(v => v.UpdateBrandModel(It.IsAny<Brand>(), It.IsAny<BrandModel>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task EditPost_StoreScoped_ForcesModelStores()
+ {
+ var brand = new Brand { Id = "b1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(true);
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ _brandViewModelServiceMock
+ .Setup(v => v.UpdateBrandModel(brand, It.IsAny<BrandModel>()))
+ .ReturnsAsync(brand)
+ .Callback<Brand, BrandModel>((_, m) => CollectionAssert.AreEqual(new[] { "store-1" }, m.Stores));
+
+ await _controller.Edit(new BrandModel { Id = "b1" }, false);
+
+ _brandViewModelServiceMock.Verify(v => v.UpdateBrandModel(brand, It.IsAny<BrandModel>()), Times.Once);
+ }
+
+ // --- Delete --------------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task Delete_ScopeDeniesAccess_RedirectsToEditWithoutDeleting()
+ {
+ var brand = new Brand { Id = "b1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(false);
+
+ var result = await _controller.Delete("b1");
+
+ var redirect = result as RedirectToActionResult;
+ Assert.IsNotNull(redirect);
+ Assert.AreEqual("Edit", redirect.ActionName);
+ Assert.AreEqual("b1", redirect.RouteValues["id"]);
+ _brandViewModelServiceMock.Verify(v => v.DeleteBrand(It.IsAny<Brand>()), Times.Never);
+ }
+
+ // --- Create (POST) ------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task CreatePost_StoreScoped_ForcesModelStores()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ var inserted = new Brand { Id = "new-1" };
+ _brandViewModelServiceMock
+ .Setup(v => v.InsertBrandModel(It.IsAny<BrandModel>()))
+ .ReturnsAsync(inserted)
+ .Callback<BrandModel>(m => CollectionAssert.AreEqual(new[] { "store-1" }, m.Stores));
+
+ await _controller.Create(new BrandModel { Name = "N" }, false);
+
+ _brandViewModelServiceMock.Verify(v => v.InsertBrandModel(It.IsAny<BrandModel>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task CreatePost_GlobalScoped_LeavesModelStoresUntouched()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);
+ var inserted = new Brand { Id = "new-1" };
+ var submitted = new BrandModel { Name = "N", Stores = ["explicit-store"] };
+ _brandViewModelServiceMock
+ .Setup(v => v.InsertBrandModel(It.IsAny<BrandModel>()))
+ .ReturnsAsync(inserted)
+ .Callback<BrandModel>(m => CollectionAssert.AreEqual(new[] { "explicit-store" }, m.Stores));
+
+ await _controller.Create(submitted, false);
+
+ _brandViewModelServiceMock.Verify(v => v.InsertBrandModel(It.IsAny<BrandModel>()), Times.Once);
+ }
+
+ // --- PicturePopup --------------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task PicturePopupGet_ScopeDeniesAccess_ReturnsDeniedContent()
+ {
+ var brand = new Brand { Id = "b1", PictureId = "pic-1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(false);
+
+ var result = await _controller.PicturePopup("b1");
+
+ var content = result as ContentResult;
+ Assert.IsNotNull(content);
+ Assert.AreEqual("This is not your brand", content.Content);
+ }
+
+ [TestMethod]
+ public async Task PicturePopupGet_BrandHasNoPicture_ReturnsNotExistContent()
+ {
+ var brand = new Brand { Id = "b1", PictureId = null };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(true);
+
+ var result = await _controller.PicturePopup("b1");
+
+ var content = result as ContentResult;
+ Assert.IsNotNull(content);
+ Assert.AreEqual("Picture not exist", content.Content);
+ }
+
+ [TestMethod]
+ public async Task PicturePopupGet_BrandNotFound_ReturnsNotExistContent()
+ {
+ _brandServiceMock.Setup(b => b.GetBrandById("missing")).ReturnsAsync((Brand)null);
+
+ var result = await _controller.PicturePopup("missing");
+
+ var content = result as ContentResult;
+ Assert.IsNotNull(content);
+ Assert.AreEqual("Brand not exist", content.Content);
+ _scopeMock.Verify(s => s.HasAccess(It.IsAny<Brand>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task PicturePopupPost_ScopeDeniesAccess_ReturnsDeniedContent()
+ {
+ var brand = new Brand { Id = "b1", PictureId = "pic-1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(false);
+
+ var model = new Grand.Web.AdminShared.Models.Common.PictureModel { ObjectId = "b1", Id = "pic-1" };
+ var result = await _controller.PicturePopup(model);
+
+ var content = result as ContentResult;
+ Assert.IsNotNull(content);
+ Assert.AreEqual("This is not your brand", content.Content);
+ }
+
+ [TestMethod]
+ public async Task PicturePopupPost_BrandNotFound_ThrowsArgumentException()
+ {
+ _brandServiceMock.Setup(b => b.GetBrandById("missing")).ReturnsAsync((Brand)null);
+
+ var model = new Grand.Web.AdminShared.Models.Common.PictureModel { ObjectId = "missing", Id = "pic-1" };
+
+ var exception = await Assert.ThrowsExactlyAsync<ArgumentException>(
+ async () => await _controller.PicturePopup(model));
+
+ Assert.AreEqual("No brand found with the specified id", exception.Message);
+ }
+
+ [TestMethod]
+ public async Task PicturePopupPost_PictureIdMismatch_ThrowsArgumentException()
+ {
+ var brand = new Brand { Id = "b1", PictureId = "pic-1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(true);
+
+ var model = new Grand.Web.AdminShared.Models.Common.PictureModel { ObjectId = "b1", Id = "pic-2" };
+
+ var exception = await Assert.ThrowsExactlyAsync<ArgumentException>(
+ async () => await _controller.PicturePopup(model));
+
+ Assert.AreEqual("Picture ident doesn't fit with brand", exception.Message);
+ }
+
+ [TestMethod]
+ public async Task PicturePopupPost_ValidRequest_CallsUpdatePicture()
+ {
+ var pictureViewModelServiceMock = new Mock<IPictureViewModelService>();
+ var brand = new Brand { Id = "b1", PictureId = "pic-1" };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+ _scopeMock.Setup(s => s.HasAccess(brand)).ReturnsAsync(true);
+ pictureViewModelServiceMock.Setup(p => p.UpdatePicture(It.IsAny<Grand.Web.AdminShared.Models.Common.PictureModel>())).Returns(Task.CompletedTask);
+
+ var controller = new TestBrandController(
+ _brandViewModelServiceMock.Object, _brandServiceMock.Object, _storeServiceMock.Object,
+ new Mock<ILanguageService>().Object, _translationServiceMock.Object,
+ pictureViewModelServiceMock.Object, _scopeMock.Object);
+ controller.ControllerContext = _controller.ControllerContext;
+ controller.TempData = _controller.TempData;
+
+ var model = new Grand.Web.AdminShared.Models.Common.PictureModel { ObjectId = "b1", Id = "pic-1" };
+
+ var result = await controller.PicturePopup(model);
+
+ var content = result as ContentResult;
+ Assert.IsNotNull(content);
+ Assert.AreEqual("", content.Content);
+ pictureViewModelServiceMock.Verify(p => p.UpdatePicture(model), Times.Once);
+ }
+
+ // --- Export / Import -----------------------------------------------------------------------------
+
+ [TestMethod]
+ public async Task ExportXlsx_Success_ReturnsXlsxFile()
+ {
+ _brandServiceMock
+ .Setup(b => b.GetAllBrands("", "", 0, int.MaxValue, true))
+ .ReturnsAsync(new PagedList<Brand>(new List<Brand> { new() { Id = "b1" } }, 0, int.MaxValue));
+ var exportManagerMock = new Mock<Grand.Business.Core.Interfaces.ExportImport.IExportManager<Brand>>();
+ exportManagerMock.Setup(e => e.Export(It.IsAny<IEnumerable<Brand>>())).ReturnsAsync([1, 2, 3]);
+
+ var result = await _controller.ExportXlsx(exportManagerMock.Object);
+
+ var file = result as FileContentResult;
+ Assert.IsNotNull(file);
+ Assert.AreEqual("brands.xlsx", file.FileDownloadName);
+ }
+
+ [TestMethod]
+ public async Task ExportXlsx_StoreScoped_ScopesExportToDefaultStoreId()
+ {
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ _brandServiceMock
+ .Setup(b => b.GetAllBrands("", "store-1", 0, int.MaxValue, true))
+ .ReturnsAsync(new PagedList<Brand>(new List<Brand> { new() { Id = "b1" } }, 0, int.MaxValue));
+ var exportManagerMock = new Mock<Grand.Business.Core.Interfaces.ExportImport.IExportManager<Brand>>();
+ exportManagerMock.Setup(e => e.Export(It.IsAny<IEnumerable<Brand>>())).ReturnsAsync([1, 2, 3]);
+
+ var result = await _controller.ExportXlsx(exportManagerMock.Object);
+
+ var file = result as FileContentResult;
+ Assert.IsNotNull(file);
+ _brandServiceMock.Verify(b => b.GetAllBrands("", "store-1", 0, int.MaxValue, true), Times.Once);
+ _brandServiceMock.Verify(b => b.GetAllBrands("", "", 0, int.MaxValue, true), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task ExportXlsx_ExportThrows_ShowsErrorAndRedirectsToList()
+ {
+ _brandServiceMock
+ .Setup(b => b.GetAllBrands("", "", 0, int.MaxValue, true))
+ .ThrowsAsync(new InvalidOperationException("boom"));
+ var exportManagerMock = new Mock<Grand.Business.Core.Interfaces.ExportImport.IExportManager<Brand>>();
+
+ var result = await _controller.ExportXlsx(exportManagerMock.Object);
+
+ var redirect = result as RedirectToActionResult;
+ Assert.IsNotNull(redirect);
+ Assert.AreEqual("List", redirect.ActionName);
+ }
+
+ [TestMethod]
+ public async Task ImportFromXlsx_NoFile_ShowsErrorAndRedirectsToList()
+ {
+ var importManagerMock = new Mock<Grand.Business.Core.Interfaces.ExportImport.IImportManager<Grand.Business.Core.Dto.BrandDto>>();
+
+ var result = await _controller.ImportFromXlsx(null, importManagerMock.Object);
+
+ var redirect = result as RedirectToActionResult;
+ Assert.IsNotNull(redirect);
+ Assert.AreEqual("List", redirect.ActionName);
+ importManagerMock.Verify(i => i.Import(It.IsAny<Stream>()), Times.Never);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BrandControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BrandControllerTests.cs
new file mode 100644
index 000000000..9a95a23c6
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BrandControllerTests.cs
@@ -0,0 +1,30 @@
+using System.Reflection;
+using Grand.Web.Admin.Controllers;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class BrandControllerTests
+{
+ [TestMethod]
+ public void BrandController_IsThinSubclassOfBaseBrandController()
+ {
+ Assert.IsTrue(typeof(BrandController).IsSubclassOf(typeof(BaseBrandController)));
+ }
+
+ [TestMethod]
+ public void BrandController_HasRequiredHostAttributes()
+ {
+ var type = typeof(BrandController);
+ Assert.IsTrue(type.IsDefined(typeof(AreaAttribute), inherit: false), "[Area] missing");
+ Assert.IsTrue(type.IsDefined(typeof(AuthorizeAdminAttribute), inherit: false), "[AuthorizeAdmin] missing");
+ Assert.IsTrue(type.IsDefined(typeof(AuthorizeMenuAttribute), inherit: false), "[AuthorizeMenu] missing");
+
+ var area = type.GetCustomAttribute<AreaAttribute>()!;
+ Assert.AreEqual("Admin", area.RouteValue);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedBrandDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedBrandDataScopeTests.cs
new file mode 100644
index 000000000..0b75d2e49
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedBrandDataScopeTests.cs
@@ -0,0 +1,66 @@
+using Grand.Domain.Catalog;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Services;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class RoutedBrandDataScopeTests
+{
+ private static RoutedBrandDataScope Build(string area, out Mock<IAdminDataScope<Brand>> globalMock, out Mock<IAdminDataScope<Brand>> storeMock)
+ {
+ var httpContext = new DefaultHttpContext();
+ if (area != null)
+ httpContext.Request.RouteValues = new RouteValueDictionary { ["area"] = area };
+
+ var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
+ httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContext);
+
+ var global = new GlobalAdminDataScope<Brand>();
+ var store = new StoreAdminDataScope<Brand>(BuildContextAccessor());
+ globalMock = null;
+ storeMock = null;
+ return new RoutedBrandDataScope(httpContextAccessorMock.Object, global, store);
+ }
+
+ private static Grand.Infrastructure.IContextAccessor BuildContextAccessor()
+ {
+ var workContext = new Mock<Grand.Infrastructure.IWorkContext>();
+ workContext.Setup(w => w.CurrentCustomer).Returns(new Grand.Domain.Customers.Customer { StaffStoreId = "store-1" });
+ var contextAccessorMock = new Mock<Grand.Infrastructure.IContextAccessor>();
+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContext.Object);
+ return contextAccessorMock.Object;
+ }
+
+ [TestMethod]
+ public void DefaultStoreId_AdminArea_ResolvesToGlobalScope()
+ {
+ var routed = Build("Admin", out _, out _);
+ Assert.IsNull(routed.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public void DefaultStoreId_StoreArea_ResolvesToStoreScope()
+ {
+ var routed = Build("Store", out _, out _);
+ Assert.AreEqual("store-1", routed.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public void DefaultStoreId_VendorArea_ThrowsFailClosed()
+ {
+ var routed = Build("Vendor", out _, out _);
+ Assert.ThrowsExactly<InvalidOperationException>(() => _ = routed.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public void DefaultStoreId_MissingArea_ThrowsFailClosed()
+ {
+ var routed = Build(null, out _, out _);
+ Assert.ThrowsExactly<InvalidOperationException>(() => _ = routed.DefaultStoreId);
+ }
+}
diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/BrandControllerTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/BrandControllerTests.cs
new file mode 100644
index 000000000..f65ab43ab
--- /dev/null
+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/BrandControllerTests.cs
@@ -0,0 +1,142 @@
+using System.Reflection;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Domain.Catalog;
+using Grand.Infrastructure.Mapper;
+using Grand.Mapping;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Mapper;
+using Grand.Web.Common.Filters;
+using Grand.Web.Store.Controllers;
+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.Store.Tests.Controllers;
+
+[TestClass]
+public class BrandControllerTests
+{
+ [TestMethod]
+ public void BrandController_IsThinSubclassOfBaseBrandController()
+ {
+ Assert.IsTrue(typeof(BrandController).IsSubclassOf(typeof(BaseBrandController)));
+ }
+
+ [TestMethod]
+ public void BrandController_HasRequiredHostAttributes()
+ {
+ var type = typeof(BrandController);
+ Assert.IsTrue(type.IsDefined(typeof(AreaAttribute), inherit: false), "[Area] missing");
+ Assert.IsTrue(type.IsDefined(typeof(AuthorizeStoreAttribute), inherit: false), "[AuthorizeStore] missing");
+ Assert.IsTrue(type.IsDefined(typeof(AuthorizeMenuAttribute), inherit: false), "[AuthorizeMenu] missing");
+
+ var area = type.GetCustomAttribute<AreaAttribute>()!;
+ Assert.AreEqual("Store", area.RouteValue);
+ }
+
+ // --- EditWarningCheck ----------------------------------------------------------------------
+ //
+ // Characterization tests for BrandController.EditWarningCheck, the one hand-ported piece of
+ // business logic in the Brand consolidation (ARCH-001 Phase 13). Exercised indirectly through
+ // the public Edit(GET) action, since EditWarningCheck itself is protected.
+
+ [TestClass]
+ public class EditWarningCheckTests
+ {
+ private const string PermissionsResourceKey = "Admin.Catalog.Brands.Permissions";
+
+ private BrandController _controller;
+ private Mock<IBrandService> _brandServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
+ private Mock<IAdminDataScope<Brand>> _scopeMock;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<BrandProfile>());
+ AutoMapperConfig.Init(mapperConfig);
+
+ _brandServiceMock = new Mock<IBrandService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");
+
+ _scopeMock = new Mock<IAdminDataScope<Brand>>();
+ _scopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");
+ _scopeMock.Setup(s => s.CanView(It.IsAny<Brand>())).ReturnsAsync(true);
+
+ var languageServiceMock = new Mock<ILanguageService>();
+ languageServiceMock.Setup(l => l.GetAllLanguages(true, It.IsAny<string>()))
+ .ReturnsAsync(new List<Grand.Domain.Localization.Language>());
+
+ _controller = new BrandController(
+ new Mock<IBrandViewModelService>().Object,
+ _brandServiceMock.Object,
+ new Mock<IStoreService>().Object,
+ languageServiceMock.Object,
+ _translationServiceMock.Object,
+ new Mock<IPictureViewModelService>().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);
+ }
+
+ private bool WarningWasRaised()
+ {
+ return _controller.TempData["grand.notifications.Warning"] is List<string> warnings
+ && warnings.Contains("resource");
+ }
+
+ [TestMethod]
+ public async Task EditGet_NotLimitedToStores_RaisesPermissionsWarning()
+ {
+ var brand = new Brand { Id = "b1", LimitedToStores = false, Stores = [] };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+
+ await _controller.Edit("b1");
+
+ Assert.IsTrue(WarningWasRaised());
+ _translationServiceMock.Verify(t => t.GetResource(PermissionsResourceKey), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task EditGet_LimitedToStores_ContainsDefaultStore_MultipleStores_RaisesPermissionsWarning()
+ {
+ var brand = new Brand { Id = "b1", LimitedToStores = true, Stores = ["store-1", "store-2"] };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+
+ await _controller.Edit("b1");
+
+ Assert.IsTrue(WarningWasRaised());
+ _translationServiceMock.Verify(t => t.GetResource(PermissionsResourceKey), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task EditGet_LimitedToStores_ContainsDefaultStore_SingleStore_DoesNotRaiseWarning()
+ {
+ var brand = new Brand { Id = "b1", LimitedToStores = true, Stores = ["store-1"] };
+ _brandServiceMock.Setup(b => b.GetBrandById("b1")).ReturnsAsync(brand);
+
+ await _controller.Edit("b1");
+
+ Assert.IsFalse(WarningWasRaised());
+ _translationServiceMock.Verify(t => t.GetResource(PermissionsResourceKey), Times.Never);
+ }
+ }
+}
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
deleted file mode 100644
index 4f8dc6e9d..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
+++ /dev/null
@@ -1,27 +0,0 @@
-@model BrandModel
-<vc:admin-widget widget-zone="brand_discounts_top" additional-data="Model"/>
-@{
- if (Model.AvailableDiscounts is { Count: > 0 })
- {
- <div class="mt-checkbox-list">
- @foreach (var discount in Model.AvailableDiscounts)
- {
- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">
- <input type="checkbox" name="SelectedDiscountIds" value="@discount.Id"
- @if (Model.SelectedDiscountIds != null && Model.SelectedDiscountIds.Contains(discount.Id))
- {
- <text> checked="checked" </text>
- }/>@discount.Name
- <div class="control__indicator"></div>
- </label>
- }
- </div>
- }
- else
- {
- <div class="note note-info">
- @Html.Raw(Loc["Admin.Catalog.Brands.Discounts.NoDiscounts"])
- </div>
- }
-}
-<vc:admin-widget widget-zone="brand_discounts_bottom" additional-data="Model"/>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
deleted file mode 100644
index 9de6e4304..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
+++ /dev/null
@@ -1,80 +0,0 @@
-@model BrandModel
-@inject AdminAreaSettings adminAreaSettings
-@if (!string.IsNullOrEmpty(Model.Id))
-{
- <div class="panel panel-default">
- <vc:admin-widget widget-zone="brand_details_documents_top" additional-data="Model"/>
- <div class="panel-body">
- <div id="brand-documents-grid"></div>
- </div>
- <div class="panel-footer">
- <button type="button" class="k-button" onclick="location.href='@Url.Action("CreateDocument", "Document", new { ObjectId = Model.Id, Reference = (int)Reference.Brand, area = Constants.AreaAdmin })'"><i class="fa fa-plus"></i>&nbsp;@Loc["Admin.Marketing.Document.Add"]</button>
- </div>
- <vc:admin-widget widget-zone="brand_details_documents_bottom" additional-data="Model"/>
- </div>
-
- <script>
- $(document).ready(function () {
- $("#brand-documents-grid").kendoGrid({
- dataSource: {
- transport: {
- read: {
- url: "@Html.Raw(Url.Action("ListDocuments", "Document", new { reference = (int)Reference.Brand, ObjectId = Model.Id, StatusId = -1, area = Constants.AreaAdmin }))",
- type: "POST",
- dataType: "json",
- data: addAntiForgeryToken
- },
- },
- schema: {
- data: "Data",
- total: "Total",
- errors: "Errors",
- },
- error: function(e) {
- display_kendoui_grid_error(e);
- // Cancel the changes
- this.cancelChanges();
- },
- pageSize: @(adminAreaSettings.DefaultGridPageSize),
- serverPaging: true,
- serverFiltering: true,
- serverSorting: true
- },
- autoBind: false,
- pageable: {
- refresh: true,
- pageSizes: [@(adminAreaSettings.GridPageSizes)]
- },
- editable: {
- confirmation: true,
- mode: "inline"
- },
- scrollable: false,
- columns: [{
- field: "Number",
- title: "@Loc["Admin.Documents.Document.Fields.Number"]",
- template: '<a class="k-link" href="@Url.Action("EditDocument", "Document", new { area = Constants.AreaAdmin })/#=Id#">#=kendo.htmlEncode(Number)#</a>',
- },
- {
- field: "Name",
- title: "@Loc["Admin.Documents.Document.Fields.Name"]",
- template: '<a class="k-link" href="@Url.Action("EditDocument", "Document", new { area = Constants.AreaAdmin })/#=Id#">#=kendo.htmlEncode(Name)#</a>',
- }, {
- field: "Published",
- title: "@Loc["Admin.Documents.Document.Fields.Published"]",
- width: 100,
- minScreenWidth: 500,
- headerAttributes: { style: "text-align:center" },
- attributes: { style: "text-align:center" },
- template: '# if(Published) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'
- }]
- });
- });
- </script>
-}
-else
-{
- <div class="note note-info">
- @Loc["Admin.Catalog.SaveBeforeEdit"]
- </div>
-}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabSeo.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
deleted file mode 100644
index 5e6df1966..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
+++ /dev/null
@@ -1,73 +0,0 @@
-@using Microsoft.AspNetCore.Mvc.Razor
-@model BrandModel
-
-@{
- Func<int, HelperResult>
- template = @<div class="form-body">
- <div class="form-group">
- <admin-label asp-for="@Model.Locales[item].MetaKeywords"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="@Model.Locales[item].MetaKeywords"/>
- <span asp-validation-for="@Model.Locales[item].MetaKeywords"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="@Model.Locales[item].MetaDescription"/>
- <div class="col-md-9 col-sm-9">
- <admin-textarea asp-for="@Model.Locales[item].MetaDescription"></admin-textarea>
- <span asp-validation-for="@Model.Locales[item].MetaDescription"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="@Model.Locales[item].MetaTitle"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="@Model.Locales[item].MetaTitle"/>
- <span asp-validation-for="@Model.Locales[item].MetaTitle"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="@Model.Locales[item].SeName"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="@Model.Locales[item].SeName"/>
- <span asp-validation-for="@Model.Locales[item].SeName"></span>
- </div>
- </div>
- <input asp-for="@Model.Locales[item].LanguageId" type="hidden"/>
- </div>;
-}
-
-<div class="form-horizontal">
- <vc:admin-widget widget-zone="brand_details_seo_top" additional-data="Model"/>
- <localized-editor localized-template="@template" name="brand-seo-localized" language-ids="@Model.Locales.Select(c => c.LanguageId).ToList()">
- <div class="form-body">
- <div class="form-group">
- <admin-label asp-for="MetaKeywords"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="MetaKeywords"/>
- <span asp-validation-for="MetaKeywords"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="MetaDescription"/>
- <div class="col-md-9 col-sm-9">
- <admin-textarea asp-for="MetaDescription"></admin-textarea>
- <span asp-validation-for="MetaDescription"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="MetaTitle"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="MetaTitle"/>
- <span asp-validation-for="MetaTitle"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="SeName"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="SeName"/>
- <span asp-validation-for="SeName"></span>
- </div>
- </div>
- </div>
- </localized-editor>
-</div>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.DetailsButtons.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.DetailsButtons.cshtml
new file mode 100644
index 000000000..7fc61a1a1
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.DetailsButtons.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_details_buttons" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.DetailsButtonsCreate.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.DetailsButtonsCreate.cshtml
new file mode 100644
index 000000000..3b3092ade
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.DetailsButtonsCreate.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_details_buttons" additional-data="null"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Discounts.Bottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Discounts.Bottom.cshtml
new file mode 100644
index 000000000..3c792a7eb
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Discounts.Bottom.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_discounts_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Discounts.Top.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Discounts.Top.cshtml
new file mode 100644
index 000000000..cbcb3a037
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Discounts.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_discounts_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Documents.Bottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Documents.Bottom.cshtml
new file mode 100644
index 000000000..e36625c06
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Documents.Bottom.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_details_documents_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Documents.Top.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Documents.Top.cshtml
new file mode 100644
index 000000000..7e7169404
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Documents.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_details_documents_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.SEO.Top.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.SEO.Top.cshtml
new file mode 100644
index 000000000..cbdca070d
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.SEO.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_details_seo_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Tabs.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Tabs.cshtml
new file mode 100644
index 000000000..2f26ae9fd
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/WidgetZone.Tabs.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:admin-widget widget-zone="brand_details_tabs" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Controllers/BrandController.cs b/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
index fb242820f..688cf0dda 100644
--- a/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/BrandController.cs
@@ -1,314 +1,33 @@
-using Grand.Business.Core.Dto;
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
-using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Domain.Catalog;
-using Grand.Domain.Permissions;
-using Grand.Web.AdminShared.Extensions.Mapping;
+using Grand.Web.Admin.Extensions;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Interfaces;
-using Grand.Web.AdminShared.Models.Catalog;
-using Grand.Web.AdminShared.Models.Common;
-using Grand.Web.Common.DataSource;
using Grand.Web.Common.Filters;
-using Grand.Web.Common.Security.Authorization;
+using Grand.Web.Common.Localization;
using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.Mvc.Rendering;
namespace Grand.Web.Admin.Controllers;
-[PermissionAuthorize(PermissionSystemName.Brands)]
-public class BrandController : BaseAdminController
-{
- #region Constructors
-
- public BrandController(
- IBrandViewModelService brandViewModelService,
- IBrandService brandService,
- IStoreService storeService,
- ILanguageService languageService,
- ITranslationService translationService,
- IPictureViewModelService pictureViewModelService)
- {
- _brandViewModelService = brandViewModelService;
- _brandService = brandService;
- _storeService = storeService;
- _languageService = languageService;
- _translationService = translationService;
- _pictureViewModelService = pictureViewModelService;
- }
-
- #endregion
-
- #region Fields
-
- private readonly IBrandViewModelService _brandViewModelService;
- private readonly IBrandService _brandService;
- private readonly IStoreService _storeService;
- private readonly ILanguageService _languageService;
- private readonly ITranslationService _translationService;
- private readonly IPictureViewModelService _pictureViewModelService;
-
- #endregion
-
- #region List
-
- public IActionResult Index()
- {
- return RedirectToAction("List");
- }
-
- public async Task<IActionResult> List()
- {
- var model = new BrandListModel();
- model.AvailableStores.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
- foreach (var s in (await _storeService.GetAllStores()))
- model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.List)]
- [HttpPost]
- public async Task<IActionResult> List(DataSourceRequest command, BrandListModel model)
- {
- var brands = await _brandService.GetAllBrands(model.SearchBrandName,
- model.SearchStoreId, command.Page - 1, command.PageSize, true);
- var gridModel = new DataSourceResult {
- Data = brands.Select(x => x.ToModel()),
- Total = brands.TotalCount
- };
-
- return Json(gridModel);
- }
-
- #endregion
-
- #region Create / Edit / Delete
-
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public async Task<IActionResult> Create([FromServices] CatalogSettings catalogSettings)
- {
- var model = new BrandModel();
- //locales
- await AddLocales(_languageService, model.Locales);
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, null, true);
- //default values
- model.PageSize = catalogSettings.DefaultPageSize;
- model.PageSizeOptions = catalogSettings.DefaultPageSizeOptions;
- model.Published = true;
- model.AllowCustomersToSelectPageSize = true;
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- public async Task<IActionResult> Create(BrandModel model, bool continueEditing)
- {
- if (ModelState.IsValid)
- {
- var collection = await _brandViewModelService.InsertBrandModel(model);
- Success(_translationService.GetResource("Admin.Catalog.Brands.Added"));
- return continueEditing ? RedirectToAction("Edit", new { id = collection.Id }) : RedirectToAction("List");
- }
-
- //If we got this far, something failed, redisplay form
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, null, true);
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Preview)]
- public async Task<IActionResult> Edit(string id)
- {
- var brand = await _brandService.GetBrandById(id);
- if (brand == null)
- //No collection found with the specified id
- return RedirectToAction("List");
-
- var model = brand.ToModel();
- //locales
- await AddLocales(_languageService, model.Locales, (locale, languageId) =>
- {
- locale.Name = brand.GetTranslation(x => x.Name, languageId, false);
- locale.Description = brand.GetTranslation(x => x.Description, languageId, false);
- locale.BottomDescription = brand.GetTranslation(x => x.BottomDescription, languageId, false);
- locale.MetaKeywords = brand.GetTranslation(x => x.MetaKeywords, languageId, false);
- locale.MetaDescription = brand.GetTranslation(x => x.MetaDescription, languageId, false);
- locale.MetaTitle = brand.GetTranslation(x => x.MetaTitle, languageId, false);
- locale.SeName = brand.GetSeName(languageId, false);
- });
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, brand, false);
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- public async Task<IActionResult> Edit(BrandModel model, bool continueEditing)
- {
- var brand = await _brandService.GetBrandById(model.Id);
- if (brand == null)
- //No collection found with the specified id
- return RedirectToAction("List");
-
- if (ModelState.IsValid)
- {
- brand = await _brandViewModelService.UpdateBrandModel(brand, model);
- Success(_translationService.GetResource("Admin.Catalog.Brands.Updated"));
-
- if (continueEditing)
- {
- //selected tab
- await SaveSelectedTabIndex();
-
- return RedirectToAction("Edit", new { id = brand.Id });
- }
-
- return RedirectToAction("List");
- }
-
-
- //If we got this far, something failed, redisplay form
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, brand, true);
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Delete)]
- [HttpPost]
- public async Task<IActionResult> Delete(string id)
- {
- var brand = await _brandService.GetBrandById(id);
- if (brand == null)
- //No collection found with the specified id
- return RedirectToAction("List");
-
- if (ModelState.IsValid)
- {
- await _brandViewModelService.DeleteBrand(brand);
-
- Success(_translationService.GetResource("Admin.Catalog.Brands.Deleted"));
- return RedirectToAction("List");
- }
-
- Error(ModelState);
- return RedirectToAction("Edit", new { id = brand.Id });
- }
-
- #endregion
-
- #region Picture
-
- [PermissionAuthorizeAction(PermissionActionName.Preview)]
- public async Task<IActionResult> PicturePopup(string brandId)
- {
- var brand = await _brandService.GetBrandById(brandId);
- if (brand == null)
- return Content("Brand not exist");
-
- if (string.IsNullOrEmpty(brand.PictureId))
- return Content("Picture not exist");
-
- return View("Partials/PicturePopup",
- await _pictureViewModelService.PreparePictureModel(brand.PictureId, brand.Id));
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- [HttpPost]
- public async Task<IActionResult> PicturePopup(PictureModel model)
- {
- if (ModelState.IsValid)
- {
- var brand = await _brandService.GetBrandById(model.ObjectId);
- if (brand == null)
- throw new ArgumentException("No brand found with the specified id");
-
- if (string.IsNullOrEmpty(brand.PictureId))
- throw new ArgumentException("No picture found with the specified id");
-
- if (brand.PictureId != model.Id)
- throw new ArgumentException("Picture ident doesn't fit with brand");
-
- await _pictureViewModelService.UpdatePicture(model);
-
- return Content("");
- }
-
- Error(ModelState);
-
- return View("Partials/PicturePopup", model);
- }
-
- #endregion
-
- #region Export / Import
-
- [PermissionAuthorizeAction(PermissionActionName.Export)]
- public async Task<IActionResult> ExportXlsx([FromServices] IExportManager<Brand> exportManager)
- {
- try
- {
- var bytes = await exportManager.Export(await _brandService.GetAllBrands(brandName: "", storeId: "", showHidden: true));
- return File(bytes, "text/xls", "brands.xlsx");
- }
- catch (Exception exc)
- {
- Error(exc);
- return RedirectToAction("List");
- }
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Import)]
- [HttpPost]
- public async Task<IActionResult> ImportFromXlsx(IFormFile importexcelfile,
- [FromServices] IImportManager<BrandDto> importManager)
- {
- try
- {
- if (importexcelfile is { Length: > 0 })
- {
- await importManager.Import(importexcelfile.OpenReadStream());
- }
- else
- {
- Error(_translationService.GetResource("Admin.Common.UploadFile"));
- return RedirectToAction("List");
- }
-
- Success(_translationService.GetResource("Admin.Catalog.Brands.Imported"));
- return RedirectToAction("List");
- }
- catch (Exception exc)
- {
- Error(exc);
- return RedirectToAction("List");
- }
- }
-
- #endregion
-}
\ No newline at end of file
+// Reduced to a thin subclass of BaseBrandController (ARCH-001 Brand consolidation). All regions of
+// behavior live in the shared base; this class only supplies Admin's DI wiring plus the attributes
+// that used to arrive transitively via BaseAdminController - BaseBrandController can't inherit any
+// single host's base controller (it's shared across Admin/Store, each with a different
+// [Area]/[Authorize*] pair), so each subclass restates its own host's attribute set explicitly.
+// Same pattern as CategoryController/CollectionController (see those files).
+[AuthorizeAdmin]
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaAdmin)]
+[AuthorizeMenu]
+public class BrandController(
+ IBrandViewModelService brandViewModelService,
+ IBrandService brandService,
+ IStoreService storeService,
+ ILanguageService languageService,
+ ITranslationService translationService,
+ IPictureViewModelService pictureViewModelService,
+ IAdminDataScope<Brand> scope)
+ : BaseBrandController(brandViewModelService, brandService, storeService, languageService,
+ translationService, pictureViewModelService, scope);
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseBrandController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseBrandController.cs
new file mode 100644
index 000000000..812386f33
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseBrandController.cs
@@ -0,0 +1,292 @@
+using Grand.Business.Core.Dto;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Catalog.Brands;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Business.Core.Interfaces.ExportImport;
+using Grand.Domain.Catalog;
+using Grand.Domain.Permissions;
+using Grand.Web.AdminShared.Extensions.Mapping;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Models.Catalog;
+using Grand.Web.AdminShared.Models.Common;
+using Grand.Web.Common.Controllers;
+using Grand.Web.Common.DataSource;
+using Grand.Web.Common.Filters;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Rendering;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+// [AutoValidateAntiforgeryToken] is restated on each concrete host subclass (Admin/Store
+// BrandController) too - ASP.NET Core resolves filters from the concrete controller's full type
+// hierarchy at runtime, so every real endpoint is already protected. It's added here as well,
+// mirroring BaseProductController/BaseCategoryController/BaseCollectionController, so static
+// analysis that doesn't follow the attribute across a base/derived project boundary has something
+// to see in the same file as the actions.
+[PermissionAuthorize(PermissionSystemName.Brands)]
+[AutoValidateAntiforgeryToken]
+public abstract class BaseBrandController(
+ IBrandViewModelService brandViewModelService,
+ IBrandService brandService,
+ IStoreService storeService,
+ ILanguageService languageService,
+ ITranslationService translationService,
+ IPictureViewModelService pictureViewModelService,
+ IAdminDataScope<Brand> scope)
+ : BaseController
+{
+ /// <summary>Hook for host-specific UI-copy warnings that aren't access-scope decisions.
+ /// Overridden by the Store subclass (Task 6); no-op everywhere else. Mirrors
+ /// BaseCategoryController.EditWarningCheck/BaseCollectionController's equivalent.</summary>
+ protected virtual void EditWarningCheck(Brand brand) { }
+
+ // Exposed for host subclasses: primary-constructor parameters are not visible to derived
+ // classes by name in C#, so Store's EditWarningCheck override needs these.
+ protected ITranslationService TranslationService => translationService;
+ protected IAdminDataScope<Brand> Scope => scope;
+
+ #region List
+
+ public IActionResult Index() => RedirectToAction("List");
+
+ public async Task<IActionResult> List()
+ {
+ var model = new BrandListModel();
+ // Admin only: Store never had this dropdown (it's implicitly single-store).
+ // ShowStoreSelector can't gate this - it's true on both Global and Store scopes.
+ if (scope.DefaultStoreId is null)
+ {
+ model.AvailableStores.Add(new SelectListItem { Text = translationService.GetResource("Admin.Common.All"), Value = "" });
+ foreach (var s in await storeService.GetAllStores())
+ {
+ model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
+ }
+ }
+
+ return View(model);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.List)]
+ [HttpPost]
+ public async Task<IActionResult> List(DataSourceRequest command, BrandListModel model)
+ {
+ if (scope.DefaultStoreId is not null) model.SearchStoreId = scope.DefaultStoreId;
+ var brands = await brandService.GetAllBrands(model.SearchBrandName,
+ model.SearchStoreId, command.Page - 1, command.PageSize, true);
+ var gridModel = new DataSourceResult {
+ Data = brands.Select(x => x.ToModel()),
+ Total = brands.TotalCount
+ };
+
+ return Json(gridModel);
+ }
+
+ #endregion
+
+ #region Create / Edit / Delete
+
+ [PermissionAuthorizeAction(PermissionActionName.Create)]
+ public async Task<IActionResult> Create([FromServices] CatalogSettings catalogSettings)
+ {
+ var model = new BrandModel();
+ await AddLocales(languageService, model.Locales);
+ await brandViewModelService.PrepareLayoutsModel(model);
+ await brandViewModelService.PrepareDiscountModel(model, null, true);
+ model.PageSize = catalogSettings.DefaultPageSize;
+ model.PageSizeOptions = catalogSettings.DefaultPageSizeOptions;
+ model.Published = true;
+ model.AllowCustomersToSelectPageSize = true;
+ brandViewModelService.PrepareSortOptionsModel(model);
+
+ return View(model);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ [HttpPost]
+ [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
+ public async Task<IActionResult> Create(BrandModel model, bool continueEditing)
+ {
+ if (ModelState.IsValid)
+ {
+ if (scope.DefaultStoreId is not null) model.Stores = [scope.DefaultStoreId];
+ var brand = await brandViewModelService.InsertBrandModel(model);
+ Success(translationService.GetResource("Admin.Catalog.Brands.Added"));
+ return continueEditing ? RedirectToAction("Edit", new { id = brand.Id }) : RedirectToAction("List");
+ }
+
+ await brandViewModelService.PrepareLayoutsModel(model);
+ await brandViewModelService.PrepareDiscountModel(model, null, true);
+ brandViewModelService.PrepareSortOptionsModel(model);
+
+ return View(model);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Preview)]
+ public async Task<IActionResult> Edit(string id)
+ {
+ var brand = await brandService.GetBrandById(id);
+ if (brand == null) return RedirectToAction("List");
+
+ EditWarningCheck(brand);
+ // CanView, not HasAccess: viewing a shared/global brand is allowed on Store (with a
+ // warning from EditWarningCheck above); only mutating one is restricted to the exclusive
+ // single-store owner. See IAdminDataScope<TEntity>.CanView's doc comment.
+ if (!await scope.CanView(brand)) return RedirectToAction("List");
+
+ var model = brand.ToModel();
+ await AddLocales(languageService, model.Locales, (locale, languageId) =>
+ {
+ locale.Name = brand.GetTranslation(x => x.Name, languageId, false);
+ locale.Description = brand.GetTranslation(x => x.Description, languageId, false);
+ locale.BottomDescription = brand.GetTranslation(x => x.BottomDescription, languageId, false);
+ locale.MetaKeywords = brand.GetTranslation(x => x.MetaKeywords, languageId, false);
+ locale.MetaDescription = brand.GetTranslation(x => x.MetaDescription, languageId, false);
+ locale.MetaTitle = brand.GetTranslation(x => x.MetaTitle, languageId, false);
+ locale.SeName = brand.GetSeName(languageId, false);
+ });
+ await brandViewModelService.PrepareLayoutsModel(model);
+ await brandViewModelService.PrepareDiscountModel(model, brand, false);
+ brandViewModelService.PrepareSortOptionsModel(model);
+
+ return View(model);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ [HttpPost]
+ [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
+ public async Task<IActionResult> Edit(BrandModel model, bool continueEditing)
+ {
+ var brand = await brandService.GetBrandById(model.Id);
+ if (brand == null) return RedirectToAction("List");
+ if (!await scope.HasAccess(brand)) return RedirectToAction("Edit", new { id = brand.Id });
+
+ if (ModelState.IsValid)
+ {
+ if (scope.DefaultStoreId is not null) model.Stores = [scope.DefaultStoreId];
+ brand = await brandViewModelService.UpdateBrandModel(brand, model);
+ Success(translationService.GetResource("Admin.Catalog.Brands.Updated"));
+
+ if (continueEditing)
+ {
+ await SaveSelectedTabIndex();
+ return RedirectToAction("Edit", new { id = brand.Id });
+ }
+ return RedirectToAction("List");
+ }
+
+ await brandViewModelService.PrepareLayoutsModel(model);
+ await brandViewModelService.PrepareDiscountModel(model, brand, true);
+ brandViewModelService.PrepareSortOptionsModel(model);
+
+ return View(model);
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Delete)]
+ [HttpPost]
+ public async Task<IActionResult> Delete(string id)
+ {
+ var brand = await brandService.GetBrandById(id);
+ if (brand == null) return RedirectToAction("List");
+ if (!await scope.HasAccess(brand)) return RedirectToAction("Edit", new { id = brand.Id });
+
+ if (ModelState.IsValid)
+ {
+ await brandViewModelService.DeleteBrand(brand);
+ Success(translationService.GetResource("Admin.Catalog.Brands.Deleted"));
+ return RedirectToAction("List");
+ }
+
+ Error(ModelState);
+ return RedirectToAction("Edit", new { id = brand.Id });
+ }
+
+ #endregion
+
+ #region Picture
+
+ [PermissionAuthorizeAction(PermissionActionName.Preview)]
+ public async Task<IActionResult> PicturePopup(string brandId)
+ {
+ var brand = await brandService.GetBrandById(brandId);
+ if (brand == null) return Content("Brand not exist");
+ if (!await scope.HasAccess(brand)) return Content("This is not your brand");
+ if (string.IsNullOrEmpty(brand.PictureId)) return Content("Picture not exist");
+
+ return View("Partials/PicturePopup",
+ await pictureViewModelService.PreparePictureModel(brand.PictureId, brand.Id));
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ [HttpPost]
+ public async Task<IActionResult> PicturePopup(PictureModel model)
+ {
+ if (ModelState.IsValid)
+ {
+ var brand = await brandService.GetBrandById(model.ObjectId);
+ if (brand == null)
+ throw new ArgumentException("No brand found with the specified id");
+ if (!await scope.HasAccess(brand)) return Content("This is not your brand");
+ if (string.IsNullOrEmpty(brand.PictureId))
+ throw new ArgumentException("No picture found with the specified id");
+ if (brand.PictureId != model.Id)
+ throw new ArgumentException("Picture ident doesn't fit with brand");
+
+ await pictureViewModelService.UpdatePicture(model);
+ return Content("");
+ }
+
+ Error(ModelState);
+ return View("Partials/PicturePopup", model);
+ }
+
+ #endregion
+
+ #region Export / Import
+
+ [PermissionAuthorizeAction(PermissionActionName.Export)]
+ public async Task<IActionResult> ExportXlsx([FromServices] IExportManager<Brand> exportManager)
+ {
+ try
+ {
+ var bytes = await exportManager.Export(await brandService.GetAllBrands(brandName: "", storeId: scope.DefaultStoreId ?? "", showHidden: true));
+ return File(bytes, "text/xls", "brands.xlsx");
+ }
+ catch (Exception exc)
+ {
+ Error(exc);
+ return RedirectToAction("List");
+ }
+ }
+
+ [PermissionAuthorizeAction(PermissionActionName.Import)]
+ [HttpPost]
+ public async Task<IActionResult> ImportFromXlsx(IFormFile importexcelfile,
+ [FromServices] IImportManager<BrandDto> importManager)
+ {
+ try
+ {
+ if (importexcelfile is { Length: > 0 })
+ {
+ await importManager.Import(importexcelfile.OpenReadStream());
+ }
+ else
+ {
+ Error(translationService.GetResource("Admin.Common.UploadFile"));
+ return RedirectToAction("List");
+ }
+
+ Success(translationService.GetResource("Admin.Catalog.Brands.Imported"));
+ return RedirectToAction("List");
+ }
+ catch (Exception exc)
+ {
+ Error(exc);
+ return RedirectToAction("List");
+ }
+ }
+
+ #endregion
+}
diff --git a/src/Web/Grand.Web.AdminShared/Services/RoutedBrandDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/RoutedBrandDataScope.cs
new file mode 100644
index 000000000..5d9f002e3
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Services/RoutedBrandDataScope.cs
@@ -0,0 +1,56 @@
+#nullable enable
+
+using Grand.Domain.Catalog;
+using Grand.Web.AdminShared.Interfaces;
+using Microsoft.AspNetCore.Http;
+
+namespace Grand.Web.AdminShared.Services;
+
+/// <summary>
+/// Resolves the correct per-host <see cref="IAdminDataScope{Brand}" /> implementation at
+/// request time, based on the current request's "area" route value — same fix and same reason
+/// as <see cref="RoutedCategoryDataScope"/>/<see cref="RoutedCollectionDataScope"/> (see those
+/// files' doc comments): Grand.Web (the combined host) loads Admin and Store together in one
+/// DI container, so a plain AddScoped&lt;IAdminDataScope&lt;Brand&gt;, X&gt;() per host would
+/// silently let whichever host's StartupApplication ran last win for every area in that
+/// process.
+///
+/// No Vendor branch: Vendor has no Brand screen at all, so any "Vendor" (or other
+/// unrecognized/missing) area value fails closed.
+/// </summary>
+public class RoutedBrandDataScope(
+ IHttpContextAccessor httpContextAccessor,
+ GlobalAdminDataScope<Brand> globalScope,
+ StoreAdminDataScope<Brand> storeScope) : IAdminDataScope<Brand>
+{
+ private IAdminDataScope<Brand> Resolved
+ {
+ get
+ {
+ var area = httpContextAccessor.HttpContext?.Request.RouteValues["area"] as string;
+ return area switch {
+ "Admin" => globalScope,
+ "Store" => storeScope,
+ //fail closed: this object fronts store tenant isolation, so an unrecognized or
+ //missing area (including "Vendor" - Brand has no Vendor screen) must never
+ //silently resolve to the unscoped global scope
+ _ => throw new InvalidOperationException(
+ $"RoutedBrandDataScope: unrecognized or missing area '{area}'.")
+ };
+ }
+ }
+
+ public Task<bool> HasAccess(Brand entity) => Resolved.HasAccess(entity);
+
+ public Task<bool> CanView(Brand entity) => Resolved.CanView(entity);
+
+ public string? DefaultStoreId => Resolved.DefaultStoreId;
+
+ public string ResourceKeyPrefix => Resolved.ResourceKeyPrefix;
+
+ public bool ShowStoreSelector => Resolved.ShowStoreSelector;
+
+ public string? DefaultVendorId => Resolved.DefaultVendorId;
+
+ public bool CanFeatureOnHomepage => Resolved.CanFeatureOnHomepage;
+}
diff --git a/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs b/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
index 8c899e75f..8278e1108 100644
--- a/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
+++ b/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
@@ -90,6 +90,12 @@ public class StartupApplication : IStartupApplication
services.AddScoped<StoreAdminDataScope<Collection>>();
services.AddScoped<IAdminDataScope<Collection>, RoutedCollectionDataScope>();
+ // IAdminDataScope<Brand>: registered once here for the same reason as Category/Collection above —
+ // see RoutedBrandDataScope's doc comment. No Vendor scope: Brand has no Vendor screen.
+ services.AddScoped<GlobalAdminDataScope<Brand>>();
+ services.AddScoped<StoreAdminDataScope<Brand>>();
+ services.AddScoped<IAdminDataScope<Brand>, RoutedBrandDataScope>();
+
// IAdminDataScope<Order>: three bespoke implementations, none reusing the generic Global/Store
// scopes — see AdminOrderDataScope/StoreOrderDataScope/VendorOrderDataScope doc comments.
services.AddScoped<AdminOrderDataScope>();
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Create.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Create.cshtml
similarity index 84%
rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Create.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Create.cshtml
index e51b46ec3..bf9a1f7cb 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Create.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Create.cshtml
@@ -2,8 +2,9 @@
@{
//page title
ViewBag.Title = Loc["Admin.Catalog.Brands.AddNew"];
+ var area = ViewContext.RouteData.Values["area"]?.ToString();
}
-<form asp-area="@Constants.AreaAdmin" asp-controller="Brand" asp-action="Create" method="post" id="brand-form">
+<form asp-area="@area" asp-controller="Brand" asp-action="Create" method="post" id="brand-form">
<div class="row">
<div class="col-md-12">
@@ -24,7 +25,7 @@
<button class="btn btn-success" type="submit" name="save-continue">
<i class="fa fa-check-circle"></i> @Loc["Admin.Common.SaveContinue"]
</button>
- <vc:admin-widget widget-zone="brand_details_buttons" additional-data="null"/>
+ <partial name="Partials/WidgetZone.DetailsButtonsCreate"/>
</div>
</div>
</div>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Edit.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Edit.cshtml
similarity index 86%
rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Edit.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Edit.cshtml
index e258fab7d..4d0d8cfe4 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Edit.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Edit.cshtml
@@ -2,8 +2,9 @@
@{
//page title
ViewBag.Title = Loc["Admin.Catalog.Brands.EditBrandDetails"];
+ var area = ViewContext.RouteData.Values["area"]?.ToString();
}
-<form asp-area="@Constants.AreaAdmin" asp-controller="Brand" asp-action="Edit" method="post" id="brand-form">
+<form asp-area="@area" asp-controller="Brand" asp-action="Edit" method="post" id="brand-form">
<div class="row">
<div class="col-md-12">
@@ -31,7 +32,7 @@
<span id="brand-delete" class="btn red">
<i class="fa fa-trash-o"></i> @Loc["Admin.Common.Delete"]
</span>
- <vc:admin-widget widget-zone="brand_details_buttons" additional-data="Model"/>
+ <partial name="Partials/WidgetZone.DetailsButtons" model="Model"/>
</div>
</div>
</div>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
similarity index 85%
rename from src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
index 4f8dc6e9d..7b43a472d 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabDiscounts.cshtml
@@ -1,5 +1,5 @@
@model BrandModel
-<vc:admin-widget widget-zone="brand_discounts_top" additional-data="Model"/>
+<partial name="Partials/WidgetZone.Discounts.Top" model="Model"/>
@{
if (Model.AvailableDiscounts is { Count: > 0 })
{
@@ -24,4 +24,4 @@
</div>
}
}
-<vc:admin-widget widget-zone="brand_discounts_bottom" additional-data="Model"/>
\ No newline at end of file
+<partial name="Partials/WidgetZone.Discounts.Bottom" model="Model"/>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
similarity index 82%
rename from src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
index d0fe77d3a..cc5821698 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabDocuments.cshtml
@@ -1,16 +1,19 @@
@model BrandModel
@inject AdminAreaSettings adminAreaSettings
+@{
+ var area = ViewContext.RouteData.Values["area"]?.ToString();
+}
@if (!string.IsNullOrEmpty(Model.Id))
{
<div class="panel panel-default">
- <vc:admin-widget widget-zone="brand_details_documents_top" additional-data="Model"/>
+ <partial name="Partials/WidgetZone.Documents.Top" model="Model"/>
<div class="panel-body">
<div id="brand-documents-grid"></div>
</div>
<div class="panel-footer">
- <button type="button" class="k-button" onclick="location.href='@Url.Action("CreateDocument", "Document", new { ObjectId = Model.Id, Reference = (int)Reference.Brand, area = Constants.AreaStore })'"><i class="fa fa-plus"></i>&nbsp;@Loc["Admin.Marketing.Document.Add"]</button>
+ <button type="button" class="k-button" onclick="location.href='@Url.Action("CreateDocument", "Document", new { ObjectId = Model.Id, Reference = (int)Reference.Brand, area = area })'"><i class="fa fa-plus"></i>&nbsp;@Loc["Admin.Marketing.Document.Add"]</button>
</div>
- <vc:admin-widget widget-zone="brand_details_documents_bottom" additional-data="Model"/>
+ <partial name="Partials/WidgetZone.Documents.Bottom" model="Model"/>
</div>
<script>
@@ -19,7 +22,7 @@
dataSource: {
transport: {
read: {
- url: "@Html.Raw(Url.Action("ListDocuments", "Document", new { reference = (int)Reference.Brand, ObjectId = Model.Id, StatusId = -1, area = Constants.AreaStore }))",
+ url: "@Html.Raw(Url.Action("ListDocuments", "Document", new { reference = (int)Reference.Brand, ObjectId = Model.Id, StatusId = -1, area = area }))",
type: "POST",
dataType: "json",
data: addAntiForgeryToken
@@ -53,12 +56,12 @@
columns: [{
field: "Number",
title: "@Loc["Admin.Documents.Document.Fields.Number"]",
- template: '<a class="k-link" href="@Url.Action("EditDocument", "Document", new { area = Constants.AreaStore })/#=Id#">#=kendo.htmlEncode(Number)#</a>',
+ template: '<a class="k-link" href="@Url.Action("EditDocument", "Document", new { area = area })/#=Id#">#=kendo.htmlEncode(Number)#</a>',
},
{
field: "Name",
title: "@Loc["Admin.Documents.Document.Fields.Name"]",
- template: '<a class="k-link" href="@Url.Action("EditDocument", "Document", new { area = Constants.AreaStore })/#=Id#">#=kendo.htmlEncode(Name)#</a>',
+ template: '<a class="k-link" href="@Url.Action("EditDocument", "Document", new { area = area })/#=Id#">#=kendo.htmlEncode(Name)#</a>',
}, {
field: "Published",
title: "@Loc["Admin.Documents.Document.Fields.Published"]",
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabSeo.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
similarity index 97%
rename from src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
index 5e6df1966..a8e587453 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.TabSeo.cshtml
@@ -37,7 +37,7 @@
}
<div class="form-horizontal">
- <vc:admin-widget widget-zone="brand_details_seo_top" additional-data="Model"/>
+ <partial name="Partials/WidgetZone.SEO.Top" model="Model"/>
<localized-editor localized-template="@template" name="brand-seo-localized" language-ids="@Model.Locales.Select(c => c.LanguageId).ToList()">
<div class="form-body">
<div class="form-group">
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.cshtml
similarity index 95%
rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.cshtml
index a7b9987f5..c1727e939 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Brand/Partials/CreateOrUpdate.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Brand/Partials/CreateOrUpdate.cshtml
@@ -48,6 +48,6 @@
</div>
</content>
</tabstrip-item>
- <vc:admin-widget widget-zone="brand_details_tabs" additional-data="Model"/>
+ <partial name="Partials/WidgetZone.Tabs" model="Model"/>
</items>
</admin-tabstrip>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Create.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Create.cshtml
deleted file mode 100644
index c6a198e86..000000000
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Create.cshtml
+++ /dev/null
@@ -1,37 +0,0 @@
-@model BrandModel
-@{
- //page title
- ViewBag.Title = Loc["Admin.Catalog.Brands.AddNew"];
-}
-<form asp-area="@Constants.AreaStore" asp-controller="Brand" asp-action="Create" method="post" id="brand-form">
-
- <div class="row">
- <div class="col-md-12">
- <div class="x_panel light form-fit">
- <div class="x_title">
- <div class="caption">
- <i class="fa fa-building-o"></i>
- @Loc["Admin.Catalog.Brands.AddNew"]
- <small>
- <i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(Loc["Admin.Catalog.Brands.BackToList"], "List")
- </small>
- </div>
- <div class="actions">
- <div class="btn-group btn-group-devided">
- <button class="btn btn-success" type="submit" name="save">
- <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]
- </button>
- <button class="btn btn-success" type="submit" name="save-continue">
- <i class="fa fa-check-circle"></i> @Loc["Admin.Common.SaveContinue"]
- </button>
- <vc:admin-widget widget-zone="brand_details_buttons" additional-data="null"/>
- </div>
- </div>
- </div>
- <div class="x_content form">
- <partial name="Partials/CreateOrUpdate" model="Model"/>
- </div>
- </div>
- </div>
- </div>
-</form>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Edit.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Edit.cshtml
deleted file mode 100644
index 2470512b3..000000000
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Edit.cshtml
+++ /dev/null
@@ -1,45 +0,0 @@
-@model BrandModel
-@{
- //page title
- ViewBag.Title = Loc["Admin.Catalog.Brands.EditBrandDetails"];
-}
-<form asp-area="@Constants.AreaStore" asp-controller="Brand" asp-action="Edit" method="post" id="brand-form">
-
- <div class="row">
- <div class="col-md-12">
- <div class="x_panel light form-fit">
- <div class="x_title">
- <div class="caption">
- <i class="fa fa-building-o"></i>
- @Loc["Admin.Catalog.Brands.EditBrandDetails"] - @Model.Name
- <small>
- <i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(Loc["Admin.Catalog.Brands.BackToList"], "List")
- </small>
- </div>
- <div class="actions">
- <div class="btn-group btn-group-devided util-btn-margin-bottom-5">
- <button type="button" onclick="window.open('@Url.RouteUrl("Brand", new { Model.SeName })','_blank');" class="btn purple">
- <i class="fa fa-eye"></i>
- @Loc["Admin.Common.Preview"]
- </button>
- <button class="btn btn-success" type="submit" name="save">
- <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]
- </button>
- <button class="btn btn-success" type="submit" name="save-continue">
- <i class="fa fa-check-circle"></i> @Loc["Admin.Common.SaveContinue"]
- </button>
- <span id="brand-delete" class="btn red">
- <i class="fa fa-trash-o"></i> @Loc["Admin.Common.Delete"]
- </span>
- <vc:admin-widget widget-zone="brand_details_buttons" additional-data="Model"/>
- </div>
- </div>
- </div>
- <div class="x_content form">
- <partial name="Partials/CreateOrUpdate" model="Model"/>
- </div>
- </div>
- </div>
- </div>
-</form>
-<admin-delete-confirmation button-id="brand-delete"/>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/List.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/List.cshtml
index acb00072f..798b8c3b6 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/List.cshtml
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/List.cshtml
@@ -16,7 +16,7 @@
<a href="@Url.Action("Create", new { area = Constants.AreaStore })" class="btn green">
<i class="fa fa-plus"></i><span class="d-none d-sm-inline"> @Loc["Admin.Common.AddNew"] </span>
</a>
- <vc:admin-widget widget-zone="brand_list_buttons" additional-data="null"/>
+ <partial name="Partials/WidgetZone.ListButtons"/>
</div>
</div>
<div class="x_content form">
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabInfo.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabInfo.cshtml
index d2717a9f5..930268138 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabInfo.cshtml
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.TabInfo.cshtml
@@ -46,7 +46,7 @@
}
<div class="form-horizontal">
- <vc:admin-widget widget-zone="brand_details_info_top" additional-data="Model"/>
+ <partial name="Partials/WidgetZone.Info.Top" model="Model"/>
<localized-editor localized-template="@template" name="brand-info-localized" language-ids="@Model.Locales.Select(c => c.LanguageId).ToList()">
<div class="form-body">
<div class="form-group">
@@ -198,4 +198,4 @@
</div>
</div>
</div>
-<vc:admin-widget widget-zone="brand_details_info_bottom" additional-data="Model"/>
\ No newline at end of file
+<partial name="Partials/WidgetZone.Info.Bottom" model="Model"/>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.cshtml
deleted file mode 100644
index a7b9987f5..000000000
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/CreateOrUpdate.cshtml
+++ /dev/null
@@ -1,53 +0,0 @@
-@using Grand.Business.Core.Interfaces.Common.Security
-@using Grand.Domain.Permissions
-@model BrandModel
-@inject IPermissionService permissionService
-@{
- //has "Manage Documents" permission?
- var canManageDocuments = await permissionService.Authorize(StandardPermission.ManageDocuments);
-}
-<div asp-validation-summary="All"></div>
-<input asp-for="Id" type="hidden"/>
-<admin-tabstrip name="brand-edit" BindGrid="true">
- <items>
- <tabstrip-item text="@Loc["Admin.Catalog.Brands.Info"]" tab-index="0">
- <content>
- <div>
- <partial name="Partials/CreateOrUpdate.TabInfo" model="Model"/>
- </div>
- </content>
- </tabstrip-item>
- <tabstrip-item text="@Loc["Admin.Common.SEO"]" tab-index="1">
- <content>
- <div>
- <partial name="Partials/CreateOrUpdate.TabSeo" model="Model"/>
- </div>
- </content>
- </tabstrip-item>
- <tabstrip-item text="@Loc["Admin.Catalog.Brands.Discounts"]" tab-index="2">
- <content>
- <div>
- <partial name="Partials/CreateOrUpdate.TabDiscounts" model="Model"/>
- </div>
- </content>
- </tabstrip-item>
- @if (canManageDocuments)
- {
- <tabstrip-item text="@Loc["Admin.Catalog.Brands.Documents"]" tab-index="3">
- <content>
- <div>
- <partial name="Partials/CreateOrUpdate.TabDocuments" model="Model"/>
- </div>
- </content>
- </tabstrip-item>
- }
- <tabstrip-item text="@Loc["Admin.Common.UserFields.Tab"]" tab-index="4">
- <content>
- <div>
- <partial name="Partials/UserFields" model="Model"/>
- </div>
- </content>
- </tabstrip-item>
- <vc:admin-widget widget-zone="brand_details_tabs" additional-data="Model"/>
- </items>
-</admin-tabstrip>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.DetailsButtons.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.DetailsButtons.cshtml
new file mode 100644
index 000000000..302f9e4bc
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.DetailsButtons.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_buttons" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.DetailsButtonsCreate.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.DetailsButtonsCreate.cshtml
new file mode 100644
index 000000000..3354b1f42
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.DetailsButtonsCreate.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_buttons" additional-data="null"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Discounts.Bottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Discounts.Bottom.cshtml
new file mode 100644
index 000000000..d3d6c1b3b
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Discounts.Bottom.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_discounts_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Discounts.Top.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Discounts.Top.cshtml
new file mode 100644
index 000000000..dfe1d0195
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Discounts.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_discounts_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Documents.Bottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Documents.Bottom.cshtml
new file mode 100644
index 000000000..004ba89e0
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Documents.Bottom.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_documents_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Documents.Top.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Documents.Top.cshtml
new file mode 100644
index 000000000..527e92d64
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Documents.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_documents_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Info.Bottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Info.Bottom.cshtml
new file mode 100644
index 000000000..f9bdfb550
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Info.Bottom.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_info_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Info.Top.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Info.Top.cshtml
new file mode 100644
index 000000000..5c59545f7
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Info.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_info_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.ListButtons.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.ListButtons.cshtml
new file mode 100644
index 000000000..e93ebaa70
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.ListButtons.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_list_buttons" additional-data="null"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.SEO.Top.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.SEO.Top.cshtml
new file mode 100644
index 000000000..cea8bcbf1
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.SEO.Top.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_seo_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Tabs.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Tabs.cshtml
new file mode 100644
index 000000000..96a051a80
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Brand/Partials/WidgetZone.Tabs.cshtml
@@ -0,0 +1,2 @@
+@model dynamic
+<vc:store-widget widget-zone="store_brand_details_tabs" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Controllers/BrandController.cs b/src/Web/Grand.Web.Store/Controllers/BrandController.cs
index c4b027f1d..fab1d1183 100644
--- a/src/Web/Grand.Web.Store/Controllers/BrandController.cs
+++ b/src/Web/Grand.Web.Store/Controllers/BrandController.cs
@@ -1,289 +1,46 @@
-using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Domain.Catalog;
-using Grand.Domain.Permissions;
-using Grand.Infrastructure;
-using Grand.Web.AdminShared.Extensions;
-using Grand.Web.AdminShared.Extensions.Mapping;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Interfaces;
-using Grand.Web.AdminShared.Models.Catalog;
-using Grand.Web.AdminShared.Models.Common;
-using Grand.Web.Common.DataSource;
using Grand.Web.Common.Filters;
-using Grand.Web.Common.Security.Authorization;
+using Grand.Web.Common.Localization;
+using Grand.Web.Store.Extensions;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Store.Controllers;
-[PermissionAuthorize(PermissionSystemName.Brands)]
-public class BrandController : BaseStoreController
+// Reduced to a thin subclass of BaseBrandController (ARCH-001 Brand consolidation). All regions of
+// behavior live in the shared base; this class only supplies Store's DI wiring, the
+// EditWarningCheck hook, and the attributes that used to arrive transitively via
+// BaseStoreController. Same pattern as CategoryController/CollectionController (see those files).
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaStore)]
+[AuthorizeStore]
+[AuthorizeMenu]
+public class BrandController(
+ IBrandViewModelService brandViewModelService,
+ IBrandService brandService,
+ IStoreService storeService,
+ ILanguageService languageService,
+ ITranslationService translationService,
+ IPictureViewModelService pictureViewModelService,
+ IAdminDataScope<Brand> scope)
+ : BaseBrandController(brandViewModelService, brandService, storeService, languageService,
+ translationService, pictureViewModelService, scope)
{
- #region Constructors
-
- public BrandController(
- IBrandViewModelService brandViewModelService,
- IBrandService brandService,
- IContextAccessor contextAccessor,
- ILanguageService languageService,
- ITranslationService translationService,
- IPictureViewModelService pictureViewModelService)
- {
- _brandViewModelService = brandViewModelService;
- _brandService = brandService;
- _contextAccessor = contextAccessor;
- _languageService = languageService;
- _translationService = translationService;
- _pictureViewModelService = pictureViewModelService;
- }
-
- #endregion
-
- #region Fields
-
- private readonly IBrandViewModelService _brandViewModelService;
- private readonly IBrandService _brandService;
- private readonly IContextAccessor _contextAccessor;
- private readonly ILanguageService _languageService;
- private readonly ITranslationService _translationService;
- private readonly IPictureViewModelService _pictureViewModelService;
-
- #endregion
-
- #region List
-
- public IActionResult Index()
- {
- return RedirectToAction("List");
- }
-
- public IActionResult List()
- {
- var model = new BrandListModel();
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.List)]
- [HttpPost]
- public async Task<IActionResult> List(DataSourceRequest command, BrandListModel model)
- {
- model.SearchStoreId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
-
- var brands = await _brandService.GetAllBrands(model.SearchBrandName, model.SearchStoreId, command.Page - 1, command.PageSize, true);
- var gridModel = new DataSourceResult {
- Data = brands.Select(x => x.ToModel()),
- Total = brands.TotalCount
- };
-
- return Json(gridModel);
- }
-
- #endregion
-
- #region Create / Edit / Delete
-
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public async Task<IActionResult> Create([FromServices] CatalogSettings catalogSettings)
- {
- var model = new BrandModel();
- //locales
- await AddLocales(_languageService, model.Locales);
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, null, true);
- //default values
- model.PageSize = catalogSettings.DefaultPageSize;
- model.PageSizeOptions = catalogSettings.DefaultPageSizeOptions;
- model.Published = true;
- model.AllowCustomersToSelectPageSize = true;
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- public async Task<IActionResult> Create(BrandModel model, bool continueEditing)
- {
- if (ModelState.IsValid)
- {
- model.Stores = [_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
- var collection = await _brandViewModelService.InsertBrandModel(model);
- Success(_translationService.GetResource("Admin.Catalog.Brands.Added"));
- return continueEditing ? RedirectToAction("Edit", new { id = collection.Id }) : RedirectToAction("List");
- }
-
- //If we got this far, something failed, redisplay form
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, null, true);
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Preview)]
- public async Task<IActionResult> Edit(string id)
- {
- var brand = await _brandService.GetBrandById(id);
- if (brand == null)
- //No collection found with the specified id
- return RedirectToAction("List");
-
- if (!brand.LimitedToStores || (brand.LimitedToStores &&
- brand.Stores.Contains(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
- brand.Stores.Count > 1))
- {
- Warning(_translationService.GetResource("Admin.Catalog.Brands.Permissions"));
- }
- else
- {
- if (!brand.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
- return RedirectToAction("List");
- }
-
-
- var model = brand.ToModel();
- //locales
- await AddLocales(_languageService, model.Locales, (locale, languageId) =>
- {
- locale.Name = brand.GetTranslation(x => x.Name, languageId, false);
- locale.Description = brand.GetTranslation(x => x.Description, languageId, false);
- locale.BottomDescription = brand.GetTranslation(x => x.BottomDescription, languageId, false);
- locale.MetaKeywords = brand.GetTranslation(x => x.MetaKeywords, languageId, false);
- locale.MetaDescription = brand.GetTranslation(x => x.MetaDescription, languageId, false);
- locale.MetaTitle = brand.GetTranslation(x => x.MetaTitle, languageId, false);
- locale.SeName = brand.GetSeName(languageId, false);
- });
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, brand, false);
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- public async Task<IActionResult> Edit(BrandModel model, bool continueEditing)
- {
- var brand = await _brandService.GetBrandById(model.Id);
- if (brand == null)
- //No collection found with the specified id
- return RedirectToAction("List");
-
- if (!brand.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
- return RedirectToAction("Edit", new { id = brand.Id });
-
- if (ModelState.IsValid)
- {
- model.Stores = [_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
- brand = await _brandViewModelService.UpdateBrandModel(brand, model);
- Success(_translationService.GetResource("Admin.Catalog.Brands.Updated"));
-
- if (continueEditing)
- {
- //selected tab
- await SaveSelectedTabIndex();
-
- return RedirectToAction("Edit", new { id = brand.Id });
- }
-
- return RedirectToAction("List");
- }
-
-
- //If we got this far, something failed, redisplay form
- //layouts
- await _brandViewModelService.PrepareLayoutsModel(model);
- //discounts
- await _brandViewModelService.PrepareDiscountModel(model, brand, true);
- //sort options
- _brandViewModelService.PrepareSortOptionsModel(model);
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Delete)]
- [HttpPost]
- public async Task<IActionResult> Delete(string id)
- {
- var brand = await _brandService.GetBrandById(id);
- if (brand == null)
- //No collection found with the specified id
- return RedirectToAction("List");
-
- if (!brand.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
- return RedirectToAction("Edit", new { id = brand.Id });
-
- if (ModelState.IsValid)
- {
- await _brandViewModelService.DeleteBrand(brand);
-
- Success(_translationService.GetResource("Admin.Catalog.Brands.Deleted"));
- return RedirectToAction("List");
- }
-
- Error(ModelState);
- return RedirectToAction("Edit", new { id = brand.Id });
- }
-
- #endregion
-
- #region Picture
-
- [PermissionAuthorizeAction(PermissionActionName.Preview)]
- public async Task<IActionResult> PicturePopup(string brandId)
- {
- var brand = await _brandService.GetBrandById(brandId);
- if (brand == null)
- return Content("Brand not exist");
-
- if (!brand.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
- return Content("This is not your brand");
-
- if (string.IsNullOrEmpty(brand.PictureId))
- return Content("Picture not exist");
-
- return View("Partials/PicturePopup",
- await _pictureViewModelService.PreparePictureModel(brand.PictureId, brand.Id));
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- [HttpPost]
- public async Task<IActionResult> PicturePopup(PictureModel model)
- {
- if (ModelState.IsValid)
- {
- var brand = await _brandService.GetBrandById(model.ObjectId);
- if (brand == null)
- throw new ArgumentException("No brand found with the specified id");
-
- if (!brand.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
- return Content("This is not your brand");
-
- if (string.IsNullOrEmpty(brand.PictureId))
- throw new ArgumentException("No picture found with the specified id");
-
- if (brand.PictureId != model.Id)
- throw new ArgumentException("Picture ident doesn't fit with brand");
-
- await _pictureViewModelService.UpdatePicture(model);
-
- return Content("");
- }
-
- Error(ModelState);
-
- return View("Partials/PicturePopup", model);
- }
- #endregion
-}
\ No newline at end of file
+ // Re-derived from the original Store BrandController.Edit(GET) (pre-cutover:
+ // src/Web/Grand.Web.Store/Controllers/BrandController.cs, lines ~138-148) - the condition is
+ // unusual (warns when NOT limited to stores at all, or when limited AND the staff member's
+ // store is one of several) and easy to get backwards. Scope.DefaultStoreId is exactly
+ // StaffStoreId for Store (StoreAdminDataScope.DefaultStoreId => CurrentCustomer.StaffStoreId).
+ protected override void EditWarningCheck(Brand brand)
+ {
+ if (!brand.LimitedToStores ||
+ (brand.LimitedToStores &&
+ brand.Stores.Contains(Scope.DefaultStoreId) &&
+ brand.Stores.Count > 1))
+ Warning(TranslationService.GetResource("Admin.Catalog.Brands.Permissions"));
+ }
+}