public void Shipping_should_be_free_when_customer_is_in_role_with_free_shipping()
        {
            var product1 = new Product
            {
                Weight         = 1.5M,
                Height         = 2.5M,
                Length         = 3.5M,
                Width          = 4.5M,
                IsFreeShipping = false,
                IsShipEnabled  = true
            };

            _productService.InsertProduct(product1);

            var product2 = new Product
            {
                Weight         = 11.5M,
                Height         = 12.5M,
                Length         = 13.5M,
                Width          = 14.5M,
                IsFreeShipping = false,
                IsShipEnabled  = true
            };

            _productService.InsertProduct(product2);

            var sci1 = new ShoppingCartItem
            {
                AttributesXml = string.Empty,
                Quantity      = 3,
                ProductId     = product1.Id
            };
            var sci2 = new ShoppingCartItem
            {
                AttributesXml = string.Empty,
                Quantity      = 4,
                ProductId     = product2.Id
            };
            var cart = new List <ShoppingCartItem> {
                sci1, sci2
            };

            var customer = new Customer();

            _customerService.InsertCustomer(customer);

            var customerRole1 = _customerRoleRepository.GetById(1);
            var customerRole2 = _customerRoleRepository.GetById(2);

            _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                CustomerId = customer.Id, CustomerRoleId = customerRole1.Id
            });
            _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                CustomerId = customer.Id, CustomerRoleId = customerRole2.Id
            });

            cart.ForEach(sci => sci.CustomerId = customer.Id);

            _orderTotalCalcService.IsFreeShipping(cart).Should().BeTrue();
        }
Esempio n. 2
0
        private Customer CreateCustomer(PasswordFormat passwordFormat, bool isRegistered = true)
        {
            var customer = new Customer
            {
                Username = "******",
                Email = "*****@*****.**",
                Active = true
            };

            _customerService.InsertCustomer(customer);

            var password = "******";
            if (passwordFormat == PasswordFormat.Encrypted)
                password = _encryptionService.EncryptText(password);

            _customerService.InsertCustomerPassword(new CustomerPassword
            {
                CustomerId = customer.Id,
                PasswordFormat = passwordFormat,
                Password = password,
                CreatedOnUtc = DateTime.UtcNow
            });

            if (isRegistered)
                _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping
                {
                    CustomerId = customer.Id,
                    CustomerRoleId = _customerService
                        .GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName).Id
                });

            return customer;
        }
