//address
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Model</param>
        /// <param name="address">Address</param>
        /// <param name="excludeProperties">A value indicating whether to exclude properties</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="localizationService">Localization service (used to prepare a select list)</param>
        /// <param name="stateProvinceService">State service (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="addressAttributeService">Address attribute service. null to don't prepare the list.</param>
        /// <param name="addressAttributeParser">Address attribute parser. null to don't prepare the list.</param>
        /// <param name="addressAttributeFormatter">Address attribute formatter. null to don't prepare the formatted custom attributes.</param>
        /// <param name="loadCountries">A function to load countries  (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="prePopulateWithCustomerFields">A value indicating whether to pre-populate an address with customer fields entered during registration. It's used only when "address" parameter is set to "null"</param>
        /// <param name="customer">Customer record which will be used to pre-populate address. Used only when "prePopulateWithCustomerFields" is "true".</param>
        /// <param name="overrideAttributesXml">When specified we do not use attributes of an address; if null, then already saved ones are used</param>
        public static void PrepareModel(this AddressModel model,
            Address address, bool excludeProperties,
            AddressSettings addressSettings,
            ILocalizationService localizationService = null,
            IStateProvinceService stateProvinceService = null,
            IAddressAttributeService addressAttributeService = null,
            IAddressAttributeParser addressAttributeParser = null,
            IAddressAttributeFormatter addressAttributeFormatter = null,
            Func<IList<Country>> loadCountries = null,
            bool prePopulateWithCustomerFields = false,
            Customer customer = null,
            string overrideAttributesXml = "")
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (addressSettings == null)
                throw new ArgumentNullException("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 = address.Country != null
                    ? address.Country.GetLocalized(x => x.Name)
                    : null;
                model.StateProvinceId = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null
                    ? address.StateProvince.GetLocalized(x => x.Name)
                    : null;
                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 = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName);
                model.LastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName);
                model.Company = customer.GetAttribute<string>(SystemCustomerAttributeNames.Company);
                model.Address1 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress);
                model.Address2 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress2);
                model.ZipPostalCode = customer.GetAttribute<string>(SystemCustomerAttributeNames.ZipPostalCode);
                model.City = customer.GetAttribute<string>(SystemCustomerAttributeNames.City);
                //ignore country and state for prepopulation. it can cause some issues when posting pack with errors, etc
                //model.CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId);
                //model.StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Phone);
                model.FaxNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Fax);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                if (localizationService == null)
                    throw new ArgumentNullException("localizationService");

                model.AvailableCountries.Add(new SelectListItem { Text = localizationService.GetResource("Address.SelectCountry"), Value = "0" });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text = c.GetLocalized(x => x.Name),
                        Value = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    //states
                    if (stateProvinceService == null)
                        throw new ArgumentNullException("stateProvinceService");

                    var languageId = EngineContext.Current.Resolve<IWorkContext>().WorkingLanguage.Id;
                    var states = stateProvinceService
                        .GetStateProvincesByCountryId(model.CountryId.HasValue ? model.CountryId.Value : 0, languageId)
                        .ToList();
                    if (states.Count > 0)
                    {
                        model.AvailableStates.Add(new SelectListItem { Text = localizationService.GetResource("Address.SelectState"), Value = "0" });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text = s.GetLocalized(x => x.Name),
                                Value = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text = localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "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.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)
            {
                PrepareCustomAddressAttributes(model, address, addressAttributeService, addressAttributeParser, overrideAttributesXml);
            }
            if (addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = addressAttributeFormatter.FormatAttributes(address.CustomAttributes);
            }
        }
        protected virtual void PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties,
                                                     bool prepareEntireAddressModel, bool prepareOrderListModel)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (affiliate != null)
            {
                model.Id  = affiliate.Id;
                model.Url = affiliate.GenerateUrl(_webHelper);
                if (!excludeProperties)
                {
                    model.AdminComment    = affiliate.AdminComment;
                    model.FriendlyUrlName = affiliate.FriendlyUrlName;
                    model.Active          = affiliate.Active;
                    model.Address         = affiliate.Address.ToModel();
                }
            }

            if (prepareEntireAddressModel)
            {
                model.Address.FirstNameEnabled      = true;
                model.Address.FirstNameRequired     = true;
                model.Address.LastNameEnabled       = true;
                model.Address.LastNameRequired      = true;
                model.Address.EmailEnabled          = true;
                model.Address.EmailRequired         = true;
                model.Address.CompanyEnabled        = true;
                model.Address.CountryEnabled        = true;
                model.Address.CountryRequired       = true;
                model.Address.StateProvinceEnabled  = true;
                model.Address.CountyEnabled         = true;
                model.Address.CountyRequired        = true;
                model.Address.CityEnabled           = true;
                model.Address.CityRequired          = true;
                model.Address.StreetAddressEnabled  = true;
                model.Address.StreetAddressRequired = true;
                model.Address.StreetAddress2Enabled = true;
                model.Address.ZipPostalCodeEnabled  = true;
                model.Address.ZipPostalCodeRequired = true;
                model.Address.PhoneEnabled          = true;
                model.Address.PhoneRequired         = true;
                model.Address.FaxEnabled            = true;

                //address
                model.Address.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0"
                });
                foreach (var c in _countryService.GetAllCountries(showHidden: true))
                {
                    model.Address.AvailableCountries.Add(new SelectListItem {
                        Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId)
                    });
                }

                var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, showHidden: true).ToList() : new List <StateProvince>();
                if (states.Any())
                {
                    foreach (var s in states)
                    {
                        model.Address.AvailableStates.Add(new SelectListItem {
                            Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId)
                        });
                    }
                }
                else
                {
                    model.Address.AvailableStates.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0"
                    });
                }
            }

            if (!prepareOrderListModel)
            {
                return;
            }

            model.AffiliatedOrderList.AffliateId = model.Id;

            //order statuses
            model.AffiliatedOrderList.AvailableOrderStatuses = OrderStatus.Pending.ToSelectList(false).ToList();
            model.AffiliatedOrderList.AvailableOrderStatuses.Insert(0, new SelectListItem {
                Text = _localizationService.GetResource("Admin.Common.All"), Value = "0"
            });

            //payment statuses
            model.AffiliatedOrderList.AvailablePaymentStatuses = PaymentStatus.Pending.ToSelectList(false).ToList();
            model.AffiliatedOrderList.AvailablePaymentStatuses.Insert(0, new SelectListItem {
                Text = _localizationService.GetResource("Admin.Common.All"), Value = "0"
            });

            //shipping statuses
            model.AffiliatedOrderList.AvailableShippingStatuses = ShippingStatus.NotYetShipped.ToSelectList(false).ToList();
            model.AffiliatedOrderList.AvailableShippingStatuses.Insert(0, new SelectListItem {
                Text = _localizationService.GetResource("Admin.Common.All"), Value = "0"
            });
        }
        /// <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>
        public virtual void PrepareAddressModel(AddressModel model,
                                                Address address, bool excludeProperties,
                                                AddressSettings addressSettings,
                                                Func <IList <Country> > loadCountries = null,
                                                bool prePopulateWithCustomerFields    = false,
                                                Customer customer            = null,
                                                string overrideAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (addressSettings == null)
            {
                throw new ArgumentNullException("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 = address.Country != null
                    ? address.Country.Name //address.Country.GetLocalized(x => x.Name)
                    : null;
                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null
                    ? address.StateProvince.Name //address.StateProvince.GetLocalized(x => x.Name)
                    : null;
                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     = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName, _genericAttributeService);
                model.LastName      = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName, _genericAttributeService);
                model.Company       = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company, _genericAttributeService);
                model.Address1      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress, _genericAttributeService);
                model.Address2      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2, _genericAttributeService);
                model.ZipPostalCode = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode, _genericAttributeService);
                model.City          = customer.GetAttribute <string>(SystemCustomerAttributeNames.City, _genericAttributeService);
                //ignore country and state for prepopulation. it can cause some issues when posting pack with errors, etc
                //model.CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId);
                //model.StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone, _genericAttributeService);
                model.FaxNumber   = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax, _genericAttributeService);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                model.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0"
                });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = c.Name,// c.GetLocalized(x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    var languageId = _baseService.WorkContext.WorkingLanguage.Id;// EngineContext.Current.Resolve<IWorkContext>().WorkingLanguage.Id;
                    var states     = _stateProvinceService
                                     .GetStateProvincesByCountryId(model.CountryId.HasValue ? model.CountryId.Value : 0, languageId)
                                     .ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = s.Name,// s.GetLocalized(x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "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.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)
            {
                PrepareCustomAddressAttributes(model, address, overrideAttributesXml);
            }
            if (_addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = _addressAttributeFormatter.FormatAttributes(address.CustomAttributes);
            }
        }
        protected void PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (affiliate != null)
            {
                model.Id  = affiliate.Id;
                model.Url = _webHelper.ModifyQueryString(_webHelper.GetStoreLocation(false), "affiliateid=" + affiliate.Id, null);
                if (!excludeProperties)
                {
                    model.Active  = affiliate.Active;
                    model.Address = affiliate.Address.ToModel();
                }
            }

            model.Address.FirstNameEnabled      = true;
            model.Address.FirstNameRequired     = true;
            model.Address.LastNameEnabled       = true;
            model.Address.LastNameRequired      = true;
            model.Address.EmailEnabled          = true;
            model.Address.EmailRequired         = true;
            model.Address.CompanyEnabled        = true;
            model.Address.CountryEnabled        = true;
            model.Address.StateProvinceEnabled  = true;
            model.Address.CityEnabled           = true;
            model.Address.CityRequired          = true;
            model.Address.StreetAddressEnabled  = true;
            model.Address.StreetAddressRequired = true;
            model.Address.StreetAddress2Enabled = true;
            model.Address.ZipPostalCodeEnabled  = true;
            model.Address.ZipPostalCodeRequired = true;
            model.Address.PhoneEnabled          = true;
            model.Address.PhoneRequired         = true;
            model.Address.FaxEnabled            = true;

            model.GridPageSize     = _adminAreaSettings.GridPageSize;
            model.UsernamesEnabled = _customerSettings.UsernamesEnabled;

            //address
            //model.Address.AvailableCountries.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" });
            foreach (var c in _countryService.GetAllCountries(true))
            {
                model.Address.AvailableCountries.Add(new SelectListItem()
                {
                    Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId)
                });
            }

            var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, true).ToList() : new List <StateProvince>();

            if (states.Count > 0)
            {
                foreach (var s in states)
                {
                    model.Address.AvailableStates.Add(new SelectListItem()
                    {
                        Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId)
                    });
                }
            }
            else
            {
                model.Address.AvailableStates.Add(new SelectListItem()
                {
                    Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0"
                });
            }
        }
