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 21: EmailAccount controller/service consolidation (Admin/Store) (#820)

Krzysztof Pajake76485a7c250
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseEmailAccountControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseEmailAccountControllerTests.cs
new file mode 100644
index 000000000..32c4edcfd
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseEmailAccountControllerTests.cs
@@ -0,0 +1,363 @@
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Messages;
+using Grand.Domain.Messages;
+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.Messages;
+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 BaseEmailAccountControllerTests
+{
+ // Concrete subclass exists only to instantiate the abstract base for direct-call unit tests -
+ // same pattern as BaseMessageTemplateControllerTests/BaseCategoryControllerTests.
+ private class TestEmailAccountController(
+ IEmailAccountViewModelService emailAccountViewModelService,
+ IEmailAccountService emailAccountService,
+ ITranslationService translationService,
+ IAdminDataScope<EmailAccount> scope)
+ : BaseEmailAccountController(emailAccountViewModelService, emailAccountService, translationService, scope);
+
+ private Mock<IEmailAccountViewModelService> _emailAccountViewModelServiceMock = null!;
+ private Mock<IEmailAccountService> _emailAccountServiceMock = null!;
+ private Mock<ITranslationService> _translationServiceMock = null!;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<EmailAccountProfile>());
+ AutoMapperConfig.Init(mapperConfig);
+
+ _emailAccountViewModelServiceMock = new Mock<IEmailAccountViewModelService>();
+ _emailAccountServiceMock = new Mock<IEmailAccountService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns((string s) => s);
+ }
+
+ private TestEmailAccountController CreateController(IAdminDataScope<EmailAccount> scope)
+ {
+ var controller = new TestEmailAccountController(
+ _emailAccountViewModelServiceMock.Object,
+ _emailAccountServiceMock.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<EmailAccount>> AdminScope()
+ {
+ var scope = new Mock<IAdminDataScope<EmailAccount>>();
+ scope.Setup(s => s.DefaultStoreId).Returns((string?)null);
+ scope.Setup(s => s.HasAccess(It.IsAny<EmailAccount>())).ReturnsAsync(true);
+ scope.Setup(s => s.ShowStoreSelector).Returns(true);
+ return scope;
+ }
+
+ private static Mock<IAdminDataScope<EmailAccount>> StoreScope(string storeId, bool hasAccess)
+ {
+ var scope = new Mock<IAdminDataScope<EmailAccount>>();
+ scope.Setup(s => s.DefaultStoreId).Returns(storeId);
+ scope.Setup(s => s.HasAccess(It.IsAny<EmailAccount>())).ReturnsAsync(hasAccess);
+ scope.Setup(s => s.ShowStoreSelector).Returns(false);
+ return scope;
+ }
+
+ // --- Create GET ---
+
+ [TestMethod]
+ public async Task CreateGet_AdminScope_DoesNotForceStoreId()
+ {
+ _emailAccountViewModelServiceMock.Setup(s => s.PrepareEmailAccountModel())
+ .ReturnsAsync(new EmailAccountModel { StoreId = "" });
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Create() as ViewResult;
+
+ var model = (EmailAccountModel)result!.Model!;
+ Assert.AreEqual("", model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task CreateGet_StoreScope_ForcesStoreId()
+ {
+ _emailAccountViewModelServiceMock.Setup(s => s.PrepareEmailAccountModel())
+ .ReturnsAsync(new EmailAccountModel { StoreId = "" });
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Create() as ViewResult;
+
+ var model = (EmailAccountModel)result!.Model!;
+ Assert.AreEqual("store-1", model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task CreateGet_AdminScope_KeepsAvailableStores()
+ {
+ _emailAccountViewModelServiceMock.Setup(s => s.PrepareEmailAccountModel())
+ .ReturnsAsync(new EmailAccountModel {
+ AvailableStores = { new SelectListItem { Value = "store-1", Text = "Store 1" } }
+ });
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Create() as ViewResult;
+
+ var model = (EmailAccountModel)result!.Model!;
+ Assert.AreEqual(1, model.AvailableStores.Count);
+ }
+
+ [TestMethod]
+ public async Task CreateGet_StoreScope_ClearsAvailableStores()
+ {
+ // Regression test for the latent cross-store leak flagged in code review: Store's own
+ // view never renders AvailableStores (it emits only a hidden StoreId input), but the
+ // shared PrepareEmailAccountModel() call always populates it - every store's id/name must
+ // not reach a model handed to Store's widget zones via additional-data="Model".
+ _emailAccountViewModelServiceMock.Setup(s => s.PrepareEmailAccountModel())
+ .ReturnsAsync(new EmailAccountModel {
+ AvailableStores = { new SelectListItem { Value = "store-1", Text = "Store 1" } }
+ });
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Create() as ViewResult;
+
+ var model = (EmailAccountModel)result!.Model!;
+ Assert.AreEqual(0, model.AvailableStores.Count);
+ }
+
+ // --- Create POST ---
+
+ [TestMethod]
+ public async Task CreatePost_StoreScope_ForcesStoreIdBeforeInsert()
+ {
+ EmailAccountModel? insertedModel = null;
+ _emailAccountViewModelServiceMock.Setup(s => s.InsertEmailAccountModel(It.IsAny<EmailAccountModel>()))
+ .Callback<EmailAccountModel>(m => insertedModel = m)
+ .ReturnsAsync(new EmailAccount { Id = "new-id" });
+ var controller = CreateController(StoreScope("store-1", true).Object);
+ var model = new EmailAccountModel { StoreId = "some-other-store" };
+
+ await controller.Create(model, false);
+
+ Assert.AreEqual("store-1", insertedModel!.StoreId);
+ }
+
+ [TestMethod]
+ public async Task CreatePost_AdminScope_LeavesPostedStoreIdUntouched()
+ {
+ EmailAccountModel? insertedModel = null;
+ _emailAccountViewModelServiceMock.Setup(s => s.InsertEmailAccountModel(It.IsAny<EmailAccountModel>()))
+ .Callback<EmailAccountModel>(m => insertedModel = m)
+ .ReturnsAsync(new EmailAccount { Id = "new-id" });
+ var controller = CreateController(AdminScope().Object);
+ var model = new EmailAccountModel { StoreId = "whatever-was-posted" };
+
+ await controller.Create(model, false);
+
+ Assert.AreEqual("whatever-was-posted", insertedModel!.StoreId);
+ }
+
+ // --- Edit GET ---
+
+ [TestMethod]
+ public async Task EditGet_NotFound_RedirectsToList()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("missing")).ReturnsAsync((EmailAccount?)null);
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Edit("missing") as RedirectToActionResult;
+
+ Assert.AreEqual("List", result!.ActionName);
+ }
+
+ [TestMethod]
+ public async Task EditGet_CrossStoreDenied_RedirectsToList()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-2" });
+ var controller = CreateController(StoreScope("store-1", false).Object);
+
+ var result = await controller.Edit("acc-1") as RedirectToActionResult;
+
+ Assert.AreEqual("List", result!.ActionName);
+ }
+
+ [TestMethod]
+ public async Task EditGet_OwnedByCurrentStore_ReturnsView()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-1", Email = "[email protected]" });
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Edit("acc-1") as ViewResult;
+
+ Assert.IsNotNull(result);
+ _emailAccountViewModelServiceMock.Verify(s => s.PrepareAvailableStores(It.IsAny<EmailAccountModel>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task EditGet_StoreScope_ClearsAvailableStores()
+ {
+ // Same leak as CreateGet_StoreScope_ClearsAvailableStores, via PrepareAvailableStores
+ // instead of PrepareEmailAccountModel.
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-1", Email = "[email protected]" });
+ _emailAccountViewModelServiceMock
+ .Setup(s => s.PrepareAvailableStores(It.IsAny<EmailAccountModel>()))
+ .Callback<EmailAccountModel>(m => m.AvailableStores.Add(new SelectListItem { Value = "store-1", Text = "Store 1" }))
+ .Returns(Task.CompletedTask);
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Edit("acc-1") as ViewResult;
+
+ var model = (EmailAccountModel)result!.Model!;
+ Assert.AreEqual(0, model.AvailableStores.Count);
+ }
+
+ [TestMethod]
+ public async Task EditGet_AdminScope_KeepsAvailableStores()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-1", Email = "[email protected]" });
+ _emailAccountViewModelServiceMock
+ .Setup(s => s.PrepareAvailableStores(It.IsAny<EmailAccountModel>()))
+ .Callback<EmailAccountModel>(m => m.AvailableStores.Add(new SelectListItem { Value = "store-1", Text = "Store 1" }))
+ .Returns(Task.CompletedTask);
+ var controller = CreateController(AdminScope().Object);
+
+ var result = await controller.Edit("acc-1") as ViewResult;
+
+ var model = (EmailAccountModel)result!.Model!;
+ Assert.AreEqual(1, model.AvailableStores.Count);
+ }
+
+ // --- Edit POST ---
+
+ [TestMethod]
+ public async Task EditPost_StoreScope_PreventsMovingToAnotherStore()
+ {
+ var existing = new EmailAccount { Id = "acc-1", StoreId = "store-1" };
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1")).ReturnsAsync(existing);
+ EmailAccountModel? updatedModel = null;
+ _emailAccountViewModelServiceMock
+ .Setup(s => s.UpdateEmailAccountModel(existing, It.IsAny<EmailAccountModel>()))
+ .Callback<EmailAccount, EmailAccountModel>((_, m) => updatedModel = m)
+ .ReturnsAsync(existing);
+ var controller = CreateController(StoreScope("store-1", true).Object);
+ var model = new EmailAccountModel { Id = "acc-1", StoreId = "store-2" };
+
+ await controller.Edit(model, false);
+
+ Assert.AreEqual("store-1", updatedModel!.StoreId);
+ }
+
+ [TestMethod]
+ public async Task EditPost_CrossStoreDenied_RedirectsToList_NoUpdateCalled()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-2" });
+ var controller = CreateController(StoreScope("store-1", false).Object);
+
+ var result = await controller.Edit(new EmailAccountModel { Id = "acc-1" }, false) as RedirectToActionResult;
+
+ Assert.AreEqual("List", result!.ActionName);
+ _emailAccountViewModelServiceMock.Verify(
+ s => s.UpdateEmailAccountModel(It.IsAny<EmailAccount>(), It.IsAny<EmailAccountModel>()), Times.Never);
+ }
+
+ // --- SendTestEmail ---
+
+ [TestMethod]
+ public async Task SendTestEmail_CrossStoreDenied_RedirectsToList()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-2" });
+ var controller = CreateController(StoreScope("store-1", false).Object);
+
+ var result = await controller.SendTestEmail(new EmailAccountModel { Id = "acc-1" }) as RedirectToActionResult;
+
+ Assert.AreEqual("List", result!.ActionName);
+ _emailAccountViewModelServiceMock.Verify(
+ s => s.SendTestEmail(It.IsAny<EmailAccount>(), It.IsAny<EmailAccountModel>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task SendTestEmail_Owned_CallsService()
+ {
+ var account = new EmailAccount { Id = "acc-1", StoreId = "store-1" };
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1")).ReturnsAsync(account);
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ await controller.SendTestEmail(new EmailAccountModel { Id = "acc-1", SendTestEmailTo = "[email protected]" });
+
+ _emailAccountViewModelServiceMock.Verify(s => s.SendTestEmail(account, It.IsAny<EmailAccountModel>()), Times.Once);
+ }
+
+ // --- Delete ---
+
+ [TestMethod]
+ public async Task Delete_CrossStoreDenied_RedirectsToList_NoDeleteCalled()
+ {
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1"))
+ .ReturnsAsync(new EmailAccount { Id = "acc-1", StoreId = "store-2" });
+ var controller = CreateController(StoreScope("store-1", false).Object);
+
+ var result = await controller.Delete("acc-1") as RedirectToActionResult;
+
+ Assert.AreEqual("List", result!.ActionName);
+ _emailAccountServiceMock.Verify(s => s.DeleteEmailAccount(It.IsAny<EmailAccount>()), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task Delete_Owned_CallsServiceAndRedirectsToList()
+ {
+ var account = new EmailAccount { Id = "acc-1", StoreId = "store-1" };
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1")).ReturnsAsync(account);
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Delete("acc-1") as RedirectToActionResult;
+
+ Assert.AreEqual("List", result!.ActionName);
+ _emailAccountServiceMock.Verify(s => s.DeleteEmailAccount(account), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task Delete_ServiceThrowsNonGrandException_CaughtAndRedirectsToEdit()
+ {
+ // Regression test for the deliberate catch(Exception) widening: a plain
+ // InvalidOperationException (not a GrandException) must be caught here, not propagate as
+ // an unhandled 500 the way it would have on Store's original narrower catch.
+ var account = new EmailAccount { Id = "acc-1", StoreId = "store-1" };
+ _emailAccountServiceMock.Setup(s => s.GetEmailAccountById("acc-1")).ReturnsAsync(account);
+ _emailAccountServiceMock.Setup(s => s.DeleteEmailAccount(account))
+ .ThrowsAsync(new InvalidOperationException("boom"));
+ var controller = CreateController(StoreScope("store-1", true).Object);
+
+ var result = await controller.Delete("acc-1") as RedirectToActionResult;
+
+ Assert.AreEqual("Edit", result!.ActionName);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/EmailAccountControllerAttributeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/EmailAccountControllerAttributeTests.cs
new file mode 100644
index 000000000..92fdb59ba
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/EmailAccountControllerAttributeTests.cs
@@ -0,0 +1,51 @@
+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 EmailAccountControllerAttributeTests
+{
+ [TestMethod]
+ public void IsSubclassOfBaseEmailAccountController()
+ {
+ Assert.IsTrue(typeof(BaseEmailAccountController).IsAssignableFrom(typeof(EmailAccountController)));
+ Assert.AreEqual(typeof(BaseEmailAccountController), typeof(EmailAccountController).BaseType);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeAdminAttribute()
+ {
+ var attr = typeof(EmailAccountController).GetCustomAttributes(typeof(AuthorizeAdminAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAreaAdminAttribute()
+ {
+ var attr = typeof(EmailAccountController)
+ .GetCustomAttributes(typeof(AreaAttribute), inherit: false)
+ .Cast<AreaAttribute>().Single();
+ Assert.AreEqual("Admin", attr.RouteValue);
+ }
+
+ [TestMethod]
+ public void HasAutoValidateAntiforgeryTokenAttribute()
+ {
+ var attr = typeof(EmailAccountController)
+ .GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: true);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeMenuAttribute()
+ {
+ var attr = typeof(EmailAccountController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedEmailAccountDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedEmailAccountDataScopeTests.cs
new file mode 100644
index 000000000..678892bf7
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedEmailAccountDataScopeTests.cs
@@ -0,0 +1,86 @@
+using Grand.Domain.Customers;
+using Grand.Domain.Messages;
+using Grand.Infrastructure;
+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 RoutedEmailAccountDataScopeTests
+{
+ 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 StoreEmailAccountDataScope 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 StoreEmailAccountDataScope(contextAccessor.Object);
+ }
+
+ [TestMethod]
+ public async Task AdminArea_ResolvesToGlobalScope_HasAccessAlwaysTrue()
+ {
+ var routed = new RoutedEmailAccountDataScope(
+ CreateHttpContextAccessor("Admin"),
+ new GlobalAdminDataScope<EmailAccount>(),
+ CreateStoreScope("store-1"));
+
+ var account = new EmailAccount { StoreId = "store-2" };
+ Assert.IsTrue(await routed.HasAccess(account));
+ Assert.IsNull(routed.DefaultStoreId);
+ }
+
+ [TestMethod]
+ public async Task StoreArea_ResolvesToStoreScope_HasAccessScoped()
+ {
+ var routed = new RoutedEmailAccountDataScope(
+ CreateHttpContextAccessor("Store"),
+ new GlobalAdminDataScope<EmailAccount>(),
+ CreateStoreScope("store-1"));
+
+ var owned = new EmailAccount { StoreId = "store-1" };
+ var notOwned = new EmailAccount { 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 RoutedEmailAccountDataScope(
+ CreateHttpContextAccessor("Vendor"),
+ new GlobalAdminDataScope<EmailAccount>(),
+ CreateStoreScope("store-1"));
+
+ await Assert.ThrowsAsync<InvalidOperationException>(
+ () => routed.HasAccess(new EmailAccount { StoreId = "store-1" }));
+ }
+
+ [TestMethod]
+ public async Task MissingArea_ThrowsInvalidOperationException()
+ {
+ var routed = new RoutedEmailAccountDataScope(
+ CreateHttpContextAccessor(null),
+ new GlobalAdminDataScope<EmailAccount>(),
+ CreateStoreScope("store-1"));
+
+ await Assert.ThrowsAsync<InvalidOperationException>(
+ () => routed.HasAccess(new EmailAccount { StoreId = "store-1" }));
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreEmailAccountDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreEmailAccountDataScopeTests.cs
new file mode 100644
index 000000000..352bbb544
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreEmailAccountDataScopeTests.cs
@@ -0,0 +1,70 @@
+using Grand.Domain.Customers;
+using Grand.Domain.Messages;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Services;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Controllers;
+
+[TestClass]
+public class StoreEmailAccountDataScopeTests
+{
+ private static StoreEmailAccountDataScope 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 StoreEmailAccountDataScope(contextAccessor.Object);
+ }
+
+ [TestMethod]
+ public async Task HasAccess_ExactStoreMatch_ReturnsTrue()
+ {
+ var scope = CreateScope("store-1");
+ var account = new EmailAccount { StoreId = "store-1" };
+ Assert.IsTrue(await scope.HasAccess(account));
+ }
+
+ [TestMethod]
+ public async Task HasAccess_DifferentStore_ReturnsFalse()
+ {
+ var scope = CreateScope("store-1");
+ var account = new EmailAccount { StoreId = "store-2" };
+ Assert.IsFalse(await scope.HasAccess(account));
+ }
+
+ [TestMethod]
+ public async Task HasAccess_GlobalAccount_ReturnsFalse()
+ {
+ // Empty StoreId (global) is NOT owned by any store — Store can never manage a global
+ // account, matching the original controller's `emailAccount.StoreId != CurrentStoreId`
+ // check (empty never equals a real store id) and GetAllEmailAccounts' exact-match filter.
+ var scope = CreateScope("store-1");
+ var account = new EmailAccount { StoreId = "" };
+ Assert.IsFalse(await scope.HasAccess(account));
+ }
+
+ [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.Store.Tests/Controllers/EmailAccountControllerAttributeTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/EmailAccountControllerAttributeTests.cs
new file mode 100644
index 000000000..8f54ca960
--- /dev/null
+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/EmailAccountControllerAttributeTests.cs
@@ -0,0 +1,51 @@
+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 EmailAccountControllerAttributeTests
+{
+ [TestMethod]
+ public void IsSubclassOfBaseEmailAccountController()
+ {
+ Assert.IsTrue(typeof(BaseEmailAccountController).IsAssignableFrom(typeof(EmailAccountController)));
+ Assert.AreEqual(typeof(BaseEmailAccountController), typeof(EmailAccountController).BaseType);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeStoreAttribute()
+ {
+ var attr = typeof(EmailAccountController).GetCustomAttributes(typeof(AuthorizeStoreAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAreaStoreAttribute()
+ {
+ var attr = typeof(EmailAccountController)
+ .GetCustomAttributes(typeof(AreaAttribute), inherit: false)
+ .Cast<AreaAttribute>().Single();
+ Assert.AreEqual("Store", attr.RouteValue);
+ }
+
+ [TestMethod]
+ public void HasAutoValidateAntiforgeryTokenAttribute()
+ {
+ var attr = typeof(EmailAccountController)
+ .GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: true);
+ Assert.AreEqual(1, attr.Length);
+ }
+
+ [TestMethod]
+ public void HasAuthorizeMenuAttribute()
+ {
+ var attr = typeof(EmailAccountController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);
+ Assert.AreEqual(1, attr.Length);
+ }
+}
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Create.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Create.cshtml
deleted file mode 100644
index 21efa4aa6..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Create.cshtml
+++ /dev/null
@@ -1,35 +0,0 @@
-@model EmailAccountModel
-@{
- //page title
- ViewBag.Title = Loc["Admin.Configuration.EmailAccounts.AddNew"];
-}
-<form asp-area="@Constants.AreaAdmin" asp-controller="EmailAccount" asp-action="Create" method="post">
-
- <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-users"></i>
- @Loc["Admin.Configuration.EmailAccounts.AddNew"]
- <small>
- <i class="fa fa-arrow-circle-left"></i> @Html.ActionLink(Loc["Admin.Configuration.EmailAccounts.BackToList"], "List")
- </small>
- </div>
- <div class="actions">
- <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="email_account_details_buttons" additional-data="null"/>
- </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.Admin/Areas/Admin/Views/EmailAccount/Edit.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Edit.cshtml
deleted file mode 100644
index ef72cb84d..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Edit.cshtml
+++ /dev/null
@@ -1,41 +0,0 @@
-@model EmailAccountModel
-@{
- //page title
- ViewBag.Title = Loc["Admin.Configuration.EmailAccounts.EditEmailAccountDetails"];
-}
-<form asp-area="@Constants.AreaAdmin" asp-controller="EmailAccount" asp-action="Edit" method="post">
-
- <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-users"></i>
- @Loc["Admin.Configuration.EmailAccounts.EditEmailAccountDetails"]
- <small>
- <i class="fa fa-arrow-circle-left"></i> @Html.ActionLink(Loc["Admin.Configuration.EmailAccounts.BackToList"], "List")
- </small>
- </div>
- <div class="actions">
- <div class="btn-group btn-group-devided util-btn-margin-bottom-5">
- <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="emailAccount-delete" class="btn red">
- <i class="fa fa-trash-o"></i><span class="d-none d-sm-inline"> @Loc["Admin.Common.Delete"]</span>
- </span>
- <vc:admin-widget widget-zone="email_account_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="emailAccount-delete"/>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/CreateOrUpdate.cshtml
deleted file mode 100644
index 66ca5ee47..000000000
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/CreateOrUpdate.cshtml
+++ /dev/null
@@ -1,98 +0,0 @@
-@using Grand.Business.Core.Enums.Messages
-@model EmailAccountModel
-
-<div asp-validation-summary="All"></div>
-<input asp-for="Id" type="hidden"/>
-<div class="form-horizontal">
- <vc:admin-widget widget-zone="email_account_details_top" additional-data="Model"/>
- <div class="form-body">
- <div class="form-group">
- <admin-label asp-for="Email"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="Email"/>
- <span asp-validation-for="Email"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="DisplayName"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="DisplayName"/>
- <span asp-validation-for="DisplayName"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="Host"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="Host"/>
- <span asp-validation-for="Host"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="Port"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="Port"/>
- <span asp-validation-for="Port"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="Username"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="Username"/>
- <span asp-validation-for="Username"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="Password"/>
- <div class="col-md-9 col-sm-9">
- <div class="input-group">
- <div class="input-icon">
- <i class="fa fa-lock fa-fw"></i>
- <admin-input asp-for="Password" autocomplete="off"/>
- </div>
- </div>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="UseServerCertificateValidation"/>
- <div class="col-md-9 col-sm-9">
- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">
- <admin-input asp-for="UseServerCertificateValidation"/>
- <div class="control__indicator"></div>
- </label>
- <span asp-validation-for="UseServerCertificateValidation"></span>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="SecureSocketOptionsId"/>
- <div class="col-md-9 col-sm-9">
- <admin-select asp-for="SecureSocketOptionsId" asp-items="EnumTranslationService.ToSelectList((SecureSocketOptions)Model.SecureSocketOptionsId)"/>
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="StoreId"/>
- <div class="col-md-9 col-sm-9">
- <select asp-for="StoreId" asp-items="Model.AvailableStores" class="form-control"></select>
- </div>
- </div>
- @if (!string.IsNullOrEmpty(Model.Id))
- {
- <div class="form-group">
- <div class="note note-info">
- @Loc["Admin.Configuration.EmailAccounts.SendTestEmail"]
- </div>
- </div>
- <div class="form-group">
- <admin-label asp-for="SendTestEmailTo"/>
- <div class="col-md-9 col-sm-9">
- <admin-input asp-for="SendTestEmailTo"/>
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-9 col-sm-9 offset-md-3">
- <input type="submit" name="sendtestemail" asp-action="SendTestEmail" class="k-button" value="@Loc["Admin.Configuration.EmailAccounts.SendTestEmail.Button"]"/>
- </div>
- </div>
- }
- </div>
- <vc:admin-widget widget-zone="email_account_details_bottom" additional-data="Model"/>
-</div>
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsBottom.cshtml
new file mode 100644
index 000000000..5484856df
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsBottom.cshtml
@@ -0,0 +1,2 @@
+@model Grand.Web.AdminShared.Models.Messages.EmailAccountModel
+<vc:admin-widget widget-zone="email_account_details_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsButtons.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsButtons.cshtml
new file mode 100644
index 000000000..549599b74
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsButtons.cshtml
@@ -0,0 +1,2 @@
+@model Grand.Web.AdminShared.Models.Messages.EmailAccountModel
+<vc:admin-widget widget-zone="email_account_details_buttons" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsTop.cshtml
new file mode 100644
index 000000000..5c0a70bad
--- /dev/null
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/EmailAccount/Partials/WidgetZone.DetailsTop.cshtml
@@ -0,0 +1,2 @@
+@model Grand.Web.AdminShared.Models.Messages.EmailAccountModel
+<vc:admin-widget widget-zone="email_account_details_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Admin/Controllers/EmailAccountController.cs b/src/Web/Grand.Web.Admin/Controllers/EmailAccountController.cs
index 4e94763b5..2906ac868 100644
--- a/src/Web/Grand.Web.Admin/Controllers/EmailAccountController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/EmailAccountController.cs
@@ -1,13 +1,13 @@
-using Grand.Business.Core.Interfaces.Common.Configuration;
+using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Messages;
-using Grand.Domain.Permissions;
using Grand.Domain.Messages;
+using Grand.Domain.Permissions;
using Grand.Infrastructure.Caching;
-using Grand.SharedKernel;
+using Grand.Web.Admin.Extensions;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Extensions.Mapping;
using Grand.Web.AdminShared.Interfaces;
-using Grand.Web.AdminShared.Models.Messages;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
@@ -15,29 +15,24 @@ using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Admin.Controllers;
-[PermissionAuthorize(PermissionSystemName.EmailAccounts)]
-public class EmailAccountController : BaseAdminController
+// Reduced to a thin subclass of BaseEmailAccountController (ARCH-001 EmailAccount
+// consolidation). Create/Edit/SendTestEmail/Delete live in the shared base; List (its grid data
+// needs the Admin-only IsDefaultEmailAccount stamp) and MarkAsDefaultEmail (writes a single
+// global setting, no per-store concept exists) stay here (see the design spec).
+[AuthorizeAdmin]
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaAdmin)]
+[AuthorizeMenu]
+public class EmailAccountController(
+ IEmailAccountViewModelService emailAccountViewModelService,
+ IEmailAccountService emailAccountService,
+ ITranslationService translationService,
+ IAdminDataScope<EmailAccount> scope,
+ ISettingService settingService,
+ EmailAccountSettings emailAccountSettings,
+ ICacheBase cacheBase)
+ : BaseEmailAccountController(emailAccountViewModelService, emailAccountService, translationService, scope)
{
- private readonly ICacheBase _cacheBase;
- private readonly IEmailAccountService _emailAccountService;
- private readonly EmailAccountSettings _emailAccountSettings;
- private readonly IEmailAccountViewModelService _emailAccountViewModelService;
- private readonly ISettingService _settingService;
- private readonly ITranslationService _translationService;
-
- public EmailAccountController(IEmailAccountViewModelService emailAccountViewModelService,
- IEmailAccountService emailAccountService,
- ITranslationService translationService, ISettingService settingService,
- EmailAccountSettings emailAccountSettings, ICacheBase cacheBase)
- {
- _emailAccountViewModelService = emailAccountViewModelService;
- _emailAccountService = emailAccountService;
- _translationService = translationService;
- _emailAccountSettings = emailAccountSettings;
- _settingService = settingService;
- _cacheBase = cacheBase;
- }
-
public IActionResult List()
{
return View();
@@ -47,10 +42,11 @@ public class EmailAccountController : BaseAdminController
[PermissionAuthorizeAction(PermissionActionName.List)]
public async Task<IActionResult> List(DataSourceRequest command)
{
- var emailAccounts = await _emailAccountService.GetAllEmailAccounts(pageIndex: command.Page - 1, pageSize: command.PageSize);
+ var emailAccounts = await emailAccountService.GetAllEmailAccounts(scope.DefaultStoreId ?? "",
+ pageIndex: command.Page - 1, pageSize: command.PageSize);
var emailAccountModels = emailAccounts.Select(x => x.ToModel()).ToList();
foreach (var eam in emailAccountModels)
- eam.IsDefaultEmailAccount = eam.Id == _emailAccountSettings.DefaultEmailAccountId;
+ eam.IsDefaultEmailAccount = eam.Id == emailAccountSettings.DefaultEmailAccountId;
var gridModel = new DataSourceResult {
Data = emailAccountModels,
@@ -63,134 +59,16 @@ public class EmailAccountController : BaseAdminController
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> MarkAsDefaultEmail(string id)
{
- var defaultEmailAccount = await _emailAccountService.GetEmailAccountById(id);
+ var defaultEmailAccount = await emailAccountService.GetEmailAccountById(id);
if (defaultEmailAccount != null)
{
- _emailAccountSettings.DefaultEmailAccountId = defaultEmailAccount.Id;
- await _settingService.SaveSetting(_emailAccountSettings);
+ emailAccountSettings.DefaultEmailAccountId = defaultEmailAccount.Id;
+ await settingService.SaveSetting(emailAccountSettings);
}
//now clear cache
- await _cacheBase.Clear();
+ await cacheBase.Clear();
return RedirectToAction("List");
}
-
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public async Task<IActionResult> Create()
- {
- var model = await _emailAccountViewModelService.PrepareEmailAccountModel();
- return View(model);
- }
-
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public async Task<IActionResult> Create(EmailAccountModel model, bool continueEditing)
- {
- if (ModelState.IsValid)
- {
- var emailAccount = await _emailAccountViewModelService.InsertEmailAccountModel(model);
- Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.Added"));
- return continueEditing ? RedirectToAction("Edit", new { id = emailAccount.Id }) : RedirectToAction("List");
- }
-
- //If we got this far, something failed, redisplay form
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Preview)]
- public async Task<IActionResult> Edit(string id)
- {
- var emailAccount = await _emailAccountService.GetEmailAccountById(id);
- if (emailAccount == null)
- //No email account found with the specified id
- return RedirectToAction("List");
-
- var model = emailAccount.ToModel();
- await _emailAccountViewModelService.PrepareAvailableStores(model);
- return View(model);
- }
-
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- public async Task<IActionResult> Edit(EmailAccountModel model, bool continueEditing)
- {
- var emailAccount = await _emailAccountService.GetEmailAccountById(model.Id);
- if (emailAccount == null)
- //No email account found with the specified id
- return RedirectToAction("List");
-
- if (ModelState.IsValid)
- {
- emailAccount = await _emailAccountViewModelService.UpdateEmailAccountModel(emailAccount, model);
- Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.Updated"));
- return continueEditing ? RedirectToAction("Edit", new { id = emailAccount.Id }) : RedirectToAction("List");
- }
-
- //If we got this far, something failed, redisplay form
- return View(model);
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- public async Task<IActionResult> SendTestEmail(EmailAccountModel model)
- {
- var emailAccount = await _emailAccountService.GetEmailAccountById(model.Id);
- if (emailAccount == null)
- //No email account found with the specified id
- return RedirectToAction("List");
- try
- {
- if (string.IsNullOrWhiteSpace(model.SendTestEmailTo))
- throw new GrandException("Enter test email address");
- if (ModelState.IsValid)
- {
- await _emailAccountViewModelService.SendTestEmail(emailAccount, model);
- Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.SendTestEmail.Success"),
- false);
- }
- else
- {
- Error(ModelState);
- }
- }
- catch (Exception exc)
- {
- Error(exc.Message);
- }
-
- //If we got this far, something failed, redisplay form
- return RedirectToAction("Edit", new { id = model.Id });
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Delete)]
- public async Task<IActionResult> Delete(string id)
- {
- var emailAccount = await _emailAccountService.GetEmailAccountById(id);
- if (emailAccount == null)
- //No email account found with the specified id
- return RedirectToAction("List");
- try
- {
- if (ModelState.IsValid)
- {
- await _emailAccountService.DeleteEmailAccount(emailAccount);
- Success(_translationService.GetResource("Admin.Configuration.EmailAccounts.Deleted"));
- }
- else
- {
- Error(ModelState);
- }
-
- return RedirectToAction("List");
- }
- catch (Exception exc)
- {
- Error(exc);
- return RedirectToAction("Edit", new { id = emailAccount.Id });
- }
- }
-}
\ No newline at end of file
+}
diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseEmailAccountController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseEmailAccountController.cs
new file mode 100644
index 000000000..c3ffec27c
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseEmailAccountController.cs
@@ -0,0 +1,181 @@
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Messages;
+using Grand.Domain.Messages;
+using Grand.Domain.Permissions;
+using Grand.SharedKernel;
+using Grand.Web.AdminShared.Extensions.Mapping;
+using Grand.Web.AdminShared.Interfaces;
+using Grand.Web.AdminShared.Models.Messages;
+using Grand.Web.Common.Controllers;
+using Grand.Web.Common.Filters;
+using Grand.Web.Common.Security.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Grand.Web.AdminShared.Controllers;
+
+[PermissionAuthorize(PermissionSystemName.EmailAccounts)]
+[AutoValidateAntiforgeryToken]
+public abstract class BaseEmailAccountController(
+ IEmailAccountViewModelService emailAccountViewModelService,
+ IEmailAccountService emailAccountService,
+ ITranslationService translationService,
+ IAdminDataScope<EmailAccount> scope)
+ : BaseController
+{
+ #region Create
+
+ [PermissionAuthorizeAction(PermissionActionName.Create)]
+ public async Task<IActionResult> Create()
+ {
+ var model = await emailAccountViewModelService.PrepareEmailAccountModel();
+ if (scope.DefaultStoreId is not null)
+ model.StoreId = scope.DefaultStoreId;
+ // Store never shows a Stores picker (its view emits only a hidden StoreId input) and must
+ // never carry other stores' names/ids in a model handed to its widget zones - same
+ // ShowStoreSelector gate ProductViewModelService uses for the same reason.
+ if (!scope.ShowStoreSelector)
+ model.AvailableStores.Clear();
+ return View(model);
+ }
+
+ [HttpPost]
+ [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
+ [PermissionAuthorizeAction(PermissionActionName.Create)]
+ public async Task<IActionResult> Create(EmailAccountModel model, bool continueEditing)
+ {
+ // Force the account to belong to the current store (no-op for Admin, whose
+ // scope.DefaultStoreId is null and so leaves whatever the caller posted untouched).
+ if (scope.DefaultStoreId is not null)
+ model.StoreId = scope.DefaultStoreId;
+
+ if (ModelState.IsValid)
+ {
+ var emailAccount = await emailAccountViewModelService.InsertEmailAccountModel(model);
+ Success(translationService.GetResource("Admin.Configuration.EmailAccounts.Added"));
+ return continueEditing ? RedirectToAction("Edit", new { id = emailAccount.Id }) : RedirectToAction("List");
+ }
+
+ //If we got this far, something failed, redisplay form
+ return View(model);
+ }
+
+ #endregion
+
+ #region Edit
+
+ [PermissionAuthorizeAction(PermissionActionName.Preview)]
+ public async Task<IActionResult> Edit(string id)
+ {
+ var emailAccount = await emailAccountService.GetEmailAccountById(id);
+ if (emailAccount == null || !await scope.HasAccess(emailAccount))
+ //No email account found with the specified id, or not owned by the current store
+ return RedirectToAction("List");
+
+ var model = emailAccount.ToModel();
+ await emailAccountViewModelService.PrepareAvailableStores(model);
+ // See Create() above: Store must never receive other stores' names/ids on this model.
+ if (!scope.ShowStoreSelector)
+ model.AvailableStores.Clear();
+ return View(model);
+ }
+
+ [HttpPost]
+ [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ public async Task<IActionResult> Edit(EmailAccountModel model, bool continueEditing)
+ {
+ var emailAccount = await emailAccountService.GetEmailAccountById(model.Id);
+ if (emailAccount == null || !await scope.HasAccess(emailAccount))
+ //No email account found with the specified id, or not owned by the current store
+ return RedirectToAction("List");
+
+ // Prevent moving the account to another store (no-op for Admin).
+ if (scope.DefaultStoreId is not null)
+ model.StoreId = scope.DefaultStoreId;
+
+ if (ModelState.IsValid)
+ {
+ emailAccount = await emailAccountViewModelService.UpdateEmailAccountModel(emailAccount, model);
+ Success(translationService.GetResource("Admin.Configuration.EmailAccounts.Updated"));
+ return continueEditing ? RedirectToAction("Edit", new { id = emailAccount.Id }) : RedirectToAction("List");
+ }
+
+ //If we got this far, something failed, redisplay form
+ return View(model);
+ }
+
+ #endregion
+
+ #region SendTestEmail
+
+ [HttpPost]
+ [PermissionAuthorizeAction(PermissionActionName.Edit)]
+ public async Task<IActionResult> SendTestEmail(EmailAccountModel model)
+ {
+ var emailAccount = await emailAccountService.GetEmailAccountById(model.Id);
+ if (emailAccount == null || !await scope.HasAccess(emailAccount))
+ //No email account found with the specified id, or not owned by the current store
+ return RedirectToAction("List");
+ try
+ {
+ if (string.IsNullOrWhiteSpace(model.SendTestEmailTo))
+ throw new GrandException("Enter test email address");
+ if (ModelState.IsValid)
+ {
+ await emailAccountViewModelService.SendTestEmail(emailAccount, model);
+ Success(translationService.GetResource("Admin.Configuration.EmailAccounts.SendTestEmail.Success"),
+ false);
+ }
+ else
+ {
+ Error(ModelState);
+ }
+ }
+ catch (Exception exc)
+ {
+ Error(exc.Message);
+ }
+
+ //If we got this far, something failed, redisplay form
+ return RedirectToAction("Edit", new { id = model.Id });
+ }
+
+ #endregion
+
+ #region Delete
+
+ [HttpPost]
+ [PermissionAuthorizeAction(PermissionActionName.Delete)]
+ public async Task<IActionResult> Delete(string id)
+ {
+ var emailAccount = await emailAccountService.GetEmailAccountById(id);
+ if (emailAccount == null || !await scope.HasAccess(emailAccount))
+ //No email account found with the specified id, or not owned by the current store
+ return RedirectToAction("List");
+ try
+ {
+ if (ModelState.IsValid)
+ {
+ await emailAccountService.DeleteEmailAccount(emailAccount);
+ Success(translationService.GetResource("Admin.Configuration.EmailAccounts.Deleted"));
+ }
+ else
+ {
+ Error(ModelState);
+ }
+
+ return RedirectToAction("List");
+ }
+ catch (Exception exc)
+ {
+ // Deliberate widening from Store's original catch(GrandException) — see the design
+ // spec's "Delete" section: unifies onto Admin's original, broader catch, turning a
+ // previously-unhandled 500 on Store into a shown error message. Never hides a
+ // currently-visible failure.
+ Error(exc);
+ return RedirectToAction("Edit", new { id = emailAccount.Id });
+ }
+ }
+
+ #endregion
+}
diff --git a/src/Web/Grand.Web.AdminShared/Services/RoutedEmailAccountDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/RoutedEmailAccountDataScope.cs
new file mode 100644
index 000000000..3a3be4fca
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Services/RoutedEmailAccountDataScope.cs
@@ -0,0 +1,53 @@
+#nullable enable
+
+using Grand.Domain.Messages;
+using Grand.Web.AdminShared.Interfaces;
+using Microsoft.AspNetCore.Http;
+
+namespace Grand.Web.AdminShared.Services;
+
+/// <summary>
+/// Resolves the correct per-host <see cref="IAdminDataScope{EmailAccount}" /> implementation
+/// at request time, based on the current request's "area" route value — same fix and same
+/// reason as <see cref="RoutedMessageTemplateDataScope"/> (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;EmailAccount&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 EmailAccount screen at all, so any "Vendor" (or
+/// other unrecognized/missing) area value fails closed.
+/// </summary>
+public class RoutedEmailAccountDataScope(
+ IHttpContextAccessor httpContextAccessor,
+ GlobalAdminDataScope<EmailAccount> globalScope,
+ StoreEmailAccountDataScope storeScope) : IAdminDataScope<EmailAccount>
+{
+ private IAdminDataScope<EmailAccount> 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" - EmailAccount has no Vendor screen) must
+ //never silently resolve to the unscoped global scope
+ _ => throw new InvalidOperationException(
+ $"RoutedEmailAccountDataScope: unrecognized or missing area '{area}'.")
+ };
+ }
+ }
+
+ public Task<bool> HasAccess(EmailAccount 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/StoreEmailAccountDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/StoreEmailAccountDataScope.cs
new file mode 100644
index 000000000..3917a8f82
--- /dev/null
+++ b/src/Web/Grand.Web.AdminShared/Services/StoreEmailAccountDataScope.cs
@@ -0,0 +1,31 @@
+#nullable enable
+
+using Grand.Domain.Messages;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Interfaces;
+
+namespace Grand.Web.AdminShared.Services;
+
+/// <summary>
+/// Store's <see cref="IAdminDataScope{EmailAccount}" />. Bespoke, not the generic
+/// <see cref="StoreAdminDataScope{TEntity}" />: <c>EmailAccount</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. No <see cref="CanView"/> override: unlike
+/// MessageTemplate/GiftVoucher there is no shared/multi-store-visible case for an email
+/// account — <see cref="IEmailAccountService.GetAllEmailAccounts"/> already filters Store's
+/// list to an exact <c>StoreId</c> match, so Store never even lists a global account, let
+/// alone needs a looser view-only check for one.
+/// </summary>
+public class StoreEmailAccountDataScope(IContextAccessor contextAccessor) : IAdminDataScope<EmailAccount>
+{
+ public Task<bool> HasAccess(EmailAccount 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 never shows a Stores picker — always self-assigned
+ 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 88646b591..840270dbb 100644
--- a/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
+++ b/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs
@@ -158,6 +158,14 @@ public class StartupApplication : IStartupApplication
services.AddScoped<StoreMessageTemplateDataScope>();
services.AddScoped<IAdminDataScope<MessageTemplate>, RoutedMessageTemplateDataScope>();
+ // IAdminDataScope<EmailAccount>: registered once here for the same reason as
+ // Category/Collection/GiftVoucher/MessageTemplate above — see
+ // RoutedEmailAccountDataScope's doc comment. No Vendor scope: EmailAccount has no
+ // Vendor screen.
+ services.AddScoped<GlobalAdminDataScope<EmailAccount>>();
+ services.AddScoped<StoreEmailAccountDataScope>();
+ services.AddScoped<IAdminDataScope<EmailAccount>, RoutedEmailAccountDataScope>();
+
// 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/Areas/Store/Views/EmailAccount/Create.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Create.cshtml
similarity index 70%
rename from src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Create.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Create.cshtml
index 637d25174..67d61560e 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Create.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Create.cshtml
@@ -1,16 +1,23 @@
@model EmailAccountModel
@{
- //page title
+ var area = ViewContext.RouteData.Values["area"]?.ToString();
ViewBag.Title = Loc["Admin.Configuration.EmailAccounts.AddNew"];
}
-<form asp-area="@Constants.AreaStore" asp-controller="EmailAccount" asp-action="Create" method="post">
+<form asp-area="@area" asp-controller="EmailAccount" asp-action="Create" method="post">
<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-envelope"></i>
+ @if (area == "Admin")
+ {
+ <i class="fa fa-users"></i>
+ }
+ else
+ {
+ <i class="fa fa-envelope"></i>
+ }
@Loc["Admin.Configuration.EmailAccounts.AddNew"]
<small>
<i class="fa fa-arrow-circle-left"></i> @Html.ActionLink(Loc["Admin.Configuration.EmailAccounts.BackToList"], "List")
@@ -23,6 +30,7 @@
<button class="btn btn-success" type="submit" name="save-continue">
<i class="fa fa-check-circle"></i> @Loc["Admin.Common.SaveContinue"]
</button>
+ <partial name="Partials/WidgetZone.DetailsButtons" model="Model"/>
</div>
</div>
<div class="x_content form">
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Edit.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Edit.cshtml
similarity index 76%
rename from src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Edit.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Edit.cshtml
index f5bb6c9cf..076aa1c25 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Edit.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Edit.cshtml
@@ -1,16 +1,23 @@
@model EmailAccountModel
@{
- //page title
+ var area = ViewContext.RouteData.Values["area"]?.ToString();
ViewBag.Title = Loc["Admin.Configuration.EmailAccounts.EditEmailAccountDetails"];
}
-<form asp-area="@Constants.AreaStore" asp-controller="EmailAccount" asp-action="Edit" method="post">
+<form asp-area="@area" asp-controller="EmailAccount" asp-action="Edit" method="post">
<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-envelope"></i>
+ @if (area == "Admin")
+ {
+ <i class="fa fa-users"></i>
+ }
+ else
+ {
+ <i class="fa fa-envelope"></i>
+ }
@Loc["Admin.Configuration.EmailAccounts.EditEmailAccountDetails"]
<small>
<i class="fa fa-arrow-circle-left"></i> @Html.ActionLink(Loc["Admin.Configuration.EmailAccounts.BackToList"], "List")
@@ -27,6 +34,7 @@
<span id="emailAccount-delete" class="btn red">
<i class="fa fa-trash-o"></i><span class="d-none d-sm-inline"> @Loc["Admin.Common.Delete"]</span>
</span>
+ <partial name="Partials/WidgetZone.DetailsButtons" model="Model"/>
</div>
</div>
</div>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Partials/CreateOrUpdate.cshtml
similarity index 85%
rename from src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/CreateOrUpdate.cshtml
rename to src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Partials/CreateOrUpdate.cshtml
index eebb29bbd..cb2465602 100644
--- a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/CreateOrUpdate.cshtml
+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/EmailAccount/Partials/CreateOrUpdate.cshtml
@@ -1,10 +1,17 @@
@using Grand.Business.Core.Enums.Messages
@model EmailAccountModel
+@{
+ var area = ViewContext.RouteData.Values["area"]?.ToString();
+}
<div asp-validation-summary="All"></div>
<input asp-for="Id" type="hidden"/>
-<input asp-for="StoreId" type="hidden"/>
+@if (area != "Admin")
+{
+ <input asp-for="StoreId" type="hidden"/>
+}
<div class="form-horizontal">
+ <partial name="Partials/WidgetZone.DetailsTop" model="Model"/>
<div class="form-body">
<div class="form-group">
<admin-label asp-for="Email"/>
@@ -68,6 +75,15 @@
<admin-select asp-for="SecureSocketOptionsId" asp-items="EnumTranslationService.ToSelectList((SecureSocketOptions)Model.SecureSocketOptionsId)"/>
</div>
</div>
+ @if (area == "Admin")
+ {
+ <div class="form-group">
+ <admin-label asp-for="StoreId"/>
+ <div class="col-md-9 col-sm-9">
+ <select asp-for="StoreId" asp-items="Model.AvailableStores" class="form-control"></select>
+ </div>
+ </div>
+ }
@if (!string.IsNullOrEmpty(Model.Id))
{
<div class="form-group">
@@ -88,4 +104,5 @@
</div>
}
</div>
+ <partial name="Partials/WidgetZone.DetailsBottom" model="Model"/>
</div>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsBottom.cshtml
new file mode 100644
index 000000000..2a1b9a136
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsBottom.cshtml
@@ -0,0 +1,2 @@
+@model Grand.Web.AdminShared.Models.Messages.EmailAccountModel
+<vc:store-widget widget-zone="store_email_account_details_bottom" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsButtons.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsButtons.cshtml
new file mode 100644
index 000000000..d7edb477d
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsButtons.cshtml
@@ -0,0 +1,2 @@
+@model Grand.Web.AdminShared.Models.Messages.EmailAccountModel
+<vc:store-widget widget-zone="store_email_account_details_buttons" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsTop.cshtml
new file mode 100644
index 000000000..bd0741d4b
--- /dev/null
+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/EmailAccount/Partials/WidgetZone.DetailsTop.cshtml
@@ -0,0 +1,2 @@
+@model Grand.Web.AdminShared.Models.Messages.EmailAccountModel
+<vc:store-widget widget-zone="store_email_account_details_top" additional-data="Model"/>
diff --git a/src/Web/Grand.Web.Store/Controllers/EmailAccountController.cs b/src/Web/Grand.Web.Store/Controllers/EmailAccountController.cs
index d7d3977bb..e25ba71b9 100644
--- a/src/Web/Grand.Web.Store/Controllers/EmailAccountController.cs
+++ b/src/Web/Grand.Web.Store/Controllers/EmailAccountController.cs
@@ -2,27 +2,31 @@ using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Domain.Messages;
using Grand.Domain.Permissions;
-using Grand.Infrastructure;
-using Grand.SharedKernel;
+using Grand.Web.AdminShared.Controllers;
using Grand.Web.AdminShared.Extensions.Mapping;
using Grand.Web.AdminShared.Interfaces;
-using Grand.Web.AdminShared.Models.Messages;
using Grand.Web.Common.DataSource;
using Grand.Web.Common.Filters;
using Grand.Web.Common.Security.Authorization;
+using Grand.Web.Store.Extensions;
using Microsoft.AspNetCore.Mvc;
namespace Grand.Web.Store.Controllers;
-[PermissionAuthorize(PermissionSystemName.EmailAccounts)]
+// Reduced to a thin subclass of BaseEmailAccountController (ARCH-001 EmailAccount
+// consolidation). Create/Edit/SendTestEmail/Delete live in the shared base; List stays here —
+// Store has no MarkAsDefaultEmail equivalent (see the design spec).
+[AutoValidateAntiforgeryToken]
+[Area(Constants.AreaStore)]
+[AuthorizeStore]
+[AuthorizeMenu]
public class EmailAccountController(
- IEmailAccountService emailAccountService,
IEmailAccountViewModelService emailAccountViewModelService,
+ IEmailAccountService emailAccountService,
ITranslationService translationService,
- IContextAccessor contextAccessor) : BaseStoreController
+ IAdminDataScope<EmailAccount> scope)
+ : BaseEmailAccountController(emailAccountViewModelService, emailAccountService, translationService, scope)
{
- private string CurrentStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
-
public IActionResult List()
{
return View();
@@ -32,7 +36,8 @@ public class EmailAccountController(
[PermissionAuthorizeAction(PermissionActionName.List)]
public async Task<IActionResult> List(DataSourceRequest command)
{
- var emailAccounts = await emailAccountService.GetAllEmailAccounts(CurrentStoreId, pageIndex: command.Page - 1, pageSize: command.PageSize);
+ var emailAccounts = await emailAccountService.GetAllEmailAccounts(scope.DefaultStoreId ?? "",
+ pageIndex: command.Page - 1, pageSize: command.PageSize);
var emailAccountModels = emailAccounts.Select(x => x.ToModel()).ToList();
var gridModel = new DataSourceResult {
@@ -42,129 +47,4 @@ public class EmailAccountController(
return Json(gridModel);
}
-
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public IActionResult Create()
- {
- var model = new EmailAccountModel {
- Port = 25,
- StoreId = CurrentStoreId
- };
- return View(model);
- }
-
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- [PermissionAuthorizeAction(PermissionActionName.Create)]
- public async Task<IActionResult> Create(EmailAccountModel model, bool continueEditing)
- {
- // Force the account to belong to the current store
- model.StoreId = CurrentStoreId;
-
- if (ModelState.IsValid)
- {
- var emailAccount = await emailAccountViewModelService.InsertEmailAccountModel(model);
- Success(translationService.GetResource("Admin.Configuration.EmailAccounts.Added"));
- return continueEditing
- ? RedirectToAction("Edit", new { id = emailAccount.Id })
- : RedirectToAction("List");
- }
-
- return View(model);
- }
-
- [PermissionAuthorizeAction(PermissionActionName.Preview)]
- public async Task<IActionResult> Edit(string id)
- {
- var emailAccount = await emailAccountService.GetEmailAccountById(id);
- if (emailAccount == null || emailAccount.StoreId != CurrentStoreId)
- return RedirectToAction("List");
-
- var model = emailAccount.ToModel();
- return View(model);
- }
-
- [HttpPost]
- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- public async Task<IActionResult> Edit(EmailAccountModel model, bool continueEditing)
- {
- var emailAccount = await emailAccountService.GetEmailAccountById(model.Id);
- if (emailAccount == null || emailAccount.StoreId != CurrentStoreId)
- return RedirectToAction("List");
-
- // Prevent moving the account to another store
- model.StoreId = CurrentStoreId;
-
- if (ModelState.IsValid)
- {
- emailAccount = await emailAccountViewModelService.UpdateEmailAccountModel(emailAccount, model);
- Success(translationService.GetResource("Admin.Configuration.EmailAccounts.Updated"));
- return continueEditing
- ? RedirectToAction("Edit", new { id = emailAccount.Id })
- : RedirectToAction("List");
- }
-
- return View(model);
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Edit)]
- public async Task<IActionResult> SendTestEmail(EmailAccountModel model)
- {
- var emailAccount = await emailAccountService.GetEmailAccountById(model.Id);
- if (emailAccount == null || emailAccount.StoreId != CurrentStoreId)
- return RedirectToAction("List");
-
- try
- {
- if (string.IsNullOrWhiteSpace(model.SendTestEmailTo))
- throw new GrandException(translationService.GetResource("Admin.Configuration.EmailAccounts.EnterTestEmail"));
- if (ModelState.IsValid)
- {
- await emailAccountViewModelService.SendTestEmail(emailAccount, model);
- Success(translationService.GetResource("Admin.Configuration.EmailAccounts.SendTestEmail.Success"),
- false);
- }
- else
- {
- Error(ModelState);
- }
- }
- catch (Exception exc)
- {
- Error(exc.Message);
- }
-
- return RedirectToAction("Edit", new { id = model.Id });
- }
-
- [HttpPost]
- [PermissionAuthorizeAction(PermissionActionName.Delete)]
- public async Task<IActionResult> Delete(string id)
- {
- var emailAccount = await emailAccountService.GetEmailAccountById(id);
- if (emailAccount == null || emailAccount.StoreId != CurrentStoreId)
- return RedirectToAction("List");
-
- try
- {
- if (ModelState.IsValid)
- {
- await emailAccountService.DeleteEmailAccount(emailAccount);
- Success(translationService.GetResource("Admin.Configuration.EmailAccounts.Deleted"));
- }
- else
- {
- Error(ModelState);
- }
-
- return RedirectToAction("List");
- }
- catch (GrandException exc)
- {
- Error(exc);
- return RedirectToAction("Edit", new { id = emailAccount.Id });
- }
- }
}