protected virtual void PrepareCustomerModel(CustomerModel model, Customer customer, bool excludeProperties) { var allStores = _storeService.GetAllStores(); if (customer != null) { model.Id = customer.Id; if (!excludeProperties) { model.Email = customer.Email; model.Username = customer.Username; model.VendorId = customer.VendorId; model.AdminComment = customer.AdminComment; model.IsTaxExempt = customer.IsTaxExempt; model.Active = customer.Active; var affiliate = _affiliateService.GetAffiliateById(customer.AffiliateId); if (affiliate != null) { model.AffiliateId = affiliate.Id; model.AffiliateName = affiliate.GetFullName(); } model.TimeZoneId = customer.GetAttribute<string>(SystemCustomerAttributeNames.TimeZoneId); model.VatNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.VatNumber); model.VatNumberStatusNote = ((VatNumberStatus)customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId)) .GetLocalizedEnum(_localizationService, _workContext); model.CreatedOn = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc); model.LastActivityDate = _dateTimeHelper.ConvertToUserTime(customer.LastActivityDateUtc, DateTimeKind.Utc); model.LastIpAddress = customer.LastIpAddress; model.LastVisitedPage = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastVisitedPage); model.SelectedCustomerRoleIds = customer.CustomerRoles.Select(cr => cr.Id).ToList(); //newsletter subscriptions if (!String.IsNullOrEmpty(customer.Email)) { var newsletterSubscriptionStoreIds = new List<int>(); foreach (var store in allStores) { var newsletterSubscription = _newsLetterSubscriptionService .GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id); if (newsletterSubscription != null) newsletterSubscriptionStoreIds.Add(store.Id); model.SelectedNewsletterSubscriptionStoreIds = newsletterSubscriptionStoreIds.ToArray(); } } //form fields model.FirstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName); model.LastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName); model.Gender = customer.GetAttribute<string>(SystemCustomerAttributeNames.Gender); model.DateOfBirth = customer.GetAttribute<DateTime?>(SystemCustomerAttributeNames.DateOfBirth); 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); } } model.UsernamesEnabled = _customerSettings.UsernamesEnabled; model.AllowUsersToChangeUsernames = _customerSettings.AllowUsersToChangeUsernames; model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone; foreach (var tzi in _dateTimeHelper.GetSystemTimeZones()) model.AvailableTimeZones.Add(new SelectListItem { Text = tzi.DisplayName, Value = tzi.Id, Selected = (tzi.Id == model.TimeZoneId) }); if (customer != null) { model.DisplayVatNumber = _taxSettings.EuVatEnabled; } else { model.DisplayVatNumber = false; } //vendors PrepareVendorsModel(model); //customer attributes PrepareCustomerAttributeModel(model, customer); model.GenderEnabled = _customerSettings.GenderEnabled; model.DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled; model.CompanyEnabled = _customerSettings.CompanyEnabled; model.StreetAddressEnabled = _customerSettings.StreetAddressEnabled; model.StreetAddress2Enabled = _customerSettings.StreetAddress2Enabled; model.ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled; model.CityEnabled = _customerSettings.CityEnabled; model.CountryEnabled = _customerSettings.CountryEnabled; model.StateProvinceEnabled = _customerSettings.StateProvinceEnabled; model.PhoneEnabled = _customerSettings.PhoneEnabled; model.FaxEnabled = _customerSettings.FaxEnabled; //countries and states if (_customerSettings.CountryEnabled) { model.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0" }); foreach (var c in _countryService.GetAllCountries(showHidden: true)) { model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = c.Id == model.CountryId }); } if (_customerSettings.StateProvinceEnabled) { //states var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId).ToList(); if (states.Any()) { model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Admin.Address.SelectState"), Value = "0" }); foreach (var s in states) { model.AvailableStates.Add(new SelectListItem { Text = s.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 ? "Admin.Address.OtherNonUS" : "Admin.Address.SelectState"), Value = "0" }); } } } //newsletter subscriptions model.AvailableNewsletterSubscriptionStores = allStores .Select(s => new CustomerModel.StoreModel() {Id = s.Id, Name = s.Name }) .ToList(); //customer roles var allRoles = _customerService.GetAllCustomerRoles(true); var adminRole = allRoles.FirstOrDefault(c => c.SystemName == SystemCustomerRoleNames.Registered); //precheck Registered Role as a default role while creating a new customer through admin if (customer == null && adminRole != null) { model.SelectedCustomerRoleIds.Add(adminRole.Id); } foreach (var role in allRoles) { model.AvailableCustomerRoles.Add(new SelectListItem { Text = role.Name, Value = role.Id.ToString(), Selected = model.SelectedCustomerRoleIds.Contains(role.Id) }); } //reward points history if (customer != null) { model.DisplayRewardPointsHistory = _rewardPointsSettings.Enabled; model.AddRewardPointsValue = 0; model.AddRewardPointsMessage = "Some comment here..."; //stores foreach (var store in allStores) { model.RewardPointsAvailableStores.Add(new SelectListItem { Text = store.Name, Value = store.Id.ToString(), Selected = (store.Id == _storeContext.CurrentStore.Id) }); } } else { model.DisplayRewardPointsHistory = false; } //external authentication records if (customer != null) { model.AssociatedExternalAuthRecords = GetAssociatedExternalAuthRecords(customer); } //sending of the welcome message: //1. "admin approval" registration method //2. already created customer //3. registered model.AllowSendingOfWelcomeMessage = _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval && customer != null && customer.IsRegistered(); //sending of the activation message //1. "email validation" registration method //2. already created customer //3. registered //4. not active model.AllowReSendingOfActivationMessage = _customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && customer != null && customer.IsRegistered() && !customer.Active; }
protected virtual CustomerModel PrepareCustomerModelForList(Customer customer) { return new CustomerModel { Id = customer.Id, Email = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"), Username = customer.Username, FullName = customer.GetFullName(), Company = customer.GetAttribute<string>(SystemCustomerAttributeNames.Company), Phone = customer.GetAttribute<string>(SystemCustomerAttributeNames.Phone), ZipPostalCode = customer.GetAttribute<string>(SystemCustomerAttributeNames.ZipPostalCode), CustomerRoleNames = GetCustomerRolesNames(customer.CustomerRoles.ToList()), Active = customer.Active, CreatedOn = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc), LastActivityDate = _dateTimeHelper.ConvertToUserTime(customer.LastActivityDateUtc, DateTimeKind.Utc), }; }
/// <summary> /// Validate discount /// </summary> /// <param name="discount">Discount</param> /// <param name="customer">Customer</param> /// <param name="couponCodeToValidate">Coupon code to validate</param> /// <returns>Discount validation result</returns> public virtual DiscountValidationResult ValidateDiscount(Discount discount, Customer customer, string couponCodeToValidate) { if (discount == null) throw new ArgumentNullException("discount"); if (customer == null) throw new ArgumentNullException("customer"); //invalid by default var result = new DiscountValidationResult(); //check coupon code if (discount.RequiresCouponCode) { if (String.IsNullOrEmpty(discount.CouponCode)) return result; if (!discount.CouponCode.Equals(couponCodeToValidate, StringComparison.InvariantCultureIgnoreCase)) return result; } //check date range DateTime now = DateTime.UtcNow; if (discount.StartDateUtc.HasValue) { DateTime startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc); if (startDate.CompareTo(now) > 0) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.NotStartedYet"); return result; } } if (discount.EndDateUtc.HasValue) { DateTime endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc); if (endDate.CompareTo(now) < 0) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.Expired"); return result; } } //discount limitation switch (discount.DiscountLimitation) { case DiscountLimitationType.NTimesOnly: { var usedTimes = GetAllDiscountUsageHistory(discount.Id, null, null, 0, 1).TotalCount; if (usedTimes >= discount.LimitationTimes) return result; } break; case DiscountLimitationType.NTimesPerCustomer: { if (customer.IsRegistered()) { var usedTimes = GetAllDiscountUsageHistory(discount.Id, customer.Id, null, 0, 1).TotalCount; if (usedTimes >= discount.LimitationTimes) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.CannotBeUsedAnymore"); return result; } } } break; case DiscountLimitationType.Unlimited: default: break; } //discount requirements var requirements = discount.DiscountRequirements; foreach (var req in requirements) { var requirementRule = LoadDiscountRequirementRuleBySystemName(req.DiscountRequirementRuleSystemName); if (requirementRule == null) continue; if (!_pluginFinder.AuthenticateStore(requirementRule.PluginDescriptor, _storeContext.CurrentStore.Id)) continue; var ruleRequest = new DiscountRequirementValidationRequest { DiscountRequirement = req, Customer = customer, Store = _storeContext.CurrentStore }; var ruleResult = requirementRule.CheckRequirement(ruleRequest); if (!ruleResult.IsValid) { result.UserError = ruleResult.UserError; return result; } } //Do not allow discounts applied to order subtotal or total when a customer has gift cards in the cart. //Otherwise, this customer can purchase gift cards with discount and get more than paid ("free money"). if (discount.DiscountType == DiscountType.AssignedToOrderSubTotal || discount.DiscountType == DiscountType.AssignedToOrderTotal) { var cart = customer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); var hasGiftCards = cart.Any(x => x.Product.IsGiftCard); if (hasGiftCards) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.CannotBeUsedWithGiftCards"); return result; } } result.IsValid = true; return result; }
public void Can_check_whether_customer_is_registered() { var customer = new Customer(); customer.CustomerRoles.Add(new CustomerRole { Active = true, Name = "Administrators", SystemName = SystemCustomerRoleNames.Administrators }); customer.CustomerRoles.Add(new CustomerRole { Active = true, Name = "Guests", SystemName = SystemCustomerRoleNames.Guests }); customer.IsRegistered().ShouldBeFalse(); customer.CustomerRoles.Add( new CustomerRole { Active = true, Name = "Registered", SystemName = SystemCustomerRoleNames.Registered }); customer.IsRegistered().ShouldBeTrue(); }
/// <summary> /// Validate discount /// </summary> /// <param name="discount">Discount</param> /// <param name="customer">Customer</param> /// <param name="couponCodeToValidate">Coupon code to validate</param> /// <returns>Discount validation result</returns> public virtual DiscountValidationResult ValidateDiscount(Discount discount, Customer customer, string couponCodeToValidate) { if (discount == null) throw new ArgumentNullException("discount"); if (customer == null) throw new ArgumentNullException("customer"); //invalid by default var result = new DiscountValidationResult(); //check coupon code if (discount.RequiresCouponCode) { if (String.IsNullOrEmpty(discount.CouponCode)) return result; if (!discount.CouponCode.Equals(couponCodeToValidate, StringComparison.InvariantCultureIgnoreCase)) return result; } //Do not allow discounts applied to order subtotal or total when a customer has gift cards in the cart. //Otherwise, this customer can purchase gift cards with discount and get more than paid ("free money"). if (discount.DiscountType == DiscountType.AssignedToOrderSubTotal || discount.DiscountType == DiscountType.AssignedToOrderTotal) { var cart = customer.ShoppingCartItems .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart) .LimitPerStore(_storeContext.CurrentStore.Id) .ToList(); var hasGiftCards = cart.Any(x => x.Product.IsGiftCard); if (hasGiftCards) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.CannotBeUsedWithGiftCards"); return result; } } //check date range DateTime now = DateTime.UtcNow; if (discount.StartDateUtc.HasValue) { DateTime startDate = DateTime.SpecifyKind(discount.StartDateUtc.Value, DateTimeKind.Utc); if (startDate.CompareTo(now) > 0) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.NotStartedYet"); return result; } } if (discount.EndDateUtc.HasValue) { DateTime endDate = DateTime.SpecifyKind(discount.EndDateUtc.Value, DateTimeKind.Utc); if (endDate.CompareTo(now) < 0) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.Expired"); return result; } } //discount limitation switch (discount.DiscountLimitation) { case DiscountLimitationType.NTimesOnly: { var usedTimes = GetAllDiscountUsageHistory(discount.Id, null, null, 0, 1).TotalCount; if (usedTimes >= discount.LimitationTimes) return result; } break; case DiscountLimitationType.NTimesPerCustomer: { if (customer.IsRegistered()) { var usedTimes = GetAllDiscountUsageHistory(discount.Id, customer.Id, null, 0, 1).TotalCount; if (usedTimes >= discount.LimitationTimes) { result.UserError = _localizationService.GetResource("ShoppingCart.Discount.CannotBeUsedAnymore"); return result; } } } break; case DiscountLimitationType.Unlimited: default: break; } //discount requirements //UNDONE we should inject static cache manager into constructor. we we already have "per request" cache manager injected. better way to do it? //we cache meta info of rdiscount requirements. this way we should not load them for each HTTP request var staticCacheManager = EngineContext.Current.ContainerManager.Resolve<ICacheManager>("nop_cache_static"); string key = string.Format(DiscountRequirementEventConsumer.DISCOUNT_REQUIREMENT_MODEL_KEY, discount.Id); //var requirements = discount.DiscountRequirements; var requirements = staticCacheManager.Get(key, () => { var cachedRequirements = new List<DiscountRequirementForCaching>(); foreach (var dr in discount.DiscountRequirements) cachedRequirements.Add(new DiscountRequirementForCaching { Id = dr.Id, SystemName = dr.DiscountRequirementRuleSystemName }); return cachedRequirements; }); foreach (var req in requirements) { //load a plugin var requirementRulePlugin = LoadDiscountRequirementRuleBySystemName(req.SystemName); if (requirementRulePlugin == null) continue; if (!_pluginFinder.AuthenticateStore(requirementRulePlugin.PluginDescriptor, _storeContext.CurrentStore.Id)) continue; var ruleRequest = new DiscountRequirementValidationRequest { DiscountRequirementId = req.Id, Customer = customer, Store = _storeContext.CurrentStore }; var ruleResult = requirementRulePlugin.CheckRequirement(ruleRequest); if (!ruleResult.IsValid) { result.UserError = ruleResult.UserError; return result; } } result.IsValid = true; return result; }
public static bool IsSeller(this Customer customer, bool onlyActiveCustomerRoles = true) { return(IsInCustomerRole(customer, SystemCustomerRoleNames.Sellers, onlyActiveCustomerRoles) && customer.IsRegistered()); }
protected virtual CustomerModel PrepareCustomerModelForList(Customer customer) { return new CustomerModel { Id = customer.Id, Email = customer.IsRegistered() ? customer.Email : _localizationService.GetResource("Admin.Customers.Guest"), }; }