public ActionResult Index(string webHookKey)
        {
            if (string.IsNullOrWhiteSpace(_settings.WebHookKey))
            {
                return(Content("Invalid Request."));
            }

            if (!string.Equals(_settings.WebHookKey, webHookKey, StringComparison.InvariantCultureIgnoreCase))
            {
                return(Content("Invalid Request."));
            }

            if (IsUnsubscribe())
            {
                var email = FindEmail();
                if (email.IsEmail())
                {
                    // TODO: multistore capable.
                    var subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(email, 0, int.MaxValue, true);

                    foreach (var subscription in subscriptions)
                    {
                        // Do not publish unsubscribe event. Or duplicate events will occur.
                        _newsLetterSubscriptionService.DeleteNewsLetterSubscription(subscription.Subscription, false);
                    }

                    if (subscriptions.Count > 0)
                    {
                        return(Content("OK"));
                    }
                }
            }

            return(Content("Invalid Request."));
        }
        public virtual IActionResult ExportCsv(NewsletterSubscriptionSearchModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            bool?isActive = null;

            if (model.ActiveId == 1)
            {
                isActive = true;
            }
            else if (model.ActiveId == 2)
            {
                isActive = false;
            }

            var startDateValue = model.StartDate == null ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.StartDate.Value, _dateTimeHelper.CurrentTimeZone);
            var endDateValue = model.EndDate == null ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1);

            var subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(model.SearchEmail,
                                                                                             startDateValue, endDateValue, model.StoreId, isActive, model.CustomerRoleId);

            var result = _exportManager.ExportNewsletterSubscribersToTxt(subscriptions);

            var fileName = $"newsletter_emails_{DateTime.Now:yyyy-MM-dd-HH-mm-ss}_{CommonHelper.GenerateRandomDigitCode(4)}.txt";

            return(File(Encoding.UTF8.GetBytes(result), MimeTypes.TextCsv, fileName));
        }