Beispiel #5
0
        //edit
        public ActionResult EditPopup(int id)
        {
            var sbw = _freeShippingByOrderTotalService.GetById(id);

            if (sbw == null)
            {
                //No record found with the specified id
                return(RedirectToAction("Configure"));
            }

            var model = new ShippingFreeOrdersOverModel()
            {
                Id                       = sbw.Id,
                CountryId                = sbw.CountryId,
                StateProvinceId          = sbw.StateProvinceId,
                Zip                      = sbw.Zip,
                OrderOver                = sbw.OrderOver,
                PrimaryStoreCurrencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode
            };

            var shippingMethods = _shippingService.GetAllShippingMethods();

            if (shippingMethods.Count == 0)
            {
                return(Content("No shipping methods can be loaded"));
            }

            var selectedShippingMethod = _shippingService.GetShippingMethodById(sbw.ShippingMethodId);
            var selectedCountry        = _countryService.GetCountryById(sbw.CountryId);
            var selectedState          = _stateProvinceService.GetStateProvinceById(sbw.StateProvinceId);

            //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 = _countryService.GetAllCountries(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?_stateProvinceService.GetStateProvincesByCountryId(selectedCountry.Id, 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("CLF.Plugin.Shipping.FreeShipping.Views.FreeShipping.EditPopup", model));
        }
