Example #1
0
        public void DeleteSelectedList(IList <int> selectedIds)
        {
            var customers = new List <Customer>();

            customers.AddRange(_customerService.GetCustomersByIds(selectedIds.ToArray()));
            for (var i = 0; i < customers.Count; i++)
            {
                var customer = customers[i];
                if (_customerService.IsAdmin(customer))
                {
                    _notificationService.ErrorNotification(_localizationService.GetResource("Admin.ClearCustomerList.DeleteAdministrator"));
                    return;
                }
                if (customer.Id != _workContext.CurrentCustomer.Id)
                {
                    _customerService.DeleteCustomer(customer);
                }

                //activity log
                _customerActivityService.InsertActivity("DeleteCustomer",
                                                        string.Format(_localizationService.GetResource("ActivityLog.DeleteCustomer"), customer.Id), customer);

                //remove newsletter subscription (if exists)
                foreach (var store in _storeService.GetAllStores())
                {
                    var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id);
                    if (subscription != null)
                    {
                        _newsLetterSubscriptionService.DeleteNewsLetterSubscription(subscription);
                    }
                }
            }
        }
        public IActionResult DeleteCustomer(int id)
        {
            if (id <= 0)
            {
                return(Error(HttpStatusCode.BadRequest, "id", "invalid id"));
            }

            var customer = _customerApiService.GetCustomerEntityById(id);

            if (customer == null)
            {
                return(Error(HttpStatusCode.NotFound, "customer", "not found"));
            }

            CustomerService.DeleteCustomer(customer);

            //remove newsletter subscription (if exists)
            foreach (var store in StoreService.GetAllStores())
            {
                var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id);
                if (subscription != null)
                {
                    _newsLetterSubscriptionService.DeleteNewsLetterSubscription(subscription);
                }
            }

            //activity log
            CustomerActivityService.InsertActivity("DeleteCustomer", LocalizationService.GetResource("ActivityLog.DeleteCustomer"), customer);

            return(new RawJsonActionResult("{}"));
        }
Example #3
0
        public ActionResult SendTestEmail(CampaignModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCampaigns))
            {
                return(AccessDeniedView());
            }

            var campaign = _campaignService.GetCampaignById(model.Id);

            if (campaign == null)
            {
                //No campaign found with the specified id
                return(RedirectToAction("List"));
            }


            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfCampaignAllowedTokens());
            //stores
            PrepareStoresModel(model);
            //Tags
            PrepareCustomerTagsModel(model);
            //email
            PrepareEmailAccounts(model);

            try
            {
                var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
                if (emailAccount == null)
                {
                    throw new NopException("Email account could not be loaded");
                }


                var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.TestEmail, _storeContext.CurrentStore.Id);
                if (subscription != null)
                {
                    //there's a subscription. let's use it
                    var subscriptions = new List <NewsLetterSubscription>();
                    subscriptions.Add(subscription);
                    _campaignService.SendCampaign(campaign, emailAccount, subscriptions);
                }
                else
                {
                    //no subscription found
                    _campaignService.SendCampaign(campaign, emailAccount, model.TestEmail);
                }

                SuccessNotification(_localizationService.GetResource("Admin.Promotions.Campaigns.TestEmailSentToCustomers"), false);
                return(View(model));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc, false);
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #4
0
        public virtual IActionResult SendTestEmail(CampaignModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCampaigns))
            {
                return(AccessDeniedView());
            }

            //try to get a campaign with the specified id
            var campaign = _campaignService.GetCampaignById(model.Id);

            if (campaign == null)
            {
                return(RedirectToAction("List"));
            }

            //prepare model
            model = _campaignModelFactory.PrepareCampaignModel(model, campaign);

            //ensure that the entered email is valid
            if (!CommonHelper.IsValidEmail(model.TestEmail))
            {
                ErrorNotification(_localizationService.GetResource("Admin.Common.WrongEmail"), false);
                return(View(model));
            }

            try
            {
                var emailAccount = GetEmailAccount(model.EmailAccountId);
                var subscription = _newsLetterSubscriptionService
                                   .GetNewsLetterSubscriptionByEmailAndStoreId(model.TestEmail, _storeContext.CurrentStore.Id);
                if (subscription != null)
                {
                    //there's a subscription. let's use it
                    _campaignService.SendCampaign(campaign, emailAccount, new List <NewsLetterSubscription> {
                        subscription
                    });
                }
                else
                {
                    //no subscription found
                    _campaignService.SendCampaign(campaign, emailAccount, model.TestEmail);
                }

                SuccessNotification(_localizationService.GetResource("Admin.Promotions.Campaigns.TestEmailSentToCustomers"), false);

                return(View(model));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc, false);
            }

            //prepare model
            model = _campaignModelFactory.PrepareCampaignModel(model, campaign, true);

            //if we got this far, something failed, redisplay form
            return(View(model));
        }
        public virtual IActionResult SendTestEmail(CampaignModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCampaigns))
            {
                return(AccessDeniedView());
            }

            var campaign = _campaignService.GetCampaignById(model.Id);

            if (campaign == null)
            {
                //No campaign found with the specified id
                return(RedirectToAction("List"));
            }

            model.AllowedTokens = string.Join(", ", _messageTokenProvider.GetListOfCampaignAllowedTokens());
            //stores
            PrepareStoresModel(model);
            //customer roles
            PrepareCustomerRolesModel(model);
            //email accounts
            PrepareEmailAccountsModel(model);

            if (!CommonHelper.IsValidEmail(model.TestEmail))
            {
                ErrorNotification(_localizationService.GetResource("Admin.Common.WrongEmail"), false);
                return(View(model));
            }

            try
            {
                var emailAccount = GetEmailAccount(model.EmailAccountId);
                var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.TestEmail, _storeContext.CurrentStore.Id);
                if (subscription != null)
                {
                    //there's a subscription. let's use it
                    var subscriptions = new List <NewsLetterSubscription>();
                    subscriptions.Add(subscription);
                    _campaignService.SendCampaign(campaign, emailAccount, subscriptions);
                }
                else
                {
                    //no subscription found
                    _campaignService.SendCampaign(campaign, emailAccount, model.TestEmail);
                }

                SuccessNotification(_localizationService.GetResource("Admin.Promotions.Campaigns.TestEmailSentToCustomers"), false);
                return(View(model));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc, false);
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
        public virtual (bool Success, string Result) SubscribeNewsletter(string email, bool subscribe)
        {
            string result;
            var    success = false;

            if (!CommonHelper.IsValidEmail(email))
            {
                result = _localizationService.GetResource("Newsletter.Email.Wrong");
            }
            else
            {
                email = email.Trim();

                var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, _storeContext.CurrentStore.Id);
                if (subscription != null)
                {
                    if (subscribe)
                    {
                        if (!subscription.Active)
                        {
                            _workflowMessageService.SendNewsLetterSubscriptionActivationMessage(subscription, _workContext.WorkingLanguage.Id);
                        }
                        result = _localizationService.GetResource("Newsletter.SubscribeEmailSent");
                    }
                    else
                    {
                        if (subscription.Active)
                        {
                            _workflowMessageService.SendNewsLetterSubscriptionDeactivationMessage(subscription, _workContext.WorkingLanguage.Id);
                        }
                        result = _localizationService.GetResource("Newsletter.UnsubscribeEmailSent");
                    }
                }
                else if (subscribe)
                {
                    subscription = new NewsLetterSubscription
                    {
                        NewsLetterSubscriptionGuid = Guid.NewGuid(),
                        Email        = email,
                        Active       = false,
                        StoreId      = _storeContext.CurrentStore.Id,
                        CreatedOnUtc = DateTime.UtcNow
                    };
                    _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
                    _workflowMessageService.SendNewsLetterSubscriptionActivationMessage(subscription, _workContext.WorkingLanguage.Id);

                    result = _localizationService.GetResource("Newsletter.SubscribeEmailSent");
                }
                else
                {
                    result = _localizationService.GetResource("Newsletter.UnsubscribeEmailSent");
                }
                success = true;
            }

            return(Success : success, Result : result);
        }
