Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Allow editing Store Id field on Customer in Grand.Web.Admin (#715)

Krzysztof Pajak5daa442d512c
diff --git a/Directory.Packages.props b/Directory.Packages.props
index bfb6469e1..8b8e6d5e6 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -5,16 +5,17 @@
<ItemGroup>
<PackageVersion Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.5.0" />
<PackageVersion Include="ExcelMapper" Version="6.0.641" />
- <PackageVersion Include="Microsoft.AspNetCore.Http" Version="2.3.10" />
- <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.8" />
+ <PackageVersion Include="MessagePack" Version="2.5.302" />
+ <PackageVersion Include="Microsoft.AspNetCore.Http" Version="2.3.11" />
+ <PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
<PackageVersion Include="Microsoft.FeatureManagement.AspNetCore" Version="4.5.0" />
- <PackageVersion Include="Scalar.AspNetCore" Version="2.14.14" />
+ <PackageVersion Include="Scalar.AspNetCore" Version="2.16.3" />
<PackageVersion Include="Scryber.Core" Version="9.5.0" />
<PackageVersion Include="Scryber.Core.OpenType" Version="9.2.0" />
<PackageVersion Include="MailKit" Version="4.17.0" />
- <PackageVersion Include="AWSSDK.Core" Version="4.0.7.5" />
- <PackageVersion Include="AWSSDK.S3" Version="4.0.24" />
- <PackageVersion Include="Azure.Storage.Blobs" Version="12.28.0" />
+ <PackageVersion Include="AWSSDK.Core" Version="4.0.9.2" />
+ <PackageVersion Include="AWSSDK.S3" Version="4.0.24.4" />
+ <PackageVersion Include="Azure.Storage.Blobs" Version="12.29.0" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.1.12" />
<PackageVersion Include="SkiaSharp" Version="3.119.4" />
<PackageVersion Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="3.119.4" />
@@ -25,23 +26,23 @@
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
<PackageVersion Include="GoogleAuthenticator" Version="3.2.0" />
<PackageVersion Include="Microsoft.Azure.AppConfiguration.AspNetCore" Version="8.5.0" />
- <PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" />
- <PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.8" />
- <PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.8" />
- <PackageVersion Include="Microsoft.Extensions.DependencyModel" Version="10.0.8" />
+ <PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
+ <PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.9" />
+ <PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="10.0.9" />
+ <PackageVersion Include="Microsoft.Extensions.DependencyModel" Version="10.0.9" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="5.3.0" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.3.0" />
<PackageVersion Include="MediatR" Version="12.5.0" />
<PackageVersion Include="Scrutor" Version="7.0.0" />
<PackageVersion Include="StackExchange.Redis" Version="2.13.17" />
<PackageVersion Include="FluentValidation" Version="12.1.1" />
- <PackageVersion Include="Microsoft.AspNetCore.JsonPatch.SystemTextJson" Version="10.0.8" />
- <PackageVersion Include="Microsoft.AspNetCore.Authentication.Facebook" Version="10.0.8" />
- <PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="10.0.8" />
+ <PackageVersion Include="Microsoft.AspNetCore.JsonPatch.SystemTextJson" Version="10.0.9" />
+ <PackageVersion Include="Microsoft.AspNetCore.Authentication.Facebook" Version="10.0.9" />
+ <PackageVersion Include="Microsoft.AspNetCore.Authentication.Google" Version="10.0.9" />
<PackageVersion Include="Braintree" Version="5.39.0" />
- <PackageVersion Include="System.Configuration.ConfigurationManager" Version="10.0.8" />
+ <PackageVersion Include="System.Configuration.ConfigurationManager" Version="10.0.9" />
<PackageVersion Include="System.Linq.Dynamic.Core" Version="1.7.2" />
- <PackageVersion Include="System.Security.Cryptography.Xml" Version="10.0.8" />
+ <PackageVersion Include="System.Security.Cryptography.Xml" Version="10.0.9" />
<PackageVersion Include="System.Xml.XPath.XmlDocument" Version="4.7.0" />
<PackageVersion Include="Stripe.net" Version="51.1.0" />
<PackageVersion Include="elFinder.Net.AspNetCore" Version="1.5.0" />
@@ -51,23 +52,23 @@
<PackageVersion Include="Azure.Extensions.AspNetCore.DataProtection.Keys" Version="1.6.3" />
<PackageVersion Include="Azure.Identity" Version="1.21.0" />
<PackageVersion Include="Flurl.Http" Version="4.0.2" />
- <PackageVersion Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="10.0.8" />
+ <PackageVersion Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="10.0.9" />
<PackageVersion Include="NetEscapades.AspNetCore.SecurityHeaders" Version="1.3.1" />
<PackageVersion Include="Wangkanai.Detection" Version="8.20.0" />
- <PackageVersion Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="10.0.8" />
+ <PackageVersion Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="10.0.9" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageVersion Include="Moq" Version="4.20.72" />
<PackageVersion Include="MSTest.TestAdapter" Version="4.2.3" />
<PackageVersion Include="MSTest.TestFramework" Version="4.2.3" />
<PackageVersion Include="coverlet.collector" Version="10.0.1" />
<PackageVersion Include="NUnit" Version="4.6.1" />
- <PackageVersion Include="Verify.MSTest" Version="31.19.0" />
- <PackageVersion Include="Aspire.Hosting.AppHost" Version="13.4.1" />
- <PackageVersion Include="Aspire.Hosting.MongoDB" Version="13.4.1" />
- <PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="10.6.0" />
- <PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="10.6.0" />
- <PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.15.3" />
- <PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.15.3" />
+ <PackageVersion Include="Verify.MSTest" Version="31.19.1" />
+ <PackageVersion Include="Aspire.Hosting.AppHost" Version="13.4.3" />
+ <PackageVersion Include="Aspire.Hosting.MongoDB" Version="13.4.3" />
+ <PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="10.7.0" />
+ <PackageVersion Include="Microsoft.Extensions.ServiceDiscovery" Version="10.7.0" />
+ <PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.16.0" />
+ <PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.16.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.15.2" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.15.1" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.15.1" />
@@ -75,7 +76,7 @@
<PackageVersion Include="Aspire.Hosting.Orchestration.$(NETCoreSdkRuntimeIdentifier)" Version="9.0.0" />
</ItemGroup>
<ItemGroup>
- <PackageVersion Update="Aspire.Dashboard.Sdk.win-x64" Version="13.4.1" />
- <PackageVersion Update="Aspire.Hosting.Orchestration.win-x64" Version="13.4.1" />
+ <PackageVersion Update="Aspire.Dashboard.Sdk.win-x64" Version="13.4.3" />
+ <PackageVersion Update="Aspire.Hosting.Orchestration.win-x64" Version="13.4.3" />
</ItemGroup>
</Project>
\ No newline at end of file
diff --git a/src/Aspire/Aspire.AppHost/Aspire.AppHost.csproj b/src/Aspire/Aspire.AppHost/Aspire.AppHost.csproj
index d13247fb5..550a7d6b8 100644
--- a/src/Aspire/Aspire.AppHost/Aspire.AppHost.csproj
+++ b/src/Aspire/Aspire.AppHost/Aspire.AppHost.csproj
@@ -20,6 +20,7 @@
<ItemGroup>
<PackageReference Include="Aspire.Dashboard.Sdk.$(NETCoreSdkRuntimeIdentifier)" />
<PackageReference Include="Aspire.Hosting.Orchestration.$(NETCoreSdkRuntimeIdentifier)" />
+ <PackageReference Include="MessagePack" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Web\Grand.Web.Admin\Grand.Web.Admin.csproj" />
diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs
index 0695644ba..ea0ad56a8 100644
--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs
+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs
@@ -485,6 +485,7 @@ public class CustomerService : ICustomerService
.Set(x => x.SeId, customer.SeId)
.Set(x => x.OwnerId, customer.OwnerId)
.Set(x => x.StaffStoreId, customer.StaffStoreId)
+ .Set(x => x.StoreId, customer.StoreId)
.Set(x => x.Attributes, customer.Attributes);
await _customerRepository.UpdateOneAsync(x => x.Id == customer.Id, update);
diff --git a/src/Plugins/Authentication.Facebook/Authentication.Facebook.csproj b/src/Plugins/Authentication.Facebook/Authentication.Facebook.csproj
index d3de7b90d..3089521e3 100644
--- a/src/Plugins/Authentication.Facebook/Authentication.Facebook.csproj
+++ b/src/Plugins/Authentication.Facebook/Authentication.Facebook.csproj
@@ -21,7 +21,7 @@
<Target Name="CopyFile" AfterTargets="AfterBuild">
<ItemGroup>
- <CopyFiles Include="$(NuGetPackageRoot)\microsoft.aspnetcore.authentication.facebook\10.0.8\lib\net10.0\*.dll" />
+ <CopyFiles Include="$(NuGetPackageRoot)\microsoft.aspnetcore.authentication.facebook\10.0.9\lib\net10.0\*.dll" />
</ItemGroup>
<Copy SourceFiles="@(CopyFiles)" DestinationFolder="..\..\Web\Grand.Web\Plugins\Authentication.Facebook\" />
</Target>
diff --git a/src/Plugins/Authentication.Google/Authentication.Google.csproj b/src/Plugins/Authentication.Google/Authentication.Google.csproj
index 1db5fedda..07847958b 100644
--- a/src/Plugins/Authentication.Google/Authentication.Google.csproj
+++ b/src/Plugins/Authentication.Google/Authentication.Google.csproj
@@ -20,7 +20,7 @@
<Target Name="CopyFile" AfterTargets="AfterBuild">
<ItemGroup>
- <CopyFiles Include="$(NuGetPackageRoot)\microsoft.aspnetcore.authentication.google\10.0.8\lib\net10.0\*.dll" />
+ <CopyFiles Include="$(NuGetPackageRoot)\microsoft.aspnetcore.authentication.google\10.0.9\lib\net10.0\*.dll" />
</ItemGroup>
<Copy SourceFiles="@(CopyFiles)" DestinationFolder="..\..\Web\Grand.Web\Plugins\Authentication.Google\" />
</Target>
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
index 86ec7f3d8..8b6ba3239 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
@@ -290,9 +290,12 @@ public class CustomerServiceTests
await _repository.InsertAsync(customer);
//Act
customer.AdminComment = "test";
+ customer.StoreId = "store-1";
await _customerService.UpdateCustomerInAdminPanel(customer);
//Assert
- Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).AdminComment);
+ var updated = _repository.Table.FirstOrDefault(x => x.Id == customer.Id);
+ Assert.AreEqual("test", updated.AdminComment);
+ Assert.AreEqual("store-1", updated.StoreId);
}
[TestMethod]
diff --git a/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs
new file mode 100644
index 000000000..beda3bb22
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Services/CustomerViewModelServiceTests.cs
@@ -0,0 +1,636 @@
+using Grand.Business.Core.Interfaces.Authentication;
+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.Stores;
+using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Interfaces.Marketing.Contacts;
+using Grand.Business.Core.Interfaces.Marketing.Customers;
+using Grand.Business.Core.Interfaces.Marketing.Newsletters;
+using Grand.Business.Core.Interfaces.Storage;
+using Grand.Domain;
+using Grand.Domain.Catalog;
+using Grand.Domain.Common;
+using Grand.Domain.Customers;
+using Grand.Domain.Media;
+using Grand.Domain.Orders;
+using Grand.Domain.Tax;
+using Grand.Domain.Vendors;
+using Grand.Domain.Messages;
+using Grand.Infrastructure;
+using Grand.Web.AdminShared.Models.Customers;
+using Grand.Web.AdminShared.Services;
+using Grand.Web.Common.Localization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc.Rendering;
+using Moq;
+using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace Grand.Web.Admin.Tests.Services;
+
+[TestClass]
+public class CustomerViewModelServiceTests
+{
+ private const string CurrentStoreId = "store-current";
+ private const string CurrentCustomerId = "current-user";
+
+ private Mock<ICustomerService> _customerServiceMock;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<IStoreService> _storeServiceMock;
+ private Mock<ICustomerTagService> _customerTagServiceMock;
+ private Mock<IVendorService> _vendorServiceMock;
+ private Mock<IEnumTranslationService> _enumTranslationServiceMock;
+ private Mock<ICustomerNoteService> _customerNoteServiceMock;
+ private Mock<ICustomerProductService> _customerProductServiceMock;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IDateTimeService> _dateTimeServiceMock;
+ private Mock<IDownloadService> _downloadServiceMock;
+ private Mock<INewsLetterSubscriptionService> _newsLetterSubscriptionServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
+ private Customer _currentCustomer;
+ private CustomerViewModelService _customerViewModelService;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _groupServiceMock = new Mock<IGroupService>();
+ _storeServiceMock = new Mock<IStoreService>();
+ _customerTagServiceMock = new Mock<ICustomerTagService>();
+ _vendorServiceMock = new Mock<IVendorService>();
+ _enumTranslationServiceMock = new Mock<IEnumTranslationService>();
+ _customerNoteServiceMock = new Mock<ICustomerNoteService>();
+ _customerProductServiceMock = new Mock<ICustomerProductService>();
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _productServiceMock = new Mock<IProductService>();
+ _dateTimeServiceMock = new Mock<IDateTimeService>();
+ _downloadServiceMock = new Mock<IDownloadService>();
+ _newsLetterSubscriptionServiceMock = new Mock<INewsLetterSubscriptionService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns<string>(k => k);
+
+ _dateTimeServiceMock.Setup(d => d.ConvertToUserTime(It.IsAny<DateTime>(), It.IsAny<DateTimeKind>()))
+ .Returns<DateTime, DateTimeKind>((dt, _) => dt);
+
+ _currentCustomer = new Customer { Id = CurrentCustomerId };
+ var workContextMock = new Mock<IWorkContext>();
+ workContextMock.Setup(w => w.CurrentCustomer).Returns(_currentCustomer);
+ var storeContextMock = new Mock<IStoreContext>();
+ storeContextMock.Setup(s => s.CurrentStore).Returns(new Grand.Domain.Stores.Store { Id = CurrentStoreId });
+ var contextAccessorMock = new Mock<IContextAccessor>();
+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
+ contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);
+
+ var salesEmployeeServiceMock = new Mock<ISalesEmployeeService>();
+ salesEmployeeServiceMock.Setup(s => s.GetAll()).ReturnsAsync(new List<SalesEmployee>());
+
+ var customerAttributeServiceMock = new Mock<ICustomerAttributeService>();
+ customerAttributeServiceMock.Setup(c => c.GetAllCustomerAttributes())
+ .ReturnsAsync(new List<CustomerAttribute>());
+
+ //http context with a service provider that resolves the external authentication service
+ var externalAuthServiceMock = new Mock<IExternalAuthenticationService>();
+ externalAuthServiceMock.Setup(e => e.GetExternalIdentifiers(It.IsAny<Customer>()))
+ .ReturnsAsync(new List<ExternalAuthentication>());
+ var serviceProviderMock = new Mock<IServiceProvider>();
+ serviceProviderMock.Setup(s => s.GetService(typeof(IExternalAuthenticationService)))
+ .Returns(externalAuthServiceMock.Object);
+ var httpContextMock = new Mock<HttpContext>();
+ httpContextMock.Setup(c => c.RequestServices).Returns(serviceProviderMock.Object);
+ var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
+ httpContextAccessorMock.Setup(a => a.HttpContext).Returns(httpContextMock.Object);
+
+ _customerServiceMock.Setup(c => c.InsertCustomer(It.IsAny<Customer>())).Returns(Task.CompletedTask);
+ _customerServiceMock.Setup(c => c.UpdateCustomerInAdminPanel(It.IsAny<Customer>())).Returns(Task.CompletedTask);
+ _customerServiceMock
+ .Setup(c => c.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<bool>(),
+ It.IsAny<string>()))
+ .Returns(Task.CompletedTask);
+ _customerServiceMock
+ .Setup(c => c.UpdateUserField(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>()))
+ .Returns(Task.CompletedTask);
+
+ _storeServiceMock.Setup(s => s.GetAllStores()).ReturnsAsync(new List<Grand.Domain.Stores.Store>());
+
+ _groupServiceMock
+ .Setup(g => g.GetAllCustomerGroups(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
+ It.IsAny<bool>()))
+ .ReturnsAsync(new PagedList<CustomerGroup>());
+
+ _customerNoteServiceMock.Setup(c => c.InsertCustomerNote(It.IsAny<CustomerNote>()))
+ .Returns(Task.CompletedTask);
+
+ _groupServiceMock.Setup(g => g.GetAllByIds(It.IsAny<string[]>()))
+ .ReturnsAsync(new List<CustomerGroup>());
+
+ _customerViewModelService = new CustomerViewModelService(
+ _customerServiceMock.Object,
+ _groupServiceMock.Object,
+ _customerProductServiceMock.Object,
+ _newsLetterSubscriptionServiceMock.Object,
+ _dateTimeServiceMock.Object,
+ _translationServiceMock.Object,
+ _loyaltyPointsServiceMock.Object,
+ new Mock<ICountryService>().Object,
+ contextAccessorMock.Object,
+ _vendorServiceMock.Object,
+ _storeServiceMock.Object,
+ new Mock<ICustomerAttributeParser>().Object,
+ customerAttributeServiceMock.Object,
+ new Mock<IAddressAttributeParser>().Object,
+ new Mock<IAddressAttributeService>().Object,
+ new Mock<IAffiliateService>().Object,
+ _customerTagServiceMock.Object,
+ _productServiceMock.Object,
+ salesEmployeeServiceMock.Object,
+ _customerNoteServiceMock.Object,
+ _downloadServiceMock.Object,
+ httpContextAccessorMock.Object,
+ new CustomerSettings(),
+ new TaxSettings(),
+ new LoyaltyPointsSettings(),
+ new AddressSettings(),
+ new CommonSettings(),
+ _enumTranslationServiceMock.Object);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerModel_MapsStoreIdFromModel()
+ {
+ var model = new CustomerModel { StoreId = "store-1" };
+
+ var customer = await _customerViewModelService.InsertCustomerModel(model);
+
+ Assert.AreEqual("store-1", customer.StoreId);
+ _customerServiceMock.Verify(c => c.InsertCustomer(It.Is<Customer>(x => x.StoreId == "store-1")), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerModel_StoreManager_PresetsCurrentStoreId()
+ {
+ _groupServiceMock.Setup(g => g.IsStoreManager(It.IsAny<Customer>())).ReturnsAsync(true);
+
+ var model = new CustomerModel();
+ await _customerViewModelService.PrepareCustomerModel(model, null, false);
+
+ Assert.AreEqual(CurrentStoreId, model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerModel_ExistingCustomer_MapsStoreIdFromEntity()
+ {
+ var customer = new Customer { Id = "c1", Email = "[email protected]", StoreId = "store-9" };
+ var model = new CustomerModel();
+
+ await _customerViewModelService.PrepareCustomerModel(model, customer, false);
+
+ Assert.AreEqual("store-9", model.StoreId);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerModel_NonStoreManager_DoesNotPresetStoreId()
+ {
+ _groupServiceMock.Setup(g => g.IsStoreManager(It.IsAny<Customer>())).ReturnsAsync(false);
+
+ var model = new CustomerModel();
+ await _customerViewModelService.PrepareCustomerModel(model, null, false);
+
+ Assert.IsTrue(string.IsNullOrEmpty(model.StoreId));
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerModel_MapsStoreIdFromModel()
+ {
+ var customer = new Customer { StoreId = "store-1" };
+ var model = new CustomerModel { Email = "[email protected]", StoreId = "store-2" };
+
+ var result = await _customerViewModelService.UpdateCustomerModel(customer, model);
+
+ Assert.AreEqual("store-2", result.StoreId);
+ _customerServiceMock.Verify(
+ c => c.UpdateCustomerInAdminPanel(It.Is<Customer>(x => x.StoreId == "store-2")), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerListModel_SelectsRegisteredGroupByDefault()
+ {
+ var registered = new CustomerGroup { Id = "reg", Name = "Registered" };
+ _groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(It.IsAny<string>()))
+ .ReturnsAsync(registered);
+ _groupServiceMock
+ .Setup(g => g.GetAllCustomerGroups(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
+ It.IsAny<bool>()))
+ .ReturnsAsync(new PagedList<CustomerGroup> { registered });
+ _customerTagServiceMock.Setup(t => t.GetAllCustomerTags()).ReturnsAsync(new List<CustomerTag>());
+
+ var model = await _customerViewModelService.PrepareCustomerListModel();
+
+ Assert.IsTrue(model.AvailableCustomerGroups.Any(x => x.Value == "reg" && x.Selected));
+ CollectionAssert.Contains(model.SearchCustomerGroupIds.ToList(), "reg");
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomer_DeletesCustomer()
+ {
+ var customer = new Customer { Id = "c1", Email = "[email protected]" };
+
+ await _customerViewModelService.DeleteCustomer(customer);
+
+ _customerServiceMock.Verify(c => c.DeleteCustomer(customer), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteSelected_DeletesAllExceptCurrentUser()
+ {
+ var other = new Customer { Id = "other" };
+ var current = new Customer { Id = CurrentCustomerId };
+ _customerServiceMock.Setup(c => c.GetCustomersByIds(It.IsAny<string[]>()))
+ .ReturnsAsync(new List<Customer> { other, current });
+
+ await _customerViewModelService.DeleteSelected(new[] { "other", CurrentCustomerId });
+
+ _customerServiceMock.Verify(c => c.DeleteCustomer(other), Times.Once);
+ _customerServiceMock.Verify(c => c.DeleteCustomer(current), Times.Never);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerModelAddProductModel_BuildsAvailableLists()
+ {
+ _storeServiceMock.Setup(s => s.GetAllStores())
+ .ReturnsAsync(new List<Grand.Domain.Stores.Store> { new() { Id = "store-1", Shortcut = "Store 1" } });
+ _vendorServiceMock
+ .Setup(v => v.GetAllVendors(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>()))
+ .ReturnsAsync(new PagedList<Vendor> { new() { Id = "vendor-1", Name = "Vendor 1" } });
+ _enumTranslationServiceMock
+ .Setup(e => e.ToSelectList(It.IsAny<ProductType>(), It.IsAny<bool>(), It.IsAny<int[]>()))
+ .Returns(new SelectList(Enumerable.Empty<SelectListItem>()));
+
+ var model = await _customerViewModelService.PrepareCustomerModelAddProductModel();
+
+ Assert.IsTrue(model.AvailableStores.Any(x => x.Value == "store-1"));
+ Assert.IsTrue(model.AvailableVendors.Any(x => x.Value == "vendor-1"));
+ Assert.IsTrue(model.AvailableProductTypes.Count > 0);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerNote_InsertsNoteWithMappedFields()
+ {
+ var note = await _customerViewModelService.InsertCustomerNote("c1", "d1", false, "title", "message");
+
+ Assert.AreEqual("c1", note.CustomerId);
+ Assert.AreEqual("d1", note.DownloadId);
+ Assert.AreEqual("title", note.Title);
+ Assert.AreEqual("message", note.Note);
+ Assert.IsFalse(note.DisplayToCustomer);
+ _customerNoteServiceMock.Verify(
+ c => c.InsertCustomerNote(It.Is<CustomerNote>(x => x.CustomerId == "c1" && x.Title == "title")),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerNote_DeletesNoteAndAttachment()
+ {
+ var note = new CustomerNote { Id = "n1", DownloadId = "d1" };
+ var download = new Download { Id = "d1" };
+ _customerNoteServiceMock.Setup(c => c.GetCustomerNote("n1")).ReturnsAsync(note);
+ _customerNoteServiceMock.Setup(c => c.DeleteCustomerNote(It.IsAny<CustomerNote>())).Returns(Task.CompletedTask);
+ _downloadServiceMock.Setup(d => d.GetDownloadById("d1")).ReturnsAsync(download);
+ _downloadServiceMock.Setup(d => d.DeleteDownload(It.IsAny<Download>())).Returns(Task.CompletedTask);
+
+ await _customerViewModelService.DeleteCustomerNote("n1", "c1");
+
+ _customerNoteServiceMock.Verify(c => c.DeleteCustomerNote(note), Times.Once);
+ _downloadServiceMock.Verify(d => d.DeleteDownload(download), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerNote_NotFound_Throws()
+ {
+ _customerNoteServiceMock.Setup(c => c.GetCustomerNote(It.IsAny<string>()))
+ .ReturnsAsync((CustomerNote)null);
+
+ await Assert.ThrowsAsync<ArgumentException>(
+ () => _customerViewModelService.DeleteCustomerNote("missing", "c1"));
+ }
+
+ [TestMethod]
+ public async Task PrepareLoyaltyPointsHistoryModel_MapsHistory()
+ {
+ _loyaltyPointsServiceMock
+ .Setup(l => l.GetLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<string>(), true))
+ .ReturnsAsync(new List<LoyaltyPointsHistory> {
+ new() { StoreId = "store-1", Points = 5, PointsBalance = 10, Message = "added" }
+ });
+ _storeServiceMock.Setup(s => s.GetStoreById("store-1"))
+ .ReturnsAsync(new Grand.Domain.Stores.Store { Id = "store-1", Shortcut = "Store 1" });
+
+ var result = (await _customerViewModelService.PrepareLoyaltyPointsHistoryModel("c1")).ToList();
+
+ Assert.AreEqual(1, result.Count);
+ Assert.AreEqual("Store 1", result[0].StoreName);
+ Assert.AreEqual(5, result[0].Points);
+ }
+
+ [TestMethod]
+ public async Task InsertLoyaltyPointsHistory_DelegatesToService()
+ {
+ var history = new LoyaltyPointsHistory();
+ _loyaltyPointsServiceMock
+ .Setup(l => l.AddLoyaltyPointsHistory("c1", 10, "store-1", "msg", It.IsAny<string>(), It.IsAny<double>()))
+ .ReturnsAsync(history);
+
+ var result = await _customerViewModelService.InsertLoyaltyPointsHistory(
+ new Customer { Id = "c1" }, "store-1", 10, "msg");
+
+ Assert.AreSame(history, result);
+ _loyaltyPointsServiceMock.Verify(
+ l => l.AddLoyaltyPointsHistory("c1", 10, "store-1", "msg", It.IsAny<string>(), It.IsAny<double>()),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteAddress_RemovesAddressAndUpdatesCustomer()
+ {
+ var address = new Address { Id = "a1" };
+ var customer = new Customer();
+ customer.Addresses.Add(address);
+
+ await _customerViewModelService.DeleteAddress(customer, address);
+
+ Assert.IsFalse(customer.Addresses.Any(a => a.Id == "a1"));
+ _customerServiceMock.Verify(c => c.UpdateCustomerInAdminPanel(customer), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductPrice_UpdatesWhenFound()
+ {
+ var price = new CustomerProductPrice { Id = "pp1", Price = 1 };
+ _customerProductServiceMock.Setup(c => c.GetCustomerProductPriceById("pp1")).ReturnsAsync(price);
+ _customerProductServiceMock.Setup(c => c.UpdateCustomerProductPrice(It.IsAny<CustomerProductPrice>()))
+ .Returns(Task.CompletedTask);
+
+ await _customerViewModelService.UpdateProductPrice(
+ new CustomerModel.ProductPriceModel { Id = "pp1", Price = 99 });
+
+ _customerProductServiceMock.Verify(
+ c => c.UpdateCustomerProductPrice(It.Is<CustomerProductPrice>(x => x.Price == 99)), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductPrice_DeletesWhenFound()
+ {
+ var price = new CustomerProductPrice { Id = "pp1" };
+ _customerProductServiceMock.Setup(c => c.GetCustomerProductPriceById("pp1")).ReturnsAsync(price);
+ _customerProductServiceMock.Setup(c => c.DeleteCustomerProductPrice(It.IsAny<CustomerProductPrice>()))
+ .Returns(Task.CompletedTask);
+
+ await _customerViewModelService.DeleteProductPrice("pp1");
+
+ _customerProductServiceMock.Verify(c => c.DeleteCustomerProductPrice(price), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductPrice_NotFound_Throws()
+ {
+ _customerProductServiceMock.Setup(c => c.GetCustomerProductPriceById(It.IsAny<string>()))
+ .ReturnsAsync((CustomerProductPrice)null);
+
+ await Assert.ThrowsAsync<ArgumentException>(
+ () => _customerViewModelService.DeleteProductPrice("missing"));
+ }
+
+ [TestMethod]
+ public async Task UpdatePersonalizedProduct_UpdatesWhenFound()
+ {
+ var customerProduct = new CustomerProduct { Id = "cp1", DisplayOrder = 1 };
+ _customerProductServiceMock.Setup(c => c.GetCustomerProduct("cp1")).ReturnsAsync(customerProduct);
+ _customerProductServiceMock.Setup(c => c.UpdateCustomerProduct(It.IsAny<CustomerProduct>()))
+ .Returns(Task.CompletedTask);
+
+ await _customerViewModelService.UpdatePersonalizedProduct(
+ new CustomerModel.ProductModel { Id = "cp1", DisplayOrder = 7 });
+
+ _customerProductServiceMock.Verify(
+ c => c.UpdateCustomerProduct(It.Is<CustomerProduct>(x => x.DisplayOrder == 7)), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeletePersonalizedProduct_NotFound_Throws()
+ {
+ _customerProductServiceMock.Setup(c => c.GetCustomerProduct(It.IsAny<string>()))
+ .ReturnsAsync((CustomerProduct)null);
+
+ await Assert.ThrowsAsync<ArgumentException>(
+ () => _customerViewModelService.DeletePersonalizedProduct("missing"));
+ }
+
+ [TestMethod]
+ public async Task PrepareProductPriceModel_MapsItems()
+ {
+ _customerProductServiceMock
+ .Setup(c => c.GetProductsPriceByCustomer(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
+ .ReturnsAsync(new PagedList<CustomerProductPrice> { new() { Id = "pp1", ProductId = "p1", Price = 3 } });
+ _productServiceMock.Setup(p => p.GetProductById("p1", false))
+ .ReturnsAsync(new Product { Id = "p1", Name = "Prod 1" });
+
+ var (items, _) = await _customerViewModelService.PrepareProductPriceModel("c1", 1, 10);
+
+ var list = items.ToList();
+ Assert.AreEqual(1, list.Count);
+ Assert.AreEqual("Prod 1", list[0].ProductName);
+ Assert.AreEqual(3, list[0].Price);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerAddProductModel_Personalized_InsertsCustomerProduct()
+ {
+ _productServiceMock.Setup(p => p.GetProductById("p1", false))
+ .ReturnsAsync(new Product { Id = "p1", Price = 5 });
+ _customerProductServiceMock.Setup(c => c.GetCustomerProduct("c1", "p1")).ReturnsAsync((CustomerProduct)null);
+ _customerProductServiceMock.Setup(c => c.InsertCustomerProduct(It.IsAny<CustomerProduct>()))
+ .Returns(Task.CompletedTask);
+
+ await _customerViewModelService.InsertCustomerAddProductModel("c1", true,
+ new CustomerModel.AddProductModel { SelectedProductIds = new[] { "p1" } });
+
+ _customerProductServiceMock.Verify(
+ c => c.InsertCustomerProduct(It.Is<CustomerProduct>(x => x.CustomerId == "c1" && x.ProductId == "p1")),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerAddProductModel_NotPersonalized_InsertsProductPrice()
+ {
+ _productServiceMock.Setup(p => p.GetProductById("p1", false))
+ .ReturnsAsync(new Product { Id = "p1", Price = 5 });
+ _customerProductServiceMock.Setup(c => c.GetPriceByCustomerProduct("c1", "p1"))
+ .ReturnsAsync((double?)null);
+ _customerProductServiceMock.Setup(c => c.InsertCustomerProductPrice(It.IsAny<CustomerProductPrice>()))
+ .Returns(Task.CompletedTask);
+
+ await _customerViewModelService.InsertCustomerAddProductModel("c1", false,
+ new CustomerModel.AddProductModel { SelectedProductIds = new[] { "p1" } });
+
+ _customerProductServiceMock.Verify(
+ c => c.InsertCustomerProductPrice(
+ It.Is<CustomerProductPrice>(x => x.CustomerId == "c1" && x.ProductId == "p1" && x.Price == 5)),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task PreparePersonalizedProducts_MapsItems()
+ {
+ _customerProductServiceMock
+ .Setup(c => c.GetProductsByCustomer(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
+ .ReturnsAsync(new PagedList<CustomerProduct>
+ { new() { Id = "cp1", ProductId = "p1", DisplayOrder = 2 } });
+ _productServiceMock.Setup(p => p.GetProductById("p1", false))
+ .ReturnsAsync(new Product { Id = "p1", Name = "Prod 1" });
+
+ var (items, _) = await _customerViewModelService.PreparePersonalizedProducts("c1", 1, 10);
+
+ var list = items.ToList();
+ Assert.AreEqual(1, list.Count);
+ Assert.AreEqual("Prod 1", list[0].ProductName);
+ Assert.AreEqual(2, list[0].DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomer_RemovesNewsletterSubscriptions()
+ {
+ var customer = new Customer { Id = "c1", Email = "[email protected]" };
+ var subscription = new NewsLetterSubscription { Id = "s1", Email = customer.Email, StoreId = "store-1" };
+ _storeServiceMock.Setup(s => s.GetAllStores())
+ .ReturnsAsync(new List<Grand.Domain.Stores.Store> { new() { Id = "store-1" } });
+ _newsLetterSubscriptionServiceMock
+ .Setup(n => n.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, "store-1"))
+ .ReturnsAsync(subscription);
+ _newsLetterSubscriptionServiceMock
+ .Setup(n => n.DeleteNewsLetterSubscription(It.IsAny<NewsLetterSubscription>(), It.IsAny<bool>()))
+ .Returns(Task.CompletedTask);
+
+ await _customerViewModelService.DeleteCustomer(customer);
+
+ _customerServiceMock.Verify(c => c.DeleteCustomer(customer), Times.Once);
+ _newsLetterSubscriptionServiceMock.Verify(
+ n => n.DeleteNewsLetterSubscription(subscription, It.IsAny<bool>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerListModel_MapsSettingsGroupsAndTags()
+ {
+ var registered = new CustomerGroup { Id = "reg", Name = "Registered" };
+ var guests = new CustomerGroup { Id = "gst", Name = "Guests" };
+ _groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(It.IsAny<string>()))
+ .ReturnsAsync(registered);
+ _groupServiceMock
+ .Setup(g => g.GetAllCustomerGroups(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
+ It.IsAny<bool>()))
+ .ReturnsAsync(new PagedList<CustomerGroup> { registered, guests });
+ _customerTagServiceMock.Setup(t => t.GetAllCustomerTags())
+ .ReturnsAsync(new List<CustomerTag> { new() { Id = "t1", Name = "VIP" } });
+
+ var model = await _customerViewModelService.PrepareCustomerListModel();
+
+ Assert.AreEqual(2, model.AvailableCustomerGroups.Count);
+ Assert.IsTrue(model.AvailableCustomerGroups.Any(x => x.Value == "gst" && !x.Selected));
+ Assert.IsTrue(model.AvailableCustomerTags.Any(x => x.Value == "t1" && x.Text == "VIP"));
+ Assert.AreEqual(new CustomerSettings().UsernamesEnabled, model.UsernamesEnabled);
+ Assert.AreEqual(new CustomerSettings().CompanyEnabled, model.CompanyEnabled);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerListModel_RegisteredGroupMissing_NullSearchGroupId()
+ {
+ _groupServiceMock.Setup(g => g.GetCustomerGroupBySystemName(It.IsAny<string>()))
+ .ReturnsAsync(new CustomerGroup { Id = "reg" });
+ _groupServiceMock
+ .Setup(g => g.GetAllCustomerGroups(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
+ It.IsAny<bool>()))
+ .ReturnsAsync(new PagedList<CustomerGroup> { new() { Id = "other" } });
+ _customerTagServiceMock.Setup(t => t.GetAllCustomerTags()).ReturnsAsync(new List<CustomerTag>());
+
+ var model = await _customerViewModelService.PrepareCustomerListModel();
+
+ //registered group is not among the available groups -> the search id resolves to null
+ Assert.AreEqual(1, model.SearchCustomerGroupIds.Count);
+ Assert.IsNull(model.SearchCustomerGroupIds.First());
+ Assert.IsFalse(model.AvailableCustomerGroups.Any(x => x.Selected));
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerList_MapsCustomers()
+ {
+ SetupGetAllCustomers(new PagedList<Customer>
+ { new() { Id = "c1", Email = "[email protected]", Active = true } });
+
+ var (list, _) = await _customerViewModelService.PrepareCustomerList(
+ new CustomerListModel(), new[] { "grp" }, new[] { "tag" }, 1, 10);
+
+ var items = list.ToList();
+ Assert.AreEqual(1, items.Count);
+ Assert.AreEqual("c1", items[0].Id);
+ Assert.AreEqual("[email protected]", items[0].Email);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerList_FiltersBySalesEmployeeAndPaging()
+ {
+ _currentCustomer.SeId = "se-1";
+ SetupGetAllCustomers(new PagedList<Customer>());
+
+ await _customerViewModelService.PrepareCustomerList(
+ new CustomerListModel(), new[] { "grp" }, new[] { "tag" }, 2, 15);
+
+ //salesEmployeeId comes from the current customer, pageIndex is zero-based
+ _customerServiceMock.Verify(c => c.GetAllCustomers(
+ It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), "se-1",
+ It.Is<string[]>(g => g.SequenceEqual(new[] { "grp" })),
+ It.Is<string[]>(t => t.SequenceEqual(new[] { "tag" })),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(),
+ It.IsAny<ShoppingCartType?>(), 1, 15,
+ It.IsAny<System.Linq.Expressions.Expression<Func<Customer, object>>>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerList_GuestCustomer_UsesGuestResource()
+ {
+ SetupGetAllCustomers(new PagedList<Customer> { new() { Id = "guest", Email = "", Active = true } });
+
+ var (list, _) = await _customerViewModelService.PrepareCustomerList(
+ new CustomerListModel(), Array.Empty<string>(), Array.Empty<string>(), 1, 10);
+
+ Assert.AreEqual("Admin.Customers.Guest", list.First().Email);
+ }
+
+ [TestMethod]
+ public async Task PrepareCustomerList_NoCustomers_ReturnsEmpty()
+ {
+ SetupGetAllCustomers(new PagedList<Customer>());
+
+ var (list, _) = await _customerViewModelService.PrepareCustomerList(
+ new CustomerListModel(), Array.Empty<string>(), Array.Empty<string>(), 1, 10);
+
+ Assert.AreEqual(0, list.Count());
+ }
+
+ private void SetupGetAllCustomers(IPagedList<Customer> result)
+ {
+ _customerServiceMock
+ .Setup(c => c.GetAllCustomers(
+ It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string[]>(),
+ It.IsAny<string[]>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<bool>(), It.IsAny<ShoppingCartType?>(), It.IsAny<int>(), It.IsAny<int>(),
+ It.IsAny<System.Linq.Expressions.Expression<Func<Customer, object>>>()))
+ .ReturnsAsync(result);
+ }
+}
diff --git a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs
new file mode 100644
index 000000000..e99f19bde
--- /dev/null
+++ b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs
@@ -0,0 +1,96 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Customers;
+using Grand.Domain;
+using Grand.Domain.Customers;
+using Grand.Domain.Stores;
+using Grand.Infrastructure;
+using Grand.Infrastructure.Validators;
+using Grand.Web.AdminShared.Models.Customers;
+using Grand.Web.AdminShared.Validators.Customers;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Web.Admin.Tests.Validators;
+
+[TestClass]
+public class CustomerValidatorTests
+{
+ private const string CurrentStoreId = "store-current";
+ private const string RequiredMessage = "Admin.Customers.Customers.Fields.Store.Required";
+ private const string MustBeCurrentStoreMessage = "Admin.Customers.Customers.Fields.Store.MustBeCurrentStore";
+
+ private Mock<IGroupService> _groupServiceMock;
+ private CustomerValidator _validator;
+
+ [TestInitialize]
+ public void Setup()
+ {
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns<string>(k => k);
+
+ _groupServiceMock = new Mock<IGroupService>();
+ _groupServiceMock
+ .Setup(g => g.GetAllCustomerGroups(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(),
+ It.IsAny<bool>()))
+ .ReturnsAsync(new PagedList<CustomerGroup>());
+
+ var workContextMock = new Mock<IWorkContext>();
+ workContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer());
+ var storeContextMock = new Mock<IStoreContext>();
+ storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = CurrentStoreId });
+ var contextAccessorMock = new Mock<IContextAccessor>();
+ contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);
+ contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);
+
+ _validator = new CustomerValidator(
+ new List<IValidatorConsumer<CustomerModel>>(),
+ translationServiceMock.Object,
+ new Mock<ICountryService>().Object,
+ contextAccessorMock.Object,
+ new Mock<ICustomerService>().Object,
+ _groupServiceMock.Object,
+ new CustomerSettings());
+ }
+
+ private static CustomerModel BuildModel(string storeId) =>
+ new() { Id = "customer-1", Email = "[email protected]", StoreId = storeId };
+
+ [TestMethod]
+ public async Task StoreId_Empty_FailsRequired()
+ {
+ var result = await _validator.ValidateAsync(BuildModel(string.Empty));
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == RequiredMessage));
+ }
+
+ [TestMethod]
+ public async Task StoreManager_WrongStore_Fails()
+ {
+ _groupServiceMock.Setup(g => g.IsStoreManager(It.IsAny<Customer>())).ReturnsAsync(true);
+
+ var result = await _validator.ValidateAsync(BuildModel("store-other"));
+
+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == MustBeCurrentStoreMessage));
+ }
+
+ [TestMethod]
+ public async Task StoreManager_CurrentStore_Passes()
+ {
+ _groupServiceMock.Setup(g => g.IsStoreManager(It.IsAny<Customer>())).ReturnsAsync(true);
+
+ var result = await _validator.ValidateAsync(BuildModel(CurrentStoreId));
+
+ Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == MustBeCurrentStoreMessage));
+ }
+
+ [TestMethod]
+ public async Task NonStoreManager_AnyStore_Passes()
+ {
+ _groupServiceMock.Setup(g => g.IsStoreManager(It.IsAny<Customer>())).ReturnsAsync(false);
+
+ var result = await _validator.ValidateAsync(BuildModel("store-other"));
+
+ Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == MustBeCurrentStoreMessage));
+ }
+}
diff --git a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml
index 46e40da93..2df010e46 100644
--- a/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml
+++ b/src/Web/Grand.Web.Admin/Areas/Admin/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml
@@ -183,6 +183,13 @@
<span asp-validation-for="StaffStoreId"></span>
</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>
+</div>
<div class="form-group">
<admin-label asp-for="Owner"/>
<div class="col-md-9 col-sm-9">
diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
index f73d8046c..ebb2254ec 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
@@ -7,16 +7,16 @@ 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.Domain.Permissions;
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.Admin.Extensions;
+using Grand.Web.AdminShared.Extensions;
using Grand.Web.AdminShared.Interfaces;
using Grand.Web.AdminShared.Models.Catalog;
using Grand.Web.AdminShared.Models.Customers;
@@ -26,7 +26,6 @@ using Grand.Web.Common.Filters;
using Grand.Web.Common.Models;
using Grand.Web.Common.Security.Authorization;
using Microsoft.AspNetCore.Mvc;
-using Grand.Web.AdminShared.Extensions;
namespace Grand.Web.Admin.Controllers;
@@ -88,46 +87,46 @@ public class CustomerController : BaseAdminController
{
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();
- }
+ {
+ 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();
- }
+ {
+ 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();
- }
+ {
+ //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();
+ 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:
diff --git a/src/Web/Grand.Web.AdminShared/Models/Customers/CustomerModel.cs b/src/Web/Grand.Web.AdminShared/Models/Customers/CustomerModel.cs
index e1f3a7d37..d866dce47 100644
--- a/src/Web/Grand.Web.AdminShared/Models/Customers/CustomerModel.cs
+++ b/src/Web/Grand.Web.AdminShared/Models/Customers/CustomerModel.cs
@@ -50,6 +50,9 @@ public class CustomerModel : BaseEntityModel
[GrandResourceDisplayName("Admin.Customers.Customers.Fields.StaffStore")]
public string StaffStoreId { get; set; }
+ [GrandResourceDisplayName("Admin.Customers.Customers.Fields.Store")]
+ public string StoreId { get; set; }
+
public IList<SelectListItem> AvailableStores { get; set; } = new List<SelectListItem>();
//form fields & properties
diff --git a/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs
index 7a9f4243d..a9d339eb5 100644
--- a/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs
+++ b/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs
@@ -190,6 +190,7 @@ public class CustomerViewModelService : ICustomerViewModelService
model.Username = customer.Username;
model.VendorId = customer.VendorId;
model.StaffStoreId = customer.StaffStoreId;
+ model.StoreId = customer.StoreId;
model.SeId = customer.SeId;
model.AdminComment = customer.AdminComment;
model.IsTaxExempt = customer.IsTaxExempt;
@@ -264,6 +265,10 @@ public class CustomerViewModelService : ICustomerViewModelService
else
{
model.SeId = _contextAccessor.WorkContext.CurrentCustomer.SeId;
+
+ //a store manager can only create customers for his own store - preset it
+ if (await _groupService.IsStoreManager(_contextAccessor.WorkContext.CurrentCustomer))
+ model.StoreId = _contextAccessor.StoreContext.CurrentStore.Id;
}
model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
@@ -385,7 +390,7 @@ public class CustomerViewModelService : ICustomerViewModelService
IsTaxExempt = model.IsTaxExempt,
FreeShipping = model.FreeShipping,
Active = model.Active,
- StoreId = _contextAccessor.StoreContext.CurrentStore.Id,
+ StoreId = model.StoreId,
OwnerId = ownerId,
Attributes = model.Attributes,
LastActivityDateUtc = DateTime.UtcNow
@@ -545,6 +550,9 @@ public class CustomerViewModelService : ICustomerViewModelService
//staff store
customer.StaffStoreId = model.StaffStoreId;
+ //store
+ customer.StoreId = model.StoreId;
+
//sales employee
customer.SeId = model.SeId;
diff --git a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs
index 0559575ca..2b321ea24 100644
--- a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs
+++ b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs
@@ -30,6 +30,17 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>
RuleFor(x => x.Email).NotEmpty().EmailAddress()
.WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Email.Required"));
+ //store
+ RuleFor(x => x.StoreId).NotEmpty()
+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Store.Required"));
+
+ //a store manager can only assign a customer to his own store
+ RuleFor(x => x.StoreId).MustAsync(async (storeId, _) =>
+ !await groupService.IsStoreManager(contextAccessor.WorkContext.CurrentCustomer) ||
+ storeId == contextAccessor.StoreContext.CurrentStore.Id)
+ .WithMessage(
+ translationService.GetResource("Admin.Customers.Customers.Fields.Store.MustBeCurrentStore"));
+
//form fields
if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
RuleFor(x => x.CountryId)
diff --git a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml
index c60e745e3..0b432bbbc 100644
Binary files a/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml and b/src/Web/Grand.Web/App_Data/Resources/DefaultLanguage.xml differ