Skip to content

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

Admin panel - CustomerController.cs - changes with validators

support2c4e33f34e30
diff --git a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
index 68f98b862..f096907a6 100644
--- a/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
+++ b/src/Web/Grand.Web.Admin/Controllers/CustomerController.cs
@@ -37,7 +37,6 @@ namespace Grand.Web.Admin.Controllers
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
- private readonly IProductService _productService;
private readonly IProductReviewService _productReviewService;
private readonly IProductReviewViewModelService _productReviewViewModelService;
private readonly IProductViewModelService _productViewModelService;
@@ -52,7 +51,6 @@ namespace Grand.Web.Admin.Controllers
private readonly IAddressAttributeParser _addressAttributeParser;
private readonly IAddressAttributeService _addressAttributeService;
private readonly IMessageProviderService _messageProviderService;
- private readonly IDownloadService _downloadService;
private readonly IPermissionService _permissionService;
private readonly CustomerSettings _customerSettings;
#endregion
@@ -60,7 +58,6 @@ namespace Grand.Web.Admin.Controllers
#region Constructors
public CustomerController(ICustomerService customerService,
- IProductService productService,
IProductReviewService productReviewService,
IProductReviewViewModelService productReviewViewModelService,
IProductViewModelService productViewModelService,
@@ -76,12 +73,10 @@ namespace Grand.Web.Admin.Controllers
IAddressAttributeParser addressAttributeParser,
IAddressAttributeService addressAttributeService,
IMessageProviderService messageProviderService,
- IDownloadService downloadService,
IPermissionService permissionService,
CustomerSettings customerSettings)
{
_customerService = customerService;
- _productService = productService;
_productReviewService = productReviewService;
_productReviewViewModelService = productReviewViewModelService;
_productViewModelService = productViewModelService;
@@ -97,7 +92,6 @@ namespace Grand.Web.Admin.Controllers
_addressAttributeParser = addressAttributeParser;
_addressAttributeService = addressAttributeService;
_messageProviderService = messageProviderService;
- _downloadService = downloadService;
_permissionService = permissionService;
_customerSettings = customerSettings;
}
@@ -225,40 +219,6 @@ namespace Grand.Web.Admin.Controllers
[HttpPost, ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
public async Task<IActionResult> Create(CustomerModel model, bool continueEditing)
{
- if (!string.IsNullOrWhiteSpace(model.Email))
- {
- var cust2 = await _customerService.GetCustomerByEmail(model.Email);
- if (cust2 != null)
- ModelState.AddModelError("", "Email is already registered");
- }
-
- if (!string.IsNullOrWhiteSpace(model.Owner))
- {
- var custowner = await _customerService.GetCustomerByEmail(model.Owner);
- if (custowner == null)
- ModelState.AddModelError("", "Owner email is not exists");
- }
-
- if (!string.IsNullOrWhiteSpace(model.Username) & _customerSettings.UsernamesEnabled)
- {
- var cust2 = await _customerService.GetCustomerByUsername(model.Username);
- if (cust2 != null)
- ModelState.AddModelError("", "Username is already registered");
- }
-
- //validate customer groups
- var allCustomerGroups = await _groupService.GetAllCustomerGroups(showHidden: true);
- var newCustomerGroups = new List<CustomerGroup>();
- foreach (var customerGroup in allCustomerGroups)
- if (model.CustomerGroups != null && model.CustomerGroups.Contains(customerGroup.Id))
- newCustomerGroups.Add(customerGroup);
- var customerGroupsError = await _customerViewModelService.ValidateCustomerGroups(newCustomerGroups);
- if (!string.IsNullOrEmpty(customerGroupsError))
- {
- ModelState.AddModelError("", customerGroupsError);
- Error(customerGroupsError);
- }
-
if (model.TwoFactorEnabled)
Warning(_translationService.GetResource("Admin.Customers.Customers.CannotTwoFactorEnabled"));
@@ -273,27 +233,6 @@ namespace Grand.Web.Admin.Controllers
var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat, model.Password);
await _customerManagerService.ChangePassword(changePassRequest);
}
- if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(model.VendorId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.AdminCouldNotbeVendor"));
- }
- if (newCustomerGroups.Any(x => x.SystemName == SystemCustomerGroupNames.Vendors) && string.IsNullOrEmpty(model.VendorId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated"));
- }
- if (newCustomerGroups.Any(x => x.SystemName == SystemCustomerGroupNames.Staff) && string.IsNullOrEmpty(model.StaffStoreId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.CannotBeInStaffGroupWithoutStaffAssociated"));
- }
- if (newCustomerGroups.Any(x => x.SystemName == SystemCustomerGroupNames.SalesManager) && string.IsNullOrEmpty(model.SeId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.CannotBeInSalesManagerGroupWithoutSalesEmployeeAssociated"));
- }
- if (await _groupService.IsStaff(customer) && await _groupService.IsVendor(customer))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff"));
- }
-
Success(_translationService.GetResource("Admin.Customers.Customers.Added"));
return continueEditing ? RedirectToAction("Edit", new { id = customer.Id }) : RedirectToAction("List");
}
@@ -325,32 +264,6 @@ namespace Grand.Web.Admin.Controllers
//No customer found with the specified id
return RedirectToAction("List");
- //validate customer groups
- var allCustomerGroups = await _groupService.GetAllCustomerGroups(showHidden: true);
- var newCustomerGroups = new List<CustomerGroup>();
- foreach (var customerGroup in allCustomerGroups)
- if (model.CustomerGroups != null && model.CustomerGroups.Contains(customerGroup.Id))
- newCustomerGroups.Add(customerGroup);
-
- var customerGroupsError = await _customerViewModelService.ValidateCustomerGroups(newCustomerGroups);
- if (!string.IsNullOrEmpty(customerGroupsError))
- {
- ModelState.AddModelError("", customerGroupsError);
- Error(customerGroupsError);
- }
- if (!string.IsNullOrWhiteSpace(model.Owner))
- {
- var custowner = await _customerService.GetCustomerByEmail(model.Owner);
- if (custowner == null)
- ModelState.AddModelError("", "Owner email is not exists");
-
- if (string.Equals(model.Owner, model.Email, StringComparison.CurrentCultureIgnoreCase))
- ModelState.AddModelError("", "You can't assign own email");
- }
-
- if (await _groupService.IsSalesManager(_workContext.CurrentCustomer) && customer.Id == _workContext.CurrentCustomer.Id)
- ModelState.AddModelError("", "You can't edit own data from admin panel");
-
if(!customer.GetUserFieldFromEntity<bool>(SystemCustomerFieldNames.TwoFactorEnabled) && model.TwoFactorEnabled)
Warning(_translationService.GetResource("Admin.Customers.Customers.CannotTwoFactorEnabled"));
@@ -366,26 +279,6 @@ namespace Grand.Web.Admin.Controllers
var changePassRequest = new ChangePasswordRequest(model.Email, _customerSettings.DefaultPasswordFormat, model.Password);
await _customerManagerService.ChangePassword(changePassRequest);
}
- if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(model.VendorId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.AdminCouldNotbeVendor"));
- }
- if (newCustomerGroups.Any(x => x.SystemName == SystemCustomerGroupNames.Vendors) && string.IsNullOrEmpty(model.VendorId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated"));
- }
- if (newCustomerGroups.Any(x => x.SystemName == SystemCustomerGroupNames.Staff) && string.IsNullOrEmpty(model.StaffStoreId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.CannotBeInStaffGroupWithoutStaffAssociated"));
- }
- if (newCustomerGroups.Any(x => x.SystemName == SystemCustomerGroupNames.SalesManager) && string.IsNullOrEmpty(model.SeId))
- {
- Error(_translationService.GetResource("Admin.Customers.Customers.CannotBeInSalesManagerGroupWithoutSalesEmployeeAssociated"));
- }
- if (await _groupService.IsStaff(customer) && await _groupService.IsVendor(customer))
- {
- Warning(_translationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff"));
- }
Success(_translationService.GetResource("Admin.Customers.Customers.Updated"));
if (continueEditing)
{
@@ -683,16 +576,10 @@ namespace Grand.Web.Admin.Controllers
//No customer found with the specified id
return RedirectToAction("List");
- //custom address attributes
- var customAttributes = await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);
- var customAttributeWarnings = await _addressAttributeParser.GetAttributeWarnings(customAttributes);
- foreach (var error in customAttributeWarnings)
- {
- ModelState.AddModelError("", error);
- }
-
if (ModelState.IsValid)
{
+ //custom address attributes
+ var customAttributes = await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);
var address = await _customerViewModelService.InsertAddressModel(customer, model, customAttributes);
Success(_translationService.GetResource("Admin.Customers.Customers.Addresses.Added"));
return RedirectToAction("AddressEdit", new { addressId = address.Id, customerId = model.CustomerId });
@@ -736,16 +623,10 @@ namespace Grand.Web.Admin.Controllers
//No address found with the specified id
return RedirectToAction("Edit", new { id = customer.Id });
- //custom address attributes
- var customAttributes = await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);
- var customAttributeWarnings = await _addressAttributeParser.GetAttributeWarnings(customAttributes);
- foreach (var error in customAttributeWarnings)
- {
- ModelState.AddModelError("", error);
- }
-
if (ModelState.IsValid)
{
+ //custom address attributes
+ var customAttributes = await model.Address.ParseCustomAddressAttributes(_addressAttributeParser, _addressAttributeService);
address = await _customerViewModelService.UpdateAddressModel(customer, address, model, customAttributes);
Success(_translationService.GetResource("Admin.Customers.Customers.Addresses.Updated"));
return RedirectToAction("AddressEdit", new { addressId = model.Address.Id, customerId = model.CustomerId });
diff --git a/src/Web/Grand.Web.Admin/Interfaces/ICustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Interfaces/ICustomerViewModelService.cs
index d62b2b682..b7077cad6 100644
--- a/src/Web/Grand.Web.Admin/Interfaces/ICustomerViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Interfaces/ICustomerViewModelService.cs
@@ -15,7 +15,6 @@ namespace Grand.Web.Admin.Interfaces
Task<(IEnumerable<CustomerModel> customerModelList, int totalCount)> PrepareCustomerList(CustomerListModel model,
string[] searchCustomerGroupIds, string[] searchCustomerTagIds, int pageIndex, int pageSize);
Task PrepareCustomerModel(CustomerModel model, Customer customer, bool excludeProperties);
- Task<string> ValidateCustomerGroups(IList<CustomerGroup> customerGroups);
Task<Customer> InsertCustomerModel(CustomerModel model);
Task<Customer> UpdateCustomerModel(Customer customer, CustomerModel model);
Task DeleteCustomer(Customer customer);
diff --git a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
index dbfbb7ac9..8f6a491be 100644
--- a/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
+++ b/src/Web/Grand.Web.Admin/Services/CustomerViewModelService.cs
@@ -618,32 +618,6 @@ namespace Grand.Web.Admin.Services
!customer.Active;
}
- public virtual async Task<string> ValidateCustomerGroups(IList<CustomerGroup> customerGroups)
- {
- if (customerGroups == null)
- throw new ArgumentNullException(nameof(customerGroups));
-
- //ensure a customer is not added to both 'Guests' and 'Registered' customer groups
- //ensure that a customer is in at least one required role ('Guests' and 'Registered')
- var isInGuestsGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Guests) != null;
- var isInRegisteredGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Registered) != null;
- var isAdminGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Administrators) != null;
-
- if (isInGuestsGroup && isInRegisteredGroup)
- return "The customer cannot be in both 'Guests' and 'Registered' customer groups";
-
- if (!isInGuestsGroup && !isInRegisteredGroup)
- return "Add the customer to 'Guests' or 'Registered' customer group";
-
- if (await _groupService.IsSalesManager(_workContext.CurrentCustomer) && (isInGuestsGroup || customerGroups.Count != 1))
- return "Sales manager can assign role 'Registered' only";
-
- if (!await _groupService.IsAdmin(_workContext.CurrentCustomer) && isAdminGroup)
- return "Only administrators can assign role 'Administrators'";
-
- //no errors
- return "";
- }
public virtual async Task<Customer> InsertCustomerModel(CustomerModel model)
{
var ownerId = string.Empty;
@@ -750,46 +724,7 @@ namespace Grand.Web.Admin.Services
customer.Groups.Add(customerGroup.Id);
await _customerService.InsertCustomerGroupInCustomer(customerGroup, customer.Id);
}
-
-
- //ensure that a customer with a vendor associated is not in "Administrators" role
- //otherwise, he won't be have access to the other functionality in admin area
- if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(customer.VendorId))
- {
- customer.VendorId = "";
- await _customerService.UpdateCustomerField(customer.Id, x => x.VendorId, customer.VendorId);
- }
-
- //ensure that a customer in the Vendors role has a vendor account associated.
- //otherwise, he will have access to ALL products
- if (await _groupService.IsVendor(customer) && string.IsNullOrEmpty(customer.VendorId))
- {
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- var vendorGroup = customerGroups.FirstOrDefault(x => x.SystemName == SystemCustomerGroupNames.Vendors);
- customer.Groups.Remove(vendorGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(vendorGroup, customer.Id);
- }
-
- //ensure that a customer in the Staff role has a staff account associated.
- //otherwise, he will have access to ALL products
- if (await _groupService.IsStaff(customer) && string.IsNullOrEmpty(customer.StaffStoreId))
- {
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- var staffGroup = customerGroups.FirstOrDefault(x => x.SystemName == SystemCustomerGroupNames.Staff);
- customer.Groups.Remove(staffGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(staffGroup, customer.Id);
- }
-
- //ensure that a customer in the Sales manager role has a staff employee associated.
- //otherwise, he will have access to ALL customers
- if (await _groupService.IsSalesManager(customer) && string.IsNullOrEmpty(customer.SeId))
- {
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- var salesGroup = customerGroups.FirstOrDefault(x => x.SystemName == SystemCustomerGroupNames.SalesManager);
- customer.Groups.Remove(salesGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(salesGroup, customer.Id);
- }
-
+
//tags
await SaveCustomerTags(customer, ParseCustomerTags(model.CustomerTags));
@@ -964,53 +899,6 @@ namespace Grand.Web.Admin.Services
}
await _customerService.UpdateCustomerInAdminPanel(customer);
-
- //ensure that a customer with a vendor associated is not in "Administrators" role
- //otherwise, he won't have access to the other functionality in admin area
- if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(customer.VendorId))
- {
- customer.VendorId = "";
- await _customerService.UpdateCustomerInAdminPanel(customer);
- }
-
- //ensure that a customer with a staff associated is not in "Administrators" role
- //otherwise, he won't have access to the other functionality in admin area
- if (await _groupService.IsAdmin(customer) && !string.IsNullOrEmpty(customer.StaffStoreId))
- {
- customer.StaffStoreId = "";
- await _customerService.UpdateCustomerInAdminPanel(customer);
- }
-
- //ensure that a customer in the Vendors role has a vendor account associated.
- //otherwise, he will have access to ALL products
- if (await _groupService.IsVendor(customer) && string.IsNullOrEmpty(customer.VendorId))
- {
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- var vendorGroup = customerGroups.FirstOrDefault(x => x.SystemName == SystemCustomerGroupNames.Vendors);
- customer.Groups.Remove(vendorGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(vendorGroup, customer.Id);
- }
-
- //ensure that a customer in the Sales manager role has a staff employee associated.
- //otherwise, he will have access to ALL customers
- if (await _groupService.IsSalesManager(customer) && string.IsNullOrEmpty(customer.SeId))
- {
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- var salesGroup = customerGroups.FirstOrDefault(x => x.SystemName == SystemCustomerGroupNames.SalesManager);
- customer.Groups.Remove(salesGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(salesGroup, customer.Id);
- }
-
- //ensure that a customer in the Staff group has a staff account associated.
- //otherwise, he will have access to ALL products
- if (await _groupService.IsStaff(customer) && string.IsNullOrEmpty(customer.StaffStoreId))
- {
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- var staffGroup = customerGroups.FirstOrDefault(x => x.SystemName == SystemCustomerGroupNames.Staff);
- customer.Groups.Remove(staffGroup.Id);
- await _customerService.DeleteCustomerGroupInCustomer(staffGroup, customer.Id);
- }
-
//tags
await SaveCustomerTags(customer, ParseCustomerTags(model.CustomerTags));
diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerAddressValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerAddressValidator.cs
index 7e77d0cfa..20ca51ffe 100644
--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerAddressValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerAddressValidator.cs
@@ -1,5 +1,8 @@
-using Grand.Infrastructure.Validators;
+using FluentValidation;
+using Grand.Business.Core.Interfaces.Common.Addresses;
+using Grand.Infrastructure.Validators;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Web.Admin.Extensions;
using Grand.Web.Admin.Models.Customers;
using Grand.Web.Admin.Validators.Common;
@@ -10,10 +13,24 @@ namespace Grand.Web.Admin.Validators.Customers
public CustomerAddressValidator(
IEnumerable<IValidatorConsumer<CustomerAddressModel>> validators,
IEnumerable<IValidatorConsumer<Models.Common.AddressModel>> addressvalidators,
+ IAddressAttributeParser addressAttributeParser,
+ IAddressAttributeService addressAttributeService,
ITranslationService translationService)
: base(validators)
{
RuleFor(x => x.Address).SetValidator(new AddressValidator(addressvalidators, translationService));
+ RuleFor(x => x).CustomAsync(async (x, context, _) =>
+ {
+ var customAddressAttributes =
+ await x.Address.ParseCustomAddressAttributes(addressAttributeParser,
+ addressAttributeService);
+ var customAddressAttributeWarnings =
+ await addressAttributeParser.GetAttributeWarnings(customAddressAttributes);
+ foreach (var error in customAddressAttributeWarnings)
+ {
+ context.AddFailure(error);
+ }
+ });
}
}
}
diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
index 841486eff..2deddf3f0 100644
--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs
@@ -3,7 +3,10 @@ using Grand.Domain.Customers;
using Grand.Infrastructure.Validators;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Business.Core.Interfaces.Customers;
+using Grand.Infrastructure;
using Grand.Web.Admin.Models.Customers;
+using Microsoft.AspNetCore.Mvc.Infrastructure;
using System.Text.RegularExpressions;
namespace Grand.Web.Admin.Validators.Customers
@@ -14,12 +17,23 @@ namespace Grand.Web.Admin.Validators.Customers
IEnumerable<IValidatorConsumer<CustomerModel>> validators,
ITranslationService translationService,
ICountryService countryService,
- CustomerSettings customerSettings)
+ IWorkContext workContext,
+ ICustomerService customerService,
+ IGroupService groupService,
+ CustomerSettings customerSettings,
+ IActionContextAccessor actionContextAccessor)
: base(validators)
{
- //customer email
- RuleFor(x => x.Email).NotEmpty().EmailAddress().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Email.Required"));
+ var currentAction = actionContextAccessor.ActionContext?.RouteData.Values["action"]?.ToString();
+ var currentController = actionContextAccessor.ActionContext?.RouteData.Values["controller"]?.ToString();
+
+ CustomerCreateValidator();
+ CustomerEditValidator();
+ //customer email
+ RuleFor(x => x.Email).NotEmpty().EmailAddress()
+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Email.Required"));
+
//form fields
if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
{
@@ -27,6 +41,7 @@ namespace Grand.Web.Admin.Validators.Customers
.NotEqual("")
.WithMessage(translationService.GetResource("Account.Fields.Country.Required"));
}
+
if (customerSettings.CountryEnabled &&
customerSettings.StateProvinceEnabled &&
customerSettings.StateProvinceRequired)
@@ -42,26 +57,36 @@ namespace Grand.Web.Admin.Validators.Customers
{
return false;
}
+
if (country.StateProvinces.FirstOrDefault(x => x.Id == y) != null)
return true;
}
+
return false;
}).WithMessage(translationService.GetResource("Account.Fields.StateProvince.Required"));
}
+
if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)
- RuleFor(x => x.Company).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Company.Required"));
- if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
- RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.StreetAddress.Required"));
+ RuleFor(x => x.Company).NotEmpty()
+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Company.Required"));
+ if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
+ RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(
+ translationService.GetResource("Admin.Customers.Customers.Fields.StreetAddress.Required"));
if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)
- RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.StreetAddress2.Required"));
+ RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(
+ translationService.GetResource("Admin.Customers.Customers.Fields.StreetAddress2.Required"));
if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)
- RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.ZipPostalCode.Required"));
+ RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(
+ translationService.GetResource("Admin.Customers.Customers.Fields.ZipPostalCode.Required"));
if (customerSettings.CityRequired && customerSettings.CityEnabled)
- RuleFor(x => x.City).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.City.Required"));
+ RuleFor(x => x.City).NotEmpty()
+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.City.Required"));
if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)
- RuleFor(x => x.Phone).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Phone.Required"));
- if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
- RuleFor(x => x.Fax).NotEmpty().WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Fax.Required"));
+ RuleFor(x => x.Phone).NotEmpty()
+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Phone.Required"));
+ if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
+ RuleFor(x => x.Fax).NotEmpty()
+ .WithMessage(translationService.GetResource("Admin.Customers.Customers.Fields.Fax.Required"));
RuleFor(x => x).Custom((x, context) =>
{
@@ -70,11 +95,138 @@ namespace Grand.Web.Admin.Validators.Customers
if (!string.IsNullOrEmpty(customerSettings.PasswordRegularExpression))
{
Regex passwordregex = new Regex(customerSettings.PasswordRegularExpression);
- if(!passwordregex.Match(x.Password).Success)
+ if (!passwordregex.Match(x.Password).Success)
context.AddFailure(translationService.GetResource("Account.Fields.Password.Validation"));
}
}
});
+
+ async Task<string> ValidateCustomerGroups(IList<CustomerGroup> customerGroups, CustomerModel customerModel)
+ {
+ if (customerGroups == null)
+ throw new ArgumentNullException(nameof(customerGroups));
+
+ //ensure a customer is not added to both 'Guests' and 'Registered' customer groups
+ //ensure that a customer is in at least one required role ('Guests' and 'Registered')
+ var isInGuestsGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Guests) != null;
+ var isInRegisteredGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Registered) != null;
+ var isAdminGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Administrators) != null;
+ var isVendorGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Vendors) != null;
+ var isStaffGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.Staff) != null;
+ var isSalesGroup = customerGroups.FirstOrDefault(cr => cr.SystemName == SystemCustomerGroupNames.SalesManager) != null;
+
+ if (isInGuestsGroup && isInRegisteredGroup)
+ return "The customer cannot be in both 'Guests' and 'Registered' customer groups";
+
+ if (!isInGuestsGroup && !isInRegisteredGroup)
+ return "Add the customer to 'Guests' or 'Registered' customer group";
+
+ if (await groupService.IsSalesManager(workContext.CurrentCustomer) &&
+ (isInGuestsGroup || customerGroups.Count != 1))
+ return "Sales manager can assign role 'Registered' only";
+
+ if (!await groupService.IsAdmin(workContext.CurrentCustomer) && isAdminGroup)
+ return "Only administrators can assign role 'Administrators'";
+
+ if (isAdminGroup && !string.IsNullOrEmpty(customerModel.VendorId))
+ return "A customer who is associated with a vendor can't be assigned the 'Administrator' role";
+
+ if (isAdminGroup && !string.IsNullOrEmpty(customerModel.StaffStoreId))
+ return "A customer who is associated with a staff can't be assigned the 'Administrator' role";
+
+ if (isVendorGroup && string.IsNullOrEmpty(customerModel.VendorId))
+ return translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated");
+
+ if (isVendorGroup && string.IsNullOrEmpty(customerModel.VendorId))
+ return translationService.GetResource("Admin.Customers.Customers.CannotBeInVendoGroupWithoutVendorAssociated");
+
+ if (isVendorGroup && isStaffGroup)
+ return translationService.GetResource("Admin.Customers.Customers.VendorShouldNotbeStaff");
+
+ if (isStaffGroup && string.IsNullOrEmpty(customerModel.StaffStoreId))
+ return translationService.GetResource("Admin.Customers.Customers.CannotBeInStaffGroupWithoutStaffAssociated");
+
+ if (isSalesGroup && string.IsNullOrEmpty(customerModel.SeId))
+ return translationService.GetResource("Admin.Customers.Customers.CannotBeInSalesManagerGroupWithoutSalesEmployeeAssociated");
+
+ //no errors
+ return "";
+ }
+ void CustomerCreateValidator()
+ {
+ When(x => (currentAction == "Create" && currentController == "Customer"), () =>
+ {
+ RuleFor(x => x).CustomAsync(async (x, context, y) =>
+ {
+ if (!string.IsNullOrWhiteSpace(x.Email))
+ {
+ var customerByEmail = await customerService.GetCustomerByEmail(x.Email);
+ if (customerByEmail != null)
+ context.AddFailure("Email is already registered");
+ }
+
+ if (!string.IsNullOrWhiteSpace(x.Owner))
+ {
+ var customerOwner = await customerService.GetCustomerByEmail(x.Owner);
+ if (customerOwner == null)
+ context.AddFailure("Owner email is not exists");
+ }
+
+ if (!string.IsNullOrWhiteSpace(x.Username) & customerSettings.UsernamesEnabled)
+ {
+ var customerByUsername = await customerService.GetCustomerByUsername(x.Username);
+ if (customerByUsername != null)
+ context.AddFailure("Username is already registered");
+ }
+
+ //validate customer groups
+ var allCustomerGroups = await groupService.GetAllCustomerGroups(showHidden: true);
+ var newCustomerGroups = allCustomerGroups.Where(customerGroup =>
+ x.CustomerGroups != null && x.CustomerGroups.Contains(customerGroup.Id)).ToList();
+ var customerGroupsError = await ValidateCustomerGroups(newCustomerGroups, x);
+ if (!string.IsNullOrEmpty(customerGroupsError))
+ {
+ context.AddFailure(customerGroupsError);
+ }
+ });
+ });
+ }
+
+ void CustomerEditValidator()
+ {
+ When(x => (currentAction == "Edit" && currentController == "Customer"), () =>
+ {
+ RuleFor(x => x).CustomAsync(async (x, context, y) =>
+ {
+ //validate customer groups
+ var allCustomerGroups = await groupService.GetAllCustomerGroups(showHidden: true);
+ var newCustomerGroups = allCustomerGroups.Where(customerGroup =>
+ x.CustomerGroups != null && x.CustomerGroups.Contains(customerGroup.Id)).ToList();
+
+ var customerGroupsError = await ValidateCustomerGroups(newCustomerGroups, x);
+ if (!string.IsNullOrEmpty(customerGroupsError))
+ {
+ context.AddFailure(customerGroupsError);
+ }
+
+ if (!string.IsNullOrWhiteSpace(x.Owner))
+ {
+ var customerByOwner = await customerService.GetCustomerByEmail(x.Owner);
+ if (customerByOwner == null)
+ context.AddFailure("Owner email is not exists");
+
+ if (string.Equals(x.Owner, x.Email, StringComparison.CurrentCultureIgnoreCase))
+ context.AddFailure("You can't assign own email");
+ }
+
+ var customer = await customerService.GetCustomerById(x.Id);
+ if (await groupService.IsSalesManager(workContext.CurrentCustomer) &&
+ customer?.Id == workContext.CurrentCustomer.Id)
+ context.AddFailure("You can't edit own data from admin panel");
+ });
+ });
+ }
+
}
}
}
\ No newline at end of file