예제 #3
0
        public ActionResult SendMassEmail(CampaignModel model)
        {
            if (!Services.Permissions.Authorize(StandardPermissionProvider.ManageCampaigns))
            {
                return(AccessDeniedView());
            }

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

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

            PrepareCampaignModel(model, campaign, false);

            try
            {
                var subscriptions   = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(null, 0, int.MaxValue, false);
                var totalEmailsSent = _campaignService.SendCampaign(campaign, subscriptions);

                NotifySuccess(string.Format(T("Admin.Promotions.Campaigns.MassEmailSentToCustomers"), totalEmailsSent), false);
                return(View(model));
            }
            catch (Exception exc)
            {
                NotifyError(exc, false);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #4
0
        public ActionResult UpdateTrial(TrialTrackerRecord trialUpdate)
        {
            var trial = _trialRepository.GetById(trialUpdate.TrialTrackerId);

            trial.ProductName   = trialUpdate.ProductName;
            trial.CustomerName  = trialUpdate.CustomerName;
            trial.CustomerEmail = trialUpdate.CustomerEmail;
            trial.DownloadDate  = trialUpdate.DownloadDate;
            trial.OnMailingList = trialUpdate.OnMailingList;

            if (trial.OnMailingList)
            {
                NewsLetterSubscription subscriber = new NewsLetterSubscription
                {
                    Active       = true,
                    CreatedOnUtc = DateTime.Now,
                    Email        = trial.CustomerEmail
                };
                _mailingService.InsertNewsLetterSubscription(subscriber);
            }
            else
            {
                NewsLetterSubscription deleteSubscriber = _mailingService.GetAllNewsLetterSubscriptions().Where(x => x.Email == trial.CustomerEmail).FirstOrDefault();
                if (deleteSubscriber != null)
                {
                    _mailingService.DeleteNewsLetterSubscription(deleteSubscriber);
                }
            }

            _trialRepository.Update(trial);

            return(new NullJsonResult());
        }
        public async Task <IActionResult> SubscriptionList(DataSourceRequest command, NewsLetterSubscriptionListModel model, string[] searchCategoryIds)
        {
            bool?isActive = null;

            if (model.ActiveId == 1)
            {
                isActive = true;
            }
            else if (model.ActiveId == 2)
            {
                isActive = false;
            }

            if (await _groupService.IsStaff(_workContext.CurrentCustomer))
            {
                model.StoreId = _workContext.CurrentCustomer.StaffStoreId;
            }

            var newsletterSubscriptions = await _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(model.SearchEmail,
                                                                                                             model.StoreId, isActive, searchCategoryIds, command.Page - 1, command.PageSize);

            var items = new List <NewsLetterSubscriptionModel>();

            foreach (var x in newsletterSubscriptions)
            {
                var m     = x.ToModel();
                var store = await _storeService.GetStoreById(x.StoreId);

                m.StoreName  = store != null ? store.Shortcut : "Unknown store";
                m.CreatedOn  = _dateTimeService.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc).ToString();
                m.Categories = await GetCategoryNames(x.Categories.ToList());

                items.Add(m);
            }
            var gridModel = new DataSourceResult
            {
                Data  = items,
                Total = newsletterSubscriptions.TotalCount
            };

            return(Json(gridModel));
        }
        public virtual ActionResult SubscriptionList(DataSourceRequest command, NewsLetterSubscriptionListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedKendoGridJson());
            }

            bool?isActive = null;

            if (model.ActiveId == 1)
            {
                isActive = true;
            }
            else if (model.ActiveId == 2)
            {
                isActive = false;
            }

            var startDateValue = (model.StartDate == null) ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.StartDate.Value, _dateTimeHelper.CurrentTimeZone);
            var endDateValue = (model.EndDate == null) ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(model.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1);

            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(model.SearchEmail,
                                                                                                       startDateValue, endDateValue, model.StoreId, isActive, model.CustomerRoleId,
                                                                                                       command.Page - 1, command.PageSize);

            var gridModel = new DataSourceResult
            {
                Data = newsletterSubscriptions.Select(x =>
                {
                    var m       = x.ToModel();
                    var store   = _storeService.GetStoreById(x.StoreId);
                    m.StoreName = store != null ? store.Name : "Unknown store";
                    m.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);
                    return(m);
                }),
                Total = newsletterSubscriptions.TotalCount
            };

            return(Json(gridModel));
        }
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(String.Empty, 0, _adminAreaSettings.GridPageSize, true);
            var model = new NewsLetterSubscriptionListModel();

            model.NewsLetterSubscriptions = new GridModel <NewsLetterSubscriptionModel>
            {
                Data = newsletterSubscriptions.Select(x =>
                {
                    var m       = x.ToModel();
                    m.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);
                    return(m);
                }),
                Total = newsletterSubscriptions.TotalCount
            };
            return(View(model));
        }
예제 #8
0
        public ActionResult List()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            var model = new NewsLetterSubscriptionListModel();


            //languages
            model.AvailableLanguageNames.Add(new SelectListItem()
            {
                Text = "---", Value = "0"
            });
            foreach (var lgs in _languageService.GetAllLanguages(true))
            {
                model.AvailableLanguageNames.Add(new SelectListItem()
                {
                    Text = lgs.Name, Value = lgs.Id.ToString()
                });
            }

            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(String.Empty, 0, _adminAreaSettings.GridPageSize, true);

            model.NewsLetterSubscriptions = new GridModel <NewsLetterSubscriptionModel>
            {
                Data = newsletterSubscriptions.Select(x =>
                {
                    var m          = x.ToModel();
                    m.LanguageName = _languageService.GetLanguageById(x.LanguageId).Name;
                    m.CreatedOn    = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);
                    return(m);
                }),
                Total = newsletterSubscriptions.TotalCount
            };
            return(View(model));
        }
        public ActionResult SubscriptionList(DataSourceRequest command, NewsLetterSubscriptionListModel model)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(model.SearchEmail,
                                                                                                       command.Page - 1, command.PageSize, true);

            var gridModel = new DataSourceResult
            {
                Data = newsletterSubscriptions.Select(x =>
                {
                    var m       = x.ToModel();
                    m.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);
                    return(m);
                }),
                Total = newsletterSubscriptions.TotalCount
            };

            return(Json(gridModel));
        }
