Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
ARCH-001 Phase 20: Customer controller/service consolidation (Admin/Store) (#819)
Krzysztof Pajakbc67ac478874
diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/AdminCustomerDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/AdminCustomerDataScopeTests.csnew file mode 100644index 000000000..fbe8f93ba--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/AdminCustomerDataScopeTests.cs@@ -0,0 +1,90 @@+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Services;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Admin.Tests.Controllers;++[TestClass]+public class AdminCustomerDataScopeTests+{+ private static AdminCustomerDataScope Build(bool isSalesManager, string currentCustomerSeId)+ {+ var customer = new Customer { SeId = currentCustomerSeId };+ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(customer);+ var contextAccessorMock = new Mock<IContextAccessor>();+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ var groupServiceMock = new Mock<IGroupService>();+ groupServiceMock.Setup(g => g.IsSalesManager(customer)).ReturnsAsync(isSalesManager);++ return new AdminCustomerDataScope(contextAccessorMock.Object, groupServiceMock.Object);+ }++ [TestMethod]+ public async Task HasAccess_NotSalesManager_TrueRegardlessOfSeId()+ {+ var scope = Build(isSalesManager: false, currentCustomerSeId: "se-1");+ var target = new Customer { SeId = "se-2" };++ Assert.IsTrue(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_SalesManager_MatchingSeId_True()+ {+ var scope = Build(isSalesManager: true, currentCustomerSeId: "se-1");+ var target = new Customer { SeId = "se-1" };++ Assert.IsTrue(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_SalesManager_MismatchedSeId_False()+ {+ var scope = Build(isSalesManager: true, currentCustomerSeId: "se-1");+ var target = new Customer { SeId = "se-2" };++ Assert.IsFalse(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_NullEntity_False()+ {+ var scope = Build(isSalesManager: false, currentCustomerSeId: "se-1");++ Assert.IsFalse(await scope.HasAccess(null));+ }++ [TestMethod]+ public async Task HasAccess_DeletedCustomer_NotSalesManager_False()+ {+ var scope = Build(isSalesManager: false, currentCustomerSeId: "se-1");+ var target = new Customer { SeId = "se-2", Deleted = true };++ Assert.IsFalse(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_DeletedCustomer_SalesManager_False()+ {+ var scope = Build(isSalesManager: true, currentCustomerSeId: "se-1");+ var target = new Customer { SeId = "se-1", Deleted = true };++ Assert.IsFalse(await scope.HasAccess(target));+ }++ [TestMethod]+ public void ScopeDefaults_MatchGlobalAdminSemantics()+ {+ var scope = Build(isSalesManager: false, currentCustomerSeId: null);++ Assert.IsNull(scope.DefaultStoreId);+ Assert.IsNull(scope.DefaultVendorId);+ Assert.AreEqual("Admin", scope.ResourceKeyPrefix);+ Assert.IsTrue(scope.ShowStoreSelector);+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseCustomerControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseCustomerControllerTests.csnew file mode 100644index 000000000..69de8356b--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseCustomerControllerTests.cs@@ -0,0 +1,596 @@+using Grand.Business.Core.Interfaces.Common.Addresses;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.Marketing.Customers;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Web.AdminShared.Controllers;+using Grand.Web.AdminShared.Interfaces;+using Grand.Web.AdminShared.Models.Common;+using Grand.Web.AdminShared.Models.Customers;+using Grand.Web.Common.DataSource;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Routing;+using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.Extensions.Logging;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Admin.Tests.Controllers;++[TestClass]+public class BaseCustomerControllerTests+{+ // BaseCustomerController is abstract; minimal subclass so actions can be invoked directly.+ // The full 17-dependency constructor is declared once here; every later task's tests reuse+ // this same TestCustomerController and Setup().+ protected class TestCustomerController(+ ICustomerService customerService,+ ICustomerViewModelService customerViewModelService,+ ICustomerManagerService customerManagerService,+ ICustomerProductService customerProductService,+ Grand.Business.Core.Interfaces.Catalog.Products.IProductReviewService productReviewService,+ Grand.Web.AdminShared.Interfaces.IProductReviewViewModelService productReviewViewModelService,+ Grand.Web.AdminShared.Interfaces.IProductViewModelService productViewModelService,+ ICustomerAttributeParser customerAttributeParser,+ ICustomerAttributeService customerAttributeService,+ IAddressAttributeParser addressAttributeParser,+ IAddressAttributeService addressAttributeService,+ Grand.Business.Core.Interfaces.Messages.IMessageProviderService messageProviderService,+ IGroupService groupService,+ ITranslationService translationService,+ IContextAccessor contextAccessor,+ CustomerSettings customerSettings,+ IAdminDataScope<Customer> scope)+ : BaseCustomerController(customerService, customerViewModelService, customerManagerService,+ customerProductService, productReviewService, productReviewViewModelService,+ productViewModelService, customerAttributeParser, customerAttributeService,+ addressAttributeParser, addressAttributeService, messageProviderService, groupService,+ translationService, contextAccessor, customerSettings, scope)+ {+ public Task<(Customer, IActionResult)> LoadAuthorizedCustomerPublic(string id) => LoadAuthorizedCustomer(id);+ }++ protected TestCustomerController Controller;+ protected Mock<ICustomerService> CustomerServiceMock;+ protected Mock<ICustomerViewModelService> CustomerViewModelServiceMock;+ protected Mock<ICustomerManagerService> CustomerManagerServiceMock;+ protected Mock<IGroupService> GroupServiceMock;+ protected Mock<IAdminDataScope<Customer>> ScopeMock;+ protected Mock<ITranslationService> TranslationServiceMock;+ protected Mock<IAddressAttributeService> AddressAttributeServiceMock;+ protected Mock<Grand.Business.Core.Interfaces.Catalog.Products.IProductReviewService> ProductReviewServiceMock;+ protected Mock<ICustomerProductService> CustomerProductServiceMock;++ [TestInitialize]+ public void Setup()+ {+ CustomerServiceMock = new Mock<ICustomerService>();+ CustomerViewModelServiceMock = new Mock<ICustomerViewModelService>();+ CustomerManagerServiceMock = new Mock<ICustomerManagerService>();+ GroupServiceMock = new Mock<IGroupService>();+ ScopeMock = new Mock<IAdminDataScope<Customer>>();+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ TranslationServiceMock = new Mock<ITranslationService>();+ TranslationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");+ AddressAttributeServiceMock = new Mock<IAddressAttributeService>();+ AddressAttributeServiceMock.Setup(a => a.GetAllAddressAttributes())+ .ReturnsAsync(new List<Grand.Domain.Common.AddressAttribute>());+ ProductReviewServiceMock = new Mock<Grand.Business.Core.Interfaces.Catalog.Products.IProductReviewService>();+ CustomerProductServiceMock = new Mock<ICustomerProductService>();++ var contextAccessorMock = new Mock<IContextAccessor>();++ Controller = new TestCustomerController(+ CustomerServiceMock.Object,+ CustomerViewModelServiceMock.Object,+ CustomerManagerServiceMock.Object,+ CustomerProductServiceMock.Object,+ ProductReviewServiceMock.Object,+ new Mock<Grand.Web.AdminShared.Interfaces.IProductReviewViewModelService>().Object,+ new Mock<Grand.Web.AdminShared.Interfaces.IProductViewModelService>().Object,+ new Mock<ICustomerAttributeParser>().Object,+ new Mock<ICustomerAttributeService>().Object,+ new Mock<IAddressAttributeParser>().Object,+ AddressAttributeServiceMock.Object,+ new Mock<Grand.Business.Core.Interfaces.Messages.IMessageProviderService>().Object,+ GroupServiceMock.Object,+ TranslationServiceMock.Object,+ contextAccessorMock.Object,+ new CustomerSettings(),+ ScopeMock.Object);++ var httpContext = new DefaultHttpContext();+ var loggerFactoryMock = new Mock<ILoggerFactory>();+ loggerFactoryMock.Setup(l => l.CreateLogger(It.IsAny<string>())).Returns(new Mock<ILogger>().Object);+ var urlHelperFactoryMock = new Mock<IUrlHelperFactory>();+ urlHelperFactoryMock.Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())).Returns(new Mock<IUrlHelper>().Object);+ var requestServicesMock = new Mock<IServiceProvider>();+ requestServicesMock.Setup(s => s.GetService(typeof(ILoggerFactory))).Returns(loggerFactoryMock.Object);+ requestServicesMock.Setup(s => s.GetService(typeof(IUrlHelperFactory))).Returns(urlHelperFactoryMock.Object);+ httpContext.RequestServices = requestServicesMock.Object;+ Controller.ControllerContext = new ControllerContext { HttpContext = httpContext };+ Controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);+ }++ [TestMethod]+ public async Task List_CallsPrepareCustomerListModel_ForBothHosts()+ {+ // The fix: both Admin and Store must call the shared, fully-populated+ // PrepareCustomerListModel() — Store's original bypassed it entirely (`new CustomerListModel()`),+ // leaving CustomerSettings-driven column-visibility flags always false regardless of config.+ CustomerViewModelServiceMock.Setup(v => v.PrepareCustomerListModel())+ .ReturnsAsync(new CustomerListModel { UsernamesEnabled = true, CompanyEnabled = true });++ var result = await Controller.List();++ var view = result as ViewResult;+ Assert.IsNotNull(view);+ var model = view.Model as CustomerListModel;+ Assert.IsTrue(model.UsernamesEnabled);+ Assert.IsTrue(model.CompanyEnabled);+ CustomerViewModelServiceMock.Verify(v => v.PrepareCustomerListModel(), Times.Once);+ }++ [TestMethod]+ public async Task CustomerList_GlobalScope_UsesSubmittedGroupIds()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock+ .Setup(v => v.PrepareCustomerList(It.IsAny<CustomerListModel>(),+ new[] { "group-1" }, null, 1, 10, ""))+ .ReturnsAsync((Enumerable.Empty<CustomerModel>(), 0));++ await Controller.CustomerList(new DataSourceRequest { Page = 1, PageSize = 10 },+ new CustomerListModel(), new[] { "group-1" }, null);++ CustomerViewModelServiceMock.Verify(v => v.PrepareCustomerList(It.IsAny<CustomerListModel>(),+ new[] { "group-1" }, null, 1, 10, ""), Times.Once);+ }++ [TestMethod]+ public async Task CustomerList_StoreScope_ForcesRegisteredGroupAndStoreId()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ var registered = new CustomerGroup { Id = "registered-id" };+ GroupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered))+ .ReturnsAsync(registered);+ CustomerViewModelServiceMock+ .Setup(v => v.PrepareCustomerList(It.IsAny<CustomerListModel>(),+ new[] { "registered-id" }, null, 1, 10, "store-1"))+ .ReturnsAsync((Enumerable.Empty<CustomerModel>(), 0));++ // Attacker/UI submits an arbitrary group filter — must be ignored under Store scope.+ await Controller.CustomerList(new DataSourceRequest { Page = 1, PageSize = 10 },+ new CustomerListModel(), new[] { "attacker-submitted-group" }, null);++ CustomerViewModelServiceMock.Verify(v => v.PrepareCustomerList(It.IsAny<CustomerListModel>(),+ new[] { "registered-id" }, null, 1, 10, "store-1"), Times.Once);+ }++ [TestMethod]+ public async Task CreateGet_GlobalScope_DoesNotCallApplyPostConstraints_ModelUntouched()+ {+ CustomerViewModelServiceMock.Setup(v => v.PrepareCustomerModel(It.IsAny<CustomerModel>(), null, false))+ .Returns(Task.CompletedTask);++ var result = await Controller.Create();++ var view = result as ViewResult;+ var model = view.Model as CustomerModel;+ Assert.IsTrue(model.Active);+ Assert.AreEqual("", model.StoreId ?? ""); // never forced for Admin (default no-op hook)+ }++ [TestMethod]+ public async Task CreatePost_Invalid_TwoFactorWarningHookNotCalledOnBase()+ {+ // BaseCustomerController's own CheckTwoFactorEnabledWarning is a no-op — verified indirectly:+ // no exception, no TempData warning entry set, for a base-level (non-Management) controller.+ var model = new CustomerModel { TwoFactorEnabled = true };+ Controller.ModelState.AddModelError("x", "invalid");+ CustomerViewModelServiceMock.Setup(v => v.PrepareCustomerModel(model, null, true))+ .Returns(Task.CompletedTask);++ var result = await Controller.Create(model, false);++ Assert.IsInstanceOfType(result, typeof(ViewResult));+ Assert.IsFalse(Controller.TempData.ContainsKey("grand.notifications.Warning"));+ }++ [TestMethod]+ public async Task LoadAuthorizedCustomer_NotFound_ReturnsRedirectToList()+ {+ CustomerServiceMock.Setup(s => s.GetCustomerById("missing")).ReturnsAsync((Customer)null);++ var (customer, denied) = await Controller.LoadAuthorizedCustomerPublic("missing");++ Assert.IsNull(customer);+ var redirect = denied as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ ScopeMock.Verify(s => s.HasAccess(It.IsAny<Customer>()), Times.Never);+ }++ [TestMethod]+ public async Task LoadAuthorizedCustomer_ScopeDenies_ReturnsRedirectToList()+ {+ var customer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(customer);+ ScopeMock.Setup(s => s.HasAccess(customer)).ReturnsAsync(false);++ var (result, denied) = await Controller.LoadAuthorizedCustomerPublic("c1");++ Assert.IsNull(result);+ var redirect = denied as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ }++ [TestMethod]+ public async Task LoadAuthorizedCustomer_ScopeAllows_ReturnsCustomerNoDenial()+ {+ var customer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(customer);+ ScopeMock.Setup(s => s.HasAccess(customer)).ReturnsAsync(true);++ var (result, denied) = await Controller.LoadAuthorizedCustomerPublic("c1");++ Assert.AreSame(customer, result);+ Assert.IsNull(denied);+ }++ [TestMethod]+ public async Task EditGet_Authorized_ReturnsViewAndCallsPrepareCustomerModel()+ {+ var customer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(customer);+ ScopeMock.Setup(s => s.HasAccess(customer)).ReturnsAsync(true);++ var result = await Controller.Edit("c1");++ Assert.IsInstanceOfType(result, typeof(ViewResult));+ CustomerViewModelServiceMock.Verify(v => v.PrepareCustomerModel(It.IsAny<CustomerModel>(), customer, false), Times.Once);+ }++ [TestMethod]+ public async Task EditGet_Denied_RedirectsToList()+ {+ CustomerServiceMock.Setup(s => s.GetCustomerById("missing")).ReturnsAsync((Customer)null);++ var result = await Controller.Edit("missing");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ }++ [TestMethod]+ public async Task Delete_SelfDelete_ErrorsAndRedirectsWithoutDeleting()+ {+ var self = new Customer { Id = "self" };+ var contextAccessorMock = new Mock<IContextAccessor>();+ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(self);+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);+ // Rebuild controller with a context accessor whose CurrentCustomer matches the target id.+ var controller = new TestCustomerController(CustomerServiceMock.Object, CustomerViewModelServiceMock.Object,+ CustomerManagerServiceMock.Object, new Mock<ICustomerProductService>().Object,+ new Mock<Grand.Business.Core.Interfaces.Catalog.Products.IProductReviewService>().Object,+ new Mock<Grand.Web.AdminShared.Interfaces.IProductReviewViewModelService>().Object,+ new Mock<Grand.Web.AdminShared.Interfaces.IProductViewModelService>().Object,+ new Mock<ICustomerAttributeParser>().Object, new Mock<ICustomerAttributeService>().Object,+ new Mock<IAddressAttributeParser>().Object, new Mock<IAddressAttributeService>().Object,+ new Mock<Grand.Business.Core.Interfaces.Messages.IMessageProviderService>().Object,+ GroupServiceMock.Object, TranslationServiceMock.Object, contextAccessorMock.Object,+ new CustomerSettings(), ScopeMock.Object)+ {+ ControllerContext = Controller.ControllerContext,+ TempData = Controller.TempData+ };+ CustomerServiceMock.Setup(s => s.GetCustomerById("self")).ReturnsAsync(self);+ ScopeMock.Setup(s => s.HasAccess(self)).ReturnsAsync(true);++ var result = await controller.Delete("self");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ CustomerViewModelServiceMock.Verify(v => v.DeleteCustomer(It.IsAny<Customer>()), Times.Never);+ }++ [TestMethod]+ public async Task LoyaltyPointsHistoryAdd_StoreScope_ForcesStaffStoreId_IgnoringSubmittedStoreId()+ {+ var customer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(customer);+ ScopeMock.Setup(s => s.HasAccess(customer)).ReturnsAsync(true);+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerViewModelServiceMock+ .Setup(v => v.InsertLoyaltyPointsHistory(customer, "store-1", 10, "msg"))+ .ReturnsAsync(new Grand.Domain.Orders.LoyaltyPointsHistory());++ // Caller submits a different, attacker-controlled storeId — must be ignored under Store scope.+ await Controller.LoyaltyPointsHistoryAdd("c1", "attacker-store", 10, "msg");++ CustomerViewModelServiceMock.Verify(v => v.InsertLoyaltyPointsHistory(customer, "store-1", 10, "msg"), Times.Once);+ }++ [TestMethod]+ public async Task LoyaltyPointsHistoryAdd_GlobalScope_UsesSubmittedStoreId()+ {+ var customer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(customer);+ ScopeMock.Setup(s => s.HasAccess(customer)).ReturnsAsync(true);+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock+ .Setup(v => v.InsertLoyaltyPointsHistory(customer, "admin-submitted-store", 10, "msg"))+ .ReturnsAsync(new Grand.Domain.Orders.LoyaltyPointsHistory());++ await Controller.LoyaltyPointsHistoryAdd("c1", "admin-submitted-store", 10, "msg");++ CustomerViewModelServiceMock.Verify(v => v.InsertLoyaltyPointsHistory(customer, "admin-submitted-store", 10, "msg"), Times.Once);+ }++ [TestMethod]+ public async Task AddressesSelect_Denied_ThrowsArgumentException()+ {+ CustomerServiceMock.Setup(s => s.GetCustomerById("missing")).ReturnsAsync((Customer)null);++ await Assert.ThrowsAsync<ArgumentException>(() =>+ Controller.AddressesSelect("missing", new DataSourceRequest()));+ }++ [TestMethod]+ public async Task AddressCreatePost_Authorized_InsertsAndRedirects()+ {+ var customer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(customer);+ ScopeMock.Setup(s => s.HasAccess(customer)).ReturnsAsync(true);+ var model = new CustomerAddressModel { CustomerId = "c1", Address = new AddressModel() };+ var inserted = new Grand.Domain.Common.Address { Id = "a1" };+ CustomerViewModelServiceMock+ .Setup(v => v.InsertAddressModel(customer, model, It.IsAny<List<Grand.Domain.Common.CustomAttribute>>()))+ .ReturnsAsync(inserted);++ var result = await Controller.AddressCreate(model);++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("AddressEdit", redirect.ActionName);+ }++ [TestMethod]+ public async Task OrderDetails_StoreScope_MismatchedStore_ReturnsEmptyNotException()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ var orderServiceMock = new Mock<Grand.Business.Core.Interfaces.Checkout.Orders.IOrderService>();+ orderServiceMock.Setup(s => s.GetOrderById("o1"))+ .ReturnsAsync(new Grand.Domain.Orders.Order { Id = "o1", StoreId = "store-2" });++ var result = await Controller.OrderDetails("o1", orderServiceMock.Object,+ new Mock<Grand.Web.AdminShared.Interfaces.IOrderViewModelService>().Object,+ new Mock<Grand.Business.Core.Interfaces.Common.Security.IPermissionService>().Object);++ var json = result as JsonResult;+ var data = json.Value as DataSourceResult;+ Assert.AreEqual(0, data.Total);+ }++ [TestMethod]+ public async Task OrderDetails_GlobalScope_NotFound_ThrowsArgumentException()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ var permissionServiceMock = new Mock<Grand.Business.Core.Interfaces.Common.Security.IPermissionService>();+ permissionServiceMock.Setup(p => p.Authorize(Grand.Domain.Permissions.StandardPermission.ManageOrders)).ReturnsAsync(true);+ var orderServiceMock = new Mock<Grand.Business.Core.Interfaces.Checkout.Orders.IOrderService>();+ orderServiceMock.Setup(s => s.GetOrderById("missing")).ReturnsAsync((Grand.Domain.Orders.Order)null);++ await Assert.ThrowsAsync<ArgumentException>(() =>+ Controller.OrderDetails("missing", orderServiceMock.Object,+ new Mock<Grand.Web.AdminShared.Interfaces.IOrderViewModelService>().Object, permissionServiceMock.Object));+ }++ [TestMethod]+ public async Task GetCartList_GlobalScope_NoOwnershipCheck_CallsServiceDirectly()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock.Setup(v => v.PrepareShoppingCartItemModel("any-customer-id", 1))+ .ReturnsAsync(new List<Grand.Web.AdminShared.Models.ShoppingCart.ShoppingCartItemModel>());++ var result = await Controller.GetCartList("any-customer-id", 1);++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerServiceMock.Verify(s => s.GetCustomerById(It.IsAny<string>()), Times.Never);+ }++ [TestMethod]+ public async Task GetCartList_StoreScope_DeniedOwnership_ReturnsEmpty()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync((Customer)null);++ var result = await Controller.GetCartList("c1", 1);++ var json = result as JsonResult;+ var data = json.Value as DataSourceResult;+ Assert.AreEqual(0, data.Total);+ CustomerViewModelServiceMock.Verify(v => v.PrepareShoppingCartItemModel(It.IsAny<string>(), It.IsAny<int>()), Times.Never);+ }++ [TestMethod]+ public async Task ReviewDelete_StoreScope_MismatchedStore_ThrowsArgumentException()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ var review = new Grand.Domain.Catalog.ProductReview { Id = "r1", StoreId = "store-2" };+ ProductReviewServiceMock.Setup(s => s.GetProductReviewById("r1")).ReturnsAsync(review);++ await Assert.ThrowsAsync<ArgumentException>(() => Controller.ReviewDelete("r1"));+ }++ [TestMethod]+ public async Task DeleteProductPrice_GlobalScope_NoOwnershipCheck_CallsServiceDirectly()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock.Setup(v => v.DeleteProductPrice("pp1")).Returns(Task.CompletedTask);++ var result = await Controller.DeleteProductPrice("pp1");++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerViewModelServiceMock.Verify(v => v.DeleteProductPrice("pp1"), Times.Once);+ }++ [TestMethod]+ public async Task DeleteProductPrice_StoreScope_PriceNotFound_NoOpsSilently()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerProductServiceMock.Setup(s => s.GetCustomerProductPriceById("pp1"))+ .ReturnsAsync((Grand.Domain.Customers.CustomerProductPrice)null);++ var result = await Controller.DeleteProductPrice("pp1");++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerViewModelServiceMock.Verify(v => v.DeleteProductPrice(It.IsAny<string>()), Times.Never);+ CustomerProductServiceMock.Verify(s => s.DeleteCustomerProductPrice(It.IsAny<Grand.Domain.Customers.CustomerProductPrice>()), Times.Never);+ }++ [TestMethod]+ public async Task DeleteProductPrice_StoreScope_DeniedOwnership_NoOpsSilently()+ {+ // Price exists but belongs to a customer outside the caller's store — exercises the+ // ownership-denial half of the guard, distinct from the not-found half above.+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ var price = new Grand.Domain.Customers.CustomerProductPrice { Id = "pp1", CustomerId = "c1" };+ CustomerProductServiceMock.Setup(s => s.GetCustomerProductPriceById("pp1")).ReturnsAsync(price);+ var foreignCustomer = new Customer { Id = "c1" };+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(foreignCustomer);+ ScopeMock.Setup(s => s.HasAccess(foreignCustomer)).ReturnsAsync(false);++ var result = await Controller.DeleteProductPrice("pp1");++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerViewModelServiceMock.Verify(v => v.DeleteProductPrice(It.IsAny<string>()), Times.Never);+ CustomerProductServiceMock.Verify(s => s.DeleteCustomerProductPrice(It.IsAny<Grand.Domain.Customers.CustomerProductPrice>()), Times.Never);+ }++ [TestMethod]+ public async Task ProductAddPopup_Get_StoreScope_Denied_RedirectsToList()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync((Customer)null);++ var result = await Controller.ProductAddPopup("c1");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("List", redirect.ActionName);+ }++ [TestMethod]+ public async Task ProductsPrice_StoreScope_DeniedOwnership_ReturnsEmpty()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync((Customer)null);++ var result = await Controller.ProductsPrice(new DataSourceRequest { Page = 1, PageSize = 10 }, "c1");++ var json = result as JsonResult;+ var data = json.Value as DataSourceResult;+ Assert.AreEqual(0, data.Total);+ CustomerViewModelServiceMock.Verify(+ v => v.PrepareProductPriceModel(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never);+ }++ [TestMethod]+ public async Task ProductsPrice_GlobalScope_NoOwnershipCheck_CallsServiceDirectly()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock.Setup(v => v.PrepareProductPriceModel("c1", 1, 10))+ .ReturnsAsync((Enumerable.Empty<CustomerModel.ProductPriceModel>(), 0));++ var result = await Controller.ProductsPrice(new DataSourceRequest { Page = 1, PageSize = 10 }, "c1");++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerServiceMock.Verify(s => s.GetCustomerById(It.IsAny<string>()), Times.Never);+ CustomerViewModelServiceMock.Verify(v => v.PrepareProductPriceModel("c1", 1, 10), Times.Once);+ }++ [TestMethod]+ public async Task PersonalizedProducts_StoreScope_DeniedOwnership_ReturnsEmpty()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync((Customer)null);++ var result = await Controller.PersonalizedProducts(new DataSourceRequest { Page = 1, PageSize = 10 }, "c1");++ var json = result as JsonResult;+ var data = json.Value as DataSourceResult;+ Assert.AreEqual(0, data.Total);+ CustomerViewModelServiceMock.Verify(+ v => v.PreparePersonalizedProducts(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never);+ }++ [TestMethod]+ public async Task PersonalizedProducts_GlobalScope_NoOwnershipCheck_CallsServiceDirectly()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock.Setup(v => v.PreparePersonalizedProducts("c1", 1, 10))+ .ReturnsAsync((Enumerable.Empty<CustomerModel.ProductModel>(), 0));++ var result = await Controller.PersonalizedProducts(new DataSourceRequest { Page = 1, PageSize = 10 }, "c1");++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerServiceMock.Verify(s => s.GetCustomerById(It.IsAny<string>()), Times.Never);+ CustomerViewModelServiceMock.Verify(v => v.PreparePersonalizedProducts("c1", 1, 10), Times.Once);+ }++ [TestMethod]+ public async Task ReviewList_StoreScope_DeniedOwnership_ReturnsEmpty()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns("store-1");+ CustomerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync((Customer)null);++ var result = await Controller.ReviewList("c1", new DataSourceRequest { Page = 1, PageSize = 10 });++ var json = result as JsonResult;+ var data = json.Value as DataSourceResult;+ Assert.AreEqual(0, data.Total);+ ProductReviewServiceMock.Verify(s => s.GetAllProductReviews(+ It.IsAny<string>(), It.IsAny<bool?>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never);+ }++ [TestMethod]+ public async Task ReviewList_GlobalScope_NoOwnershipCheck_CallsServiceDirectly()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ ProductReviewServiceMock.Setup(s => s.GetAllProductReviews(+ "c1", null, null, null, "", null, "", 0, 10))+ .ReturnsAsync(new Grand.Domain.PagedList<Grand.Domain.Catalog.ProductReview>(+ new List<Grand.Domain.Catalog.ProductReview>(), 0, 10, 0));++ var result = await Controller.ReviewList("c1", new DataSourceRequest { Page = 1, PageSize = 10 });++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerServiceMock.Verify(s => s.GetCustomerById(It.IsAny<string>()), Times.Never);+ }++ [TestMethod]+ public async Task OutOfStockSubscriptionList_GlobalScope_NoOwnershipCheck()+ {+ ScopeMock.Setup(s => s.DefaultStoreId).Returns((string)null);+ CustomerViewModelServiceMock+ .Setup(v => v.PrepareOutOfStockSubscriptionModel("c1", 1, 10))+ .ReturnsAsync((Enumerable.Empty<CustomerModel.OutOfStockSubscriptionModel>(), 0));++ var result = await Controller.OutOfStockSubscriptionList(+ new DataSourceRequest { Page = 1, PageSize = 10 }, "c1");++ Assert.IsInstanceOfType(result, typeof(JsonResult));+ CustomerServiceMock.Verify(s => s.GetCustomerById(It.IsAny<string>()), Times.Never);+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseCustomerManagementControllerTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseCustomerManagementControllerTests.csnew file mode 100644index 000000000..ef46e8632--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/BaseCustomerManagementControllerTests.cs@@ -0,0 +1,151 @@+using Grand.Business.Core.Interfaces.Catalog.Products;+using Grand.Business.Core.Interfaces.Common.Addresses;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.ExportImport;+using Grand.Business.Core.Interfaces.Marketing.Customers;+using Grand.Business.Core.Interfaces.Messages;+using Grand.Domain.Customers;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Web.AdminShared.Controllers;+using Grand.Web.AdminShared.Interfaces;+using Grand.Web.AdminShared.Models.Customers;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Routing;+using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.Extensions.Logging;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Admin.Tests.Controllers;++[TestClass]+public class BaseCustomerManagementControllerTests+{+ private class TestManagementController(+ ICustomerService customerService, ICustomerViewModelService customerViewModelService,+ ICustomerManagerService customerManagerService, ICustomerProductService customerProductService,+ IProductReviewService productReviewService, IProductReviewViewModelService productReviewViewModelService,+ IProductViewModelService productViewModelService, ICustomerAttributeParser customerAttributeParser,+ ICustomerAttributeService customerAttributeService, IAddressAttributeParser addressAttributeParser,+ IAddressAttributeService addressAttributeService, IMessageProviderService messageProviderService,+ IGroupService groupService, ITranslationService translationService, IContextAccessor contextAccessor,+ CustomerSettings customerSettings, IAdminDataScope<Customer> scope,+ IPermissionService permissionService, IExportManager<Customer> exportManager)+ : BaseCustomerManagementController(customerService, customerViewModelService, customerManagerService,+ customerProductService, productReviewService, productReviewViewModelService, productViewModelService,+ customerAttributeParser, customerAttributeService, addressAttributeParser, addressAttributeService,+ messageProviderService, groupService, translationService, contextAccessor, customerSettings, scope,+ permissionService, exportManager)+ {+ public void CheckTwoFactorEnabledWarningPublic(Customer existingCustomer, CustomerModel model) =>+ CheckTwoFactorEnabledWarning(existingCustomer, model);+ }++ private TestManagementController _controller;+ private Mock<ICustomerService> _customerServiceMock;+ private Mock<IGroupService> _groupServiceMock;+ private Mock<IPermissionService> _permissionServiceMock;+ private Mock<IContextAccessor> _contextAccessorMock;++ [TestInitialize]+ public void Setup()+ {+ _customerServiceMock = new Mock<ICustomerService>();+ _groupServiceMock = new Mock<IGroupService>();+ _permissionServiceMock = new Mock<IPermissionService>();+ _contextAccessorMock = new Mock<IContextAccessor>();+ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer { Id = "admin-self" });+ _contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ var scopeMock = new Mock<IAdminDataScope<Customer>>();+ scopeMock.Setup(s => s.HasAccess(It.IsAny<Customer>())).ReturnsAsync(true);+ var translationServiceMock = new Mock<ITranslationService>();+ translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");++ _controller = new TestManagementController(_customerServiceMock.Object,+ new Mock<ICustomerViewModelService>().Object, new Mock<ICustomerManagerService>().Object,+ new Mock<ICustomerProductService>().Object, new Mock<IProductReviewService>().Object,+ new Mock<IProductReviewViewModelService>().Object, new Mock<IProductViewModelService>().Object,+ new Mock<ICustomerAttributeParser>().Object, new Mock<ICustomerAttributeService>().Object,+ new Mock<IAddressAttributeParser>().Object, new Mock<IAddressAttributeService>().Object,+ new Mock<IMessageProviderService>().Object, _groupServiceMock.Object, translationServiceMock.Object,+ _contextAccessorMock.Object, new CustomerSettings(), scopeMock.Object,+ _permissionServiceMock.Object, new Mock<IExportManager<Customer>>().Object);++ var httpContext = new DefaultHttpContext();+ var loggerFactoryMock = new Mock<ILoggerFactory>();+ loggerFactoryMock.Setup(l => l.CreateLogger(It.IsAny<string>())).Returns(new Mock<ILogger>().Object);+ var urlHelperFactoryMock = new Mock<IUrlHelperFactory>();+ urlHelperFactoryMock.Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())).Returns(new Mock<IUrlHelper>().Object);+ var requestServicesMock = new Mock<IServiceProvider>();+ requestServicesMock.Setup(s => s.GetService(typeof(ILoggerFactory))).Returns(loggerFactoryMock.Object);+ requestServicesMock.Setup(s => s.GetService(typeof(IUrlHelperFactory))).Returns(urlHelperFactoryMock.Object);+ httpContext.RequestServices = requestServicesMock.Object;+ _controller.ControllerContext = new ControllerContext { HttpContext = httpContext };+ _controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);+ }++ [TestMethod]+ public async Task Impersonate_NoPermission_ErrorsAndRedirectsToEdit_NoUserFieldUpdate()+ {+ var target = new Customer { Id = "c1" };+ _customerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(target);+ _permissionServiceMock.Setup(p => p.Authorize(StandardPermission.AllowCustomerImpersonation)).ReturnsAsync(false);++ var result = await _controller.Impersonate("c1");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("Edit", redirect.ActionName);+ _customerServiceMock.Verify(s => s.UpdateUserField(It.IsAny<Customer>(),+ SystemCustomerFieldNames.ImpersonatedCustomerId, It.IsAny<object>()), Times.Never);+ }++ [TestMethod]+ public async Task Impersonate_NonAdminImpersonatingAdmin_Denied()+ {+ var target = new Customer { Id = "c1" };+ _customerServiceMock.Setup(s => s.GetCustomerById("c1")).ReturnsAsync(target);+ _permissionServiceMock.Setup(p => p.Authorize(StandardPermission.AllowCustomerImpersonation)).ReturnsAsync(true);+ _groupServiceMock.Setup(g => g.IsAdmin(It.Is<Customer>(c => c.Id == "admin-self"))).ReturnsAsync(false);+ _groupServiceMock.Setup(g => g.IsAdmin(target)).ReturnsAsync(true);++ var result = await _controller.Impersonate("c1");++ var redirect = result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual("Edit", redirect.ActionName);+ _customerServiceMock.Verify(s => s.UpdateUserField(It.IsAny<Customer>(),+ SystemCustomerFieldNames.ImpersonatedCustomerId, It.IsAny<object>()), Times.Never);+ }++ [TestMethod]+ public void CheckTwoFactorEnabledWarning_CreateTime_NoExistingCustomer_WarnsIfEnabling()+ {+ var model = new CustomerModel { TwoFactorEnabled = true };++ _controller.CheckTwoFactorEnabledWarningPublic(null, model);++ Assert.IsTrue(_controller.TempData.ContainsKey("grand.notifications.Warning"));+ }++ [TestMethod]+ public void CheckTwoFactorEnabledWarning_EditTime_AlreadyEnabled_NoWarning()+ {+ var existing = new Customer();+ existing.UserFields.Add(new Grand.Domain.Common.UserField+ { Key = SystemCustomerFieldNames.TwoFactorEnabled, Value = "true", StoreId = "" });+ var model = new CustomerModel { TwoFactorEnabled = true };++ _controller.CheckTwoFactorEnabledWarningPublic(existing, model);++ Assert.IsFalse(_controller.TempData.ContainsKey("grand.notifications.Warning"));+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/CustomerControllerAttributeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/CustomerControllerAttributeTests.csnew file mode 100644index 000000000..0013b8893--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/CustomerControllerAttributeTests.cs@@ -0,0 +1,96 @@+using System.Linq;+using System.Reflection;+using Grand.Domain.Permissions;+using Grand.Web.Admin.Controllers;+using Grand.Web.AdminShared.Controllers;+using Grand.Web.AdminShared.Models.Customers;+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;++// Mirrors BrandControllerTests.cs's own precedent (the immediately-preceding phase to get this+// right on first attempt) — cross-checked directly against the sibling ProductController's own+// attribute set, not re-derived from memory of what "should" be there.+//+// Deviation from the task-10 brief: the brief's draft checked for+// Microsoft.AspNetCore.Authorization.AuthorizeAttribute, but [AuthorizeAdmin] is+// Grand.Web.Common.Filters.AuthorizeAdminAttribute, a TypeFilterAttribute that does NOT derive+// from AuthorizeAttribute — so that check would read 0 matches both before AND after the+// cutover and could never catch the regression it exists to catch. Checked directly against+// AuthorizeAdminAttribute/AuthorizeMenuAttribute instead, matching BrandControllerTests.cs.+[TestClass]+public class CustomerControllerAttributeTests+{+ [TestMethod]+ public void CustomerController_CarriesAreaAttribute()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AreaAttribute), inherit: false);+ Assert.AreEqual(1, attr.Length,+ "CustomerController must restate [Area] — BaseCustomerManagementController can't carry it (host-agnostic, lives in AdminShared).");+ Assert.AreEqual("Admin", ((AreaAttribute)attr[0]).RouteValue);+ }++ [TestMethod]+ public void CustomerController_CarriesAuthorizeAdminAttribute()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AuthorizeAdminAttribute), inherit: false);+ Assert.IsTrue(attr.Length >= 1,+ "CustomerController must restate [AuthorizeAdmin] — it previously arrived via BaseAdminController, which the new shared base can't extend.");+ }++ [TestMethod]+ public void CustomerController_CarriesAuthorizeMenuAttribute()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);+ Assert.IsTrue(attr.Length >= 1,+ "CustomerController must restate [AuthorizeMenu] — same transitive-base problem as [AuthorizeAdmin].");+ }++ [TestMethod]+ public void CustomerController_CarriesAutoValidateAntiforgeryToken()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: true);+ // inherit: true is fine here — BaseCustomerController already states this one directly+ // (Task 4), so it's expected to arrive via inheritance, unlike Area/AuthorizeAdmin/AuthorizeMenu.+ Assert.IsTrue(attr.Length >= 1);+ }++ [TestMethod]+ public void CustomerController_InheritsBaseCustomerManagementController_NotJustBaseCustomerController()+ {+ // Admin gets the FULL surface (Impersonate/Export/Notes/etc.) — verify it inherited the+ // management subclass, not just the shared base, so a future refactor can't silently+ // narrow Admin's own action surface without a compile-time signal here.+ Assert.IsTrue(typeof(BaseCustomerManagementController).IsAssignableFrom(typeof(CustomerController)));+ }++ [TestMethod]+ public void CustomerController_IsThinSubclass_DeclaresNoOwnActionMethods()+ {+ var ownMethods = typeof(CustomerController).GetMethods(+ BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);+ Assert.AreEqual(0, ownMethods.Length,+ "CustomerController should declare zero action methods of its own — everything lives in BaseCustomerManagementController/BaseCustomerController.");+ }++ // Regression test for the disclosed bug fix noted on BaseCustomerController.Create(POST):+ // pre-consolidation, Admin's own Create(POST) required PermissionActionName.Edit while+ // everything else on Create required .Create (same defect class as GiftVoucher's, see+ // GiftVoucherControllerAttributeTests.CreatePost_RequiresCreatePermission). Pin the fixed+ // permission via reflection so a future edit can't silently regress it.+ [TestMethod]+ public void CreatePost_RequiresCreatePermission()+ {+ var method = typeof(BaseCustomerController).GetMethods(BindingFlags.Public | BindingFlags.Instance)+ .Single(m => m.Name == "Create" && m.GetParameters().Length == 2+ && m.GetParameters()[0].ParameterType == typeof(CustomerModel));++ var attr = method.GetCustomAttributes(typeof(PermissionAuthorizeActionAttribute), inherit: false)+ .Cast<PermissionAuthorizeActionAttribute>().Single();++ Assert.AreEqual(PermissionActionName.Create, attr.PermissionAction);+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedCustomerDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedCustomerDataScopeTests.csnew file mode 100644index 000000000..90f6aef76--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/RoutedCustomerDataScopeTests.cs@@ -0,0 +1,137 @@+#nullable enable++using System.Reflection;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Interfaces;+using Grand.Web.AdminShared.Services;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Routing;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Admin.Tests.Controllers;++/// <summary>+/// Covers the routing decision itself - which concrete IAdminDataScope<Customer> the resolver+/// delegates to for each area, and that an unrecognized or missing area fails closed rather than+/// falling back to any concrete scope. Mirrors RoutedOrderDataScopeTests/+/// RoutedMessageTemplateDataScopeTests: real concrete scopes built with mocked+/// IContextAccessor/IGroupService dependencies, since AdminCustomerDataScope/+/// StoreCustomerDataScope have no virtual members for Moq to intercept and+/// RoutedCustomerDataScope's constructor (matching every other Routed*DataScope in this+/// codebase) takes the two concrete scope types rather than IAdminDataScope<Customer> twice -+/// two parameters of the same interface type would make the plain+/// AddScoped<IAdminDataScope<Customer>, RoutedCustomerDataScope>() DI registration+/// ambiguous/self-referencing at resolution time.+/// </summary>+[TestClass]+public class RoutedCustomerDataScopeTests+{+ private const string StaffStoreId = "store-1";++ private AdminCustomerDataScope _adminScope = null!;+ private StoreCustomerDataScope _storeScope = null!;++ [TestInitialize]+ public void Setup()+ {+ var workContext = new Mock<IWorkContext>();+ workContext.Setup(w => w.CurrentCustomer).Returns(new Customer { StaffStoreId = StaffStoreId });+ var contextAccessor = new Mock<IContextAccessor>();+ contextAccessor.Setup(c => c.WorkContext).Returns(workContext.Object);++ var groupService = new Mock<IGroupService>();+ groupService.Setup(g => g.IsSalesManager(It.IsAny<Customer>())).ReturnsAsync(false);+ groupService.Setup(g => g.IsRegistered(It.IsAny<Customer>())).ReturnsAsync(true);++ _adminScope = new AdminCustomerDataScope(contextAccessor.Object, groupService.Object);+ _storeScope = new StoreCustomerDataScope(contextAccessor.Object, groupService.Object);+ }++ private RoutedCustomerDataScope ResolverForArea(string? area)+ {+ var httpContext = new DefaultHttpContext();+ if (area is not null) httpContext.Request.RouteValues = new RouteValueDictionary { ["area"] = area };+ var httpContextAccessor = new Mock<IHttpContextAccessor>();+ httpContextAccessor.Setup(a => a.HttpContext).Returns(httpContext);+ return new RoutedCustomerDataScope(httpContextAccessor.Object, _adminScope, _storeScope);+ }++ [TestMethod]+ public void AdminArea_ResolvesToAdminScope()+ {+ var resolver = ResolverForArea("Admin");+ // Admin never scopes to a default store; Store always defaults to the staff's store -+ // the one behavioral difference between the two concrete scopes today.+ Assert.IsNull(resolver.DefaultStoreId);+ }++ [TestMethod]+ public async Task AdminArea_HasAccess_NotGatedByStoreOwnership()+ {+ var resolver = ResolverForArea("Admin");+ // AdminCustomerDataScope has no store-ownership check at all (only the Sales-Manager+ // restriction) - a customer from any store is visible.+ var result = await resolver.HasAccess(new Customer { StoreId = "some-other-store" });+ Assert.IsTrue(result);+ }++ [TestMethod]+ public void StoreArea_ResolvesToStoreScope()+ {+ var resolver = ResolverForArea("Store");+ Assert.AreEqual(StaffStoreId, resolver.DefaultStoreId);+ }++ [TestMethod]+ public async Task StoreArea_HasAccess_GatedByStoreOwnership()+ {+ var resolver = ResolverForArea("Store");+ var owned = await resolver.HasAccess(new Customer { StoreId = StaffStoreId });+ var other = await resolver.HasAccess(new Customer { StoreId = "some-other-store" });+ Assert.IsTrue(owned);+ Assert.IsFalse(other);+ }++ [TestMethod]+ public void UnrecognizedOrMissingArea_ThrowsFailClosed()+ {+ var resolver = ResolverForArea("Vendor");+ Assert.Throws<InvalidOperationException>(() => _ = resolver.ResourceKeyPrefix);++ var resolverNoArea = ResolverForArea(null);+ Assert.Throws<InvalidOperationException>(() => _ = resolverNoArea.ResourceKeyPrefix);+ }++ [TestMethod]+ public void CanView_IsExplicitlyForwarded_NotLeftToTheInterfaceDefault()+ {+ // Regression guard: a routed scope can forward HasAccess while forgetting CanView,+ // silently falling back to the interface default (=> HasAccess) instead of a scope's real+ // CanView override - the standing lesson from VendorReview's RoutedOrderDataScope gap.+ // Customer has no CanView override on either concrete scope today, so no behavioral+ // difference between "forwards HasAccess" and "forwards CanView" is observable through a+ // real AdminCustomerDataScope/StoreCustomerDataScope - the failure mode this guards+ // against only bites once a future override lands on one of them. Verify structurally+ // instead: RoutedCustomerDataScope must declare its own CanView method rather than relying+ // on IAdminDataScope<Customer>'s default interface implementation, so that a future+ // override on either concrete scope is never silently bypassed.+ var declaresOwnCanView = typeof(RoutedCustomerDataScope)+ .GetMethod(nameof(RoutedCustomerDataScope.CanView), BindingFlags.Public | BindingFlags.Instance)+ ?.DeclaringType == typeof(RoutedCustomerDataScope);++ Assert.IsTrue(declaresOwnCanView,+ "RoutedCustomerDataScope must explicitly declare CanView, not rely on the IAdminDataScope<Customer> default.");+ }++ [TestMethod]+ public async Task CanView_ForwardsToResolvedScopesCanView()+ {+ var resolver = ResolverForArea("Store");+ var target = new Customer { StoreId = StaffStoreId };+ IAdminDataScope<Customer> storeScope = _storeScope;+ Assert.AreEqual(await storeScope.CanView(target), await resolver.CanView(target));+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreCustomerDataScopeTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreCustomerDataScopeTests.csnew file mode 100644index 000000000..95a0335b2--- /dev/null+++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/StoreCustomerDataScopeTests.cs@@ -0,0 +1,79 @@+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Services;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Admin.Tests.Controllers;++[TestClass]+public class StoreCustomerDataScopeTests+{+ private static StoreCustomerDataScope Build(string staffStoreId, bool isRegistered = true)+ {+ var customer = new Customer { StaffStoreId = staffStoreId };+ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(customer);+ var contextAccessorMock = new Mock<IContextAccessor>();+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ var groupServiceMock = new Mock<IGroupService>();+ groupServiceMock.Setup(g => g.IsRegistered(It.IsAny<Customer>())).ReturnsAsync(isRegistered);++ return new StoreCustomerDataScope(contextAccessorMock.Object, groupServiceMock.Object);+ }++ [TestMethod]+ public async Task HasAccess_MatchingStoreId_Registered_NotDeleted_True()+ {+ var scope = Build("store-1");+ var target = new Customer { StoreId = "store-1", Deleted = false };++ Assert.IsTrue(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_MismatchedStoreId_False()+ {+ var scope = Build("store-1");+ var target = new Customer { StoreId = "store-2", Deleted = false };++ Assert.IsFalse(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_Deleted_False()+ {+ var scope = Build("store-1");+ var target = new Customer { StoreId = "store-1", Deleted = true };++ Assert.IsFalse(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_NotRegistered_False()+ {+ var scope = Build("store-1", isRegistered: false);+ var target = new Customer { StoreId = "store-1", Deleted = false };++ Assert.IsFalse(await scope.HasAccess(target));+ }++ [TestMethod]+ public async Task HasAccess_NullEntity_False()+ {+ var scope = Build("store-1");++ Assert.IsFalse(await scope.HasAccess(null));+ }++ [TestMethod]+ public void DefaultStoreId_ReturnsStaffStoreId()+ {+ var scope = Build("store-1");++ Assert.AreEqual("store-1", scope.DefaultStoreId);+ Assert.IsNull(scope.DefaultVendorId);+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.csindex beda3bb22..7fbd5b0a9 100644--- a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs@@ -42,6 +42,7 @@ public class CustomerViewModelServiceTestsprivate Mock<IStoreService> _storeServiceMock;private Mock<ICustomerTagService> _customerTagServiceMock;private Mock<IVendorService> _vendorServiceMock;+ private Mock<IAffiliateService> _affiliateServiceMock;private Mock<IEnumTranslationService> _enumTranslationServiceMock;private Mock<ICustomerNoteService> _customerNoteServiceMock;private Mock<ICustomerProductService> _customerProductServiceMock;@@ -62,6 +63,7 @@ public class CustomerViewModelServiceTests_storeServiceMock = new Mock<IStoreService>();_customerTagServiceMock = new Mock<ICustomerTagService>();_vendorServiceMock = new Mock<IVendorService>();+ _affiliateServiceMock = new Mock<IAffiliateService>();_enumTranslationServiceMock = new Mock<IEnumTranslationService>();_customerNoteServiceMock = new Mock<ICustomerNoteService>();_customerProductServiceMock = new Mock<ICustomerProductService>();@@ -144,7 +146,7 @@ public class CustomerViewModelServiceTestscustomerAttributeServiceMock.Object,new Mock<IAddressAttributeParser>().Object,new Mock<IAddressAttributeService>().Object,- new Mock<IAffiliateService>().Object,+ _affiliateServiceMock.Object,_customerTagServiceMock.Object,_productServiceMock.Object,salesEmployeeServiceMock.Object,@@ -203,6 +205,82 @@ public class CustomerViewModelServiceTestsAssert.IsTrue(string.IsNullOrEmpty(model.StoreId));}+ /// <summary>+ /// TabInfo.cshtml (Task 13) gates CustomerGroups/CustomerTags/VendorId/StaffStoreId/StoreId/+ /// Owner/SeId/AffiliateId behind "@if (Scope.DefaultStoreId is null)" — Admin-scoped rendering+ /// only. PrepareCustomerModel itself is host-agnostic and always populates these fields; the+ /// Store host's own BaseCustomerController.ApplyPostConstraints (not PrepareCustomerModel)+ /// blanks/forces them back on POST. This test proves PrepareCustomerModel's output has every+ /// field both hosts' TabInfo.cshtml needs, for a global-scoped (Admin) call, so Admin's view+ /// has real data to render behind its gate.+ /// </summary>+ [TestMethod]+ public async Task PrepareCustomerModel_GlobalScopedCall_PopulatesAdminOnlyGatedFields()+ {+ var customer = new Customer+ {+ Id = "c1",+ Email = "[email protected]",+ VendorId = "vendor-1",+ StaffStoreId = "store-staff",+ StoreId = "store-9",+ SeId = "se-1",+ AffiliateId = "aff-1"+ };+ customer.CustomerTags.Add("tag-1");+ _customerTagServiceMock.Setup(t => t.GetCustomerTagById("tag-1"))+ .ReturnsAsync(new CustomerTag { Id = "tag-1", Name = "VIP" });+ _groupServiceMock.Setup(g => g.IsOwner(customer)).ReturnsAsync(true);+ _affiliateServiceMock.Setup(a => a.GetAffiliateById("aff-1"))+ .ReturnsAsync(new Grand.Domain.Affiliates.Affiliate+ {+ Id = "aff-1",+ Address = new Address { FirstName = "Aff", LastName = "Iliate" }+ });++ var model = new CustomerModel();+ await _customerViewModelService.PrepareCustomerModel(model, customer, false);++ //fields TabInfo.cshtml renders unconditionally on both hosts+ Assert.AreEqual("[email protected]", model.Email);+ //fields TabInfo.cshtml gates behind "Scope.DefaultStoreId is null" (category (a)/(b) per+ //Task 13's audit) — PrepareCustomerModel always populates them; the view/controller layer+ //decides visibility, not this service.+ Assert.AreEqual("VIP, ", model.CustomerTags);+ Assert.IsTrue(string.IsNullOrEmpty(model.Owner)); //IsOwner true -> Owner blanked, by design+ Assert.AreEqual("aff-1", model.AffiliateId);+ }++ /// <summary>+ /// Store-scoped call: BaseCustomerController.ApplyPostConstraints (Store's override, exercised+ /// on POST, not by PrepareCustomerModel) is what actually forces/blanks StoreId/Owner/VendorId/+ /// StaffStoreId/SeId/CustomerGroups. This test proves the GET/prepare path still leaves those+ /// same fields populated from the entity for an existing customer even when scoped to a store,+ /// confirming TabInfo.cshtml's Scope-gate — not this service — is what hides them for Store.+ /// </summary>+ [TestMethod]+ public async Task PrepareCustomerModel_StoreScopedExistingCustomer_StillMapsGatedFieldsFromEntity()+ {+ var customer = new Customer+ {+ Id = "c1",+ Email = "[email protected]",+ StoreId = "store-9",+ VendorId = "vendor-1"+ };++ var model = new CustomerModel();+ await _customerViewModelService.PrepareCustomerModel(model, customer, false);++ //fields Store's TabInfo.cshtml needs (ungated, always rendered)+ Assert.AreEqual("[email protected]", model.Email);+ //PrepareCustomerModel maps StoreId/VendorId from the entity regardless of host; it is+ //ApplyPostConstraints (controller-level, Store-only) that later forces StoreId back to+ //scope.DefaultStoreId and blanks VendorId on submit -- not this method.+ Assert.AreEqual("store-9", model.StoreId);+ Assert.AreEqual("vendor-1", model.VendorId);+ }+[TestMethod]public async Task UpdateCustomerModel_MapsStoreIdFromModel(){diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerAttributeTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerAttributeTests.csnew file mode 100644index 000000000..94099932a--- /dev/null+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerAttributeTests.cs@@ -0,0 +1,82 @@+using System.Reflection;+using Grand.Web.Common.Filters;+using Grand.Web.Store.Controllers;+using Microsoft.AspNetCore.Mvc;+using Microsoft.VisualStudio.TestTools.UnitTesting;++namespace Grand.Web.Store.Tests.Controllers;++// Mirrors the Admin equivalent (Task 10, CustomerControllerAttributeTests.cs) and the same+// deviation it recorded: the task-11 brief's draft checked for+// Microsoft.AspNetCore.Authorization.AuthorizeAttribute for [AuthorizeStore], but AuthorizeStore+// is Grand.Web.Common.Filters.AuthorizeStoreAttribute, a TypeFilterAttribute that does NOT derive+// from AuthorizeAttribute (verified directly against AuthorizeStoreAttribute.cs) — so that check+// would read 0 matches both before AND after the cutover and could never catch the regression it+// exists to catch. Checked directly against AuthorizeStoreAttribute/AuthorizeMenuAttribute instead.+[TestClass]+public class CustomerControllerAttributeTests+{+ [TestMethod]+ public void CustomerController_CarriesAreaAttribute()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AreaAttribute), inherit: false);+ Assert.AreEqual(1, attr.Length,+ "CustomerController must restate [Area] — BaseCustomerController can't carry it (host-agnostic, lives in AdminShared).");+ Assert.AreEqual("Store", ((AreaAttribute)attr[0]).RouteValue);+ }++ [TestMethod]+ public void CustomerController_CarriesAuthorizeStoreAttribute()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AuthorizeStoreAttribute), inherit: false);+ Assert.IsTrue(attr.Length >= 1,+ "CustomerController must restate [AuthorizeStore] — it previously arrived via BaseStoreController, which the new shared base can't extend.");+ }++ [TestMethod]+ public void CustomerController_CarriesAuthorizeMenuAttribute()+ {+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AuthorizeMenuAttribute), inherit: false);+ Assert.IsTrue(attr.Length >= 1, "CustomerController must restate [AuthorizeMenu] — same transitive-base problem as [AuthorizeStore].");+ }++ [TestMethod]+ public void CustomerController_CarriesAutoValidateAntiforgeryToken_ViaInheritance()+ {+ // Unlike Area/AuthorizeStore/AuthorizeMenu, BaseCustomerController (AdminShared) already+ // states [AutoValidateAntiforgeryToken] directly (Task 4) — Store's original+ // BaseStoreController also carried it, but since it's no longer in the inheritance chain,+ // confirm it still arrives, now via BaseCustomerController, without Store needing to+ // restate it itself.+ var attr = typeof(CustomerController).GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: true);+ Assert.IsTrue(attr.Length >= 1);+ var ownAttr = typeof(CustomerController).GetCustomAttributes(typeof(AutoValidateAntiforgeryTokenAttribute), inherit: false);+ Assert.AreEqual(0, ownAttr.Length,+ "CustomerController should NOT restate [AutoValidateAntiforgeryToken] itself — it already arrives from BaseCustomerController.");+ }++ [TestMethod]+ public void CustomerController_DoesNotInheritBaseCustomerManagementController()+ {+ // Store gets the SUBSET surface only — verify it inherited the shared base, not the+ // Admin-only management subclass, so Impersonate/Export/etc. can never leak onto Store.+ Assert.IsFalse(typeof(Grand.Web.AdminShared.Controllers.BaseCustomerManagementController)+ .IsAssignableFrom(typeof(CustomerController)));+ Assert.IsTrue(typeof(Grand.Web.AdminShared.Controllers.BaseCustomerController)+ .IsAssignableFrom(typeof(CustomerController)));+ }++ [TestMethod]+ public void CustomerController_DeclaresOnlyItsThreeOwnMembers()+ {+ // The per-store gate override, PerStoreDisabled, and ApplyPostConstraints override are+ // genuine Store-only infrastructure — everything else must live in BaseCustomerController.+ var ownMethods = typeof(CustomerController).GetMethods(+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);+ var ownMethodNames = ownMethods.Select(m => m.Name)+ .Where(n => !n.StartsWith("get_") && !n.StartsWith("set_")).ToHashSet();+ var allowed = new HashSet<string> { "OnActionExecutionAsync", "PerStoreDisabled", "ApplyPostConstraints", ".ctor" };+ Assert.IsTrue(ownMethodNames.IsSubsetOf(allowed),+ $"Unexpected own members on thin Store subclass: {string.Join(", ", ownMethodNames.Except(allowed))}");+ }+}diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.csindex 21f63d44a..e3348c1f3 100644--- a/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.cs+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.cs@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Business.Core.Interfaces.Marketing.Customers;using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Utilities.Customers;using Grand.Domain.Customers;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;@@ -24,6 +25,11 @@ using Moq;namespace Grand.Web.Store.Tests.Controllers;+// Trimmed for the Task 11 thin-subclass cutover: business logic now shared through+// BaseCustomerController is exercised by BaseCustomerControllerTests.cs (Admin.Tests, Tasks 4-8)+// and applies identically to Store. What remains here is genuinely Store-only: the per-store+// feature gate (OnActionExecutionAsync), the PerStoreDisabled page, and the+// ApplyPostConstraints override's anti-smuggling contract.[TestClass]public class CustomerControllerTests{@@ -36,6 +42,7 @@ public class CustomerControllerTestsprivate Mock<IGroupService> _groupServiceMock;private Mock<ITranslationService> _translationServiceMock;private Mock<IContextAccessor> _contextAccessorMock;+ private Mock<IAdminDataScope<Customer>> _scopeMock;[TestInitialize]public void Setup()@@ -52,11 +59,46 @@ public class CustomerControllerTestsworkContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer { StaffStoreId = StoreId });_contextAccessorMock = new Mock<IContextAccessor>();_contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);++ _scopeMock = new Mock<IAdminDataScope<Customer>>();+ _scopeMock.Setup(s => s.DefaultStoreId).Returns(StoreId);+ }++ /// <summary>Test-only subclass exposing the protected ApplyPostConstraints override for direct+ /// invocation, analogous to BaseCustomerControllerTests's LoadAuthorizedCustomerPublic+ /// wrapper.</summary>+ private class TestableCustomerController(+ ICustomerService customerService,+ ICustomerViewModelService customerViewModelService,+ ICustomerManagerService customerManagerService,+ ICustomerProductService customerProductService,+ IProductReviewService productReviewService,+ IProductReviewViewModelService productReviewViewModelService,+ IProductViewModelService productViewModelService,+ ICustomerAttributeParser customerAttributeParser,+ ICustomerAttributeService customerAttributeService,+ IAddressAttributeParser addressAttributeParser,+ IAddressAttributeService addressAttributeService,+ IMessageProviderService messageProviderService,+ IGroupService groupService,+ ITranslationService translationService,+ IContextAccessor contextAccessor,+ CustomerSettings customerSettings,+ IAdminDataScope<Customer> scope,+ CustomerConfig customerConfig)+ : CustomerController(customerService, customerViewModelService, customerManagerService,+ customerProductService, productReviewService, productReviewViewModelService, productViewModelService,+ customerAttributeParser, customerAttributeService, addressAttributeParser, addressAttributeService,+ messageProviderService, groupService, translationService, contextAccessor, customerSettings, scope,+ customerConfig)+ {+ public Task ApplyPostConstraintsPublic(CustomerModel model) => ApplyPostConstraints(model);}- private CustomerController BuildController(bool perStoreEnabled)+ private TestableCustomerController BuildStoreController(bool perStoreEnabled = true,+ IGroupService groupService = null, IAdminDataScope<Customer> scope = null){- var controller = new CustomerController(+ var controller = new TestableCustomerController(_customerServiceMock.Object,_customerViewModelServiceMock.Object,_customerManagerServiceMock.Object,@@ -69,10 +111,11 @@ public class CustomerControllerTestsnew Mock<IAddressAttributeParser>().Object,new Mock<IAddressAttributeService>().Object,new Mock<IMessageProviderService>().Object,- _groupServiceMock.Object,+ groupService ?? _groupServiceMock.Object,_translationServiceMock.Object,_contextAccessorMock.Object,new CustomerSettings(),+ scope ?? _scopeMock.Object,new CustomerConfig { RegisterCustomersPerStore = perStoreEnabled });var httpContext = new DefaultHttpContext();@@ -81,21 +124,19 @@ public class CustomerControllerTestsreturn controller;}- private static (ActionExecutingContext context, Func<bool> wasNextCalled) BuildGate(CustomerController controller,- string actionName)+ private static ActionExecutingContext BuildGate(CustomerController controller, string actionName){var actionContext = new ActionContext(controller.ControllerContext.HttpContext, new RouteData(),new ControllerActionDescriptor { ActionName = actionName });- var context = new ActionExecutingContext(actionContext, new List<IFilterMetadata>(),+ return new ActionExecutingContext(actionContext, new List<IFilterMetadata>(),new Dictionary<string, object>(), controller);- return (context, () => false);}[TestMethod]public async Task Gate_PerStoreDisabled_RedirectsToPerStoreDisabled(){- var controller = BuildController(perStoreEnabled: false);- var (context, _) = BuildGate(controller, nameof(CustomerController.List));+ var controller = BuildStoreController(perStoreEnabled: false);+ var context = BuildGate(controller, nameof(CustomerController.List));var nextCalled = false;await controller.OnActionExecutionAsync(context, () =>@@ -113,8 +154,8 @@ public class CustomerControllerTests[TestMethod]public async Task Gate_PerStoreDisabled_AllowsPerStoreDisabledAction(){- var controller = BuildController(perStoreEnabled: false);- var (context, _) = BuildGate(controller, nameof(CustomerController.PerStoreDisabled));+ var controller = BuildStoreController(perStoreEnabled: false);+ var context = BuildGate(controller, nameof(CustomerController.PerStoreDisabled));var nextCalled = false;await controller.OnActionExecutionAsync(context, () =>@@ -130,8 +171,8 @@ public class CustomerControllerTests[TestMethod]public async Task Gate_PerStoreEnabled_CallsNext(){- var controller = BuildController(perStoreEnabled: true);- var (context, _) = BuildGate(controller, nameof(CustomerController.List));+ var controller = BuildStoreController(perStoreEnabled: true);+ var context = BuildGate(controller, nameof(CustomerController.List));var nextCalled = false;await controller.OnActionExecutionAsync(context, () =>@@ -147,47 +188,63 @@ public class CustomerControllerTests[TestMethod]public void PerStoreDisabled_ReturnsView(){- var controller = BuildController(perStoreEnabled: false);+ var controller = BuildStoreController(perStoreEnabled: false);var result = controller.PerStoreDisabled();Assert.IsInstanceOfType(result, typeof(ViewResult));}[TestMethod]- public async Task Create_ForcesStoreScopedRegisteredOnlyConstraints()+ public async Task ApplyPostConstraints_CraftedPost_CannotSmuggleOwnershipFields(){- var controller = BuildController(perStoreEnabled: true);-- _groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered))- .ReturnsAsync(new CustomerGroup { Id = "registered-group" });- _customerAttributeServiceMock.Setup(a => a.GetAllCustomerAttributes())- .ReturnsAsync(new List<CustomerAttribute>());-- CustomerModel captured = null;- _customerViewModelServiceMock.Setup(s => s.InsertCustomerModel(It.IsAny<CustomerModel>()))- .Callback<CustomerModel>(m => captured = m)- .ReturnsAsync(new Customer { Id = "c1", StoreId = StoreId });-- //a malicious payload trying to assign a foreign store/role/ownership- var model = new CustomerModel {- Email = "[email protected]",- StoreId = "foreign-store",- Owner = "[email protected]",- VendorId = "vendor-1",- StaffStoreId = "staff-store",- SeId = "sales-1",- CustomerGroups = ["administrators-group"],- SelectedAttributes = new List<CustomAttributeModel>()+ // Anti-smuggling proof required by the design spec: a caller-crafted CustomerModel claiming+ // a foreign StoreId/Owner/VendorId/StaffStoreId/SeId/CustomerGroups must be fully overwritten,+ // not merely "some field got touched."+ var groupServiceMock = new Mock<IGroupService>();+ var registered = new CustomerGroup { Id = "registered-id" };+ groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered))+ .ReturnsAsync(registered);+ var scopeMock = new Mock<IAdminDataScope<Customer>>();+ scopeMock.Setup(s => s.DefaultStoreId).Returns("legit-store-1");+ var controller = BuildStoreController(groupService: groupServiceMock.Object, scope: scopeMock.Object);++ var craftedModel = new CustomerModel {+ StoreId = "attacker-foreign-store",+ Owner = "attacker-owner-id",+ VendorId = "attacker-vendor-id",+ StaffStoreId = "attacker-staff-store-id",+ SeId = "attacker-se-id",+ CustomerGroups = new[] { "attacker-admin-group-id" }};- var result = await controller.Create(model, false);+ await controller.ApplyPostConstraintsPublic(craftedModel);++ // Assert the ACTUAL enforced values, not merely that the method ran (the Phase 19+ // MessageTemplate review lesson this task explicitly carries forward).+ Assert.AreEqual("legit-store-1", craftedModel.StoreId);+ Assert.AreEqual("", craftedModel.Owner);+ Assert.AreEqual("", craftedModel.VendorId);+ Assert.AreEqual("", craftedModel.StaffStoreId);+ Assert.AreEqual("", craftedModel.SeId);+ CollectionAssert.AreEqual(new[] { "registered-id" }, craftedModel.CustomerGroups.ToArray());+ }++ [TestMethod]+ public async Task ApplyPostConstraints_NoRegisteredGroupFound_ClearsCustomerGroups()+ {+ // Edge case the crafted-POST test doesn't cover: if the Registered group is missing/+ // misconfigured, the override must not fall back to whatever the caller submitted — it+ // must end up empty, never the attacker-supplied group list.+ var groupServiceMock = new Mock<IGroupService>();+ groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered))+ .ReturnsAsync((CustomerGroup)null);+ var scopeMock = new Mock<IAdminDataScope<Customer>>();+ scopeMock.Setup(s => s.DefaultStoreId).Returns("legit-store-1");+ var controller = BuildStoreController(groupService: groupServiceMock.Object, scope: scopeMock.Object);++ var craftedModel = new CustomerModel { CustomerGroups = new[] { "attacker-admin-group-id" } };++ await controller.ApplyPostConstraintsPublic(craftedModel);- Assert.IsInstanceOfType(result, typeof(RedirectToActionResult));- Assert.IsNotNull(captured);- Assert.AreEqual(StoreId, captured.StoreId);- Assert.AreEqual("", captured.Owner);- Assert.AreEqual("", captured.VendorId);- Assert.AreEqual("", captured.StaffStoreId);- Assert.AreEqual("", captured.SeId);- CollectionAssert.AreEqual(new[] { "registered-group" }, captured.CustomerGroups);+ Assert.AreEqual(0, craftedModel.CustomerGroups.Count());}}diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtmldeleted file mode 100644index eb944eebb..000000000--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml+++ /dev/null@@ -1,86 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings-<div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_addresses_top" additional-data="Model"/>- <div class="panel-body">- <div id="customer-addresses-grid"></div>- </div>- <div class="panel-footer">- <button type="button" class="k-button" onclick="location.href='@Url.Action("AddressCreate", new { customerId = Model.Id, area = Constants.AreaAdmin })'"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.Addresses.AddButton"]</button>- </div>- <vc:admin-widget widget-zone="customer_details_addresses_bottom" additional-data="Model"/>-</div>--<script>-$(document).ready(function () {- $("#customer-addresses-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("AddressesSelect", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("AddressDelete", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors",- model: {- id: "Id"- }- },- error: function(e) {- display_kendoui_grid_error(e);- // Cancel the changes- this.cancelChanges();- },- pageSize: @(adminAreaSettings.DefaultGridPageSize),- },- autoBind: false,- pageable: {- refresh: true,- pageSizes: [@(adminAreaSettings.GridPageSizes)]- },- editable: {- confirmation: true,- mode: "inline"- },- scrollable: false,- columns: [{- field: "FirstName",- title: "@Loc["Admin.Address.Fields.FirstName"]"- }, {- field: "LastName",- title: "@Loc["Admin.Address.Fields.LastName"]"- }, {- field: "Email",- title: "@Loc["Admin.Address.Fields.Email"]"- }, {- field: "PhoneNumber",- title: "@Loc["Admin.Address.Fields.PhoneNumber"]",- minScreenWidth: 1020,- }, {- field: "AddressHtml",- title: "@Loc["Admin.Address"]",- encoded: false- }, {- field: "Id",- title: "@Loc["Admin.Common.Edit"]",- width: 100,- template: '<a class="k-button" href="@Url.Action("AddressEdit", "Customer", new { area = Constants.AreaAdmin })[email protected]&addressid=#=Id#"><span class="k-icon k-i-edit"></span> @Loc["Admin.Common.Edit"]</a>'- }, {- command: { name: "destroy", text: "@Loc["Admin.Common.Delete"]" },- title: "@Loc["Admin.Common.Delete"]",- width: 100- }]- });-});-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdateAddress.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdateAddress.cshtmldeleted file mode 100644index acb51e999..000000000--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdateAddress.cshtml+++ /dev/null@@ -1,6 +0,0 @@-@model CustomerAddressModel-<div asp-validation-summary="All"></div>-<input type="hidden" asp-for="CustomerId"/>-<vc:admin-widget widget-zone="customer_address_details_top" additional-data="Model"/>-<admin-input asp-for="Address" asp-template="Address"/>-<vc:admin-widget widget-zone="customer_address_details_bottom" additional-data="Model"/>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/SendEmail.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/SendEmail.cshtmldeleted file mode 100644index 35fb2aafe..000000000--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/SendEmail.cshtml+++ /dev/null@@ -1,70 +0,0 @@-@model CustomerModel.SendEmailModel--<div id="sendemail-window" style="display:none;">- <form asp-area="@Constants.AreaAdmin" asp-controller="Customer" asp-action="SendEmail" method="post" asp-route-id="Id">- <input type="hidden" asp-for="Id" id="sendemail_customerId"/>- <div class="form-horizontal">- <div class="form-body">- <div class="form-group">- <admin-label asp-for="Subject"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="Subject"/>- <span asp-validation-for="Subject"></span>- </div>- </div>- <div class="form-group">- <admin-label asp-for="Body"/>- <div class="col-md-9 col-sm-9">- <admin-textarea asp-for="Body"></admin-textarea>- <span asp-validation-for="Body"></span>- </div>- </div>- <div class="form-group">- <admin-label asp-for="SendImmediately"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="SendImmediately"/>- <span asp-validation-for="SendImmediately"></span>- </div>- </div>- <div class="form-group" id="pnl-send-date">- <admin-label asp-for="DontSendBeforeDate"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="DontSendBeforeDate"/>- <span asp-validation-for="DontSendBeforeDate"></span>- </div>- </div>- </div>- <div class="form-actions">- <div class="offset-md-3 offset-sm-3 col-md-6 col-sm-6">- <button type="submit" class="k-button"><span class="k-icon k-i-email"></span> @Loc["Admin.Customers.Customers.SendEmail"]</button>- </div>- </div>- </div>- </form>-</div>-<script>- $(document).ready(function () {- $("#sendemail").click(function (e) {- e.preventDefault();- var window = $("#sendemail-window");- if (!window.data("kendoWindow")) {- window.kendoWindow({- modal: true,- width: "650px",- title: "@Loc["Admin.Customers.Customers.SendEmail"]",- actions: ["Close"]- });- }- window.data('kendoWindow').center().open();- });--- //timing of send email section- $("#pnl-send-date").hide();-- $("#sendemail-window .check-box").click(function () {- $("#pnl-send-date").toggle();- });-- });-</script>\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressDetailsBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressDetailsBottom.cshtmlnew file mode 100644index 000000000..884b7439d--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressDetailsBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerAddressModel+<vc:admin-widget widget-zone="customer_address_details_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressDetailsTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressDetailsTop.cshtmlnew file mode 100644index 000000000..f05c24948--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressDetailsTop.cshtml@@ -0,0 +1,2 @@+@model CustomerAddressModel+<vc:admin-widget widget-zone="customer_address_details_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressesBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressesBottom.cshtmlnew file mode 100644index 000000000..bfc513337--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressesBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_addresses_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressesTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressesTop.cshtmlnew file mode 100644index 000000000..aac5252d7--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.AddressesTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_addresses_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.BackInStockBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.BackInStockBottom.cshtmlnew file mode 100644index 000000000..598d25ccf--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.BackInStockBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_back_in_stock_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.BackInStockTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.BackInStockTop.cshtmlnew file mode 100644index 000000000..65df692ac--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.BackInStockTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_back_in_stock_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.DetailsTabs.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.DetailsTabs.cshtmlnew file mode 100644index 000000000..8f25a432a--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.DetailsTabs.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_tabs" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.InfoBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.InfoBottom.cshtmlnew file mode 100644index 000000000..91f1e0331--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.InfoBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_info_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.InfoTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.InfoTop.cshtmlnew file mode 100644index 000000000..52a140316--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.InfoTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_info_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.LoyaltyPointsBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.LoyaltyPointsBottom.cshtmlnew file mode 100644index 000000000..4f000fb2f--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.LoyaltyPointsBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_loyalty_points_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.LoyaltyPointsTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.LoyaltyPointsTop.cshtmlnew file mode 100644index 000000000..f8335fda3--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.LoyaltyPointsTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_loyalty_points_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.OrdersBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.OrdersBottom.cshtmlnew file mode 100644index 000000000..335f0c6fa--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.OrdersBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_orders_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.OrdersTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.OrdersTop.cshtmlnew file mode 100644index 000000000..fb1056ce0--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.OrdersTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_orders_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductBottom.cshtmlnew file mode 100644index 000000000..a7383ab6b--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_product_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductPriceBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductPriceBottom.cshtmlnew file mode 100644index 000000000..71a475e82--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductPriceBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_product_price_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductPriceTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductPriceTop.cshtmlnew file mode 100644index 000000000..af36e0b82--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductPriceTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_product_price_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductTop.cshtmlnew file mode 100644index 000000000..e26b4cc6e--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ProductTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_product_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ReviewsBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ReviewsBottom.cshtmlnew file mode 100644index 000000000..78921ebe4--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ReviewsBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_reviews_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ReviewsTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ReviewsTop.cshtmlnew file mode 100644index 000000000..042f376b6--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ReviewsTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_reviews_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ShoppingCartBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ShoppingCartBottom.cshtmlnew file mode 100644index 000000000..392132f66--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ShoppingCartBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_shopping_cart_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ShoppingCartTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ShoppingCartTop.cshtmlnew file mode 100644index 000000000..3ef65ae7b--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.ShoppingCartTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_shopping_cart_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.WishlistBottom.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.WishlistBottom.cshtmlnew file mode 100644index 000000000..260f335fd--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.WishlistBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_wishlist_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.WishlistTop.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.WishlistTop.cshtmlnew file mode 100644index 000000000..5e5f383e1--- /dev/null+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/WidgetZone.WishlistTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:admin-widget widget-zone="customer_details_wishlist_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.csindex 1509f59c3..f2fd982bd 100644--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs@@ -1,1007 +1,36 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Interfaces.Checkout.Orders;-using Grand.Business.Core.Interfaces.Common.Addresses;-using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Interfaces.Common.Security;-using Grand.Business.Core.Interfaces.Customers;-using Grand.Business.Core.Interfaces.ExportImport;-using Grand.Business.Core.Interfaces.Messages;-using Grand.Business.Core.Utilities.Customers;-using Grand.Domain.Catalog;-using Grand.Domain.Common;-using Grand.Domain.Customers;-using Grand.Domain.Permissions;-using Grand.Domain.Tax;-using Grand.Infrastructure;-using Grand.SharedKernel;-using Grand.SharedKernel.Extensions;-using Grand.Web.AdminShared.Extensions;-using Grand.Web.AdminShared.Interfaces;-using Grand.Web.AdminShared.Models.Catalog;-using Grand.Web.AdminShared.Models.Customers;-using Grand.Web.AdminShared.Models.Orders;-using Grand.Web.Common.DataSource;+using Grand.Web.Admin.Extensions;+using Grand.Web.AdminShared.Controllers;using Grand.Web.Common.Filters;-using Grand.Web.Common.Models;-using Grand.Web.Common.Security.Authorization;using Microsoft.AspNetCore.Mvc;namespace Grand.Web.Admin.Controllers;-[PermissionAuthorize(PermissionSystemName.Customers)]-public class CustomerController : BaseAdminController-{- #region Constructors-- public CustomerController(ICustomerService customerService,- IProductReviewService productReviewService,- IProductReviewViewModelService productReviewViewModelService,- IProductViewModelService productViewModelService,- ICustomerViewModelService customerViewModelService,- ICustomerManagerService customerManagerService,- ITranslationService translationService,- IContextAccessor contextAccessor,- IGroupService groupService,- IExportManager<Customer> exportManager,- ICustomerAttributeParser customerAttributeParser,- ICustomerAttributeService customerAttributeService,- IAddressAttributeParser addressAttributeParser,- IAddressAttributeService addressAttributeService,- IMessageProviderService messageProviderService,- IPermissionService permissionService,- CustomerSettings customerSettings)- {- _customerService = customerService;- _productReviewService = productReviewService;- _productReviewViewModelService = productReviewViewModelService;- _productViewModelService = productViewModelService;- _customerViewModelService = customerViewModelService;- _customerManagerService = customerManagerService;- _translationService = translationService;- _contextAccessor = contextAccessor;- _groupService = groupService;- _exportManager = exportManager;- _customerAttributeParser = customerAttributeParser;- _customerAttributeService = customerAttributeService;- _addressAttributeParser = addressAttributeParser;- _addressAttributeService = addressAttributeService;- _messageProviderService = messageProviderService;- _permissionService = permissionService;- _customerSettings = customerSettings;- }-- #endregion-- protected virtual async Task<IList<CustomAttribute>> ParseCustomCustomerAttributes(- IList<CustomAttributeModel> model)- {- ArgumentNullException.ThrowIfNull(model);-- var customAttributes = new List<CustomAttribute>();- var customerAttributes = await _customerAttributeService.GetAllCustomerAttributes();- foreach (var attribute in customerAttributes)- {- var controlId = $"customer_attribute_{attribute.Id}";- switch (attribute.AttributeControlTypeId)- {- case AttributeControlType.DropdownList:- case AttributeControlType.RadioList:- {- var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customAttributes = _customerAttributeParser.AddCustomerAttribute(customAttributes,- attribute, ctrlAttributes).ToList();- }- break;- case AttributeControlType.Checkboxes:- {- var cblAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- foreach (var item in cblAttributes.Split(','))- if (!string.IsNullOrEmpty(item))- customAttributes = _customerAttributeParser.AddCustomerAttribute(customAttributes,- attribute, item).ToList();- }- break;- case AttributeControlType.ReadonlyCheckboxes:- {- //load read-only (already server-side selected) values- var attributeValues = attribute.CustomerAttributeValues;- foreach (var selectedAttributeId in attributeValues- .Where(v => v.IsPreSelected)- .Select(v => v.Id)- .ToList())- customAttributes = _customerAttributeParser.AddCustomerAttribute(customAttributes,- attribute, selectedAttributeId).ToList();- }- break;- case AttributeControlType.TextBox:- case AttributeControlType.MultilineTextbox:- {- var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- {- var enteredText = ctrlAttributes.Trim();- customAttributes = _customerAttributeParser.AddCustomerAttribute(customAttributes,- attribute, enteredText).ToList();- }- }- break;- case AttributeControlType.Datepicker:- case AttributeControlType.ColorSquares:- case AttributeControlType.ImageSquares:- case AttributeControlType.FileUpload:- //not supported customer attributes- default:- break;- }- }-- return customAttributes;- }-- protected virtual async Task<bool> CheckSalesManager(Customer customer)- {- return await _groupService.IsSalesManager(_contextAccessor.WorkContext.CurrentCustomer)- && _contextAccessor.WorkContext.CurrentCustomer.SeId != customer.SeId;- }-- #region Message contact form-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> ContactFormList(DataSourceRequest command, string customerId)- {- var (contactFormModels, totalCount) =- await _customerViewModelService.PrepareContactFormModel(customerId, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = contactFormModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- #endregion-- #region Out of stock subscriptions-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> OutOfStockSubscriptionList(DataSourceRequest command, string customerId)- {- var (outOfStockSubscriptionModels, totalCount) =- await _customerViewModelService.PrepareOutOfStockSubscriptionModel(customerId, command.Page,- command.PageSize);- var gridModel = new DataSourceResult {- Data = outOfStockSubscriptionModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- #endregion-- #region Fields-- private readonly ICustomerService _customerService;- private readonly IGroupService _groupService;- private readonly IProductReviewService _productReviewService;- private readonly IProductReviewViewModelService _productReviewViewModelService;- private readonly IProductViewModelService _productViewModelService;- private readonly ICustomerViewModelService _customerViewModelService;- private readonly ICustomerManagerService _customerManagerService;- private readonly ITranslationService _translationService;- private readonly IContextAccessor _contextAccessor;- private readonly IExportManager<Customer> _exportManager;- private readonly ICustomerAttributeParser _customerAttributeParser;- private readonly ICustomerAttributeService _customerAttributeService;- private readonly IAddressAttributeParser _addressAttributeParser;- private readonly IAddressAttributeService _addressAttributeService;- private readonly IMessageProviderService _messageProviderService;- private readonly IPermissionService _permissionService;- private readonly CustomerSettings _customerSettings;-- #endregion-- #region Customers-- public IActionResult Index()- {- return RedirectToAction("List");- }-- public async Task<IActionResult> List()- {- var model = await _customerViewModelService.PrepareCustomerListModel();- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.List)]- [HttpPost]- public async Task<IActionResult> CustomerList(DataSourceRequest command, CustomerListModel model,- string[] searchCustomerGroupIds, string[] searchCustomerTagIds)- {- var (customerModelList, totalCount) = await _customerViewModelService.PrepareCustomerList(model,- searchCustomerGroupIds, searchCustomerTagIds, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = customerModelList.ToList(),- Total = totalCount- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Create)]- public async Task<IActionResult> Create()- {- var model = new CustomerModel();- await _customerViewModelService.PrepareCustomerModel(model, null, false);- //default value- model.Active = true;- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]- public async Task<IActionResult> Create(CustomerModel model, bool continueEditing)- {- if (model.TwoFactorEnabled)- Warning(_translationService.GetResource("Admin.Customers.Customers.CannotTwoFactorEnabled"));-- if (ModelState.IsValid)- {- model.Attributes = await ParseCustomCustomerAttributes(model.SelectedAttributes);- var customer = await _customerViewModelService.InsertCustomerModel(model);-- //password- if (!string.IsNullOrWhiteSpace(model.Password))- {- var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat,- model.Password);- await _customerManagerService.ChangePassword(changePassRequest, customer.StoreId);- }-- Success(_translationService.GetResource("Admin.Customers.Customers.Added"));- return continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List");- }-- //If we got this far, something failed, redisplay form- await _customerViewModelService.PrepareCustomerModel(model, null, true);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- public async Task<IActionResult> Edit(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- var model = new CustomerModel();- await _customerViewModelService.PrepareCustomerModel(model, customer, false);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]- public async Task<IActionResult> Edit(CustomerModel model, bool continueEditing)- {- var customer = await _customerService.GetCustomerById(model.Id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- if (!customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled) && model.TwoFactorEnabled)- Warning(_translationService.GetResource("Admin.Customers.Customers.CannotTwoFactorEnabled"));-- if (ModelState.IsValid)- try- {- model.Attributes = await ParseCustomCustomerAttributes(model.SelectedAttributes);- customer = await _customerViewModelService.UpdateCustomerModel(customer, model);- //change password- if (!string.IsNullOrWhiteSpace(model.Password))- {- var changePassRequest = new ChangePasswordRequest(model.Email,- _customerSettings.DefaultPasswordFormat, model.Password);- await _customerManagerService.ChangePassword(changePassRequest, customer.StoreId);- }-- Success(_translationService.GetResource("Admin.Customers.Customers.Updated"));- if (continueEditing)- {- //selected tab- await SaveSelectedTabIndex();-- return RedirectToAction("Edit", new { id = customer.Id });- }-- return RedirectToAction("List");- }- catch (Exception exc)- {- Error(exc.Message);- }-- //If we got this far, something failed, redisplay form- await _customerViewModelService.PrepareCustomerModel(model, customer, true);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> MarkVatNumberAsValid(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- await _customerService.UpdateUserField(customer,- SystemCustomerFieldNames.VatNumberStatusId,- (int)VatNumberStatus.Valid);-- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> MarkVatNumberAsInvalid(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- await _customerService.UpdateUserField(customer,- SystemCustomerFieldNames.VatNumberStatusId,- (int)VatNumberStatus.Invalid);-- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> RemoveAffiliate(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- customer.AffiliateId = "";- await _customerService.UpdateCustomerField(customer.Id, x => x.AffiliateId, customer.AffiliateId);- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Delete)]- [HttpPost]- public async Task<IActionResult> Delete(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- if (customer.Id == _contextAccessor.WorkContext.CurrentCustomer.Id)- {- Error(_translationService.GetResource("Admin.Customers.Customers.NoSelfDelete"));- return RedirectToAction("List");- }-- try- {- if (ModelState.IsValid)- {- await _customerViewModelService.DeleteCustomer(customer);- Success(_translationService.GetResource("Admin.Customers.Customers.Deleted"));- return RedirectToAction("List");- }-- Error(ModelState);- return RedirectToAction("Edit", new { id = customer.Id });- }- catch (Exception exc)- {- Error(exc.Message);- return RedirectToAction("Edit", new { id = customer.Id });- }- }-- [PermissionAuthorizeAction(PermissionActionName.Delete)]- public async Task<IActionResult> DeleteSelected(ICollection<string> selectedIds)- {- if (selectedIds != null) await _customerViewModelService.DeleteSelected(selectedIds.ToList());-- return Json(new { Result = true });- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> Impersonate(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- if (!await _permissionService.Authorize(StandardPermission.AllowCustomerImpersonation))- {- Error("User does not have permission for the impersonate session");- return RedirectToAction("Edit", customer.Id);- }-- if (!await _groupService.IsAdmin(_contextAccessor.WorkContext.CurrentCustomer) && await _groupService.IsAdmin(customer))- {- Error("A non-admin user cannot impersonate as an administrator");- return RedirectToAction("Edit", customer.Id);- }-- await _customerService.UpdateUserField(_contextAccessor.WorkContext.CurrentCustomer,- SystemCustomerFieldNames.ImpersonatedCustomerId, customer.Id);-- return RedirectToAction("Index", "Home", new { area = "" });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> SendWelcomeMessage(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- await _messageProviderService.SendCustomerWelcomeMessage(customer, _contextAccessor.StoreContext.CurrentStore,- _contextAccessor.WorkContext.WorkingLanguage.Id);-- Success(_translationService.GetResource("Admin.Customers.Customers.SendWelcomeMessage.Success"));-- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ReSendActivationMessage(string id)- {- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- //email validation message- await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.AccountActivationToken,- Guid.NewGuid().ToString());- await _messageProviderService.SendCustomerEmailValidationMessage(customer, _contextAccessor.StoreContext.CurrentStore,- _contextAccessor.WorkContext.WorkingLanguage.Id);-- Success(_translationService.GetResource("Admin.Customers.Customers.ReSendActivationMessage.Success"));-- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> SendEmail(CustomerModel.SendEmailModel model)- {- var customer = await _customerService.GetCustomerById(model.Id);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- try- {- if (string.IsNullOrWhiteSpace(customer.Email))- throw new GrandException("Customer email is empty");- if (!CommonHelper.IsValidEmail(customer.Email))- throw new GrandException("Customer email is not valid");- if (string.IsNullOrWhiteSpace(model.Subject))- throw new GrandException("Email subject is empty");- if (string.IsNullOrWhiteSpace(model.Body))- throw new GrandException("Email body is empty");-- await _customerViewModelService.SendEmail(customer, model);-- Success(_translationService.GetResource("Admin.Customers.Customers.SendEmail.Queued"));- }- catch (Exception exc)- {- Error(exc.Message);- }-- return RedirectToAction("Edit", new { id = customer.Id });- }-- #endregion-- #region Loyalty points history-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> LoyaltyPointsHistorySelect(string customerId)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id");-- var model = (await _customerViewModelService.PrepareLoyaltyPointsHistoryModel(customerId)).ToList();- var gridModel = new DataSourceResult {- Data = model,- Total = model.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> LoyaltyPointsHistoryAdd(string customerId, string storeId,- int addLoyaltyPointsValue, string addLoyaltyPointsMessage)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- return Json(new { Result = false });-- await _customerViewModelService.InsertLoyaltyPointsHistory(customer, storeId, addLoyaltyPointsValue,- addLoyaltyPointsMessage);-- return Json(new { Result = true });- }-- #endregion-- #region Addresses-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> AddressesSelect(string customerId, DataSourceRequest command)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- var addresses = (await _customerViewModelService.PrepareAddressModel(customer)).ToList();- var gridModel = new DataSourceResult {- Data = addresses,- Total = addresses.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> AddressDelete(string id, string customerId)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- var address = customer.Addresses.FirstOrDefault(a => a.Id == id);- if (address == null)- //No customer found with the specified id- return Content("No customer found with the specified id");- if (ModelState.IsValid)- {- await _customerViewModelService.DeleteAddress(customer, address);- return new JsonResult("");- }-- return ErrorForKendoGridJson(ModelState);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> AddressCreate(string customerId)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- var model = new CustomerAddressModel();- await _customerViewModelService.PrepareAddressModel(model, null, customer, false);-- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> AddressCreate(CustomerAddressModel model)- {- var customer = await _customerService.GetCustomerById(model.CustomerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- if (ModelState.IsValid)- {- //custom address attributes- var customAttributes =- await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);- var address = await _customerViewModelService.InsertAddressModel(customer, model, customAttributes);- Success(_translationService.GetResource("Admin.Customers.Customers.Addresses.Added"));- return RedirectToAction("AddressEdit", new { addressId = address.Id, customerId = model.CustomerId });- }-- //If we got this far, something failed, redisplay form- await _customerViewModelService.PrepareAddressModel(model, null, customer, true);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> AddressEdit(string addressId, string customerId)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- var address = customer.Addresses.FirstOrDefault(x => x.Id == addressId);- if (address == null)- //No address found with the specified id- return RedirectToAction("Edit", new { id = customer.Id });-- var model = new CustomerAddressModel();- await _customerViewModelService.PrepareAddressModel(model, address, customer, false);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> AddressEdit(CustomerAddressModel model)- {- var customer = await _customerService.GetCustomerById(model.CustomerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- //No customer found with the specified id- return RedirectToAction("List");-- var address = customer.Addresses.FirstOrDefault(x => x.Id == model.Address.Id);- if (address == null)- //No address found with the specified id- return RedirectToAction("Edit", new { id = customer.Id });-- if (ModelState.IsValid)- {- //custom address attributes- var customAttributes =- await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);- address = await _customerViewModelService.UpdateAddressModel(customer, address, model, customAttributes);- Success(_translationService.GetResource("Admin.Customers.Customers.Addresses.Updated"));- return RedirectToAction("AddressEdit", new { addressId = model.Address.Id, customerId = model.CustomerId });- }-- //If we got this far, something failed, redisplay form- await _customerViewModelService.PrepareAddressModel(model, address, customer, true);-- return View(model);- }-- #endregion-- #region Orders-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> OrderList(string customerId, DataSourceRequest command,- [FromServices] IOrderViewModelService orderViewModelService)- {- if (!await _permissionService.Authorize(StandardPermission.ManageOrders))- return Json(new DataSourceResult {- Data = null,- Total = 0- });-- var model = new OrderListModel {- CustomerId = customerId- };-- var (orderModels, totalCount) =- await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = orderModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> OrderDetails(string orderId,- [FromServices] IOrderService orderService, [FromServices] IOrderViewModelService orderViewModelService)- {- if (!await _permissionService.Authorize(StandardPermission.ManageOrders))- return Json(new DataSourceResult {- Data = null,- Total = 0- });-- var order = await orderService.GetOrderById(orderId);- if (order == null)- throw new ArgumentException("No order found with the specified id");-- var ordermodel = new OrderModel();- await orderViewModelService.PrepareOrderDetailsModel(ordermodel, order);- var gridModel = new DataSourceResult {- Data = ordermodel.Items,- Total = ordermodel.Items.Count- };-- return Json(gridModel);- }-- #endregion-- #region Reviews-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> ReviewList(string customerId, DataSourceRequest command)- {- var productReviews = await _productReviewService.GetAllProductReviews(customerId, null,- null, null, "", null, "", command.Page - 1, command.PageSize);- var items = new List<ProductReviewModel>();- foreach (var x in productReviews)- {- var m = new ProductReviewModel();- await _productViewModelService.PrepareProductReviewModel(m, x, false, true);- items.Add(m);- }-- var gridModel = new DataSourceResult {- Data = items,- Total = productReviews.TotalCount- };- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ReviewDelete(string id)- {- var productReview = await _productReviewService.GetProductReviewById(id);- if (productReview == null)- throw new ArgumentException("No review found with the specified id", nameof(id));-- await _productReviewViewModelService.DeleteProductReview(productReview);- return new JsonResult("");- }-- #endregion-- #region Current shopping cart/ wishlist-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> GetCartList(string customerId, int cartTypeId)- {- var cart = await _customerViewModelService.PrepareShoppingCartItemModel(customerId, cartTypeId);- var gridModel = new DataSourceResult {- Data = cart,- Total = cart.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> UpdateCart(string id, string customerId, double? unitPriceValue)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- var warnings = await _customerViewModelService.UpdateCart(customer, id, unitPriceValue);- if (warnings.Any())- return ErrorForKendoGridJson(string.Join(",", warnings));-- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> DeleteCart(string id, string customerId)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- await _customerViewModelService.DeleteCart(customer, id);-- return new JsonResult("");- }-- #endregion-- #region Customer Product Personalize / Price-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> ProductsPrice(DataSourceRequest command, string customerId)- {- var (productPriceModels, totalCount) =- await _customerViewModelService.PrepareProductPriceModel(customerId, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = productPriceModels.ToList(),- Total = totalCount- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> PersonalizedProducts(DataSourceRequest command, string customerId)- {- var (productModels, totalCount) =- await _customerViewModelService.PreparePersonalizedProducts(customerId, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = productModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> ProductAddPopup(string customerId)- {- var model = await _customerViewModelService.PrepareCustomerModelAddProductModel();- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command, CustomerModel.AddProductModel model)- {- var products = await _customerViewModelService.PrepareProductModel(model, command.Page, command.PageSize);-- var gridModel = new DataSourceResult {- Data = products.products.ToList(),- Total = products.totalCount- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ProductAddPopup(string customerId, bool personalized,- CustomerModel.AddProductModel model)- {- if (model.SelectedProductIds != null)- await _customerViewModelService.InsertCustomerAddProductModel(customerId, personalized, model);- return Content("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> UpdateProductPrice(CustomerModel.ProductPriceModel model)- {- await _customerViewModelService.UpdateProductPrice(model);- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> DeleteProductPrice(string id)- {- await _customerViewModelService.DeleteProductPrice(id);- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> UpdatePersonalizedProduct(CustomerModel.ProductModel model)- {- await _customerViewModelService.UpdatePersonalizedProduct(model);- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> DeletePersonalizedProduct(string id)- {- await _customerViewModelService.DeletePersonalizedProduct(id);- return new JsonResult("");- }-- #endregion-- #region Customer note-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> CustomerNotesSelect(string customerId, DataSourceRequest command)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id");-- var customerNoteModels = await _customerViewModelService.PrepareCustomerNoteList(customerId);- var gridModel = new DataSourceResult {- Data = customerNoteModels,- Total = customerNoteModels.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> CustomerNoteAdd(string customerId, string downloadId, bool displayToCustomer,- string title, string message)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- return Json(new { Result = false });-- await _customerViewModelService.InsertCustomerNote(customerId, downloadId, displayToCustomer, title, message);-- return Json(new { Result = true });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> CustomerNoteDelete(string id, string customerId)- {- var customer = await _customerService.GetCustomerById(customerId);- if (customer == null || customer.Deleted || await CheckSalesManager(customer))- throw new ArgumentException("No customer found with the specified id");-- await _customerViewModelService.DeleteCustomerNote(id, customerId);-- return new JsonResult("");- }-- #endregion-- #region Export-- [PermissionAuthorizeAction(PermissionActionName.Export)]- [HttpPost]- public async Task<IActionResult> ExportExcelAll(CustomerListModel model)- {- var salesEmployeeId =- await _groupService.IsSalesManager(_contextAccessor.WorkContext.CurrentCustomer) ? _contextAccessor.WorkContext.CurrentCustomer.SeId : "";-- var customers = await _customerService.GetAllCustomers(- customerGroupIds: model.SearchCustomerGroupIds.ToArray(),- salesEmployeeId: salesEmployeeId,- email: model.SearchEmail,- username: model.SearchUsername,- firstName: model.SearchFirstName,- lastName: model.SearchLastName,- company: model.SearchCompany,- phone: model.SearchPhone,- zipPostalCode: model.SearchZipPostalCode,- loadOnlyWithShoppingCart: false);-- try- {- var bytes = await _exportManager.Export(customers);- return File(bytes, "text/xls", "customers.xlsx");- }- catch (Exception exc)- {- Error(exc);- return RedirectToAction("List");- }- }-- [PermissionAuthorizeAction(PermissionActionName.Export)]- [HttpPost]- public async Task<IActionResult> ExportExcelSelected(string selectedIds)- {- var customers = new List<Customer>();- if (selectedIds != null)- {- var ids = selectedIds- .Split([','], StringSplitOptions.RemoveEmptyEntries)- .Select(x => x)- .ToArray();- customers.AddRange(await _customerService.GetCustomersByIds(ids));- }-- var bytes = await _exportManager.Export(customers);- return File(bytes, "text/xls", "customers.xlsx");- }-- #endregion-}\ No newline at end of file+[AuthorizeAdmin]+[AutoValidateAntiforgeryToken]+[Area(Constants.AreaAdmin)]+[AuthorizeMenu]+public class CustomerController(+ Grand.Business.Core.Interfaces.Customers.ICustomerService customerService,+ Grand.Web.AdminShared.Interfaces.ICustomerViewModelService customerViewModelService,+ Grand.Business.Core.Interfaces.Customers.ICustomerManagerService customerManagerService,+ Grand.Business.Core.Interfaces.Marketing.Customers.ICustomerProductService customerProductService,+ Grand.Business.Core.Interfaces.Catalog.Products.IProductReviewService productReviewService,+ Grand.Web.AdminShared.Interfaces.IProductReviewViewModelService productReviewViewModelService,+ Grand.Web.AdminShared.Interfaces.IProductViewModelService productViewModelService,+ Grand.Business.Core.Interfaces.Customers.ICustomerAttributeParser customerAttributeParser,+ Grand.Business.Core.Interfaces.Customers.ICustomerAttributeService customerAttributeService,+ Grand.Business.Core.Interfaces.Common.Addresses.IAddressAttributeParser addressAttributeParser,+ Grand.Business.Core.Interfaces.Common.Addresses.IAddressAttributeService addressAttributeService,+ Grand.Business.Core.Interfaces.Messages.IMessageProviderService messageProviderService,+ Grand.Business.Core.Interfaces.Common.Directory.IGroupService groupService,+ Grand.Business.Core.Interfaces.Common.Localization.ITranslationService translationService,+ Grand.Infrastructure.IContextAccessor contextAccessor,+ Grand.Domain.Customers.CustomerSettings customerSettings,+ Grand.Web.AdminShared.Interfaces.IAdminDataScope<Grand.Domain.Customers.Customer> scope,+ Grand.Business.Core.Interfaces.Common.Security.IPermissionService permissionService,+ Grand.Business.Core.Interfaces.ExportImport.IExportManager<Grand.Domain.Customers.Customer> exportManager)+ : BaseCustomerManagementController(customerService, customerViewModelService, customerManagerService,+ customerProductService, productReviewService, productReviewViewModelService, productViewModelService,+ customerAttributeParser, customerAttributeService, addressAttributeParser, addressAttributeService,+ messageProviderService, groupService, translationService, contextAccessor, customerSettings, scope,+ permissionService, exportManager);diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseCustomerController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseCustomerController.csnew file mode 100644index 000000000..e3d1b2106--- /dev/null+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseCustomerController.cs@@ -0,0 +1,857 @@+#nullable enable++using Grand.Business.Core.Interfaces.Catalog.Products;+using Grand.Business.Core.Interfaces.Common.Addresses;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.Marketing.Customers;+using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Utilities.Customers;+using Grand.Domain.Catalog;+using Grand.Domain.Common;+using Grand.Domain.Customers;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Web.AdminShared.Extensions;+using Grand.Web.AdminShared.Interfaces;+using Grand.Web.AdminShared.Models.Customers;+using Grand.Web.Common.Controllers;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Filters;+using Grand.Web.Common.Models;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;++namespace Grand.Web.AdminShared.Controllers;++[PermissionAuthorize(PermissionSystemName.Customers)]+[AutoValidateAntiforgeryToken]+public abstract class BaseCustomerController(+ ICustomerService customerService,+ ICustomerViewModelService customerViewModelService,+ ICustomerManagerService customerManagerService,+ ICustomerProductService customerProductService,+ IProductReviewService productReviewService,+ IProductReviewViewModelService productReviewViewModelService,+ IProductViewModelService productViewModelService,+ ICustomerAttributeParser customerAttributeParser,+ ICustomerAttributeService customerAttributeService,+ IAddressAttributeParser addressAttributeParser,+ IAddressAttributeService addressAttributeService,+ IMessageProviderService messageProviderService,+ IGroupService groupService,+ ITranslationService translationService,+ IContextAccessor contextAccessor,+ CustomerSettings customerSettings,+ IAdminDataScope<Customer> scope)+ : BaseController+{+ // Exposed for BaseCustomerManagementController (primary-constructor parameters aren't visible+ // to derived classes by name in C#).+ protected ICustomerService CustomerService => customerService;+ protected ICustomerViewModelService CustomerViewModelService => customerViewModelService;+ protected ICustomerManagerService CustomerManagerService => customerManagerService;+ protected ICustomerProductService CustomerProductService => customerProductService;+ protected IProductReviewService ProductReviewService => productReviewService;+ protected IProductReviewViewModelService ProductReviewViewModelService => productReviewViewModelService;+ protected IProductViewModelService ProductViewModelService => productViewModelService;+ protected ICustomerAttributeParser CustomerAttributeParser => customerAttributeParser;+ protected ICustomerAttributeService CustomerAttributeService => customerAttributeService;+ protected IAddressAttributeParser AddressAttributeParser => addressAttributeParser;+ protected IAddressAttributeService AddressAttributeService => addressAttributeService;+ protected IMessageProviderService MessageProviderService => messageProviderService;+ protected IGroupService GroupService => groupService;+ protected ITranslationService TranslationService => translationService;+ protected IContextAccessor ContextAccessor => contextAccessor;+ protected CustomerSettings CustomerSettings => customerSettings;+ protected IAdminDataScope<Customer> Scope => scope;++ /// <summary>Store-only: forces StoreId/blanks Owner/VendorId/StaffStoreId/SeId/CustomerGroups+ /// on the posted model, ported from Store's original ApplyStoreConstraints. No-op for Admin+ /// (BaseCustomerManagementController never overrides this — Admin never had this method).</summary>+ protected virtual Task ApplyPostConstraints(CustomerModel model) => Task.CompletedTask;++ /// <summary>Admin-only: warns when a submitted model newly enables two-factor auth. No-op here+ /// — Store's originals never referenced TwoFactorEnabled at all. existingCustomer is null on+ /// Create, which collapses to Admin's original simpler create-time condition automatically.</summary>+ protected virtual void CheckTwoFactorEnabledWarning(Customer? existingCustomer, CustomerModel model)+ {+ }++ protected virtual async Task<IList<CustomAttribute>> ParseCustomCustomerAttributes(+ IList<CustomAttributeModel> model)+ {+ ArgumentNullException.ThrowIfNull(model);++ var customAttributes = new List<CustomAttribute>();+ var customerAttributes = await customerAttributeService.GetAllCustomerAttributes();+ foreach (var attribute in customerAttributes)+ {+ switch (attribute.AttributeControlTypeId)+ {+ case AttributeControlType.DropdownList:+ case AttributeControlType.RadioList:+ {+ var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customAttributes = customerAttributeParser+ .AddCustomerAttribute(customAttributes, attribute, ctrlAttributes).ToList();+ }+ break;+ case AttributeControlType.Checkboxes:+ {+ var cblAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(cblAttributes))+ foreach (var item in cblAttributes.Split(',').Where(x => !string.IsNullOrEmpty(x)))+ customAttributes = customerAttributeParser+ .AddCustomerAttribute(customAttributes, attribute, item).ToList();+ }+ break;+ case AttributeControlType.ReadonlyCheckboxes:+ {+ foreach (var selectedAttributeId in attribute.CustomerAttributeValues+ .Where(v => v.IsPreSelected).Select(v => v.Id).ToList())+ customAttributes = customerAttributeParser+ .AddCustomerAttribute(customAttributes, attribute, selectedAttributeId).ToList();+ }+ break;+ case AttributeControlType.TextBox:+ case AttributeControlType.MultilineTextbox:+ {+ var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customAttributes = customerAttributeParser+ .AddCustomerAttribute(customAttributes, attribute, ctrlAttributes.Trim()).ToList();+ }+ break;+ default:+ break;+ }+ }++ return customAttributes;+ }++ #region Customers++ public IActionResult Index() => RedirectToAction("List");++ [PermissionAuthorizeAction(PermissionActionName.List)]+ public async Task<IActionResult> List()+ {+ // Fix: unconditionally call the shared, fully-populated PrepareCustomerListModel() for+ // BOTH hosts. Store's original bypassed this (`new CustomerListModel()`), silently leaving+ // UsernamesEnabled/CompanyEnabled/PhoneEnabled/ZipPostalCodeEnabled false regardless of+ // CustomerSettings, hiding those 4 optional grid columns even when configured on. Store's+ // view never reads AvailableCustomerGroups/AvailableCustomerTags, so computing them for+ // Store too is harmless, not a correctness requirement — see spec "List() model gap".+ var model = await customerViewModelService.PrepareCustomerListModel();+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.List)]+ [HttpPost]+ public async Task<IActionResult> CustomerList(DataSourceRequest command, CustomerListModel model,+ string[] searchCustomerGroupIds, string[] searchCustomerTagIds)+ {+ var groupIds = searchCustomerGroupIds;+ string[]? tagIds = searchCustomerTagIds;+ if (scope.DefaultStoreId is not null)+ {+ // Store panel always restricts to the Registered group regardless of what was+ // submitted — ports Store's original hardcoded registered-only CustomerList.+ var registered = await groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered);+ groupIds = registered != null ? new[] { registered.Id } : Array.Empty<string>();+ tagIds = null;+ }++ var (customerModelList, totalCount) = await customerViewModelService.PrepareCustomerList(model,+ groupIds, tagIds, command.Page, command.PageSize, scope.DefaultStoreId ?? "");+ var gridModel = new DataSourceResult {+ Data = customerModelList.ToList(),+ Total = totalCount+ };++ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Create)]+ public async Task<IActionResult> Create()+ {+ var model = new CustomerModel();+ await customerViewModelService.PrepareCustomerModel(model, null, false);+ await ApplyPostConstraints(model);+ model.Active = true;+ return View(model);+ }++ // Disclosed bug fix, same class as GiftVoucher's: Admin's pre-consolidation Create(POST)+ // required PermissionActionName.Edit while everything else on Create required .Create — Store's+ // original already used .Create. Harmonized on .Create here (matches every other Base*Controller+ // in AdminShared). See CustomerControllerAttributeTests.CreatePost_RequiresCreatePermission.+ [PermissionAuthorizeAction(PermissionActionName.Create)]+ [HttpPost]+ [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]+ public async Task<IActionResult> Create(CustomerModel model, bool continueEditing)+ {+ await ApplyPostConstraints(model);+ CheckTwoFactorEnabledWarning(null, model);++ if (ModelState.IsValid)+ {+ model.Attributes = await ParseCustomCustomerAttributes(model.SelectedAttributes);+ var customer = await customerViewModelService.InsertCustomerModel(model);++ if (!string.IsNullOrWhiteSpace(model.Password))+ {+ var changePassRequest = new ChangePasswordRequest(model.Email,+ customerSettings.DefaultPasswordFormat, model.Password);+ await customerManagerService.ChangePassword(changePassRequest, customer.StoreId);+ }++ Success(translationService.GetResource("Admin.Customers.Customers.Added"));+ return continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List");+ }++ await customerViewModelService.PrepareCustomerModel(model, null, true);+ await ApplyPostConstraints(model);+ return View(model);+ }++ #endregion++ /// <summary>DRY replacement for the repeated "load customer, redirect to List if not found or+ /// not authorized" pattern in both original controllers — every action in both files redirects+ /// to "List", never "Edit", on either condition.</summary>+ protected async Task<(Customer? customer, IActionResult? denied)> LoadAuthorizedCustomer(string id)+ {+ var customer = await customerService.GetCustomerById(id);+ if (customer == null) return (null, RedirectToAction("List"));+ if (!await scope.HasAccess(customer)) return (null, RedirectToAction("List"));+ return (customer, null);+ }++ #region Edit / Delete++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ public async Task<IActionResult> Edit(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ var model = new CustomerModel();+ await customerViewModelService.PrepareCustomerModel(model, customer, false);+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]+ public async Task<IActionResult> Edit(CustomerModel model, bool continueEditing)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(model.Id);+ if (customer is null) return denied!;++ await ApplyPostConstraints(model);+ CheckTwoFactorEnabledWarning(customer, model);++ if (ModelState.IsValid)+ try+ {+ model.Attributes = await ParseCustomCustomerAttributes(model.SelectedAttributes);+ customer = await customerViewModelService.UpdateCustomerModel(customer, model);++ if (!string.IsNullOrWhiteSpace(model.Password))+ {+ var changePassRequest = new ChangePasswordRequest(model.Email,+ customerSettings.DefaultPasswordFormat, model.Password);+ await customerManagerService.ChangePassword(changePassRequest, customer.StoreId);+ }++ Success(translationService.GetResource("Admin.Customers.Customers.Updated"));+ if (continueEditing)+ {+ await SaveSelectedTabIndex();+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ return RedirectToAction("List");+ }+ catch (Exception exc)+ {+ Error(exc.Message);+ }++ await customerViewModelService.PrepareCustomerModel(model, customer, true);+ await ApplyPostConstraints(model);+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Delete)]+ [HttpPost]+ public async Task<IActionResult> Delete(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ if (customer.Id == contextAccessor.WorkContext.CurrentCustomer.Id)+ {+ Error(translationService.GetResource("Admin.Customers.Customers.NoSelfDelete"));+ return RedirectToAction("List");+ }++ try+ {+ if (ModelState.IsValid)+ {+ await customerViewModelService.DeleteCustomer(customer);+ Success(translationService.GetResource("Admin.Customers.Customers.Deleted"));+ return RedirectToAction("List");+ }++ Error(ModelState);+ return RedirectToAction("Edit", new { id = customer.Id });+ }+ catch (Exception exc)+ {+ Error(exc.Message);+ return RedirectToAction("Edit", new { id = customer.Id });+ }+ }++ #endregion++ #region Vat / Messages++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> MarkVatNumberAsValid(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ await customerService.UpdateUserField(customer, SystemCustomerFieldNames.VatNumberStatusId,+ (int)Grand.Domain.Tax.VatNumberStatus.Valid);+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> MarkVatNumberAsInvalid(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ await customerService.UpdateUserField(customer, SystemCustomerFieldNames.VatNumberStatusId,+ (int)Grand.Domain.Tax.VatNumberStatus.Invalid);+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> SendWelcomeMessage(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ await messageProviderService.SendCustomerWelcomeMessage(customer, contextAccessor.StoreContext.CurrentStore,+ contextAccessor.WorkContext.WorkingLanguage.Id);+ Success(translationService.GetResource("Admin.Customers.Customers.SendWelcomeMessage.Success"));+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> ReSendActivationMessage(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ await customerService.UpdateUserField(customer, SystemCustomerFieldNames.AccountActivationToken,+ Guid.NewGuid().ToString());+ await messageProviderService.SendCustomerEmailValidationMessage(customer,+ contextAccessor.StoreContext.CurrentStore, contextAccessor.WorkContext.WorkingLanguage.Id);+ Success(translationService.GetResource("Admin.Customers.Customers.ReSendActivationMessage.Success"));+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> SendEmail(CustomerModel.SendEmailModel model)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(model.Id);+ if (customer is null) return denied!;++ try+ {+ if (string.IsNullOrWhiteSpace(customer.Email))+ throw new Grand.SharedKernel.GrandException("Customer email is empty");+ if (!Grand.SharedKernel.Extensions.CommonHelper.IsValidEmail(customer.Email))+ throw new Grand.SharedKernel.GrandException("Customer email is not valid");+ if (string.IsNullOrWhiteSpace(model.Subject))+ throw new Grand.SharedKernel.GrandException("Email subject is empty");+ if (string.IsNullOrWhiteSpace(model.Body))+ throw new Grand.SharedKernel.GrandException("Email body is empty");++ await customerViewModelService.SendEmail(customer, model);+ Success(translationService.GetResource("Admin.Customers.Customers.SendEmail.Queued"));+ }+ catch (Exception exc)+ {+ Error(exc.Message);+ }++ return RedirectToAction("Edit", new { id = customer.Id });+ }++ #endregion++ #region Loyalty points history++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> LoyaltyPointsHistorySelect(string customerId)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) throw new ArgumentException("No customer found with the specified id");++ var model = (await customerViewModelService.PrepareLoyaltyPointsHistoryModel(customerId)).ToList();+ var gridModel = new DataSourceResult { Data = model, Total = model.Count };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> LoyaltyPointsHistoryAdd(string customerId, string storeId,+ int addLoyaltyPointsValue, string addLoyaltyPointsMessage)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) return Json(new { Result = false });++ // Store scope always forces its own StaffStoreId, ignoring the caller-supplied storeId —+ // ports the original controller's `CurrentStoreId` usage. Admin has no store concept here+ // and keeps using whatever the caller (its own store picker) submitted.+ var effectiveStoreId = scope.DefaultStoreId ?? storeId;++ await customerViewModelService.InsertLoyaltyPointsHistory(customer, effectiveStoreId,+ addLoyaltyPointsValue, addLoyaltyPointsMessage);+ return Json(new { Result = true });+ }++ #endregion++ #region Addresses++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> AddressesSelect(string customerId, DataSourceRequest command)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) throw new ArgumentException("No customer found with the specified id", nameof(customerId));++ var addresses = (await customerViewModelService.PrepareAddressModel(customer)).ToList();+ var gridModel = new DataSourceResult { Data = addresses, Total = addresses.Count };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> AddressDelete(string id, string customerId)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) throw new ArgumentException("No customer found with the specified id", nameof(customerId));++ var address = customer.Addresses.FirstOrDefault(a => a.Id == id);+ if (address == null) return Content("No customer found with the specified id");+ if (ModelState.IsValid)+ {+ await customerViewModelService.DeleteAddress(customer, address);+ return new JsonResult("");+ }++ return ErrorForKendoGridJson(ModelState);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> AddressCreate(string customerId)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) return denied!;++ var model = new CustomerAddressModel();+ await customerViewModelService.PrepareAddressModel(model, null, customer, false);+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> AddressCreate(CustomerAddressModel model)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(model.CustomerId);+ if (customer is null) return denied!;++ if (ModelState.IsValid)+ {+ var customAttributes =+ await model.Address.ParseCustomAddressAttributes(addressAttributeParser, addressAttributeService);+ var address = await customerViewModelService.InsertAddressModel(customer, model, customAttributes);+ Success(translationService.GetResource("Admin.Customers.Customers.Addresses.Added"));+ return RedirectToAction("AddressEdit", new { addressId = address.Id, customerId = model.CustomerId });+ }++ await customerViewModelService.PrepareAddressModel(model, null, customer, true);+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> AddressEdit(string addressId, string customerId)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) return denied!;++ var address = customer.Addresses.FirstOrDefault(x => x.Id == addressId);+ if (address == null) return RedirectToAction("Edit", new { id = customer.Id });++ var model = new CustomerAddressModel();+ await customerViewModelService.PrepareAddressModel(model, address, customer, false);+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> AddressEdit(CustomerAddressModel model)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(model.CustomerId);+ if (customer is null) return denied!;++ var address = customer.Addresses.FirstOrDefault(x => x.Id == model.Address.Id);+ if (address == null) return RedirectToAction("Edit", new { id = customer.Id });++ if (ModelState.IsValid)+ {+ var customAttributes =+ await model.Address.ParseCustomAddressAttributes(addressAttributeParser, addressAttributeService);+ await customerViewModelService.UpdateAddressModel(customer, address, model, customAttributes);+ Success(translationService.GetResource("Admin.Customers.Customers.Addresses.Updated"));+ return RedirectToAction("AddressEdit", new { addressId = model.Address.Id, customerId = model.CustomerId });+ }++ await customerViewModelService.PrepareAddressModel(model, address, customer, true);+ return View(model);+ }++ #endregion++ #region Orders++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> OrderList(string customerId, DataSourceRequest command,+ [FromServices] Grand.Business.Core.Interfaces.Checkout.Orders.IOrderService orderService,+ [FromServices] Grand.Web.AdminShared.Interfaces.IOrderViewModelService orderViewModelService,+ [FromServices] IPermissionService permissionService)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new DataSourceResult { Data = null, Total = 0 });+ }+ else if (!await permissionService.Authorize(StandardPermission.ManageOrders))+ {+ return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var model = new Grand.Web.AdminShared.Models.Orders.OrderListModel {+ CustomerId = customerId, StoreId = scope.DefaultStoreId ?? ""+ };+ var (orderModels, totalCount) = await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);+ var gridModel = new DataSourceResult { Data = orderModels.ToList(), Total = totalCount };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> OrderDetails(string orderId,+ [FromServices] Grand.Business.Core.Interfaces.Checkout.Orders.IOrderService orderService,+ [FromServices] Grand.Web.AdminShared.Interfaces.IOrderViewModelService orderViewModelService,+ [FromServices] IPermissionService permissionService)+ {+ Grand.Domain.Orders.Order order;+ if (scope.DefaultStoreId is null)+ {+ if (!await permissionService.Authorize(StandardPermission.ManageOrders))+ return Json(new DataSourceResult { Data = null, Total = 0 });++ order = await orderService.GetOrderById(orderId);+ if (order == null) throw new ArgumentException("No order found with the specified id");+ }+ else+ {+ order = await orderService.GetOrderById(orderId);+ if (order == null || order.StoreId != scope.DefaultStoreId)+ return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var ordermodel = new Grand.Web.AdminShared.Models.Orders.OrderModel();+ await orderViewModelService.PrepareOrderDetailsModel(ordermodel, order);+ var gridModel = new DataSourceResult { Data = ordermodel.Items, Total = ordermodel.Items.Count };+ return Json(gridModel);+ }++ #endregion++ #region Reviews++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> ReviewList(string customerId, DataSourceRequest command)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var productReviews = await productReviewService.GetAllProductReviews(customerId, null,+ null, null, "", scope.DefaultStoreId, "", command.Page - 1, command.PageSize);+ var items = new List<Grand.Web.AdminShared.Models.Catalog.ProductReviewModel>();+ foreach (var x in productReviews)+ {+ var m = new Grand.Web.AdminShared.Models.Catalog.ProductReviewModel();+ await productViewModelService.PrepareProductReviewModel(m, x, false, true);+ items.Add(m);+ }++ var gridModel = new DataSourceResult { Data = items, Total = productReviews.TotalCount };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> ReviewDelete(string id)+ {+ var productReview = await productReviewService.GetProductReviewById(id);+ if (productReview == null) throw new ArgumentException("No review found with the specified id", nameof(id));+ if (scope.DefaultStoreId is not null && productReview.StoreId != scope.DefaultStoreId)+ throw new ArgumentException("No review found with the specified id", nameof(id));++ await productReviewViewModelService.DeleteProductReview(productReview);+ return new JsonResult("");+ }++ #endregion++ #region Current shopping cart / wishlist++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> GetCartList(string customerId, int cartTypeId)+ {+ // Admin's original never checked ownership here at all — preserved exactly, see task note.+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var cart = await customerViewModelService.PrepareShoppingCartItemModel(customerId, cartTypeId);+ var gridModel = new DataSourceResult { Data = cart, Total = cart.Count };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> UpdateCart(string id, string customerId, double? unitPriceValue)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) throw new ArgumentException("No customer found with the specified id", nameof(customerId));++ var warnings = await customerViewModelService.UpdateCart(customer, id, unitPriceValue);+ if (warnings.Any()) return ErrorForKendoGridJson(string.Join(",", warnings));+ return new JsonResult("");+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> DeleteCart(string id, string customerId)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(customerId);+ if (customer is null) throw new ArgumentException("No customer found with the specified id", nameof(customerId));++ await customerViewModelService.DeleteCart(customer, id);+ return new JsonResult("");+ }++ #endregion++ /// <summary>Non-redirecting ownership check for actions that soft-deny with an empty JSON+ /// result instead of a redirect (e.g. UpdateProductPrice/DeleteProductPrice).</summary>+ protected async Task<bool> HasAccessToCustomer(string customerId)+ {+ var customer = await customerService.GetCustomerById(customerId);+ return customer != null && await scope.HasAccess(customer);+ }++ #region Customer Product Personalize / Price++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> ProductsPrice(DataSourceRequest command, string customerId)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var (productPriceModels, totalCount) =+ await customerViewModelService.PrepareProductPriceModel(customerId, command.Page, command.PageSize);+ var gridModel = new DataSourceResult { Data = productPriceModels.ToList(), Total = totalCount };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> PersonalizedProducts(DataSourceRequest command, string customerId)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var (productModels, totalCount) =+ await customerViewModelService.PreparePersonalizedProducts(customerId, command.Page, command.PageSize);+ var gridModel = new DataSourceResult { Data = productModels.ToList(), Total = totalCount };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> ProductAddPopup(string customerId)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return denied;+ }++ var model = await customerViewModelService.PrepareCustomerModelAddProductModel();+ return View(model);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command, CustomerModel.AddProductModel model)+ {+ var products = await customerViewModelService.PrepareProductModel(model, command.Page, command.PageSize);+ var gridModel = new DataSourceResult { Data = products.products.ToList(), Total = products.totalCount };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> ProductAddPopup(string customerId, bool personalized,+ CustomerModel.AddProductModel model)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Content("");+ }++ if (model.SelectedProductIds != null)+ await customerViewModelService.InsertCustomerAddProductModel(customerId, personalized, model);+ return Content("");+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> UpdateProductPrice(CustomerModel.ProductPriceModel model)+ {+ if (scope.DefaultStoreId is not null)+ {+ var productPrice = await customerProductService.GetCustomerProductPriceById(model.Id);+ if (productPrice == null || !await HasAccessToCustomer(productPrice.CustomerId))+ return new JsonResult("");+ }++ await customerViewModelService.UpdateProductPrice(model);+ return new JsonResult("");+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> DeleteProductPrice(string id)+ {+ if (scope.DefaultStoreId is not null)+ {+ var productPrice = await customerProductService.GetCustomerProductPriceById(id);+ if (productPrice == null || !await HasAccessToCustomer(productPrice.CustomerId))+ return new JsonResult("");++ await customerProductService.DeleteCustomerProductPrice(productPrice);+ return new JsonResult("");+ }++ await customerViewModelService.DeleteProductPrice(id);+ return new JsonResult("");+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> UpdatePersonalizedProduct(CustomerModel.ProductModel model)+ {+ if (scope.DefaultStoreId is not null)+ {+ var customerProduct = await customerProductService.GetCustomerProduct(model.Id);+ if (customerProduct == null || !await HasAccessToCustomer(customerProduct.CustomerId))+ return new JsonResult("");+ }++ await customerViewModelService.UpdatePersonalizedProduct(model);+ return new JsonResult("");+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> DeletePersonalizedProduct(string id)+ {+ if (scope.DefaultStoreId is not null)+ {+ var customerProduct = await customerProductService.GetCustomerProduct(id);+ if (customerProduct == null || !await HasAccessToCustomer(customerProduct.CustomerId))+ return new JsonResult("");++ await customerProductService.DeleteCustomerProduct(customerProduct);+ return new JsonResult("");+ }++ // Admin's original convenience method, preserved for the global-scope branch (still present+ // on ICustomerViewModelService — no need to fall back to a two-step Get+Delete).+ await customerViewModelService.DeletePersonalizedProduct(id);+ return new JsonResult("");+ }++ #endregion++ #region Out of stock subscriptions++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> OutOfStockSubscriptionList(DataSourceRequest command, string customerId)+ {+ if (scope.DefaultStoreId is not null)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new DataSourceResult { Data = null, Total = 0 });+ }++ var (outOfStockSubscriptionModels, totalCount) =+ await customerViewModelService.PrepareOutOfStockSubscriptionModel(customerId, command.Page, command.PageSize);+ var gridModel = new DataSourceResult { Data = outOfStockSubscriptionModels.ToList(), Total = totalCount };+ return Json(gridModel);+ }++ #endregion+}diff --git a/src/Web/Grand.Web.AdminShared/Controllers/BaseCustomerManagementController.cs b/src/Web/Grand.Web.AdminShared/Controllers/BaseCustomerManagementController.csnew file mode 100644index 000000000..c82162ec4--- /dev/null+++ b/src/Web/Grand.Web.AdminShared/Controllers/BaseCustomerManagementController.cs@@ -0,0 +1,215 @@+#nullable enable++using Grand.Business.Core.Interfaces.Catalog.Products;+using Grand.Business.Core.Interfaces.Common.Addresses;+using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Business.Core.Interfaces.Common.Localization;+using Grand.Business.Core.Interfaces.Common.Security;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Interfaces.ExportImport;+using Grand.Business.Core.Interfaces.Marketing.Customers;+using Grand.Business.Core.Interfaces.Messages;+using Grand.Domain.Common;+using Grand.Domain.Customers;+using Grand.Domain.Permissions;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Web.AdminShared.Interfaces;+using Grand.Web.AdminShared.Models.Customers;+using Grand.Web.Common.DataSource;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;++namespace Grand.Web.AdminShared.Controllers;++/// <summary>+/// Admin-only Customer actions no other host has: Impersonate, RemoveAffiliate, DeleteSelected,+/// Export (All/Selected), CustomerNote (Select/Add/Delete), ContactFormList — plus the+/// TwoFactorEnabled warning on Create/Edit. Only Admin's concrete CustomerController inherits+/// this; Store's inherits <see cref="BaseCustomerController" /> directly (a genuine subset, same+/// shape as ARCH-001 Order's Vendor).+/// </summary>+public abstract class BaseCustomerManagementController(+ ICustomerService customerService,+ ICustomerViewModelService customerViewModelService,+ ICustomerManagerService customerManagerService,+ ICustomerProductService customerProductService,+ IProductReviewService productReviewService,+ IProductReviewViewModelService productReviewViewModelService,+ IProductViewModelService productViewModelService,+ ICustomerAttributeParser customerAttributeParser,+ ICustomerAttributeService customerAttributeService,+ IAddressAttributeParser addressAttributeParser,+ IAddressAttributeService addressAttributeService,+ IMessageProviderService messageProviderService,+ IGroupService groupService,+ ITranslationService translationService,+ IContextAccessor contextAccessor,+ CustomerSettings customerSettings,+ IAdminDataScope<Customer> scope,+ IPermissionService permissionService,+ IExportManager<Customer> exportManager)+ : BaseCustomerController(customerService, customerViewModelService, customerManagerService,+ customerProductService, productReviewService, productReviewViewModelService, productViewModelService,+ customerAttributeParser, customerAttributeService, addressAttributeParser, addressAttributeService,+ messageProviderService, groupService, translationService, contextAccessor, customerSettings, scope)+{+ protected override void CheckTwoFactorEnabledWarning(Customer? existingCustomer, CustomerModel model)+ {+ var wasEnabled = existingCustomer is not null &&+ existingCustomer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled);+ if (!wasEnabled && model.TwoFactorEnabled)+ Warning(TranslationService.GetResource("Admin.Customers.Customers.CannotTwoFactorEnabled"));+ }++ #region Message contact form++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> ContactFormList(DataSourceRequest command, string customerId)+ {+ var (contactFormModels, totalCount) =+ await CustomerViewModelService.PrepareContactFormModel(customerId, command.Page, command.PageSize);+ var gridModel = new DataSourceResult { Data = contactFormModels.ToList(), Total = totalCount };+ return Json(gridModel);+ }++ #endregion++ #region Impersonate / affiliate / bulk delete++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> Impersonate(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ if (!await permissionService.Authorize(StandardPermission.AllowCustomerImpersonation))+ {+ Error("User does not have permission for the impersonate session");+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ if (!await GroupService.IsAdmin(ContextAccessor.WorkContext.CurrentCustomer) && await GroupService.IsAdmin(customer))+ {+ Error("A non-admin user cannot impersonate as an administrator");+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ await CustomerService.UpdateUserField(ContextAccessor.WorkContext.CurrentCustomer,+ SystemCustomerFieldNames.ImpersonatedCustomerId, customer.Id);+ return RedirectToAction("Index", "Home", new { area = "" });+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> RemoveAffiliate(string id)+ {+ var (customer, denied) = await LoadAuthorizedCustomer(id);+ if (customer is null) return denied!;++ customer.AffiliateId = "";+ await CustomerService.UpdateCustomerField(customer.Id, x => x.AffiliateId, customer.AffiliateId);+ return RedirectToAction("Edit", new { id = customer.Id });+ }++ [PermissionAuthorizeAction(PermissionActionName.Delete)]+ [HttpPost]+ public async Task<IActionResult> DeleteSelected(ICollection<string> selectedIds)+ {+ if (selectedIds != null) await CustomerViewModelService.DeleteSelected(selectedIds.ToList());+ return Json(new { Result = true });+ }++ #endregion++ #region Customer note++ [PermissionAuthorizeAction(PermissionActionName.Preview)]+ [HttpPost]+ public async Task<IActionResult> CustomerNotesSelect(string customerId, DataSourceRequest command)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) throw new ArgumentException("No customer found with the specified id");++ var customerNoteModels = await CustomerViewModelService.PrepareCustomerNoteList(customerId);+ var gridModel = new DataSourceResult { Data = customerNoteModels, Total = customerNoteModels.Count };+ return Json(gridModel);+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ public async Task<IActionResult> CustomerNoteAdd(string customerId, string downloadId, bool displayToCustomer,+ string title, string message)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) return Json(new { Result = false });++ await CustomerViewModelService.InsertCustomerNote(customerId, downloadId, displayToCustomer, title, message);+ return Json(new { Result = true });+ }++ [PermissionAuthorizeAction(PermissionActionName.Edit)]+ [HttpPost]+ public async Task<IActionResult> CustomerNoteDelete(string id, string customerId)+ {+ var (_, denied) = await LoadAuthorizedCustomer(customerId);+ if (denied != null) throw new ArgumentException("No customer found with the specified id");++ await CustomerViewModelService.DeleteCustomerNote(id, customerId);+ return new JsonResult("");+ }++ #endregion++ #region Export++ [PermissionAuthorizeAction(PermissionActionName.Export)]+ [HttpPost]+ public async Task<IActionResult> ExportExcelAll(CustomerListModel model)+ {+ var salesEmployeeId = await GroupService.IsSalesManager(ContextAccessor.WorkContext.CurrentCustomer)+ ? ContextAccessor.WorkContext.CurrentCustomer.SeId+ : "";++ var customers = await CustomerService.GetAllCustomers(+ customerGroupIds: model.SearchCustomerGroupIds.ToArray(),+ salesEmployeeId: salesEmployeeId,+ email: model.SearchEmail,+ username: model.SearchUsername,+ firstName: model.SearchFirstName,+ lastName: model.SearchLastName,+ company: model.SearchCompany,+ phone: model.SearchPhone,+ zipPostalCode: model.SearchZipPostalCode,+ loadOnlyWithShoppingCart: false);++ try+ {+ var bytes = await exportManager.Export(customers);+ return File(bytes, "text/xls", "customers.xlsx");+ }+ catch (Exception exc)+ {+ Error(exc);+ return RedirectToAction("List");+ }+ }++ [PermissionAuthorizeAction(PermissionActionName.Export)]+ [HttpPost]+ public async Task<IActionResult> ExportExcelSelected(string selectedIds)+ {+ var customers = new List<Customer>();+ if (selectedIds != null)+ {+ var ids = selectedIds.Split([','], StringSplitOptions.RemoveEmptyEntries).ToArray();+ customers.AddRange(await CustomerService.GetCustomersByIds(ids));+ }++ var bytes = await exportManager.Export(customers);+ return File(bytes, "text/xls", "customers.xlsx");+ }++ #endregion+}diff --git a/src/Web/Grand.Web.AdminShared/Services/AdminCustomerDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/AdminCustomerDataScope.csnew file mode 100644index 000000000..2a04512e5--- /dev/null+++ b/src/Web/Grand.Web.AdminShared/Services/AdminCustomerDataScope.cs@@ -0,0 +1,34 @@+#nullable enable++using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Interfaces;++namespace Grand.Web.AdminShared.Services;++/// <summary>+/// Admin's <see cref="IAdminDataScope{Customer}" />. Deliberately NOT a no-op scope — Admin's+/// original CustomerController gates nearly every action through a Sales Manager check+/// (<c>groupService.IsSalesManager(CurrentCustomer) && CurrentCustomer.SeId !=+/// customer.SeId</c>, named <c>CheckSalesManager</c> in the original) that Store never had.+/// Same shape as ARCH-001 Order's <c>AdminOrderDataScope</c>. See Customer consolidation spec+/// "Scope classes".+/// </summary>+public class AdminCustomerDataScope(IContextAccessor contextAccessor, IGroupService groupService)+ : IAdminDataScope<Customer>+{+ public async Task<bool> HasAccess(Customer entity)+ {+ if (entity is null) return false;+ if (entity.Deleted) return false;+ var isSalesManager = await groupService.IsSalesManager(contextAccessor.WorkContext.CurrentCustomer);+ return !isSalesManager || contextAccessor.WorkContext.CurrentCustomer.SeId == entity.SeId;+ }++ public string? DefaultStoreId => null;+ public string ResourceKeyPrefix => "Admin";+ public bool ShowStoreSelector => true;+ public string? DefaultVendorId => null;+ public bool CanFeatureOnHomepage => true; // unused for Customer; required interface member+}diff --git a/src/Web/Grand.Web.AdminShared/Services/RoutedCustomerDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/RoutedCustomerDataScope.csnew file mode 100644index 000000000..a0bc45f23--- /dev/null+++ b/src/Web/Grand.Web.AdminShared/Services/RoutedCustomerDataScope.cs@@ -0,0 +1,51 @@+#nullable enable++using Grand.Domain.Customers;+using Grand.Web.AdminShared.Interfaces;+using Microsoft.AspNetCore.Http;++namespace Grand.Web.AdminShared.Services;++/// <summary>+/// Resolves the correct per-host <see cref="IAdminDataScope{Customer}" /> implementation at+/// request time, based on the current request's "area" route value — same fix and same reason+/// as <see cref="RoutedGiftVoucherDataScope" />: Grand.Web (the combined host) loads Admin and+/// Store together in one DI container, so a plain per-host registration would silently let+/// whichever host's StartupApplication ran last win for every area in that process.+///+/// No Vendor branch: Vendor has no CustomerController at all, so "Vendor" (or any other+/// unrecognized/missing area) fails closed. Explicitly forwards CanView rather than relying on+/// the interface default — the standing lesson from VendorReview's own RoutedOrderDataScope+/// gap (a routed scope that forwards HasAccess but not CanView silently reintroduces the+/// interface's HasAccess-only default even when a concrete scope overrides CanView).+/// </summary>+public class RoutedCustomerDataScope(+ IHttpContextAccessor httpContextAccessor,+ AdminCustomerDataScope adminScope,+ StoreCustomerDataScope storeScope) : IAdminDataScope<Customer>+{+ private IAdminDataScope<Customer> Resolved+ {+ get+ {+ var area = httpContextAccessor.HttpContext?.Request.RouteValues["area"] as string;+ return area switch {+ "Admin" => adminScope,+ "Store" => storeScope,+ //fail closed: this object fronts store tenant isolation and the Sales-Manager+ //restriction, so an unrecognized or missing area (including "Vendor" - Customer has+ //no Vendor screen) must never silently resolve to any concrete scope+ _ => throw new InvalidOperationException(+ $"RoutedCustomerDataScope: unrecognized or missing area '{area}'.")+ };+ }+ }++ public Task<bool> HasAccess(Customer entity) => Resolved.HasAccess(entity);+ public Task<bool> CanView(Customer entity) => Resolved.CanView(entity);+ public string? DefaultStoreId => Resolved.DefaultStoreId;+ public string ResourceKeyPrefix => Resolved.ResourceKeyPrefix;+ public bool ShowStoreSelector => Resolved.ShowStoreSelector;+ public string? DefaultVendorId => Resolved.DefaultVendorId;+ public bool CanFeatureOnHomepage => Resolved.CanFeatureOnHomepage;+}diff --git a/src/Web/Grand.Web.AdminShared/Services/StoreCustomerDataScope.cs b/src/Web/Grand.Web.AdminShared/Services/StoreCustomerDataScope.csnew file mode 100644index 000000000..1b0e4f07b--- /dev/null+++ b/src/Web/Grand.Web.AdminShared/Services/StoreCustomerDataScope.cs@@ -0,0 +1,35 @@+#nullable enable++using Grand.Business.Core.Interfaces.Common.Directory;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Web.AdminShared.Interfaces;++namespace Grand.Web.AdminShared.Services;++/// <summary>+/// Store's <see cref="IAdminDataScope{Customer}" />. Bespoke, not the generic+/// <see cref="StoreAdminDataScope{TEntity}" />: <c>Customer</c> is a plain <see cref="Grand.Domain.Common.BaseEntity" />+/// with a single <c>StoreId</c> field, not <c>IStoreLinkEntity</c>. Also folds in a business+/// rule with no parallel in any other ARCH-001 entity: the store panel may only manage+/// *registered* customers of its own store (ported from the original controller's+/// <c>GetStoreCustomer</c> helper) — not a scope concept, a deliberate UI/product restriction,+/// but it lives here because every original call site checked it in the same breath as+/// ownership.+/// </summary>+public class StoreCustomerDataScope(IContextAccessor contextAccessor, IGroupService groupService)+ : IAdminDataScope<Customer>+{+ public async Task<bool> HasAccess(Customer entity)+ {+ if (entity is null || entity.Deleted) return false;+ if (entity.StoreId != contextAccessor.WorkContext.CurrentCustomer.StaffStoreId) return false;+ return await groupService.IsRegistered(entity);+ }++ public string? DefaultStoreId => contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;+ public string ResourceKeyPrefix => "Admin";+ public bool ShowStoreSelector => true;+ 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.csindex 840270dbb..4651040ed 100644--- a/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs+++ b/src/Web/Grand.Web.AdminShared/Startup/StartupApplication.cs@@ -158,6 +158,13 @@ public class StartupApplication : IStartupApplicationservices.AddScoped<StoreMessageTemplateDataScope>();services.AddScoped<IAdminDataScope<MessageTemplate>, RoutedMessageTemplateDataScope>();+ // IAdminDataScope<Customer>: two bespoke implementations, neither reusing+ // GlobalAdminDataScope<T>/StoreAdminDataScope<T> — see AdminCustomerDataScope/+ // StoreCustomerDataScope doc comments. No Vendor scope: Customer has no Vendor screen.+ services.AddScoped<AdminCustomerDataScope>();+ services.AddScoped<StoreCustomerDataScope>();+ services.AddScoped<IAdminDataScope<Customer>, RoutedCustomerDataScope>();+// 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 nodiff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabAddresses.cshtmlsimilarity index 80%rename from src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabAddresses.cshtmlindex c7832a8de..fc4bd39a0 100644--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml@@ -1,12 +1,17 @@@model CustomerModel@inject AdminAreaSettings adminAreaSettings+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}<div class="panel panel-default">+ <partial name="Partials/WidgetZone.AddressesTop" model="Model"/><div class="panel-body"><div id="customer-addresses-grid"></div></div><div class="panel-footer">- <button type="button" class="k-button" onclick="location.href='@Url.Action("AddressCreate", new { customerId = Model.Id, area = Constants.AreaStore })'"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.Addresses.AddButton"]</button>+ <button type="button" class="k-button" onclick="location.href='@Url.Action("AddressCreate", new { customerId = Model.Id, area = area })'"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.Addresses.AddButton"]</button></div>+ <partial name="Partials/WidgetZone.AddressesBottom" model="Model"/></div><script>@@ -15,13 +20,13 @@ $(document).ready(function () {dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("AddressesSelect", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",+ url: "@Html.Raw(Url.Action("AddressesSelect", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},destroy: {- url: "@Html.Raw(Url.Action("AddressDelete", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",+ url: "@Html.Raw(Url.Action("AddressDelete", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -37,6 +42,7 @@ $(document).ready(function () {},error: function(e) {display_kendoui_grid_error(e);+ // Cancel the changesthis.cancelChanges();},pageSize: @(adminAreaSettings.DefaultGridPageSize),@@ -72,7 +78,7 @@ $(document).ready(function () {field: "Id",title: "@Loc["Admin.Common.Edit"]",width: 100,- template: '<a class="k-button" href="@Url.Action("AddressEdit", "Customer", new { area = Constants.AreaStore })[email protected]&addressid=#=Id#"><span class="k-icon k-i-edit"></span> @Loc["Admin.Common.Edit"]</a>'+ template: '<a class="k-button" href="@Url.Action("AddressEdit", "Customer", new { area = area })[email protected]&addressid=#=Id#"><span class="k-icon k-i-edit"></span> @Loc["Admin.Common.Edit"]</a>'}, {command: { name: "destroy", text: "@Loc["Admin.Common.Delete"]" },title: "@Loc["Admin.Common.Delete"]",diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtmlsimilarity index 88%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtmlindex d12cf93fe..bd51bce61 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtml@@ -1,15 +1,19 @@-@model CustomerModel+@using Grand.Domain.Orders+@model CustomerModel@inject AdminAreaSettings adminAreaSettings+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}<div class="panel panel-default"><div class="panel-heading">@Loc["Admin.Customers.Customers.CurrentShoppingCart"]</div>- <vc:admin-widget widget-zone="customer_details_shopping_cart_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ShoppingCartTop" model="Model"/><div class="panel-body"><div id="currentshoppingcart-grid"></div></div>- <vc:admin-widget widget-zone="customer_details_shopping_cart_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ShoppingCartBottom" model="Model"/></div><script>@@ -18,19 +22,19 @@ $(document).ready(function () {dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("GetCartList", "Customer", new { customerId = Model.Id, cartTypeId = (int)ShoppingCartType.ShoppingCart, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("GetCartList", "Customer", new { customerId = Model.Id, cartTypeId = (int)ShoppingCartType.ShoppingCart, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},update: {- url: "@Html.Raw(Url.Action("UpdateCart", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("UpdateCart", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},destroy: {- url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -84,7 +88,7 @@ $(document).ready(function () {field: "ProductName",title: "@Loc["Admin.CurrentCarts.Product"]",width:500,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#">#:kendo.htmlEncode(ProductName)#</a>' ++ template: '<a href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#">#:kendo.htmlEncode(ProductName)#</a>' +'# if(AttributeInfo && AttributeInfo.length > 0) {# <br />#=AttributeInfo# #} #'}, {field: "Quantity",@@ -108,7 +112,7 @@ $(document).ready(function () {title: "@Loc["Admin.CurrentCarts.Total"]",width:200},- @if (!adminAreaSettings.HideStoreColumn)+ @if (area == "Admin" && !adminAreaSettings.HideStoreColumn){<text>{@@ -137,13 +141,13 @@ $(document).ready(function () {var dataItem = grid.dataSource.get(id);var tokenInput = $('input[name=__RequestVerificationToken]');$.ajax({- url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",data: {id: dataItem.Id,customerId: "@Model.Id",__RequestVerificationToken: tokenInput.val(),- },+ },success: function () {grid.dataSource.remove(dataItem);grid.dataSource.sync();@@ -154,4 +158,4 @@ $(document).ready(function () {});}-</script>\ No newline at end of file+</script>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtmlsimilarity index 87%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtmlindex 682587ed5..bc596eada 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtml@@ -1,14 +1,18 @@-@model CustomerModel+@using Grand.Domain.Orders+@model CustomerModel@inject AdminAreaSettings adminAreaSettings+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}<div class="panel panel-default"><div class="panel-heading">@Loc["Admin.Customers.Customers.CurrentWishlist"]</div><div class="panel-body">- <vc:admin-widget widget-zone="customer_details_wishlist_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.WishlistTop" model="Model"/><div id="currentwishlist-grid"></div>- <vc:admin-widget widget-zone="customer_details_wishlist_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.WishlistBottom" model="Model"/></div></div><script>@@ -17,13 +21,13 @@ $(document).ready(function () {dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("GetCartList", "Customer", new { customerId = Model.Id, cartTypeId = (int)ShoppingCartType.Wishlist, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("GetCartList", "Customer", new { customerId = Model.Id, cartTypeId = (int)ShoppingCartType.Wishlist, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},destroy: {- url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -70,7 +74,7 @@ $(document).ready(function () {field: "ProductName",title: "@Loc["Admin.CurrentCarts.Product"]",width:500,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#">#:kendo.htmlEncode(ProductName)#</a>' ++ template: '<a href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#">#:kendo.htmlEncode(ProductName)#</a>' +'# if(AttributeInfo && AttributeInfo.length > 0) {# <br />#=AttributeInfo# #} #'}, {field: "Quantity",@@ -85,7 +89,7 @@ $(document).ready(function () {title: "@Loc["Admin.CurrentCarts.Total"]",width:200},- @if (!adminAreaSettings.HideStoreColumn)+ @if (area == "Admin" && !adminAreaSettings.HideStoreColumn){<text>{@@ -111,4 +115,4 @@ $(document).ready(function () {}]});});-</script>\ No newline at end of file+</script>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabInfo.cshtmlsimilarity index 86%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabInfo.cshtmlindex 2df010e46..d7cabc1fc 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabInfo.cshtml@@ -1,5 +1,10 @@-@model CustomerModel+@using Grand.Domain.Customers+@model CustomerModel+@inject IAdminDataScope<Customer> Scope+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}@if (Model.CountryEnabled && Model.StateProvinceEnabled){<script>@@ -16,7 +21,7 @@$.ajax({cache: false,type: "GET",- url: "@(Url.Action("GetStatesByCountryId", "Home", new { area = Constants.AreaAdmin }))",+ url: "@(Url.Action("GetStatesByCountryId", "Home", new { area = area }))",data: postData,success: function(data) {ddlStates.html('');@@ -33,7 +38,7 @@</script>}<div class="form-horizontal">-<vc:admin-widget widget-zone="customer_details_info_top" additional-data="Model"/>+<partial name="Partials/WidgetZone.InfoTop" model="Model"/><div class="form-body">@if (Model.UsernamesEnabled){@@ -76,23 +81,26 @@</div></div></div>-<div class="form-group">- @{- ViewData["DisableIgnoreAclWarnings"] = true;- }- <admin-label asp-for="CustomerGroups"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="CustomerGroups"/>- <span asp-validation-for="CustomerGroups"></span>+@if (Scope.DefaultStoreId is null)+{+ <div class="form-group">+ @{+ ViewData["DisableIgnoreAclWarnings"] = true;+ }+ <admin-label asp-for="CustomerGroups"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="CustomerGroups"/>+ <span asp-validation-for="CustomerGroups"></span>+ </div></div>-</div>-<div class="form-group">- <admin-label asp-for="CustomerTags"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="CustomerTags"/>- <span asp-validation-for="CustomerTags"></span>+ <div class="form-group">+ <admin-label asp-for="CustomerTags"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="CustomerTags"/>+ <span asp-validation-for="CustomerTags"></span>+ </div></div>-</div>+}@if (!string.IsNullOrEmpty(Model.Id) && Model.AssociatedExternalAuthRecords.Count > 0){<div class="form-group">@@ -168,42 +176,45 @@</div></div>}-<div class="form-group">- <admin-label asp-for="VendorId"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="VendorId"/>- <span asp-validation-for="VendorId"></span>- <em>@Loc["Admin.Customers.Customers.VendorShouldBeInVendorsGroup"]</em>+@if (Scope.DefaultStoreId is null)+{+ <div class="form-group">+ <admin-label asp-for="VendorId"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="VendorId"/>+ <span asp-validation-for="VendorId"></span>+ <em>@Loc["Admin.Customers.Customers.VendorShouldBeInVendorsGroup"]</em>+ </div></div>-</div>-<div class="form-group">- <admin-label asp-for="StaffStoreId"/>- <div class="col-md-9 col-sm-9">- <admin-select asp-for="StaffStoreId" asp-items="Model.AvailableStores"/>- <span asp-validation-for="StaffStoreId"></span>+ <div class="form-group">+ <admin-label asp-for="StaffStoreId"/>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="StaffStoreId" asp-items="Model.AvailableStores"/>+ <span asp-validation-for="StaffStoreId"></span>+ </div></div>-</div>-<div class="form-group">- <admin-label asp-for="StoreId"/>- <div class="col-md-9 col-sm-9">- <admin-select asp-for="StoreId" asp-items="Model.AvailableStores"/>- <span asp-validation-for="StoreId"></span>+ <div class="form-group">+ <admin-label asp-for="StoreId"/>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="StoreId" asp-items="Model.AvailableStores"/>+ <span asp-validation-for="StoreId"></span>+ </div></div>-</div>-<div class="form-group">- <admin-label asp-for="Owner"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="Owner"/>- <span asp-validation-for="Owner"></span>+ <div class="form-group">+ <admin-label asp-for="Owner"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="Owner"/>+ <span asp-validation-for="Owner"></span>+ </div></div>-</div>-<div class="form-group">- <admin-label asp-for="SeId"/>- <div class="col-md-9 col-sm-9">- <admin-select asp-for="SeId" asp-items="Model.AvailableSalesEmployees"/>- <span asp-validation-for="SeId"></span>+ <div class="form-group">+ <admin-label asp-for="SeId"/>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="SeId" asp-items="Model.AvailableSalesEmployees"/>+ <span asp-validation-for="SeId"></span>+ </div></div>-</div>+}@if (Model.GenderEnabled){<div class="form-group">@@ -377,12 +388,12 @@<span asp-validation-for="TwoFactorEnabled"></span></div></div>-@if (!string.IsNullOrEmpty(Model.AffiliateId))+@if (Scope.DefaultStoreId is null && !string.IsNullOrEmpty(Model.AffiliateId)){<div class="form-group"><admin-label asp-for="AffiliateId"/><div class="col-md-9 col-sm-9">- <a class="k-button" href="@Url.Action("Edit", "Affiliate", new { id = Model.AffiliateId, area = Constants.AreaAdmin })"><span class="k-icon k-i-eye"></span> @Model.AffiliateName - @Loc["Admin.Common.View"]</a>+ <a class="k-button" href="@Url.Action("Edit", "Affiliate", new { id = Model.AffiliateId, area = area })"><span class="k-icon k-i-eye"></span> @Model.AffiliateName - @Loc["Admin.Common.View"]</a><button type="submit" name="remove-affiliate" asp-action="RemoveAffiliate" class="k-button red"><span class="k-icon k-i-delete"></span> @Loc["Admin.Customers.Customers.Fields.Affiliate.Remove"]</button></div></div>@@ -484,5 +495,5 @@ else</div>}</div>-<vc:admin-widget widget-zone="customer_details_info_bottom" additional-data="Model"/>-</div>\ No newline at end of file+<partial name="Partials/WidgetZone.InfoBottom" model="Model"/>+</div>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtmlsimilarity index 84%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtmlindex 3eed28f7f..55d6f5216 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtml@@ -1,12 +1,15 @@-@model CustomerModel+@model CustomerModel@inject AdminAreaSettings adminAreaSettings+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}<div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_loyalty_points_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.LoyaltyPointsTop" model="Model"/><div class="panel-body"><div id="customer-loyaltypoints-grid"></div></div>- <vc:admin-widget widget-zone="customer_details_loyalty_points_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.LoyaltyPointsBottom" model="Model"/></div><script>@@ -15,7 +18,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("LoyaltyPointsHistorySelect", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("LoyaltyPointsHistorySelect", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -48,7 +51,7 @@},scrollable: false,columns: [- @if (!adminAreaSettings.HideStoreColumn)+ @if (area == "Admin" && !adminAreaSettings.HideStoreColumn){<text>{@@ -95,13 +98,16 @@<span asp-validation-for="AddLoyaltyPointsMessage"></span></div></div>- <div class="form-group">- <admin-label asp-for="AddLoyaltyPointsStoreId"/>- <div class="col-md-9 col-sm-9">- <admin-select asp-for="AddLoyaltyPointsStoreId" asp-items="Model.LoyaltyPointsAvailableStores"/>- <span asp-validation-for="AddLoyaltyPointsStoreId"></span>+ @if (area == "Admin")+ {+ <div class="form-group">+ <admin-label asp-for="AddLoyaltyPointsStoreId"/>+ <div class="col-md-9 col-sm-9">+ <admin-select asp-for="AddLoyaltyPointsStoreId" asp-items="Model.LoyaltyPointsAvailableStores"/>+ <span asp-validation-for="AddLoyaltyPointsStoreId"></span>+ </div></div>- </div>+ }</div><div class="form-actions"><div class="offset-md-3">@@ -114,13 +120,23 @@$('#addLoyaltyPoints').click(function () {var loyaltyPointsValue = $("#@Html.IdFor(model => model.AddLoyaltyPointsValue)").val();var loyaltyPointsMessage = $("#@Html.IdFor(model => model.AddLoyaltyPointsMessage)").val();+@if (area == "Admin")+{+ <text>var loyaltyPointsStoreId = $("#@Html.IdFor(model => model.AddLoyaltyPointsStoreId)").val();+ </text>+}$('#addLoyaltyPoints').attr('disabled', true);var postData = {addLoyaltyPointsValue: loyaltyPointsValue,addLoyaltyPointsMessage: loyaltyPointsMessage,+@if (area == "Admin")+{+ <text>storeId: loyaltyPointsStoreId,+ </text>+}customerId: '@Model.Id'};addAntiForgeryToken(postData);@@ -128,7 +144,7 @@$.ajax({cache:false,type: "POST",- url: "@(Url.Action("LoyaltyPointsHistoryAdd", "Customer", new { area = Constants.AreaAdmin }))",+ url: "@(Url.Action("LoyaltyPointsHistoryAdd", "Customer", new { area = area }))",data: postData,success: function (data) {var grid = $("#customer-loyaltypoints-grid").data('kendoGrid');@@ -142,4 +158,4 @@});});});-</script>\ No newline at end of file+</script>diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabOrders.cshtmlsimilarity index 89%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabOrders.cshtmlindex 6d8439c41..ab81e5d11 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabOrders.cshtml@@ -1,12 +1,13 @@-@model CustomerModel+@model CustomerModel@inject AdminAreaSettings adminAreaSettings@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();<div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_orders_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.OrdersTop" model="Model"/><div class="panel-body"><div id="order-grid"></div></div>- <vc:admin-widget widget-zone="customer_details_orders_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.OrdersBottom" model="Model"/></div><script>$(document).ready(function () {@@ -14,7 +15,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("OrderList", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("OrderList", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -51,12 +52,12 @@field: "OrderNumber",title: "@Loc["Admin.Customers.Customers.Orders.ID"]",width: 90,- template: '<a class="k-link" href="@Url.Action("Edit", "Order", new { area = Constants.AreaAdmin })/#=Id#">#=OrderNumber#</a>'+ template: '<a class="k-link" href="@Url.Action("Edit", "Order", new { area = area })/#=Id#">#=OrderNumber#</a>'}, {field: "OrderTotal",title: "@Loc["Admin.Customers.Customers.Orders.OrderTotal"]",width: 120,- template: '<a class="k-link" href="@Url.Action("Edit", "Order", new { area = Constants.AreaAdmin })/#=Id#">#=OrderTotal#</a>'+ template: '<a class="k-link" href="@Url.Action("Edit", "Order", new { area = area })/#=Id#">#=OrderTotal#</a>'}, {field: "OrderStatus",title: "@Loc["Admin.Customers.Customers.Orders.OrderStatus"]",@@ -77,7 +78,7 @@title: "@Loc["Admin.Customers.Customers.Orders.ShippingStatus"]",width: 180},- @if (!adminAreaSettings.HideStoreColumn)+ @if (area == "Admin" && !adminAreaSettings.HideStoreColumn){<text>{@@ -102,7 +103,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("OrderDetails", "Customer", new { area = Constants.AreaAdmin }))?orderId="+e.data.Id,+ url: "@Html.Raw(Url.Action("OrderDetails", "Customer", new { area = area }))?orderId="+e.data.Id,type: "POST",dataType: "json",data: addAntiForgeryToken@@ -135,7 +136,7 @@field: "ProductName",title: "@Loc["Admin.Orders.Products.ProductName"]",width: 400,- template: '<a class="k-link" href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#">#=ProductName#</a>'+ template: '<a class="k-link" href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#">#=ProductName#</a>'},{field: "Quantity",@@ -155,4 +156,4 @@]});}-</script>}\ No newline at end of file+</script>}diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtmlsimilarity index 86%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtmlindex cd452d6b5..146b36271 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtml@@ -1,12 +1,13 @@-@model CustomerModel+@model CustomerModel@inject AdminAreaSettings adminAreaSettings@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();<div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_back_in_stock_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.BackInStockTop" model="Model"/><div class="panel-body"><div id="outofstock-subscriptions-grid"></div></div>- <vc:admin-widget widget-zone="customer_details_back_in_stock_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.BackInStockBottom" model="Model"/></div><script>$(document).ready(function () {@@ -14,7 +15,7 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("OutOfStockSubscriptionList", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("OutOfStockSubscriptionList", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -46,7 +47,7 @@},scrollable: false,columns: [- @if (!adminAreaSettings.HideStoreColumn)+ @if (area == "Admin" && !adminAreaSettings.HideStoreColumn){<text>{@@ -60,7 +61,7 @@field: "ProductId",title: "@Loc["Admin.Customers.Customers.OutOfStockSubscriptions.Product"]",width: 300,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#">#:ProductName#</a>'+ template: '<a href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#">#:ProductName#</a>'},{field: "CreatedOn",title: "@Loc["Admin.Customers.Customers.OutOfStockSubscriptions.CreatedOn"]",@@ -70,4 +71,4 @@}]});});-</script>}\ No newline at end of file+</script>}diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabProduct.cshtmlsimilarity index 87%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabProduct.cshtmlindex f4e302afc..02bad0437 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabProduct.cshtml@@ -1,17 +1,18 @@-@model CustomerModel+@model CustomerModel@inject AdminAreaSettings adminAreaSettings@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();<strong>@Html.Raw(Loc["Admin.Customers.Customers.PersonalizedProduct"])</strong><div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_product_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ProductTop" model="Model"/><div class="panel-body"><div id="personalizedproduct-grid"></div></div><div class="panel-footer">- <a id="btnAddNewPersonalizedProduct" href="@(Url.Action("ProductAddPopup", "Customer", new { customerId = Model.Id, btnId = "btnRefreshPersonalizedProducts", formId = "customer-form", personalized = "true", area = Constants.AreaAdmin }))" class="k-button"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.PersonalizedProduct.AddNew"]</a>+ <a id="btnAddNewPersonalizedProduct" href="@(Url.Action("ProductAddPopup", "Customer", new { customerId = Model.Id, btnId = "btnRefreshPersonalizedProducts", formId = "customer-form", personalized = "true", area = area }))" class="k-button"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.PersonalizedProduct.AddNew"]</a><input type="submit" id="btnRefreshPersonalizedProducts" style="display: none"/></div>- <vc:admin-widget widget-zone="customer_details_product_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ProductBottom" model="Model"/></div><script>$(document).ready(function () {@@ -32,19 +33,19 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("PersonalizedProducts", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("PersonalizedProducts", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},update: {- url:"@Html.Raw(Url.Action("UpdatePersonalizedProduct", "Customer", new { area = Constants.AreaAdmin }))",+ url:"@Html.Raw(Url.Action("UpdatePersonalizedProduct", "Customer", new { area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},destroy: {- url: "@Html.Raw(Url.Action("DeletePersonalizedProduct", "Customer", new { area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("DeletePersonalizedProduct", "Customer", new { area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -86,7 +87,7 @@field: "ProductName",title: "@Loc["Admin.Customers.Customers.PersonalizedProduct.ProductName"]",width: 300,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#" target="_blank">#=kendo.htmlEncode(ProductName)#</a>'+ template: '<a href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#" target="_blank">#=kendo.htmlEncode(ProductName)#</a>'}, {field: "DisplayOrder",title: "@Loc["Admin.Customers.Customers.PersonalizedProduct.DisplayOrder"]",@@ -120,4 +121,4 @@});});</script>-}\ No newline at end of file+}diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtmlsimilarity index 86%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtmlindex 5fcdb228c..ba842ad5c 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtml@@ -1,17 +1,18 @@-@model CustomerModel+@model CustomerModel@inject AdminAreaSettings adminAreaSettings@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();<strong>@Loc["Admin.Customers.Customers.ProductPrice"]</strong><div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_product_price_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ProductPriceTop" model="Model"/><div class="panel-body"><div id="productprice-grid"></div></div><div class="panel-footer">- <a id="btnAddNewProduct" href="@(Url.Action("ProductAddPopup", "Customer", new { customerId = Model.Id, btnId = "btnRefreshProducts", formId = "customer-form", area = Constants.AreaAdmin }))" class="k-button"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.ProductPrice.AddNew"]</a>+ <a id="btnAddNewProduct" href="@(Url.Action("ProductAddPopup", "Customer", new { customerId = Model.Id, btnId = "btnRefreshProducts", formId = "customer-form", area = area }))" class="k-button"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.ProductPrice.AddNew"]</a><input type="submit" id="btnRefreshProducts" style="display: none"/></div>- <vc:admin-widget widget-zone="customer_details_product_price_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ProductPriceBottom" model="Model"/></div><div class="note note-info">@Loc["Admin.Customers.Customers.ProductPrice.Price.Warning"]@@ -36,19 +37,19 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("ProductsPrice", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("ProductsPrice", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},update: {- url:"@Html.Raw(Url.Action("UpdateProductPrice", "Customer", new { area = Constants.AreaAdmin }))",+ url:"@Html.Raw(Url.Action("UpdateProductPrice", "Customer", new { area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},destroy: {- url: "@Html.Raw(Url.Action("DeleteProductPrice", "Customer", new { area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("DeleteProductPrice", "Customer", new { area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -90,7 +91,7 @@field: "ProductName",title: "@Loc["Admin.Customers.Customers.ProductPrice.ProductName"]",width: 300,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#" target="_blank">#=kendo.htmlEncode(ProductName)#</a>'+ template: '<a href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#" target="_blank">#=kendo.htmlEncode(ProductName)#</a>'}, {field: "Price",title: "@Loc["Admin.Customers.Customers.ProductPrice.Price"]",@@ -124,4 +125,4 @@});});</script>-}\ No newline at end of file+}diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabReviews.cshtmlsimilarity index 89%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabReviews.cshtmlindex 06148451e..e6fec2bb7 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.TabReviews.cshtml@@ -1,12 +1,13 @@-@model CustomerModel+@model CustomerModel@inject AdminAreaSettings adminAreaSettings@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();<div class="panel panel-default">- <vc:admin-widget widget-zone="customer_details_reviews_top" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ReviewsTop" model="Model"/><div class="panel-body"><div id="review-grid"></div></div>- <vc:admin-widget widget-zone="customer_details_reviews_bottom" additional-data="Model"/>+ <partial name="Partials/WidgetZone.ReviewsBottom" model="Model"/></div><style>.rating {@@ -47,13 +48,13 @@dataSource: {transport: {read: {- url: "@Html.Raw(Url.Action("ReviewList", "Customer", new { customerId = Model.Id, area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("ReviewList", "Customer", new { customerId = Model.Id, area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken},destroy: {- url: "@Html.Raw(Url.Action("ReviewDelete", "Customer", new { area = Constants.AreaAdmin }))",+ url: "@Html.Raw(Url.Action("ReviewDelete", "Customer", new { area = area }))",type: "POST",dataType: "json",data: addAntiForgeryToken@@ -97,11 +98,11 @@field: "ProductName",title: "@Loc["Admin.Customers.Customers.Reviews.Product"]",width: 90,- template: '<a class="k-link" href="@Url.Action("Edit", "Product", new { area = Constants.AreaAdmin })/#=ProductId#">#=kendo.htmlEncode(ProductName)#</a>'+ template: '<a class="k-link" href="@Url.Action("Edit", "Product", new { area = area })/#=ProductId#">#=kendo.htmlEncode(ProductName)#</a>'}, {field: "Title",title: "@Loc["Admin.Customers.Customers.Reviews.Title"]",- template: '<a class="k-link" href="@Url.Action("Edit", "ProductReview", new { area = Constants.AreaAdmin })/#=Id#">#:kendo.htmlEncode(Title)#</a>',+ template: '<a class="k-link" href="@Url.Action("Edit", "ProductReview", new { area = area })/#=Id#">#:kendo.htmlEncode(Title)#</a>',width: 120}, {field: "Rating",@@ -128,4 +129,4 @@return '<div class="rating"><div class="rating-ghost">☆☆☆☆☆</div><div class="rating-real" style="width: ' + rating * 20 + '%">★★★★★</div></div>'}</script>-}\ No newline at end of file+}diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.cshtmlsimilarity index 60%rename from src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.cshtmlindex b1d1cf65d..af0df12ea 100644--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdate.cshtml@@ -1,37 +1,52 @@-@using Grand.Business.Core.Interfaces.Common.Security+@using Grand.Business.Core.Interfaces.Common.Security+@using Grand.Domain.Customers@using Grand.Domain.Permissions-@using Constants = Grand.SharedUIResources.Constants@model CustomerModel@inject IPermissionService permissionService+@inject IAdminDataScope<Customer> Scope@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();//has "Manage Documents" permission?var canManageDocuments = await permissionService.Authorize(StandardPermission.ManageDocuments);}<div asp-validation-summary="All"></div><input asp-for="Id" type="hidden"/>+@if (area == "Store")+{+ <input asp-for="StoreId" type="hidden"/>+ @foreach (var item in Model.CustomerGroups.Select((value, index) => new { value, index }))+ {+ <input type="hidden"+ name="CustomerGroups[@item.index]"+ value="@item.value"/>+ }+}-<link rel="stylesheet" type="text/css" asp-src="@(Constants.WwwRoot)/administration/tagEditor/jquery.tag-editor.css"/>-<script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/tagEditor/jquery.tag-editor.min.js"></script>-<script asp-location="Footer" asp-src="@(Constants.WwwRoot)/administration/tagEditor/jquery.caret.min.js"></script>+@if (area == "Admin")+{+ <link rel="stylesheet" type="text/css" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/tagEditor/jquery.tag-editor.css"/>+ <script asp-location="Footer" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/tagEditor/jquery.tag-editor.min.js"></script>+ <script asp-location="Footer" asp-src="@(Grand.SharedUIResources.Constants.WwwRoot)/administration/tagEditor/jquery.caret.min.js"></script>-<script>- //tags- $(document).ready(function () {- $("#@Html.IdFor(model => model.CustomerTags)").tagEditor({- autocomplete: {- delay: 0,- position: { collision: 'flip' },- source: '@Url.Action("Search", "CustomerTag", new { area = Grand.Web.Admin.Extensions.Constants.AreaAdmin })',- minLength: 3,- //source: initialProductTags- },- delimiter: ',',- placeholder: 'Enter tags ...'+ <script>+ //tags+ $(document).ready(function () {+ $("#@Html.IdFor(model => model.CustomerTags)").tagEditor({+ autocomplete: {+ delay: 0,+ position: { collision: 'flip' },+ source: '@Url.Action("Search", "CustomerTag", new { area = area })',+ minLength: 3,+ //source: initialProductTags+ },+ delimiter: ',',+ placeholder: 'Enter tags ...'+ });});- });-</script>+ </script>+}<admin-tabstrip name="customer-edit" SetTabPos="true" BindGrid="true"><items>@@ -81,20 +96,23 @@</div></content></tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.CustomerNotes"]" tab-index="6">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabNotes" model="Model"/>- </div>- </content>- </tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.ActivityLog"]" tab-index="7">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabActivityLog" model="Model"/>- </div>- </content>- </tabstrip-item>+ @if (Scope.DefaultStoreId is null)+ {+ <tabstrip-item text="@Loc["Admin.Customers.Customers.CustomerNotes"]" tab-index="6">+ <content>+ <div>+ <partial name="Partials/CreateOrUpdate.TabNotes" model="Model"/>+ </div>+ </content>+ </tabstrip-item>+ <tabstrip-item text="@Loc["Admin.Customers.Customers.ActivityLog"]" tab-index="7">+ <content>+ <div>+ <partial name="Partials/CreateOrUpdate.TabActivityLog" model="Model"/>+ </div>+ </content>+ </tabstrip-item>+ }<tabstrip-item text="@Loc["Admin.Customers.Customers.OutOfStockSubscriptions"]" tab-index="8"><content><div>@@ -113,7 +131,7 @@</tabstrip-item>}- @if (canManageDocuments)+ @if (Scope.DefaultStoreId is null && canManageDocuments){<tabstrip-item text="@Loc["Admin.Customers.Customers.Documents"]" tab-index="10"><content>@@ -124,6 +142,6 @@</tabstrip-item>}}- <vc:admin-widget widget-zone="customer_details_tabs" additional-data="Model"/>+ <partial name="Partials/WidgetZone.DetailsTabs" model="Model"/></items>-</admin-tabstrip>\ No newline at end of file+</admin-tabstrip>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdateAddress.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdateAddress.cshtmlsimilarity index 54%rename from src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdateAddress.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdateAddress.cshtmlindex ef794153e..5ec1c4b03 100644--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdateAddress.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/CreateOrUpdateAddress.cshtml@@ -1,4 +1,6 @@@model CustomerAddressModel<div asp-validation-summary="All"></div><input type="hidden" asp-for="CustomerId"/>+<partial name="Partials/WidgetZone.AddressDetailsTop" model="Model"/><admin-input asp-for="Address" asp-template="Address"/>+<partial name="Partials/WidgetZone.AddressDetailsBottom" model="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/SendEmail.cshtml b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/SendEmail.cshtmlsimilarity index 93%rename from src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/SendEmail.cshtmlrename to src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/SendEmail.cshtmlindex b6fb9b055..e9d8cd77e 100644--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/SendEmail.cshtml+++ b/src/Web/Grand.Web.AdminShared/Views/AdminShared/Customer/Partials/SendEmail.cshtml@@ -1,7 +1,10 @@@model CustomerModel.SendEmailModel+@{+ var area = ViewContext.RouteData.Values["area"]?.ToString();+}<div id="sendemail-window" style="display:none;">- <form asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="SendEmail" method="post" asp-route-id="Id">+ <form asp-area="@area" asp-controller="Customer" asp-action="SendEmail" method="post" asp-route-id="Id"><input type="hidden" asp-for="Id" id="sendemail_customerId"/><div class="form-horizontal"><div class="form-body">@@ -58,11 +61,13 @@window.data('kendoWindow').center().open();});+//timing of send email section$("#pnl-send-date").hide();$("#sendemail-window .check-box").click(function () {$("#pnl-send-date").toggle();});+});</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtmldeleted file mode 100644index d17d04056..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtml+++ /dev/null@@ -1,143 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings--<div class="panel panel-default">- <div class="panel-heading">- @Loc["Admin.Customers.Customers.CurrentShoppingCart"]- </div>- <div class="panel-body">- <div id="currentshoppingcart-grid"></div>- </div>-</div>--<script>-$(document).ready(function () {- $("#currentshoppingcart-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("GetCartList", "Customer", new { customerId = Model.Id, cartTypeId = (int)ShoppingCartType.ShoppingCart, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- update: {- url: "@Html.Raw(Url.Action("UpdateCart", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors",- model: {- id: "Id",- fields: {- ProductName: { editable: false, type: "string" },- Quantity: { editable: false, type: "number" },- UnitPrice: { editable: false, type: "string" },- UnitPriceValue: { editable: true, type: "number" },- Total: { editable: false, type: "string" },- Store: { editable: false, type: "string" },- UpdatedOn: { editable: false, type: "date" },- }- }- },- requestEnd: function (e) {- if (e.type == "update" || e.type == "destroy") {- this.read();- }- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- numeric: false,- previousNext: false,- info: false- },- editable: {- confirmation: true,- mode: "incell"- },- toolbar: ["save"],- scrollable: false,- columns: [{- field: "ProductName",- title: "@Loc["Admin.CurrentCarts.Product"]",- width:500,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#">#:kendo.htmlEncode(ProductName)#</a>' +- '# if(AttributeInfo && AttributeInfo.length > 0) {# <br />#=AttributeInfo# #} #'- }, {- field: "Quantity",- title: "@Loc["Admin.CurrentCarts.Quantity"]",- width:200- },{- field: "UnitPriceValue",- title: "@Loc["Admin.CurrentCarts.UnitPrice"]",- width: 200,- format: "{0:n2}",- editor: function (container, options) {- $('<input name="' + options.field + '"/>')- .appendTo(container)- .kendoNumericTextBox({- format: "{0:n2}",- decimals: 2- });- }- },{- field: "Total",- title: "@Loc["Admin.CurrentCarts.Total"]",- width:200- }, {- field: "UpdatedOn",- title: "@Loc["Admin.CurrentCarts.UpdatedOn"]",- width: 200,- type: "date",- format: "{0:G}"- }, {- title: "@Loc["Admin.Common.Delete"]",- width: 200,- template: "<button class='k-button k-grid-delete' onclick=deleteRow('#=Id#')>Delete</button>"- }]- });-});-- function deleteRow(id) {- var grid = $("#currentshoppingcart-grid").data("kendoGrid");- var dataItem = grid.dataSource.get(id);- var tokenInput = $('input[name=__RequestVerificationToken]');- $.ajax({- url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- data: {- id: dataItem.Id,- customerId: "@Model.Id",- __RequestVerificationToken: tokenInput.val(),- },- success: function () {- grid.dataSource.remove(dataItem);- grid.dataSource.sync();- },- error: function (e) {- display_kendoui_grid_error(e);- }- });- }--</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtmldeleted file mode 100644index 765a52864..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtml+++ /dev/null@@ -1,100 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings--<div class="panel panel-default">- <div class="panel-heading">- @Loc["Admin.Customers.Customers.CurrentWishlist"]- </div>- <div class="panel-body">- <div id="currentwishlist-grid"></div>- </div>-</div>-<script>-$(document).ready(function () {- $("#currentwishlist-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("GetCartList", "Customer", new { customerId = Model.Id, cartTypeId = (int)ShoppingCartType.Wishlist, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("DeleteCart", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors",- model: {- id: "Id",- fields: {- ProductName: { editable: false, type: "string" },- Quantity: { editable: false, type: "number" },- UnitPrice: { editable: false, type: "string" },- Total: { editable: false, type: "string" },- Store: { editable: false, type: "string" },- UpdatedOn: { editable: false, type: "date" },- }- }- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- numeric: false,- previousNext: false,- info: false- },- editable: {- confirmation: true,- mode: "inline"- },- scrollable: false,- columns: [{- field: "ProductName",- title: "@Loc["Admin.CurrentCarts.Product"]",- width:500,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#">#:kendo.htmlEncode(ProductName)#</a>' +- '# if(AttributeInfo && AttributeInfo.length > 0) {# <br />#=AttributeInfo# #} #'- }, {- field: "Quantity",- title: "@Loc["Admin.CurrentCarts.Quantity"]",- width:200- },{- field: "UnitPrice",- title: "@Loc["Admin.CurrentCarts.UnitPrice"]",- width:200- },{- field: "Total",- title: "@Loc["Admin.CurrentCarts.Total"]",- width:200- }, {- field: "UpdatedOn",- title: "@Loc["Admin.CurrentCarts.UpdatedOn"]",- width: 200,- type: "date",- format: "{0:G}"- }, {- command: [- {- name: "destroy",- text: "@Loc["Admin.Common.Delete"]"- }],- width: 200- }]- });-});-</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtmldeleted file mode 100644index ae49760cf..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml+++ /dev/null@@ -1,406 +0,0 @@-@model CustomerModel--@if (Model.CountryEnabled && Model.StateProvinceEnabled)-{- <script>- $(document).ready(function() {- $("#@Html.IdFor(model => model.CountryId)").change(function() {- var selectedItem = $(this).val();- var ddlStates = $("#@Html.IdFor(model => model.StateProvinceId)");-- var postData = {- countryId: selectedItem,- addSelectStateItem: "true"- };-- $.ajax({- cache: false,- type: "GET",- url: "@(Url.Action("GetStatesByCountryId", "Home", new { area = Constants.AreaStore }))",- data: postData,- success: function(data) {- ddlStates.html('');- $.each(data, function(id, option) {- ddlStates.append($('<option></option>').val(option.id).html(option.name));- });- },- error: function(xhr, ajaxOptions, thrownError) {- alert('Failed to retrieve states.');- }- });- });- });- </script>-}-<div class="form-horizontal">-<div class="form-body">-@if (Model.UsernamesEnabled)-{- if (string.IsNullOrEmpty(Model.Id) || Model.AllowUsersToChangeUsernames)- {- <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>- }- else- {- <div class="form-group">- <admin-label asp-for="Username"/>- <div class="col-md-9 col-sm-9">- <label class="control-label"> @Model.Username</label>- <input asp-for="Username" type="hidden"/>- </div>- </div>- }-}-<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="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>-@if (!string.IsNullOrEmpty(Model.Id) && Model.AssociatedExternalAuthRecords.Count > 0)-{- <div class="form-group">- <admin-label asp-for="AssociatedExternalAuthRecords"/>- <div class="col-md-9 col-sm-9">- <div id="externalauthrecords-grid"></div>- <script>- var externalauthrecords = [- @for (var i = 0; i < Model.AssociatedExternalAuthRecords.Count; i++)- {- var aear = Model.AssociatedExternalAuthRecords[i];- <text>- {- AuthMethodName: "@aear.AuthMethodName",- Email: "@aear.Email",- ExternalIdentifier: "@aear.ExternalIdentifier"- }- </text>- if (i != Model.AssociatedExternalAuthRecords.Count - 1)- {- <text>,</text>- }- }- ];-- $(document).ready(function () {- $("#externalauthrecords-grid").kendoGrid({- dataSource: {- data: externalauthrecords,- schema: {- model: {- fields: {- AuthMethodName: { type: "string" },- Email: { type: "string" },- ExternalIdentifier: { type: "string" }- }- }- },- error: function (e) {- display_kendoui_grid_error(e);- this.cancelChanges();- }- },- pageable: {- refresh: true,- numeric: false,- previousNext: false,- info: false- },- scrollable: false,- columns: [- {- field: "AuthMethodName",- title: "@Loc["Admin.Customers.Customers.AssociatedExternalAuth.Fields.AuthMethodName"]",- width: 100- }, {- field: "Email",- title: "@Loc["Admin.Customers.Customers.AssociatedExternalAuth.Fields.Email"]",- width: 100- },{- field: "ExternalIdentifier",- title: "@Loc["Admin.Customers.Customers.AssociatedExternalAuth.Fields.ExternalIdentifier"]",- width: 300- }- ]- });- });- </script>- </div>- </div>-}-@if (Model.GenderEnabled)-{- <div class="form-group">- <admin-label asp-for="Gender"/>- <div class="col-md-9 col-sm-9">- <div class="gender">- @Html.RadioButton("Gender", "M", Model.Gender == "M", new { id = "Gender_Male" })- <label class="forcheckbox" for="Gender_Male">@Loc["Admin.Customers.Customers.Fields.Gender.Male"]</label>- </div>- <div class="gender">- @Html.RadioButton("Gender", "F", Model.Gender == "F", new { id = "Gender_Female" })- <label class="forcheckbox" for="Gender_Female">@Loc["Admin.Customers.Customers.Fields.Gender.Female"]</label>- </div>- </div>- </div>-}-<div class="form-group">- <admin-label asp-for="FirstName"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="FirstName"/>- <span asp-validation-for="FirstName"></span>- </div>-</div>-<div class="form-group">- <admin-label asp-for="LastName"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="LastName"/>- <span asp-validation-for="LastName"></span>- </div>-</div>-@if (Model.DateOfBirthEnabled)-{- <div class="form-group">- <admin-label asp-for="DateOfBirth"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="DateOfBirth"/>- <span asp-validation-for="DateOfBirth"></span>- </div>- </div>-}-@if (Model.CompanyEnabled)-{- <div class="form-group">- <admin-label asp-for="Company"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="Company"/>- <span asp-validation-for="Company"></span>- </div>- </div>-}-@if (Model.StreetAddressEnabled)-{- <div class="form-group">- <admin-label asp-for="StreetAddress"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="StreetAddress"/>- <span asp-validation-for="StreetAddress"></span>- </div>- </div>-}-@if (Model.StreetAddress2Enabled)-{- <div class="form-group">- <admin-label asp-for="StreetAddress2"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="StreetAddress2"/>- <span asp-validation-for="StreetAddress2"></span>- </div>- </div>-}-@if (Model.ZipPostalCodeEnabled)-{- <div class="form-group">- <admin-label asp-for="ZipPostalCode"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="ZipPostalCode"/>- <span asp-validation-for="ZipPostalCode"></span>- </div>- </div>-}-@if (Model.CityEnabled)-{- <div class="form-group">- <admin-label asp-for="City"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="City"/>- <span asp-validation-for="City"></span>- </div>- </div>-}-@if (Model.CountryEnabled)-{- <div class="form-group">- <admin-label asp-for="CountryId"/>- <div class="col-md-9 col-sm-9">- <admin-select asp-for="CountryId" asp-items="Model.AvailableCountries"/>- <span asp-validation-for="CountryId"></span>- </div>- </div>-}-@if (Model.CountryEnabled && Model.StateProvinceEnabled)-{- <div class="form-group">- <admin-label asp-for="StateProvinceId"/>- <div class="col-md-9 col-sm-9">- <admin-select asp-for="StateProvinceId" asp-items="Model.AvailableStates"/>- <span asp-validation-for="StateProvinceId"></span>- </div>- </div>-}-@if (Model.PhoneEnabled)-{- <div class="form-group">- <admin-label asp-for="Phone"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="Phone"/>- <span asp-validation-for="Phone"></span>- </div>- </div>-}-@if (Model.FaxEnabled)-{- <div class="form-group">- <admin-label asp-for="Fax"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="Fax"/>- <span asp-validation-for="Fax"></span>- </div>- </div>-}-@if (Model.CustomerAttributes.Count > 0)-{- <div class="form-group">- <partial name="Partials/CustomerAttributes" model="Model.CustomerAttributes"/>- </div>-}-<div class="form-group">- <admin-label asp-for="AdminComment"/>- <div class="col-md-9 col-sm-9">- <admin-textarea asp-for="AdminComment"></admin-textarea>- <span asp-validation-for="AdminComment"></span>- </div>-</div>-<div class="form-group">- <admin-label asp-for="IsTaxExempt"/>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="IsTaxExempt"/>- <div class="control__indicator"></div>- </label>- <span asp-validation-for="IsTaxExempt"></span>- </div>-</div>-<div class="form-group">- <admin-label asp-for="FreeShipping"/>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="FreeShipping"/>- <div class="control__indicator"></div>- </label>- <span asp-validation-for="FreeShipping"></span>- </div>-</div>-<div class="form-group">- <admin-label asp-for="TwoFactorEnabled"/>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="TwoFactorEnabled"/>- <div class="control__indicator"></div>- </label>- <span asp-validation-for="TwoFactorEnabled"></span>- </div>-</div>-@if (Model.DisplayVatNumber)-{- <div class="form-group">- <admin-label asp-for="VatNumber"/>- <div class="col-md-9 col-sm-9">- <div class="input-group-control">- <admin-input asp-for="VatNumber"/>- <label class="control-label">- (@string.Format(Loc["Admin.Customers.Customers.Fields.VatNumberStatus"], Model.VatNumberStatusNote))- </label>- <input type="submit" name="markVatNumberAsValid" asp-action="MarkVatNumberAsValid" class="btn green" value="@Loc["Admin.Customers.Customers.Fields.VatNumber.MarkAsValid"]"/>- <input type="submit" name="markVatNumberAsInvalid" asp-action="MarkVatNumberAsInvalid" class="btn red" value="@Loc["Admin.Customers.Customers.Fields.VatNumber.MarkAsInvalid"]"/>- </div>- <span asp-validation-for="VatNumber"></span>- </div>- </div>-}-@if (Model.AvailableNewsletterSubscriptionStores is { Count: > 0 })-{- <div class="form-group">- <admin-label asp-for="SelectedNewsletterSubscriptionStoreIds"/>- <div class="col-md-9 col-sm-9">- @foreach (var store in Model.AvailableNewsletterSubscriptionStores)- {- <div>- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <input type="checkbox" name="SelectedNewsletterSubscriptionStoreIds" value="@store.Id" checked="@(Model.SelectedNewsletterSubscriptionStoreIds != null && Model.SelectedNewsletterSubscriptionStoreIds.Contains(store.Id))"/>(@(store.Name))- <div class="control__indicator"></div>- </label>- </div>- }- </div>- </div>-}-<div class="form-group">- <admin-label asp-for="Active"/>- <div class="col-md-9 col-sm-9">- <label class="mt-checkbox mt-checkbox-outline control control-checkbox">- <admin-input asp-for="Active"/>- <div class="control__indicator"></div>- </label>- <span asp-validation-for="Active"></span>- </div>-</div>-@if (!string.IsNullOrEmpty(Model.Id))-{- <div class="form-group">- <admin-label asp-for="LastIpAddress"/>- <div class="col-md-9 col-sm-9">- <label class="control-label">@Model.LastIpAddress</label>- </div>- </div>- <div class="form-group">- <admin-label asp-for="CreatedOn"/>- <div class="col-md-9 col-sm-9">- <label class="control-label">@Model.CreatedOn</label>- </div>- </div>- <div class="form-group">- <admin-label asp-for="LastActivityDate"/>- <div class="col-md-9 col-sm-9">- <label class="control-label">@Model.LastActivityDate</label>- </div>- </div>-}-@if (!string.IsNullOrEmpty(Model.Id) && !string.IsNullOrEmpty(Model.LastVisitedPage))-{- <div class="form-group">- <admin-label asp-for="LastVisitedPage"/>- <div class="col-md-9 col-sm-9">- <label class="control-label">@Model.LastVisitedPage</label>- </div>- </div>-}-@if (!string.IsNullOrEmpty(Model.Id) && Model.LastPurchaseDate.HasValue)-{- <div class="form-group">- <admin-label asp-for="LastPurchaseDate"/>- <div class="col-md-9 col-sm-9">- <label class="control-label">@Model.LastPurchaseDate</label>- </div>- </div>-}-</div>-</div>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtmldeleted file mode 100644index 9bac57f94..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtml+++ /dev/null@@ -1,124 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings--<div class="panel panel-default">- <div class="panel-body">- <div id="customer-loyaltypoints-grid"></div>- </div>-</div>--<script>- $(document).ready(function () {- $("#customer-loyaltypoints-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("LoyaltyPointsHistorySelect", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors"- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- numeric: false,- previousNext: false,- info: false- },- editable: {- confirmation: false,- mode: "inline"- },- scrollable: false,- columns: [- {- field: "Points",- title: "@Loc["Admin.Customers.Customers.LoyaltyPoints.Fields.Points"]"- }, {- field: "PointsBalance",- title: "@Loc["Admin.Customers.Customers.LoyaltyPoints.Fields.PointsBalance"]"- },{- field: "Message",- title: "@Loc["Admin.Customers.Customers.LoyaltyPoints.Fields.Message"]"- },{- field: "CreatedOn",- title: "@Loc["admin.marketing.Campaigns.Fields.CreatedOn"]",- width: 200,- type: "date",- format: "{0:G}"- }]- });- });-</script>-<p>- <strong> @Loc["Admin.Customers.Customers.LoyaltyPoints.AddTitle"]</strong>-</p>-<div class="form-horizontal">- <div class="form-body">- <div class="form-group">- <admin-label asp-for="AddLoyaltyPointsValue"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="AddLoyaltyPointsValue"/>- <span asp-validation-for="AddLoyaltyPointsValue"></span>- </div>- </div>- <div class="form-group">- <admin-label asp-for="AddLoyaltyPointsMessage"/>- <div class="col-md-9 col-sm-9">- <admin-input asp-for="AddLoyaltyPointsMessage"/>- <span asp-validation-for="AddLoyaltyPointsMessage"></span>- </div>- </div>- </div>- <div class="form-actions">- <div class="offset-md-3">- <input type="button" id="addLoyaltyPoints" class="k-button" value="@Loc["Admin.Customers.Customers.LoyaltyPoints.AddButton"]"/>- </div>- </div>-</div>-<script>- $(document).ready(function () {- $('#addLoyaltyPoints').click(function () {- var loyaltyPointsValue = $("#@Html.IdFor(model => model.AddLoyaltyPointsValue)").val();- var loyaltyPointsMessage = $("#@Html.IdFor(model => model.AddLoyaltyPointsMessage)").val();- $('#addLoyaltyPoints').attr('disabled', true);-- var postData = {- addLoyaltyPointsValue: loyaltyPointsValue,- addLoyaltyPointsMessage: loyaltyPointsMessage,- customerId: '@Model.Id'- };- addAntiForgeryToken(postData);-- $.ajax({- cache:false,- type: "POST",- url: "@(Url.Action("LoyaltyPointsHistoryAdd", "Customer", new { area = Constants.AreaStore }))",- data: postData,- success: function (data) {- var grid = $("#customer-loyaltypoints-grid").data('kendoGrid');- grid.dataSource.read();- $('#addLoyaltyPoints').attr('disabled', false);- },- error:function (xhr, ajaxOptions, thrownError){- alert('Failed to add loyalty points.');- $('#addLoyaltyPoints').attr('disabled', false);- }- });- });- });-</script>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtmldeleted file mode 100644index 795c57425..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml+++ /dev/null@@ -1,141 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings-@{- <div class="panel panel-default">- <div class="panel-body">- <div id="order-grid"></div>- </div>- </div>- <script>- $(document).ready(function () {- $("#order-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("OrderList", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors"- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- pageSize: @(adminAreaSettings.DefaultGridPageSize),- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- pageSizes: [@(adminAreaSettings.GridPageSizes)]- },- editable: {- confirmation: false,- mode: "inline"- },- detailInit: detailInit,- scrollable: false,- columns: [{- field: "OrderNumber",- title: "@Loc["Admin.Customers.Customers.Orders.ID"]",- width: 90,- template: '<a class="k-link" href="@Url.Action("Edit", "Order", new { area = Constants.AreaStore })/#=Id#">#=OrderNumber#</a>'- }, {- field: "OrderTotal",- title: "@Loc["Admin.Customers.Customers.Orders.OrderTotal"]",- width: 120,- template: '<a class="k-link" href="@Url.Action("Edit", "Order", new { area = Constants.AreaStore })/#=Id#">#=OrderTotal#</a>'- }, {- field: "OrderStatus",- title: "@Loc["Admin.Customers.Customers.Orders.OrderStatus"]",- width: 160,- template: '<h4><span class="label label-' +- '# if(OrderStatusId == 10) {#warning #} #' +- '# if(OrderStatusId == 20) {#info #} #' +- '# if(OrderStatusId == 25) {#info #} #' +- '# if(OrderStatusId == 30) {#success #} #' +- '# if(OrderStatusId == 40) {#danger #} #' +- '">#=OrderStatus#</span></h4>'- }, {- field: "PaymentStatus",- title: "@Loc["Admin.Customers.Customers.Orders.PaymentStatus"]",- width: 180- }, {- field: "ShippingStatus",- title: "@Loc["Admin.Customers.Customers.Orders.ShippingStatus"]",- width: 180- }, {- field: "CreatedOn",- title: "@Loc["Admin.Customers.Customers.Orders.CreatedOn"]",- width: 220,- type: "date",- format: "{0:G}"- }]- });- });- function detailInit(e) {- $("<div/>").appendTo(e.detailCell).kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("OrderDetails", "Customer", new { area = Constants.AreaStore }))?orderId="+e.data.Id,- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors"- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- scrollable: false,- sortable: false,- pageable: {- refresh: true,- numeric: false,- previousNext: false,- info: false- },- columns: [- {- field: "ProductName",- title: "@Loc["Admin.Orders.Products.ProductName"]",- width: 400,- template: '<a class="k-link" href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#">#=ProductName#</a>'- },- {- field: "Quantity",- title: "@Loc["Admin.Orders.Products.Quantity"]",- width: 100- },- {- field: "UnitPriceInclTax",- title: "@Loc["Admin.Orders.Products.Price"]",- width: 200- },- {- field: "SubTotalInclTax",- title: "@Loc["Admin.Orders.Products.Total"]",- width: 200- }- ]- });- }-</script>}diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtmldeleted file mode 100644index d26585a1a..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtml+++ /dev/null@@ -1,60 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings-@{- <div class="panel panel-default">- <div class="panel-body">- <div id="outofstock-subscriptions-grid"></div>- </div>- </div>- <script>- $(document).ready(function () {- $("#outofstock-subscriptions-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("OutOfStockSubscriptionList", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors"- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- pageSize: @(adminAreaSettings.DefaultGridPageSize),- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- pageSizes: [@(adminAreaSettings.GridPageSizes)]- },- editable: {- confirmation: false,- mode: "inline"- },- scrollable: false,- columns: [- {- field: "ProductId",- title: "@Loc["Admin.Customers.Customers.OutOfStockSubscriptions.Product"]",- width: 300,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#">#:ProductName#</a>'- },{- field: "CreatedOn",- title: "@Loc["Admin.Customers.Customers.OutOfStockSubscriptions.CreatedOn"]",- width: 200,- type: "date",- format: "{0:G}"- }]- });- });-</script>}diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtmldeleted file mode 100644index fd5dfd5f0..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtml+++ /dev/null@@ -1,117 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings-@{- <strong>@Html.Raw(Loc["Admin.Customers.Customers.PersonalizedProduct"])</strong>- <div class="panel panel-default">- <div class="panel-body">- <div id="personalizedproduct-grid"></div>- </div>- <div class="panel-footer">- <a id="btnAddNewPersonalizedProduct" href="@(Url.Action("ProductAddPopup", "Customer", new { customerId = Model.Id, btnId = "btnRefreshPersonalizedProducts", formId = "customer-form", personalized = "true", area = Constants.AreaStore }))" class="k-button"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.PersonalizedProduct.AddNew"]</a>- <input type="submit" id="btnRefreshPersonalizedProducts" style="display: none"/>- </div>- </div>- <script>- $(document).ready(function () {- $('#btnAddNewPersonalizedProduct').magnificPopup({- type: 'ajax',- settings: { cache: false, async: false },- midClick: true,- callbacks: {- parseAjax: function (mfpResponse) {- mfpResponse.data = $('<div></div>').html(mfpResponse.data);- },- ajaxContentAdded: function () {- $('.mfp-wrap').removeAttr('tabindex');- }- }- });- $("#personalizedproduct-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("PersonalizedProducts", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- update: {- url:"@Html.Raw(Url.Action("UpdatePersonalizedProduct", "Customer", new { area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("DeletePersonalizedProduct", "Customer", new { area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors",- model: {- id: "Id",- fields: {- ProductName: {editable: false, type: "string" },- DisplayOrder: {editable: true, type: "number", format:"{0:n2}" },- }- }- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- pageSize: @(adminAreaSettings.DefaultGridPageSize),- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- pageSizes: [@(adminAreaSettings.GridPageSizes)]- },- editable: {- confirmation: false,- mode: "inline"- },- scrollable: false,- columns: [{- field: "ProductName",- title: "@Loc["Admin.Customers.Customers.PersonalizedProduct.ProductName"]",- width: 300,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#" target="_blank">#=kendo.htmlEncode(ProductName)#</a>'- }, {- field: "DisplayOrder",- title: "@Loc["Admin.Customers.Customers.PersonalizedProduct.DisplayOrder"]",- width: 100,- type: "number",-- }, {- command: [{- name: "edit",- text: {- edit: "@Loc["Admin.Common.Edit"]",- update: "@Loc["Admin.Common.Update"]",- cancel: "@Loc["Admin.Common.Cancel"]"} }, {- name: "destroy",- text: "@Loc["Admin.Common.Delete"]"- }],- width: 200- }]- });- });-</script>- <script>- $(document).ready(function () {- $('#btnRefreshPersonalizedProducts').click(function () {- var grid = $("#personalizedproduct-grid").data('kendoGrid');- grid.dataSource.read();- return false;- });- });- </script>-}diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtmldeleted file mode 100644index 4b73fd8c2..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtml+++ /dev/null@@ -1,121 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings-@{- <strong>@Loc["Admin.Customers.Customers.ProductPrice"]</strong>- <div class="panel panel-default">- <div class="panel-body">- <div id="productprice-grid"></div>- </div>- <div class="panel-footer">- <a id="btnAddNewProduct" href="@(Url.Action("ProductAddPopup", "Customer", new { customerId = Model.Id, btnId = "btnRefreshProducts", formId = "customer-form", area = Constants.AreaStore }))" class="k-button"><i class="fa fa-plus"></i> @Loc["Admin.Customers.Customers.ProductPrice.AddNew"]</a>- <input type="submit" id="btnRefreshProducts" style="display: none"/>- </div>- </div>- <div class="note note-info">- @Loc["Admin.Customers.Customers.ProductPrice.Price.Warning"]- </div>-- <script>- $(document).ready(function () {- $('#btnAddNewProduct').magnificPopup({- type: 'ajax',- settings: { cache: false, async: false },- midClick: true,- callbacks: {- parseAjax: function (mfpResponse) {- mfpResponse.data = $('<div></div>').html(mfpResponse.data);- },- ajaxContentAdded: function () {- $('.mfp-wrap').removeAttr('tabindex');- }- }- });- $("#productprice-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("ProductsPrice", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- update: {- url:"@Html.Raw(Url.Action("UpdateProductPrice", "Customer", new { area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("DeleteProductPrice", "Customer", new { area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- data: "Data",- total: "Total",- errors: "Errors",- model: {- id: "Id",- fields: {- ProductName: {editable: false, type: "string" },- Price: {editable: true, type: "number", format:"{0:c2}" },- }- }- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- pageSize: @(adminAreaSettings.DefaultGridPageSize),- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- pageSizes: [@(adminAreaSettings.GridPageSizes)]- },- editable: {- confirmation: false,- mode: "inline"- },- scrollable: false,- columns: [{- field: "ProductName",- title: "@Loc["Admin.Customers.Customers.ProductPrice.ProductName"]",- width: 300,- template: '<a href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#" target="_blank">#=kendo.htmlEncode(ProductName)#</a>'- }, {- field: "Price",- title: "@Loc["Admin.Customers.Customers.ProductPrice.Price"]",- width: 100,- type: "number",-- }, {- command: [{- name: "edit",- text: {- edit: "@Loc["Admin.Common.Edit"]",- update: "@Loc["Admin.Common.Update"]",- cancel: "@Loc["Admin.Common.Cancel"]"} }, {- name: "destroy",- text: "@Loc["Admin.Common.Delete"]"- }],- width: 200- }]- });- });- </script>- <script>- $(document).ready(function () {- $('#btnRefreshProducts').click(function () {- var grid = $("#productprice-grid").data('kendoGrid');- grid.dataSource.read();- return false;- });- });- </script>-}diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtmldeleted file mode 100644index ce52b7ee5..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtml+++ /dev/null@@ -1,125 +0,0 @@-@model CustomerModel-@inject AdminAreaSettings adminAreaSettings-@{- <div class="panel panel-default">- <div class="panel-body">- <div id="review-grid"></div>- </div>- </div>- <style>- .rating {- position: relative;- display: flex;- align-items: center;- width: 83px;- height: 19px;- line-height: 1;- font-size: 20px;- margin: 5px 0;- }-- .rating .rating-ghost {- z-index: 1;- position: absolute;- top: 0;- left: 0;- width: 100%;- height: 19px;- white-space: nowrap;- color: #f0ad4e;- }-- .rating .rating-real {- z-index: 2;- position: absolute;- top: 0;- left: 0;- color: #f0ad4e;- overflow: hidden;- white-space: nowrap;- }- </style>- <script>- $(document).ready(function () {- $("#review-grid").kendoGrid({- dataSource: {- transport: {- read: {- url: "@Html.Raw(Url.Action("ReviewList", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- },- destroy: {- url: "@Html.Raw(Url.Action("ReviewDelete", "Customer", new { area = Constants.AreaStore }))",- type: "POST",- dataType: "json",- data: addAntiForgeryToken- }- },- schema: {- model: {- id: "Id",- fields: {- CreatedOn: { type: "date" }- }- },- data: "Data",- total: "Total",- errors: "Errors"- },- error: function(e) {- display_kendoui_grid_error(e);- this.cancelChanges();- },- pageSize: @(adminAreaSettings.DefaultGridPageSize),- serverPaging: true,- serverFiltering: true,- serverSorting: true- },- autoBind: false,- pageable: {- refresh: true,- pageSizes: [@(adminAreaSettings.GridPageSizes)]- },- editable: {- confirmation: false,- mode: "inline"- },- scrollable: false,- columns: [{- field: "ProductName",- title: "@Loc["Admin.Customers.Customers.Reviews.Product"]",- width: 90,- template: '<a class="k-link" href="@Url.Action("Edit", "Product", new { area = Constants.AreaStore })/#=ProductId#">#=kendo.htmlEncode(ProductName)#</a>'- }, {- field: "Title",- title: "@Loc["Admin.Customers.Customers.Reviews.Title"]",- template: '<a class="k-link" href="@Url.Action("Edit", "ProductReview", new { area = Constants.AreaStore })/#=Id#">#:kendo.htmlEncode(Title)#</a>',- width: 120- }, {- field: "Rating",- title: "@Loc["Admin.Customers.Customers.Reviews.Rating"]",- width: 100,- encoded: false,- template: "#=ratingCellTemplate(Rating)#"- }, {- field: "CreatedOn",- title: "@Loc["Admin.Catalog.ProductReviews.Fields.CreatedOn"]",- width: 150,- type: "date",- format: "{0:G}",- minScreenWidth: 500,- }, {- command: { name: "destroy", text: "@Loc["Admin.Common.Delete"]" },- title: "@Loc["Admin.Common.Delete"]",- width: 100- }]- });- });-- function ratingCellTemplate(rating) {- return '<div class="rating"><div class="rating-ghost">☆☆☆☆☆</div><div class="rating-real" style="width: ' + rating * 20 + '%">★★★★★</div></div>'- }- </script>-}diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.cshtmldeleted file mode 100644index dbb056350..000000000--- a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.cshtml+++ /dev/null@@ -1,80 +0,0 @@-@model CustomerModel-<div asp-validation-summary="All"></div>-<input asp-for="Id" type="hidden"/>-<input asp-for="StoreId" type="hidden" />-@foreach (var item in Model.CustomerGroups.Select((value, index) => new { value, index }))-{- <input type="hidden"- name="CustomerGroups[@item.index]"- value="@item.value" />-}---<admin-tabstrip name="customer-edit" SetTabPos="true" BindGrid="true">- <items>- <tabstrip-item text="@Loc["Admin.Customers.Customers.Info"]" tab-index="0">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabInfo" model="Model"/>- </div>- </content>- </tabstrip-item>- @if (!string.IsNullOrEmpty(Model.Id))- {- <tabstrip-item text="@Loc["Admin.Customers.Customers.Orders"]" tab-index="1">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabOrders" model="Model"/>- </div>- </content>- </tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.Reviews"]" tab-index="2">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabReviews" model="Model"/>- </div>- </content>- </tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.Addresses"]" tab-index="3">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabAddresses" model="Model"/>- </div>- </content>- </tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.ShoppingCartWishlist"]" tab-index="4">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabCurrentShoppingCart" model="Model"/>- <partial name="Partials/CreateOrUpdate.TabCurrentWishlist" model="Model"/>- </div>- </content>- </tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.PersonalizedProduct"]" tab-index="5">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabProduct" model="Model"/>- <partial name="Partials/CreateOrUpdate.TabProductPrice" model="Model"/>- </div>- </content>- </tabstrip-item>- <tabstrip-item text="@Loc["Admin.Customers.Customers.OutOfStockSubscriptions"]" tab-index="6">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabOutOfStockSubscriptions" model="Model"/>- </div>- </content>- </tabstrip-item>- @if (Model.DisplayLoyaltyPointsHistory)- {- <tabstrip-item text="@Loc["Admin.Customers.Customers.LoyaltyPoints"]" tab-index="7">- <content>- <div>- <partial name="Partials/CreateOrUpdate.TabLoyaltyPoints" model="Model"/>- </div>- </content>- </tabstrip-item>- }- }- </items>-</admin-tabstrip>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressDetailsBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressDetailsBottom.cshtmlnew file mode 100644index 000000000..498e44996--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressDetailsBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerAddressModel+<vc:store-widget widget-zone="store_customer_address_details_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressDetailsTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressDetailsTop.cshtmlnew file mode 100644index 000000000..9c1cd1d91--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressDetailsTop.cshtml@@ -0,0 +1,2 @@+@model CustomerAddressModel+<vc:store-widget widget-zone="store_customer_address_details_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressesBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressesBottom.cshtmlnew file mode 100644index 000000000..3bb00726d--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressesBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_addresses_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressesTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressesTop.cshtmlnew file mode 100644index 000000000..44e61f384--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.AddressesTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_addresses_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.BackInStockBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.BackInStockBottom.cshtmlnew file mode 100644index 000000000..8fdd378f8--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.BackInStockBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_back_in_stock_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.BackInStockTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.BackInStockTop.cshtmlnew file mode 100644index 000000000..b8d284006--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.BackInStockTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_back_in_stock_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.DetailsTabs.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.DetailsTabs.cshtmlnew file mode 100644index 000000000..59df57aaf--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.DetailsTabs.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_tabs" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.InfoBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.InfoBottom.cshtmlnew file mode 100644index 000000000..a872e9122--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.InfoBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_info_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.InfoTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.InfoTop.cshtmlnew file mode 100644index 000000000..cbe89a999--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.InfoTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_info_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.LoyaltyPointsBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.LoyaltyPointsBottom.cshtmlnew file mode 100644index 000000000..b65a0a1cd--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.LoyaltyPointsBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_loyalty_points_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.LoyaltyPointsTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.LoyaltyPointsTop.cshtmlnew file mode 100644index 000000000..c22f08f1c--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.LoyaltyPointsTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_loyalty_points_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.OrdersBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.OrdersBottom.cshtmlnew file mode 100644index 000000000..5c2ed1fa7--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.OrdersBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_orders_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.OrdersTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.OrdersTop.cshtmlnew file mode 100644index 000000000..b1e977560--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.OrdersTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_orders_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductBottom.cshtmlnew file mode 100644index 000000000..6c8f19f81--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_product_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductPriceBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductPriceBottom.cshtmlnew file mode 100644index 000000000..290ba34db--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductPriceBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_product_price_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductPriceTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductPriceTop.cshtmlnew file mode 100644index 000000000..8a51d0a04--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductPriceTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_product_price_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductTop.cshtmlnew file mode 100644index 000000000..4adfd5a42--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ProductTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_product_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ReviewsBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ReviewsBottom.cshtmlnew file mode 100644index 000000000..95426ce22--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ReviewsBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_reviews_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ReviewsTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ReviewsTop.cshtmlnew file mode 100644index 000000000..61b63f437--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ReviewsTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_reviews_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ShoppingCartBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ShoppingCartBottom.cshtmlnew file mode 100644index 000000000..0059ce2a8--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ShoppingCartBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_shopping_cart_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ShoppingCartTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ShoppingCartTop.cshtmlnew file mode 100644index 000000000..620eee949--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.ShoppingCartTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_shopping_cart_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.WishlistBottom.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.WishlistBottom.cshtmlnew file mode 100644index 000000000..c01d324c3--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.WishlistBottom.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_wishlist_bottom" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.WishlistTop.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.WishlistTop.cshtmlnew file mode 100644index 000000000..ebd7b81f8--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/WidgetZone.WishlistTop.cshtml@@ -0,0 +1,2 @@+@model CustomerModel+<vc:store-widget widget-zone="store_customer_details_wishlist_top" additional-data="Model"/>diff --git a/src/Web/Grand.Web.Store/Controllers/CustomerController.cs b/src/Web/Grand.Web.Store/Controllers/CustomerController.csindex 22797b69b..b6d8cf563 100644--- a/src/Web/Grand.Web.Store/Controllers/CustomerController.cs+++ b/src/Web/Grand.Web.Store/Controllers/CustomerController.cs@@ -1,30 +1,14 @@-using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Interfaces.Checkout.Orders;-using Grand.Business.Core.Interfaces.Common.Addresses;using Grand.Business.Core.Interfaces.Common.Directory;-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Business.Core.Interfaces.Customers;-using Grand.Business.Core.Interfaces.Marketing.Customers;-using Grand.Business.Core.Interfaces.Messages;+using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Utilities.Customers;-using Grand.Domain.Catalog;-using Grand.Domain.Common;using Grand.Domain.Customers;-using Grand.Domain.Permissions;-using Grand.Domain.Tax;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;-using Grand.SharedKernel;-using Grand.SharedKernel.Extensions;-using Grand.Web.AdminShared.Extensions;+using Grand.Web.AdminShared.Controllers;using Grand.Web.AdminShared.Interfaces;-using Grand.Web.AdminShared.Models.Catalog;using Grand.Web.AdminShared.Models.Customers;-using Grand.Web.AdminShared.Models.Orders;-using Grand.Web.Common.DataSource;using Grand.Web.Common.Filters;-using Grand.Web.Common.Models;-using Grand.Web.Common.Security.Authorization;+using Grand.Web.Store.Extensions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Controllers;using Microsoft.AspNetCore.Mvc.Filters;@@ -32,86 +16,45 @@ using Microsoft.AspNetCore.Mvc.Filters;namespace Grand.Web.Store.Controllers;/// <summary>-/// Lets a store manager manage the registered customers that belong to his own store.-/// The customer is always forced into the 'Registered' group and tied to the current store; the manager-/// never sees or sets the role, owner, vendor, staff-store or store fields, and the customer-notes /-/// documents tabs are not exposed. Export and impersonation are intentionally not available here.+/// Lets a store manager manage the registered customers that belong to his own store. See+/// BaseCustomerController for the shared surface; the three members below are the genuine+/// Store-only pieces that don't belong in AdminShared: the per-store feature gate, the page+/// shown when that feature is off, and the constraint-forcing override of+/// BaseCustomerController.ApplyPostConstraints./// </summary>-[PermissionAuthorize(PermissionSystemName.Customers)]-public class CustomerController : BaseStoreController+[AuthorizeStore]+[Area(Constants.AreaStore)]+[AuthorizeMenu]+public class CustomerController(+ Grand.Business.Core.Interfaces.Customers.ICustomerService customerService,+ ICustomerViewModelService customerViewModelService,+ Grand.Business.Core.Interfaces.Customers.ICustomerManagerService customerManagerService,+ Grand.Business.Core.Interfaces.Marketing.Customers.ICustomerProductService customerProductService,+ Grand.Business.Core.Interfaces.Catalog.Products.IProductReviewService productReviewService,+ IProductReviewViewModelService productReviewViewModelService,+ IProductViewModelService productViewModelService,+ Grand.Business.Core.Interfaces.Customers.ICustomerAttributeParser customerAttributeParser,+ Grand.Business.Core.Interfaces.Customers.ICustomerAttributeService customerAttributeService,+ Grand.Business.Core.Interfaces.Common.Addresses.IAddressAttributeParser addressAttributeParser,+ Grand.Business.Core.Interfaces.Common.Addresses.IAddressAttributeService addressAttributeService,+ Grand.Business.Core.Interfaces.Messages.IMessageProviderService messageProviderService,+ IGroupService groupService,+ Grand.Business.Core.Interfaces.Common.Localization.ITranslationService translationService,+ IContextAccessor contextAccessor,+ CustomerSettings customerSettings,+ IAdminDataScope<Customer> scope,+ CustomerConfig customerConfig)+ : BaseCustomerController(customerService, customerViewModelService, customerManagerService,+ customerProductService, productReviewService, productReviewViewModelService, productViewModelService,+ customerAttributeParser, customerAttributeService, addressAttributeParser, addressAttributeService,+ messageProviderService, groupService, translationService, contextAccessor, customerSettings, scope){- #region Constructors-- public CustomerController(- ICustomerService customerService,- ICustomerViewModelService customerViewModelService,- ICustomerManagerService customerManagerService,- ICustomerProductService customerProductService,- IProductReviewService productReviewService,- IProductReviewViewModelService productReviewViewModelService,- IProductViewModelService productViewModelService,- ICustomerAttributeParser customerAttributeParser,- ICustomerAttributeService customerAttributeService,- IAddressAttributeParser addressAttributeParser,- IAddressAttributeService addressAttributeService,- IMessageProviderService messageProviderService,- IGroupService groupService,- ITranslationService translationService,- IContextAccessor contextAccessor,- CustomerSettings customerSettings,- CustomerConfig customerConfig)- {- _customerService = customerService;- _customerViewModelService = customerViewModelService;- _customerManagerService = customerManagerService;- _customerProductService = customerProductService;- _productReviewService = productReviewService;- _productReviewViewModelService = productReviewViewModelService;- _productViewModelService = productViewModelService;- _customerAttributeParser = customerAttributeParser;- _customerAttributeService = customerAttributeService;- _addressAttributeParser = addressAttributeParser;- _addressAttributeService = addressAttributeService;- _messageProviderService = messageProviderService;- _groupService = groupService;- _translationService = translationService;- _contextAccessor = contextAccessor;- _customerSettings = customerSettings;- _customerConfig = customerConfig;- }-- #endregion-- #region Fields-- private readonly ICustomerService _customerService;- private readonly ICustomerViewModelService _customerViewModelService;- private readonly ICustomerManagerService _customerManagerService;- private readonly ICustomerProductService _customerProductService;- private readonly IProductReviewService _productReviewService;- private readonly IProductReviewViewModelService _productReviewViewModelService;- private readonly IProductViewModelService _productViewModelService;- private readonly ICustomerAttributeParser _customerAttributeParser;- private readonly ICustomerAttributeService _customerAttributeService;- private readonly IAddressAttributeParser _addressAttributeParser;- private readonly IAddressAttributeService _addressAttributeService;- private readonly IMessageProviderService _messageProviderService;- private readonly IGroupService _groupService;- private readonly ITranslationService _translationService;- private readonly IContextAccessor _contextAccessor;- private readonly CustomerSettings _customerSettings;- private readonly CustomerConfig _customerConfig;-- #endregion-- #region Per-store gate-- //managing customers from the store panel only makes sense when customer identity is scoped per store- //(Customer:RegisterCustomersPerStore). When it's off the whole controller is disabled and every action- //is routed to the PerStoreDisabled page that explains how to enable the setting.+ //managing customers from the store panel only makes sense when customer identity is scoped per+ //store (Customer:RegisterCustomersPerStore). When it's off the whole controller is disabled and+ //every action is routed to the PerStoreDisabled page that explains how to enable the setting.public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){- if (!_customerConfig.RegisterCustomersPerStore &&+ if (!customerConfig.RegisterCustomersPerStore &&context.ActionDescriptor is ControllerActionDescriptor { ActionName: not nameof(PerStoreDisabled) }){context.Result = RedirectToAction(nameof(PerStoreDisabled));@@ -121,786 +64,21 @@ public class CustomerController : BaseStoreControllerawait next();}- #endregion-- #region Utilities+ /// <summary>Shown instead of the panel when per-store customer identity is disabled.</summary>+ public IActionResult PerStoreDisabled() => View();- private string CurrentStoreId => _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;-- /// <summary>- /// Loads a customer only when it is a non-deleted, registered customer of the current store.- /// Returns null otherwise so callers can deny access.- /// </summary>- private async Task<Customer> GetStoreCustomer(string id)+ /// <summary>Forces the store-scoped, registered-only constraints on the posted model+ /// regardless of what was sent, so the shared insert/update path in BaseCustomerController can+ /// never assign a foreign store, role, or ownership. See CustomerControllerTests's+ /// ApplyPostConstraints_CraftedPost_CannotSmuggleOwnershipFields for the exact contract.</summary>+ protected override async Task ApplyPostConstraints(CustomerModel model){- var customer = await _customerService.GetCustomerById(id);- if (customer == null || customer.Deleted || customer.StoreId != CurrentStoreId)- return null;- if (!await _groupService.IsRegistered(customer))- return null;- return customer;- }-- /// <summary>- /// Forces the store-scoped, registered-only constraints on the posted model regardless of what was sent,- /// so the reused AdminShared insert/update path can never assign a foreign store, role or ownership.- /// </summary>- private async Task ApplyStoreConstraints(CustomerModel model)- {- model.StoreId = CurrentStoreId;+ model.StoreId = scope.DefaultStoreId;model.Owner = "";model.VendorId = "";model.StaffStoreId = "";model.SeId = "";- var registered = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered);+ var registered = await groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered);model.CustomerGroups = registered != null ? new[] { registered.Id } : Array.Empty<string>();}-- private async Task<IList<CustomAttribute>> ParseCustomCustomerAttributes(IList<CustomAttributeModel> model)- {- ArgumentNullException.ThrowIfNull(model);-- var customAttributes = new List<CustomAttribute>();- var customerAttributes = await _customerAttributeService.GetAllCustomerAttributes();- foreach (var attribute in customerAttributes)- {- switch (attribute.AttributeControlTypeId)- {- case AttributeControlType.DropdownList:- case AttributeControlType.RadioList:- {- var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customAttributes = _customerAttributeParser- .AddCustomerAttribute(customAttributes, attribute, ctrlAttributes).ToList();- }- break;- case AttributeControlType.Checkboxes:- {- var cblAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- foreach (var item in cblAttributes.Split(',').Where(x => !string.IsNullOrEmpty(x)))- customAttributes = _customerAttributeParser- .AddCustomerAttribute(customAttributes, attribute, item).ToList();- }- break;- case AttributeControlType.ReadonlyCheckboxes:- {- foreach (var selectedAttributeId in attribute.CustomerAttributeValues- .Where(v => v.IsPreSelected).Select(v => v.Id).ToList())- customAttributes = _customerAttributeParser- .AddCustomerAttribute(customAttributes, attribute, selectedAttributeId).ToList();- }- break;- case AttributeControlType.TextBox:- case AttributeControlType.MultilineTextbox:- {- var ctrlAttributes = model.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customAttributes = _customerAttributeParser- .AddCustomerAttribute(customAttributes, attribute, ctrlAttributes.Trim()).ToList();- }- break;- default:- break;- }- }-- return customAttributes;- }-- #endregion-- #region Customers-- public IActionResult Index()- {- return RedirectToAction("List");- }-- [PermissionAuthorizeAction(PermissionActionName.List)]- public async Task<IActionResult> List()- {- var model = new CustomerListModel();- return View(model);- }-- /// <summary>- /// Shown instead of the panel when per-store customer identity is disabled (see the gate below).- /// </summary>- public IActionResult PerStoreDisabled()- {- return View();- }-- [PermissionAuthorizeAction(PermissionActionName.List)]- [HttpPost]- public async Task<IActionResult> CustomerList(DataSourceRequest command, CustomerListModel model)- {- //store managers only ever see the registered customers of their own store- var registered = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Registered);- var (customerModelList, totalCount) = await _customerViewModelService.PrepareCustomerList(model,- registered != null ? [registered.Id] : [], null, command.Page, command.PageSize, CurrentStoreId);- var gridModel = new DataSourceResult {- Data = customerModelList.ToList(),- Total = totalCount- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Create)]- public async Task<IActionResult> Create()- {- var model = new CustomerModel();- await _customerViewModelService.PrepareCustomerModel(model, null, false);- await ApplyStoreConstraints(model);- model.Active = true;- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Create)]- [HttpPost]- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]- public async Task<IActionResult> Create(CustomerModel model, bool continueEditing)- {- await ApplyStoreConstraints(model);-- if (ModelState.IsValid)- {- model.Attributes = await ParseCustomCustomerAttributes(model.SelectedAttributes);- var customer = await _customerViewModelService.InsertCustomerModel(model);-- //password- if (!string.IsNullOrWhiteSpace(model.Password))- {- var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat,- model.Password);- await _customerManagerService.ChangePassword(changePassRequest, customer.StoreId);- }-- Success(_translationService.GetResource("Admin.Customers.Customers.Added"));- return continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List");- }-- //If we got this far, something failed, redisplay form- await _customerViewModelService.PrepareCustomerModel(model, null, true);- await ApplyStoreConstraints(model);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- public async Task<IActionResult> Edit(string id)- {- var customer = await GetStoreCustomer(id);- if (customer == null)- return RedirectToAction("List");-- var model = new CustomerModel();- await _customerViewModelService.PrepareCustomerModel(model, customer, false);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]- public async Task<IActionResult> Edit(CustomerModel model, bool continueEditing)- {- var customer = await GetStoreCustomer(model.Id);- if (customer == null)- return RedirectToAction("List");-- await ApplyStoreConstraints(model);-- if (ModelState.IsValid)- try- {- model.Attributes = await ParseCustomCustomerAttributes(model.SelectedAttributes);- customer = await _customerViewModelService.UpdateCustomerModel(customer, model);- //change password- if (!string.IsNullOrWhiteSpace(model.Password))- {- var changePassRequest = new ChangePasswordRequest(model.Email,- _customerSettings.DefaultPasswordFormat, model.Password);- await _customerManagerService.ChangePassword(changePassRequest, customer.StoreId);- }-- Success(_translationService.GetResource("Admin.Customers.Customers.Updated"));- if (continueEditing)- {- await SaveSelectedTabIndex();- return RedirectToAction("Edit", new { id = customer.Id });- }-- return RedirectToAction("List");- }- catch (GrandException exc)- {- Error(exc.Message);- }-- //If we got this far, something failed, redisplay form- await _customerViewModelService.PrepareCustomerModel(model, customer, true);- await ApplyStoreConstraints(model);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Delete)]- [HttpPost]- public async Task<IActionResult> Delete(string id)- {- var customer = await GetStoreCustomer(id);- if (customer == null)- return RedirectToAction("List");-- if (customer.Id == _contextAccessor.WorkContext.CurrentCustomer.Id)- {- Error(_translationService.GetResource("Admin.Customers.Customers.NoSelfDelete"));- return RedirectToAction("List");- }-- try- {- if (ModelState.IsValid)- {- await _customerViewModelService.DeleteCustomer(customer);- Success(_translationService.GetResource("Admin.Customers.Customers.Deleted"));- return RedirectToAction("List");- }-- Error(ModelState);- return RedirectToAction("Edit", new { id = customer.Id });- }- catch (GrandException exc)- {- Error(exc.Message);- return RedirectToAction("Edit", new { id = customer.Id });- }- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> MarkVatNumberAsValid(string id)- {- var customer = await GetStoreCustomer(id);- if (customer == null)- return RedirectToAction("List");-- await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.VatNumberStatusId,- (int)VatNumberStatus.Valid);-- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> MarkVatNumberAsInvalid(string id)- {- var customer = await GetStoreCustomer(id);- if (customer == null)- return RedirectToAction("List");-- await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.VatNumberStatusId,- (int)VatNumberStatus.Invalid);-- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> SendWelcomeMessage(string id)- {- var customer = await GetStoreCustomer(id);- if (customer == null)- return RedirectToAction("List");-- await _messageProviderService.SendCustomerWelcomeMessage(customer, _contextAccessor.StoreContext.CurrentStore,- _contextAccessor.WorkContext.WorkingLanguage.Id);-- Success(_translationService.GetResource("Admin.Customers.Customers.SendWelcomeMessage.Success"));- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ReSendActivationMessage(string id)- {- var customer = await GetStoreCustomer(id);- if (customer == null)- return RedirectToAction("List");-- await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.AccountActivationToken,- Guid.NewGuid().ToString());- await _messageProviderService.SendCustomerEmailValidationMessage(customer,- _contextAccessor.StoreContext.CurrentStore, _contextAccessor.WorkContext.WorkingLanguage.Id);-- Success(_translationService.GetResource("Admin.Customers.Customers.ReSendActivationMessage.Success"));- return RedirectToAction("Edit", new { id = customer.Id });- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> SendEmail(CustomerModel.SendEmailModel model)- {- var customer = await GetStoreCustomer(model.Id);- if (customer == null)- return RedirectToAction("List");-- try- {- if (string.IsNullOrWhiteSpace(customer.Email))- throw new GrandException("Customer email is empty");- if (!CommonHelper.IsValidEmail(customer.Email))- throw new GrandException("Customer email is not valid");- if (string.IsNullOrWhiteSpace(model.Subject))- throw new GrandException("Email subject is empty");- if (string.IsNullOrWhiteSpace(model.Body))- throw new GrandException("Email body is empty");-- await _customerViewModelService.SendEmail(customer, model);- Success(_translationService.GetResource("Admin.Customers.Customers.SendEmail.Queued"));- }- catch (GrandException exc)- {- Error(exc.Message);- }-- return RedirectToAction("Edit", new { id = customer.Id });- }-- #endregion-- #region Loyalty points history-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> LoyaltyPointsHistorySelect(string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- throw new ArgumentException("No customer found with the specified id");-- var model = (await _customerViewModelService.PrepareLoyaltyPointsHistoryModel(customerId)).ToList();- var gridModel = new DataSourceResult {- Data = model,- Total = model.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> LoyaltyPointsHistoryAdd(string customerId, string storeId,- int addLoyaltyPointsValue, string addLoyaltyPointsMessage)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new { Result = false });-- await _customerViewModelService.InsertLoyaltyPointsHistory(customer, CurrentStoreId, addLoyaltyPointsValue,- addLoyaltyPointsMessage);-- return Json(new { Result = true });- }-- #endregion-- #region Addresses-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> AddressesSelect(string customerId, DataSourceRequest command)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- var addresses = (await _customerViewModelService.PrepareAddressModel(customer)).ToList();- var gridModel = new DataSourceResult {- Data = addresses,- Total = addresses.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> AddressDelete(string id, string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- var address = customer.Addresses.FirstOrDefault(a => a.Id == id);- if (address == null)- return Content("No customer found with the specified id");- if (ModelState.IsValid)- {- await _customerViewModelService.DeleteAddress(customer, address);- return new JsonResult("");- }-- return ErrorForKendoGridJson(ModelState);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> AddressCreate(string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return RedirectToAction("List");-- var model = new CustomerAddressModel();- await _customerViewModelService.PrepareAddressModel(model, null, customer, false);-- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> AddressCreate(CustomerAddressModel model)- {- var customer = await GetStoreCustomer(model.CustomerId);- if (customer == null)- return RedirectToAction("List");-- if (ModelState.IsValid)- {- var customAttributes =- await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);- var address = await _customerViewModelService.InsertAddressModel(customer, model, customAttributes);- Success(_translationService.GetResource("Admin.Customers.Customers.Addresses.Added"));- return RedirectToAction("AddressEdit", new { addressId = address.Id, customerId = model.CustomerId });- }-- await _customerViewModelService.PrepareAddressModel(model, null, customer, true);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> AddressEdit(string addressId, string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return RedirectToAction("List");-- var address = customer.Addresses.FirstOrDefault(x => x.Id == addressId);- if (address == null)- return RedirectToAction("Edit", new { id = customer.Id });-- var model = new CustomerAddressModel();- await _customerViewModelService.PrepareAddressModel(model, address, customer, false);- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> AddressEdit(CustomerAddressModel model)- {- var customer = await GetStoreCustomer(model.CustomerId);- if (customer == null)- return RedirectToAction("List");-- var address = customer.Addresses.FirstOrDefault(x => x.Id == model.Address.Id);- if (address == null)- return RedirectToAction("Edit", new { id = customer.Id });-- if (ModelState.IsValid)- {- var customAttributes =- await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);- await _customerViewModelService.UpdateAddressModel(customer, address, model, customAttributes);- Success(_translationService.GetResource("Admin.Customers.Customers.Addresses.Updated"));- return RedirectToAction("AddressEdit", new { addressId = model.Address.Id, customerId = model.CustomerId });- }-- await _customerViewModelService.PrepareAddressModel(model, address, customer, true);- return View(model);- }-- #endregion-- #region Orders-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> OrderList(string customerId, DataSourceRequest command,- [FromServices] IOrderViewModelService orderViewModelService)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var model = new OrderListModel {- CustomerId = customerId,- StoreId = CurrentStoreId- };-- var (orderModels, totalCount) =- await orderViewModelService.PrepareOrderModel(model, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = orderModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> OrderDetails(string orderId,- [FromServices] IOrderService orderService, [FromServices] IOrderViewModelService orderViewModelService)- {- var order = await orderService.GetOrderById(orderId);- if (order == null || order.StoreId != CurrentStoreId)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var ordermodel = new OrderModel();- await orderViewModelService.PrepareOrderDetailsModel(ordermodel, order);- var gridModel = new DataSourceResult {- Data = ordermodel.Items,- Total = ordermodel.Items.Count- };-- return Json(gridModel);- }-- #endregion-- #region Reviews-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> ReviewList(string customerId, DataSourceRequest command)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var productReviews = await _productReviewService.GetAllProductReviews(customerId, null,- null, null, "", CurrentStoreId, "", command.Page - 1, command.PageSize);- var items = new List<ProductReviewModel>();- foreach (var x in productReviews)- {- var m = new ProductReviewModel();- await _productViewModelService.PrepareProductReviewModel(m, x, false, true);- items.Add(m);- }-- var gridModel = new DataSourceResult {- Data = items,- Total = productReviews.TotalCount- };- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ReviewDelete(string id)- {- var productReview = await _productReviewService.GetProductReviewById(id);- if (productReview == null || productReview.StoreId != CurrentStoreId)- throw new ArgumentException("No review found with the specified id", nameof(id));-- await _productReviewViewModelService.DeleteProductReview(productReview);- return new JsonResult("");- }-- #endregion-- #region Current shopping cart / wishlist-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> GetCartList(string customerId, int cartTypeId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var cart = await _customerViewModelService.PrepareShoppingCartItemModel(customerId, cartTypeId);- var gridModel = new DataSourceResult {- Data = cart,- Total = cart.Count- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> UpdateCart(string id, string customerId, double? unitPriceValue)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- var warnings = await _customerViewModelService.UpdateCart(customer, id, unitPriceValue);- if (warnings.Any())- return ErrorForKendoGridJson(string.Join(",", warnings));-- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> DeleteCart(string id, string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- throw new ArgumentException("No customer found with the specified id", nameof(customerId));-- await _customerViewModelService.DeleteCart(customer, id);- return new JsonResult("");- }-- #endregion-- #region Customer Product Personalize / Price-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> ProductsPrice(DataSourceRequest command, string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var (productPriceModels, totalCount) =- await _customerViewModelService.PrepareProductPriceModel(customerId, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = productPriceModels.ToList(),- Total = totalCount- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> PersonalizedProducts(DataSourceRequest command, string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var (productModels, totalCount) =- await _customerViewModelService.PreparePersonalizedProducts(customerId, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = productModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- public async Task<IActionResult> ProductAddPopup(string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return RedirectToAction("List");-- var model = await _customerViewModelService.PrepareCustomerModelAddProductModel();- return View(model);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command, CustomerModel.AddProductModel model)- {- var products = await _customerViewModelService.PrepareProductModel(model, command.Page, command.PageSize);- var gridModel = new DataSourceResult {- Data = products.products.ToList(),- Total = products.totalCount- };-- return Json(gridModel);- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> ProductAddPopup(string customerId, bool personalized,- CustomerModel.AddProductModel model)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Content("");-- if (model.SelectedProductIds != null)- await _customerViewModelService.InsertCustomerAddProductModel(customerId, personalized, model);- return Content("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> UpdateProductPrice(CustomerModel.ProductPriceModel model)- {- var productPrice = await _customerProductService.GetCustomerProductPriceById(model.Id);- if (productPrice == null || await GetStoreCustomer(productPrice.CustomerId) == null)- return new JsonResult("");-- await _customerViewModelService.UpdateProductPrice(model);- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> DeleteProductPrice(string id)- {- var productPrice = await _customerProductService.GetCustomerProductPriceById(id);- if (productPrice == null || await GetStoreCustomer(productPrice.CustomerId) == null)- return new JsonResult("");-- //delete the already-resolved entity to avoid a redundant reload / TOCTOU throw- await _customerProductService.DeleteCustomerProductPrice(productPrice);- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> UpdatePersonalizedProduct(CustomerModel.ProductModel model)- {- var customerProduct = await _customerProductService.GetCustomerProduct(model.Id);- if (customerProduct == null || await GetStoreCustomer(customerProduct.CustomerId) == null)- return new JsonResult("");-- await _customerViewModelService.UpdatePersonalizedProduct(model);- return new JsonResult("");- }-- [PermissionAuthorizeAction(PermissionActionName.Edit)]- [HttpPost]- public async Task<IActionResult> DeletePersonalizedProduct(string id)- {- var customerProduct = await _customerProductService.GetCustomerProduct(id);- if (customerProduct == null || await GetStoreCustomer(customerProduct.CustomerId) == null)- return new JsonResult("");-- //delete the already-resolved entity to avoid a redundant reload / TOCTOU throw- await _customerProductService.DeleteCustomerProduct(customerProduct);- return new JsonResult("");- }-- #endregion-- #region Out of stock subscriptions-- [PermissionAuthorizeAction(PermissionActionName.Preview)]- [HttpPost]- public async Task<IActionResult> OutOfStockSubscriptionList(DataSourceRequest command, string customerId)- {- var customer = await GetStoreCustomer(customerId);- if (customer == null)- return Json(new DataSourceResult { Data = null, Total = 0 });-- var (outOfStockSubscriptionModels, totalCount) =- await _customerViewModelService.PrepareOutOfStockSubscriptionModel(customerId, command.Page,- command.PageSize);- var gridModel = new DataSourceResult {- Data = outOfStockSubscriptionModels.ToList(),- Total = totalCount- };- return Json(gridModel);- }-- #endregion}