Example #7
0
        public virtual async Task DeleteAccount(Customer customer)
        {
            //send notification to customer
            await _workflowMessageService.SendCustomerDeleteStoreOwnerNotification(customer, _serviceProvider.GetRequiredService <LocalizationSettings>().DefaultAdminLanguageId);

            //delete emails
            await _serviceProvider.GetRequiredService <IQueuedEmailService>().DeleteCustomerEmail(customer.Email);

            //delete newsletter subscription
            var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id);

            if (newsletter != null)
            {
                await _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
            }

            //delete account
            await _serviceProvider.GetRequiredService <ICustomerService>().DeleteCustomer(customer);
        }
        public virtual void DeleteAccount(Customer customer)
        {
            //send notification to customer
            _workflowMessageService.SendCustomerDeleteStoreOwnerNotification(customer, EngineContext.Current.Resolve <LocalizationSettings>().DefaultAdminLanguageId);

            //delete emails
            EngineContext.Current.Resolve <IQueuedEmailService>().DeleteCustomerEmail(customer.Email);

            //delete newsletter subscription
            var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id);

            if (newsletter != null)
            {
                _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
            }

            //delete account
            EngineContext.Current.Resolve <ICustomerService>().DeleteCustomer(customer);
        }
        private async Task UpdateNewsletter(UpdateCustomerInfoCommand request)
        {
            var categories = new List <string>();

            foreach (string formKey in request.Form.Keys)
            {
                if (formKey.Contains("customernewsletterCategory_"))
                {
                    try
                    {
                        var category = formKey.Split('_')[1];
                        categories.Add(category);
                    }
                    catch { }
                }
            }
            //save newsletter value
            var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(request.Customer.Email, request.Store.Id);

            if (newsletter != null)
            {
                newsletter.Categories.Clear();
                categories.ForEach(x => newsletter.Categories.Add(x));

                if (request.Model.Newsletter)
                {
                    newsletter.Active = true;
                    await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                }
                else
                {
                    newsletter.Active = false;
                    await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                }
            }
            else
            {
                if (request.Model.Newsletter)
                {
                    var newsLetterSubscription = new NewsLetterSubscription
                    {
                        NewsLetterSubscriptionGuid = Guid.NewGuid(),
                        Email        = request.Customer.Email,
                        CustomerId   = request.Customer.Id,
                        Active       = true,
                        StoreId      = request.Store.Id,
                        CreatedOnUtc = DateTime.UtcNow
                    };
                    categories.ForEach(x => newsLetterSubscription.Categories.Add(x));
                    await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
                }
            }
        }
Example #10
0
        /// <summary>
        /// Sets a user email
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="newEmail">New email</param>
        public virtual async Task SetEmail(Customer customer, string newEmail)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            if (newEmail == null)
            {
                throw new GrandException("Email cannot be null");
            }

            newEmail = newEmail.Trim();
            string oldEmail = customer.Email;

            if (!CommonHelper.IsValidEmail(newEmail))
            {
                throw new GrandException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));
            }

            if (newEmail.Length > 100)
            {
                throw new GrandException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));
            }

            var customer2 = await _customerService.GetCustomerByEmail(newEmail);

            if (customer2 != null && customer.Id != customer2.Id)
            {
                throw new GrandException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));
            }

            customer.Email = newEmail;
            await _customerService.UpdateCustomer(customer);

            //update newsletter subscription (if required)
            if (!String.IsNullOrEmpty(oldEmail) && !oldEmail.Equals(newEmail, StringComparison.OrdinalIgnoreCase))
            {
                foreach (var store in await _storeService.GetAllStores())
                {
                    var subscriptionOld = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(oldEmail, store.Id);

                    if (subscriptionOld != null)
                    {
                        subscriptionOld.Email = newEmail;
                        await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);
                    }
                }
            }
        }