예제 #10
0
        public ActionResult List()
        {
            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(String.Empty, 0, _adminAreaSettings.GridPageSize, true);
            var model = new NewsLetterSubscriptionListModel();

            PrepareNewsLetterSubscriptionListModel(model);

            model.NewsLetterSubscriptions = new GridModel <NewsLetterSubscriptionModel>
            {
                Data = newsletterSubscriptions.Select(x =>
                {
                    var m     = x.ToModel();
                    var store = _storeService.GetStoreById(x.StoreId);

                    m.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);
                    m.StoreName = store != null ? store.Name : "".NaIfEmpty();

                    return(m);
                }),
                Total = newsletterSubscriptions.TotalCount
            };
            return(View(model));
        }
        public IActionResult SubscriptionList(DataSourceRequest command, NewsLetterSubscriptionListModel model, string[] searchCategoryIds)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNewsletterSubscribers))
            {
                return(AccessDeniedView());
            }

            bool?isActive = null;

            if (model.ActiveId == 1)
            {
                isActive = true;
            }
            else if (model.ActiveId == 2)
            {
                isActive = false;
            }

            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(model.SearchEmail,
                                                                                                       model.StoreId, isActive, searchCategoryIds, command.Page - 1, command.PageSize);

            var gridModel = new DataSourceResult
            {
                Data = newsletterSubscriptions.Select(x =>
                {
                    var m        = x.ToModel();
                    var store    = _storeService.GetStoreById(x.StoreId);
                    m.StoreName  = store != null ? store.Name : "Unknown store";
                    m.CreatedOn  = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc).ToLongTimeString();
                    m.Categories = GetCategoryNames(x.Categories.ToList());
                    return(m);
                }),
                Total = newsletterSubscriptions.TotalCount
            };

            return(Json(gridModel));
        }