Beispiel #6
0
        public virtual void PrepareAddressModel(AddressModel model,
                                                Address address, bool excludeProperties,
                                                Func <IList <Country> > loadCountries = null,
                                                bool prePopulateWithCustomerFields    = false,
                                                Customer customer = null,
                                                AddressSettings addressSettings = null)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            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.VatNumber = address.VatNumber;
                model.CountryId = address.CountryId;
                Country country = null;
                if (!String.IsNullOrEmpty(address.CountryId))
                {
                    country = _countryService.GetCountryById(address.CountryId);
                }
                model.CountryName = country != null?country.GetLocalized(x => x.Name) : null;

                model.StateProvinceId = address.StateProvinceId;
                StateProvince state = null;
                if (!String.IsNullOrEmpty(address.StateProvinceId))
                {
                    state = _stateProvinceService.GetStateProvinceById(address.StateProvinceId);
                }
                model.StateProvinceName = state != null?state.GetLocalized(x => x.Name) : null;

                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       = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName);
                model.LastName        = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName);
                model.Company         = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company);
                model.VatNumber       = customer.GetAttribute <string>(SystemCustomerAttributeNames.VatNumber);
                model.Address1        = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress);
                model.Address2        = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2);
                model.ZipPostalCode   = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode);
                model.City            = customer.GetAttribute <string>(SystemCustomerAttributeNames.City);
                model.CountryId       = customer.GetAttribute <string>(SystemCustomerAttributeNames.CountryId);
                model.StateProvinceId = customer.GetAttribute <string>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber     = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone);
                model.FaxNumber       = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                model.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Address.SelectCountry"), Value = ""
                });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = c.GetLocalized(x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    var languageId = _workContext.WorkingLanguage.Id;
                    var states     = _stateProvinceService
                                     .GetStateProvincesByCountryId(!String.IsNullOrEmpty(model.CountryId) ? model.CountryId : "", languageId)
                                     .ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = ""
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = s.GetLocalized(x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = ""
                        });
                    }
                }
            }

            //form fields
            model.CompanyEnabled         = addressSettings.CompanyEnabled;
            model.CompanyRequired        = addressSettings.CompanyRequired;
            model.VatNumberEnabled       = addressSettings.VatNumberEnabled;
            model.VatNumberRequired      = addressSettings.VatNumberRequired;
            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.CountryEnabled         = addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled           = addressSettings.PhoneEnabled;
            model.PhoneRequired          = addressSettings.PhoneRequired;
            model.FaxEnabled             = addressSettings.FaxEnabled;
            model.FaxRequired            = addressSettings.FaxRequired;
        }
        public IActionResult Create()
        {
            if (!_permissionService.Authorize(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 = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0"
            });
            foreach (var country in _countryService.GetAllCountries(showHidden: true))
            {
                model.Address.AvailableCountries.Add(new SelectListItem {
                    Text = country.Name, Value = country.Id.ToString()
                });
            }

            var states = !model.Address.CountryId.HasValue ? new List <StateProvince>()
                : _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, showHidden: true);

            if (states.Any())
            {
                model.Address.AvailableStates.Add(new SelectListItem {
                    Text = _localizationService.GetResource("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 = _localizationService.GetResource("Admin.Address.Other"), Value = "0"
                });
            }

            model.AvailableStores.Add(new SelectListItem {
                Text = _localizationService.GetResource("Admin.Configuration.Settings.StoreScope.AllStores"), Value = "0"
            });
            foreach (var store in _storeService.GetAllStores())
            {
                model.AvailableStores.Add(new SelectListItem {
                    Text = store.Name, Value = store.Id.ToString()
                });
            }

            return(View("~/Plugins/Pickup.PickupInStore/Views/Create.cshtml", model));
        }
        /// <summary>
        /// Prepare the customer info model
        /// </summary>
        /// <param name="model">Customer info model</param>
        /// <param name="customer">Customer</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <param name="overrideCustomCustomerAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param>
        /// <returns>Customer info model</returns>
        public virtual CustomerInfoModel PrepareCustomerInfoModel(CustomerInfoModel model, Customer customer,
                                                                  bool excludeProperties, string overrideCustomCustomerAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
            foreach (var tzi in _dateTimeHelper.GetSystemTimeZones())
            {
                model.AvailableTimeZones.Add(new SelectListItem {
                    Text = tzi.DisplayName, Value = tzi.Id, Selected = (excludeProperties ? tzi.Id == model.TimeZoneId : tzi.Id == _dateTimeHelper.CurrentTimeZone.Id)
                });
            }

            if (!excludeProperties)
            {
                model.VatNumber = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.VatNumberAttribute);
                model.FirstName = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
                model.LastName  = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);
                model.Gender    = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.GenderAttribute);
                var dateOfBirth = _genericAttributeService.GetAttribute <DateTime?>(customer, NopCustomerDefaults.DateOfBirthAttribute);
                if (dateOfBirth.HasValue)
                {
                    model.DateOfBirthDay   = dateOfBirth.Value.Day;
                    model.DateOfBirthMonth = dateOfBirth.Value.Month;
                    model.DateOfBirthYear  = dateOfBirth.Value.Year;
                }
                model.Company         = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CompanyAttribute);
                model.StreetAddress   = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddressAttribute);
                model.StreetAddress2  = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.StreetAddress2Attribute);
                model.ZipPostalCode   = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute);
                model.City            = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CityAttribute);
                model.County          = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.CountyAttribute);
                model.CountryId       = _genericAttributeService.GetAttribute <int>(customer, NopCustomerDefaults.CountryIdAttribute);
                model.StateProvinceId = _genericAttributeService.GetAttribute <int>(customer, NopCustomerDefaults.StateProvinceIdAttribute);
                model.Phone           = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.PhoneAttribute);
                model.Fax             = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FaxAttribute);

                //newsletter
                var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id);
                model.Newsletter = newsletter != null && newsletter.Active;

                model.Signature = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.SignatureAttribute);

                model.Email    = customer.Email;
                model.Username = customer.Username;
            }
            else
            {
                if (_customerSettings.UsernamesEnabled && !_customerSettings.AllowUsersToChangeUsernames)
                {
                    model.Username = customer.Username;
                }
            }

            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                model.EmailToRevalidate = customer.EmailToRevalidate;
            }

            //countries and states
            if (_customerSettings.CountryEnabled)
            {
                model.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0"
                });
                foreach (var c in _countryService.GetAllCountries(_workContext.WorkingLanguage.Id))
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = _localizationService.GetLocalized(c, x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (_customerSettings.StateProvinceEnabled)
                {
                    //states
                    var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, _workContext.WorkingLanguage.Id).ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem {
                                Text = _localizationService.GetLocalized(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  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                }
            }

            model.DisplayVatNumber    = _taxSettings.EuVatEnabled;
            model.VatNumberStatusNote = _localizationService.GetLocalizedEnum((VatNumberStatus)_genericAttributeService
                                                                              .GetAttribute <int>(customer, NopCustomerDefaults.VatNumberStatusIdAttribute));
            model.GenderEnabled                    = _customerSettings.GenderEnabled;
            model.DateOfBirthEnabled               = _customerSettings.DateOfBirthEnabled;
            model.DateOfBirthRequired              = _customerSettings.DateOfBirthRequired;
            model.CompanyEnabled                   = _customerSettings.CompanyEnabled;
            model.CompanyRequired                  = _customerSettings.CompanyRequired;
            model.StreetAddressEnabled             = _customerSettings.StreetAddressEnabled;
            model.StreetAddressRequired            = _customerSettings.StreetAddressRequired;
            model.StreetAddress2Enabled            = _customerSettings.StreetAddress2Enabled;
            model.StreetAddress2Required           = _customerSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled             = _customerSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired            = _customerSettings.ZipPostalCodeRequired;
            model.CityEnabled                      = _customerSettings.CityEnabled;
            model.CityRequired                     = _customerSettings.CityRequired;
            model.CountyEnabled                    = _customerSettings.CountyEnabled;
            model.CountyRequired                   = _customerSettings.CountyRequired;
            model.CountryEnabled                   = _customerSettings.CountryEnabled;
            model.CountryRequired                  = _customerSettings.CountryRequired;
            model.StateProvinceEnabled             = _customerSettings.StateProvinceEnabled;
            model.StateProvinceRequired            = _customerSettings.StateProvinceRequired;
            model.PhoneEnabled                     = _customerSettings.PhoneEnabled;
            model.PhoneRequired                    = _customerSettings.PhoneRequired;
            model.FaxEnabled                       = _customerSettings.FaxEnabled;
            model.FaxRequired                      = _customerSettings.FaxRequired;
            model.NewsletterEnabled                = _customerSettings.NewsletterEnabled;
            model.UsernamesEnabled                 = _customerSettings.UsernamesEnabled;
            model.AllowUsersToChangeUsernames      = _customerSettings.AllowUsersToChangeUsernames;
            model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled;
            model.SignatureEnabled                 = _forumSettings.ForumsEnabled && _forumSettings.SignaturesEnabled;

            //external authentication
            model.AllowCustomersToRemoveAssociations      = _externalAuthenticationSettings.AllowCustomersToRemoveAssociations;
            model.NumberOfExternalAuthenticationProviders = _authenticationPluginManager
                                                            .LoadActivePlugins(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id)
                                                            .Count;
            foreach (var record in customer.ExternalAuthenticationRecords)
            {
                var authMethod = _authenticationPluginManager.LoadPluginBySystemName(record.ProviderSystemName);
                if (!_authenticationPluginManager.IsPluginActive(authMethod))
                {
                    continue;
                }

                model.AssociatedExternalAuthRecords.Add(new CustomerInfoModel.AssociatedExternalAuthModel
                {
                    Id    = record.Id,
                    Email = record.Email,
                    ExternalIdentifier = !string.IsNullOrEmpty(record.ExternalDisplayIdentifier)
                        ? record.ExternalDisplayIdentifier : record.ExternalIdentifier,
                    AuthMethodName = _localizationService.GetLocalizedFriendlyName(authMethod, _workContext.WorkingLanguage.Id)
                });
            }

            //custom customer attributes
            var customAttributes = PrepareCustomCustomerAttributes(customer, overrideCustomCustomerAttributesXml);

            foreach (var attribute in customAttributes)
            {
                model.CustomerAttributes.Add(attribute);
            }

            //GDPR
            if (_gdprSettings.GdprEnabled)
            {
                var consents = _gdprService.GetAllConsents().Where(consent => consent.DisplayOnCustomerInfoPage).ToList();
                foreach (var consent in consents)
                {
                    var accepted = _gdprService.IsConsentAccepted(consent.Id, _workContext.CurrentCustomer.Id);
                    model.GdprConsents.Add(PrepareGdprConsentModel(consent, accepted.HasValue && accepted.Value));
                }
            }

            return(model);
        }
        public CustomerInfoValidator(ILocalizationService localizationService,
                                     IStateProvinceService stateProvinceService,
                                     CustomerSettings customerSettings)
        {
            RuleFor(x => x.Email).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Email.Required"));
            RuleFor(x => x.Email).EmailAddress().WithMessage(localizationService.GetResource("Common.WrongEmail"));
            RuleFor(x => x.FirstName).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.FirstName.Required"));
            RuleFor(x => x.LastName).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.LastName.Required"));

            if (customerSettings.UsernamesEnabled && customerSettings.AllowUsersToChangeUsernames)
            {
                //RuleFor(x => x.Username).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Username.Required"));
            }

            //form fields
            if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
            {
                RuleFor(x => x.CountryId)
                .NotEqual(0)
                .WithMessage(localizationService.GetResource("Account.Fields.Country.Required"));
            }
            if (customerSettings.CountryEnabled &&
                customerSettings.StateProvinceEnabled &&
                customerSettings.StateProvinceRequired)
            {
                RuleFor(x => x.StateProvinceId).Must((x, context) =>
                {
                    //does selected country have states?
                    var hasStates = stateProvinceService.GetStateProvincesByCountryId(x.CountryId).Any();
                    if (hasStates)
                    {
                        //if yes, then ensure that a state is selected
                        if (x.StateProvinceId == 0)
                        {
                            return(false);
                        }
                    }

                    return(true);
                }).WithMessage(localizationService.GetResource("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);
                }).WithMessage(localizationService.GetResource("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);
                }).WithMessage(string.Format(localizationService.GetResource("Account.Fields.DateOfBirth.MinimumAge"), customerSettings.DateOfBirthMinimumAge));
            }
            if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)
            {
                RuleFor(x => x.Company).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Company.Required"));
            }
            if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
            {
                RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress.Required"));
            }
            if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)
            {
                RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress2.Required"));
            }
            if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)
            {
                RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ZipPostalCode.Required"));
            }
            if (customerSettings.CityRequired && customerSettings.CityEnabled)
            {
                RuleFor(x => x.City).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.City.Required"));
            }
            if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)
            {
                RuleFor(x => x.Phone).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Phone.Required"));
            }
            if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
            {
                RuleFor(x => x.Fax).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Fax.Required"));
            }
        }
        /// <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 bool IsAddressValid(Address address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            if (String.IsNullOrWhiteSpace(address.FirstName))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(address.LastName))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(address.PhoneNumber))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(address.Email))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(address.Address1))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(address.City))
            {
                return(false);
            }

            if (String.IsNullOrWhiteSpace(address.ZipPostalCode))
            {
                return(false);
            }

            if (address.CountryId == null || address.CountryId.Value == 0)
            {
                return(false);
            }

            var country = _countryService.GetCountryById(address.CountryId.Value);

            if (country == null)
            {
                return(false);
            }

            var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id);

            if (states.Count > 0)
            {
                if (address.StateProvinceId == null || address.StateProvinceId.Value == 0)
                {
                    return(false);
                }

                var state = _stateProvinceService.GetStateProvinceById(address.StateProvinceId.Value);
                if (state == null)
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Model</param>
        /// <param name="address">Address</param>
        /// <param name="excludeProperties">A value indicating whether to exclude properties</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="localizationService">Localization service (used to prepare a select list)</param>
        /// <param name="stateProvinceService">State service (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="loadCountries">A function to load countries  (used to prepare a select list). null to don't prepare the list.</param>
        public static void PrepareModel(this AddressModel model,
                                        Address address, bool excludeProperties,
                                        AddressSettings addressSettings,
                                        ILocalizationService localizationService   = null,
                                        IStateProvinceService stateProvinceService = null,
                                        Func <IList <Country> > loadCountries      = null)
        {
            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 = address.Country != null
                    ? localizationService?.GetLocalized(address.Country, x => x.Name)
                    : null;

                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null
                    ? localizationService?.GetLocalized(address.StateProvince, x => x.Name)
                    : null;

                model.City          = address.City;
                model.Address1      = address.Address1;
                model.Address2      = address.Address2;
                model.ZipPostalCode = address.ZipPostalCode;
                model.PhoneNumber   = address.PhoneNumber;
                model.FaxNumber     = address.FaxNumber;
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                if (localizationService == null)
                {
                    throw new ArgumentNullException(nameof(localizationService));
                }

                model.AvailableCountries.Add(new SelectListItem
                {
                    Text  = localizationService.GetResource("Address.SelectCountry"),
                    Value = "0"
                });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = localizationService.GetLocalized(c, x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    //states
                    if (stateProvinceService == null)
                    {
                        throw new ArgumentNullException(nameof(stateProvinceService));
                    }

                    var states = stateProvinceService
                                 .GetStateProvincesByCountryId(model.CountryId ?? 0)
                                 .ToList();
                    if (states.Count > 0)
                    {
                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = localizationService.GetLocalized(s, x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = s.Id == model.StateProvinceId
                            });
                        }
                    }
                    else
                    {
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = localizationService.GetResource("Address.OtherNonUS"),
                            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.CountryEnabled         = addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled           = addressSettings.PhoneEnabled;
            model.PhoneRequired          = addressSettings.PhoneRequired;
            model.FaxEnabled             = addressSettings.FaxEnabled;
            model.FaxRequired            = addressSettings.FaxRequired;
        }
Beispiel #12
0
        public CustomerValidator(
            IEnumerable <IValidatorConsumer <CustomerDto> > validators,
            ILocalizationService localizationService, IStateProvinceService stateProvinceService,
            ICustomerService customerService, IStoreService storeService, CustomerSettings customerSettings)
            : base(validators)
        {
            RuleFor(x => x).MustAsync(async(x, context) =>
            {
                var customer = await customerService.GetCustomerByEmail(x.Email);
                if (customer != null && customer.Id != x.Id)
                {
                    return(false);
                }
                return(true);
            }).WithMessage(localizationService.GetResource("Api.Customers.Customer.Fields.Email.Registered"));

            RuleFor(x => x).MustAsync(async(x, context) =>
            {
                var username = await customerService.GetCustomerByUsername(x.Username);
                if (username != null && username.Id != x.Id && customerSettings.UsernamesEnabled)
                {
                    return(false);
                }
                return(true);
            }).WithMessage(localizationService.GetResource("Api.Customers.Customer.Fields.Username.Registered"));

            RuleFor(x => x).MustAsync(async(x, context) =>
            {
                var customer = await customerService.GetCustomerByGuid(x.CustomerGuid);
                if (customer != null && customer.Id != x.Id)
                {
                    return(false);
                }
                return(true);
            }).WithMessage(localizationService.GetResource("Api.Customers.Customer.Fields.Guid.Exists"));

            RuleFor(x => x).MustAsync(async(x, context) =>
            {
                var store = await storeService.GetStoreById(x.StoreId);
                if (store != null)
                {
                    return(true);
                }
                return(false);
            }).WithMessage(localizationService.GetResource("Api.Customers.Customer.Fields.StoreId.NotExists"));


            //form fields
            if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
            {
                RuleFor(x => x.CountryId)
                .NotEqual("")
                .WithMessage(localizationService.GetResource("Api.Customers.Customer.Fields.Country.Required"));
            }
            if (customerSettings.CountryEnabled &&
                customerSettings.StateProvinceEnabled &&
                customerSettings.StateProvinceRequired)
            {
                RuleFor(x => x.StateProvinceId).MustAsync(async(x, y, context) =>
                {
                    //does selected country has states?
                    var countryId = !string.IsNullOrEmpty(x.CountryId) ? x.CountryId : "";
                    var hasStates = (await stateProvinceService.GetStateProvincesByCountryId(countryId)).Count > 0;
                    if (hasStates)
                    {
                        //if yes, then ensure that state is selected
                        if (string.IsNullOrEmpty(y))
                        {
                            return(false);
                        }
                    }
                    return(true);
                }).WithMessage(localizationService.GetResource("pi.Customers.Customer.Fields.StateProvince.Required"));
            }
            if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)
            {
                RuleFor(x => x.Company).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Company.Required"));
            }
            if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
            {
                RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.StreetAddress.Required"));
            }
            if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)
            {
                RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.StreetAddress2.Required"));
            }
            if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)
            {
                RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.ZipPostalCode.Required"));
            }
            if (customerSettings.CityRequired && customerSettings.CityEnabled)
            {
                RuleFor(x => x.City).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.City.Required"));
            }
            if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)
            {
                RuleFor(x => x.Phone).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Phone.Required"));
            }
            if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
            {
                RuleFor(x => x.Fax).NotEmpty().WithMessage(localizationService.GetResource("Api.Customers.Customer.Customers.Customers.Fields.Fax.Required"));
            }
        }