Example #11
0
        public async Task <IActionResult> SendTestEmail(CampaignModel model)
        {
            var campaign = await _campaignService.GetCampaignById(model.Id);

            if (campaign == null)
            {
                //No campaign found with the specified id
                return(RedirectToAction("List"));
            }

            model = await _campaignViewModelService.PrepareCampaignModel(model);

            try
            {
                var emailAccount = await _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);

                if (emailAccount == null)
                {
                    throw new GrandException("Email account could not be loaded");
                }

                var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.TestEmail, _workContext.CurrentStore.Id);

                if (subscription != null)
                {
                    //there's a subscription. use it
                    var subscriptions = new List <NewsLetterSubscription>
                    {
                        subscription
                    };
                    await _campaignService.SendCampaign(campaign, emailAccount, subscriptions);
                }
                else
                {
                    //no subscription found
                    await _campaignService.SendCampaign(campaign, emailAccount, model.TestEmail);
                }

                Success(_translationService.GetResource("admin.marketing.Campaigns.TestEmailSentToCustomers"), false);
                return(RedirectToAction("Edit", new { id = campaign.Id }));
            }
            catch (Exception exc)
            {
                Error(exc, false);
            }

            //If we got this far, something failed, redisplay form
            return(RedirectToAction("Edit", new { id = campaign.Id }));
        }
        public IActionResult SendTestEmail(CampaignModel model)
        {
            var campaign = _campaignService.GetCampaignById(model.Id);

            if (campaign == null)
            {
                //No campaign found with the specified id
                return(RedirectToAction("List"));
            }

            model = _campaignViewModelService.PrepareCampaignModel(model);
            try
            {
                var emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
                if (emailAccount == null)
                {
                    throw new GrandException("Email account could not be loaded");
                }


                var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.TestEmail, _storeContext.CurrentStore.Id);
                if (subscription != null)
                {
                    //there's a subscription. let's use it
                    var subscriptions = new List <NewsLetterSubscription>();
                    subscriptions.Add(subscription);
                    _campaignService.SendCampaign(campaign, emailAccount, subscriptions);
                }
                else
                {
                    //no subscription found
                    _campaignService.SendCampaign(campaign, emailAccount, model.TestEmail);
                }

                SuccessNotification(_localizationService.GetResource("Admin.Promotions.Campaigns.TestEmailSentToCustomers"), false);
                return(View(model));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc, false);
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
        public IActionResult DeactivateNewsLetterSubscription(string email)
        {
            if (string.IsNullOrEmpty(email))
            {
                return(Error(HttpStatusCode.BadRequest, "The email parameter could not be empty."));
            }

            var existingSubscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, _storeContext.CurrentStore.Id);

            if (existingSubscription == null)
            {
                return(Error(HttpStatusCode.BadRequest, "There is no news letter subscription with the specified email."));
            }

            existingSubscription.Active = false;

            _newsLetterSubscriptionService.UpdateNewsLetterSubscription(existingSubscription);

            return(Ok());
        }
Example #14
0
        public async Task <bool> Handle(DeleteAccountCommand request, CancellationToken cancellationToken)
        {
            //send notification to customer
            await _workflowMessageService.SendCustomerDeleteStoreOwnerNotification(request.Customer, _localizationSettings.DefaultAdminLanguageId);

            //delete emails
            await _queuedEmailService.DeleteCustomerEmail(request.Customer.Email);

            //delete newsletter subscription
            var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(request.Customer.Email, request.Store.Id);

            if (newsletter != null)
            {
                await _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
            }

            //delete account
            await _customerService.DeleteCustomer(request.Customer);

            return(true);
        }
Example #15
0
        private async Task PrepareNewsletter(CustomerInfoModel model, GetInfo request)
        {
            //newsletter
            var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(request.Customer.Email, request.Store.Id);

            //TODO - it is necessary ?
            //if (newsletter == null)
            //    newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByCustomerId(request.Customer.Id);

            model.Newsletter = newsletter != null && newsletter.Active;

            var categories = (await _newsletterCategoryService.GetAllNewsletterCategory()).ToList();

            categories.ForEach(x => model.NewsletterCategories.Add(new NewsletterSimpleCategory()
            {
                Id          = x.Id,
                Description = x.GetTranslation(y => y.Description, request.Language.Id),
                Name        = x.GetTranslation(y => y.Name, request.Language.Id),
                Selected    = newsletter == null ? false : newsletter.Categories.Contains(x.Id),
            }));
        }
        /// <summary>
        /// Delete unsubscribed user (in SendInBlue) from nopCommerce subscription list
        /// </summary>
        /// <param name="unsubscriberUser">User information</param>
        public void UnsubscribeWebhook(string unsubscriberUser)
        {
            if (!IsConfigured)
            {
                return;
            }

            //parse string to JSON object
            dynamic unsubscriber = JObject.Parse(unsubscriberUser);

            //we pass the store identifier in the X-Mailin-Tag at sending emails, now get it here
            int storeId;

            if (!int.TryParse(unsubscriber.tag, out storeId))
            {
                return;
            }

            var store = _storeService.GetStoreById(storeId);

            if (store == null)
            {
                return;
            }

            //get subscription by email and store identifier
            var email        = (string)unsubscriber.email;
            var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, store.Id);

            if (subscription != null)
            {
                //delete subscription
                _newsLetterSubscriptionService.DeleteNewsLetterSubscription(subscription, false);
                _logger.Information(string.Format("SendInBlue unsubscription: email {0}, store {1}, date {2}",
                                                  email, store.Name, (string)unsubscriber.date_event));
            }
        }
        public async Task <bool> Handle(DeleteAccountCommand request, CancellationToken cancellationToken)
        {
            //activity log
            await _customerActivityService.InsertActivity("PublicStore.DeleteAccount", "", _translationService.GetResource("ActivityLog.DeleteAccount"), request.Customer);

            //send notification to customer
            await _messageProviderService.SendCustomerDeleteStoreOwnerMessage(request.Customer, _languageSettings.DefaultAdminLanguageId);

            //delete emails
            await _queuedEmailService.DeleteCustomerEmail(request.Customer.Email);

            //delete newsletter subscription
            var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(request.Customer.Email, request.Store.Id);

            if (newsletter != null)
            {
                await _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
            }

            //delete account
            await _customerService.DeleteCustomer(request.Customer);

            return(true);
        }
        public virtual async Task <SubscribeNewsletterResultModel> SubscribeNewsletter(string email, bool subscribe)
        {
            var model = new SubscribeNewsletterResultModel();

            if (!CommonHelper.IsValidEmail(email))
            {
                model.Result = _localizationService.GetResource("Newsletter.Email.Wrong");
            }
            else
            {
                email = email.Trim();

                var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, _storeContext.CurrentStore.Id);

                if (subscription != null)
                {
                    if (subscribe)
                    {
                        if (!subscription.Active)
                        {
                            await _workflowMessageService.SendNewsLetterSubscriptionActivationMessage(subscription, _workContext.WorkingLanguage.Id);
                        }
                        model.Result = _localizationService.GetResource("Newsletter.SubscribeEmailSent");
                    }
                    else
                    {
                        if (subscription.Active)
                        {
                            await _workflowMessageService.SendNewsLetterSubscriptionDeactivationMessage(subscription, _workContext.WorkingLanguage.Id);
                        }
                        model.Result = _localizationService.GetResource("Newsletter.UnsubscribeEmailSent");
                    }
                }
                else if (subscribe)
                {
                    subscription = new NewsLetterSubscription
                    {
                        NewsLetterSubscriptionGuid = Guid.NewGuid(),
                        Email        = email,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        Active       = false,
                        StoreId      = _storeContext.CurrentStore.Id,
                        CreatedOnUtc = DateTime.UtcNow
                    };
                    await _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);

                    await _workflowMessageService.SendNewsLetterSubscriptionActivationMessage(subscription, _workContext.WorkingLanguage.Id);

                    model.Result = _localizationService.GetResource("Newsletter.SubscribeEmailSent");
                    var modelCategory = await PrepareNewsletterCategory(subscription.Id);

                    if (modelCategory.NewsletterCategories.Count > 0)
                    {
                        model.NewsletterCategory = modelCategory;
                    }
                }
                else
                {
                    model.Result = _localizationService.GetResource("Newsletter.UnsubscribeEmailSent");
                }
                model.Success = true;
            }

            return(model);
        }