Esempio n. 3
0
        private void CustomerRoleMapping(Customer customer)
        {
            var _apiRole = CreateCustomerRole();

            if (!_customerService.IsInCustomerRole(customer, Constants.Roles.ApiRoleSystemName))
            {
                var _roleMapping = new CustomerCustomerRoleMapping()
                {
                    CustomerId     = customer.Id,
                    CustomerRoleId = _apiRole.Id
                };

                _customerService.AddCustomerRoleMapping(_roleMapping);
            }
        }
        private void MappingCustomersToRegisteredRole()
        {
            var regRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);

            regRole.Should().NotBeNull();
            var customers = _customerService.GetAllCustomers();

            customers.Should().NotBeNull();

            foreach (var customer in customers)
            {
                _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                    CustomerId = customer.Id, CustomerRoleId = regRole.Id
                });
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Permanent delete of customer
        /// </summary>
        /// <param name="customer">Customer</param>
        public virtual void PermanentDeleteCustomer(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            //blog comments
            var blogComments = _blogService.GetAllComments(customerId: customer.Id);

            _blogService.DeleteBlogComments(blogComments);

            //news comments
            var newsComments = _newsService.GetAllComments(customerId: customer.Id);

            _newsService.DeleteNewsComments(newsComments);

            //back in stock subscriptions
            var backInStockSubscriptions = _backInStockSubscriptionService.GetAllSubscriptionsByCustomerId(customer.Id);

            foreach (var backInStockSubscription in backInStockSubscriptions)
            {
                _backInStockSubscriptionService.DeleteSubscription(backInStockSubscription);
            }

            //product review
            var productReviews   = _productService.GetAllProductReviews(customer.Id);
            var reviewedProducts = _productService.GetProductsByIds(productReviews.Select(p => p.ProductId).Distinct().ToArray());

            _productService.DeleteProductReviews(productReviews);
            //update product totals
            foreach (var product in reviewedProducts)
            {
                _productService.UpdateProductReviewTotals(product);
            }

            //external authentication record
            foreach (var ear in _externalAuthenticationService.GetCustomerExternalAuthenticationRecords(customer))
            {
                _externalAuthenticationService.DeleteExternalAuthenticationRecord(ear);
            }

            //forum subscriptions
            var forumSubscriptions = _forumService.GetAllSubscriptions(customer.Id);

            foreach (var forumSubscription in forumSubscriptions)
            {
                _forumService.DeleteSubscription(forumSubscription);
            }

            //shopping cart items
            foreach (var sci in _shoppingCartService.GetShoppingCart(customer))
            {
                _shoppingCartService.DeleteShoppingCartItem(sci);
            }

            //private messages (sent)
            foreach (var pm in _forumService.GetAllPrivateMessages(0, customer.Id, 0, null, null, null, null))
            {
                _forumService.DeletePrivateMessage(pm);
            }

            //private messages (received)
            foreach (var pm in _forumService.GetAllPrivateMessages(0, 0, customer.Id, null, null, null, null))
            {
                _forumService.DeletePrivateMessage(pm);
            }

            //newsletter
            var allStores = _storeService.GetAllStores();

            foreach (var store in allStores)
            {
                var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id);
                if (newsletter != null)
                {
                    _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                }
            }

            //addresses
            foreach (var address in _customerService.GetAddressesByCustomerId(customer.Id))
            {
                _customerService.RemoveCustomerAddress(customer, address);
                _customerService.UpdateCustomer(customer);
                //now delete the address record
                _addressService.DeleteAddress(address);
            }

            //generic attributes
            var keyGroup          = customer.GetType().Name;
            var genericAttributes = _genericAttributeService.GetAttributesForEntity(customer.Id, keyGroup);

            _genericAttributeService.DeleteAttributes(genericAttributes);

            //ignore ActivityLog
            //ignore ForumPost, ForumTopic, ignore ForumPostVote
            //ignore Log
            //ignore PollVotingRecord
            //ignore ProductReviewHelpfulness
            //ignore RecurringPayment
            //ignore ReturnRequest
            //ignore RewardPointsHistory
            //and we do not delete orders

            //remove from Registered role, add to Guest one
            if (_customerService.IsRegistered(customer))
            {
                var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);
                _customerService.RemoveCustomerRoleMapping(customer, registeredRole);
            }

            if (!_customerService.IsGuest(customer))
            {
                var guestRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.GuestsRoleName);
                _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                    CustomerId = customer.Id, CustomerRoleId = guestRole.Id
                });
            }

            var email = customer.Email;

            //clear other information
            customer.Email             = string.Empty;
            customer.EmailToRevalidate = string.Empty;
            customer.Username          = string.Empty;
            customer.Active            = false;
            customer.Deleted           = true;
            _customerService.UpdateCustomer(customer);

            //raise event
            _eventPublisher.Publish(new CustomerPermanentlyDeleted(customer.Id, email));
        }
        /// <summary>
        /// Register customer
        /// </summary>
        /// <param name="request">Request</param>
        /// <returns>Result</returns>
        public virtual CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Customer == null)
            {
                throw new ArgumentException("Can't load current customer");
            }

            var result = new CustomerRegistrationResult();

            if (request.Customer.IsSearchEngineAccount())
            {
                result.AddError("Search engine can't be registered");
                return(result);
            }

            if (request.Customer.IsBackgroundTaskAccount())
            {
                result.AddError("Background task account can't be registered");
                return(result);
            }

            if (_customerService.IsRegistered(request.Customer))
            {
                result.AddError("Current customer is already registered");
                return(result);
            }

            if (string.IsNullOrEmpty(request.Email))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided"));
                return(result);
            }

            if (!CommonHelper.IsValidEmail(request.Email))
            {
                result.AddError(_localizationService.GetResource("Common.WrongEmail"));
                return(result);
            }

            if (string.IsNullOrWhiteSpace(request.Password))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided"));
                return(result);
            }

            if (_customerSettings.UsernamesEnabled && string.IsNullOrEmpty(request.Username))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided"));
                return(result);
            }

            //validate unique user
            if (_customerService.GetCustomerByEmail(request.Email) != null)
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailAlreadyExists"));
                return(result);
            }

            if (_customerSettings.UsernamesEnabled && _customerService.GetCustomerByUsername(request.Username) != null)
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists"));
                return(result);
            }

            //at this point request is valid
            request.Customer.Username = request.Username;
            request.Customer.Email    = request.Email;

            var customerPassword = new CustomerPassword
            {
                CustomerId     = request.Customer.Id,
                PasswordFormat = request.PasswordFormat,
                CreatedOnUtc   = DateTime.UtcNow
            };

            switch (request.PasswordFormat)
            {
            case PasswordFormat.Clear:
                customerPassword.Password = request.Password;
                break;

            case PasswordFormat.Encrypted:
                customerPassword.Password = _encryptionService.EncryptText(request.Password);
                break;

            case PasswordFormat.Hashed:
                var saltKey = _encryptionService.CreateSaltKey(NopCustomerServiceDefaults.PasswordSaltKeySize);
                customerPassword.PasswordSalt = saltKey;
                customerPassword.Password     = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);
                break;
            }

            _customerService.InsertCustomerPassword(customerPassword);

            request.Customer.Active = request.IsApproved;

            //add to 'Registered' role
            var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);

            if (registeredRole == null)
            {
                throw new NopException("'Registered' role could not be loaded");
            }

            _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                CustomerId = request.Customer.Id, CustomerRoleId = registeredRole.Id
            });

            //remove from 'Guests' role
            if (_customerService.IsGuest(request.Customer))
            {
                var guestRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.GuestsRoleName);
                _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                    CustomerId = request.Customer.Id, CustomerRoleId = guestRole.Id
                });
            }

            //add reward points for customer registration (if enabled)
            if (_rewardPointsSettings.Enabled && _rewardPointsSettings.PointsForRegistration > 0)
            {
                var endDate = _rewardPointsSettings.RegistrationPointsValidity > 0
                    ? (DateTime?)DateTime.UtcNow.AddDays(_rewardPointsSettings.RegistrationPointsValidity.Value) : null;
                _rewardPointService.AddRewardPointsHistoryEntry(request.Customer, _rewardPointsSettings.PointsForRegistration,
                                                                request.StoreId, _localizationService.GetResource("RewardPoints.Message.EarnedForRegistration"), endDate: endDate);
            }

            _customerService.UpdateCustomer(request.Customer);

            return(result);
        }
        /// <summary>
        /// Register customer
        /// </summary>
        /// <param name="request">Request</param>
        /// <returns>Errors if something goes wrong</returns>
        public virtual IEnumerable <string> RegisterCustomer(CustomerRegistrationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.Customer == null)
            {
                throw new ArgumentException("Can't load current customer");
            }

            var result      = new List <string>();
            var validations = new Dictionary <Func <bool>, string>()
            {
                { request.Customer.IsSearchEngineAccount, "Customer.RegisterCustomer.SearchEngineAccount.Validation" },
                { request.Customer.IsBackgroundTaskAccount, "Customer.RegisterCustomer.BackgroundTask.Validation" },
                {
                    () => _customerService.IsRegistered(request.Customer),
                    "Customer.RegisterCustomer.IsRegistered.Validation"
                },
            };

            foreach (var validation in validations.Where(validation => validation.Key.Invoke()))
            {
                result.Add(_localizationService.GetResource(validation.Value));
                return(result);
            }
            if (_customerSettings.UsernamesEnabled && string.IsNullOrEmpty(request.Customer?.Username))
            {
                result.Add(_localizationService.GetResource("Account.Register.Errors.UsernameIsNotProvided.Validation"));
                return(result);
            }

            //validate unique user
            if (_customerService.GetCustomerByEmail(request.Customer?.Email) != null)
            {
                result.Add(_localizationService.GetResource("Customer.RegisterCustomer.EmailAlreadyExist.Validation"));
                return(result);
            }

            if (_customerSettings.UsernamesEnabled && _customerService.GetCustomerByUsername(request.Customer.Username) != null)
            {
                result.Add(_localizationService.GetResource("Account.Register.Errors.UsernameAlreadyExists.Validation"));
                return(result);
            }
            var customerPassword = new CustomerPassword
            {
                CustomerId     = request.Customer.Id,
                PasswordFormat = request.PasswordFormat,
                CreatedOnUtc   = DateTime.UtcNow
            };

            switch (request.PasswordFormat)
            {
            case PasswordFormat.Clear:
                customerPassword.Password = request.Password;
                break;

            case PasswordFormat.Encrypted:
                customerPassword.Password = _encryptionService.EncryptText(request.Password);
                break;

            case PasswordFormat.Hashed:
                var saltKey = _encryptionService.CreateSaltKey(NopCustomerServicesDefaults.PasswordSaltKeySize);
                customerPassword.PasswordSalt = saltKey;
                customerPassword.Password     = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);
                break;
            }

            _customerService.InsertCustomer(request.Customer);
            _customerService.InsertCustomerPassword(customerPassword);

            //add to 'Registered' role
            var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);

            if (registeredRole == null)
            {
                throw new NopException("'Registered' role could not be loaded");
            }

            _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                CustomerId = request.Customer.Id, CustomerRoleId = registeredRole.Id
            });

            ////remove from 'Guests' role
            //if (_customerService.IsGuest(request.Customer))
            //{
            //    var guestRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.GuestsRoleName);
            //    _customerService.RemoveCustomerRoleMapping(request.Customer, guestRole);
            //}
            return(result);
        }
