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
Store-manager customer management + per-store customer identity (#717)
Krzysztof Pajakee112838aac3
diff --git a/GrandNode.sln b/GrandNode.slnindex 3b6f0c8d0..176e625e4 100644--- a/GrandNode.sln+++ b/GrandNode.sln@@ -159,6 +159,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{8D626EA8-CEndProjectProject("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Web", "Web", "{03997797-E7F5-0643-168D-B8EA7178C2FE}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Module.Api.Tests", "src\Tests\Grand.Module.Api.Tests\Grand.Module.Api.Tests.csproj", "{FE75CD3C-8329-C22D-A70E-B797DC30326D}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Grand.Web.Tests", "src\Tests\Grand.Web.Tests\Grand.Web.Tests.csproj", "{920E338E-0E4A-4632-8D88-C89F340EB8A2}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -913,6 +917,30 @@ Global{5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x64.Build.0 = Release|Any CPU{5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x86.ActiveCfg = Release|Any CPU{5819B37B-4972-4BBC-B51C-57B0028EF869}.Release|x86.Build.0 = Release|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Debug|x64.ActiveCfg = Debug|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Debug|x64.Build.0 = Debug|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Debug|x86.ActiveCfg = Debug|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Debug|x86.Build.0 = Debug|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Release|Any CPU.Build.0 = Release|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Release|x64.ActiveCfg = Release|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Release|x64.Build.0 = Release|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Release|x86.ActiveCfg = Release|Any CPU+ {FE75CD3C-8329-C22D-A70E-B797DC30326D}.Release|x86.Build.0 = Release|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Debug|x64.ActiveCfg = Debug|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Debug|x64.Build.0 = Debug|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Debug|x86.ActiveCfg = Debug|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Debug|x86.Build.0 = Debug|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Release|Any CPU.Build.0 = Release|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Release|x64.ActiveCfg = Release|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Release|x64.Build.0 = Release|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Release|x86.ActiveCfg = Release|Any CPU+ {920E338E-0E4A-4632-8D88-C89F340EB8A2}.Release|x86.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -982,6 +1010,7 @@ Global{5819B37B-4972-4BBC-B51C-57B0028EF869} = {CEA09484-30F6-4D44-02F6-822E06DBC57C}{8D626EA8-CB54-BC41-363A-217881BEBA6E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}{03997797-E7F5-0643-168D-B8EA7178C2FE} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}+ {FE75CD3C-8329-C22D-A70E-B797DC30326D} = {6360202A-F931-4BBD-ADBD-C9A628EE59F8}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {88B478F4-FD3B-4C24-9E84-4FAAF0254397}diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.csindex 2c86f0fa7..a0469ff14 100644--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs@@ -47,10 +47,16 @@ public class ApiAuthenticationService : IApiAuthenticationServiceif (!authenticateResult.Succeeded)return null;- //try to get customer by email- var emailClaim = authenticateResult.Principal.Claims.FirstOrDefault(claim => claim.Type == "Email");- if (emailClaim != null)- customer = await _customerService.GetCustomerByEmail(emailClaim.Value);+ //prefer the stable customer id (unambiguous with per-store identity), fall back to e-mail for old tokens+ var customerIdClaim = authenticateResult.Principal.Claims.FirstOrDefault(claim => claim.Type == "CustomerId");+ if (customerIdClaim != null)+ customer = await _customerService.GetCustomerById(customerIdClaim.Value);+ else+ {+ var emailClaim = authenticateResult.Principal.Claims.FirstOrDefault(claim => claim.Type == "Email");+ if (emailClaim != null)+ customer = await _customerService.GetCustomerByEmail(emailClaim.Value);+ }//whether the found customer is availableif (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))@@ -75,8 +81,14 @@ public class ApiAuthenticationService : IApiAuthenticationServiceif (!authResult.Succeeded)return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);+ var customerId = authResult.Principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value;var email = authResult.Principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value;- if (email is null)+ if (!string.IsNullOrEmpty(customerId))+ {+ //prefer the stable customer id - unambiguous with per-store identity+ customer = await _customerService.GetCustomerById(customerId);+ }+ else if (email is null){//guestvar id = authResult.Principal.Claims.FirstOrDefault(x => x.Type == "Guid")?.Value;diff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.csindex 416bd682e..508e1e1b6 100644--- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs@@ -48,6 +48,10 @@ public class CookieAuthenticationService : IGrandAuthenticationServiceprivate string CustomerCookieName => $"{_securityConfig.CookiePrefix}Customer";+ //claim carrying the customer's stable id, so the authenticated session can be re-resolved unambiguously+ //(works regardless of per-store customer identity - the id is globally unique, unlike e-mail/username)+ private const string CustomerIdClaimType = "grand:customerId";+#endregion#region Fields@@ -84,6 +88,12 @@ public class CookieAuthenticationService : IGrandAuthenticationServiceclaims.Add(new Claim(ClaimTypes.Email, customer.Email, ClaimValueTypes.Email,_securityConfig.CookieClaimsIssuer));+ //store the customer's stable id so the session is re-resolved by id (GetCustomerById) rather than by+ //e-mail/username, which is not unique when per-store customer identity is enabled+ if (!string.IsNullOrEmpty(customer.Id))+ claims.Add(new Claim(CustomerIdClaimType, customer.Id, ClaimValueTypes.String,+ _securityConfig.CookieClaimsIssuer));+//add tokenvar passwordToken = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken);if (string.IsNullOrEmpty(passwordToken))@@ -154,6 +164,16 @@ public class CookieAuthenticationService : IGrandAuthenticationServiceprivate async Task<Customer> RetrieveCustomer(ClaimsPrincipal principal){+ //prefer the stable customer id - unambiguous even with per-store customer identity+ var customerId = principal.FindFirst(claim =>+ claim.Type == CustomerIdClaimType &&+ claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase))+ ?.Value;++ if (!string.IsNullOrEmpty(customerId))+ return await _customerService.GetCustomerById(customerId);++ //fallback for sessions issued before the id claim existed (resolved globally, as before)if (_customerSettings.UsernamesEnabled){var username = principal.FindFirst(claim =>diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.csindex aa3519d23..9d980237c 100644--- a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs@@ -29,11 +29,17 @@ public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthentipublic async Task<bool> Valid(TokenValidatedContext context){if (context.Principal == null) return false;- var email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;- var passwordToken = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;- var refreshId = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "RefreshId")?.Value;+ var customerId = context.Principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value;+ var email = context.Principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value;+ var passwordToken = context.Principal.Claims.FirstOrDefault(x => x.Type == "Token")?.Value;+ var refreshId = context.Principal.Claims.FirstOrDefault(x => x.Type == "RefreshId")?.Value;Customer customer = null;- if (email is null)+ if (!string.IsNullOrEmpty(customerId))+ {+ //prefer the stable customer id - unambiguous with per-store identity+ customer = await _customerService.GetCustomerById(customerId);+ }+ else if (email is null){//guestvar id = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;@@ -41,6 +47,7 @@ public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthenti}else{+ //legacy fallback for tokens issued before the id claim existedcustomer = await _customerService.GetCustomerByEmail(email);}diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.csindex fcfef781b..250d926aa 100644--- a/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs+++ b/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs@@ -209,6 +209,7 @@ public class PermissionProvider : IPermissionProviderStandardPermission.ManagePaymentTransactions,StandardPermission.ManageShipments,StandardPermission.ManageMerchandiseReturns,+ StandardPermission.ManageCustomers,StandardPermission.ManageReports]},diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.csindex a0bf37ed6..9536c9197 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs@@ -13,8 +13,9 @@ public interface ICustomerManagerService/// </summary>/// <param name="usernameOrEmail">Username or email</param>/// <param name="password">Password</param>+ /// <param name="storeId">Store identifier - used to resolve the customer when per-store customer identity is enabled</param>/// <returns>Result</returns>- Task<CustomerLoginResults> LoginCustomer(string usernameOrEmail, string password);+ Task<CustomerLoginResults> LoginCustomer(string usernameOrEmail, string password, string storeId = "");/// <summary>/// Register customer@@ -36,5 +37,6 @@ public interface ICustomerManagerService/// Change password/// </summary>/// <param name="request">Request</param>- Task ChangePassword(ChangePasswordRequest request);+ /// <param name="storeId">Store identifier - used to resolve the customer when per-store customer identity is enabled</param>+ Task ChangePassword(ChangePasswordRequest request, string storeId = "");}\ No newline at end of filediff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.csindex 407308a40..685404e62 100644--- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs+++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs@@ -104,11 +104,14 @@ public interface ICustomerServiceTask<Customer> GetCustomerByGuid(Guid customerGuid);/// <summary>- /// Get customer by email+ /// Get customer by email.+ /// When <paramref name="storeId" /> is supplied (per-store customer identity) the lookup is scoped to+ /// that store; when it is empty the customer is resolved globally (default behaviour)./// </summary>/// <param name="email">Email</param>+ /// <param name="storeId">Store identifier (optional)</param>/// <returns>Customer</returns>- Task<Customer> GetCustomerByEmail(string email);+ Task<Customer> GetCustomerByEmail(string email, string storeId = "");/// <summary>/// Get customer by system group@@ -118,11 +121,14 @@ public interface ICustomerServiceTask<Customer> GetCustomerBySystemName(string systemName);/// <summary>- /// Get customer by username+ /// Get customer by username.+ /// When <paramref name="storeId" /> is supplied (per-store customer identity) the lookup is scoped to+ /// that store; when it is empty the customer is resolved globally (default behaviour)./// </summary>/// <param name="username">Username</param>+ /// <param name="storeId">Store identifier (optional)</param>/// <returns>Customer</returns>- Task<Customer> GetCustomerByUsername(string username);+ Task<Customer> GetCustomerByUsername(string username, string storeId = "");/// <summary>/// Insert a guest customerdiff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.csindex b0c5bbc2e..b32096d71 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs@@ -78,11 +78,11 @@ public class CustomerManagerService : ICustomerManagerService/// <param name="usernameOrEmail">Username or email</param>/// <param name="password">Password</param>/// <returns>Result</returns>- public virtual async Task<CustomerLoginResults> LoginCustomer(string usernameOrEmail, string password)+ public virtual async Task<CustomerLoginResults> LoginCustomer(string usernameOrEmail, string password, string storeId = ""){var customer = _customerSettings.UsernamesEnabled- ? await _customerService.GetCustomerByUsername(usernameOrEmail)- : await _customerService.GetCustomerByEmail(usernameOrEmail);+ ? await _customerService.GetCustomerByUsername(usernameOrEmail, storeId)+ : await _customerService.GetCustomerByEmail(usernameOrEmail, storeId);var pwd = customer.PasswordFormatId switch {PasswordFormat.Clear => password,@@ -168,11 +168,11 @@ public class CustomerManagerService : ICustomerManagerService/// Change password/// </summary>/// <param name="request">Request</param>- public virtual async Task ChangePassword(ChangePasswordRequest request)+ public virtual async Task ChangePassword(ChangePasswordRequest request, string storeId = ""){ArgumentNullException.ThrowIfNull(request);- var customer = await _customerService.GetCustomerByEmail(request.Email);+ var customer = await _customerService.GetCustomerByEmail(request.Email, storeId);ArgumentNullException.ThrowIfNull(customer);switch (request.PasswordFormat)diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.csindex ea0ad56a8..538cf4732 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs@@ -8,6 +8,7 @@ using Grand.Domain.Orders;using Grand.Domain.Shipping;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using Grand.SharedKernel;using Grand.SharedKernel.Extensions;@@ -26,11 +27,13 @@ public class CustomerService : ICustomerServicepublic CustomerService(IRepository<Customer> customerRepository,IMediator mediator,- ICacheBase cacheBase)+ ICacheBase cacheBase,+ CustomerConfig customerConfig){_customerRepository = customerRepository;_mediator = mediator;_cacheBase = cacheBase;+ _customerConfig = customerConfig;}#endregion@@ -40,6 +43,7 @@ public class CustomerService : ICustomerServiceprivate readonly IRepository<Customer> _customerRepository;private readonly IMediator _mediator;private readonly ICacheBase _cacheBase;+ private readonly CustomerConfig _customerConfig;#endregion@@ -224,9 +228,37 @@ public class CustomerService : ICustomerService/// </summary>/// <param name="email">Email</param>/// <returns>Customer</returns>- public virtual Task<Customer> GetCustomerByEmail(string email)+ public virtual async Task<Customer> GetCustomerByEmail(string email, string storeId = ""){- return string.IsNullOrWhiteSpace(email) ? Task.FromResult<Customer>(null) : _customerRepository.GetOneAsync(x => x.Email == email.ToLowerInvariant());+ if (string.IsNullOrWhiteSpace(email))+ return null;++ var loweredEmail = email.ToLowerInvariant();+ if (!string.IsNullOrEmpty(storeId))+ {+ var inStore = await _customerRepository.GetOneAsync(x => x.Email == loweredEmail && x.StoreId == storeId);+ if (inStore != null)+ return inStore;++ if (!_customerConfig.RegisterCustomersPerStore)+ return null;++ return await _customerRepository.GetOneAsync(x =>+ x.Email == loweredEmail && (x.StoreId == null || x.StoreId == ""));+ }++ //global (store-independent) lookup. With per-store identity the same email may exist in several+ //stores, so prefer the store-independent account (system/admin/back-office created without a store)+ //to make sure e.g. admin panel login is not shadowed by a store customer that reused the email.+ if (_customerConfig.RegisterCustomersPerStore)+ {+ var storeless = await _customerRepository.GetOneAsync(x =>+ x.Email == loweredEmail && (x.StoreId == null || x.StoreId == ""));+ if (storeless != null)+ return storeless;+ }++ return await _customerRepository.GetOneAsync(x => x.Email == loweredEmail);}/// <summary>@@ -249,12 +281,37 @@ public class CustomerService : ICustomerService/// </summary>/// <param name="username">Username</param>/// <returns>Customer</returns>- public virtual Task<Customer> GetCustomerByUsername(string username)+ public virtual async Task<Customer> GetCustomerByUsername(string username, string storeId = ""){if (string.IsNullOrWhiteSpace(username))- return Task.FromResult<Customer>(null);+ return null;++ var loweredUsername = username.ToLowerInvariant();+ if (!string.IsNullOrEmpty(storeId))+ {+ var inStore = await _customerRepository.GetOneAsync(x => x.Username == loweredUsername && x.StoreId == storeId);+ if (inStore != null)+ return inStore;++ //no customer for this store: without per-store identity there is no fallback; with it, a+ //store-scoped lookup must still reach the store-independent system/back-office account+ if (!_customerConfig.RegisterCustomersPerStore)+ return null;++ return await _customerRepository.GetOneAsync(x =>+ x.Username == loweredUsername && (x.StoreId == null || x.StoreId == ""));+ }++ //global (store-independent) lookup - prefer the store-independent account (see GetCustomerByEmail)+ if (_customerConfig.RegisterCustomersPerStore)+ {+ var storeless = await _customerRepository.GetOneAsync(x =>+ x.Username == loweredUsername && (x.StoreId == null || x.StoreId == ""));+ if (storeless != null)+ return storeless;+ }- return _customerRepository.GetOneAsync(x => x.Username == username.ToLowerInvariant());+ return await _customerRepository.GetOneAsync(x => x.Username == loweredUsername);}/// <summary>diff --git a/src/Core/Grand.Infrastructure/Configuration/CustomerConfig.cs b/src/Core/Grand.Infrastructure/Configuration/CustomerConfig.csnew file mode 100644index 000000000..1fa860ae5--- /dev/null+++ b/src/Core/Grand.Infrastructure/Configuration/CustomerConfig.cs@@ -0,0 +1,30 @@+namespace Grand.Infrastructure.Configuration;++/// <summary>+/// Represents a Customer Config (bound from the "Customer" section of appsettings.json)+/// </summary>+public class CustomerConfig+{+ /// <summary>+ /// Gets or sets a value indicating whether customer accounts are scoped per store.+ /// <para>+ /// When <c>false</c> (default), the customer uniqueness key is the e-mail address (and username)+ /// alone — an e-mail can only ever belong to a single customer across the whole installation.+ /// </para>+ /// <para>+ /// When <c>true</c>, the uniqueness key becomes the pair (e-mail / username + <c>StoreId</c>).+ /// The same e-mail address may therefore be registered independently in two different stores as+ /// two separate, unrelated accounts. This affects: customer registration, storefront login,+ /// the re-resolution of the authenticated customer from the auth cookie, password recovery and+ /// the duplicate-checks performed by the Admin / Store-manager customer editors.+ /// </para>+ /// <para>+ /// NOTE: customers are still stored in a single collection (they are discriminated by the+ /// <c>StoreId</c> field — there is no separate collection per store). Uniqueness is enforced at+ /// the application layer; the customer lookup index is the compound (Email + StoreId) index.+ /// Changing this value on a live installation that already contains duplicate e-mails across+ /// stores can make some accounts unreachable, so set it before going live.+ /// </para>+ /// </summary>+ public bool RegisterCustomersPerStore { get; set; }+}diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.csindex 34b6dc411..539bfc929 100644--- a/src/Core/Grand.Infrastructure/StartupBase.cs+++ b/src/Core/Grand.Infrastructure/StartupBase.cs@@ -214,6 +214,7 @@ public static class StartupBase});services.StartupConfig<AppConfig>(configuration.GetSection("Application"));+ services.StartupConfig<CustomerConfig>(configuration.GetSection("Customer"));services.StartupConfig<PerformanceConfig>(configuration.GetSection("Performance"));services.StartupConfig<SecurityConfig>(configuration.GetSection("Security"));services.StartupConfig<ExtensionsConfig>(configuration.GetSection("Extensions"));diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.csindex a77d92170..4e4f2db57 100644--- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs+++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerCommandHandler.cs@@ -1,5 +1,7 @@using Grand.Business.Core.Interfaces.Customers;+using Grand.Infrastructure.Configuration;using Grand.Module.Api.Commands.Models.Customers;+using Grand.SharedKernel;using MediatR;namespace Grand.Module.Api.Commands.Handlers.Customers;@@ -7,16 +9,27 @@ namespace Grand.Module.Api.Commands.Handlers.Customers;public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerCommand, bool>{private readonly ICustomerService _customerService;+ private readonly CustomerConfig _customerConfig;- public DeleteCustomerCommandHandler(ICustomerService customerService)+ public DeleteCustomerCommandHandler(ICustomerService customerService, CustomerConfig customerConfig){_customerService = customerService;+ _customerConfig = customerConfig;}public async Task<bool> Handle(DeleteCustomerCommand request, CancellationToken cancellationToken){var customer = await _customerService.GetCustomerByEmail(request.Email);- if (customer != null) await _customerService.DeleteCustomer(customer);+ if (customer == null) return true;++ //Under per-store customer identity the e-mail is not a unique key, and the global lookup prefers+ //the store-independent (system/back-office/admin) account. Refuse to delete such an account through+ //this by-email API so an attempt to remove a store customer can never destroy the administrator.+ if (_customerConfig.RegisterCustomersPerStore && string.IsNullOrEmpty(customer.StoreId))+ throw new GrandException(+ "Refusing to delete a store-independent (system/back-office) account by e-mail while per-store customer identity is enabled");++ await _customerService.DeleteCustomer(customer);return true;}diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.csindex 326a0a2df..fc560f3fe 100644--- a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs+++ b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs@@ -35,7 +35,8 @@ public class TokenWebController : ControllerBaseIContextAccessor contextAccessor,IRefreshTokenService refreshTokenService,IAntiforgery antiforgery,- FrontendAPIConfig apiConfig)+ FrontendAPIConfig apiConfig,+ CustomerConfig customerConfig){_customerService = customerService;_mediator = mediator;@@ -43,8 +44,17 @@ public class TokenWebController : ControllerBase_refreshTokenService = refreshTokenService;_antiforgery = antiforgery;_apiConfig = apiConfig;+ _customerConfig = customerConfig;}+ private readonly CustomerConfig _customerConfig;++ /// <summary>+ /// The current store id when per-store customer identity is enabled, otherwise empty (global lookup).+ /// </summary>+ private string CustomerStoreId =>+ _customerConfig.RegisterCustomersPerStore ? _contextAccessor.StoreContext.CurrentStore.Id : "";+[AllowAnonymous][IgnoreAntiforgeryToken][HttpPost]@@ -80,9 +90,10 @@ public class TokenWebController : ControllerBasetry{- var customer = await _customerService.GetCustomerByEmail(model.Email);+ var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId);var claims = new Dictionary<string, string> {- { "Email", model.Email },+ { "CustomerId", customer.Id },+ { "Email", model.Email },{ "Token", customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken) }};var tokenDto = await GetToken(claims, customer);@@ -102,34 +113,46 @@ public class TokenWebController : ControllerBaseif (!_apiConfig.Enabled)return BadRequest("API is disabled");- string email;Customer customer = null;var claims = new Dictionary<string, string>();ClaimsPrincipal principal;+ string customerId;+ string email;+ string guid;try{principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken);- email = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;+ customerId = principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value;+ email = principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value;+ guid = principal.Claims.FirstOrDefault(x => x.Type == "Guid")?.Value;}catch (Exception){return BadRequest("Invalid access token");}- if (!string.IsNullOrEmpty(email))- {+ //prefer the stable customer id (unambiguous with per-store identity); fall back to e-mail/guid for+ //tokens issued before the id claim existed+ if (!string.IsNullOrEmpty(customerId))+ customer = await _customerService.GetCustomerById(customerId);+ else if (!string.IsNullOrEmpty(email))customer = await _customerService.GetCustomerByEmail(email);- claims.Add("Email", email);+ else if (!string.IsNullOrEmpty(guid))+ customer = await _customerService.GetCustomerByGuid(Guid.Parse(guid));++ if (customer == null)+ return BadRequest("Invalid access token");++ //rebuild the claims from the resolved customer (registered carry id/email/token, guests carry the guid)+ if (!string.IsNullOrEmpty(customer.Email))+ {+ claims.Add("CustomerId", customer.Id);+ claims.Add("Email", customer.Email);claims.Add("Token", customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.PasswordToken));}else{- var guid = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;- if (guid != null)- {- customer = await _customerService.GetCustomerByGuid(Guid.Parse(guid));- claims.Add("Guid", guid);- }+ claims.Add("Guid", customer.CustomerGuid.ToString());}var customerRefreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.csindex ebc17d0ca..29349e51d 100644--- a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs+++ b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs@@ -2,6 +2,7 @@using Grand.Module.Api.Models.Common;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;+using Grand.Infrastructure;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;@@ -13,9 +14,15 @@ public class LoginWebValidator : BaseGrandValidator<LoginWebModel>IEnumerable<IValidatorConsumer<LoginWebModel>> validators,FrontendAPIConfig apiConfig,ICustomerService customerService,- ICustomerManagerService customerManagerService)+ ICustomerManagerService customerManagerService,+ IContextAccessor contextAccessor,+ CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? contextAccessor.StoreContext.CurrentStore.Id+ : "";+if (!apiConfig.Enabled){RuleFor(x => x).Must(_ => false).WithMessage("API is disabled");@@ -28,12 +35,12 @@ public class LoginWebValidator : BaseGrandValidator<LoginWebModel>{if (!string.IsNullOrEmpty(x.Email)){- var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant());+ var customer = await customerService.GetCustomerByEmail(x.Email.ToLowerInvariant(), storeId);if (customer is { Active: true } && !customer.IsSystemAccount()){var base64EncodedBytes = Convert.FromBase64String(x.Password);var password = Encoding.UTF8.GetString(base64EncodedBytes);- var result = await customerManagerService.LoginCustomer(x.Email, password);+ var result = await customerManagerService.LoginCustomer(x.Email, password, storeId);return result == CustomerLoginResults.Successful;}}diff --git a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs b/src/Modules/Grand.Module.Installer/Services/InstallationService.csindex 4c8ec00b3..e7e0efa51 100644--- a/src/Modules/Grand.Module.Installer/Services/InstallationService.cs+++ b/src/Modules/Grand.Module.Installer/Services/InstallationService.cs@@ -406,6 +406,9 @@ public partial class InstallationService : IInstallationServiceprivate readonly IWebHostEnvironment _hostingEnvironment;private readonly IServiceProvider _serviceProvider;+ private const string CustomerId = "CustomerId";+ private const string ProductCategoriesCategoryId = "ProductCategories.CategoryId";+#endregion#region Utilities@@ -494,6 +497,12 @@ public partial class InstallationService : IInstallationService"CustomerGuid_1");await dbContext.CreateIndex(_customerRepository, OrderBuilder<Customer>.Create().Ascending(x => x.Email),"Email_1");+ //compound lookup indexes supporting per-store customer identity (uniqueness of Email/Username + StoreId+ //is enforced at the application layer, gated by the "Customer:RegisterCustomersPerStore" setting)+ await dbContext.CreateIndex(_customerRepository,+ OrderBuilder<Customer>.Create().Ascending(x => x.Email).Ascending(x => x.StoreId), "Email_StoreId");+ await dbContext.CreateIndex(_customerRepository,+ OrderBuilder<Customer>.Create().Ascending(x => x.Username).Ascending(x => x.StoreId), "Username_StoreId");await dbContext.CreateIndex(_customerRepository,OrderBuilder<Customer>.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc");@@ -551,12 +560,12 @@ public partial class InstallationService : IInstallationService//customer history passwordawait dbContext.CreateIndex(_customerHistoryPasswordRepository,OrderBuilder<CustomerHistoryPassword>.Create().Ascending(x => x.CustomerId).Descending(x => x.CreatedOnUtc),- "CustomerId");+ CustomerId);//customer noteawait dbContext.CreateIndex(_customerNoteRepository,OrderBuilder<CustomerNote>.Create().Ascending(x => x.CustomerId).Descending(x => x.CreatedOnUtc),- "CustomerId");+ CustomerId);await dbContext.CreateIndex(_customerNoteRepository,OrderBuilder<CustomerNote>.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc");@@ -638,23 +647,23 @@ public partial class InstallationService : IInstallationServiceOrderBuilder<Product>.Create().Ascending("ProductCategories.DisplayOrder"), "CategoryId_1_DisplayOrder_1");await dbContext.CreateIndex(_productRepository,OrderBuilder<Product>.Create().Ascending(x => x.Published).Ascending(x => x.VisibleIndividually)- .Ascending(x => x.DisplayOrderCategory).Ascending("ProductCategories.CategoryId"),+ .Ascending(x => x.DisplayOrderCategory).Ascending(ProductCategoriesCategoryId),"ProductCategories.CategoryId_1_OrderCategory_1");await dbContext.CreateIndex(_productRepository,OrderBuilder<Product>.Create().Ascending(x => x.Published).Ascending(x => x.VisibleIndividually)- .Ascending(x => x.Name).Ascending("ProductCategories.CategoryId"),+ .Ascending(x => x.Name).Ascending(ProductCategoriesCategoryId),"ProductCategories.CategoryId_1_Name_1");await dbContext.CreateIndex(_productRepository,OrderBuilder<Product>.Create().Ascending(x => x.Published).Ascending(x => x.VisibleIndividually)- .Ascending(x => x.Price).Ascending("ProductCategories.CategoryId"),+ .Ascending(x => x.Price).Ascending(ProductCategoriesCategoryId),"ProductCategories.CategoryId_1_Price_1");await dbContext.CreateIndex(_productRepository,OrderBuilder<Product>.Create().Ascending(x => x.Published).Ascending(x => x.VisibleIndividually)- .Ascending(x => x.Sold).Ascending("ProductCategories.CategoryId"),+ .Ascending(x => x.Sold).Ascending(ProductCategoriesCategoryId),"ProductCategories.CategoryId_1_Sold_1");await dbContext.CreateIndex(_productRepository,OrderBuilder<Product>.Create().Ascending(x => x.Published).Ascending(x => x.VisibleIndividually)- .Ascending("ProductCategories.CategoryId").Ascending("ProductCategories.IsFeaturedProduct"),+ .Ascending(ProductCategoriesCategoryId).Ascending("ProductCategories.IsFeaturedProduct"),"ProductCategories.CategoryId_1_IsFeaturedProduct_1");await dbContext.CreateIndex(_productRepository,OrderBuilder<Product>.Create().Ascending("ProductCollections.CollectionId").Ascending(x => x.Published)@@ -794,7 +803,7 @@ public partial class InstallationService : IInstallationServiceOrderBuilder<DiscountCoupon>.Create().Ascending(x => x.DiscountId), "DiscountId");await dbContext.CreateIndex(_discountusageRepository,- OrderBuilder<DiscountUsageHistory>.Create().Ascending(x => x.CustomerId), "CustomerId");+ OrderBuilder<DiscountUsageHistory>.Create().Ascending(x => x.CustomerId), CustomerId);await dbContext.CreateIndex(_discountusageRepository,OrderBuilder<DiscountUsageHistory>.Create().Ascending(x => x.DiscountId), "DiscountId");await dbContext.CreateIndex(_discountusageRepository,@@ -830,7 +839,7 @@ public partial class InstallationService : IInstallationService//newsletterawait dbContext.CreateIndex(_newslettersubscriptionRepository,- OrderBuilder<NewsLetterSubscription>.Create().Ascending(x => x.CustomerId), "CustomerId");+ OrderBuilder<NewsLetterSubscription>.Create().Ascending(x => x.CustomerId), CustomerId);await dbContext.CreateIndex(_newslettersubscriptionRepository,OrderBuilder<NewsLetterSubscription>.Create().Ascending(x => x.Email), "Email");@@ -843,7 +852,7 @@ public partial class InstallationService : IInstallationService//loyalty pointsawait dbContext.CreateIndex(_loyaltypointshistoryRepository,- OrderBuilder<LoyaltyPointsHistory>.Create().Ascending(x => x.CustomerId), "CustomerId");+ OrderBuilder<LoyaltyPointsHistory>.Create().Ascending(x => x.CustomerId), CustomerId);await dbContext.CreateIndex(_loyaltypointshistoryRepository,OrderBuilder<LoyaltyPointsHistory>.Create().Descending(x => x.CreatedOnUtc), "CreatedOnUtc");@@ -914,7 +923,7 @@ public partial class InstallationService : IInstallationService//externalauthawait dbContext.CreateIndex(_externalAuthenticationRepository,- OrderBuilder<ExternalAuthentication>.Create().Ascending(x => x.CustomerId), "CustomerId");+ OrderBuilder<ExternalAuthentication>.Create().Ascending(x => x.CustomerId), CustomerId);//merchandise returnawait dbContext.CreateIndex(_merchandiseReturnRepository,diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.csindex 1654a0d89..2599bcbd9 100644--- a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs@@ -113,6 +113,27 @@ public class CookieAuthenticationServiceTestsAssert.AreEqual(customer.Username, expectedCustomer.Username);}+ [TestMethod]+ public async Task GetAuthenticatedCustomer_WithCustomerIdClaim_ResolvesById_ReturnCustomer()+ {+ var expectedCustomer = new Customer { Id = "cust-1", Email = "[email protected]", Active = true };+ var claims = new List<Claim> {+ new("grand:customerId", "cust-1", ClaimValueTypes.String, "grandnode")+ };+ var principals =+ new ClaimsPrincipal(new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme));+ _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))+ .Returns(() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principals, ""))));+ _customerServiceMock.Setup(c => c.GetCustomerById("cust-1")).ReturnsAsync(expectedCustomer);+ _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));++ var customer = await _cookieAuthService.GetAuthenticatedCustomer();++ Assert.IsNotNull(customer);+ Assert.AreEqual("cust-1", customer.Id);+ _customerServiceMock.Verify(c => c.GetCustomerById("cust-1"), Times.Once);+ }+[TestMethod]public async Task GetAuthenticatedCustomer_UsernameEnableGuests_ReturnNull(){diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.csindex ec45adec1..5d42643a6 100644--- a/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs@@ -127,6 +127,36 @@ public class JwtBearerCustomerAuthenticationServiceTestsawait _jwtBearerCustomerAuthenticationService.ErrorMessage());}+ [TestMethod]+ public async Task Valid_WithCustomerIdClaim_ResolvesById_ReturnTrue()+ {+ var customer = new Customer { Id = "cust-1", Username = "John", Active = true };+ customer.UserFields.Add(new UserField+ { Key = SystemCustomerFieldNames.PasswordToken, Value = "123", StoreId = "" });+ _customerServiceMock.Setup(c => c.GetCustomerById("cust-1")).ReturnsAsync(customer);+ _refreshTokenServiceMock.Setup(c => c.GetCustomerRefreshToken(customer)).Returns(() =>+ Task.FromResult(new RefreshToken { IsActive = true, RefreshId = "567", Token = "123" }));+ _permissionServiceMock.Setup(c => c.Authorize(StandardPermission.AllowUseApi, customer))+ .ReturnsAsync(true);+ var httpContext = new Mock<HttpContext>();+ var context = new TokenValidatedContext(httpContext.Object,+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());+ IList<Claim> claims = new List<Claim> {+ new("CustomerId", "cust-1"),+ new("Email", "[email protected]"),+ new("Token", "123"),+ new("RefreshId", "567")+ };+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));++ var result = await _jwtBearerCustomerAuthenticationService.Valid(context);++ Assert.IsTrue(result);+ //resolved by the stable id, not by e-mail+ _customerServiceMock.Verify(c => c.GetCustomerById("cust-1"), Times.Once);+ _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()), Times.Never);+ }+[TestMethod]public async Task Valid_Customer_ReturnTrue(){diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionProviderTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionProviderTests.csnew file mode 100644index 000000000..5eb36f462--- /dev/null+++ b/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionProviderTests.cs@@ -0,0 +1,23 @@+using Grand.Business.Common.Services.Security;+using Grand.Domain.Customers;+using Grand.Domain.Permissions;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using System.Linq;++namespace Grand.Business.Common.Tests.Services.Security;++[TestClass]+public class PermissionProviderTests+{+ private readonly PermissionProvider _provider = new();++ [TestMethod]+ public void StoreManager_DefaultPermissions_IncludeManageCustomers()+ {+ var storeManager = _provider.GetDefaultPermissions()+ .FirstOrDefault(p => p.CustomerGroupSystemName == SystemCustomerGroupNames.StoreManager);++ Assert.IsNotNull(storeManager);+ CollectionAssert.Contains(storeManager.Permissions.ToList(), StandardPermission.ManageCustomers);+ }+}diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.csindex 07348f69f..3314e2eab 100644--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs@@ -66,6 +66,35 @@ public class CustomerManagerServiceTestsAssert.AreEqual(CustomerLoginResults.Successful, result);}+ [TestMethod]+ public async Task LoginCustomer_PassesStoreIdToLookup()+ {+ //Arrange+ var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };+ _customerServiceMock.Setup(c => c.GetCustomerByEmail("[email protected]", "store-1"))+ .ReturnsAsync(customer);+ _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).ReturnsAsync(true);+ //Act+ var result = await _customerManagerService.LoginCustomer("[email protected]", "123456", "store-1");+ //Assert+ Assert.AreEqual(CustomerLoginResults.Successful, result);+ _customerServiceMock.Verify(c => c.GetCustomerByEmail("[email protected]", "store-1"), Times.Once);+ }++ [TestMethod]+ public async Task ChangePassword_PassesStoreIdToLookup()+ {+ //Arrange+ var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };+ _customerServiceMock.Setup(c => c.GetCustomerByEmail("[email protected]", "store-1"))+ .ReturnsAsync(customer);+ var changepassword = new ChangePasswordRequest("[email protected]", PasswordFormat.Clear, "zxcvbn", "123456");+ //Act+ await _customerManagerService.ChangePassword(changepassword, "store-1");+ //Assert+ _customerServiceMock.Verify(c => c.GetCustomerByEmail("[email protected]", "store-1"), Times.Once);+ }+[TestMethod]public async Task ChangePasswordTest_Success(){diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.csindex 8b6ba3239..11bb8e2f9 100644--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs@@ -30,9 +30,17 @@ public class CustomerServiceTests_cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,new CacheConfig { DefaultCacheTimeMinutes = 1 });- _customerService = new CustomerService(_repository, _mediatorMock.Object, _cacheBase);+ _customerService = new CustomerService(_repository, _mediatorMock.Object, _cacheBase,+ _customerConfig);}+ private readonly CustomerConfig _customerConfig = new() { RegisterCustomersPerStore = true };++ //builds a service over the same in-memory repository with the per-store flag explicitly set+ private CustomerService CreateService(bool registerCustomersPerStore) =>+ new(_repository, _mediatorMock.Object, _cacheBase,+ new CustomerConfig { RegisterCustomersPerStore = registerCustomersPerStore });+[TestMethod]public async Task GetOnlineCustomersTest()@@ -135,6 +143,174 @@ public class CustomerServiceTestsAssert.IsNotNull(result);}+ [TestMethod]+ public async Task GetCustomerByEmail_WithStoreId_ReturnsOnlyMatchingStore()+ {+ //Arrange - same e-mail in two stores (per-store customer identity)+ const string email = "[email protected]";+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "store-1" });+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "store-2" });+ //Act+ var result = await _customerService.GetCustomerByEmail(email, "store-2");+ //Assert+ Assert.IsNotNull(result);+ Assert.AreEqual("store-2", result.StoreId);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_WithStoreId_NoMatch_ReturnsNull()+ {+ //Arrange+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "store-1" });+ //Act+ var result = await _customerService.GetCustomerByEmail("[email protected]", "other-store");+ //Assert+ Assert.IsNull(result);+ }++ [TestMethod]+ public async Task GetCustomerByUsername_WithStoreId_ReturnsOnlyMatchingStore()+ {+ //Arrange - same username in two stores+ await _repository.InsertAsync(new Customer { Username = "user", StoreId = "store-1" });+ await _repository.InsertAsync(new Customer { Username = "user", StoreId = "store-2" });+ //Act+ var result = await _customerService.GetCustomerByUsername("user", "store-1");+ //Assert+ Assert.IsNotNull(result);+ Assert.AreEqual("store-1", result.StoreId);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_StoreScoped_FallsBackToStorelessAccount()+ {+ //Arrange - only the store-independent admin account exists (no customer for this store)+ const string email = "[email protected]";+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "" });+ //Act - storefront login scoped to a store must still find the storeless admin+ var result = await _customerService.GetCustomerByEmail(email, "store-1");+ //Assert+ Assert.IsNotNull(result);+ Assert.AreEqual("", result.StoreId);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_StoreScoped_PrefersStoreCustomerOverStoreless()+ {+ //Arrange - both a store customer and the storeless admin share the email+ const string email = "[email protected]";+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "" });+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "store-1" });+ //Act+ var result = await _customerService.GetCustomerByEmail(email, "store-1");+ //Assert - the store's own customer wins within that store+ Assert.IsNotNull(result);+ Assert.AreEqual("store-1", result.StoreId);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_GlobalLookup_PrefersStorelessAccount()+ {+ //Arrange - a store customer reused the same email as the store-independent admin account+ const string email = "[email protected]";+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "store-2" });+ await _repository.InsertAsync(new Customer { Email = email, StoreId = "" }); //admin / back-office+ //Act - global lookup (e.g. back-office login) must not be shadowed by the store customer+ var result = await _customerService.GetCustomerByEmail(email);+ //Assert+ Assert.IsNotNull(result);+ Assert.AreEqual("", result.StoreId);+ }++ #region GetCustomerByEmail - full branch coverage++ [TestMethod]+ public async Task GetCustomerByEmail_NullEmail_ReturnsNull()+ {+ await _repository.InsertAsync(new Customer { Email = "[email protected]" });+ var result = await _customerService.GetCustomerByEmail(null);+ Assert.IsNull(result);+ }++ [DataTestMethod]+ [DataRow("")]+ [DataRow(" ")]+ public async Task GetCustomerByEmail_EmptyOrWhitespaceEmail_ReturnsNull(string email)+ {+ await _repository.InsertAsync(new Customer { Email = "[email protected]" });+ var result = await _customerService.GetCustomerByEmail(email);+ Assert.IsNull(result);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_IsCaseInsensitive()+ {+ //stored lowercased; the lookup must lowercase the input+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "" });+ var result = await _customerService.GetCustomerByEmail("[email protected]");+ Assert.IsNotNull(result);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_StoreScoped_FallsBackToAccountWithNullStoreId()+ {+ //admin created without a store leaves StoreId null (not just "") - the fallback must match it too+ await _repository.InsertAsync(new Customer { Email = "[email protected]" });+ var result = await _customerService.GetCustomerByEmail("[email protected]", "store-1");+ Assert.IsNotNull(result);+ Assert.IsTrue(string.IsNullOrEmpty(result.StoreId));+ }++ [TestMethod]+ public async Task GetCustomerByEmail_PerStoreOn_Global_NoStoreless_FallsBackToAnyMatch()+ {+ //only a store customer exists (no store-independent account) - global lookup still returns it+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "store-1" });+ var result = await _customerService.GetCustomerByEmail("[email protected]");+ Assert.IsNotNull(result);+ Assert.AreEqual("store-1", result.StoreId);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_PerStoreOn_StoreScoped_NoMatchAndNoStoreless_ReturnsNull()+ {+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "store-1" });+ var result = await _customerService.GetCustomerByEmail("[email protected]", "store-2");+ Assert.IsNull(result);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_PerStoreOff_StoreScoped_ReturnsExactStoreMatch()+ {+ var service = CreateService(registerCustomersPerStore: false);+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "store-1" });+ var result = await service.GetCustomerByEmail("[email protected]", "store-1");+ Assert.IsNotNull(result);+ Assert.AreEqual("store-1", result.StoreId);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_PerStoreOff_StoreScoped_DoesNotFallBackToStoreless()+ {+ var service = CreateService(registerCustomersPerStore: false);+ //a store-independent account exists, but with the flag off there is no fallback+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "" });+ var result = await service.GetCustomerByEmail("[email protected]", "store-1");+ Assert.IsNull(result);+ }++ [TestMethod]+ public async Task GetCustomerByEmail_PerStoreOff_Global_ReturnsMatch()+ {+ var service = CreateService(registerCustomersPerStore: false);+ await _repository.InsertAsync(new Customer { Email = "[email protected]", StoreId = "store-1" });+ var result = await service.GetCustomerByEmail("[email protected]");+ Assert.IsNotNull(result);+ Assert.AreEqual("store-1", result.StoreId);+ }++ #endregion+[TestMethod]public async Task InsertGuestCustomerTest(){diff --git a/src/Tests/Grand.Module.Api.Tests/Commands/Customers/DeleteCustomerCommandHandlerTests.cs b/src/Tests/Grand.Module.Api.Tests/Commands/Customers/DeleteCustomerCommandHandlerTests.csnew file mode 100644index 000000000..0357f1434--- /dev/null+++ b/src/Tests/Grand.Module.Api.Tests/Commands/Customers/DeleteCustomerCommandHandlerTests.cs@@ -0,0 +1,82 @@+using Grand.Business.Core.Interfaces.Customers;+using Grand.Domain.Customers;+using Grand.Infrastructure.Configuration;+using Grand.Module.Api.Commands.Handlers.Customers;+using Grand.Module.Api.Commands.Models.Customers;+using Grand.SharedKernel;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Module.Api.Tests.Commands.Customers;++[TestClass]+public class DeleteCustomerCommandHandlerTests+{+ private Mock<ICustomerService> _customerServiceMock;++ [TestInitialize]+ public void Init()+ {+ _customerServiceMock = new Mock<ICustomerService>();+ }++ private DeleteCustomerCommandHandler CreateHandler(bool perStore) =>+ new(_customerServiceMock.Object, new CustomerConfig { RegisterCustomersPerStore = perStore });++ [TestMethod]+ public async Task Handle_CustomerNotFound_ReturnsTrue_AndDoesNotDelete()+ {+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))+ .ReturnsAsync((Customer)null);+ var handler = CreateHandler(perStore: true);++ var result = await handler.Handle(new DeleteCustomerCommand { Email = "[email protected]" }, default);++ Assert.IsTrue(result);+ _customerServiceMock.Verify(c => c.DeleteCustomer(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);+ }++ [TestMethod]+ public async Task Handle_StoreCustomer_Deletes()+ {+ var customer = new Customer { Id = "c1", Email = "[email protected]", StoreId = "store-1" };+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))+ .ReturnsAsync(customer);+ var handler = CreateHandler(perStore: true);++ var result = await handler.Handle(new DeleteCustomerCommand { Email = "[email protected]" }, default);++ Assert.IsTrue(result);+ _customerServiceMock.Verify(c => c.DeleteCustomer(customer, It.IsAny<bool>()), Times.Once);+ }++ [TestMethod]+ public async Task Handle_PerStoreOn_StorelessAccount_Refuses()+ {+ //the by-email lookup resolved a store-independent (admin/back-office) account+ var admin = new Customer { Id = "admin", Email = "[email protected]", StoreId = "" };+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))+ .ReturnsAsync(admin);+ var handler = CreateHandler(perStore: true);++ await Assert.ThrowsExactlyAsync<GrandException>(() =>+ handler.Handle(new DeleteCustomerCommand { Email = "[email protected]" }, default));++ _customerServiceMock.Verify(c => c.DeleteCustomer(It.IsAny<Customer>(), It.IsAny<bool>()), Times.Never);+ }++ [TestMethod]+ public async Task Handle_PerStoreOff_StorelessAccount_Deletes()+ {+ //with the flag off the guard does not apply (e-mail is globally unique)+ var customer = new Customer { Id = "c1", Email = "[email protected]", StoreId = "" };+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))+ .ReturnsAsync(customer);+ var handler = CreateHandler(perStore: false);++ var result = await handler.Handle(new DeleteCustomerCommand { Email = "[email protected]" }, default);++ Assert.IsTrue(result);+ _customerServiceMock.Verify(c => c.DeleteCustomer(customer, It.IsAny<bool>()), Times.Once);+ }+}diff --git a/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.cs b/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.csnew file mode 100644index 000000000..8acaa1854--- /dev/null+++ b/src/Tests/Grand.Module.Api.Tests/Controllers/TokenWebControllerTests.cs@@ -0,0 +1,105 @@+using Grand.Business.Core.Interfaces.Authentication;+using Grand.Business.Core.Interfaces.Customers;+using Grand.Domain.Customers;+using Grand.Domain.Security;+using Grand.Domain.Stores;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Module.Api.Commands.Models.Common;+using Grand.Module.Api.Controllers;+using Grand.Module.Api.DTOs;+using Grand.Module.Api.Models.Common;+using MediatR;+using Microsoft.AspNetCore.Antiforgery;+using Microsoft.AspNetCore.Mvc;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;+using System.Security.Claims;++namespace Grand.Module.Api.Tests.Controllers;++[TestClass]+public class TokenWebControllerTests+{+ private const string StoreId = "store-1";++ private Mock<ICustomerService> _customerServiceMock;+ private Mock<IMediator> _mediatorMock;+ private Mock<IRefreshTokenService> _refreshTokenServiceMock;+ private GenerateTokenWebCommand _capturedCommand;++ [TestInitialize]+ public void Init()+ {+ _customerServiceMock = new Mock<ICustomerService>();+ _mediatorMock = new Mock<IMediator>();+ _refreshTokenServiceMock = new Mock<IRefreshTokenService>();++ _refreshTokenServiceMock.Setup(r => r.GenerateRefreshToken()).Returns("rt");+ _refreshTokenServiceMock.Setup(r => r.SaveRefreshTokenToCustomer(It.IsAny<Customer>(), It.IsAny<string>()))+ .ReturnsAsync(new RefreshToken { RefreshId = "rid" });+ _mediatorMock.Setup(m => m.Send(It.IsAny<GenerateTokenWebCommand>(), It.IsAny<CancellationToken>()))+ .Callback((IRequest<string> req, CancellationToken _) => _capturedCommand = req as GenerateTokenWebCommand)+ .ReturnsAsync("jwt");+ }++ private TokenWebController CreateController(bool perStore)+ {+ var storeContext = new Mock<IStoreContext>();+ storeContext.Setup(s => s.CurrentStore).Returns(new Store { Id = StoreId });+ var contextAccessor = new Mock<IContextAccessor>();+ contextAccessor.Setup(c => c.StoreContext).Returns(storeContext.Object);++ return new TokenWebController(+ _customerServiceMock.Object, _mediatorMock.Object, contextAccessor.Object,+ _refreshTokenServiceMock.Object, new Mock<IAntiforgery>().Object,+ new FrontendAPIConfig { Enabled = true },+ new CustomerConfig { RegisterCustomersPerStore = perStore });+ }++ [TestMethod]+ public async Task Login_PerStoreOn_ScopesLookupToStore_AndAddsCustomerIdClaim()+ {+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId))+ .ReturnsAsync(new Customer { Id = "c1" });+ var controller = CreateController(perStore: true);++ var result = await controller.Login(new LoginWebModel { Email = "[email protected]", Password = "p" });++ Assert.IsInstanceOfType(result, typeof(OkObjectResult));+ _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.Once);+ Assert.IsNotNull(_capturedCommand);+ Assert.AreEqual("c1", _capturedCommand.Claims["CustomerId"]);+ }++ [TestMethod]+ public async Task Login_PerStoreOff_UsesGlobalLookup()+ {+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), ""))+ .ReturnsAsync(new Customer { Id = "c1" });+ var controller = CreateController(perStore: false);++ var result = await controller.Login(new LoginWebModel { Email = "[email protected]", Password = "p" });++ Assert.IsInstanceOfType(result, typeof(OkObjectResult));+ _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), ""), Times.Once);+ }++ [TestMethod]+ public async Task Refresh_WithCustomerIdClaim_ResolvesById()+ {+ var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("CustomerId", "c1") }));+ _refreshTokenServiceMock.Setup(r => r.GetPrincipalFromToken("access")).Returns(principal);+ var customer = new Customer { Id = "c1", Email = "[email protected]" };+ _customerServiceMock.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer);+ _refreshTokenServiceMock.Setup(r => r.GetCustomerRefreshToken(customer))+ .ReturnsAsync(new RefreshToken { Token = "rt", ValidTo = DateTime.UtcNow.AddDays(1), RefreshId = "rid" });+ var controller = CreateController(perStore: true);++ var result = await controller.Refresh(new TokenDto { AccessToken = "access", RefreshToken = "rt" });++ Assert.IsInstanceOfType(result, typeof(OkObjectResult));+ _customerServiceMock.Verify(c => c.GetCustomerById("c1"), Times.Once);+ _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()), Times.Never);+ }+}diff --git a/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csproj b/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csprojnew file mode 100644index 000000000..4ecd9d8a6--- /dev/null+++ b/src/Tests/Grand.Module.Api.Tests/Grand.Module.Api.Tests.csproj@@ -0,0 +1,26 @@+<Project Sdk="Microsoft.NET.Sdk">++ <Import Project="..\..\Build\Grand.Common.props" />+ <PropertyGroup>+ <IsPackable>false</IsPackable>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" />+ <PackageReference Include="FluentValidation" />+ <PackageReference Include="MediatR" />+ <PackageReference Include="MongoDB.Bson" />+ <PackageReference Include="Moq" />+ <PackageReference Include="MSTest.TestAdapter" />+ <PackageReference Include="MSTest.TestFramework" />+ <PackageReference Include="coverlet.collector">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />+ <ProjectReference Include="..\..\Modules\Grand.Module.Api\Grand.Module.Api.csproj" />+ </ItemGroup>+</Project>diff --git a/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.csnew file mode 100644index 000000000..3ff4d2d96--- /dev/null+++ b/src/Tests/Grand.Module.Api.Tests/Validators/Common/LoginWebValidatorTests.cs@@ -0,0 +1,100 @@+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Utilities.Customers;+using Grand.Domain.Customers;+using Grand.Domain.Stores;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Infrastructure.Validators;+using Grand.Module.Api.Models.Common;+using Grand.Module.Api.Validators.Common;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;+using System.Text;++namespace Grand.Module.Api.Tests.Validators.Common;++[TestClass]+public class LoginWebValidatorTests+{+ private const string StoreId = "store-1";++ private Mock<ICustomerService> _customerServiceMock;+ private Mock<ICustomerManagerService> _customerManagerServiceMock;+ private Mock<IContextAccessor> _contextAccessorMock;++ [TestInitialize]+ public void Init()+ {+ _customerServiceMock = new Mock<ICustomerService>();+ _customerManagerServiceMock = new Mock<ICustomerManagerService>();++ var storeContextMock = new Mock<IStoreContext>();+ storeContextMock.Setup(s => s.CurrentStore).Returns(new Store { Id = StoreId });+ _contextAccessorMock = new Mock<IContextAccessor>();+ _contextAccessorMock.Setup(c => c.StoreContext).Returns(storeContextMock.Object);+ }++ private LoginWebValidator CreateValidator(bool apiEnabled, bool perStore) =>+ new(new List<IValidatorConsumer<LoginWebModel>>(),+ new FrontendAPIConfig { Enabled = apiEnabled },+ _customerServiceMock.Object,+ _customerManagerServiceMock.Object,+ _contextAccessorMock.Object,+ new CustomerConfig { RegisterCustomersPerStore = perStore });++ private static LoginWebModel ValidModel() => new() {+ Email = "[email protected]",+ Password = Convert.ToBase64String(Encoding.UTF8.GetBytes("secret"))+ };++ [TestMethod]+ public async Task ApiDisabled_Fails()+ {+ var validator = CreateValidator(apiEnabled: false, perStore: true);+ var result = await validator.ValidateAsync(ValidModel());+ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "API is disabled"));+ }++ [TestMethod]+ public async Task PerStoreOn_ValidCredentials_ScopesLookupAndLoginToCurrentStore()+ {+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId))+ .ReturnsAsync(new Customer { Active = true });+ _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny<string>(), It.IsAny<string>(), StoreId))+ .ReturnsAsync(CustomerLoginResults.Successful);++ var validator = CreateValidator(apiEnabled: true, perStore: true);+ var result = await validator.ValidateAsync(ValidModel());++ Assert.IsTrue(result.IsValid);+ _customerServiceMock.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.Once);+ _customerManagerServiceMock.Verify(m => m.LoginCustomer(It.IsAny<string>(), It.IsAny<string>(), StoreId), Times.Once);+ }++ [TestMethod]+ public async Task PerStoreOff_UsesGlobalLookup()+ {+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), ""))+ .ReturnsAsync(new Customer { Active = true });+ _customerManagerServiceMock.Setup(m => m.LoginCustomer(It.IsAny<string>(), It.IsAny<string>(), ""))+ .ReturnsAsync(CustomerLoginResults.Successful);++ var validator = CreateValidator(apiEnabled: true, perStore: false);+ var result = await validator.ValidateAsync(ValidModel());++ Assert.IsTrue(result.IsValid);+ _customerManagerServiceMock.Verify(m => m.LoginCustomer(It.IsAny<string>(), It.IsAny<string>(), ""), Times.Once);+ }++ [TestMethod]+ public async Task WrongCredentials_Fails()+ {+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>(), It.IsAny<string>()))+ .ReturnsAsync((Customer)null);++ var validator = CreateValidator(apiEnabled: true, perStore: true);+ var result = await validator.ValidateAsync(ValidModel());++ Assert.IsTrue(result.Errors.Any(e => e.ErrorMessage == "Customer not exist or password is wrong"));+ }+}diff --git a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.csindex e99f19bde..9cf0644de 100644--- a/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs+++ b/src/Tests/Grand.Web.Admin.Tests/Validators/CustomerValidatorTests.cs@@ -5,6 +5,7 @@ using Grand.Domain;using Grand.Domain.Customers;using Grand.Domain.Stores;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;using Grand.Web.AdminShared.Models.Customers;using Grand.Web.AdminShared.Validators.Customers;@@ -50,7 +51,8 @@ public class CustomerValidatorTestscontextAccessorMock.Object,new Mock<ICustomerService>().Object,_groupServiceMock.Object,- new CustomerSettings());+ new CustomerSettings(),+ new CustomerConfig());}private static CustomerModel BuildModel(string storeId) =>@@ -64,6 +66,17 @@ public class CustomerValidatorTestsAssert.IsTrue(result.Errors.Any(e => e.ErrorMessage == RequiredMessage));}+ [TestMethod]+ public async Task StoreId_Empty_Admin_DoesNotFailRequired()+ {+ //an administrator may manage a store-independent (storeless) account+ _groupServiceMock.Setup(g => g.IsAdmin(It.IsAny<Customer>())).ReturnsAsync(true);++ var result = await _validator.ValidateAsync(BuildModel(string.Empty));++ Assert.IsFalse(result.Errors.Any(e => e.ErrorMessage == RequiredMessage));+ }+[TestMethod]public async Task StoreManager_WrongStore_Fails(){diff --git a/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.cs b/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.csnew file mode 100644index 000000000..2a91c0b62--- /dev/null+++ b/src/Tests/Grand.Web.Store.Tests/Controllers/CustomerControllerTests.cs@@ -0,0 +1,191 @@+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.Customers;+using Grand.Business.Core.Interfaces.Messages;+using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;+using Grand.Web.AdminShared.Interfaces;+using Grand.Web.AdminShared.Models.Customers;+using Grand.Web.Common.Models;+using Grand.Web.Store.Controllers;+using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Abstractions;+using Microsoft.AspNetCore.Mvc.Controllers;+using Microsoft.AspNetCore.Mvc.Filters;+using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.AspNetCore.Routing;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Store.Tests.Controllers;++[TestClass]+public class CustomerControllerTests+{+ private const string StoreId = "store-current";++ private Mock<ICustomerService> _customerServiceMock;+ private Mock<ICustomerViewModelService> _customerViewModelServiceMock;+ private Mock<ICustomerManagerService> _customerManagerServiceMock;+ private Mock<ICustomerAttributeService> _customerAttributeServiceMock;+ private Mock<IGroupService> _groupServiceMock;+ private Mock<ITranslationService> _translationServiceMock;+ private Mock<IContextAccessor> _contextAccessorMock;++ [TestInitialize]+ public void Setup()+ {+ _customerServiceMock = new Mock<ICustomerService>();+ _customerViewModelServiceMock = new Mock<ICustomerViewModelService>();+ _customerManagerServiceMock = new Mock<ICustomerManagerService>();+ _customerAttributeServiceMock = new Mock<ICustomerAttributeService>();+ _groupServiceMock = new Mock<IGroupService>();+ _translationServiceMock = new Mock<ITranslationService>();+ _translationServiceMock.Setup(t => t.GetResource(It.IsAny<string>())).Returns("resource");++ var workContextMock = new Mock<IWorkContext>();+ workContextMock.Setup(w => w.CurrentCustomer).Returns(new Customer { StaffStoreId = StoreId });+ _contextAccessorMock = new Mock<IContextAccessor>();+ _contextAccessorMock.Setup(c => c.WorkContext).Returns(workContextMock.Object);+ }++ private CustomerController BuildController(bool perStoreEnabled)+ {+ var controller = new CustomerController(+ _customerServiceMock.Object,+ _customerViewModelServiceMock.Object,+ _customerManagerServiceMock.Object,+ new Mock<IProductReviewService>().Object,+ new Mock<IProductReviewViewModelService>().Object,+ new Mock<IProductViewModelService>().Object,+ new Mock<ICustomerAttributeParser>().Object,+ _customerAttributeServiceMock.Object,+ new Mock<IAddressAttributeParser>().Object,+ new Mock<IAddressAttributeService>().Object,+ new Mock<IMessageProviderService>().Object,+ _groupServiceMock.Object,+ _translationServiceMock.Object,+ _contextAccessorMock.Object,+ new CustomerSettings(),+ new CustomerConfig { RegisterCustomersPerStore = perStoreEnabled });++ var httpContext = new DefaultHttpContext();+ controller.ControllerContext = new ControllerContext { HttpContext = httpContext };+ controller.TempData = new TempDataDictionary(httpContext, new Mock<ITempDataProvider>().Object);+ return controller;+ }++ private static (ActionExecutingContext context, Func<bool> wasNextCalled) 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>(),+ 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 nextCalled = false;++ await controller.OnActionExecutionAsync(context, () =>+ {+ nextCalled = true;+ return Task.FromResult(new ActionExecutedContext(context, new List<IFilterMetadata>(), controller));+ });++ Assert.IsFalse(nextCalled);+ var redirect = context.Result as RedirectToActionResult;+ Assert.IsNotNull(redirect);+ Assert.AreEqual(nameof(CustomerController.PerStoreDisabled), redirect.ActionName);+ }++ [TestMethod]+ public async Task Gate_PerStoreDisabled_AllowsPerStoreDisabledAction()+ {+ var controller = BuildController(perStoreEnabled: false);+ var (context, _) = BuildGate(controller, nameof(CustomerController.PerStoreDisabled));+ var nextCalled = false;++ await controller.OnActionExecutionAsync(context, () =>+ {+ nextCalled = true;+ return Task.FromResult(new ActionExecutedContext(context, new List<IFilterMetadata>(), controller));+ });++ Assert.IsTrue(nextCalled);+ Assert.IsNull(context.Result);+ }++ [TestMethod]+ public async Task Gate_PerStoreEnabled_CallsNext()+ {+ var controller = BuildController(perStoreEnabled: true);+ var (context, _) = BuildGate(controller, nameof(CustomerController.List));+ var nextCalled = false;++ await controller.OnActionExecutionAsync(context, () =>+ {+ nextCalled = true;+ return Task.FromResult(new ActionExecutedContext(context, new List<IFilterMetadata>(), controller));+ });++ Assert.IsTrue(nextCalled);+ Assert.IsNull(context.Result);+ }++ [TestMethod]+ public void PerStoreDisabled_ReturnsView()+ {+ var controller = BuildController(perStoreEnabled: false);+ var result = controller.PerStoreDisabled();+ Assert.IsInstanceOfType(result, typeof(ViewResult));+ }++ [TestMethod]+ public async Task Create_ForcesStoreScopedRegisteredOnlyConstraints()+ {+ 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>()+ };++ var result = await controller.Create(model, false);++ 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);+ }+}diff --git a/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.cs b/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.csnew file mode 100644index 000000000..39337c109--- /dev/null+++ b/src/Tests/Grand.Web.Tests/Commands/Customers/SubAccountEditCommandHandlerTests.cs@@ -0,0 +1,67 @@+using Grand.Business.Core.Interfaces.Customers;+using Grand.Business.Core.Utilities.Customers;+using Grand.Domain.Customers;+using Grand.Web.Commands.Handler.Customers;+using Grand.Web.Commands.Models.Customers;+using Grand.Web.Models.Customer;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Tests.Commands.Customers;++[TestClass]+public class SubAccountEditCommandHandlerTests+{+ private Mock<ICustomerService> _customerServiceMock;+ private Mock<ICustomerManagerService> _customerManagerServiceMock;+ private SubAccountEditCommandHandler _handler;++ [TestInitialize]+ public void Init()+ {+ _customerServiceMock = new Mock<ICustomerService>();+ _customerManagerServiceMock = new Mock<ICustomerManagerService>();+ _handler = new SubAccountEditCommandHandler(_customerServiceMock.Object,+ _customerManagerServiceMock.Object, new CustomerSettings { AllowUsersToChangeEmail = true });+ }++ [TestMethod]+ public async Task Handle_WithPassword_ChangesPasswordScopedToCustomerStore()+ {+ var customer = new Customer { Id = "c1", Email = "[email protected]", StoreId = "store-9" };+ _customerServiceMock.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer);++ var command = new SubAccountEditCommand {+ CurrentCustomer = new Customer { Id = "owner" },+ EditModel = new SubAccountEditModel {+ Id = "c1", Email = "[email protected]", Password = "newpass", Active = true,+ FirstName = "John", LastName = "Doe"+ }+ };++ var result = await _handler.Handle(command, default);++ Assert.IsTrue(result);+ //the sub-account's store must scope the password change (safe with or without per-store identity)+ _customerManagerServiceMock.Verify(m => m.ChangePassword(+ It.Is<ChangePasswordRequest>(r => r.Email == "[email protected]"), "store-9"), Times.Once);+ }++ [TestMethod]+ public async Task Handle_WithoutPassword_DoesNotChangePassword()+ {+ var customer = new Customer { Id = "c1", Email = "[email protected]", StoreId = "store-9" };+ _customerServiceMock.Setup(c => c.GetCustomerById("c1")).ReturnsAsync(customer);++ var command = new SubAccountEditCommand {+ CurrentCustomer = new Customer { Id = "owner" },+ EditModel = new SubAccountEditModel { Id = "c1", Email = "[email protected]", Active = true }+ };++ var result = await _handler.Handle(command, default);++ Assert.IsTrue(result);+ _customerManagerServiceMock.Verify(m => m.ChangePassword(+ It.IsAny<ChangePasswordRequest>(), It.IsAny<string>()), Times.Never);+ }+}diff --git a/src/Tests/Grand.Web.Tests/Grand.Web.Tests.csproj b/src/Tests/Grand.Web.Tests/Grand.Web.Tests.csprojnew file mode 100644index 000000000..edd2a8c96--- /dev/null+++ b/src/Tests/Grand.Web.Tests/Grand.Web.Tests.csproj@@ -0,0 +1,26 @@+<Project Sdk="Microsoft.NET.Sdk">++ <Import Project="..\..\Build\Grand.Common.props" />+ <PropertyGroup>+ <IsPackable>false</IsPackable>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" />+ <PackageReference Include="FluentValidation" />+ <PackageReference Include="MediatR" />+ <PackageReference Include="MongoDB.Bson" />+ <PackageReference Include="Moq" />+ <PackageReference Include="MSTest.TestAdapter" />+ <PackageReference Include="MSTest.TestFramework" />+ <PackageReference Include="coverlet.collector">+ <PrivateAssets>all</PrivateAssets>+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>+ </PackageReference>+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />+ <ProjectReference Include="..\..\Web\Grand.Web\Grand.Web.csproj" />+ </ItemGroup>+</Project>diff --git a/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs b/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.csnew file mode 100644index 000000000..1994fb4a1--- /dev/null+++ b/src/Tests/Grand.Web.Tests/Validators/Customer/CustomerValidatorsStoreScopingTests.cs@@ -0,0 +1,192 @@+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.Domain.Common;+using Grand.Domain.Customers;+using Grand.Domain.Stores;+using Grand.Infrastructure;+using Grand.Infrastructure.Models;+using Grand.Infrastructure.Validators;+using Grand.SharedKernel.Captcha;+using Grand.Web.Features.Models.Customers;+using Grand.Web.Models.Customer;+using Grand.Web.Validators.Customer;+using MediatR;+using Microsoft.AspNetCore.Http;+using Microsoft.VisualStudio.TestTools.UnitTesting;+using Moq;++namespace Grand.Web.Tests.Validators.Customers;++/// <summary>+/// Verifies the storefront customer validators thread the current store into the customer lookup when+/// per-store customer identity is enabled (Customer:RegisterCustomersPerStore).+/// </summary>+[TestClass]+public class CustomerValidatorsStoreScopingTests+{+ private const string StoreId = "store-1";++ private static Mock<ITranslationService> Translation()+ {+ var m = new Mock<ITranslationService>();+ m.Setup(t => t.GetResource(It.IsAny<string>())).Returns<string>(k => k);+ return m;+ }++ private static IContextAccessor Context(string currentCustomerEmail = "[email protected]")+ {+ var work = new Mock<IWorkContext>();+ work.Setup(w => w.CurrentCustomer).Returns(new Customer { Email = currentCustomerEmail });+ var store = new Mock<IStoreContext>();+ store.Setup(s => s.CurrentStore).Returns(new Grand.Domain.Stores.Store { Id = StoreId });+ var ctx = new Mock<IContextAccessor>();+ ctx.Setup(c => c.WorkContext).Returns(work.Object);+ ctx.Setup(c => c.StoreContext).Returns(store.Object);+ return ctx.Object;+ }++ private static CustomerConfigProbe PerStoreOn() => new(true);++ //small wrapper so the intent (per-store on) reads clearly at call sites+ private sealed record CustomerConfigProbe(bool On)+ {+ public Grand.Infrastructure.Configuration.CustomerConfig Config => new() { RegisterCustomersPerStore = On };+ }++ [TestMethod]+ public async Task LoginValidator_ScopesEmailLookupToCurrentStore()+ {+ var customerService = new Mock<ICustomerService>();+ var validator = new LoginValidator(+ new List<IValidatorConsumer<LoginModel>>(),+ new List<IValidatorConsumer<ICaptchaValidModel>>(),+ customerService.Object, new Mock<IGroupService>().Object, new Mock<IEncryptionService>().Object,+ Translation().Object, new CustomerSettings(), new Grand.Domain.Common.CaptchaSettings(),+ new Mock<IHttpContextAccessor>().Object, new Mock<IGoogleReCaptchaValidator>().Object,+ Context(), PerStoreOn().Config);++ await validator.ValidateAsync(new LoginModel { Email = "[email protected]", Password = "p" });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }++ [TestMethod]+ public async Task RegisterValidator_ScopesEmailLookupToCurrentStore()+ {+ var customerService = new Mock<ICustomerService>();+ var groupService = new Mock<IGroupService>();+ groupService.Setup(g => g.IsRegistered(It.IsAny<Customer>())).ReturnsAsync(false);+ var mediator = new Mock<IMediator>();+ mediator.Setup(m => m.Send(It.IsAny<GetParseCustomAttributes>(), It.IsAny<CancellationToken>()))+ .ReturnsAsync(new List<CustomAttribute>());+ var attrParser = new Mock<ICustomerAttributeParser>();+ attrParser.Setup(p => p.GetAttributeWarnings(It.IsAny<IList<CustomAttribute>>()))+ .ReturnsAsync(new List<string>());++ var validator = new RegisterValidator(+ new List<IValidatorConsumer<RegisterModel>>(),+ new List<IValidatorConsumer<ICaptchaValidModel>>(),+ Translation().Object, new Mock<ICountryService>().Object, new CustomerSettings(),+ new Grand.Domain.Common.CaptchaSettings(), new Mock<IHttpContextAccessor>().Object,+ new Mock<IGoogleReCaptchaValidator>().Object, mediator.Object, attrParser.Object,+ customerService.Object, groupService.Object, Context(), PerStoreOn().Config);++ await validator.ValidateAsync(new RegisterModel { Email = "[email protected]" });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }++ [TestMethod]+ public async Task PasswordRecoveryValidator_ScopesEmailLookupToCurrentStore()+ {+ var customerService = new Mock<ICustomerService>();+ var validator = new PasswordRecoveryValidator(+ new List<IValidatorConsumer<PasswordRecoveryModel>>(),+ new List<IValidatorConsumer<ICaptchaValidModel>>(),+ customerService.Object, new Grand.Domain.Common.CaptchaSettings(),+ new Mock<IHttpContextAccessor>().Object, new Mock<IGoogleReCaptchaValidator>().Object,+ Translation().Object, Context(), PerStoreOn().Config);++ await validator.ValidateAsync(new PasswordRecoveryModel { Email = "[email protected]" });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }++ [TestMethod]+ public async Task PasswordRecoveryConfirmValidator_ScopesEmailLookupToCurrentStore()+ {+ var customerService = new Mock<ICustomerService>();+ var validator = new PasswordRecoveryConfirmValidator(+ new List<IValidatorConsumer<PasswordRecoveryConfirmModel>>(),+ customerService.Object, new Mock<IGroupService>().Object,+ new Mock<ICustomerManagerService>().Object, new Mock<ICustomerHistoryPasswordService>().Object,+ Translation().Object, new CustomerSettings(), Context(), PerStoreOn().Config);++ await validator.ValidateAsync(new PasswordRecoveryConfirmModel {+ Email = "[email protected]", NewPassword = "abc", ConfirmNewPassword = "abc"+ });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }++ [TestMethod]+ public async Task CustomerInfoValidator_ScopesEmailLookupToCurrentStore_WhenEmailChanged()+ {+ var customerService = new Mock<ICustomerService>();+ var mediator = new Mock<IMediator>();+ mediator.Setup(m => m.Send(It.IsAny<GetParseCustomAttributes>(), It.IsAny<CancellationToken>()))+ .ReturnsAsync(new List<CustomAttribute>());+ var attrParser = new Mock<ICustomerAttributeParser>();+ attrParser.Setup(p => p.GetAttributeWarnings(It.IsAny<IList<CustomAttribute>>()))+ .ReturnsAsync(new List<string>());++ var validator = new CustomerInfoValidator(+ new List<IValidatorConsumer<CustomerInfoModel>>(),+ Context("[email protected]"), customerService.Object, mediator.Object, attrParser.Object,+ Translation().Object, new Mock<ICountryService>().Object,+ new CustomerSettings { AllowUsersToChangeEmail = true }, PerStoreOn().Config);++ await validator.ValidateAsync(new CustomerInfoModel { Email = "[email protected]" });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }++ [TestMethod]+ public async Task SubAccountCreateValidator_ScopesEmailLookupToCurrentStore()+ {+ var customerService = new Mock<ICustomerService>();+ var validator = new SubAccountCreateValidator(+ new List<IValidatorConsumer<SubAccountCreateModel>>(),+ customerService.Object, Translation().Object, new CustomerSettings(),+ Context(), PerStoreOn().Config);++ await validator.ValidateAsync(new SubAccountCreateModel {+ Email = "[email protected]", FirstName = "A", LastName = "B", Password = "p"+ });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }++ [TestMethod]+ public async Task SubAccountEditValidator_ScopesEmailLookupToCurrentStore_WhenEmailChanged()+ {+ var customerService = new Mock<ICustomerService>();+ customerService.Setup(c => c.GetCustomerById("c1"))+ .ReturnsAsync(new Customer { Id = "c1", Email = "[email protected]" });+ var groupService = new Mock<IGroupService>();+ groupService.Setup(g => g.IsRegistered(It.IsAny<Customer>())).ReturnsAsync(true);++ var validator = new SubAccountEditValidator(+ new List<IValidatorConsumer<SubAccountEditModel>>(),+ customerService.Object, groupService.Object, Translation().Object,+ Context(), new CustomerSettings { AllowUsersToChangeEmail = true }, PerStoreOn().Config);++ await validator.ValidateAsync(new SubAccountEditModel {+ Id = "c1", Email = "[email protected]", FirstName = "A", LastName = "B"+ });++ customerService.Verify(c => c.GetCustomerByEmail(It.IsAny<string>(), StoreId), Times.AtLeastOnce);+ }+}diff --git a/src/Web/Grand.Web.Admin/App_Data/appsettings.json b/src/Web/Grand.Web.Admin/App_Data/appsettings.jsonindex e32f347f7..ffb1a975d 100644--- a/src/Web/Grand.Web.Admin/App_Data/appsettings.json+++ b/src/Web/Grand.Web.Admin/App_Data/appsettings.json@@ -21,6 +21,12 @@//Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore"EnableContextLoggingMiddleware": true},+ "Customer": {+ //Scope customer accounts per store. Must match the value used by the storefront (Grand.Web).+ //false (default): the e-mail/username is a GLOBAL unique key across the whole installation.+ //true: the uniqueness key becomes (e-mail/username + StoreId) - the same e-mail can be registered independently per store.+ "RegisterCustomersPerStore": false+ },//only for advanced users, allow to set ConnectionString for MongoDb"ConnectionStrings": {"Mongodb": ""diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.csindex ebb2254ec..7dfb21515 100644--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs@@ -260,7 +260,7 @@ public class CustomerController : BaseAdminController{var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat,model.Password);- await _customerManagerService.ChangePassword(changePassRequest);+ await _customerManagerService.ChangePassword(changePassRequest, customer.StoreId);}Success(_translationService.GetResource("Admin.Customers.Customers.Added"));@@ -308,7 +308,7 @@ public class CustomerController : BaseAdminController{var changePassRequest = new ChangePasswordRequest(model.Email,_customerSettings.DefaultPasswordFormat, model.Password);- await _customerManagerService.ChangePassword(changePassRequest);+ await _customerManagerService.ChangePassword(changePassRequest, customer.StoreId);}Success(_translationService.GetResource("Admin.Customers.Customers.Updated"));diff --git a/src/Web/Grand.Web.AdminShared/Interfaces/ICustomerViewModelService.cs b/src/Web/Grand.Web.AdminShared/Interfaces/ICustomerViewModelService.csindex f49b7419f..fce6cb99e 100644--- a/src/Web/Grand.Web.AdminShared/Interfaces/ICustomerViewModelService.cs+++ b/src/Web/Grand.Web.AdminShared/Interfaces/ICustomerViewModelService.cs@@ -14,7 +14,8 @@ public interface ICustomerViewModelServiceTask<CustomerListModel> PrepareCustomerListModel();Task<(IEnumerable<CustomerModel> customerModelList, int totalCount)> PrepareCustomerList(CustomerListModel model,- string[] searchCustomerGroupIds, string[] searchCustomerTagIds, int pageIndex, int pageSize);+ string[] searchCustomerGroupIds, string[] searchCustomerTagIds, int pageIndex, int pageSize,+ string storeId = "");Task PrepareCustomerModel(CustomerModel model, Customer customer, bool excludeProperties);Task<Customer> InsertCustomerModel(CustomerModel model);diff --git a/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.csindex a9d339eb5..ae9f0f111 100644--- a/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs+++ b/src/Web/Grand.Web.AdminShared/Services/CustomerViewModelService.cs@@ -153,11 +153,13 @@ public class CustomerViewModelService : ICustomerViewModelServicepublic virtual async Task<(IEnumerable<CustomerModel> customerModelList, int totalCount)> PrepareCustomerList(CustomerListModel model,- string[] searchCustomerGroupIds, string[] searchCustomerTagIds, int pageIndex, int pageSize)+ string[] searchCustomerGroupIds, string[] searchCustomerTagIds, int pageIndex, int pageSize,+ string storeId = ""){var salesEmployeeId = _contextAccessor.WorkContext.CurrentCustomer.SeId;var customers = await _customerService.GetAllCustomers(+ storeId: storeId,customerGroupIds: searchCustomerGroupIds,customerTagIds: searchCustomerTagIds,email: model.SearchEmail,@@ -179,7 +181,8 @@ public class CustomerViewModelService : ICustomerViewModelServicepublic virtual async Task PrepareCustomerModel(CustomerModel model, Customer customer, bool excludeProperties){- var allStores = await _storeService.GetAllStores();+ var hasStaffStore = !string.IsNullOrEmpty(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId);+ var allStores = hasStaffStore ? [await _storeService.GetStoreById(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId)] : await _storeService.GetAllStores();if (customer != null){model.Id = customer.Id;diff --git a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.csindex 2b321ea24..041059c58 100644--- a/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs+++ b/src/Web/Grand.Web.AdminShared/Validators/Customers/CustomerValidator.cs@@ -4,6 +4,7 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;using Grand.SharedKernel.Extensions;using Grand.Web.AdminShared.Models.Customers;@@ -20,9 +21,13 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>IContextAccessor contextAccessor,ICustomerService customerService,IGroupService groupService,- CustomerSettings customerSettings)+ CustomerSettings customerSettings,+ CustomerConfig customerConfig): base(validators){+ //when per-store customer identity is enabled, uniqueness is scoped to the customer's store+ string StoreScope(CustomerModel m) => customerConfig.RegisterCustomersPerStore ? m.StoreId : "";+CustomerCreateValidator();CustomerEditValidator();@@ -30,9 +35,11 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>RuleFor(x => x.Email).NotEmpty().EmailAddress().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Email.Required"));- //store+ //store - required only when the editor is not an administrator (admins may manage store-independent+ //back-office/system accounts that have no store)RuleFor(x => x.StoreId).NotEmpty()- .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Store.Required"));+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Store.Required"))+ .WhenAsync(async (_, _) => !await groupService.IsAdmin(contextAccessor.WorkContext.CurrentCustomer));//a store manager can only assign a customer to his own storeRuleFor(x => x.StoreId).MustAsync(async (storeId, _) =>@@ -182,21 +189,21 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));- var customerByEmail = await customerService.GetCustomerByEmail(x.Email);+ var customerByEmail = await customerService.GetCustomerByEmail(x.Email, StoreScope(x));if (customerByEmail != null)context.AddFailure("Email is already registered");}if (!string.IsNullOrWhiteSpace(x.Owner)){- var customerOwner = await customerService.GetCustomerByEmail(x.Owner);+ var customerOwner = await customerService.GetCustomerByEmail(x.Owner, StoreScope(x));if (customerOwner == null)context.AddFailure("Owner email is not exists");}if (!string.IsNullOrWhiteSpace(x.Username) && customerSettings.UsernamesEnabled){- var customerByUsername = await customerService.GetCustomerByUsername(x.Username);+ var customerByUsername = await customerService.GetCustomerByUsername(x.Username, StoreScope(x));if (customerByUsername != null)context.AddFailure("Username is already registered");@@ -230,7 +237,7 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>if (!string.IsNullOrWhiteSpace(x.Owner)){- var customerByOwner = await customerService.GetCustomerByEmail(x.Owner);+ var customerByOwner = await customerService.GetCustomerByEmail(x.Owner, StoreScope(x));if (customerByOwner == null)context.AddFailure("Owner email is not exists");@@ -253,7 +260,7 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));- var customer2 = await customerService.GetCustomerByEmail(x.Email);+ var customer2 = await customerService.GetCustomerByEmail(x.Email, StoreScope(x));if (customer2 != null && customer.Id != customer2.Id)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));@@ -264,7 +271,7 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>if (x.Username.Length > 100)context.AddFailure("Username is too long");- var user2 = await customerService.GetCustomerByUsername(x.Username);+ var user2 = await customerService.GetCustomerByUsername(x.Username, StoreScope(x));if (user2 != null && customer.Id != user2.Id)context.AddFailure("The username is already in use");}diff --git a/src/Web/Grand.Web.Store/App_Data/appsettings.json b/src/Web/Grand.Web.Store/App_Data/appsettings.jsonindex d0d8805b5..8de0a2c9c 100644--- a/src/Web/Grand.Web.Store/App_Data/appsettings.json+++ b/src/Web/Grand.Web.Store/App_Data/appsettings.json@@ -21,6 +21,12 @@//Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore"EnableContextLoggingMiddleware": true},+ "Customer": {+ //Scope customer accounts per store. Must match the value used by the storefront (Grand.Web).+ //false (default): the e-mail/username is a GLOBAL unique key across the whole installation.+ //true: the uniqueness key becomes (e-mail/username + StoreId) - the same e-mail can be registered independently per store.+ "RegisterCustomersPerStore": false+ },//only for advanced users, allow to set ConnectionString for MongoDb"ConnectionStrings": {"Mongodb": ""diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/AddressCreate.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/AddressCreate.cshtmlnew file mode 100644index 000000000..941b61c6f--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/AddressCreate.cshtml@@ -0,0 +1,28 @@+@model CustomerAddressModel+@{+ ViewBag.Title = Loc["Admin.Customers.Customers.Addresses.AddNew"];+}+<form asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="AddressCreate" method="post">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-user-plus"></i>+ @Loc["Admin.Customers.Customers.Addresses.AddNew"]+ <small>@Html.ActionLink("(" + Loc["Admin.Customers.Customers.Addresses.BackToCustomer"] + ")", "Edit", new { id = Model.CustomerId })</small>+ </div>+ <div class="actions">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ <div class="x_content form">+ <partial name="Partials/CreateOrUpdateAddress" model="Model"/>+ </div>+ </div>+ </div>+ </div>+</form>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/AddressEdit.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/AddressEdit.cshtmlnew file mode 100644index 000000000..44640ad46--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/AddressEdit.cshtml@@ -0,0 +1,28 @@+@model CustomerAddressModel+@{+ ViewBag.Title = Loc["Admin.Customers.Customers.Addresses.EditAddress"];+}+<form asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="AddressEdit" method="post">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-user-plus"></i>+ @Loc["Admin.Customers.Customers.Addresses.EditAddress"]+ <small>@Html.ActionLink("(" + Loc["Admin.Customers.Customers.Addresses.BackToCustomer"] + ")", "Edit", new { id = Model.CustomerId })</small>+ </div>+ <div class="actions">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ </div>+ </div>+ <div class="x_content form">+ <partial name="Partials/CreateOrUpdateAddress" model="Model"/>+ </div>+ </div>+ </div>+ </div>+</form>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Create.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Create.cshtmlnew file mode 100644index 000000000..9eff4594a--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Create.cshtml@@ -0,0 +1,35 @@+@model CustomerModel+@{+ ViewBag.Title = Loc["Admin.Customers.Customers.AddNew"];+}+<form asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="Create" method="post">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-user"></i>+ @Loc["Admin.Customers.Customers.AddNew"]+ <small>+ <i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(Loc["Admin.Customers.Customers.BackToList"], "List")+ </small>+ </div>+ <div class="actions">+ <div class="btn-group btn-group-devided">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ <button class="btn btn-success" type="submit" name="save-continue">+ <i class="fa fa-check-circle"></i> @Loc["Admin.Common.SaveContinue"]+ </button>+ </div>+ </div>+ </div>+ <div class="x_content form">+ <partial name="Partials/CreateOrUpdate" model="Model"/>+ </div>+ </div>+ </div>+ </div>+</form>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Edit.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Edit.cshtmlnew file mode 100644index 000000000..433784d2e--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Edit.cshtml@@ -0,0 +1,50 @@+@model CustomerModel+@{+ ViewBag.Title = Loc["Admin.Customers.Customers.EditCustomerDetails"];+}+<form asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="Edit" method="post" id="customer-form">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-user"></i>+ @Loc["Admin.Customers.Customers.EditCustomerDetails"] - @Model.LastName @Model.FirstName+ <small>+ <i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(Loc["Admin.Customers.Customers.BackToList"], "List")+ </small>+ </div>+ <div class="actions">+ <div class="btn-group btn-group-devided util-btn-margin-bottom-5">+ <button class="btn btn-success" type="submit" name="save">+ <i class="fa fa-check"></i> @Loc["Admin.Common.Save"]+ </button>+ <button class="btn btn-success" type="submit" name="save-continue">+ <i class="fa fa-check-circle"></i> @Loc["Admin.Common.SaveContinue"]+ </button>+ <button class="btn btn-info" type="submit" id="sendemail"><i class="fa fa-paper-plane" aria-hidden="true"></i> @Loc["Admin.Customers.Customers.SendEmail"] </button>+ @if (Model.AllowSendingOfWelcomeMessage)+ {+ <button class="btn btn-primary" type="submit" name="send-welcome-message" asp-action="SendWelcomeMessage" onclick="return confirm('@Loc["Admin.Common.AreYouSure"]');"><span class="k-icon k-i-rotate"></span> @Loc["Admin.Customers.Customers.SendWelcomeMessage"] </button>+ }+ @if (Model.AllowReSendingOfActivationMessage)+ {+ <button class="btn btn-primary" type="submit" name="resend-activation-message" asp-action="ReSendActivationMessage" onclick="return confirm('@Loc["Admin.Common.AreYouSure"]');"><span class="k-icon k-i-rotate"></span> @Loc["Admin.Customers.Customers.ReSendActivationMessage"] </button>+ }+ <span id="customer-delete" class="btn red">+ <i class="fa fa-trash-o"></i><span class="d-none d-sm-inline"> @Loc["Admin.Common.Delete"]</span>+ </span>+ </div>+ </div>+ </div>+ <div class="x_content form">+ <partial name="Partials/CreateOrUpdate" model="Model"/>+ </div>+ </div>+ </div>+ </div>+</form>+<admin-delete-confirmation button-id="customer-delete"/>++<partial name="Partials/SendEmail" model="Model.SendEmail"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/List.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/List.cshtmlnew file mode 100644index 000000000..f4a35ede7--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/List.cshtml@@ -0,0 +1,236 @@+@model CustomerListModel+@inject AdminAreaSettings adminAreaSettings+@{+ ViewBag.Title = Loc["Admin.Customers.Customers"];+}++<form asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="List" method="post">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit popup-window">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-users"></i>+ @Loc["Admin.Customers.Customers"]+ </div>+ <div class="actions btn-group btn-group-devided">+ <a href="@Url.Action("Create", new { area = Constants.AreaStore })" class="btn green">+ <i class="fa fa-plus"></i><span class="d-none d-sm-inline">@Loc["Admin.Common.AddNew"] </span>+ </a>+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="main-header col-12 px-0">+ <div class="row align-items-end">+ <div class="col-md-8 col-ms-12 col-12">+ <div class="form-group mb-0">+ <admin-label asp-for="SearchEmail" class="control-label"/>+ <admin-input asp-for="SearchEmail"/>+ </div>+ </div>+ <div class="col-md-4 col-sm-12 col-12">+ <div class="form-actions">+ <div class="btn-group">+ <button class="btn btn-success filter-submit" id="search-customers">+ <i class="fa fa-search"></i> @Loc["Admin.Common.Search"]+ </button>+ <button class="btn btn-info" type="button" data-toggle="collapse" data-target="#filterCollapse" aria-expanded="false" aria-controls="filterCollapse">+ <i class="fa fa-filter"></i> @Loc["Admin.Common.Filters"]+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ <div class="collapse" id="filterCollapse">+ <div class="drop-filters-container w-100">+ @if (Model.UsernamesEnabled)+ {+ <div class="form-group">+ <admin-label asp-for="SearchUsername" class="col-sm-3 control-label"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="SearchUsername"/>+ </div>+ </div>+ }+ <div class="form-group">+ <admin-label asp-for="SearchFirstName" class="col-sm-3 control-label"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="SearchFirstName"/>+ </div>+ </div>+ <div class="form-group">+ <admin-label asp-for="SearchLastName" class="col-sm-3 control-label"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="SearchLastName"/>+ </div>+ </div>+ @if (Model.CompanyEnabled)+ {+ <div class="form-group">+ <admin-label asp-for="SearchCompany" class="col-sm-3 control-label"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="SearchCompany"/>+ </div>+ </div>+ }+ @if (Model.PhoneEnabled)+ {+ <div class="form-group">+ <admin-label asp-for="SearchPhone" class="col-sm-3 control-label"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="SearchPhone"/>+ </div>+ </div>+ }+ @if (Model.ZipPostalCodeEnabled)+ {+ <div class="form-group">+ <admin-label asp-for="SearchZipPostalCode" class="col-sm-3 control-label"/>+ <div class="col-md-9 col-sm-9">+ <admin-input asp-for="SearchZipPostalCode"/>+ </div>+ </div>+ }+ </div>+ </div>+ </div>+ </div>+ </div>+ <div class="x_content">+ <div id="customers-grid"></div>+ </div>+ </div>+ </div>+ </div>++ <script>+ $(document).ready(function () {+ $("#customers-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("CustomerList", "Customer", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: additionalData+ }+ },+ 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+ },+ pageable: {+ refresh: true,+ pageSizes: [@(adminAreaSettings.GridPageSizes)]+ },+ scrollable: false,+ columns: [{+ field: "Email",+ title: "@Loc["Admin.Customers.Customers.Fields.Email"]",+ width: 200,+ template: '<a class="k-link" href="Edit/#=Id#">#=Email#</a>'+ },+ @if (Model.UsernamesEnabled)+ {+ <text>{+ field: "Username",+ title: "@Loc["Admin.Customers.Customers.Fields.Username"]",+ width: 200+ },</text>+ }+ {+ field: "FullName",+ title: "@Loc["Admin.Customers.Customers.Fields.FullName"]",+ width: 200,+ encoded: true+ },+ @if (Model.CompanyEnabled)+ {+ <text>{+ field: "Company",+ title: "@Loc["Admin.Customers.Customers.Fields.Company"]",+ width: 200,+ minScreenWidth: 770+ },</text>+ }+ @if (Model.PhoneEnabled)+ {+ <text>{+ field: "Phone",+ title: "@Loc["Admin.Customers.Customers.Fields.Phone"]",+ width: 200,+ minScreenWidth: 770+ },</text>+ }+ @if (Model.ZipPostalCodeEnabled)+ {+ <text>{+ field: "ZipPostalCode",+ title: "@Loc["Admin.Customers.Customers.Fields.ZipPostalCode"]",+ width: 200,+ minScreenWidth: 770+ },</text>+ }+ {+ field: "Active",+ title: "@Loc["Admin.Customers.Customers.Fields.Active"]",+ width: 100,+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(Active) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }, {+ field: "CreatedOn",+ title: "@Loc["Admin.Customers.Customers.Fields.CreatedOn"]",+ width: 200,+ type: "date",+ format: "{0:G}",+ minScreenWidth: 770+ }, {+ field: "LastActivityDate",+ title: "@Loc["Admin.Customers.Customers.Fields.LastActivityDate"]",+ width: 200,+ type: "date",+ format: "{0:G}"+ }]+ });++ $('#search-customers').click(function () {+ var grid = $('#customers-grid').data('kendoGrid');+ grid.dataSource.page(1);+ return false;+ });++ $("#@Html.IdFor(model => model.SearchEmail)").keydown(function (event) {+ if (event.keyCode == 13) { $("#search-customers").click(); return false; }+ });+ });++ function additionalData() {+ var data = {+ SearchEmail: $('#@Html.IdFor(model => model.SearchEmail)').val(),+ SearchUsername: $('#@Html.IdFor(model => model.SearchUsername)').val(),+ SearchFirstName: $('#@Html.IdFor(model => model.SearchFirstName)').val(),+ SearchLastName: $('#@Html.IdFor(model => model.SearchLastName)').val(),+ SearchCompany: $('#@Html.IdFor(model => model.SearchCompany)').val(),+ SearchPhone: $('#@Html.IdFor(model => model.SearchPhone)').val(),+ SearchZipPostalCode: $('#@Html.IdFor(model => model.SearchZipPostalCode)').val()+ };+ addAntiForgeryToken(data);+ return data;+ }+ </script>+</form>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtmlnew file mode 100644index 000000000..c7832a8de--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabAddresses.cshtml@@ -0,0 +1,83 @@+@model CustomerModel+@inject AdminAreaSettings adminAreaSettings+<div class="panel panel-default">+ <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>+ </div>+</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.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ },+ destroy: {+ url: "@Html.Raw(Url.Action("AddressDelete", "Customer", new { customerId = Model.Id, area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: addAntiForgeryToken+ }+ },+ schema: {+ data: "Data",+ total: "Total",+ errors: "Errors",+ model: {+ id: "Id"+ }+ },+ error: function(e) {+ display_kendoui_grid_error(e);+ 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.AreaStore })[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>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.cshtmlnew file mode 100644index 000000000..d17d04056--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentShoppingCart.cshtml@@ -0,0 +1,143 @@+@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.cshtmlnew file mode 100644index 000000000..765a52864--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabCurrentWishlist.cshtml@@ -0,0 +1,100 @@+@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.cshtmlnew file mode 100644index 000000000..ae49760cf--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabInfo.cshtml@@ -0,0 +1,406 @@+@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.cshtmlnew file mode 100644index 000000000..9bac57f94--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabLoyaltyPoints.cshtml@@ -0,0 +1,124 @@+@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.cshtmlnew file mode 100644index 000000000..795c57425--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOrders.cshtml@@ -0,0 +1,141 @@+@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.cshtmlnew file mode 100644index 000000000..d26585a1a--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabOutOfStockSubscriptions.cshtml@@ -0,0 +1,60 @@+@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.cshtmlnew file mode 100644index 000000000..fd5dfd5f0--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProduct.cshtml@@ -0,0 +1,117 @@+@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.cshtmlnew file mode 100644index 000000000..4b73fd8c2--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabProductPrice.cshtml@@ -0,0 +1,121 @@+@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.cshtmlnew file mode 100644index 000000000..ce52b7ee5--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.TabReviews.cshtml@@ -0,0 +1,125 @@+@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.cshtmlnew file mode 100644index 000000000..dbb056350--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdate.cshtml@@ -0,0 +1,80 @@+@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/CreateOrUpdateAddress.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdateAddress.cshtmlnew file mode 100644index 000000000..ef794153e--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CreateOrUpdateAddress.cshtml@@ -0,0 +1,4 @@+@model CustomerAddressModel+<div asp-validation-summary="All"></div>+<input type="hidden" asp-for="CustomerId"/>+<admin-input asp-for="Address" asp-template="Address"/>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CustomerAttributes.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CustomerAttributes.cshtmlnew file mode 100644index 000000000..046159e42--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/CustomerAttributes.cshtml@@ -0,0 +1,78 @@+@model IList<CustomerModel.CustomerAttributeModel>+@foreach (var attribute in Model)+{+ var controlId = $"attributes[{attribute.Id}]";+ var textPrompt = attribute.Name;+ <div class="form-horizontal">+ <div class="form-body">+ <label class="control-label col-md-3">+ @textPrompt+ </label>+ <div class="col-md-9 col-sm-9">++ @switch (attribute.AttributeControlType)+ {+ case AttributeControlType.DropdownList:+ {+ <select class="form-control k-input" name="@(controlId)" id="@(controlId)">+ @if (!attribute.IsRequired)+ {+ <option value="">---</option>+ }+ @foreach (var attributeValue in attribute.Values)+ {+ <option selected="@attributeValue.IsPreSelected" value="@attributeValue.Id">@attributeValue.Name</option>+ }+ </select>+ }+ break;+ case AttributeControlType.RadioList:+ {+ <div class="radio-list">+ @foreach (var attributeValue in attribute.Values)+ {+ <div>+ <input id="@(controlId)_@(attributeValue.Id)" type="radio" name="@(controlId)" value="@attributeValue.Id" checked="@attributeValue.IsPreSelected"/>+ <label for="@(controlId)_@(attributeValue.Id)">@attributeValue.Name</label>+ </div>+ }+ </div>+ }+ break;+ case AttributeControlType.Checkboxes:+ case AttributeControlType.ReadonlyCheckboxes:+ {+ <div class="checkbox-list">+ @foreach (var attributeValue in attribute.Values)+ {+ <div>+ <input id="@(controlId)_@(attributeValue.Id)" type="checkbox" name="@(controlId)" value="@attributeValue.Id" checked="@(attributeValue.IsPreSelected)" @(attribute.AttributeControlType == AttributeControlType.ReadonlyCheckboxes ? Html.Raw(" disabled=\"disabled\"") : null)/>+ <label for="@(controlId)_@(attributeValue.Id)">@attributeValue.Name</label>+ </div>+ }+ </div>+ }+ break;+ case AttributeControlType.TextBox:+ {+ <input name="@(controlId)" type="text" class="form-control k-input text-box single-line" id="@(controlId)" value="@(attribute.DefaultValue)"/>+ }+ break;+ case AttributeControlType.MultilineTextbox:+ {+ <textarea id="@(controlId)" style="Height: 150px;" class="form-control k-input" name="@(controlId)">@(attribute.DefaultValue)</textarea>+ }+ break;+ case AttributeControlType.Datepicker:+ case AttributeControlType.FileUpload:+ case AttributeControlType.ColorSquares:+ case AttributeControlType.ImageSquares:+ {+ //not support attribute type+ }+ break;+ }+ </div>+ </div>+ </div>+}diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/SendEmail.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/SendEmail.cshtmlnew file mode 100644index 000000000..b6fb9b055--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/Partials/SendEmail.cshtml@@ -0,0 +1,68 @@+@model CustomerModel.SendEmailModel++<div id="sendemail-window" style="display:none;">+ <form asp-area="@Constants.AreaStore" 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>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/PerStoreDisabled.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/PerStoreDisabled.cshtmlnew file mode 100644index 000000000..76e513256--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/PerStoreDisabled.cshtml@@ -0,0 +1,23 @@+@{+ ViewBag.Title = Loc["Admin.Customers.Customers"];+}++<div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-users"></i>+ @Loc["Admin.Customers.Customers"]+ </div>+ </div>+ <div class="x_content">+ <div class="alert alert-warning">+ Customer management from the store panel is disabled. It requires per-store customer+ identity. Ask an administrator to set <strong>Customer:RegisterCustomersPerStore</strong>+ to <strong>true</strong> in appsettings.json.+ </div>+ </div>+ </div>+ </div>+</div>diff --git a/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/ProductAddPopup.cshtml b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/ProductAddPopup.cshtmlnew file mode 100644index 000000000..bfe08490f--- /dev/null+++ b/src/Web/Grand.Web.Store/Areas/Store/Views/Customer/ProductAddPopup.cshtml@@ -0,0 +1,175 @@+@model CustomerModel.AddProductModel+@inject AdminAreaSettings adminAreaSettings+@{+ Layout = "";+ ViewBag.Title = Loc["Admin.Customers.Products.AddNew"];+}++<form id="ProductAddPopup" asp-area="@Constants.AreaStore" asp-controller="Customer" asp-action="ProductAddPopup" method="post"+ asp-route-CustomerId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["CustomerId"])"+ asp-route-btnId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["btnId"])"+ asp-route-formId="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["formId"])"+ asp-route-personalized="@HtmlExtensions.HtmlEncodeSafe(Context.Request.Query["personalized"])">++ <div class="row">+ <div class="col-md-12">+ <div class="x_panel light form-fit popup-window">+ <div class="x_title">+ <div class="caption">+ <i class="fa fa-sitemap"></i>+ @Loc["Admin.Customers.Products.AddNew"]+ </div>+ </div>+ <div class="x_content form">+ <div class="form-horizontal">+ <div class="form-body">+ <div class="main-header col-12 px-0">+ <div class="row align-items-end">+ <div class="col-md col-ms-12 col-12">+ <div class="form-group mb-0">+ <admin-label asp-for="SearchProductName" class="control-label"/>+ <admin-input asp-for="SearchProductName"/>+ </div>+ </div>+ <div class="col-md-auto col-sm-12 col-12">+ <div class="form-actions">+ <div class="btn-group btn-group-devided">+ <button class="btn btn-success filter-submit" id="search-products">+ <i class="fa fa-search"></i> @Loc["Admin.Common.Search"]+ </button>+ </div>+ <button class="btn btn-success" type="submit" name="save"><i class="fa fa-check"></i> @Loc["Admin.Common.Save"] </button>+ </div>+ </div>+ </div>+ </div>+ <div id="products-grid"></div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>++ <script>+ var mfp = $.magnificPopup.instance;+ $("#ProductAddPopup").submit(function (e) {+ e.preventDefault();+ var form = $(this);+ var url = form.attr('action');+ $.ajax({+ type: "POST",+ url: url,+ data: form.serialize(),+ success: function (data) {+ if (data == "") {+ mfp.close();+ $('#btnRefreshPersonalizedProducts').click();+ $('#btnRefreshProducts').click();+ } else {+ $.magnificPopup.open({+ items: {+ src: data,+ type: 'inline'+ },+ callbacks: {+ open: function () {+ $('.mfp-wrap').removeAttr('tabindex');+ }+ }+ });+ }+ }+ });+ });++ $("#products-grid").kendoGrid({+ dataSource: {+ transport: {+ read: {+ url: "@Html.Raw(Url.Action("ProductAddPopupList", "Customer", new { area = Constants.AreaStore }))",+ type: "POST",+ dataType: "json",+ data: additionalData+ }+ },+ 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+ },+ pageable: {+ refresh: true,+ pageSizes: [@(adminAreaSettings.GridPageSizes)]+ },+ editable: {+ confirmation: false,+ mode: "inline"+ },+ scrollable: false,+ columns: [{+ field: "Id",+ headerTemplate: "<label class='mt-checkbox mt-checkbox-outline control control-checkbox'><input id='mastercheckbox' type='checkbox'/><div class='control__indicator'></div></label>",+ headerAttributes: { style: "text-align:center" },+ template: "<label class='mt-checkbox mt-checkbox-outline control control-checkbox'><input type='checkbox' name='SelectedProductIds' value='#=Id#' class='checkboxGroups' /><div class='control__indicator'></div></label>",+ attributes: { style: "text-align:center" },+ width: 50+ }, {+ field: "Name",+ title: "@Loc["Admin.Catalog.Products.Fields.Name"]"+ }, {+ field: "Published",+ title: "@Loc["Admin.Catalog.Products.Fields.Published"]",+ width: 100,+ headerAttributes: { style: "text-align:center" },+ attributes: { style: "text-align:center" },+ template: '# if(Published) {# <i class="fa fa-check" aria-hidden="true" style="color:green"></i> #} else {# <i class="fa fa-times" aria-hidden="true" style="color:red"></i> #} #'+ }]+ });++ $('#search-products').click(function() {+ var grid = $('#products-grid').data('kendoGrid');+ grid.dataSource.page(1);+ $('.checkboxGroups').prop('checked', false).change();+ return false;+ });++ $("#@Html.IdFor(model => model.SearchProductName)").keydown(function(event) {+ if (event.keyCode == 13) {+ $("#search-products").click();+ return false;+ }+ });++ $('#mastercheckbox').click(function() {+ $('.checkboxGroups').prop('checked', $(this).is(':checked')).change();+ });++ $('#products-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function(e) {+ updateMasterCheckbox();+ });++ function additionalData() {+ var data = {+ SearchProductName: $('#@Html.IdFor(model => model.SearchProductName)').val()+ };+ addAntiForgeryToken(data);+ return data;+ }++ function updateMasterCheckbox() {+ var numChkBoxes = $('#products-grid input[type=checkbox][id!=mastercheckbox]').length;+ var numChkBoxesChecked = $('#products-grid input[type=checkbox][id!=mastercheckbox]:checked').length;+ $('#mastercheckbox').prop('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);+ }+ </script>+</form>diff --git a/src/Web/Grand.Web.Store/Controllers/CustomerController.cs b/src/Web/Grand.Web.Store/Controllers/CustomerController.csnew file mode 100644index 000000000..93ddccd0b--- /dev/null+++ b/src/Web/Grand.Web.Store/Controllers/CustomerController.cs@@ -0,0 +1,880 @@+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.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.Infrastructure.Configuration;+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.Common.Filters;+using Grand.Web.Common.Models;+using Grand.Web.Common.Security.Authorization;+using Microsoft.AspNetCore.Mvc;+using Microsoft.AspNetCore.Mvc.Controllers;+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.+/// </summary>+[PermissionAuthorize(PermissionSystemName.Customers)]+public class CustomerController : BaseStoreController+{+ #region Constructors++ public CustomerController(+ ICustomerService customerService,+ ICustomerViewModelService customerViewModelService,+ ICustomerManagerService customerManagerService,+ 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;+ _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 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.+ public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ {+ if (!_customerConfig.RegisterCustomersPerStore &&+ context.ActionDescriptor is ControllerActionDescriptor { ActionName: not nameof(PerStoreDisabled) })+ {+ context.Result = RedirectToAction(nameof(PerStoreDisabled));+ return;+ }++ await next();+ }++ #endregion++ #region Utilities++ 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)+ {+ 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.Owner = "";+ model.VendorId = "";+ model.StaffStoreId = "";+ model.SeId = "";+ 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)]+ 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 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+}diff --git a/src/Web/Grand.Web.Vendor/App_Data/appsettings.json b/src/Web/Grand.Web.Vendor/App_Data/appsettings.jsonindex e32f347f7..ffb1a975d 100644--- a/src/Web/Grand.Web.Vendor/App_Data/appsettings.json+++ b/src/Web/Grand.Web.Vendor/App_Data/appsettings.json@@ -21,6 +21,12 @@//Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore"EnableContextLoggingMiddleware": true},+ "Customer": {+ //Scope customer accounts per store. Must match the value used by the storefront (Grand.Web).+ //false (default): the e-mail/username is a GLOBAL unique key across the whole installation.+ //true: the uniqueness key becomes (e-mail/username + StoreId) - the same e-mail can be registered independently per store.+ "RegisterCustomersPerStore": false+ },//only for advanced users, allow to set ConnectionString for MongoDb"ConnectionStrings": {"Mongodb": ""diff --git a/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs b/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.csindex 7adb0e302..0c0bb2400 100644--- a/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs+++ b/src/Web/Grand.Web.Vendor/Services/MerchandiseReturnViewModelService.cs@@ -11,6 +11,7 @@ using Grand.Domain.Directory;using Grand.Domain.Localization;using Grand.Domain.Orders;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Web.Common.Localization;using Grand.Web.Vendor.Extensions;using Grand.Web.Vendor.Interfaces;@@ -41,6 +42,7 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServprivate readonly IAddressAttributeService _addressAttributeService;private readonly IAddressAttributeParser _addressAttributeParser;private readonly IEnumTranslationService _enumTranslationService;+ private readonly CustomerConfig _customerConfig;#endregion Fields@@ -61,8 +63,9 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServICountryService countryService,IAddressAttributeService addressAttributeService,IAddressAttributeParser addressAttributeParser,- OrderSettings orderSettings,- IEnumTranslationService enumTranslationService)+ OrderSettings orderSettings,+ IEnumTranslationService enumTranslationService,+ CustomerConfig customerConfig){_orderService = orderService;_contextAccessor = contextAccessor;@@ -80,6 +83,7 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServ_addressAttributeParser = addressAttributeParser;_orderSettings = orderSettings;_enumTranslationService = enumTranslationService;+ _customerConfig = customerConfig;}#endregion@@ -139,7 +143,12 @@ public class MerchandiseReturnViewModelService : IMerchandiseReturnViewModelServvar customerId = string.Empty;if (!string.IsNullOrEmpty(model.SearchCustomerEmail)){- var customer = await _customerService.GetCustomerByEmail(model.SearchCustomerEmail);+ //with per-store customer identity the same e-mail may exist in several stores - scope the+ //lookup to the current store so the search matches this store's customer+ var storeId = _customerConfig.RegisterCustomersPerStore+ ? _contextAccessor.StoreContext.CurrentStore.Id+ : "";+ var customer = await _customerService.GetCustomerByEmail(model.SearchCustomerEmail, storeId);customerId = customer != null ? customer.Id : "00000000-0000-0000-0000-000000000000";}diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.jsonindex 4c2d343e3..ab2136d1c 100644--- a/src/Web/Grand.Web/App_Data/appsettings.json+++ b/src/Web/Grand.Web/App_Data/appsettings.json@@ -21,6 +21,22 @@//Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and CurrentStore"EnableContextLoggingMiddleware": true},+ "Customer": {+ //Per-store customer identity.+ //IMPORTANT: keep this value IDENTICAL on every host (Grand.Web, Grand.Web.Admin, Grand.Web.Store,+ //Grand.Web.Vendor) - they all share one database. Mixing values (e.g. true in the storefront but false+ //in the Admin) breaks login resolution - typically the administrator can no longer sign in.+ //false (default): the e-mail/username is a GLOBAL unique key across the whole installation.+ //true: the uniqueness key becomes (e-mail/username + StoreId) - the same e-mail can be registered+ // independently per store. Affects registration, storefront login, auth-cookie re-resolution,+ // password recovery and the Admin/Store customer editors. Customers stay in a single collection+ // (discriminated by StoreId); the lookup index is the compound (Email + StoreId) index.+ // System/back-office accounts (administrator, etc.) are created WITHOUT a store and stay globally+ // unique - do NOT assign a StoreId to the administrator and do NOT reuse a back-office e-mail for a+ // store customer. Set this BEFORE going live - flipping it on data that already has duplicate+ // e-mails across stores can make some accounts unreachable.+ "RegisterCustomersPerStore": false+ },//only for advanced users, allow to set ConnectionString for MongoDb"ConnectionStrings": {"Mongodb": ""diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.csindex 6af8544b9..134e5dcf4 100644--- a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs@@ -34,11 +34,11 @@ public class SubAccountEditCommandHandler : IRequestHandler<SubAccountEditCommanawait _customerService.UpdateCustomerField(customer, x => x.Email, request.EditModel.Email);}- //update password+ //update password (scope the lookup to the sub-account's store - safe with or without per-store identity)if (!string.IsNullOrEmpty(request.EditModel.Password))await _customerManagerService.ChangePassword(new ChangePasswordRequest(customer.Email, _customerSettings.DefaultPasswordFormat,- request.EditModel.Password));+ request.EditModel.Password), customer.StoreId);//update activecustomer.Active = request.EditModel.Active;diff --git a/src/Web/Grand.Web/Controllers/AccountController.cs b/src/Web/Grand.Web/Controllers/AccountController.csindex 2ed396c62..8169012a0 100644--- a/src/Web/Grand.Web/Controllers/AccountController.cs+++ b/src/Web/Grand.Web/Controllers/AccountController.cs@@ -10,6 +10,7 @@ using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Stores;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using Grand.SharedKernel.Attributes;using Grand.Web.Commands.Models.Customers;@@ -44,7 +45,8 @@ public class AccountController : BasePublicControllerIMediator mediator,IMessageProviderService messageProviderService,CaptchaSettings captchaSettings,- CustomerSettings customerSettings)+ CustomerSettings customerSettings,+ CustomerConfig customerConfig){_authenticationService = authenticationService;_translationService = translationService;@@ -57,8 +59,16 @@ public class AccountController : BasePublicController_messageProviderService = messageProviderService;_captchaSettings = captchaSettings;_mediator = mediator;+ _customerConfig = customerConfig;}+ /// <summary>+ /// Returns the current store id when per-store customer identity is enabled, otherwise an empty+ /// string (which makes the store-aware customer lookups fall back to the global behaviour).+ /// </summary>+ private string CustomerStoreId =>+ _customerConfig.RegisterCustomersPerStore ? _contextAccessor.StoreContext.CurrentStore.Id : "";+#endregion#region My account / Auctions@@ -160,6 +170,7 @@ public class AccountController : BasePublicControllerprivate readonly IMediator _mediator;private readonly IMessageProviderService _messageProviderService;private readonly CustomerSettings _customerSettings;+ private readonly CustomerConfig _customerConfig;private readonly CaptchaSettings _captchaSettings;#endregion@@ -192,14 +203,14 @@ public class AccountController : BasePublicController{var loginResult =await _customerManagerService.LoginCustomer(- _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password);+ _customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password, CustomerStoreId);switch (loginResult){case CustomerLoginResults.Successful:{var customer = _customerSettings.UsernamesEnabled- ? await _customerService.GetCustomerByUsername(model.Username)- : await _customerService.GetCustomerByEmail(model.Email);+ ? await _customerService.GetCustomerByUsername(model.Username, CustomerStoreId)+ : await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId);//sign inreturn await SignInAction(customer, model.RememberMe, returnUrl);}@@ -230,8 +241,8 @@ public class AccountController : BasePublicControllerreturn RedirectToRoute("HomePage");var customer = _customerSettings.UsernamesEnabled- ? await _customerService.GetCustomerByUsername(username)- : await _customerService.GetCustomerByEmail(username);+ ? await _customerService.GetCustomerByUsername(username, CustomerStoreId)+ : await _customerService.GetCustomerByEmail(username, CustomerStoreId);if (customer == null)return RedirectToRoute("HomePage");@@ -261,8 +272,8 @@ public class AccountController : BasePublicControllerreturn RedirectToRoute("HomePage");var customer = _customerSettings.UsernamesEnabled- ? await _customerService.GetCustomerByUsername(username)- : await _customerService.GetCustomerByEmail(username);+ ? await _customerService.GetCustomerByUsername(username, CustomerStoreId)+ : await _customerService.GetCustomerByEmail(username, CustomerStoreId);if (customer == null)return RedirectToRoute("Login");@@ -362,7 +373,7 @@ public class AccountController : BasePublicController{if (!ModelState.IsValid) return View(model);- var customer = await _customerService.GetCustomerByEmail(model.Email);+ var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId);await _mediator.Send(new PasswordRecoverySendCommand {Customer = customer,Store = _contextAccessor.StoreContext.CurrentStore,@@ -379,7 +390,7 @@ public class AccountController : BasePublicController[PublicStore(true)]public virtual async Task<ActionResult<PasswordRecoveryConfirmModel>> PasswordRecoveryConfirm(string token, string email){- var customer = await _customerService.GetCustomerByEmail(email);+ var customer = await _customerService.GetCustomerByEmail(email, CustomerStoreId);if (customer == null)return RedirectToRoute("HomePage");@@ -396,10 +407,10 @@ public class AccountController : BasePublicController{if (!ModelState.IsValid) return View(model);- var customer = await _customerService.GetCustomerByEmail(model.Email);+ var customer = await _customerService.GetCustomerByEmail(model.Email, CustomerStoreId);await _customerManagerService.ChangePassword(new ChangePasswordRequest(model.Email,- _customerSettings.DefaultPasswordFormat, model.NewPassword));+ _customerSettings.DefaultPasswordFormat, model.NewPassword), CustomerStoreId);await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.PasswordRecoveryToken, "");@@ -577,7 +588,7 @@ public class AccountController : BasePublicController}else{- var customer = await _customerService.GetCustomerByUsername(username);+ var customer = await _customerService.GetCustomerByUsername(username, CustomerStoreId);if (customer != null) return Json(new { Available = false, Text = statusText });statusText = _translationService.GetResource("Account.CheckUsernameAvailability.Available");usernameAvailable = true;@@ -591,7 +602,7 @@ public class AccountController : BasePublicController[PublicStore(true)]public virtual async Task<IActionResult> AccountActivation(string token, string email){- var customer = await _customerService.GetCustomerByEmail(email);+ var customer = await _customerService.GetCustomerByEmail(email, CustomerStoreId);if (customer == null)return RedirectToRoute("HomePage");diff --git a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.csindex 685363d53..214f5fea5 100644--- a/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/CustomerInfoValidator.cs@@ -4,6 +4,7 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;using Grand.SharedKernel.Extensions;using Grand.Web.Features.Models.Customers;@@ -21,9 +22,14 @@ public class CustomerInfoValidator : BaseGrandValidator<CustomerInfoModel>IMediator mediator, ICustomerAttributeParser customerAttributeParser,ITranslationService translationService,ICountryService countryService,- CustomerSettings customerSettings)+ CustomerSettings customerSettings,+ CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? contextAccessor.StoreContext.CurrentStore.Id+ : "";+RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));@@ -128,7 +134,7 @@ public class CustomerInfoValidator : BaseGrandValidator<CustomerInfoModel>if (x.Email.Length > 100)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));- var customer2 = await customerService.GetCustomerByEmail(x.Email);+ var customer2 = await customerService.GetCustomerByEmail(x.Email, storeId);if (customer2 != null)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));@@ -140,7 +146,7 @@ public class CustomerInfoValidator : BaseGrandValidator<CustomerInfoModel>if (x.Username.ToLower().Length > 100)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.UsernameTooLong"));- var customer2 = await customerService.GetCustomerByUsername(x.Username.ToLower());+ var customer2 = await customerService.GetCustomerByUsername(x.Username.ToLower(), storeId);if (customer2 != null)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.UsernameAlreadyExists"));diff --git a/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs b/src/Web/Grand.Web/Validators/Customer/LoginValidator.csindex ba33fa992..9520be907 100644--- a/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/LoginValidator.cs@@ -6,6 +6,8 @@ using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Common;using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Models;using Grand.Infrastructure.Validators;using Grand.SharedKernel.Captcha;@@ -22,9 +24,14 @@ public class LoginValidator : BaseGrandValidator<LoginModel>IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,ICustomerService customerService, IGroupService groupService, IEncryptionService encryptionService,ITranslationService translationService, CustomerSettings customerSettings, CaptchaSettings captchaSettings,- IHttpContextAccessor contextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator)+ IHttpContextAccessor contextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator,+ IContextAccessor workContextAccessor, CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? workContextAccessor.StoreContext.CurrentStore.Id+ : "";+if (!customerSettings.UsernamesEnabled){RuleFor(x => x.Email).NotEmpty()@@ -44,8 +51,8 @@ public class LoginValidator : BaseGrandValidator<LoginModel>RuleFor(x => x).CustomAsync(async (x, context, _) =>{var customer = customerSettings.UsernamesEnabled- ? await customerService.GetCustomerByUsername(x.Username)- : await customerService.GetCustomerByEmail(x.Email);+ ? await customerService.GetCustomerByUsername(x.Username, storeId)+ : await customerService.GetCustomerByEmail(x.Email, storeId);switch (customer){diff --git a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.csindex f9227086c..55d279294 100644--- a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryConfirmValidator.cs@@ -3,6 +3,8 @@ using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;using Grand.Web.Models.Customer;@@ -15,9 +17,14 @@ public class PasswordRecoveryConfirmValidator : BaseGrandValidator<PasswordRecovICustomerService customerService, IGroupService groupService,ICustomerManagerService customerManagerService,ICustomerHistoryPasswordService customerHistoryPasswordService,- ITranslationService translationService, CustomerSettings customerSettings)+ ITranslationService translationService, CustomerSettings customerSettings,+ IContextAccessor contextAccessor, CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? contextAccessor.StoreContext.CurrentStore.Id+ : "";+RuleFor(x => x.NewPassword).NotEmpty().WithMessage(translationService.GetResource("Account.PasswordRecovery.NewPassword.Required"));@@ -33,7 +40,7 @@ public class PasswordRecoveryConfirmValidator : BaseGrandValidator<PasswordRecovRuleFor(x => x).CustomAsync(async (x, context, _) =>{- var customer = await customerService.GetCustomerByEmail(x.Email);+ var customer = await customerService.GetCustomerByEmail(x.Email, storeId);switch (customer){diff --git a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.csindex 9cc23f971..1a518adef 100644--- a/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/PasswordRecoveryValidator.cs@@ -2,6 +2,8 @@using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Common;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Models;using Grand.Infrastructure.Validators;using Grand.SharedKernel.Captcha;@@ -17,15 +19,20 @@ public class PasswordRecoveryValidator : BaseGrandValidator<PasswordRecoveryModeIEnumerable<IValidatorConsumer<ICaptchaValidModel>> validatorsCaptcha,ICustomerService customerService, CaptchaSettings captchaSettings,IHttpContextAccessor contextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator,- ITranslationService translationService)+ ITranslationService translationService,+ IContextAccessor workContextAccessor, CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? workContextAccessor.StoreContext.CurrentStore.Id+ : "";+RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.PasswordRecovery.Email.Required"));RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));RuleFor(x => x).CustomAsync(async (x, context, _) =>{- var customer = await customerService.GetCustomerByEmail(x.Email);+ var customer = await customerService.GetCustomerByEmail(x.Email, storeId);switch (customer){diff --git a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.csindex 9bd0bb8c5..ff41ee029 100644--- a/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/RegisterValidator.cs@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Models;using Grand.Infrastructure.Validators;using Grand.SharedKernel.Captcha;@@ -27,10 +28,15 @@ public class RegisterValidator : BaseGrandValidator<RegisterModel>IHttpContextAccessor httpcontextAccessor, IGoogleReCaptchaValidator googleReCaptchaValidator,IMediator mediator, ICustomerAttributeParser customerAttributeParser,ICustomerService customerService,- IGroupService groupService, IContextAccessor contextAccessor+ IGroupService groupService, IContextAccessor contextAccessor,+ CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? contextAccessor.StoreContext.CurrentStore.Id+ : "";+RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));@@ -142,14 +148,14 @@ public class RegisterValidator : BaseGrandValidator<RegisterModel>//validate unique user- if (await customerService.GetCustomerByEmail(x.Email) != null)+ if (await customerService.GetCustomerByEmail(x.Email, storeId) != null){context.AddFailure(translationService.GetResource("Account.Register.Errors.EmailAlreadyExists"));return;}if (customerSettings.UsernamesEnabled)- if (await customerService.GetCustomerByUsername(x.Username) != null)+ if (await customerService.GetCustomerByUsername(x.Username, storeId) != null)context.AddFailure(translationService.GetResource("Account.Register.Errors.UsernameAlreadyExists"));});}diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.csindex 603f1f1c5..c4e31d13f 100644--- a/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountCreateValidator.cs@@ -2,6 +2,8 @@using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;+using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;using Grand.Web.Models.Customer;@@ -13,9 +15,14 @@ public class SubAccountCreateValidator : BaseGrandValidator<SubAccountCreateModeIEnumerable<IValidatorConsumer<SubAccountCreateModel>> validators,ICustomerService customerService,ITranslationService translationService,- CustomerSettings customerSettings)+ CustomerSettings customerSettings,+ IContextAccessor contextAccessor, CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? contextAccessor.StoreContext.CurrentStore.Id+ : "";+RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));@@ -34,7 +41,7 @@ public class SubAccountCreateValidator : BaseGrandValidator<SubAccountCreateModeRuleFor(x => x).CustomAsync(async (x, context, _) =>{- var customer = await customerService.GetCustomerByEmail(x.Email);+ var customer = await customerService.GetCustomerByEmail(x.Email, storeId);if (customer != null)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));diff --git a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.csindex 674b1b526..c719ff68c 100644--- a/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs+++ b/src/Web/Grand.Web/Validators/Customer/SubAccountEditValidator.cs@@ -4,6 +4,7 @@ using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Customers;using Grand.Domain.Customers;using Grand.Infrastructure;+using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Validators;using Grand.SharedKernel.Extensions;using Grand.Web.Models.Customer;@@ -17,9 +18,14 @@ public class SubAccountEditValidator : BaseGrandValidator<SubAccountEditModel>ICustomerService customerService, IGroupService groupService,ITranslationService translationService,IContextAccessor contextAccessor,- CustomerSettings customerSettings)+ CustomerSettings customerSettings,+ CustomerConfig customerConfig): base(validators){+ var storeId = customerConfig.RegisterCustomersPerStore+ ? contextAccessor.StoreContext.CurrentStore.Id+ : "";+RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Account.Fields.Email.Required"));RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Common.WrongEmail"));@@ -66,7 +72,7 @@ public class SubAccountEditValidator : BaseGrandValidator<SubAccountEditModel>if (x.Email.Length > 100)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));- var customer2 = await customerService.GetCustomerByEmail(x.Email);+ var customer2 = await customerService.GetCustomerByEmail(x.Email, storeId);if (customer2 != null && customer.Id != customer2.Id)context.AddFailure(translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));diff --git a/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml b/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtmlindex 3af7bd23a..32c581983 100644--- a/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml+++ b/src/Web/Grand.Web/Views/Shared/Partials/HeaderLinks.cshtml@@ -11,7 +11,7 @@var isCustomerImpersonated = contextAccessor.WorkContext.OriginalCustomerIfImpersonated != null;var isAdminAccess = await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel);var isVendor = contextAccessor.WorkContext.CurrentVendor != null;- var isStaffStore = contextAccessor.WorkContext.CurrentCustomer.StaffStoreId != null;+ var isStaffStore = !string.IsNullOrEmpty(contextAccessor.WorkContext.CurrentCustomer.StaffStoreId);}@await Component.InvokeAsync("Widget", new { widgetZone = "header_links_before" })