Beispiel #13
0
        /// <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 IList <StateProvinceModel> GetStatesByCountryId(string countryId, bool addSelectStateItem)
        {
            if (string.IsNullOrEmpty(countryId))
            {
                throw new ArgumentNullException(nameof(countryId));
            }

            var cacheKey    = string.Format(NopModelCacheDefaults.StateProvincesByCountryModelKey, countryId, addSelectStateItem, _workContext.WorkingLanguage.Id);
            var cachedModel = _cacheManager.Get(cacheKey, () =>
            {
                var country = _countryService.GetCountryById(Convert.ToInt32(countryId));
                var states  = _stateProvinceService.GetStateProvincesByCountryId(country != null ? country.Id : 0, _workContext.WorkingLanguage.Id).ToList();
                var result  = new List <StateProvinceModel>();
                foreach (var state in states)
                {
                    result.Add(new StateProvinceModel
                    {
                        id   = state.Id,
                        name = _localizationService.GetLocalized(state, x => x.Name)
                    });
                }

                if (country == null)
                {
                    //country is not selected ("choose country" item)
                    if (addSelectStateItem)
                    {
                        result.Insert(0, new StateProvinceModel
                        {
                            id   = 0,
                            name = _localizationService.GetResource("Address.SelectState")
                        });
                    }
                    else
                    {
                        result.Insert(0, new StateProvinceModel
                        {
                            id   = 0,
                            name = _localizationService.GetResource("Address.OtherNonUS")
                        });
                    }
                }
                else
                {
                    //some country is selected
                    if (!result.Any())
                    {
                        //country does not have states
                        result.Insert(0, new StateProvinceModel
                        {
                            id   = 0,
                            name = _localizationService.GetResource("Address.OtherNonUS")
                        });
                    }
                    else
                    {
                        //country has some states
                        if (addSelectStateItem)
                        {
                            result.Insert(0, new StateProvinceModel
                            {
                                id   = 0,
                                name = _localizationService.GetResource("Address.SelectState")
                            });
                        }
                    }
                }

                return(result);
            });

            return(cachedModel);
        }
Beispiel #14
0
        public RegisterValidator(ILocalizationService localizationService,
                                 IStateProvinceService stateProvinceService,
                                 CustomerSettings customerSettings)
        {
            RuleFor(x => x.Email).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Email.Required"));
            RuleFor(x => x.Email).EmailAddress().WithMessage(localizationService.GetResource("Common.WrongEmail"));

            if (customerSettings.EnteringEmailTwice)
            {
                RuleFor(x => x.ConfirmEmail).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ConfirmEmail.Required"));
                RuleFor(x => x.ConfirmEmail).EmailAddress().WithMessage(localizationService.GetResource("Common.WrongEmail"));
                RuleFor(x => x.ConfirmEmail).Equal(x => x.Email).WithMessage(localizationService.GetResource("Account.Fields.Email.EnteredEmailsDoNotMatch"));
            }

            if (customerSettings.UsernamesEnabled)
            {
                RuleFor(x => x.Username).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Username.Required"));
            }

            RuleFor(x => x.FirstName).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.FirstName.Required"));
            RuleFor(x => x.LastName).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.LastName.Required"));


            RuleFor(x => x.Password).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Password.Required"));
            RuleFor(x => x.Password).Length(customerSettings.PasswordMinLength, 999).WithMessage(string.Format(localizationService.GetResource("Account.Fields.Password.LengthValidation"), customerSettings.PasswordMinLength));
            RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ConfirmPassword.Required"));
            RuleFor(x => x.ConfirmPassword).Equal(x => x.Password).WithMessage(localizationService.GetResource("Account.Fields.Password.EnteredPasswordsDoNotMatch"));

            //form fields
            if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
            {
                RuleFor(x => x.CountryId)
                .NotEqual(0)
                .WithMessage(localizationService.GetResource("Account.Fields.Country.Required"));
            }
            if (customerSettings.CountryEnabled &&
                customerSettings.StateProvinceEnabled &&
                customerSettings.StateProvinceRequired)
            {
                Custom(x =>
                {
                    //does selected country have states?
                    var hasStates = stateProvinceService.GetStateProvincesByCountryId(x.CountryId).Any();
                    if (hasStates)
                    {
                        //if yes, then ensure that a state is selected
                        if (x.StateProvinceId == 0)
                        {
                            return(new ValidationFailure("StateProvinceId", localizationService.GetResource("Account.Fields.StateProvince.Required")));
                        }
                    }
                    return(null);
                });
            }
            if (customerSettings.DateOfBirthEnabled && customerSettings.DateOfBirthRequired)
            {
                Custom(x =>
                {
                    var dateOfBirth = x.ParseDateOfBirth();
                    //entered?
                    if (!dateOfBirth.HasValue)
                    {
                        return(new ValidationFailure("DateOfBirthDay", localizationService.GetResource("Account.Fields.DateOfBirth.Required")));
                    }
                    //minimum age
                    if (customerSettings.DateOfBirthMinimumAge.HasValue &&
                        CommonHelper.GetDifferenceInYears(dateOfBirth.Value, DateTime.Today) < customerSettings.DateOfBirthMinimumAge.Value)
                    {
                        return(new ValidationFailure("DateOfBirthDay", string.Format(localizationService.GetResource("Account.Fields.DateOfBirth.MinimumAge"), customerSettings.DateOfBirthMinimumAge.Value)));
                    }
                    return(null);
                });
            }
            if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)
            {
                RuleFor(x => x.Company).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Company.Required"));
            }
            if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
            {
                RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress.Required"));
            }
            if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)
            {
                RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress2.Required"));
            }
            if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)
            {
                RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ZipPostalCode.Required"));
            }
            if (customerSettings.CityRequired && customerSettings.CityEnabled)
            {
                RuleFor(x => x.City).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.City.Required"));
            }
            if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)
            {
                RuleFor(x => x.Phone).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Phone.Required"));
            }
            if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
            {
                RuleFor(x => x.Fax).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Fax.Required"));
            }
        }
Beispiel #15
0
        //edit
        public async Task <IActionResult> EditPopup(string id)
        {
            var sbw = await _shippingByWeightService.GetById(id);

            if (sbw == null)
            {
                //No record found with the specified id
                return(RedirectToAction("Configure"));
            }

            var model = new ShippingByWeightModel {
                Id                       = sbw.Id,
                StoreId                  = sbw.StoreId,
                WarehouseId              = sbw.WarehouseId,
                CountryId                = sbw.CountryId,
                StateProvinceId          = sbw.StateProvinceId,
                Zip                      = sbw.Zip,
                ShippingMethodId         = sbw.ShippingMethodId,
                From                     = sbw.From,
                To                       = sbw.To,
                AdditionalFixedCost      = sbw.AdditionalFixedCost,
                PercentageRateOfSubtotal = sbw.PercentageRateOfSubtotal,
                RatePerWeightUnit        = sbw.RatePerWeightUnit,
                LowerWeightLimit         = sbw.LowerWeightLimit,
                PrimaryStoreCurrencyCode = (await _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)).CurrencyCode,
                BaseWeightIn             = (await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId)).Name
            };

            var shippingMethods = await _shippingService.GetAllShippingMethods();

            if (shippingMethods.Count == 0)
            {
                return(Content("No shipping methods can be loaded"));
            }

            var selectedStore = await _storeService.GetStoreById(sbw.StoreId);

            var selectedWarehouse = await _shippingService.GetWarehouseById(sbw.WarehouseId);

            var selectedShippingMethod = await _shippingService.GetShippingMethodById(sbw.ShippingMethodId);

            var selectedCountry = await _countryService.GetCountryById(sbw.CountryId);

            var selectedState = await _stateProvinceService.GetStateProvinceById(sbw.StateProvinceId);

            //stores
            model.AvailableStores.Add(new SelectListItem {
                Text = "*", Value = ""
            });
            foreach (var store in await _storeService.GetAllStores())
            {
                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 = ""
            });
            foreach (var warehouse in await _shippingService.GetAllWarehouses())
            {
                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 = ""
            });
            var countries = await _countryService.GetAllCountries(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.GetStateProvincesByCountryId(selectedCountry.Id, showHidden : true) : new List <StateProvince>();

            model.AvailableStates.Add(new SelectListItem {
                Text = "*", Value = ""
            });
            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.ByWeight/Views/EditPopup.cshtml", model));
        }