예제 #12
0
        public ActionResult SendMassEmail(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);
            //customer roles
            PrepareCustomerRolesModel(model);

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

                //subscribers of certain store?
                var store         = _storeService.GetStoreById(campaign.StoreId);
                var storeId       = store != null ? store.Id : 0;
                var subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(storeId: storeId,
                                                                                                 customerRoleId: model.CustomerRoleId,
                                                                                                 isActive: true);
                var totalEmailsSent = _campaignService.SendCampaign(campaign, emailAccount, subscriptions);
                SuccessNotification(string.Format(_localizationService.GetResource("Admin.Promotions.Campaigns.MassEmailSentToCustomers"), totalEmailsSent), false);
                return(View(model));
            }
            catch (Exception exc)
            {
                ErrorNotification(exc, false);
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #13
0
        public virtual IActionResult SendMassEmail(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);

            try
            {
                var emailAccount = GetEmailAccount(model.EmailAccountId);

                //subscribers of certain store?
                var storeId       = _storeService.GetStoreById(campaign.StoreId)?.Id ?? 0;
                var subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(storeId: storeId,
                                                                                                 customerRoleId: model.CustomerRoleId,
                                                                                                 isActive: true);
                var totalEmailsSent = _campaignService.SendCampaign(campaign, emailAccount, subscriptions);

                SuccessNotification(string.Format(_localizationService.GetResource("Admin.Promotions.Campaigns.MassEmailSentToCustomers"), totalEmailsSent), 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));
        }
        /// <summary>
        /// Prepare paged newsletter subscription list model
        /// </summary>
        /// <param name="searchModel">Newsletter subscription search model</param>
        /// <returns>Newsletter subscription list model</returns>
        public virtual NewsletterSubscriptionListModel PrepareNewsletterSubscriptionListModel(NewsletterSubscriptionSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get parameters to filter newsletter subscriptions
            var isActivatedOnly = searchModel.ActiveId == 0 ? null : searchModel.ActiveId == 1 ? true : (bool?)false;
            var startDateValue  = !searchModel.StartDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.StartDate.Value, _dateTimeHelper.CurrentTimeZone);
            var endDateValue = !searchModel.EndDate.HasValue ? null
                : (DateTime?)_dateTimeHelper.ConvertToUtcTime(searchModel.EndDate.Value, _dateTimeHelper.CurrentTimeZone).AddDays(1);

            //get newsletter subscriptions
            var newsletterSubscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(email: searchModel.SearchEmail,
                                                                                                       customerRoleId: searchModel.CustomerRoleId,
                                                                                                       storeId: searchModel.StoreId,
                                                                                                       isActive: isActivatedOnly,
                                                                                                       createdFromUtc: startDateValue,
                                                                                                       createdToUtc: endDateValue,
                                                                                                       pageIndex: searchModel.Page - 1, pageSize: searchModel.PageSize);

            //prepare list model
            var model = new NewsletterSubscriptionListModel
            {
                Data = newsletterSubscriptions.Select(subscription =>
                {
                    //fill in model values from the entity
                    var subscriptionModel = subscription.ToModel();

                    //convert dates to the user time
                    subscriptionModel.CreatedOn = _dateTimeHelper.ConvertToUserTime(subscription.CreatedOnUtc, DateTimeKind.Utc);

                    //fill in additional values (not existing in the entity)
                    subscriptionModel.StoreName = _storeService.GetStoreById(subscription.StoreId)?.Name ?? "Deleted";

                    return(subscriptionModel);
                }),
                Total = newsletterSubscriptions.TotalCount
            };

            return(model);
        }