Example #19
0
        public ActionResult ImportCsv(FormCollection form)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            try
            {
                var file = Request.Files["importcsvfile"];
                if (file != null && file.ContentLength > 0)
                {
                    int count = 0;

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

                            var  email    = "";
                            bool isActive = true;
                            int  storeId  = _storeContext.CurrentStore.Id;
                            //parse
                            if (tmp.Length == 1)
                            {
                                //"email" only
                                email = tmp[0].Trim();
                            }
                            else if (tmp.Length == 2)
                            {
                                //"email" and "active" fields specified
                                email    = tmp[0].Trim();
                                isActive = Boolean.Parse(tmp[1].Trim());
                            }
                            else if (tmp.Length == 3)
                            {
                                //"email" and "active" and "storeId" fields specified
                                email    = tmp[0].Trim();
                                isActive = Boolean.Parse(tmp[1].Trim());
                                storeId  = Int32.Parse(tmp[2].Trim());
                            }
                            else
                            {
                                throw new NopException("Wrong file format");
                            }

                            //import
                            var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);
                            if (subscription != null)
                            {
                                subscription.Email  = email;
                                subscription.Active = isActive;
                                _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
                            }
                            else
                            {
                                subscription = new NewsLetterSubscription()
                                {
                                    Active       = isActive,
                                    CreatedOnUtc = DateTime.UtcNow,
                                    Email        = email,
                                    StoreId      = storeId,
                                    NewsLetterSubscriptionGuid = Guid.NewGuid()
                                };
                                _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
                            }
                            count++;
                        }
                        SuccessNotification(String.Format(_localizationService.GetResource("Admin.Promotions.NewsLetterSubscriptions.ImportEmailsSuccess"), count));
                        return(RedirectToAction("List"));
                    }
                }
                ErrorNotification(_localizationService.GetResource("Admin.Common.UploadFile"));
                return(RedirectToAction("List"));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc);
                return(RedirectToAction("List"));
            }
        }
