/// <summary>
        /// Prepare message template model
        /// </summary>
        /// <param name="model">Message template model</param>
        /// <param name="messageTemplate">Message template</param>
        /// <param name="excludeProperties">Whether to exclude populating of some properties of model</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the message template model
        /// </returns>
        public virtual async Task <MessageTemplateModel> PrepareMessageTemplateModelAsync(MessageTemplateModel model,
                                                                                          MessageTemplate messageTemplate, bool excludeProperties = false)
        {
            Action <MessageTemplateLocalizedModel, int> localizedModelConfiguration = null;

            if (messageTemplate != null)
            {
                //fill in model values from the entity
                model ??= messageTemplate.ToModel <MessageTemplateModel>();

                //define localized model configuration action
                localizedModelConfiguration = async(locale, languageId) =>
                {
                    locale.BccEmailAddresses = await _localizationService.GetLocalizedAsync(messageTemplate, entity => entity.BccEmailAddresses, languageId, false, false);

                    locale.Subject = await _localizationService.GetLocalizedAsync(messageTemplate, entity => entity.Subject, languageId, false, false);

                    locale.Body = await _localizationService.GetLocalizedAsync(messageTemplate, entity => entity.Body, languageId, false, false);

                    locale.EmailAccountId = await _localizationService.GetLocalizedAsync(messageTemplate, entity => entity.EmailAccountId, languageId, false, false);

                    //prepare available email accounts
                    await _baseAdminModelFactory.PrepareEmailAccountsAsync(locale.AvailableEmailAccounts,
                                                                           defaultItemText : await _localizationService.GetResourceAsync("Admin.ContentManagement.MessageTemplates.Fields.EmailAccount.Standard"));

                    //PrepareEmailAccounts only gets available accounts, we need to set the item as selected manually
                    if (locale.AvailableEmailAccounts?.FirstOrDefault(x => x.Value == locale.EmailAccountId.ToString()) is SelectListItem emailAccountListItem)
                    {
                        emailAccountListItem.Selected = true;
                    }
                };
            }

            model.SendImmediately     = !model.DelayBeforeSend.HasValue;
            model.HasAttachedDownload = model.AttachedDownloadId > 0;

            var allowedTokens = string.Join(", ", await _messageTokenProvider.GetListOfAllowedTokensAsync(_messageTokenProvider.GetTokenGroups(messageTemplate)));

            model.AllowedTokens = $"{allowedTokens}{Environment.NewLine}{Environment.NewLine}" +
                                  $"{await _localizationService.GetResourceAsync("Admin.ContentManagement.MessageTemplates.Tokens.ConditionalStatement")}{Environment.NewLine}";

            //prepare localized models
            if (!excludeProperties)
            {
                model.Locales = await _localizedModelFactory.PrepareLocalizedModelsAsync(localizedModelConfiguration);
            }

            //prepare available email accounts
            await _baseAdminModelFactory.PrepareEmailAccountsAsync(model.AvailableEmailAccounts);

            //prepare available stores
            await _storeMappingSupportedModelFactory.PrepareModelStoresAsync(model, messageTemplate, excludeProperties);

            return(model);
        }