예제 #15
0
        public ActionResult SendMassEmail(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());

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

                var subscriptions   = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(null, 0, int.MaxValue, false);
                var totalEmailsSent = _campaignService.SendCampaign(campaign, emailAccount, subscriptions);
                NotifySuccess(string.Format(_localizationService.GetResource("Admin.Promotions.Campaigns.MassEmailSentToCustomers"), totalEmailsSent), false);
                return(View(model));
            }
            catch (Exception exc)
            {
                NotifyError(exc, false);
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #16
0
        public virtual int SendCampaign(Campaign campaign)
        {
            Guard.NotNull(campaign, nameof(campaign));

            var totalEmailsSent = 0;
            var pageIndex       = -1;

            int[] storeIds = null;
            int[] rolesIds = null;
            var   alreadyProcessedEmails = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);

            if (campaign.LimitedToStores)
            {
                storeIds = _storeMappingService.GetStoreMappings(campaign)
                           .Select(x => x.StoreId)
                           .Distinct()
                           .ToArray();
            }

            if (campaign.SubjectToAcl)
            {
                rolesIds = _aclService.GetAclRecords(campaign)
                           .Select(x => x.CustomerRoleId)
                           .Distinct()
                           .ToArray();
            }

            while (true)
            {
                var subscribers = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(null, ++pageIndex, 500, false, storeIds, rolesIds);

                foreach (var subscriber in subscribers)
                {
                    // Create only one message per subscription email.
                    if (alreadyProcessedEmails.Contains(subscriber.Subscription.Email))
                    {
                        continue;
                    }

                    if (subscriber.Customer != null && !subscriber.Customer.Active)
                    {
                        continue;
                    }

                    var result = SendCampaign(campaign, subscriber);
                    if ((result?.Email?.Id ?? 0) != 0)
                    {
                        alreadyProcessedEmails.Add(subscriber.Subscription.Email);

                        ++totalEmailsSent;
                    }
                }

                if (!subscribers.HasNextPage)
                {
                    break;
                }
            }

            return(totalEmailsSent);
        }
        /// <summary>
        /// Import subscriptions from nopCommerce to SendInBlue
        /// </summary>
        /// <param name="manualSync">A value indicating that method is called by user</param>
        /// <param name="storeScope">Store identifier; pass 0 for the synchronization for the all stores</param>
        /// <returns>Empty string if success, otherwise error string</returns>
        public string Synchronize(bool manualSync = false, int storeScope = 0)
        {
            var error = string.Empty;

            if (!IsConfigured)
            {
                _logger.Error("SendInBlue synchronization error: Plugin not configured");
                return("Plugin not configured");
            }

            //use only passed store identifier for the manual synchronization
            //use all store ids for the synchronization task
            var storeIds = manualSync ? new List <int> {
                storeScope
            }
                : new List <int> {
                0
            }.Union(_storeService.GetAllStores().Select(store => store.Id));

            foreach (var storeId in storeIds)
            {
                //get list identifier from the settings
                var listId = _settingService.GetSettingByKey <int>("SendInBlueSettings.ListId", storeId: storeId);
                if (listId > 0)
                {
                    //get notify url from the settings
                    var url = _settingService.GetSettingByKey <string>("SendInBlueSettings.UrlSync", storeId: storeId);
                    if (string.IsNullOrEmpty(url))
                    {
                        _logger.Warning("SendInBlue synchronization warning: Notify url not specified");
                    }

                    var subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(storeId: storeId, isActive: true);
                    if (subscriptions.Count == 0)
                    {
                        error = "There are no subscriptions";
                        continue;
                    }

                    //import subscriptions from nopCommerce to SendInBlue
                    var csv = subscriptions.Aggregate(string.Format("{0};{1}", "EMAIL", "STORE_ID"),
                                                      (current, next) => string.Format("{0}\n{1};{2}", current, next.Email, next.StoreId));

                    //sometimes occur Exception "Request failed" https://github.com/mailin-api/mailin-api-csharp/commit/d7d9f19fd6a18fee51ef7507e2020a972dc18093
                    //it does not affect the correct functioning
                    try
                    {
                        var importParams = new Dictionary <string, object>
                        {
                            { "notify_url", url },
                            { "body", csv },
                            { "listids", new List <int> {
                                  listId
                              } }
                        };
                        var import = Manager.import_users(importParams);
                        if (!IsSuccess(import))
                        {
                            _logger.Error(string.Format("SendInBlue synchronization error: {0}", (string)import.message));
                            error = (string)import.message;
                        }
                    }
                    catch (Exception)
                    { }
                }
                else
                {
                    error = "List ID is empty";
                }
            }

            return(error);
        }
