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 22: TaxCategory controller/service consolidation (Admin/Store) (#822)

Krzysztof Pajak47ac86239161
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseTaxCategoryControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseTaxCategoryControllerTests.cs
new file mode 100644
index 000000000..f52e80a3d
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseTaxCategoryControllerTests.cs
@@ -0,0 +1,293 @@
+using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Domain.Stores;
+using Grand.Domain.Tax;
+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.Tax;
+using Grand.Web.Common.DataSource;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Rendering;
+using Microsoft.AspNetCore.Mvc.Routing;
+using Microsoft.AspNetCore.Mvc.ViewFeatures;
+using Microsoft.Extensions.Logging;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class BaseTaxCategoryControllerTests
+{
+ // Concrete subclass exists only to instantiate the abstract base for direct-call unit tests -
+ // same pattern as BaseEmailAccountControllerTests/BaseCategoryControllerTests.
+ private class TestTaxCategoryController(
+ ITaxCategoryService taxCategoryService,
+ IStoreService storeService,
+ ITranslationService translationService,
+ IAdminDataScope<TaxCategory> scope)
+ : BaseTaxCategoryController(taxCategoryService, storeService, translationService, scope);
+
+ private Mock<ITaxCategoryService> _taxCategoryServiceMock = null!;
+ private Mock<IStoreService> _storeServiceMock = null!;
+ private Mock<ITranslationService> _translationServiceMock = null!;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<TaxCategoryProfile>());
+ AutoMapperConfig.Init(mapperConfig);
+
+ _taxCategoryServiceMock = new Mock<ITaxCategoryService>();
+ _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((string s) => s);
+ }
+
+ private TestTaxCategoryController CreateController(IAdminDataScope<TaxCategory> scope)
+ {
+ var controller = new TestTaxCategoryController(
+ _taxCategoryServiceMock.Object,
+ _storeServiceMock.Object,
+ _translationServiceMock.Object,
+ scope);
+
+ 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, Mock.Of<ITempDataProvider>());
+ return controller;
+ }
+
+ private static Mock<IAdminDataScope<TaxCategory>> AdminScope() => AdminScope(true);
+
+ private static Mock<IAdminDataScope<TaxCategory>> AdminScope(bool hasAccess)
+ {
+ var scope = new Mock<IAdminDataScope<TaxCategory>>();
+ scope.Setup(s => s.DefaultStoreId).Returns((string?)null);
+ scope.Setup(s => s.HasAccess(It.IsAny<TaxCategory>())).ReturnsAsync(hasAccess);
+ scope.Setup(s => s.ShowStoreSelector).Returns(true);
+ return scope;
+ }
+
+ private static Mock<IAdminDataScope<TaxCategory>> StoreScope(string storeId, bool hasAccess)
+ {
+ var scope = new Mock<IAdminDataScope<TaxCategory>>();
+ scope.Setup(s => s.DefaultStoreId).Returns(storeId);
+ scope.Setup(s => s.HasAccess(It.IsAny<TaxCategory>())).ReturnsAsync(hasAccess);
+ scope.Setup(s => s.ShowStoreSelector).Returns(false);
+ return scope;
+ }
+
+ // --- Categories (grid data) ---
+
+ [TestMethod]
+ public async Task Categories_AdminScope_RequestsAllStores()
+ {
+ _taxCategoryServiceMock.Setup(s => s.GetAllTaxCategories(""))
+ .ReturnsAsync(new List<TaxCategory> { new() { Id = "tc-1", Name = "Books", StoreId = "" } });
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Categories(new DataSourceRequest()) as JsonResult;
+
+ var payload = (DataSourceResult)result!.Value!;
+ Assert.AreEqual(1, payload.Total);
+ _taxCategoryServiceMock.Verify(s => s.GetAllTaxCategories(""), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task Categories_StoreScope_RequestsOwnStore()
+ {
+ _taxCategoryServiceMock.Setup(s => s.GetAllTaxCategories("store-1"))
+ .ReturnsAsync(new List<TaxCategory>());
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ await controller.Categories(new DataSourceRequest());
+
+ _taxCategoryServiceMock.Verify(s => s.GetAllTaxCategories("store-1"), Times.Once);
+ _storeServiceMock.Verify(s => s.GetAllStores(), Times.Never); // ShowStoreSelector=false: no store lookup needed
+ }
+
+ [TestMethod]
+ public async Task Categories_AdminScope_ResolvesStoreNameForOwnedCategory()
+ {
+ _storeServiceMock.Setup(s => s.GetAllStores())
+ .ReturnsAsync(new List<Store> { new() { Id = "store-1", Shortcut = "MyStore" } });
+ _taxCategoryServiceMock.Setup(s => s.GetAllTaxCategories(""))
+ .ReturnsAsync(new List<TaxCategory> { new() { Id = "tc-1", Name = "Books", StoreId = "store-1" } });
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Categories(new DataSourceRequest()) as JsonResult;
+
+ var payload = (DataSourceResult)result!.Value!;
+ var items = (List<TaxCategoryModel>)payload.Data;
+ Assert.AreEqual("MyStore", items.Single().StoreName);
+ }
+
+ [TestMethod]
+ public async Task Categories_AdminScope_ResolvesStoreNameAsAllForGlobalCategory()
+ {
+ _storeServiceMock.Setup(s => s.GetAllStores())
+ .ReturnsAsync(new List<Store> { new() { Id = "store-1", Shortcut = "MyStore" } });
+ _taxCategoryServiceMock.Setup(s => s.GetAllTaxCategories(""))
+ .ReturnsAsync(new List<TaxCategory> { new() { Id = "tc-1", Name = "Books", StoreId = "" } });
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Categories(new DataSourceRequest()) as JsonResult;
+
+ var payload = (DataSourceResult)result!.Value!;
+ var items = (List<TaxCategoryModel>)payload.Data;
+ Assert.AreEqual("Admin.Common.All", items.Single().StoreName);
+ }
+
+ [TestMethod]
+ public async Task Categories_StoreScope_LeavesStoreNameEmpty()
+ {
+ _taxCategoryServiceMock.Setup(s => s.GetAllTaxCategories("store-1"))
+ .ReturnsAsync(new List<TaxCategory> { new() { Id = "tc-1", Name = "Books", StoreId = "store-1" } });
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Categories(new DataSourceRequest()) as JsonResult;
+
+ var payload = (DataSourceResult)result!.Value!;
+ var items = (List<TaxCategoryModel>)payload.Data;
+ Assert.AreEqual(string.Empty, items.Single().StoreName);
+ }
+
+ // --- CategoryAdd ---
+
+ [TestMethod]
+ public async Task CategoryAdd_AdminScope_DoesNotForceStoreId()
+ {
+ TaxCategory? inserted = null;
+ _taxCategoryServiceMock.Setup(s => s.InsertTaxCategory(It.IsAny<TaxCategory>()))
+ .Callback<TaxCategory>(tc => inserted = tc)
+ .Returns(Task.CompletedTask);
+ var controller = CreateController(AdminScope().Object);
+
+ await controller.CategoryAdd(new TaxCategoryModel { Name = "Books", StoreId = "store-9" });
+
+ Assert.AreEqual("store-9", inserted!.StoreId); // whatever the admin's grid dropdown picked
+ }
+
+ [TestMethod]
+ public async Task CategoryAdd_StoreScope_ForcesStoreId()
+ {
+ TaxCategory? inserted = null;
+ _taxCategoryServiceMock.Setup(s => s.InsertTaxCategory(It.IsAny<TaxCategory>()))
+ .Callback<TaxCategory>(tc => inserted = tc)
+ .Returns(Task.CompletedTask);
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ await controller.CategoryAdd(new TaxCategoryModel { Name = "Books" });
+
+ Assert.AreEqual("store-1", inserted!.StoreId);
+ }
+
+ // --- CategoryUpdate ---
+
+ [TestMethod]
+ public async Task CategoryUpdate_AdminScope_UpdatesRegardlessOfOwnership()
+ {
+ var existing = new TaxCategory { Id = "tc-1", Name = "Old", StoreId = "" };
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("tc-1")).ReturnsAsync(existing);
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.CategoryUpdate(new TaxCategoryModel { Id = "tc-1", Name = "New" });
+
+ _taxCategoryServiceMock.Verify(s => s.UpdateTaxCategory(It.IsAny<TaxCategory>()), Times.Once);
+ Assert.IsInstanceOfType(result, typeof(JsonResult));
+ }
+
+ [TestMethod]
+ public async Task CategoryUpdate_StoreScope_DeniedOwnership_DoesNotUpdate()
+ {
+ var existing = new TaxCategory { Id = "tc-1", Name = "Old", StoreId = "store-2" };
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("tc-1")).ReturnsAsync(existing);
+ var controller = CreateController(StoreScope("store-1", false).Object);
+
+ await controller.CategoryUpdate(new TaxCategoryModel { Id = "tc-1", Name = "New" });
+
+ _taxCategoryServiceMock.Verify(s => s.UpdateTaxCategory(It.IsAny<TaxCategory>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task CategoryUpdate_NotFound_DoesNotUpdate()
+ {
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("missing")).ReturnsAsync((TaxCategory)null!);
+ var controller = CreateController(AdminScope().Object);
+
+ await controller.CategoryUpdate(new TaxCategoryModel { Id = "missing", Name = "New" });
+
+ _taxCategoryServiceMock.Verify(s => s.UpdateTaxCategory(It.IsAny<TaxCategory>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task CategoryUpdate_StoreScope_ForcesStoreIdOnMappedEntity()
+ {
+ var existing = new TaxCategory { Id = "tc-1", Name = "Old", StoreId = "store-1" };
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("tc-1")).ReturnsAsync(existing);
+ TaxCategory? updated = null;
+ _taxCategoryServiceMock.Setup(s => s.UpdateTaxCategory(It.IsAny<TaxCategory>()))
+ .Callback<TaxCategory>(tc => updated = tc)
+ .Returns(Task.CompletedTask);
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ await controller.CategoryUpdate(new TaxCategoryModel { Id = "tc-1", Name = "New" });
+
+ Assert.AreEqual("store-1", updated!.StoreId);
+ }
+
+ // --- CategoryDelete ---
+
+ [TestMethod]
+ public async Task CategoryDelete_AdminScope_Deletes()
+ {
+ var existing = new TaxCategory { Id = "tc-1", StoreId = "" };
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("tc-1")).ReturnsAsync(existing);
+ var controller = CreateController(AdminScope().Object);
+
+ await controller.CategoryDelete("tc-1");
+
+ _taxCategoryServiceMock.Verify(s => s.DeleteTaxCategory(existing), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task CategoryDelete_StoreScope_DeniedOwnership_DoesNotDelete()
+ {
+ var existing = new TaxCategory { Id = "tc-1", StoreId = "store-2" };
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("tc-1")).ReturnsAsync(existing);
+ var controller = CreateController(StoreScope("store-1", false).Object);
+
+ await controller.CategoryDelete("tc-1");
+
+ _taxCategoryServiceMock.Verify(s => s.DeleteTaxCategory(It.IsAny<TaxCategory>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task CategoryDelete_NotFound_ReturnsEmptyJsonWithoutThrowing()
+ {
+ // Deliberate unification onto Store's original silent-empty-JSON behavior for not-found
+ // (Admin originally threw ArgumentException here) — see design spec.
+ _taxCategoryServiceMock.Setup(s => s.GetTaxCategoryById("missing")).ReturnsAsync((TaxCategory)null!);
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.CategoryDelete("missing");
+
+ Assert.IsInstanceOfType(result, typeof(JsonResult));
+ _taxCategoryServiceMock.Verify(s => s.DeleteTaxCategory(It.IsAny<TaxCategory>()), Times.Never);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedTaxCategoryDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedTaxCategoryDataScopeTests.cs
new file mode 100644
index 000000000..304642538
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedTaxCategoryDataScopeTests.cs
@@ -0,0 +1,85 @@
+using Grand.Domain.Customers;
+using Grand.Domain.Tax;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Services;
+using Microsoft.AspNetCore.Http;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class RoutedTaxCategoryDataScopeTests
+{
+ private static IHttpContextAccessor CreateHttpContextAccessor(string? area)
+ {
+ var httpContext = new DefaultHttpContext();
+ if (area is not null)
+ httpContext.Request.RouteValues["area"] = area;
+ var accessor = new Mock<IHttpContextAccessor>();
+ accessor.Setup(a => a.HttpContext).Returns(httpContext);
+ return accessor.Object;
+ }
+
+ private static StoreTaxCategoryDataScope CreateStoreScope(string staffStoreId)
+ {
+ var customer = new Customer { StaffStoreId = staffStoreId };
+ var workContext = new Mock<IWorkContext>();
+ workContext.Setup(w => w.CurrentCustomer).Returns(customer);
+ var contextAccessor = new Mock<IContextAccessor>();
+ contextAccessor.Setup(c => c.WorkContext).Returns(workContext.Object);
+ return new StoreTaxCategoryDataScope(contextAccessor.Object);
+ }
+
+ [TestMethod]
+ public async Task AdminArea_ResolvesToGlobalScope_HasAccessAlwaysTrue()
+ {
+ var routed = new RoutedTaxCategoryDataScope(
+ CreateHttpContextAccessor("Admin"),
+ new GlobalAdminDataScope<TaxCategory>(),
+ CreateStoreScope("store-1"));
+
+ var category = new TaxCategory { StoreId = "store-2" };
+ Assert.IsTrue(await routed.HasAccess(category));
+ Assert.IsNull(routed.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public async Task StoreArea_ResolvesToStoreScope_HasAccessScoped()
+ {
+ var routed = new RoutedTaxCategoryDataScope(
+ CreateHttpContextAccessor("Store"),
+ new GlobalAdminDataScope<TaxCategory>(),
+ CreateStoreScope("store-1"));
+
+ var owned = new TaxCategory { StoreId = "store-1" };
+ var notOwned = new TaxCategory { StoreId = "store-2" };
+ Assert.IsTrue(await routed.HasAccess(owned));
+ Assert.IsFalse(await routed.HasAccess(notOwned));
+ Assert.AreEqual("store-1", routed.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public async Task UnrecognizedArea_ThrowsInvalidOperationException()
+ {
+ var routed = new RoutedTaxCategoryDataScope(
+ CreateHttpContextAccessor("Vendor"),
+ new GlobalAdminDataScope<TaxCategory>(),
+ CreateStoreScope("store-1"));
+
+ await Assert.ThrowsAsync<InvalidOperationException>(
+ () => routed.HasAccess(new TaxCategory { StoreId = "store-1" }));
+ }
+
+ [TestMethod]
+ public async Task MissingArea_ThrowsInvalidOperationException()
+ {
+ var routed = new RoutedTaxCategoryDataScope(
+ CreateHttpContextAccessor(null),
+ new GlobalAdminDataScope<TaxCategory>(),
+ CreateStoreScope("store-1"));
+
+ await Assert.ThrowsAsync<InvalidOperationException>(
+ () => routed.HasAccess(new TaxCategory { StoreId = "store-1" }));
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreTaxCategoryDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreTaxCategoryDataScopeTests.cs
new file mode 100644
index 000000000..15204f135
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreTaxCategoryDataScopeTests.cs
@@ -0,0 +1,70 @@
+using Grand.Domain.Customers;
+using Grand.Domain.Tax;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Services;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class StoreTaxCategoryDataScopeTests
+{
+ private static StoreTaxCategoryDataScope CreateScope(string staffStoreId)
+ {
+ var customer = new Customer { StaffStoreId = staffStoreId };
+ var workContext = new Mock<IWorkContext>();
+ workContext.Setup(w => w.CurrentCustomer).Returns(customer);
+ var contextAccessor = new Mock<IContextAccessor>();
+ contextAccessor.Setup(c => c.WorkContext).Returns(workContext.Object);
+ return new StoreTaxCategoryDataScope(contextAccessor.Object);
+ }
+
+ [TestMethod]
+ public async Task HasAccess_ExactStoreMatch_ReturnsTrue()
+ {
+ var scope = CreateScope("store-1");
+ var category = new TaxCategory { StoreId = "store-1" };
+ Assert.IsTrue(await scope.HasAccess(category));
+ }
+
+ [TestMethod]
+ public async Task HasAccess_DifferentStore_ReturnsFalse()
+ {
+ var scope = CreateScope("store-1");
+ var category = new TaxCategory { StoreId = "store-2" };
+ Assert.IsFalse(await scope.HasAccess(category));
+ }
+
+ [TestMethod]
+ public async Task HasAccess_GlobalCategory_ReturnsFalse()
+ {
+ // Empty StoreId (global) is NOT owned by any store — a store manager can never
+ // edit/delete a global tax category, matching the original controller's
+ // `taxCategory.StoreId != CurrentStoreId` check (empty never equals a real store id).
+ var scope = CreateScope("store-1");
+ var category = new TaxCategory { StoreId = "" };
+ Assert.IsFalse(await scope.HasAccess(category));
+ }
+
+ [TestMethod]
+ public async Task HasAccess_NullEntity_ReturnsFalse()
+ {
+ var scope = CreateScope("store-1");
+ Assert.IsFalse(await scope.HasAccess(null!));
+ }
+
+ [TestMethod]
+ public void DefaultStoreId_ReturnsStaffStoreId()
+ {
+ var scope = CreateScope("store-1");
+ Assert.AreEqual("store-1", scope.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public void ShowStoreSelector_ReturnsFalse()
+ {
+ var scope = CreateScope("store-1");
+ Assert.IsFalse(scope.ShowStoreSelector);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/TaxControllerAttributeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/TaxControllerAttributeTests.cs
new file mode 100644
index 000000000..0a8a52698
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/TaxControllerAttributeTests.cs
@@ -0,0 +1,43 @@
+using System.Linq;
+using Grand.Web.Admin.Controllers;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class TaxControllerAttributeTests
+{
+ [TestMethod]
+ public void IsSubclassOfBaseTaxCategoryController()
+ {
+ Assert.IsTrue(typeof(BaseTaxCategoryController).IsAssignableFrom(typeof(TaxController)));
+ Assert.AreEqual(typeof(BaseTaxCategoryController), typeof(TaxController).BaseType);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeAdminAttribute()
+ {
+ var attr = typeof(TaxController).GetCustomAttributes(typeof(AuthorizeAdminAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAreaAdminAttribute()
+ {
+ var attr = typeof(TaxController)
+ .GetCustomAttributes(typeof(AreaAttribute), inherit: false)
+ .Cast<AreaAttribute>().Single();
+ Assert.AreEqual("Admin", attr.RouteValue);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeMenuAttribute()
+ {
+ var attr = typeof(TaxController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+}
diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/TaxControllerAttributeTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/TaxControllerAttributeTests.cs
new file mode 100644
index 000000000..3f6066c06
--- /dev/null
+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/TaxControllerAttributeTests.cs
@@ -0,0 +1,43 @@
+using System.Linq;
+using Grand.Web.AdminShared.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Common.Security.Authorization;
+using Grand.Web.Store.Controllers;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Store.Tests.Controllers;
+
+[TestClass]
+public class TaxControllerAttributeTests
+{
+ [TestMethod]
+ public void IsSubclassOfBaseTaxCategoryController()
+ {
+ Assert.IsTrue(typeof(BaseTaxCategoryController).IsAssignableFrom(typeof(TaxController)));
+ Assert.AreEqual(typeof(BaseTaxCategoryController), typeof(TaxController).BaseType);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeStoreAttribute()
+ {
+ var attr = typeof(TaxController).GetCustomAttributes(typeof(AuthorizeStoreAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAreaStoreAttribute()
+ {
+ var attr = typeof(TaxController)
+ .GetCustomAttributes(typeof(AreaAttribute), inherit: false)
+ .Cast<AreaAttribute>().Single();
+ Assert.AreEqual("Store", attr.RouteValue);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeMenuAttribute()
+ {
+ var attr = typeof(TaxController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+}
diff --git a/src/Web/Grand.Web.Admin/Controllers/TaxController.cs b/src/Web/Grand.Web.Admin/Controllers/TaxController.cs
index 41be5f5ff..05aa760a1 100644
--- a/src/Web/Grand.Web.Admin/Controllers/TaxController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/TaxController.cs
@@ -1,73 +1,82 @@
-using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Core.Interfaces.Catalog.Tax;
using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Stores;
-using Grand.Domain.Permissions;
+using Grand.Domain.Common;
+using Grand.Domain.Customers;
using Grand.Domain.Directory;
using Grand.Domain.Tax;
+using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Plugins;
+using Grand.Web.Admin.Extensions;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Extensions.Mapping;
using Grand.Web.AdminShared.Extensions.Mapping.Settings;
+using Grand.Web.AdminShared.Interfaces;
using Grand.Web.AdminShared.Models.Common;
using Grand.Web.AdminShared.Models.Tax;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Extensions;
+using Grand.Web.Common.Filters;
using Grand.Web.Common.Localization;
-using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Grand.Web.Admin.Controllers;
-[PermissionAuthorize(PermissionSystemName.TaxSettings)]
-public class TaxController : BaseAdminController
+// Attributes are restated here (and on Store's TaxController) because they used to arrive
+// transitively via BaseAdminController/BaseStoreController - BaseTaxCategoryController (used
+// instead now) can't inherit either, since it must stay host-agnostic: Admin, Store, and
+// (hypothetically) Vendor all extend it.
+[AuthorizeAdmin]
+[Area(Constants.AreaAdmin)]
+[AuthorizeMenu]
+public class TaxController(
+ ITaxService taxService,
+ ITaxCategoryService taxCategoryService,
+ ISettingService settingService,
+ IServiceProvider serviceProvider,
+ ICacheBase cacheBase,
+ ITranslationService translationService,
+ ICountryService countryService,
+ IStoreService storeService,
+ IEnumTranslationService enumTranslationService,
+ IContextAccessor contextAccessor,
+ IAdminDataScope<TaxCategory> scope)
+ : BaseTaxCategoryController(taxCategoryService, storeService, translationService, scope)
{
- #region Constructors
-
- public TaxController(ITaxService taxService,
- ITaxCategoryService taxCategoryService,
- ISettingService settingService,
- IServiceProvider serviceProvider,
- ICacheBase cacheBase,
- ITranslationService translationService,
- ICountryService countryService,
- IStoreService storeService,
- IEnumTranslationService enumTranslationService)
+ /// <summary>
+ /// Get active store scope (for multi-store configuration mode)
+ /// </summary>
+ /// <returns>Store ID; 0 if we are in a shared mode</returns>
+ private async Task<string> GetActiveStore()
{
- _taxService = taxService;
- _taxCategoryService = taxCategoryService;
- _settingService = settingService;
- _serviceProvider = serviceProvider;
- _cacheBase = cacheBase;
- _translationService = translationService;
- _countryService = countryService;
- _storeService = storeService;
- _enumTranslationService = enumTranslationService;
- }
+ var workContext = contextAccessor.WorkContext;
- #endregion
+ var stores = await storeService.GetAllStores();
+ if (stores.Count < 2)
+ return stores.FirstOrDefault()?.Id;
- #region Fields
-
- private readonly ITaxService _taxService;
- private readonly ITaxCategoryService _taxCategoryService;
- private readonly ISettingService _settingService;
- private readonly IServiceProvider _serviceProvider;
- private readonly ICacheBase _cacheBase;
- private readonly ITranslationService _translationService;
- private readonly ICountryService _countryService;
- private readonly IStoreService _storeService;
- private readonly IEnumTranslationService _enumTranslationService;
-
- #endregion
+ var storeId =
+ workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames
+ .AdminAreaStoreScopeConfiguration);
+ //empty scope means "all stores" - settings are loaded from/saved to the global scope
+ if (string.IsNullOrEmpty(storeId))
+ {
+ return "";
+ }
+
+ var store = await storeService.GetStoreById(storeId);
+ return store != null ? store.Id : "";
+ }
#region Tax Providers
protected async Task ClearCache()
{
- await _cacheBase.Clear();
+ await cacheBase.Clear();
}
public IActionResult Providers()
@@ -79,9 +88,9 @@ public class TaxController : BaseAdminController
public async Task<IActionResult> Providers(DataSourceRequest command)
{
var storeScope = await GetActiveStore();
- var taxProviderSettings = await _settingService.LoadSetting<TaxProviderSettings>(storeScope);
+ var taxProviderSettings = await settingService.LoadSetting<TaxProviderSettings>(storeScope);
- var taxProviders = _taxService.LoadAllTaxProviders()
+ var taxProviders = taxService.LoadAllTaxProviders()
.ToList();
var taxProvidersModel = new List<TaxProviderModel>();
foreach (var tax in taxProviders)
@@ -91,7 +100,7 @@ public class TaxController : BaseAdminController
if (string.IsNullOrEmpty(url))
url = PluginManager.ReferencedPlugins.FirstOrDefault(x =>
x.SystemName.Equals(tax.SystemName, StringComparison.OrdinalIgnoreCase))
- ?.Instance<IPlugin>(_serviceProvider)?.ConfigurationUrl();
+ ?.Instance<IPlugin>(serviceProvider)?.ConfigurationUrl();
tmp.ConfigurationUrl = url;
tmp.IsPrimaryTaxProvider = tmp.SystemName.Equals(taxProviderSettings.ActiveTaxProviderSystemName,
@@ -110,14 +119,14 @@ public class TaxController : BaseAdminController
public async Task<IActionResult> MarkAsPrimaryProvider(string systemName)
{
var storeScope = await GetActiveStore();
- var taxProviderettings = await _settingService.LoadSetting<TaxProviderSettings>(storeScope);
+ var taxProviderettings = await settingService.LoadSetting<TaxProviderSettings>(storeScope);
if (string.IsNullOrEmpty(systemName)) return RedirectToAction("Providers");
- var taxProvider = _taxService.LoadTaxProviderBySystemName(systemName);
+ var taxProvider = taxService.LoadTaxProviderBySystemName(systemName);
if (taxProvider != null)
{
taxProviderettings.ActiveTaxProviderSystemName = systemName;
- await _settingService.SaveSetting(taxProviderettings, storeScope);
+ await settingService.SaveSetting(taxProviderettings, storeScope);
}
//now clear cache
@@ -134,43 +143,43 @@ public class TaxController : BaseAdminController
{
//load settings for a chosen store scope
var storeScope = await GetActiveStore();
- var taxSettings = await _settingService.LoadSetting<TaxSettings>(storeScope);
+ var taxSettings = await settingService.LoadSetting<TaxSettings>(storeScope);
var model = taxSettings.ToModel();
model.ActiveStore = storeScope;
- model.TaxBasedOnValues = _enumTranslationService.ToSelectList(taxSettings.TaxBasedOn);
- model.TaxDisplayTypeValues = _enumTranslationService.ToSelectList(taxSettings.TaxDisplayType);
+ model.TaxBasedOnValues = enumTranslationService.ToSelectList(taxSettings.TaxBasedOn);
+ model.TaxDisplayTypeValues = enumTranslationService.ToSelectList(taxSettings.TaxDisplayType);
//tax categories
- var taxCategories = await _taxCategoryService.GetAllTaxCategories();
+ var taxCategories = await taxCategoryService.GetAllTaxCategories();
model.TaxCategories.Add(new SelectListItem {
- Text = _translationService.GetResource("Admin.Configuration.Tax.Settings.TaxCategories.None"), Value = ""
+ Text = translationService.GetResource("Admin.Configuration.Tax.Settings.TaxCategories.None"), Value = ""
});
foreach (var tc in taxCategories)
model.TaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id });
//EU VAT countries
model.EuVatShopCountries.Add(new SelectListItem
- { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });
- foreach (var c in await _countryService.GetAllCountries(showHidden: true))
+ { Text = translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });
+ foreach (var c in await countryService.GetAllCountries(showHidden: true))
model.EuVatShopCountries.Add(new SelectListItem
{ Text = c.Name, Value = c.Id, Selected = c.Id == taxSettings.EuVatShopCountryId });
//default tax address
var defaultAddress = taxSettings.DefaultTaxAddress;
if (defaultAddress != null)
- model.DefaultTaxAddress = await defaultAddress.ToModel(_countryService);
+ model.DefaultTaxAddress = await defaultAddress.ToModel(countryService);
else
model.DefaultTaxAddress = new AddressModel();
model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem
- { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });
- foreach (var c in await _countryService.GetAllCountries(showHidden: true))
+ { Text = translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });
+ foreach (var c in await countryService.GetAllCountries(showHidden: true))
model.DefaultTaxAddress.AvailableCountries.Add(new SelectListItem
{ Text = c.Name, Value = c.Id, Selected = defaultAddress != null && c.Id == defaultAddress.CountryId });
var states = defaultAddress != null && !string.IsNullOrEmpty(defaultAddress.CountryId)
- ? (await _countryService.GetCountryById(defaultAddress.CountryId))?.StateProvinces
+ ? (await countryService.GetCountryById(defaultAddress.CountryId))?.StateProvinces
: new List<StateProvince>();
if (states?.Count > 0)
foreach (var s in states)
@@ -190,15 +199,15 @@ public class TaxController : BaseAdminController
{
//load settings for a chosen store scope
var storeScope = await GetActiveStore();
- var taxSettings = await _settingService.LoadSetting<TaxSettings>(storeScope);
+ var taxSettings = await settingService.LoadSetting<TaxSettings>(storeScope);
taxSettings = model.ToEntity(taxSettings);
- await _settingService.SaveSetting(taxSettings, storeScope);
+ await settingService.SaveSetting(taxSettings, storeScope);
//now clear cache
await ClearCache();
- Success(_translationService.GetResource("Admin.Configuration.Updated"));
+ Success(translationService.GetResource("Admin.Configuration.Updated"));
return RedirectToAction("Settings");
}
@@ -210,66 +219,11 @@ public class TaxController : BaseAdminController
{
var model = new TaxCategoryListModel();
model.AvailableStores.Add(new SelectListItem
- { Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
- foreach (var s in await _storeService.GetAllStores())
+ { 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);
}
- [HttpPost]
- public async Task<IActionResult> Categories(DataSourceRequest command)
- {
- var storeMap = (await _storeService.GetAllStores()).ToDictionary(s => s.Id, s => s.Shortcut);
- var categoriesModel = (await _taxCategoryService.GetAllTaxCategories())
- .Select(x => {
- var m = x.ToModel();
- m.StoreName = !string.IsNullOrEmpty(x.StoreId) && storeMap.TryGetValue(x.StoreId, out var name)
- ? name
- : _translationService.GetResource("Admin.Common.All");
- return m;
- })
- .ToList();
- var gridModel = new DataSourceResult {
- Data = categoriesModel,
- Total = categoriesModel.Count
- };
- return Json(gridModel);
- }
-
- [HttpPost]
- public async Task<IActionResult> CategoryUpdate(TaxCategoryModel model)
- {
- if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
-
- var taxCategory = await _taxCategoryService.GetTaxCategoryById(model.Id);
- taxCategory = model.ToEntity(taxCategory);
- await _taxCategoryService.UpdateTaxCategory(taxCategory);
-
- return new JsonResult("");
- }
-
- [HttpPost]
- public async Task<IActionResult> CategoryAdd(TaxCategoryModel model)
- {
- if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
-
- var taxCategory = new TaxCategory();
- taxCategory = model.ToEntity(taxCategory);
- await _taxCategoryService.InsertTaxCategory(taxCategory);
-
- return new JsonResult("");
- }
-
- [HttpPost]
- public async Task<IActionResult> CategoryDelete(string id)
- {
- var taxCategory = await _taxCategoryService.GetTaxCategoryById(id);
- if (taxCategory == null)
- throw new ArgumentException("No tax category found with the specified id");
- await _taxCategoryService.DeleteTaxCategory(taxCategory);
-
- return new JsonResult("");
- }
-
#endregion
-}
\ No newline at end of file
+}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseTaxCategoryController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseTaxCategoryController.cs
new file mode 100644
index 000000000..b58740ffc
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseTaxCategoryController.cs
@@ -0,0 +1,106 @@
+#nullable enable
+
+using Grand.Business.Core.Interfaces.Catalog.Tax;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Domain.Permissions;
+using Grand.Domain.Tax;
+using Grand.Web.AdminShared.Extensions.Mapping;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Models.Tax;
+using Grand.Web.Common.Controllers;
+using Grand.Web.Common.DataSource;
+using Grand.Web.Common.Extensions;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+// Holds only the TaxCategory CRUD region of TaxController — Providers/Settings are not entity-
+// shaped (no IAdminDataScope<TEntity> to apply) and stay duplicated in each host's own
+// TaxController (see the design spec). [PermissionAuthorize] is safe on the base itself (it's
+// not host-specific, unlike [Area]/[AuthorizeAdmin]/[AuthorizeStore]/[AuthorizeMenu], which every
+// concrete subclass must restate individually).
+[PermissionAuthorize(PermissionSystemName.TaxSettings)]
+[AutoValidateAntiforgeryToken]
+public abstract class BaseTaxCategoryController(
+ ITaxCategoryService taxCategoryService,
+ IStoreService storeService,
+ ITranslationService translationService,
+ IAdminDataScope<TaxCategory> scope)
+ : BaseController
+{
+ [HttpPost]
+ [PermissionAuthorizeAction(PermissionActionName.List)]
+ public virtual async Task<IActionResult> Categories(DataSourceRequest command)
+ {
+ var categories = await taxCategoryService.GetAllTaxCategories(scope.DefaultStoreId ?? "");
+
+ Dictionary<string, string>? storeMap = null;
+ if (scope.ShowStoreSelector)
+ storeMap = (await storeService.GetAllStores()).ToDictionary(s => s.Id, s => s.Shortcut);
+
+ var categoriesModel = categories
+ .Select(x => {
+ var m = x.ToModel();
+ m.StoreName = storeMap is null
+ ? string.Empty
+ : !string.IsNullOrEmpty(x.StoreId) && storeMap.TryGetValue(x.StoreId, out var name)
+ ? name
+ : translationService.GetResource("Admin.Common.All");
+ return m;
+ })
+ .ToList();
+
+ var gridModel = new DataSourceResult {
+ Data = categoriesModel,
+ Total = categoriesModel.Count
+ };
+ return Json(gridModel);
+ }
+
+ [HttpPost]
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ public virtual async Task<IActionResult> CategoryUpdate(TaxCategoryModel model)
+ {
+ if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+
+ var taxCategory = await taxCategoryService.GetTaxCategoryById(model.Id);
+ if (taxCategory == null || !await scope.HasAccess(taxCategory))
+ return new JsonResult("");
+
+ taxCategory = model.ToEntity(taxCategory);
+ if (scope.DefaultStoreId is not null)
+ taxCategory.StoreId = scope.DefaultStoreId;
+ await taxCategoryService.UpdateTaxCategory(taxCategory);
+
+ return new JsonResult("");
+ }
+
+ [HttpPost]
+ [PermissionAuthorizeAction(PermissionActionName.Create)]
+ public virtual async Task<IActionResult> CategoryAdd(TaxCategoryModel model)
+ {
+ if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
+
+ var taxCategory = new TaxCategory();
+ taxCategory = model.ToEntity(taxCategory);
+ if (scope.DefaultStoreId is not null)
+ taxCategory.StoreId = scope.DefaultStoreId;
+ await taxCategoryService.InsertTaxCategory(taxCategory);
+
+ return new JsonResult("");
+ }
+
+ [HttpPost]
+ [PermissionAuthorizeAction(PermissionActionName.Delete)]
+ public virtual async Task<IActionResult> CategoryDelete(string id)
+ {
+ var taxCategory = await taxCategoryService.GetTaxCategoryById(id);
+ if (taxCategory == null || !await scope.HasAccess(taxCategory))
+ return new JsonResult("");
+ await taxCategoryService.DeleteTaxCategory(taxCategory);
+
+ return new JsonResult("");
+ }
+}
diff --git a/src/Web/Grand.Web.AdminShared/Services/RoutedTaxCategoryDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/RoutedTaxCategoryDataScope.cs
new file mode 100644
index 000000000..8861a1ae2
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Services/RoutedTaxCategoryDataScope.cs
@@ -0,0 +1,48 @@
+#nullable enable
+
+using Grand.Domain.Tax;
+using Grand.Web.AdminShared.Interfaces;
+using Microsoft.AspNetCore.Http;
+
+namespace Grand.Web.AdminShared.Services;
+
+/// <summary>
+/// Resolves the correct per-host <see cref="IAdminDataScope{TaxCategory}" /> implementation
+/// at request time, based on the current request's "area" route value — same fix and same
+/// reason as <see cref="RoutedEmailAccountDataScope"/> (see that file's doc comment):
+/// Grand.Web (the combined host) loads Admin and Store together in one DI container, so a
+/// plain AddScoped&lt;IAdminDataScope&lt;TaxCategory&gt;, X&gt;() per host would silently
+/// let whichever host's StartupApplication ran last win for every area in that process.
+///
+/// There is no Vendor branch: Vendor has no TaxController at all, so any "Vendor" (or other
+/// unrecognized/missing) area value fails closed.
+/// </summary>
+public class RoutedTaxCategoryDataScope(
+ IHttpContextAccessor httpContextAccessor,
+ GlobalAdminDataScope<TaxCategory> globalScope,
+ StoreTaxCategoryDataScope storeScope) : IAdminDataScope<TaxCategory>
+{
+ private IAdminDataScope<TaxCategory> 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" - TaxCategory has no Vendor screen) must
+ //never silently resolve to the unscoped global scope
+ _ => throw new InvalidOperationException(
+ $"RoutedTaxCategoryDataScope: unrecognized or missing area '{area}'.")
+ };
+ }
+ }
+
+ public Task<bool> HasAccess(TaxCategory entity) => Resolved.HasAccess(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/Services/StoreTaxCategoryDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/StoreTaxCategoryDataScope.cs
new file mode 100644
index 000000000..ed725f3b2
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Services/StoreTaxCategoryDataScope.cs
@@ -0,0 +1,28 @@
+#nullable enable
+
+using Grand.Domain.Tax;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Interfaces;
+
+namespace Grand.Web.AdminShared.Services;
+
+/// <summary>
+/// Store's <see cref="IAdminDataScope{TaxCategory}" />. Bespoke, not the generic
+/// <see cref="StoreAdminDataScope{TEntity}" />: <c>TaxCategory</c> is a plain
+/// <c>BaseEntity</c> with a flat <c>StoreId</c> string (empty means global/shared), not
+/// <c>IStoreLinkEntity</c> — ownership is a single exact-match comparison, not a
+/// <c>Stores.Contains</c> list check. Same shape as <see cref="StoreOrderDataScope"/>/
+/// <see cref="StoreEmailAccountDataScope"/>.
+/// </summary>
+public class StoreTaxCategoryDataScope(IContextAccessor contextAccessor) : IAdminDataScope<TaxCategory>
+{
+ public Task<bool> HasAccess(TaxCategory entity) =>
+ Task.FromResult(entity is not null &&
+ entity.StoreId == contextAccessor.WorkContext.CurrentCustomer.StaffStoreId);
+
+ public string? DefaultStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
+ public string ResourceKeyPrefix => "Admin";
+ public bool ShowStoreSelector => false; // Store's grid never shows an editable store column
+ public string? DefaultVendorId => null;
+ public bool CanFeatureOnHomepage => true;
+}
diff --git a/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs b/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
index 4651040ed..4557caf05 100644
--- a/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
+++ b/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
@@ -11,6 +11,7 @@ using Grand.Domain.Orders;
using Grand.Domain.Pages;
using Grand.Domain.Payments;
using Grand.Domain.Shipping;
+using Grand.Domain.Tax;
using Grand.Domain.Vendors;
using Grand.Infrastructure;
using Grand.Web.AdminShared.Interfaces;
@@ -173,6 +174,13 @@ public class StartupApplication : IStartupApplication
services.AddScoped<StoreEmailAccountDataScope>();
services.AddScoped<IAdminDataScope<EmailAccount>, RoutedEmailAccountDataScope>();
+ // IAdminDataScope<TaxCategory>: registered once here for the same reason as EmailAccount
+ // above — see RoutedTaxCategoryDataScope's doc comment. No Vendor scope: Tax has no
+ // Vendor screen.
+ services.AddScoped<GlobalAdminDataScope<TaxCategory>>();
+ services.AddScoped<StoreTaxCategoryDataScope>();
+ services.AddScoped<IAdminDataScope<TaxCategory>, RoutedTaxCategoryDataScope>();
+
// IReportDataScope: NOT an IAdminDataScope<TEntity> registration (Reports has no entity —
// see IReportDataScope's doc comment and ARCH-001 Reports consolidation spec §3). All three
// hosts have a Reports screen, so all three concrete scopes are registered.
diff --git a/src/Web/Grand.Web.Store/Controllers/TaxController.cs b/src/Web/Grand.Web.Store/Controllers/TaxController.cs
index ac4641816..b3d214130 100644
--- a/src/Web/Grand.Web.Store/Controllers/TaxController.cs
+++ b/src/Web/Grand.Web.Store/Controllers/TaxController.cs
@@ -2,27 +2,38 @@ using Grand.Business.Core.Interfaces.Catalog.Tax;
using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Domain.Directory;
using Grand.Domain.Permissions;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Plugins;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Extensions.Mapping;
using Grand.Web.AdminShared.Extensions.Mapping.Settings;
+using Grand.Web.AdminShared.Interfaces;
using Grand.Web.AdminShared.Models.Common;
using Grand.Web.AdminShared.Models.Tax;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Extensions;
+using Grand.Web.Common.Filters;
using Grand.Web.Common.Localization;
using Grand.Web.Common.Security.Authorization;
+using Grand.Web.Store.Extensions;
using Grand.Web.Store.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Grand.Web.Store.Controllers;
-[PermissionAuthorize(PermissionSystemName.TaxSettings)]
+// Attributes are restated here (and on Admin's TaxController) because they used to arrive
+// transitively via BaseAdminController/BaseStoreController - BaseTaxCategoryController (used
+// instead now) can't inherit either, since it must stay host-agnostic: Admin, Store, and
+// (hypothetically) Vendor all extend it.
+[AuthorizeStore]
+[Area(Constants.AreaStore)]
+[AuthorizeMenu]
public class TaxController(
ITaxService taxService,
ITaxCategoryService taxCategoryService,
@@ -32,7 +43,10 @@ public class TaxController(
ITranslationService translationService,
ICountryService countryService,
IEnumTranslationService enumTranslationService,
- IContextAccessor contextAccessor) : BaseStoreController
+ IContextAccessor contextAccessor,
+ IStoreService storeService,
+ IAdminDataScope<TaxCategory> scope)
+ : BaseTaxCategoryController(taxCategoryService, storeService, translationService, scope)
{
private string CurrentStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
@@ -158,56 +172,5 @@ public class TaxController(
return View(new Models.TaxCategoryListModel { StoreId = CurrentStoreId });
}
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.List)]
- public async Task<IActionResult> Categories(DataSourceRequest command)
- {
- var categoriesModel = (await taxCategoryService.GetAllTaxCategories(CurrentStoreId))
- .Select(x => x.ToModel())
- .ToList();
- var gridModel = new DataSourceResult {
- Data = categoriesModel,
- Total = categoriesModel.Count
- };
- return Json(gridModel);
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- public async Task<IActionResult> CategoryUpdate(TaxCategoryModel model)
- {
- if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
- var taxCategory = await taxCategoryService.GetTaxCategoryById(model.Id);
- if (taxCategory == null || taxCategory.StoreId != CurrentStoreId)
- return new JsonResult("");
- taxCategory = model.ToEntity(taxCategory);
- taxCategory.StoreId = CurrentStoreId;
- await taxCategoryService.UpdateTaxCategory(taxCategory);
- return new JsonResult("");
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public async Task<IActionResult> CategoryAdd(TaxCategoryModel model)
- {
- if (!ModelState.IsValid) return Json(new DataSourceResult { Errors = ModelState.SerializeErrors() });
- var taxCategory = new TaxCategory { StoreId = CurrentStoreId };
- taxCategory = model.ToEntity(taxCategory);
- taxCategory.StoreId = CurrentStoreId;
- await taxCategoryService.InsertTaxCategory(taxCategory);
- return new JsonResult("");
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Delete)]
- public async Task<IActionResult> CategoryDelete(string id)
- {
- var taxCategory = await taxCategoryService.GetTaxCategoryById(id);
- if (taxCategory == null || taxCategory.StoreId != CurrentStoreId)
- return new JsonResult("");
- await taxCategoryService.DeleteTaxCategory(taxCategory);
- return new JsonResult("");
- }
-
#endregion
}