Example #20
0
        public virtual ActionResult Register(PaaMember member, string returnUrl, bool captchaValid, FormCollection form)
        {
            RegisterModel model = null;// = member.RegisterModel;



            //check whether registration is allowed
            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }

            if (_workContext.CurrentCustomer.IsRegistered())
            {
                //Already registered customer.
                _authenticationService.SignOut();

                //raise logged out event
                _eventPublisher.Publish(new CustomerLoggedOutEvent(_workContext.CurrentCustomer));

                //Save a new record
                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
            }
            var customer = _workContext.CurrentCustomer;

            customer.RegisteredInStoreId = _storeContext.CurrentStore.Id;

            //custom customer attributes
            var customerAttributesXml     = ParseCustomCustomerAttributes(form);
            var customerAttributeWarnings = _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);

            foreach (var error in customerAttributeWarnings)
            {
                ModelState.AddModelError("", error);
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
            {
                ModelState.AddModelError("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
            }

            if (ModelState.IsValid)
            {
                if (_customerSettings.UsernamesEnabled && model.Username != null)
                {
                    model.Username = model.Username.Trim();
                }

                bool isApproved          = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                var  registrationRequest = new CustomerRegistrationRequest(customer,
                                                                           model.Email,
                                                                           _customerSettings.UsernamesEnabled ? model.Username : model.Email,
                                                                           model.Password,
                                                                           _customerSettings.DefaultPasswordFormat,
                                                                           _storeContext.CurrentStore.Id,
                                                                           isApproved);
                var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                if (registrationResult.Success)
                {
                    //properties
                    if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                    }
                    //VAT number
                    if (_taxSettings.EuVatEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber);

                        string vatName;
                        string vatAddress;
                        var    vatNumberStatus = _taxService.GetVatNumberStatus(model.VatNumber, out vatName,
                                                                                out vatAddress);
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumberStatusId, (int)vatNumberStatus);
                        //send VAT number admin notification
                        if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                        {
                            _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vatAddress, _localizationSettings.DefaultAdminLanguageId);
                        }
                    }

                    //form fields
                    if (_customerSettings.GenderEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                    }
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                    if (_customerSettings.DateOfBirthEnabled)
                    {
                        //                       DateTime? dateOfBirth = model.ParseDateOfBirth();
                        //                       _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
                    }
                    if (_customerSettings.CompanyEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
                    }
                    if (_customerSettings.StreetAddressEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress);
                    }
                    if (_customerSettings.StreetAddress2Enabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2);
                    }
                    if (_customerSettings.ZipPostalCodeEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode);
                    }
                    if (_customerSettings.CityEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City);
                    }
                    if (_customerSettings.CountryEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
                    }
                    if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId,
                                                               model.StateProvinceId);
                    }
                    if (_customerSettings.PhoneEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                    }
                    if (_customerSettings.FaxEnabled)
                    {
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax);
                    }

                    //newsletter
                    if (_customerSettings.NewsletterEnabled)
                    {
                        //save newsletter value
                        var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.Email, _storeContext.CurrentStore.Id);
                        if (newsletter != null)
                        {
                            if (model.Newsletter)
                            {
                                newsletter.Active = true;
                                _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                            }
                            //else
                            //{
                            //When registering, not checking the newsletter check box should not take an existing email address off of the subscription list.
                            //_newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                            //}
                        }
                        else
                        {
                            if (model.Newsletter)
                            {
                                _newsLetterSubscriptionService.InsertNewsLetterSubscription(new NewsLetterSubscription
                                {
                                    NewsLetterSubscriptionGuid = Guid.NewGuid(),
                                    Email        = model.Email,
                                    Active       = true,
                                    StoreId      = _storeContext.CurrentStore.Id,
                                    CreatedOnUtc = DateTime.UtcNow
                                });
                            }
                        }
                    }

                    //save customer attributes
                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributesXml);

                    //login customer now
                    if (isApproved)
                    {
                        _authenticationService.SignIn(customer, true);
                    }

                    //associated with external account (if possible)
                    TryAssociateAccountWithExternalAccount(customer);

                    //insert default address (if possible)
                    var defaultAddress = new Address
                    {
                        FirstName = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName),
                        LastName  = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName),
                        Email     = customer.Email,
                        Company   = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company),
                        CountryId = customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId) > 0
                            ? (int?)customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId)
                            : null,
                        StateProvinceId = customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId) > 0
                            ? (int?)customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId)
                            : null,
                        City          = customer.GetAttribute <string>(SystemCustomerAttributeNames.City),
                        Address1      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress),
                        Address2      = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2),
                        ZipPostalCode = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode),
                        PhoneNumber   = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone),
                        FaxNumber     = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax),
                        CreatedOnUtc  = customer.CreatedOnUtc
                    };
                    if (this._addressService.IsAddressValid(defaultAddress))
                    {
                        //some validation
                        if (defaultAddress.CountryId == 0)
                        {
                            defaultAddress.CountryId = null;
                        }
                        if (defaultAddress.StateProvinceId == 0)
                        {
                            defaultAddress.StateProvinceId = null;
                        }
                        //set default address
                        customer.Addresses.Add(defaultAddress);
                        customer.BillingAddress  = defaultAddress;
                        customer.ShippingAddress = defaultAddress;
                        _customerService.UpdateCustomer(customer);
                    }

                    //notifications
                    if (_customerSettings.NotifyNewCustomerRegistration)
                    {
                        _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer,
                                                                                          _localizationSettings.DefaultAdminLanguageId);
                    }

                    //raise event
                    _eventPublisher.Publish(new CustomerRegisteredEvent(customer));

                    switch (_customerSettings.UserRegistrationType)
                    {
                    case UserRegistrationType.EmailValidation:
                    {
                        //email validation message
                        _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                        _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                        //result
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.EmailValidation }));
                    }

                    case UserRegistrationType.AdminApproval:
                    {
                        return(RedirectToRoute("RegisterResult",
                                               new { resultId = (int)UserRegistrationType.AdminApproval }));
                    }

                    case UserRegistrationType.Standard:
                    {
                        //send customer welcome message
                        _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                        var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                        if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                        }
                        return(Redirect(redirectUrl));
                    }

                    default:
                    {
                        return(RedirectToRoute("HomePage"));
                    }
                    }
                }

                //errors
                foreach (var error in registrationResult.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            //If we got this far, something failed, redisplay form

            //           model = _customerModelFactory.PrepareRegisterModel( model, true, customerAttributesXml);
            //           return View("PaidMemberShip" , model);

            return(null);
        }