Esempio n. 2
0
        /// <summary>
        /// Prepare SendinblueModel
        /// </summary>
        /// <param name="model">Model</param>
        private async Task PrepareModelAsync(ConfigurationModel model)
        {
            //load settings for active store scope
            var storeId = await _storeContext.GetActiveStoreScopeConfigurationAsync();

            var sendinblueSettings = await _settingService.LoadSettingAsync <SendinblueSettings>(storeId);

            //whether plugin is configured
            if (string.IsNullOrEmpty(sendinblueSettings.ApiKey))
            {
                return;
            }

            //prepare common properties
            model.ActiveStoreScopeConfiguration = storeId;
            model.ApiKey                 = sendinblueSettings.ApiKey;
            model.ListId                 = sendinblueSettings.ListId;
            model.SmtpKey                = sendinblueSettings.SmtpKey;
            model.SenderId               = sendinblueSettings.SenderId;
            model.UseSmsNotifications    = sendinblueSettings.UseSmsNotifications;
            model.SmsSenderName          = sendinblueSettings.SmsSenderName;
            model.StoreOwnerPhoneNumber  = sendinblueSettings.StoreOwnerPhoneNumber;
            model.UseMarketingAutomation = sendinblueSettings.UseMarketingAutomation;
            model.TrackingScript         = sendinblueSettings.TrackingScript;

            model.HideGeneralBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinblueDefaults.HideGeneralBlock);

            model.HideSynchronizationBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinblueDefaults.HideSynchronizationBlock);

            model.HideTransactionalBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinblueDefaults.HideTransactionalBlock);

            model.HideSmsBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinblueDefaults.HideSmsBlock);

            model.HideMarketingAutomationBlock = await _genericAttributeService.GetAttributeAsync <bool>(await _workContext.GetCurrentCustomerAsync(), SendinblueDefaults.HideMarketingAutomationBlock);

            //prepare nested search models
            model.MessageTemplateSearchModel.SetGridPageSize();
            model.SmsSearchModel.SetGridPageSize();

            //prepare add SMS model
            model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(await _localizationService.GetResourceAsync("Plugins.Misc.Sendinblue.MyPhone"), "0"));
            model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(await _localizationService.GetResourceAsync("Plugins.Misc.Sendinblue.CustomerPhone"), "1"));
            model.AddSms.AvailablePhoneTypes.Add(new SelectListItem(await _localizationService.GetResourceAsync("Plugins.Misc.Sendinblue.BillingAddressPhone"), "2"));
            model.AddSms.DefaultSelectedPhoneTypeId = model.AddSms.AvailablePhoneTypes.First().Value;

            var stores = await _storeService.GetAllStoresAsync();

            var messageTemplates = await _messageTemplateService.GetAllMessageTemplatesAsync(storeId);

            model.AddSms.AvailableMessages = await messageTemplates.SelectAwait(async messageTemplate =>
            {
                var name = messageTemplate.Name;
                if (storeId == 0 && messageTemplate.LimitedToStores)
                {
                    var storeIds   = await _storeMappingService.GetStoresIdsWithAccessAsync(messageTemplate);
                    var storeNames = stores.Where(store => storeIds.Contains(store.Id)).Select(store => store.Name);
                    name           = $"{name} ({string.Join(',', storeNames)})";
                }

                return(new SelectListItem(name, messageTemplate.Id.ToString()));
            }).ToListAsync();

            var defaultSelectedMessage = model.AddSms.AvailableMessages.FirstOrDefault();

            model.AddSms.DefaultSelectedMessageId = defaultSelectedMessage?.Value ?? "0";

            //check whether email account exists
            if (sendinblueSettings.UseSmtp && await _emailAccountService.GetEmailAccountByIdAsync(sendinblueSettings.EmailAccountId) != null)
            {
                model.UseSmtp = sendinblueSettings.UseSmtp;
            }

            //get account info
            var(accountInfo, marketingAutomationEnabled, maKey, accountErrors) = await _sendinblueEmailManager.GetAccountInfoAsync();

            model.AccountInfo                 = accountInfo;
            model.MarketingAutomationKey      = maKey;
            model.MarketingAutomationDisabled = !marketingAutomationEnabled;
            if (!string.IsNullOrEmpty(accountErrors))
            {
                _notificationService.ErrorNotification($"{SendinblueDefaults.NotificationMessage} {accountErrors}");
            }

            //prepare overridable settings
            if (storeId > 0)
            {
                model.ListId_OverrideForStore = await _settingService.SettingExistsAsync(sendinblueSettings, settings => settings.ListId, storeId);

                model.UseSmtp_OverrideForStore = await _settingService.SettingExistsAsync(sendinblueSettings, settings => settings.UseSmtp, storeId);

                model.SenderId_OverrideForStore = await _settingService.SettingExistsAsync(sendinblueSettings, settings => settings.SenderId, storeId);

                model.UseSmsNotifications_OverrideForStore = await _settingService.SettingExistsAsync(sendinblueSettings, settings => settings.UseSmsNotifications, storeId);

                model.SmsSenderName_OverrideForStore = await _settingService.SettingExistsAsync(sendinblueSettings, settings => settings.SmsSenderName, storeId);

                model.UseMarketingAutomation_OverrideForStore = await _settingService.SettingExistsAsync(sendinblueSettings, settings => settings.UseMarketingAutomation, storeId);
            }

            //check SMTP status
            var(smtpEnabled, smtpErrors) = await _sendinblueEmailManager.SmtpIsEnabledAsync();

            if (!string.IsNullOrEmpty(smtpErrors))
            {
                _notificationService.ErrorNotification($"{SendinblueDefaults.NotificationMessage} {smtpErrors}");
            }

            //get available contact lists to synchronize
            var(lists, listsErrors) = await _sendinblueEmailManager.GetListsAsync();

            model.AvailableLists = lists.Select(list => new SelectListItem(list.Name, list.Id)).ToList();
            model.AvailableLists.Insert(0, new SelectListItem("Select list", "0"));
            if (!string.IsNullOrEmpty(listsErrors))
            {
                _notificationService.ErrorNotification($"{SendinblueDefaults.NotificationMessage} {listsErrors}");
            }

            //get available senders of emails from account
            var(senders, sendersErrors) = await _sendinblueEmailManager.GetSendersAsync();

            model.AvailableSenders = senders.Select(list => new SelectListItem(list.Name, list.Id)).ToList();
            model.AvailableSenders.Insert(0, new SelectListItem("Select sender", "0"));
            if (!string.IsNullOrEmpty(sendersErrors))
            {
                _notificationService.ErrorNotification($"{SendinblueDefaults.NotificationMessage} {sendersErrors}");
            }

            //get allowed tokens
            model.AllowedTokens = string.Join(", ", await _messageTokenProvider.GetListOfAllowedTokensAsync());

            //create attributes in account
            var attributesErrors = await _sendinblueEmailManager.PrepareAttributesAsync();

            if (!string.IsNullOrEmpty(attributesErrors))
            {
                _notificationService.ErrorNotification($"{SendinblueDefaults.NotificationMessage} {attributesErrors}");
            }
        }