public virtual async Task <IActionResult> GetStatesByCountryId(string countryId, bool?addSelectStateItem, bool?addAsterisk) { //permission validation is not required here // This action method gets called via an ajax request if (string.IsNullOrEmpty(countryId)) { throw new ArgumentNullException(nameof(countryId)); } var country = await _countryService.GetCountryByIdAsync(Convert.ToInt32(countryId)); var states = country != null ? (await _stateProvinceService.GetStateProvincesByCountryIdAsync(country.Id, showHidden: true)).ToList() : new List <StateProvince>(); var result = (from s in states select new { id = s.Id, name = s.Name }).ToList(); if (addAsterisk.HasValue && addAsterisk.Value) { //asterisk result.Insert(0, new { id = 0, name = "*" }); } else { if (country == null) { //country is not selected ("choose country" item) if (addSelectStateItem.HasValue && addSelectStateItem.Value) { result.Insert(0, new { id = 0, name = await _localizationService.GetResourceAsync("Admin.Address.SelectState") }); } else { result.Insert(0, new { id = 0, name = await _localizationService.GetResourceAsync("Admin.Address.Other") }); } } else { //some country is selected if (!result.Any()) { //country does not have states result.Insert(0, new { id = 0, name = await _localizationService.GetResourceAsync("Admin.Address.Other") }); } else { //country has some states if (addSelectStateItem.HasValue && addSelectStateItem.Value) { result.Insert(0, new { id = 0, name = await _localizationService.GetResourceAsync("Admin.Address.SelectState") }); } } } } return(Json(result)); }
/// <summary> /// Prepare payment method restriction model /// </summary> /// <param name="model">Payment method restriction model</param> /// <returns>Payment method restriction model</returns> protected virtual async Task <PaymentMethodRestrictionModel> PreparePaymentMethodRestrictionModelAsync(PaymentMethodRestrictionModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } var countries = await _countryService.GetAllCountriesAsync(showHidden : true); model.AvailableCountries = await countries.SelectAwait(async country => { var countryModel = country.ToModel <CountryModel>(); countryModel.NumberOfStates = (await _stateProvinceService.GetStateProvincesByCountryIdAsync(country.Id))?.Count ?? 0; return(countryModel); }).ToListAsync(); foreach (var method in await _paymentPluginManager.LoadAllPluginsAsync()) { var paymentMethodModel = method.ToPluginModel <PaymentMethodModel>(); paymentMethodModel.RecurringPaymentType = await _localizationService.GetLocalizedEnumAsync(method.RecurringPaymentType); model.AvailablePaymentMethods.Add(paymentMethodModel); var restrictedCountries = await _paymentPluginManager.GetRestrictedCountryIdsAsync(method); foreach (var country in countries) { if (!model.Restricted.ContainsKey(method.PluginDescriptor.SystemName)) { model.Restricted[method.PluginDescriptor.SystemName] = new Dictionary <int, bool>(); } model.Restricted[method.PluginDescriptor.SystemName][country.Id] = restrictedCountries.Contains(country.Id); } } return(model); }
/// <summary> /// Gets a value indicating whether address is valid (can be saved) /// </summary> /// <param name="address">Address to validate</param> /// <returns>Result</returns> public virtual async Task <bool> IsAddressValidAsync(Address address) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (string.IsNullOrWhiteSpace(address.FirstName)) { return(false); } if (string.IsNullOrWhiteSpace(address.LastName)) { return(false); } if (string.IsNullOrWhiteSpace(address.Email)) { return(false); } if (_addressSettings.CompanyEnabled && _addressSettings.CompanyRequired && string.IsNullOrWhiteSpace(address.Company)) { return(false); } if (_addressSettings.StreetAddressEnabled && _addressSettings.StreetAddressRequired && string.IsNullOrWhiteSpace(address.Address1)) { return(false); } if (_addressSettings.StreetAddress2Enabled && _addressSettings.StreetAddress2Required && string.IsNullOrWhiteSpace(address.Address2)) { return(false); } if (_addressSettings.ZipPostalCodeEnabled && _addressSettings.ZipPostalCodeRequired && string.IsNullOrWhiteSpace(address.ZipPostalCode)) { return(false); } if (_addressSettings.CountryEnabled) { var country = await _countryService.GetCountryByAddressAsync(address); if (country == null) { return(false); } if (_addressSettings.StateProvinceEnabled) { var states = await _stateProvinceService.GetStateProvincesByCountryIdAsync(country.Id); if (states.Any()) { if (address.StateProvinceId == null || address.StateProvinceId.Value == 0) { return(false); } var state = states.FirstOrDefault(x => x.Id == address.StateProvinceId.Value); if (state == null) { return(false); } } } } if (_addressSettings.CountyEnabled && _addressSettings.CountyRequired && string.IsNullOrWhiteSpace(address.County)) { return(false); } if (_addressSettings.CityEnabled && _addressSettings.CityRequired && string.IsNullOrWhiteSpace(address.City)) { return(false); } if (_addressSettings.PhoneEnabled && _addressSettings.PhoneRequired && string.IsNullOrWhiteSpace(address.PhoneNumber)) { return(false); } if (_addressSettings.FaxEnabled && _addressSettings.FaxRequired && string.IsNullOrWhiteSpace(address.FaxNumber)) { return(false); } var requiredAttributes = (await _addressAttributeService.GetAllAddressAttributesAsync()).Where(x => x.IsRequired); foreach (var requiredAttribute in requiredAttributes) { var value = _addressAttributeParser.ParseValues(address.CustomAttributes, requiredAttribute.Id); if (!value.Any() || string.IsNullOrEmpty(value[0])) { return(false); } } return(true); }
public CustomerValidator(CustomerSettings customerSettings, ICustomerService customerService, ILocalizationService localizationService, IMappingEntityAccessor mappingEntityAccessor, IStateProvinceService stateProvinceService) { //ensure that valid email address is entered if Registered role is checked to avoid registered customers with empty email address RuleFor(x => x.Email) .NotEmpty() .EmailAddress() //.WithMessage("Valid Email is required for customer to be in 'Registered' role") .WithMessageAwait(localizationService.GetResourceAsync("Admin.Common.WrongEmail")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); //form fields if (customerSettings.CountryEnabled && customerSettings.CountryRequired) { RuleFor(x => x.CountryId) .NotEqual(0) .WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Country.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.CountryEnabled && customerSettings.StateProvinceEnabled && customerSettings.StateProvinceRequired) { RuleFor(x => x.StateProvinceId).MustAwait(async(x, context) => { //does selected country have states? var hasStates = (await stateProvinceService.GetStateProvincesByCountryIdAsync(x.CountryId)).Any(); if (hasStates) { //if yes, then ensure that a state is selected if (x.StateProvinceId == 0) { return(false); } } return(true); }).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.StateProvince.Required")); } if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled) { RuleFor(x => x.Company) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.Company.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled) { RuleFor(x => x.StreetAddress) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.StreetAddress.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled) { RuleFor(x => x.StreetAddress2) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.StreetAddress2.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled) { RuleFor(x => x.ZipPostalCode) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.ZipPostalCode.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.CityRequired && customerSettings.CityEnabled) { RuleFor(x => x.City) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.City.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.CountyRequired && customerSettings.CountyEnabled) { RuleFor(x => x.County) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.County.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled) { RuleFor(x => x.Phone) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.Phone.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } if (customerSettings.FaxRequired && customerSettings.FaxEnabled) { RuleFor(x => x.Fax) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Admin.Customers.Customers.Fields.Fax.Required")) //only for registered users .WhenAwait(async x => await IsRegisteredCustomerRoleCheckedAsync(x, customerService)); } SetDatabaseValidationRules <Customer>(mappingEntityAccessor); }
/// <returns>A task that represents the asynchronous operation</returns> public async Task <IActionResult> EditRateByWeightByTotalPopup(int id) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageShippingSettings)) { return(AccessDeniedView()); } var sbw = await _shippingByWeightService.GetByIdAsync(id); if (sbw == null) { //no record found with the specified id return(RedirectToAction("Configure")); } var model = new ShippingByWeightByTotalModel { Id = sbw.Id, StoreId = sbw.StoreId, WarehouseId = sbw.WarehouseId, CountryId = sbw.CountryId, StateProvinceId = sbw.StateProvinceId, Zip = sbw.Zip, ShippingMethodId = sbw.ShippingMethodId, WeightFrom = sbw.WeightFrom, WeightTo = sbw.WeightTo, OrderSubtotalFrom = sbw.OrderSubtotalFrom, OrderSubtotalTo = sbw.OrderSubtotalTo, AdditionalFixedCost = sbw.AdditionalFixedCost, PercentageRateOfSubtotal = sbw.PercentageRateOfSubtotal, RatePerWeightUnit = sbw.RatePerWeightUnit, LowerWeightLimit = sbw.LowerWeightLimit, PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyByIdAsync(_currencySettings.PrimaryStoreCurrencyId))?.CurrencyCode, BaseWeightIn = (await _measureService.GetMeasureWeightByIdAsync(_measureSettings.BaseWeightId))?.Name, TransitDays = sbw.TransitDays }; var shippingMethods = await _shippingService.GetAllShippingMethodsAsync(); if (!shippingMethods.Any()) { return(Content("No shipping methods can be loaded")); } var selectedStore = await _storeService.GetStoreByIdAsync(sbw.StoreId); var selectedWarehouse = await _shippingService.GetWarehouseByIdAsync(sbw.WarehouseId); var selectedShippingMethod = await _shippingService.GetShippingMethodByIdAsync(sbw.ShippingMethodId); var selectedCountry = await _countryService.GetCountryByIdAsync(sbw.CountryId); var selectedState = await _stateProvinceService.GetStateProvinceByIdAsync(sbw.StateProvinceId); //stores model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "0" }); foreach (var store in await _storeService.GetAllStoresAsync()) { model.AvailableStores.Add(new SelectListItem { Text = store.Name, Value = store.Id.ToString(), Selected = (selectedStore != null && store.Id == selectedStore.Id) }); } //warehouses model.AvailableWarehouses.Add(new SelectListItem { Text = "*", Value = "0" }); foreach (var warehouse in await _shippingService.GetAllWarehousesAsync()) { model.AvailableWarehouses.Add(new SelectListItem { Text = warehouse.Name, Value = warehouse.Id.ToString(), Selected = (selectedWarehouse != null && warehouse.Id == selectedWarehouse.Id) }); } //shipping methods foreach (var sm in shippingMethods) { model.AvailableShippingMethods.Add(new SelectListItem { Text = sm.Name, Value = sm.Id.ToString(), Selected = (selectedShippingMethod != null && sm.Id == selectedShippingMethod.Id) }); } //countries model.AvailableCountries.Add(new SelectListItem { Text = "*", Value = "0" }); var countries = await _countryService.GetAllCountriesAsync(showHidden : true); foreach (var c in countries) { model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = (selectedCountry != null && c.Id == selectedCountry.Id) }); } //states var states = selectedCountry != null ? (await _stateProvinceService.GetStateProvincesByCountryIdAsync(selectedCountry.Id, showHidden: true)).ToList() : new List <StateProvince>(); model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "0" }); foreach (var s in states) { model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (selectedState != null && s.Id == selectedState.Id) }); } return(View("~/Plugins/Shipping.FixedByWeightByTotal/Views/EditRateByWeightByTotalPopup.cshtml", model)); }
public RegisterValidator(ILocalizationService localizationService, IStateProvinceService stateProvinceService, CustomerSettings customerSettings) { RuleFor(x => x.Email).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Email.Required")); RuleFor(x => x.Email).EmailAddress().WithMessageAwait(localizationService.GetResourceAsync("Common.WrongEmail")); if (customerSettings.EnteringEmailTwice) { RuleFor(x => x.ConfirmEmail).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.ConfirmEmail.Required")); RuleFor(x => x.ConfirmEmail).EmailAddress().WithMessageAwait(localizationService.GetResourceAsync("Common.WrongEmail")); RuleFor(x => x.ConfirmEmail).Equal(x => x.Email).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Email.EnteredEmailsDoNotMatch")); } if (customerSettings.UsernamesEnabled) { RuleFor(x => x.Username).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Username.Required")); RuleFor(x => x.Username).IsUsername(customerSettings).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Username.NotValid")); } if (customerSettings.FirstNameEnabled && customerSettings.FirstNameRequired) { RuleFor(x => x.FirstName).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.FirstName.Required")); } if (customerSettings.LastNameEnabled && customerSettings.LastNameRequired) { RuleFor(x => x.LastName).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.LastName.Required")); } //Password rule RuleFor(x => x.Password).IsPassword(localizationService, customerSettings); RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.ConfirmPassword.Required")); RuleFor(x => x.ConfirmPassword).Equal(x => x.Password).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Password.EnteredPasswordsDoNotMatch")); //form fields if (customerSettings.CountryEnabled && customerSettings.CountryRequired) { RuleFor(x => x.CountryId) .NotEqual(0) .WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Country.Required")); } if (customerSettings.CountryEnabled && customerSettings.StateProvinceEnabled && customerSettings.StateProvinceRequired) { RuleFor(x => x.StateProvinceId).MustAwait(async(x, context) => { //does selected country have states? var hasStates = (await stateProvinceService.GetStateProvincesByCountryIdAsync(x.CountryId)).Any(); if (hasStates) { //if yes, then ensure that a state is selected if (x.StateProvinceId == 0) { return(false); } } return(true); }).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.StateProvince.Required")); } if (customerSettings.DateOfBirthEnabled && customerSettings.DateOfBirthRequired) { //entered? RuleFor(x => x.DateOfBirthDay).Must((x, context) => { var dateOfBirth = x.ParseDateOfBirth(); if (!dateOfBirth.HasValue) { return(false); } return(true); }).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.DateOfBirth.Required")); //minimum age RuleFor(x => x.DateOfBirthDay).Must((x, context) => { var dateOfBirth = x.ParseDateOfBirth(); if (dateOfBirth.HasValue && customerSettings.DateOfBirthMinimumAge.HasValue && CommonHelper.GetDifferenceInYears(dateOfBirth.Value, DateTime.Today) < customerSettings.DateOfBirthMinimumAge.Value) { return(false); } return(true); }).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.DateOfBirth.MinimumAge"), customerSettings.DateOfBirthMinimumAge); } if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled) { RuleFor(x => x.Company).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Company.Required")); } if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled) { RuleFor(x => x.StreetAddress).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.StreetAddress.Required")); } if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled) { RuleFor(x => x.StreetAddress2).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.StreetAddress2.Required")); } if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled) { RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.ZipPostalCode.Required")); } if (customerSettings.CountyRequired && customerSettings.CountyEnabled) { RuleFor(x => x.County).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.County.Required")); } if (customerSettings.CityRequired && customerSettings.CityEnabled) { RuleFor(x => x.City).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.City.Required")); } if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled) { RuleFor(x => x.Phone).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Phone.Required")); } if (customerSettings.PhoneEnabled) { RuleFor(x => x.Phone).IsPhoneNumber(customerSettings).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Phone.NotValid")); } if (customerSettings.FaxRequired && customerSettings.FaxEnabled) { RuleFor(x => x.Fax).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Fax.Required")); } }
/// <summary> /// Get states and provinces by country identifier /// </summary> /// <param name="countryId">Country identifier</param> /// <param name="addSelectStateItem">Whether to add "Select state" item to list of states</param> /// <returns>List of identifiers and names of states and provinces</returns> public virtual async Task <IList <StateProvinceModel> > GetStatesByCountryIdAsync(string countryId, bool addSelectStateItem) { if (string.IsNullOrEmpty(countryId)) { throw new ArgumentNullException(nameof(countryId)); } var country = await _countryService.GetCountryByIdAsync(Convert.ToInt32(countryId)); var states = (await _stateProvinceService .GetStateProvincesByCountryIdAsync(country?.Id ?? 0, (await _workContext.GetWorkingLanguageAsync()).Id)) .ToList(); var result = new List <StateProvinceModel>(); foreach (var state in states) { result.Add(new StateProvinceModel { id = state.Id, name = await _localizationService.GetLocalizedAsync(state, x => x.Name) }); } if (country == null) { //country is not selected ("choose country" item) if (addSelectStateItem) { result.Insert(0, new StateProvinceModel { id = 0, name = await _localizationService.GetResourceAsync("Address.SelectState") }); } else { result.Insert(0, new StateProvinceModel { id = 0, name = await _localizationService.GetResourceAsync("Address.Other") }); } } else { //some country is selected if (!result.Any()) { //country does not have states result.Insert(0, new StateProvinceModel { id = 0, name = await _localizationService.GetResourceAsync("Address.Other") }); } else { //country has some states if (addSelectStateItem) { result.Insert(0, new StateProvinceModel { id = 0, name = await _localizationService.GetResourceAsync("Address.SelectState") }); } } } return(result); }
public async Task <IActionResult> Configure(bool showtour = false) { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageTaxSettings)) { return(AccessDeniedView()); } var taxCategories = await _taxCategoryService.GetAllTaxCategoriesAsync(); if (!taxCategories.Any()) { var errorModel = new ConfigurationModel { TaxCategoriesCanNotLoadedError = string.Format( await _localizationService.GetResourceAsync( "Plugins.Tax.FixedOrByCountryStateZip.TaxCategoriesCanNotLoaded"), Url.Action("Categories", "Tax")) }; return(View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", errorModel)); } var model = new ConfigurationModel { CountryStateZipEnabled = _countryStateZipSettings.CountryStateZipEnabled }; //stores model.AvailableStores.Add(new SelectListItem { Text = "*", Value = "0" }); var stores = await _storeService.GetAllStoresAsync(); foreach (var s in stores) { model.AvailableStores.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); } //tax categories foreach (var tc in taxCategories) { model.AvailableTaxCategories.Add(new SelectListItem { Text = tc.Name, Value = tc.Id.ToString() }); } //countries var countries = await _countryService.GetAllCountriesAsync(showHidden : true); foreach (var c in countries) { model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() }); } //states model.AvailableStates.Add(new SelectListItem { Text = "*", Value = "0" }); var defaultCountry = countries.FirstOrDefault(); if (defaultCountry != null) { var states = await _stateProvinceService.GetStateProvincesByCountryIdAsync(defaultCountry.Id); foreach (var s in states) { model.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString() }); } } //show configuration tour if (showtour) { var customer = await _workContext.GetCurrentCustomerAsync(); var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.HideConfigurationStepsAttribute); var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.CloseConfigurationStepsAttribute); if (!hideCard && !closeCard) { ViewBag.ShowTour = true; } } return(View("~/Plugins/Tax.FixedOrByCountryStateZip/Views/Configure.cshtml", model)); }
public async Task <IActionResult> Create() { if (!await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageShippingSettings)) { return(AccessDeniedView()); } var model = new StorePickupPointModel { Address = { CountryEnabled = _addressSettings.CountryEnabled, StateProvinceEnabled = _addressSettings.StateProvinceEnabled, ZipPostalCodeEnabled = _addressSettings.ZipPostalCodeEnabled, CityEnabled = _addressSettings.CityEnabled, CountyEnabled = _addressSettings.CountyEnabled } }; model.Address.AvailableCountries.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync("Admin.Address.SelectCountry"), Value = "0" }); foreach (var country in await _countryService.GetAllCountriesAsync(showHidden: true)) { model.Address.AvailableCountries.Add(new SelectListItem { Text = country.Name, Value = country.Id.ToString() }); } var states = !model.Address.CountryId.HasValue ? new List <StateProvince>() : await _stateProvinceService.GetStateProvincesByCountryIdAsync(model.Address.CountryId.Value, showHidden : true); if (states.Any()) { model.Address.AvailableStates.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync("Admin.Address.SelectState"), Value = "0" }); foreach (var state in states) { model.Address.AvailableStates.Add(new SelectListItem { Text = state.Name, Value = state.Id.ToString() }); } } else { model.Address.AvailableStates.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync("Admin.Address.Other"), Value = "0" }); } model.AvailableStores.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync("Admin.Configuration.Settings.StoreScope.AllStores"), Value = "0" }); foreach (var store in await _storeService.GetAllStoresAsync()) { model.AvailableStores.Add(new SelectListItem { Text = store.Name, Value = store.Id.ToString() }); } return(View("~/Plugins/Pickup.PickupInStore/Views/Create.cshtml", model)); }
/// <summary> /// Prepare address model /// </summary> /// <param name="model">Address model</param> /// <param name="address">Address entity</param> /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param> /// <param name="addressSettings">Address settings</param> /// <param name="loadCountries">Countries loading function; pass null if countries do not need to load</param> /// <param name="prePopulateWithCustomerFields">Whether to populate model properties with the customer fields (used with the customer entity)</param> /// <param name="customer">Customer entity; required if prePopulateWithCustomerFields is true</param> /// <param name="overrideAttributesXml">Overridden address attributes in XML format; pass null to use CustomAttributes of the address entity</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task PrepareAddressModelAsync(AddressModel model, Address address, bool excludeProperties, AddressSettings addressSettings, Func <Task <IList <Country> > > loadCountries = null, bool prePopulateWithCustomerFields = false, Customer customer = null, string overrideAttributesXml = "") { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (addressSettings == null) { throw new ArgumentNullException(nameof(addressSettings)); } if (!excludeProperties && address != null) { model.Id = address.Id; model.FirstName = address.FirstName; model.LastName = address.LastName; model.Email = address.Email; model.Company = address.Company; model.CountryId = address.CountryId; model.CountryName = await _countryService.GetCountryByAddressAsync(address) is Country country ? await _localizationService.GetLocalizedAsync(country, x => x.Name) : null; model.StateProvinceId = address.StateProvinceId; model.StateProvinceName = await _stateProvinceService.GetStateProvinceByAddressAsync(address) is StateProvince stateProvince ? await _localizationService.GetLocalizedAsync(stateProvince, x => x.Name) : null; model.County = address.County; model.City = address.City; model.Address1 = address.Address1; model.Address2 = address.Address2; model.ZipPostalCode = address.ZipPostalCode; model.PhoneNumber = address.PhoneNumber; model.FaxNumber = address.FaxNumber; } if (address == null && prePopulateWithCustomerFields) { if (customer == null) { throw new Exception("Customer cannot be null when prepopulating an address"); } model.Email = customer.Email; model.FirstName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FirstNameAttribute); model.LastName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.LastNameAttribute); model.Company = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CompanyAttribute); model.Address1 = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.StreetAddressAttribute); model.Address2 = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.StreetAddress2Attribute); model.ZipPostalCode = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute); model.City = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CityAttribute); model.County = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CountyAttribute); model.PhoneNumber = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.PhoneAttribute); model.FaxNumber = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FaxAttribute); } //countries and states if (addressSettings.CountryEnabled && loadCountries != null) { var countries = await loadCountries(); if (_addressSettings.PreselectCountryIfOnlyOne && countries.Count == 1) { model.CountryId = countries[0].Id; } else { model.AvailableCountries.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync("Address.SelectCountry"), Value = "0" }); } foreach (var c in countries) { model.AvailableCountries.Add(new SelectListItem { Text = await _localizationService.GetLocalizedAsync(c, x => x.Name), Value = c.Id.ToString(), Selected = c.Id == model.CountryId }); } if (addressSettings.StateProvinceEnabled) { var languageId = (await _workContext.GetWorkingLanguageAsync()).Id; var states = (await _stateProvinceService .GetStateProvincesByCountryIdAsync(model.CountryId ?? 0, languageId)) .ToList(); if (states.Any()) { model.AvailableStates.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync("Address.SelectState"), Value = "0" }); foreach (var s in states) { model.AvailableStates.Add(new SelectListItem { Text = await _localizationService.GetLocalizedAsync(s, x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId) }); } } else { var anyCountrySelected = model.AvailableCountries.Any(x => x.Selected); model.AvailableStates.Add(new SelectListItem { Text = await _localizationService.GetResourceAsync(anyCountrySelected ? "Address.Other" : "Address.SelectState"), Value = "0" }); } } } //form fields model.CompanyEnabled = addressSettings.CompanyEnabled; model.CompanyRequired = addressSettings.CompanyRequired; model.StreetAddressEnabled = addressSettings.StreetAddressEnabled; model.StreetAddressRequired = addressSettings.StreetAddressRequired; model.StreetAddress2Enabled = addressSettings.StreetAddress2Enabled; model.StreetAddress2Required = addressSettings.StreetAddress2Required; model.ZipPostalCodeEnabled = addressSettings.ZipPostalCodeEnabled; model.ZipPostalCodeRequired = addressSettings.ZipPostalCodeRequired; model.CityEnabled = addressSettings.CityEnabled; model.CityRequired = addressSettings.CityRequired; model.CountyEnabled = addressSettings.CountyEnabled; model.CountyRequired = addressSettings.CountyRequired; model.CountryEnabled = addressSettings.CountryEnabled; model.StateProvinceEnabled = addressSettings.StateProvinceEnabled; model.PhoneEnabled = addressSettings.PhoneEnabled; model.PhoneRequired = addressSettings.PhoneRequired; model.FaxEnabled = addressSettings.FaxEnabled; model.FaxRequired = addressSettings.FaxRequired; //customer attribute services if (_addressAttributeService != null && _addressAttributeParser != null) { await PrepareCustomAddressAttributesAsync(model, address, overrideAttributesXml); } if (_addressAttributeFormatter != null && address != null) { model.FormattedCustomAddressAttributes = await _addressAttributeFormatter.FormatAttributesAsync(address.CustomAttributes); } }
public AddressValidator(ILocalizationService localizationService, IStateProvinceService stateProvinceService, AddressSettings addressSettings, CustomerSettings customerSettings) { RuleFor(x => x.FirstName) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.FirstName.Required")); RuleFor(x => x.LastName) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.LastName.Required")); RuleFor(x => x.Email) .NotEmpty() .WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.Email.Required")); RuleFor(x => x.Email) .EmailAddress() .WithMessageAwait(localizationService.GetResourceAsync("Common.WrongEmail")); if (addressSettings.CountryEnabled) { RuleFor(x => x.CountryId) .NotNull() .WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.Country.Required")); RuleFor(x => x.CountryId) .NotEqual(0) .WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.Country.Required")); } if (addressSettings.CountryEnabled && addressSettings.StateProvinceEnabled) { RuleFor(x => x.StateProvinceId).MustAwait(async(x, context) => { //does selected country has states? var countryId = x.CountryId ?? 0; var hasStates = (await stateProvinceService.GetStateProvincesByCountryIdAsync(countryId)).Any(); if (hasStates) { //if yes, then ensure that state is selected if (!x.StateProvinceId.HasValue || x.StateProvinceId.Value == 0) { return(false); } } return(true); }).WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.StateProvince.Required")); } if (addressSettings.CompanyRequired && addressSettings.CompanyEnabled) { RuleFor(x => x.Company).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Company.Required")); } if (addressSettings.StreetAddressRequired && addressSettings.StreetAddressEnabled) { RuleFor(x => x.Address1).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.StreetAddress.Required")); } if (addressSettings.StreetAddress2Required && addressSettings.StreetAddress2Enabled) { RuleFor(x => x.Address2).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.StreetAddress2.Required")); } if (addressSettings.ZipPostalCodeRequired && addressSettings.ZipPostalCodeEnabled) { RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.ZipPostalCode.Required")); } if (addressSettings.CountyEnabled && addressSettings.CountyRequired) { RuleFor(x => x.County).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Address.Fields.County.Required")); } if (addressSettings.CityRequired && addressSettings.CityEnabled) { RuleFor(x => x.City).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.City.Required")); } if (addressSettings.PhoneRequired && addressSettings.PhoneEnabled) { RuleFor(x => x.PhoneNumber).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Phone.Required")); } if (addressSettings.PhoneEnabled) { RuleFor(x => x.PhoneNumber).IsPhoneNumber(customerSettings).WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Phone.NotValid")); } if (addressSettings.FaxRequired && addressSettings.FaxEnabled) { RuleFor(x => x.FaxNumber).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Account.Fields.Fax.Required")); } }