Beispiel #16
0
        public async Task <RegisterModel> Handle(GetRegister request, CancellationToken cancellationToken)
        {
            var model = new RegisterModel();

            if (request.Model != null)
            {
                model = request.Model;
            }
            else
            {
                //enable newsletter by default
                model.Newsletter = _customerSettings.NewsletterTickedByDefault;
            }

            model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
            if (model.AllowCustomersToSetTimeZone)
            {
                foreach (var tzi in _dateTimeHelper.GetSystemTimeZones())
                {
                    model.AvailableTimeZones.Add(new SelectListItem {
                        Text = tzi.DisplayName, Value = tzi.Id, Selected = (request.ExcludeProperties ? tzi.Id == model.TimeZoneId : tzi.Id == _dateTimeHelper.CurrentTimeZone.Id)
                    });
                }
            }

            model.DisplayVatNumber = _taxSettings.EuVatEnabled;
            //form fields
            model.GenderEnabled                    = _customerSettings.GenderEnabled;
            model.DateOfBirthEnabled               = _customerSettings.DateOfBirthEnabled;
            model.DateOfBirthRequired              = _customerSettings.DateOfBirthRequired;
            model.CompanyEnabled                   = _customerSettings.CompanyEnabled;
            model.CompanyRequired                  = _customerSettings.CompanyRequired;
            model.StreetAddressEnabled             = _customerSettings.StreetAddressEnabled;
            model.StreetAddressRequired            = _customerSettings.StreetAddressRequired;
            model.StreetAddress2Enabled            = _customerSettings.StreetAddress2Enabled;
            model.StreetAddress2Required           = _customerSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled             = _customerSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired            = _customerSettings.ZipPostalCodeRequired;
            model.CityEnabled                      = _customerSettings.CityEnabled;
            model.CityRequired                     = _customerSettings.CityRequired;
            model.CountryEnabled                   = _customerSettings.CountryEnabled;
            model.CountryRequired                  = _customerSettings.CountryRequired;
            model.StateProvinceEnabled             = _customerSettings.StateProvinceEnabled;
            model.StateProvinceRequired            = _customerSettings.StateProvinceRequired;
            model.PhoneEnabled                     = _customerSettings.PhoneEnabled;
            model.PhoneRequired                    = _customerSettings.PhoneRequired;
            model.FaxEnabled                       = _customerSettings.FaxEnabled;
            model.FaxRequired                      = _customerSettings.FaxRequired;
            model.NewsletterEnabled                = _customerSettings.NewsletterEnabled;
            model.AcceptPrivacyPolicyEnabled       = _customerSettings.AcceptPrivacyPolicyEnabled;
            model.UsernamesEnabled                 = _customerSettings.UsernamesEnabled;
            model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled;
            model.HoneypotEnabled                  = _securitySettings.HoneypotEnabled;
            model.DisplayCaptcha                   = _captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage;

            //countries and states
            if (_customerSettings.CountryEnabled)
            {
                model.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Address.SelectCountry"), Value = ""
                });

                foreach (var c in await _countryService.GetAllCountries(request.Language.Id))
                {
                    model.AvailableCountries.Add(new SelectListItem {
                        Text     = c.GetLocalized(x => x.Name, request.Language.Id),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (_customerSettings.StateProvinceEnabled)
                {
                    //states
                    var states = await _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, request.Language.Id);

                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = ""
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem {
                                Text = s.GetLocalized(x => x.Name, request.Language.Id), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);

                        model.AvailableStates.Add(new SelectListItem {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = ""
                        });
                    }
                }
            }

            //custom customer attributes
            var customAttributes = await _mediator.Send(new GetCustomAttributes()
            {
                Customer = request.Customer,
                Language = request.Language,
                OverrideAttributesXml = request.OverrideCustomCustomerAttributesXml
            });

            foreach (var item in customAttributes)
            {
                model.CustomerAttributes.Add(item);
            }

            //newsletter categories
            var newsletterCategories = await _newsletterCategoryService.GetNewsletterCategoriesByStore(request.Store.Id);

            foreach (var item in newsletterCategories)
            {
                model.NewsletterCategories.Add(new NewsletterSimpleCategory()
                {
                    Id          = item.Id,
                    Name        = item.GetLocalized(x => x.Name, request.Language.Id),
                    Description = item.GetLocalized(x => x.Description, request.Language.Id),
                    Selected    = item.Selected
                });
            }
            return(model);
        }
        public async Task <EstimateShippingModel> Handle(GetEstimateShipping request, CancellationToken cancellationToken)
        {
            var model = new EstimateShippingModel();

            model.Enabled = request.Cart.Any() && request.Cart.RequiresShipping() && _shippingSettings.EstimateShippingEnabled;
            if (model.Enabled)
            {
                //countries
                var defaultEstimateCountryId = (request.SetEstimateShippingDefaultAddress && request.Customer.ShippingAddress != null) ? request.Customer.ShippingAddress.CountryId : model.CountryId;
                if (string.IsNullOrEmpty(defaultEstimateCountryId))
                {
                    defaultEstimateCountryId = request.Store.DefaultCountryId;
                }

                model.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Address.SelectCountry"), Value = ""
                });
                foreach (var c in await _countryService.GetAllCountriesForShipping(request.Language.Id))
                {
                    model.AvailableCountries.Add(new SelectListItem {
                        Text     = c.GetLocalized(x => x.Name, request.Language.Id),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == defaultEstimateCountryId
                    });
                }
                //states
                string defaultEstimateStateId = (request.SetEstimateShippingDefaultAddress && request.Customer.ShippingAddress != null) ? request.Customer.ShippingAddress.StateProvinceId : model.StateProvinceId;
                var    states = !String.IsNullOrEmpty(defaultEstimateCountryId) ? await _stateProvinceService.GetStateProvincesByCountryId(defaultEstimateCountryId, request.Language.Id) : new List <StateProvince>();

                if (states.Any())
                {
                    foreach (var s in states)
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text     = s.GetLocalized(x => x.Name, request.Language.Id),
                            Value    = s.Id.ToString(),
                            Selected = s.Id == defaultEstimateStateId
                        });
                    }
                }
                else
                {
                    model.AvailableStates.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Address.OtherNonUS"), Value = ""
                    });
                }

                if (request.SetEstimateShippingDefaultAddress && request.Customer.ShippingAddress != null)
                {
                    model.ZipPostalCode = request.Customer.ShippingAddress.ZipPostalCode;
                }
            }
            return(model);
        }
Beispiel #18
0
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Model</param>
        /// <param name="address">Address</param>
        /// <param name="excludeProperties">A value indicating whether to exclude properties</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="localizationService">Localization service (used to prepare a select list)</param>
        /// <param name="stateProvinceService">State service (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="loadCountries">A function to load countries  (used to prepare a select list). null to don't prepare the list.</param>
        public static void PrepareModel(this AddressModel model,
                                        Address address,
                                        bool excludeProperties,
                                        AddressSettings addressSettings,
                                        ILocalizationService localizationService   = null,
                                        IStateProvinceService stateProvinceService = null,
                                        Func <IList <Country> > loadCountries      = null)
        {
            Guard.NotNull(model, nameof(model));
            Guard.NotNull(addressSettings, nameof(addressSettings));

            // Form fields
            MiniMapper.Map(addressSettings, model);

            if (!excludeProperties && address != null)
            {
                MiniMapper.Map(address, model);

                model.EmailMatch  = address.Email;
                model.CountryName = address.Country?.GetLocalized(x => x.Name);
                if (address.StateProvinceId.HasValue && address.StateProvince != null)
                {
                    model.StateProvinceName = address.StateProvince.GetLocalized(x => x.Name);
                }
                model.FormattedAddress = Core.Infrastructure.EngineContext.Current.Resolve <IAddressService>().FormatAddress(address, true);
            }

            // Countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                if (localizationService == null)
                {
                    throw new ArgumentNullException("localizationService");
                }

                model.AvailableCountries.Add(new SelectListItem {
                    Text = localizationService.GetResource("Address.SelectCountry"), Value = "0"
                });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = c.GetLocalized(x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    // States
                    if (stateProvinceService == null)
                    {
                        throw new ArgumentNullException("stateProvinceService");
                    }

                    var states = stateProvinceService
                                 .GetStateProvincesByCountryId(model.CountryId ?? 0)
                                 .ToList();
                    if (states.Count > 0)
                    {
                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = s.GetLocalized(x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = localizationService.GetResource("Address.OtherNonUS"),
                            Value = "0"
                        });
                    }
                }
            }

            if (localizationService != null)
            {
                string salutations = addressSettings.GetLocalized(x => x.Salutations);
                foreach (var sal in salutations.SplitSafe(","))
                {
                    model.AvailableSalutations.Add(new SelectListItem {
                        Value = sal, Text = sal
                    });
                }
            }
        }
Beispiel #19
0
        //address
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Model</param>
        /// <param name="address">Address</param>
        /// <param name="excludeProperties">A value indicating whether to exclude properties</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="localizationService">Localization service (used to prepare a select list)</param>
        /// <param name="stateProvinceService">State service (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="addressAttributeService">Address attribute service. null to don't prepare the list.</param>
        /// <param name="addressAttributeParser">Address attribute parser. null to don't prepare the list.</param>
        /// <param name="addressAttributeFormatter">Address attribute formatter. null to don't prepare the formatted custom attributes.</param>
        /// <param name="loadCountries">A function to load countries  (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="prePopulateWithCustomerFields">A value indicating whether to pre-populate an address with customer fields entered during registration. It's used only when "address" parameter is set to "null"</param>
        /// <param name="customer">Customer record which will be used to pre-populate address. Used only when "prePopulateWithCustomerFields" is "true".</param>
        public static void PrepareModel(this AddressModel model,
                                        Address address, bool excludeProperties,
                                        AddressSettings addressSettings,
                                        ILocalizationService localizationService   = null,
                                        IStateProvinceService stateProvinceService = null,
                                        IDiaChiService diachiService = null,
                                        IAddressAttributeService addressAttributeService     = null,
                                        IAddressAttributeParser addressAttributeParser       = null,
                                        IAddressAttributeFormatter addressAttributeFormatter = null,
                                        Func <IList <Country> > loadCountries = null,
                                        bool prePopulateWithCustomerFields    = false,
                                        Customer customer = null)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (addressSettings == null)
            {
                throw new ArgumentNullException("addressSettings");
            }

            if (!excludeProperties && address != null)
            {
                model.Id          = address.Id;
                model.FirstName   = address.FirstName;
                model.LastName    = address.LastName;
                model.FullName    = string.Format("{0} {1}", address.FirstName, address.LastName);
                model.Email       = address.Email;
                model.Company     = address.Company;
                model.CountryId   = NhaXesController.CountryID;
                model.CountryName = address.Country != null
                    ? address.Country.GetLocalized(x => x.Name)
                    : null;

                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null
                    ? address.StateProvince.GetLocalized(x => x.Name)
                    : null;

                model.QuanHuyenId   = address.QuanHuyenId;
                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     = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName);
                model.LastName      = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName);
                model.Company       = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company);
                model.Address1      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress);
                model.Address2      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2);
                model.ZipPostalCode = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode);
                model.City          = customer.GetAttribute <string>(SystemCustomerAttributeNames.City);
                //ignore country and state for prepopulation. it can cause some issues when posting pack with errors, etc
                //model.CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId);
                //model.StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId);
                model.PhoneNumber = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone);
                model.FaxNumber   = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                if (localizationService == null)
                {
                    throw new ArgumentNullException("localizationService");
                }

                //model.AvailableCountries.Add(new SelectListItem { Text = localizationService.GetResource("Address.SelectCountry"), Value = "0" });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = c.GetLocalized(x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    //states
                    if (stateProvinceService == null)
                    {
                        throw new ArgumentNullException("stateProvinceService");
                    }

                    var states = stateProvinceService
                                 .GetStateProvincesByCountryId(loadCountries().First().Id)
                                 .ToList();
                    if (states.Count > 0)
                    {
                        //model.AvailableStates.Add(new SelectListItem { Text = localizationService.GetResource("Address.SelectState"), Value = "0" });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = s.GetLocalized(x => x.Name),
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);
                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                    if (model.StateProvinceId.GetValueOrDefault(0) > 0)
                    {
                        var quanhuyens = diachiService.GetQuanHuyenByProvinceId(model.StateProvinceId.GetValueOrDefault(0));

                        foreach (var s in quanhuyens)
                        {
                            model.AvailableQuanHuyens.Add(new SelectListItem
                            {
                                Text     = s.Ten,
                                Value    = s.Id.ToString(),
                                Selected = (s.Id == model.QuanHuyenId)
                            });
                        }
                    }
                }
            }

            //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.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)
            {
                PrepareCustomAddressAttributes(model, address, addressAttributeService, addressAttributeParser);
            }
            if (addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = addressAttributeFormatter.FormatAttributes(address.CustomAttributes);
            }
        }