예제 #18
0
        public ActionResult SendMassEmail(CampaignModel model, List <TreeViewItem> category_treeview_checkedNodes)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageCampaigns))
            {
                return(AccessDeniedView());
            }

            List <int> categoryList;

            if (model.EnableTimePeriod)
            {
                categoryList = category_treeview_checkedNodes.Where(x => x.Checked).Select(x => int.Parse(x.Value)).ToList();
            }
            else
            {
                categoryList = _categoryService.GetAllCategories(showHidden: true).Select(x => x.Id).ToList();
            }
            if (!CheckLocales(model) || categoryList.Count == 0 || (ModelState["StartDate"] != null && ModelState["StartDate"].Errors.Count > 0) || model.CompaignLanguages.Where(x => x.Selected).Count() == 0 || (model.EnableTimePeriod && !model.EndDate.HasValue))
            {
                if (model.CompaignLanguages.Where(x => x.Selected).Count() == 0)
                {
                    AddNotification(NotifyType.Error, _localizationService.GetResource("Admin.ETF.Languages.One"), false);
                }
                if (model.EnableTimePeriod && !model.EndDate.HasValue)
                {
                    AddNotification(NotifyType.Error, _localizationService.GetResource("Admin.ETF.Campaign.EndDate"), false);
                }
                var lang = model.CompaignLanguages.Where(x => x.LanguageName != null).FirstOrDefault();
                if (lang != null)
                {
                    string Error = String.Format(_localizationService.GetResource("Admin.Campaign.LocaleError", _workContext.WorkingLanguage.Id), lang.LanguageName, _languageService.GetLanguageById(lang.LanguageId).Name);
                    AddNotification(NotifyType.Error, Error, false);
                }
                model.CompaignLanguages = _languageService.GetAllLanguages()
                                          .Select(x => new CompaignLanguage()
                {
                    LanguageId   = x.Id,
                    LanguageName = x.Name,
                    Selected     = false
                }).ToList();
                model.AllowedTokens  = FormatTokens(_messageTokenProvider.GetListOfCampaignAllowedTokens());
                model.CategoriesTree = new List <TreeViewItemModel>();
                model.CategoriesTree = PrepareTreeView(model.CategoriesTree, 0);
                return(View(model));
            }
            var campaign = _campaignService.GetCampaignById(model.Id);

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

            model.AllowedTokens = FormatTokens(_messageTokenProvider.GetListOfCampaignAllowedTokens());
            if (!model.EnableTimePeriod)
            {
                model.EndDate = null;
            }
            foreach (var lang in model.CompaignLanguages.Where(x => x.Selected))
            {
                campaign.Body    = campaign.GetLocalized(x => x.Body, lang.LanguageId);
                campaign.Subject = campaign.GetLocalized(x => x.Subject, lang.LanguageId);
                try
                {
                    var emailAccount = _emailAccountService.GetAllEmailAccounts().Where(x => x.DisplayName == "TradeBel newsletter").FirstOrDefault();
                    if (emailAccount == null)
                    {
                        throw new NopException("Email account could not be loaded");
                    }
                    IList <NewsLetterSubscription> subscriptions;
                    if (campaign.Body.IndexOf("%Store.RecentProducts%") > 0)
                    {
                        subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(null, 0, int.MaxValue, false)
                                        .Where(x => x.NewProduct).ToList();
                    }
                    else
                    {
                        subscriptions = _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions(null, 0, int.MaxValue, false)
                                        .Where(x => x.NewBuyingRequests).ToList();
                    }

                    var totalEmailsSent = _campaignService.SendCampaign(campaign, emailAccount, subscriptions, lang.LanguageId, categoryList, model.StartDate, model.EndDate, model.NumberOfItems);
                    SuccessNotification(string.Format(_localizationService.GetResource("Admin.Promotions.Campaigns.MassEmailSentToCustomers"), totalEmailsSent), false);

                    model.CompaignLanguages = _languageService.GetAllLanguages()
                                              .Select(x => new CompaignLanguage()
                    {
                        LanguageId   = x.Id,
                        LanguageName = x.Name,
                        Selected     = false
                    }).ToList();
                }
                catch (Exception exc)
                {
                    ErrorNotification(exc, false);
                }
            }

            model.CompaignLanguages = _languageService.GetAllLanguages()
                                      .Select(x => new CompaignLanguage()
            {
                LanguageId   = x.Id,
                LanguageName = x.Name,
                Selected     = false
            }).ToList();
            //If we got this far, something failed, redisplay form
            model.CategoriesTree = new List <TreeViewItemModel>();
            model.CategoriesTree = PrepareTreeView(model.CategoriesTree, 0);
            return(View(model));
        }
        /// <summary>
        /// Uninstall the plugin
        /// </summary>
        public override void Uninstall()
        {
            //generic attributes
            var onDateSettings = _rewardPointsOnDateSettingsService.GetAllRewardPointsOnDateSettings().ToList();

            onDateSettings.ForEach(setting => _genericAttributeService.SaveAttribute(setting, "CustomersAwardedOnDate", string.Empty));

            _blogService.GetAllComments().ToList().ForEach(comment =>
                                                           _genericAttributeService.SaveAttribute(comment, "CustomerAwardedForBlogComment", string.Empty, comment.StoreId));

            _newsService.GetAllComments().ToList().ForEach(comment =>
                                                           _genericAttributeService.SaveAttribute(comment, "CustomerAwardedForNewsComment", string.Empty, comment.StoreId));

            _productService.GetAllProductReviews(0, null).ToList().ForEach(review =>
                                                                           _genericAttributeService.SaveAttribute(review, "CustomerAwardedForProductReview", string.Empty, review.StoreId));

            _newsLetterSubscriptionService.GetAllNewsLetterSubscriptions().ToList().ForEach(subscription =>
                                                                                            _genericAttributeService.SaveAttribute(subscription, "CustomerAwardedForSubscription", string.Empty, subscription.StoreId));

            _customerService.GetAllCustomers().ToList().ForEach(customer =>
                                                                _genericAttributeService.DeleteAttributes(_genericAttributeService.GetAttributesForEntity(customer.Id, "Customer")
                                                                                                          .Where(attribute => attribute.Key.Equals("PurchaseStartTime")).ToList()));

            //localized properties
            var localizedSettings = new[]
            {
                _settingService.GetSetting("RewardPointsForBlogCommentsSettings.Message"),
                _settingService.GetSetting("RewardPointsForFastPurchaseSettings.Message"),
                _settingService.GetSetting("RewardPointsForFirstPurchaseSettings.Message"),
                _settingService.GetSetting("RewardPointsForNewsCommentsSettings.Message"),
                _settingService.GetSetting("RewardPointsForNewsletterSubscriptionsSettings.Message"),
                _settingService.GetSetting("RewardPointsForProductReviewsSettings.Message")
            }.Where(setting => setting != null).ToList();

            foreach (var language in _languageService.GetAllLanguages(true))
            {
                localizedSettings.ForEach(setting => _localizedEntityService.SaveLocalizedValue(setting, x => x.Value, string.Empty, language.Id));
                onDateSettings.ForEach(setting => _localizedEntityService.SaveLocalizedValue(setting, x => x.Message, string.Empty, language.Id));
            }

            //database objects
            _objectContext.Uninstall();

            //settings
            _settingService.DeleteSetting <RewardPointsForBlogCommentsSettings>();
            _settingService.DeleteSetting <RewardPointsForFastPurchaseSettings>();
            _settingService.DeleteSetting <RewardPointsForFirstPurchaseSettings>();
            _settingService.DeleteSetting <RewardPointsForNewsCommentsSettings>();
            _settingService.DeleteSetting <RewardPointsForNewsletterSubscriptionsSettings>();
            _settingService.DeleteSetting <RewardPointsForProductReviewsSettings>();
            _settingService.DeleteSetting <RewardPointsForRegistrationSettings>();

            //scheduled task
            var task = _scheduleTaskService.GetTaskByType(EXTENDED_REWARD_POINTS_PROGRAM_TASK_TYPE);

            if (task != null)
            {
                _scheduleTaskService.DeleteTask(task);
            }

            //locales
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivatePointsImmediately");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivatePointsImmediately.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivationDelay");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.ActivationDelay.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.IsEnabled");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.IsEnabled.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Message");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Message.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Points");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.Fields.Points.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForBlogComments");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForBlogComments.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFirstPurchase");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFirstPurchase.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase.Fields.Minutes");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase.Fields.Minutes.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForFastPurchase.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsComments");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsComments.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsletterSubscriptions");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForNewsletterSubscriptions.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForProductReviews");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForProductReviews.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForRegistration");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.ForRegistration.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.AddNew");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Edit");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.AwardingDate");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.AwardingDate.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.CustomerRole");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.CustomerRole.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.Store");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Fields.Store.Hint");
            _localizationService.DeletePluginLocaleResource("Plugins.Misc.ExtendedRewardPointsProgram.RewardPointsOnDate.Hint");

            base.Uninstall();
        }