Example #21
0
        public async Task <bool> Handle(CustomerRegisteredCommand request, CancellationToken cancellationToken)
        {
            //properties
            if (_dateTimeSettings.AllowCustomersToSetTimeZone)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.TimeZoneId, request.Model.TimeZoneId);
            }
            //VAT number
            if (_taxSettings.EuVatEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.VatNumber, request.Model.VatNumber);

                var vat = await _checkVatService.GetVatNumberStatus(request.Model.VatNumber);

                await _genericAttributeService.SaveAttribute(request.Customer,
                                                             SystemCustomerAttributeNames.VatNumberStatusId,
                                                             (int)vat.status);

                //send VAT number admin notification
                if (!String.IsNullOrEmpty(request.Model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                {
                    await _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(request.Customer, request.Store, request.Model.VatNumber, vat.address, _localizationSettings.DefaultAdminLanguageId);
                }
            }

            //form fields
            if (_customerSettings.GenderEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.Gender, request.Model.Gender);
            }
            await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.FirstName, request.Model.FirstName);

            await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.LastName, request.Model.LastName);

            if (_customerSettings.DateOfBirthEnabled)
            {
                DateTime?dateOfBirth = request.Model.ParseDateOfBirth();
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
            }
            if (_customerSettings.CompanyEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.Company, request.Model.Company);
            }
            if (_customerSettings.StreetAddressEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.StreetAddress, request.Model.StreetAddress);
            }
            if (_customerSettings.StreetAddress2Enabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.StreetAddress2, request.Model.StreetAddress2);
            }
            if (_customerSettings.ZipPostalCodeEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.ZipPostalCode, request.Model.ZipPostalCode);
            }
            if (_customerSettings.CityEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.City, request.Model.City);
            }
            if (_customerSettings.CountryEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.CountryId, request.Model.CountryId);
            }
            if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.StateProvinceId, request.Model.StateProvinceId);
            }
            if (_customerSettings.PhoneEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.Phone, request.Model.Phone);
            }
            if (_customerSettings.FaxEnabled)
            {
                await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.Fax, request.Model.Fax);
            }

            //newsletter
            if (_customerSettings.NewsletterEnabled)
            {
                var categories = new List <string>();
                foreach (string formKey in request.Form.Keys)
                {
                    if (formKey.Contains("customernewsletterCategory_"))
                    {
                        try
                        {
                            var category = formKey.Split('_')[1];
                            categories.Add(category);
                        }
                        catch { }
                    }
                }

                //save newsletter value
                var newsletter = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(request.Model.Email, request.Store.Id);

                if (newsletter != null)
                {
                    newsletter.Categories.Clear();
                    categories.ForEach(x => newsletter.Categories.Add(x));
                    if (request.Model.Newsletter)
                    {
                        newsletter.Active = true;
                        await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                    }
                }
                else
                {
                    if (request.Model.Newsletter)
                    {
                        var newsLetterSubscription = new NewsLetterSubscription {
                            NewsLetterSubscriptionGuid = Guid.NewGuid(),
                            Email        = request.Model.Email,
                            CustomerId   = request.Customer.Id,
                            Active       = true,
                            StoreId      = request.Store.Id,
                            CreatedOnUtc = DateTime.UtcNow
                        };
                        categories.ForEach(x => newsLetterSubscription.Categories.Add(x));
                        await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
                    }
                }
            }

            //save customer attributes
            await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.CustomCustomerAttributes, request.CustomerAttributesXml);

            //insert default address (if possible)
            var defaultAddress = new Address {
                FirstName = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.FirstName),
                LastName  = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.LastName),
                Email     = request.Customer.Email,
                Company   = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.Company),
                VatNumber = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.VatNumber),
                CountryId = !string.IsNullOrEmpty(request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.CountryId)) ?
                            request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.CountryId) : "",
                StateProvinceId = !string.IsNullOrEmpty(request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.StateProvinceId)) ?
                                  request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.StateProvinceId) : "",
                City          = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.City),
                Address1      = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.StreetAddress),
                Address2      = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.StreetAddress2),
                ZipPostalCode = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.ZipPostalCode),
                PhoneNumber   = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.Phone),
                FaxNumber     = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.Fax),
                CreatedOnUtc  = request.Customer.CreatedOnUtc,
            };

            if (await _addressService.IsAddressValid(defaultAddress))
            {
                //set default address
                defaultAddress.CustomerId = request.Customer.Id;
                request.Customer.Addresses.Add(defaultAddress);
                await _customerService.InsertAddress(defaultAddress);

                request.Customer.BillingAddress = defaultAddress;
                await _customerService.UpdateBillingAddress(defaultAddress);

                request.Customer.ShippingAddress = defaultAddress;
                await _customerService.UpdateShippingAddress(defaultAddress);
            }

            //notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                await _workflowMessageService.SendCustomerRegisteredNotificationMessage(request.Customer, request.Store, _localizationSettings.DefaultAdminLanguageId);
            }

            //New customer has a free shipping for the first order
            if (_customerSettings.RegistrationFreeShipping)
            {
                await _customerService.UpdateFreeShipping(request.Customer.Id, true);
            }

            await _customerActionEventService.Registration(request.Customer);

            return(true);
        }
Example #22
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);



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

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

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


            //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 customer.Addresses)
            {
                _customerService.RemoveCustomerAddress(customer, address);
                _customerService.UpdateCustomer(customer);
                //now delete the address record
                _addressService.DeleteAddress(address);
            }

            //generic attributes
            var keyGroup          = customer.GetUnproxiedEntityType().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 (customer.IsRegistered())
            {
                var registeredRole = _customerService.GetCustomerRoleBySystemName(GSCustomerDefaults.RegisteredRoleName);
                customer.CustomerCustomerRoleMappings
                .Remove(customer.CustomerCustomerRoleMappings.FirstOrDefault(mapping => mapping.CustomerRoleId == registeredRole.Id));
            }

            if (!customer.IsGuest())
            {
                var guestRole = _customerService.GetCustomerRoleBySystemName(GSCustomerDefaults.GuestsRoleName);
                customer.CustomerCustomerRoleMappings.Add(new CustomerCustomerRoleMapping {
                    CustomerRole = guestRole
                });
            }

            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));
        }
Example #23
0
 /// <summary>
 /// Gets a newsletter subscription by email and store ID
 /// </summary>
 /// <param name="email">The newsletter subscription email</param>
 /// <param name="storeId">Store identifier</param>
 /// <returns>NewsLetter subscription</returns>
 public NewsLetterSubscription GetNewsLetterSubscriptionByEmailAndStoreId(string email, int storeId)
 {
     return(_newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId));
 }