Beispiel #20
0
        protected virtual void PrepareVendorModel(VendorModel model, Vendor vendor, bool excludeProperties, bool prepareEntireAddressModel)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var address = _addressService.GetAddressById(vendor != null ? vendor.AddressId : 0);

            if (vendor != null)
            {
                if (!excludeProperties)
                {
                    if (address != null)
                    {
                        model.Address = address.ToModel();
                    }
                }

                //associated customer emails
                model.AssociatedCustomers = _customerService
                                            .GetAllCustomers(vendorId: vendor.Id)
                                            .Select(c => new VendorModel.AssociatedCustomerInfo()
                {
                    Id    = c.Id,
                    Email = c.Email
                })
                                            .ToList();
            }

            if (prepareEntireAddressModel)
            {
                model.Address.CountryEnabled        = true;
                model.Address.StateProvinceEnabled  = true;
                model.Address.CityEnabled           = true;
                model.Address.StreetAddressEnabled  = true;
                model.Address.StreetAddress2Enabled = true;
                model.Address.ZipPostalCodeEnabled  = true;
                model.Address.PhoneEnabled          = true;
                model.Address.FaxEnabled            = true;

                //address
                model.Address.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0"
                });
                foreach (var c in _countryService.GetAllCountries(showHidden: true))
                {
                    model.Address.AvailableCountries.Add(new SelectListItem {
                        Text = c.Name, Value = c.Id.ToString(), Selected = (address != null && c.Id == address.CountryId)
                    });
                }

                var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, showHidden: true).ToList() : new List <StateProvince>();
                if (states.Any())
                {
                    foreach (var s in states)
                    {
                        model.Address.AvailableStates.Add(new SelectListItem {
                            Text = s.Name, Value = s.Id.ToString(), Selected = (address != null && s.Id == address.StateProvinceId)
                        });
                    }
                }
                else
                {
                    model.Address.AvailableStates.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0"
                    });
                }
            }
        }
        /// <summary>
        /// Prepare the customer info model
        /// </summary>
        /// <param name="model">Customer info model</param>
        /// <param name="customer">Customer</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <param name="overrideCustomCustomerAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param>
        /// <returns>Customer info model</returns>
        public virtual CustomerInfoModel PrepareCustomerInfoModel(CustomerInfoModel model, Customer customer,
                                                                  bool excludeProperties, string overrideCustomCustomerAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
            foreach (var tzi in _dateTimeHelper.GetSystemTimeZones())
            {
                model.AvailableTimeZones.Add(new SelectListItem {
                    Text = tzi.DisplayName, Value = tzi.Id, Selected = (excludeProperties ? tzi.Id == model.TimeZoneId : tzi.Id == _dateTimeHelper.CurrentTimeZone.Id)
                });
            }

            if (!excludeProperties)
            {
                model.VatNumber = customer.GetAttribute <string>(SystemCustomerAttributeNames.VatNumber);
                model.FirstName = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName);
                model.LastName  = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName);
                model.Gender    = customer.GetAttribute <string>(SystemCustomerAttributeNames.Gender);
                var dateOfBirth = customer.GetAttribute <DateTime?>(SystemCustomerAttributeNames.DateOfBirth);
                if (dateOfBirth.HasValue)
                {
                    model.DateOfBirthDay   = dateOfBirth.Value.Day;
                    model.DateOfBirthMonth = dateOfBirth.Value.Month;
                    model.DateOfBirthYear  = dateOfBirth.Value.Year;
                }
                model.Company         = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company);
                model.StreetAddress   = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress);
                model.StreetAddress2  = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2);
                model.ZipPostalCode   = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode);
                model.City            = customer.GetAttribute <string>(SystemCustomerAttributeNames.City);
                model.CountryId       = customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId);
                model.StateProvinceId = customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId);
                model.Phone           = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone);
                model.Fax             = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax);

                //newsletter
                var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id);
                model.Newsletter = newsletter != null && newsletter.Active;

                model.Signature = customer.GetAttribute <string>(SystemCustomerAttributeNames.Signature);

                model.Email    = customer.Email;
                model.Username = customer.Username;
            }
            else
            {
                if (_customerSettings.UsernamesEnabled && !_customerSettings.AllowUsersToChangeUsernames)
                {
                    model.Username = customer.Username;
                }
            }

            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                model.EmailToRevalidate = customer.EmailToRevalidate;
            }

            //countries and states
            if (_customerSettings.CountryEnabled)
            {
                model.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0"
                });
                foreach (var c in _countryService.GetAllCountries(_workContext.WorkingLanguage.Id))
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = c.GetLocalized(x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (_customerSettings.StateProvinceEnabled)
                {
                    //states
                    var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, _workContext.WorkingLanguage.Id).ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = _localizationService.GetResource("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem {
                                Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected);

                        model.AvailableStates.Add(new SelectListItem
                        {
                            Text  = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                }
            }
            model.DisplayVatNumber    = _taxSettings.EuVatEnabled;
            model.VatNumberStatusNote = ((VatNumberStatus)customer.GetAttribute <int>(SystemCustomerAttributeNames.VatNumberStatusId))
                                        .GetLocalizedEnum(_localizationService, _workContext);
            model.GenderEnabled                    = _customerSettings.GenderEnabled;
            model.DateOfBirthEnabled               = _customerSettings.DateOfBirthEnabled;
            model.DateOfBirthRequired              = _customerSettings.DateOfBirthRequired;
            model.CompanyEnabled                   = _customerSettings.CompanyEnabled;
            model.CompanyRequired                  = _customerSettings.CompanyRequired;
            model.StreetAddressEnabled             = _customerSettings.StreetAddressEnabled;
            model.StreetAddressRequired            = _customerSettings.StreetAddressRequired;
            model.StreetAddress2Enabled            = _customerSettings.StreetAddress2Enabled;
            model.StreetAddress2Required           = _customerSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled             = _customerSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired            = _customerSettings.ZipPostalCodeRequired;
            model.CityEnabled                      = _customerSettings.CityEnabled;
            model.CityRequired                     = _customerSettings.CityRequired;
            model.CountryEnabled                   = _customerSettings.CountryEnabled;
            model.CountryRequired                  = _customerSettings.CountryRequired;
            model.StateProvinceEnabled             = _customerSettings.StateProvinceEnabled;
            model.StateProvinceRequired            = _customerSettings.StateProvinceRequired;
            model.PhoneEnabled                     = _customerSettings.PhoneEnabled;
            model.PhoneRequired                    = _customerSettings.PhoneRequired;
            model.FaxEnabled                       = _customerSettings.FaxEnabled;
            model.FaxRequired                      = _customerSettings.FaxRequired;
            model.NewsletterEnabled                = _customerSettings.NewsletterEnabled;
            model.UsernamesEnabled                 = _customerSettings.UsernamesEnabled;
            model.AllowUsersToChangeUsernames      = _customerSettings.AllowUsersToChangeUsernames;
            model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled;
            model.SignatureEnabled                 = _forumSettings.ForumsEnabled && _forumSettings.SignaturesEnabled;

            //external authentication
            model.NumberOfExternalAuthenticationProviders = _openAuthenticationService
                                                            .LoadActiveExternalAuthenticationMethods(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id).Count;
            foreach (var ear in _openAuthenticationService.GetExternalIdentifiersFor(customer))
            {
                var authMethod = _openAuthenticationService.LoadExternalAuthenticationMethodBySystemName(ear.ProviderSystemName);
                if (authMethod == null || !authMethod.IsMethodActive(_externalAuthenticationSettings))
                {
                    continue;
                }

                model.AssociatedExternalAuthRecords.Add(new CustomerInfoModel.AssociatedExternalAuthModel
                {
                    Id    = ear.Id,
                    Email = ear.Email,
                    ExternalIdentifier = ear.ExternalIdentifier,
                    AuthMethodName     = authMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id)
                });
            }

            //custom customer attributes
            var customAttributes = PrepareCustomCustomerAttributes(customer, overrideCustomCustomerAttributesXml);

            customAttributes.ForEach(model.CustomerAttributes.Add);

            return(model);
        }
Beispiel #22
0
        public RegisterValidator(
            IEnumerable <IValidatorConsumer <RegisterModel> > validators,
            ILocalizationService localizationService,
            IStateProvinceService stateProvinceService,
            CustomerSettings customerSettings)
            : base(validators)
        {
            RuleFor(x => x.Email).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Email.Required"));
            RuleFor(x => x.Email).EmailAddress().WithMessage(localizationService.GetResource("Common.WrongEmail"));


            if (customerSettings.UsernamesEnabled)
            {
                RuleFor(x => x.Username).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Username.Required"));
            }

            RuleFor(x => x.FirstName).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.FirstName.Required"));
            RuleFor(x => x.LastName).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.LastName.Required"));


            RuleFor(x => x.Password).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Password.Required"));
            RuleFor(x => x.Password).Length(customerSettings.PasswordMinLength, 999).WithMessage(string.Format(localizationService.GetResource("Account.Fields.Password.LengthValidation"), customerSettings.PasswordMinLength));
            RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ConfirmPassword.Required"));
            RuleFor(x => x.ConfirmPassword).Equal(x => x.Password).WithMessage(localizationService.GetResource("Account.Fields.Password.EnteredPasswordsDoNotMatch"));

            //form fields
            if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
            {
                RuleFor(x => x.CountryId)
                .NotNull()
                .WithMessage(localizationService.GetResource("Address.Fields.Country.Required"));
                RuleFor(x => x.CountryId)
                .NotEqual("")
                .WithMessage(localizationService.GetResource("Address.Fields.Country.Required"));
            }
            if (customerSettings.CountryEnabled &&
                customerSettings.StateProvinceEnabled &&
                customerSettings.StateProvinceRequired)
            {
                RuleFor(x => x.StateProvinceId).MustAsync(async(x, y, context) =>
                {
                    //does selected country has states?
                    var countryId = !String.IsNullOrEmpty(x.CountryId) ? x.CountryId : "";
                    var hasStates = (await stateProvinceService.GetStateProvincesByCountryId(countryId)).Count > 0;
                    if (hasStates)
                    {
                        //if yes, then ensure that state is selected
                        if (String.IsNullOrEmpty(y))
                        {
                            return(false);
                        }
                    }
                    return(true);
                }).WithMessage(localizationService.GetResource("Account.Fields.StateProvince.Required"));
            }
            if (customerSettings.DateOfBirthEnabled && customerSettings.DateOfBirthRequired)
            {
                RuleFor(x => x.DateOfBirthDay).Must((x, context) =>
                {
                    var dateOfBirth = x.ParseDateOfBirth();
                    if (!dateOfBirth.HasValue)
                    {
                        return(false);
                    }

                    return(true);
                }).WithMessage(localizationService.GetResource("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);
                }).WithMessage(string.Format(localizationService.GetResource("Account.Fields.DateOfBirth.MinimumAge"), customerSettings.DateOfBirthMinimumAge));
            }
            if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)
            {
                RuleFor(x => x.Company).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Company.Required"));
            }
            if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
            {
                RuleFor(x => x.StreetAddress).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress.Required"));
            }
            if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)
            {
                RuleFor(x => x.StreetAddress2).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress2.Required"));
            }
            if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)
            {
                RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ZipPostalCode.Required"));
            }
            if (customerSettings.CityRequired && customerSettings.CityEnabled)
            {
                RuleFor(x => x.City).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.City.Required"));
            }
            if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)
            {
                RuleFor(x => x.Phone).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Phone.Required"));
            }
            if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
            {
                RuleFor(x => x.Fax).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Fax.Required"));
            }
        }