Esempio n. 8
0
        /// <summary>
        /// Register customer
        /// </summary>
        /// <param name="request">Request</param>
        /// <returns>Result</returns>
        public virtual CustomerRegistrationResult RegisterCustomer(CustomerRegistrationRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var result = new CustomerRegistrationResult();

            if (string.IsNullOrEmpty(request.Phone))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.EmailIsNotProvided"));
                return(result);
            }

            if (!CommonHelper.IsValidPhone(request.Phone))
            {
                result.AddError(_localizationService.GetResource("Common.WrongEmail"));
                return(result);
            }

            if (string.IsNullOrWhiteSpace(request.Password))
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.PasswordIsNotProvided"));
                return(result);
            }

            //validate unique user
            if (_customerService.GetCustomerByPhone(request.Phone) != null)
            {
                result.AddError(_localizationService.GetResource("Account.Register.Errors.PhoneAlreadyExists"));
                return(result);
            }


            _customerService.InsertCustomer(request.Customer);

            var customerPassword = new CustomerPassword
            {
                CustomerId     = request.Customer.Id,
                PasswordFormat = request.PasswordFormat,
                CreatedOnUtc   = DateTime.UtcNow
            };

            switch (request.PasswordFormat)
            {
            case PasswordFormat.Clear:
                customerPassword.Password = request.Password;
                break;

            case PasswordFormat.Encrypted:
                customerPassword.Password = _encryptionService.EncryptText(request.Password);
                break;

            case PasswordFormat.Hashed:
                var saltKey = _encryptionService.CreateSaltKey(BopCustomerServiceDefaults.PasswordSaltKeySize);
                customerPassword.PasswordSalt = saltKey;
                customerPassword.Password     = _encryptionService.CreatePasswordHash(request.Password, saltKey, _customerSettings.HashedPasswordFormat);
                break;
            }

            _customerService.InsertCustomerPassword(customerPassword);

            //add to 'Registered' role
            var registeredRole = _customerService.GetCustomerRoleBySystemName(BopCustomerDefaults.RegisteredRoleName);

            if (registeredRole == null)
            {
                throw new BopException("'Registered' role could not be loaded");
            }

            _customerService.AddCustomerRoleMapping(new CustomerCustomerRoleMapping {
                CustomerId = request.Customer.Id, CustomerRoleId = registeredRole.Id
            });

            return(result);
        }