Example #24
0
        /// <summary>
        /// Sets a user email
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="newEmail">New email</param>
        /// <param name="requireValidation">Require validation of new email address</param>
        public virtual void SetEmail(Customer customer, string newEmail, bool requireValidation)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (newEmail == null)
            {
                throw new QNetException("Email cannot be null");
            }

            newEmail = newEmail.Trim();
            var oldEmail = customer.Email;

            if (!CommonHelper.IsValidEmail(newEmail))
            {
                throw new QNetException(_localizationService.GetResource("Account.EmailUsernameErrors.NewEmailIsNotValid"));
            }

            if (newEmail.Length > 100)
            {
                throw new QNetException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailTooLong"));
            }

            var customer2 = _customerService.GetCustomerByEmail(newEmail);

            if (customer2 != null && customer.Id != customer2.Id)
            {
                throw new QNetException(_localizationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));
            }

            if (requireValidation)
            {
                //re-validate email
                customer.EmailToRevalidate = newEmail;
                _customerService.UpdateCustomer(customer);

                //email re-validation message
                _genericAttributeService.SaveAttribute(customer, QNetCustomerDefaults.EmailRevalidationTokenAttribute, Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailRevalidationMessage(customer, _workContext.WorkingLanguage.Id);
            }
            else
            {
                customer.Email = newEmail;
                _customerService.UpdateCustomer(customer);

                if (string.IsNullOrEmpty(oldEmail) || oldEmail.Equals(newEmail, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                //update newsletter subscription (if required)
                foreach (var store in _storeService.GetAllStores())
                {
                    var subscriptionOld = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(oldEmail, store.Id);

                    if (subscriptionOld == null)
                    {
                        continue;
                    }

                    subscriptionOld.Email = newEmail;
                    _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscriptionOld);
                }
            }
        }
Example #25
0
        /// <summary>
        /// Prepare customer model
        /// </summary>
        /// <param name="model">Customer model</param>
        /// <param name="customer">Customer</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>Customer model</returns>
        public virtual CustomerModel PrepareCustomerModel(CustomerModel model, Customer customer, bool excludeProperties = false)
        {
            if (customer != null)
            {
                //fill in model values from the entity
                model = model ?? new CustomerModel();

                model.Id = customer.Id;
                model.AllowSendingOfWelcomeMessage = customer.IsRegistered() &&
                                                     _customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval;
                model.AllowReSendingOfActivationMessage = customer.IsRegistered() && !customer.Active &&
                                                          _customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation;
                model.GdprEnabled = _gdprSettings.GdprEnabled;

                //whether to fill in some of properties
                if (!excludeProperties)
                {
                    model.Email                   = customer.Email;
                    model.Username                = customer.Username;
                    model.VendorId                = customer.VendorId;
                    model.AdminComment            = customer.AdminComment;
                    model.Active                  = customer.Active;
                    model.FirstName               = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.FirstNameAttribute);
                    model.LastName                = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastNameAttribute);
                    model.Gender                  = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.GenderAttribute);
                    model.DateOfBirth             = _genericAttributeService.GetAttribute <DateTime?>(customer, NopCustomerDefaults.DateOfBirthAttribute);
                    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);
                    model.TimeZoneId              = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.TimeZoneIdAttribute);
                    model.CreatedOn               = _dateTimeHelper.ConvertToUserTime(customer.CreatedOnUtc, DateTimeKind.Utc);
                    model.LastActivityDate        = _dateTimeHelper.ConvertToUserTime(customer.LastActivityDateUtc, DateTimeKind.Utc);
                    model.LastIpAddress           = customer.LastIpAddress;
                    model.LastVisitedPage         = _genericAttributeService.GetAttribute <string>(customer, NopCustomerDefaults.LastVisitedPageAttribute);
                    model.SelectedCustomerRoleIds = customer.CustomerCustomerRoleMappings.Select(mapping => mapping.CustomerRoleId).ToList();
                    model.RegisteredInStore       = _storeService.GetAllStores()
                                                    .FirstOrDefault(store => store.Id == customer.RegisteredInStoreId)?.Name ?? string.Empty;

                    //prepare model newsletter subscriptions
                    if (!string.IsNullOrEmpty(customer.Email))
                    {
                        model.SelectedNewsletterSubscriptionStoreIds = _storeService.GetAllStores()
                                                                       .Where(store => _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id) != null)
                                                                       .Select(store => store.Id).ToList();
                    }
                }

                //prepare external authentication records
                PrepareAssociatedExternalAuthModels(model.AssociatedExternalAuthRecords, customer);

                //prepare nested search models
                PrepareCustomerAddressSearchModel(model.CustomerAddressSearchModel, customer);
                PrepareCustomerActivityLogSearchModel(model.CustomerActivityLogSearchModel, customer);
            }
            else
            {
                //whether to fill in some of properties
                if (!excludeProperties)
                {
                    //precheck Registered Role as a default role while creating a new customer through admin
                    var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);
                    if (registeredRole != null)
                    {
                        model.SelectedCustomerRoleIds.Add(registeredRole.Id);
                    }
                }
            }

            model.UsernamesEnabled            = _customerSettings.UsernamesEnabled;
            model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone;
            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.CountyEnabled         = _customerSettings.CountyEnabled;
            model.CountryEnabled        = _customerSettings.CountryEnabled;
            model.StateProvinceEnabled  = _customerSettings.StateProvinceEnabled;
            model.PhoneEnabled          = _customerSettings.PhoneEnabled;
            model.FaxEnabled            = _customerSettings.FaxEnabled;

            //set default values for the new model
            if (customer == null)
            {
                model.Active = true;
            }

            //prepare available vendors
            _baseAdminModelFactory.PrepareVendors(model.AvailableVendors,
                                                  defaultItemText: _localizationService.GetResource("Admin.Customers.Customers.Fields.Vendor.None"));

            //prepare model customer attributes
            PrepareCustomerAttributeModels(model.CustomerAttributes, customer);

            //prepare model stores for newsletter subscriptions
            model.AvailableNewsletterSubscriptionStores = _storeService.GetAllStores().Select(store => new SelectListItem
            {
                Value    = store.Id.ToString(),
                Text     = store.Name,
                Selected = model.SelectedNewsletterSubscriptionStoreIds.Contains(store.Id)
            }).ToList();

            //prepare model customer roles
            _aclSupportedModelFactory.PrepareModelCustomerRoles(model);

            //prepare available time zones
            _baseAdminModelFactory.PrepareTimeZones(model.AvailableTimeZones, false);

            //prepare available countries and states
            if (_customerSettings.CountryEnabled)
            {
                _baseAdminModelFactory.PrepareCountries(model.AvailableCountries);
                if (_customerSettings.StateProvinceEnabled)
                {
                    _baseAdminModelFactory.PrepareStatesAndProvinces(model.AvailableStates, model.CountryId == 0 ? null : (int?)model.CountryId);
                }
            }

            return(model);
        }