Beispiel #23
0
        /// <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 bool IsAddressValid(Address address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("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)
            {
                if (address.CountryId == null || address.CountryId.Value == 0)
                {
                    return(false);
                }

                var country = _countryService.GetCountryById(address.CountryId.Value);
                if (country == null)
                {
                    return(false);
                }

                if (_addressSettings.StateProvinceEnabled)
                {
                    var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id);
                    if (states.Count > 0)
                    {
                        if (address.StateProvinceId == null || address.StateProvinceId.Value == 0)
                        {
                            return(false);
                        }

                        var state = _stateProvinceService.GetStateProvinceById(address.StateProvinceId.Value);
                        if (state == null)
                        {
                            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);
            }

            return(true);
        }
        public AddressValidator(ILocalizationService localizationService,
                                IStateProvinceService stateProvinceService,
                                AddressSettings addressSettings)
        {
            RuleFor(x => x.FirstName)
            .NotEmpty()
            .WithMessage(localizationService.GetResource("Address.Fields.FirstName.Required"));
            RuleFor(x => x.LastName)
            .NotEmpty()
            .WithMessage(localizationService.GetResource("Address.Fields.LastName.Required"));
            RuleFor(x => x.Email)
            .NotEmpty()
            .WithMessage(localizationService.GetResource("Address.Fields.Email.Required"));
            RuleFor(x => x.Email)
            .EmailAddress()
            .WithMessage(localizationService.GetResource("Common.WrongEmail"));
            if (addressSettings.CountryEnabled)
            {
                RuleFor(x => x.CountryId)
                .NotNull()
                .WithMessage(localizationService.GetResource("Address.Fields.Country.Required"));
                RuleFor(x => x.CountryId)
                .NotEqual(0)
                .WithMessage(localizationService.GetResource("Address.Fields.Country.Required"));
            }
            if (addressSettings.CountryEnabled && addressSettings.StateProvinceEnabled)
            {
                RuleFor(x => x.StateProvinceId).Must((x, context) =>
                {
                    //does selected country has states?
                    var countryId = x.CountryId.HasValue ? x.CountryId.Value : 0;
                    var hasStates = stateProvinceService.GetStateProvincesByCountryId(countryId).Any();

                    if (hasStates)
                    {
                        //if yes, then ensure that state is selected
                        if (!x.StateProvinceId.HasValue || x.StateProvinceId.Value == 0)
                        {
                            return(false);
                        }
                    }

                    return(true);
                }).WithMessage(localizationService.GetResource("Address.Fields.StateProvince.Required"));
            }
            if (addressSettings.CompanyRequired && addressSettings.CompanyEnabled)
            {
                RuleFor(x => x.Company).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Company.Required"));
            }
            if (addressSettings.StreetAddressRequired && addressSettings.StreetAddressEnabled)
            {
                RuleFor(x => x.Address1).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress.Required"));
            }
            if (addressSettings.StreetAddress2Required && addressSettings.StreetAddress2Enabled)
            {
                RuleFor(x => x.Address2).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.StreetAddress2.Required"));
            }
            if (addressSettings.ZipPostalCodeRequired && addressSettings.ZipPostalCodeEnabled)
            {
                RuleFor(x => x.ZipPostalCode).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.ZipPostalCode.Required"));
            }
            if (addressSettings.CityRequired && addressSettings.CityEnabled)
            {
                RuleFor(x => x.City).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.City.Required"));
            }
            if (addressSettings.PhoneRequired && addressSettings.PhoneEnabled)
            {
                RuleFor(x => x.PhoneNumber).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Phone.Required"));
            }
            if (addressSettings.FaxRequired && addressSettings.FaxEnabled)
            {
                RuleFor(x => x.FaxNumber).NotEmpty().WithMessage(localizationService.GetResource("Account.Fields.Fax.Required"));
            }
        }
Beispiel #25
0
        public CustomerValidator(ILocalizationService localizationService,
                                 IStateProvinceService stateProvinceService,
                                 ICustomerService customerService,
                                 CustomerSettings customerSettings,
                                 IDbContext dbContext)
        {
            //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")
            .WithMessage(localizationService.GetResource("Admin.Common.WrongEmail"))
            //only for registered users
            .When(x => IsRegisteredCustomerRoleChecked(x, customerService));

            //form fields
            if (customerSettings.CountryEnabled && customerSettings.CountryRequired)
            {
                RuleFor(x => x.CountryId)
                .NotEqual(0)
                .WithMessage(localizationService.GetResource("Account.Fields.Country.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.CountryEnabled &&
                customerSettings.StateProvinceEnabled &&
                customerSettings.StateProvinceRequired)
            {
                RuleFor(x => x.StateProvinceId).Must((x, context) =>
                {
                    //does selected country have states?
                    var hasStates = stateProvinceService.GetStateProvincesByCountryId(x.CountryId).Any();
                    if (hasStates)
                    {
                        //if yes, then ensure that a state is selected
                        if (x.StateProvinceId == 0)
                        {
                            return(false);
                        }
                    }

                    return(true);
                }).WithMessage(localizationService.GetResource("Account.Fields.StateProvince.Required"));
            }
            if (customerSettings.CompanyRequired && customerSettings.CompanyEnabled)
            {
                RuleFor(x => x.Company)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.Company.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.StreetAddressRequired && customerSettings.StreetAddressEnabled)
            {
                RuleFor(x => x.StreetAddress)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.StreetAddress.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.StreetAddress2Required && customerSettings.StreetAddress2Enabled)
            {
                RuleFor(x => x.StreetAddress2)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.StreetAddress2.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.ZipPostalCodeRequired && customerSettings.ZipPostalCodeEnabled)
            {
                RuleFor(x => x.ZipPostalCode)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.ZipPostalCode.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.CityRequired && customerSettings.CityEnabled)
            {
                RuleFor(x => x.City)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.City.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.CountyRequired && customerSettings.CountyEnabled)
            {
                RuleFor(x => x.County)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.County.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.PhoneRequired && customerSettings.PhoneEnabled)
            {
                RuleFor(x => x.Phone)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.Phone.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }
            if (customerSettings.FaxRequired && customerSettings.FaxEnabled)
            {
                RuleFor(x => x.Fax)
                .NotEmpty()
                .WithMessage(localizationService.GetResource("Admin.Customers.Customers.Fields.Fax.Required"))
                //only for registered users
                .When(x => IsRegisteredCustomerRoleChecked(x, customerService));
            }

            SetDatabaseValidationRules <Customer>(dbContext);
        }
        public ActionResult Configure()
        {
            var taxCategories = _taxCategoryService.GetAllTaxCategories();

            if (taxCategories.Count == 0)
            {
                return(Content("No tax categories can be loaded"));
            }

            var model = new ByRegionTaxRateListModel();

            foreach (var tc in taxCategories)
            {
                model.AvailableTaxCategories.Add(new SelectListItem()
                {
                    Text = tc.Name, Value = tc.Id.ToString()
                });
            }
            var countries = _countryService.GetAllCountries(true);

            foreach (var c in countries)
            {
                model.AvailableCountries.Add(new SelectListItem()
                {
                    Text = c.Name, Value = c.Id.ToString()
                });
            }
            model.AvailableStates.Add(new SelectListItem()
            {
                Text = "*", Value = "0"
            });
            var states = _stateProvinceService.GetStateProvincesByCountryId(countries.FirstOrDefault().Id);

            if (states.Count > 0)
            {
                foreach (var s in states)
                {
                    model.AvailableStates.Add(new SelectListItem()
                    {
                        Text = s.Name, Value = s.Id.ToString()
                    });
                }
            }

            model.TaxRates = _taxRateService.GetAllTaxRates()
                             .Select(x =>
            {
                var m = new ByRegionTaxRateModel()
                {
                    Id              = x.Id,
                    TaxCategoryId   = x.TaxCategoryId,
                    CountryId       = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip             = x.Zip,
                    Percentage      = x.Percentage,
                };
                var tc              = _taxCategoryService.GetTaxCategoryById(x.TaxCategoryId);
                m.TaxCategoryName   = (tc != null) ? tc.Name : "";
                var c               = _countryService.GetCountryById(x.CountryId);
                m.CountryName       = (c != null) ? c.Name : "Unavailable";
                var s               = _stateProvinceService.GetStateProvinceById(x.StateProvinceId);
                m.StateProvinceName = (s != null) ? s.Name : "*";
                m.Zip               = (!String.IsNullOrEmpty(x.Zip)) ? x.Zip : "*";
                return(m);
            })
                             .ToList();

            return(View(model));
        }
Beispiel #27
0
        /// <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 bool IsAddressValid(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)
            {
                if (address.CountryId == null || address.CountryId.Value == 0)
                {
                    return(false);
                }

                var country = _countryService.GetCountryById(address.CountryId.Value);
                if (country == null)
                {
                    return(false);
                }

                if (_addressSettings.StateProvinceEnabled)
                {
                    var states = _stateProvinceService.GetStateProvincesByCountryId(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 = _addressAttributeService.GetAllAddressAttributes().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 virtual async Task PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties,
                                                        bool prepareEntireAddressModel = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (affiliate != null)
            {
                model.Id  = affiliate.Id;
                model.Url = affiliate.GenerateUrl(_webHelper);
                if (!excludeProperties)
                {
                    model.AdminComment    = affiliate.AdminComment;
                    model.FriendlyUrlName = affiliate.FriendlyUrlName;
                    model.Active          = affiliate.Active;
                    model.Address         = await affiliate.Address.ToModel(_countryService, _stateProvinceService);
                }
            }

            if (prepareEntireAddressModel)
            {
                model.Address.FirstNameEnabled      = true;
                model.Address.FirstNameRequired     = true;
                model.Address.LastNameEnabled       = true;
                model.Address.LastNameRequired      = true;
                model.Address.EmailEnabled          = true;
                model.Address.EmailRequired         = true;
                model.Address.CompanyEnabled        = true;
                model.Address.CountryEnabled        = true;
                model.Address.StateProvinceEnabled  = true;
                model.Address.CityEnabled           = true;
                model.Address.CityRequired          = true;
                model.Address.StreetAddressEnabled  = true;
                model.Address.StreetAddressRequired = true;
                model.Address.StreetAddress2Enabled = true;
                model.Address.ZipPostalCodeEnabled  = true;
                model.Address.ZipPostalCodeRequired = true;
                model.Address.PhoneEnabled          = true;
                model.Address.PhoneRequired         = true;
                model.Address.FaxEnabled            = true;

                //address
                model.Address.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = ""
                });
                foreach (var c in await _countryService.GetAllCountries(showHidden: true))
                {
                    model.Address.AvailableCountries.Add(new SelectListItem {
                        Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId)
                    });
                }

                var states = !String.IsNullOrEmpty(model.Address.CountryId) ? await _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId, showHidden : true) : new List <StateProvince>();

                if (states.Count > 0)
                {
                    foreach (var s in states)
                    {
                        model.Address.AvailableStates.Add(new SelectListItem {
                            Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId)
                        });
                    }
                }
                else
                {
                    model.Address.AvailableStates.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = ""
                    });
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Import states from TXT file
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <returns>Number of imported states</returns>
        public virtual int ImportStatesFromTxt(Stream stream)
        {
            int count = 0;

            using (var reader = new StreamReader(stream))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (String.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }
                    string[] tmp = line.Split(',');

                    if (tmp.Length != 5)
                    {
                        throw new NopException("Wrong file format");
                    }

                    //parse
                    var  countryTwoLetterIsoCode = tmp[0].Trim();
                    var  name         = tmp[1].Trim();
                    var  abbreviation = tmp[2].Trim();
                    bool published    = Boolean.Parse(tmp[3].Trim());
                    int  displayOrder = Int32.Parse(tmp[4].Trim());

                    var country = _countryService.GetCountryByTwoLetterIsoCode(countryTwoLetterIsoCode);
                    if (country == null)
                    {
                        //country cannot be loaded. skip
                        continue;
                    }

                    //import
                    var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id, true);
                    var state  = states.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));

                    if (state != null)
                    {
                        state.Abbreviation = abbreviation;
                        state.Published    = published;
                        state.DisplayOrder = displayOrder;
                        _stateProvinceService.UpdateStateProvince(state);
                    }
                    else
                    {
                        state = new StateProvince
                        {
                            CountryId    = country.Id,
                            Name         = name,
                            Abbreviation = abbreviation,
                            Published    = published,
                            DisplayOrder = displayOrder,
                        };
                        _stateProvinceService.InsertStateProvince(state);
                    }
                    count++;
                }
            }

            return(count);
        }