Example #26
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(customerId: customer.Id, approved: null);
            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 customer.ExternalAuthenticationRecords)
            {
                _externalAuthenticationService.DeleteExternalAuthenticationRecord(ear);
            }

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

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

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

            //private messages (sent)
            foreach (var pm in _forumService.GetAllPrivateMessages(storeId: 0, fromCustomerId: customer.Id, toCustomerId: 0,
                                                                   isRead: null, isDeletedByAuthor: null, isDeletedByRecipient: null, keywords: null))
            {
                _forumService.DeletePrivateMessage(pm);
            }
            //private messages (received)
            foreach (var pm in _forumService.GetAllPrivateMessages(storeId: 0, fromCustomerId: 0, toCustomerId: customer.Id,
                                                                   isRead: null, isDeletedByAuthor: null, isDeletedByRecipient: null, keywords: 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 customer.Addresses)
            {
                customer.RemoveAddress(address);
                _customerService.UpdateCustomer(customer);
                //now delete the address record
                _addressService.DeleteAddress(address);
            }

            //generic attributes
            var keyGroup          = customer.GetUnproxiedEntityType().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 (customer.IsRegistered())
            {
                var registeredRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.RegisteredRoleName);
                customer.CustomerCustomerRoleMappings
                .Remove(customer.CustomerCustomerRoleMappings.FirstOrDefault(mapping => mapping.CustomerRoleId == registeredRole.Id));
            }
            if (!customer.IsGuest())
            {
                var guestRole = _customerService.GetCustomerRoleBySystemName(NopCustomerDefaults.GuestsRoleName);
                customer.CustomerCustomerRoleMappings.Add(new CustomerCustomerRoleMapping {
                    CustomerRole = guestRole
                });
            }

            var email = customer.Email;

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

            //raise event
            _eventPublisher.Publish(new CustomerPermanentlyDeleted(customer.Id, email));
        }
        /// <summary>
        /// Export customer list to xml
        /// </summary>
        /// <param name="customers">Customers</param>
        /// <returns>Result in XML format</returns>
        public virtual string ExportCustomersToXml(IList <Customer> customers)
        {
            var sb           = new StringBuilder();
            var stringWriter = new StringWriter(sb);
            var xmlWriter    = new XmlTextWriter(stringWriter);

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("Customers");
            xmlWriter.WriteAttributeString("Version", NopVersion.CurrentVersion);

            foreach (var customer in customers)
            {
                xmlWriter.WriteStartElement("Customer");
                xmlWriter.WriteElementString("CustomerId", null, customer.Id.ToString());
                xmlWriter.WriteElementString("CustomerGuid", null, customer.CustomerGuid.ToString());
                xmlWriter.WriteElementString("Email", null, customer.Email);
                xmlWriter.WriteElementString("Username", null, customer.Username);

                var customerPassword = _customerService.GetCurrentPassword(customer.Id);
                xmlWriter.WriteElementString("Password", null, customerPassword.Return(password => password.Password, null));
                xmlWriter.WriteElementString("PasswordFormatId", null, customerPassword.Return(password => password.PasswordFormatId, 0).ToString());
                xmlWriter.WriteElementString("PasswordSalt", null, customerPassword.Return(password => password.PasswordSalt, null));

                xmlWriter.WriteElementString("Active", null, customer.Active.ToString());

                xmlWriter.WriteElementString("IsGuest", null, customer.IsGuest().ToString());
                xmlWriter.WriteElementString("IsRegistered", null, customer.IsRegistered().ToString());
                xmlWriter.WriteElementString("IsAdministrator", null, customer.IsAdmin().ToString());
                xmlWriter.WriteElementString("IsForumModerator", null, customer.IsForumModerator().ToString());
                xmlWriter.WriteElementString("CreatedOnUtc", null, customer.CreatedOnUtc.ToString());

                xmlWriter.WriteElementString("FirstName", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName));
                xmlWriter.WriteElementString("LastName", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName));
                xmlWriter.WriteElementString("Gender", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.Gender));
                xmlWriter.WriteElementString("Company", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.Company));

                xmlWriter.WriteElementString("CountryId", null, customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId).ToString());
                xmlWriter.WriteElementString("StreetAddress", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress));
                xmlWriter.WriteElementString("StreetAddress2", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2));
                xmlWriter.WriteElementString("ZipPostalCode", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode));
                xmlWriter.WriteElementString("City", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.City));
                xmlWriter.WriteElementString("StateProvinceId", null, customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId).ToString());
                xmlWriter.WriteElementString("Phone", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone));
                xmlWriter.WriteElementString("Fax", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax));
                xmlWriter.WriteElementString("TimeZoneId", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.TimeZoneId));

                foreach (var store in _storeService.GetAllStores())
                {
                    var  newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(customer.Email, store.Id);
                    bool subscribedToNewsletters = newsletter != null && newsletter.Active;
                    xmlWriter.WriteElementString(string.Format("Newsletter-in-store-{0}", store.Id), null, subscribedToNewsletters.ToString());
                }

                xmlWriter.WriteElementString("AvatarPictureId", null, customer.GetAttribute <int>(SystemCustomerAttributeNames.AvatarPictureId).ToString());
                xmlWriter.WriteElementString("ForumPostCount", null, customer.GetAttribute <int>(SystemCustomerAttributeNames.ForumPostCount).ToString());
                xmlWriter.WriteElementString("Signature", null, customer.GetAttribute <string>(SystemCustomerAttributeNames.Signature));

                var selectedCustomerAttributesString = customer.GetAttribute <string>(SystemCustomerAttributeNames.CustomCustomerAttributes, _genericAttributeService);

                if (!string.IsNullOrEmpty(selectedCustomerAttributesString))
                {
                    var selectedCustomerAttributes          = new StringReader(selectedCustomerAttributesString);
                    var selectedCustomerAttributesXmlReader = XmlReader.Create(selectedCustomerAttributes);
                    xmlWriter.WriteNode(selectedCustomerAttributesXmlReader, false);
                }

                xmlWriter.WriteEndElement();
            }

            xmlWriter.WriteEndElement();
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
            return(stringWriter.ToString());
        }
        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);
        }
        /// <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);
        }
Example #30
0
        /// <summary>
        /// Import newsletter subscribers from TXT file
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <returns>Number of imported subscribers</returns>
        public virtual int ImportNewsletterSubscribersFromTxt(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(',');

                    var  email    = "";
                    bool isActive = true;
                    int  storeId  = _storeContext.CurrentStore.Id;
                    //parse
                    if (tmp.Length == 1)
                    {
                        //"email" only
                        email = tmp[0].Trim();
                    }
                    else if (tmp.Length == 2)
                    {
                        //"email" and "active" fields specified
                        email    = tmp[0].Trim();
                        isActive = Boolean.Parse(tmp[1].Trim());
                    }
                    else if (tmp.Length == 3)
                    {
                        //"email" and "active" and "storeId" fields specified
                        email    = tmp[0].Trim();
                        isActive = Boolean.Parse(tmp[1].Trim());
                        storeId  = Int32.Parse(tmp[2].Trim());
                    }
                    else
                    {
                        throw new NopException("Wrong file format");
                    }

                    //import
                    var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);
                    if (subscription != null)
                    {
                        subscription.Email  = email;
                        subscription.Active = isActive;
                        _newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
                    }
                    else
                    {
                        subscription = new NewsLetterSubscription
                        {
                            Active       = isActive,
                            CreatedOnUtc = DateTime.UtcNow,
                            Email        = email,
                            StoreId      = storeId,
                            NewsLetterSubscriptionGuid = Guid.NewGuid()
                        };
                        _newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
                    }
                    count++;
                }
            }

            return(count);
        }