Beispiel #30
0
        public IActionResult EditRateByWeightByTotalPopup(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageShippingSettings))
            {
                return(AccessDeniedView());
            }

            var sbw = _shippingByWeightService.GetById(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 = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)?.CurrencyCode,
                BaseWeightIn             = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId)?.Name
            };

            var shippingMethods = _shippingService.GetAllShippingMethods();

            if (!shippingMethods.Any())
            {
                return(Content("No shipping methods can be loaded"));
            }

            var selectedStore          = _storeService.GetStoreById(sbw.StoreId);
            var selectedWarehouse      = _shippingService.GetWarehouseById(sbw.WarehouseId);
            var selectedShippingMethod = _shippingService.GetShippingMethodById(sbw.ShippingMethodId);
            var selectedCountry        = _countryService.GetCountryById(sbw.CountryId);
            var selectedState          = _stateProvinceService.GetStateProvinceById(sbw.StateProvinceId);

            //stores
            model.AvailableStores.Add(new SelectListItem {
                Text = "*", Value = "0"
            });
            foreach (var store in _storeService.GetAllStores())
            {
                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 _shippingService.GetAllWarehouses())
            {
                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 = _countryService.GetAllCountries(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?_stateProvinceService.GetStateProvincesByCountryId(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 virtual async Task <AddressModel> PrepareAddressModel(AddressModel model, Address address, bool excludeProperties)
        {
            if (address != null)
            {
                if (!excludeProperties)
                {
                    model = await address.ToModel(_countryService, _stateProvinceService);
                }
            }

            if (model == null)
            {
                model = new AddressModel();
            }

            model.FirstNameEnabled       = true;
            model.FirstNameRequired      = true;
            model.LastNameEnabled        = true;
            model.LastNameRequired       = true;
            model.EmailEnabled           = true;
            model.EmailRequired          = true;
            model.CompanyEnabled         = _addressSettings.CompanyEnabled;
            model.CompanyRequired        = _addressSettings.CompanyRequired;
            model.VatNumberEnabled       = _addressSettings.VatNumberEnabled;
            model.VatNumberRequired      = _addressSettings.VatNumberRequired;
            model.CountryEnabled         = _addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = _addressSettings.StateProvinceEnabled;
            model.CityEnabled            = _addressSettings.CityEnabled;
            model.CityRequired           = _addressSettings.CityRequired;
            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.PhoneEnabled           = _addressSettings.PhoneEnabled;
            model.PhoneRequired          = _addressSettings.PhoneRequired;
            model.FaxEnabled             = _addressSettings.FaxEnabled;
            model.FaxRequired            = _addressSettings.FaxRequired;
            //countries
            model.AvailableCountries.Add(new SelectListItem {
                Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = ""
            });
            foreach (var c in await _countryService.GetAllCountries(showHidden: true))
            {
                model.AvailableCountries.Add(new SelectListItem {
                    Text = c.Name, Value = c.Id.ToString(), Selected = (c.Id == model.CountryId)
                });
            }
            //states
            var states = !String.IsNullOrEmpty(model.CountryId) ? await _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, showHidden : true) : new List <StateProvince>();

            if (states.Count > 0)
            {
                foreach (var s in states)
                {
                    model.AvailableStates.Add(new SelectListItem {
                        Text = s.Name, Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId)
                    });
                }
            }
            else
            {
                model.AvailableStates.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = ""
                });
            }
            //customer attribute services
            await model.PrepareCustomAddressAttributes(address, _addressAttributeService, _addressAttributeParser);

            return(model);
        }
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Model</param>
        /// <param name="address">Address</param>
        /// <param name="excludeProperties">A value indicating whether to exclude properties</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="localizationService">Localization service (used to prepare a select list)</param>
        /// <param name="stateProvinceService">State service (used to prepare a select list). null to don't prepare the list.</param>
        /// <param name="loadCountries">A function to load countries  (used to prepare a select list). null to don't prepare the list.</param>
        public static void PrepareModel(this AddressModel model,
            Address address, bool excludeProperties,
            AddressSettings addressSettings,
            ILocalizationService localizationService = null,
            IStateProvinceService stateProvinceService = null,
            Func<IList<Country>> loadCountries = null)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (addressSettings == null)
                throw new ArgumentNullException("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 = address.Country != null
                    ? address.Country.GetLocalized(x => x.Name)
                    : null;
                model.StateProvinceId = address.StateProvinceId;
                model.StateProvinceName = address.StateProvince != null
                    ? address.StateProvince.GetLocalized(x => x.Name)
                    : null;
                model.City = address.City;
                model.Address1 = address.Address1;
                model.Address2 = address.Address2;
                model.ZipPostalCode = address.ZipPostalCode;
                model.PhoneNumber = address.PhoneNumber;
                model.FaxNumber = address.FaxNumber;
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                if (localizationService == null)
                    throw new ArgumentNullException("localizationService");

                model.AvailableCountries.Add(new SelectListItem() { Text = localizationService.GetResource("Address.SelectCountry"), Value = "0" });
                foreach (var c in loadCountries())
                {
                    model.AvailableCountries.Add(new SelectListItem()
                    {
                        Text = c.GetLocalized(x => x.Name),
                        Value = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    //states
                    if (stateProvinceService == null)
                        throw new ArgumentNullException("stateProvinceService");

                    var states = stateProvinceService
                        .GetStateProvincesByCountryId(model.CountryId.HasValue ? model.CountryId.Value : 0)
                        .ToList();
                    if (states.Count > 0)
                    {
                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem()
                            {
                                Text = s.GetLocalized(x => x.Name),
                                Value = s.Id.ToString(),
                                Selected = (s.Id == model.StateProvinceId)
                            });
                        }
                    }
                    else
                    {
                        model.AvailableStates.Add(new SelectListItem()
                        {
                            Text = localizationService.GetResource("Address.OtherNonUS"),
                            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.CountryEnabled = addressSettings.CountryEnabled;
            model.StateProvinceEnabled = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled = addressSettings.PhoneEnabled;
            model.PhoneRequired = addressSettings.PhoneRequired;
            model.FaxEnabled = addressSettings.FaxEnabled;
            model.FaxRequired = addressSettings.FaxRequired;
        }
        public static ExtendedVendorListModel ToListModel(this Domain.ExtendedVendor ExtendedVendor, IPictureService _pictureService, ICacheManager _cacheManager,ICountryService _countryService, IStateProvinceService _stateProvinceService)
        {
            var model = new ExtendedVendorListModel()
            {
                AddressLine1 = ExtendedVendor.AddressLine1,
                AddressLine2 = ExtendedVendor.AddressLine2,
                City = ExtendedVendor.City,
                CountryId = ExtendedVendor.CountryId,
                HelpfulnessEnabled = ExtendedVendor.HelpfulnessEnabled,
                LogoId = ExtendedVendor.LogoId,
                ReviewsEnabled = ExtendedVendor.ReviewsEnabled,
                StateProvinceId = ExtendedVendor.StateProvinceId,
                VendorId = ExtendedVendor.VendorId,
                TINNumber = ExtendedVendor.TinNumber,
                ServiceTaxNumber = ExtendedVendor.ServiceTaxNumber,
                ShortCode = ExtendedVendor.ShortCode,
                VatCST = ExtendedVendor.VatCST,
                Id = ExtendedVendor.Id,
                ZipCode = ExtendedVendor.ZipCode,
                PhoneNumber = ExtendedVendor.PhoneNumber,
                CommissionPercentage = ExtendedVendor.CommissionPercentage
            };
            var countries = _countryService.GetAllCountries();
            foreach (var country in countries)
            {
                var listItem = new SelectListItem
                {
                    Text = country.Name,
                    Value = country.Id.ToString()
                };
                if (country.Id == model.CountryId)
                    listItem.Selected = true;

                model.SelectedCountry.Add(listItem);

            }
            if (model.CountryId != 0)
            {
                var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId);
                foreach (var state in states)
                {
                    var listItem = new SelectListItem
                    {
                        Text = state.Name,
                        Value = state.Id.ToString()
                    };
                    if (state.Id == model.StateProvinceId)
                        listItem.Selected = true;
                    model.SelectedStateProvince.Add(listItem);
                }
            }

            return model;
        }