Ejemplo n.º 1
0
        /// <summary>
        /// Prepare the home page news items model
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the home page news items model
        /// </returns>
        public virtual async Task <HomepageNewsItemsModel> PrepareHomepageNewsItemsModelAsync()
        {
            var cacheKey    = _staticCacheManager.PrepareKeyForDefaultCache(NopModelCacheDefaults.HomepageNewsModelKey, await _workContext.GetWorkingLanguageAsync(), await _storeContext.GetCurrentStoreAsync());
            var cachedModel = await _staticCacheManager.GetAsync(cacheKey, async() =>
            {
                var language  = await _workContext.GetWorkingLanguageAsync();
                var store     = await _storeContext.GetCurrentStoreAsync();
                var newsItems = await _newsService.GetAllNewsAsync(language.Id, store.Id, 0, _newsSettings.MainPageNewsCount);

                return(new HomepageNewsItemsModel
                {
                    WorkingLanguageId = language.Id,
                    NewsItems = await newsItems.SelectAwait(async newsItem =>
                    {
                        var newsModel = new NewsItemModel();
                        await PrepareNewsItemModelAsync(newsModel, newsItem, false);
                        return newsModel;
                    }).ToListAsync()
                });
            });

            //"Comments" property of "NewsItemModel" object depends on the current customer.
            //Furthermore, we just don't need it for home page news. So let's reset it.
            //But first we need to clone the cached model (the updated one should not be cached)
            var model = cachedModel with {
            };

            foreach (var newsItemModel in model.NewsItems)
            {
                newsItemModel.Comments.Clear();
            }

            return(model);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets a resource string based on the specified ResourceKey property.
        /// </summary>
        /// <param name="resourceKey">A string representing a ResourceKey.</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains a string representing the requested resource string.
        /// </returns>
        public virtual async Task <string> GetResourceAsync(string resourceKey)
        {
            var workingLanguage = await _workContext.GetWorkingLanguageAsync();

            if (workingLanguage != null)
            {
                return(await GetResourceAsync(resourceKey, workingLanguage.Id));
            }

            return(string.Empty);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Check the current store for the copyright removal key
        /// </summary>
        /// <returns>The asynchronous task whose result contains the warning text</returns>
        public virtual async Task <string> GetCopyrightWarningAsync()
        {
            //prepare URL to request
            var language = _languageService.GetTwoLetterIsoLanguageName(await _workContext.GetWorkingLanguageAsync());
            var url      = string.Format(NopCommonDefaults.NopCopyrightWarningPath,
                                         (await _storeContext.GetCurrentStoreAsync()).Url,
                                         _webHelper.IsLocalRequest(_httpContextAccessor.HttpContext.Request),
                                         language).ToLowerInvariant();

            //get the message
            return(await _httpClient.GetStringAsync(url));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get tinyMCE language name for current language
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the inyMCE language name
        /// </returns>
        public async Task <string> GetTinyMceLanguageAsync()
        {
            //nopCommerce supports TinyMCE's localization for 10 languages:
            //Chinese, Spanish, Arabic, Portuguese, Russian, German, French, Italian, Dutch and English out-of-the-box.
            //Additional languages can be downloaded from the website TinyMCE(https://www.tinymce.com/download/language-packages/)

            var languageCulture = (await _workContext.GetWorkingLanguageAsync()).LanguageCulture;

            var langFile      = $"{languageCulture}.js";
            var directoryPath = _nopFileProvider.Combine(_webHostEnvironment.WebRootPath, @"lib_npm\tinymce\langs");
            var fileExists    = _nopFileProvider.FileExists($"{directoryPath}\\{langFile}");

            if (!fileExists)
            {
                languageCulture = languageCulture.Replace('-', '_');
                langFile        = $"{languageCulture}.js";
                fileExists      = _nopFileProvider.FileExists($"{directoryPath}\\{langFile}");
            }

            if (!fileExists)
            {
                languageCulture = languageCulture.Split('_', '-')[0];
                langFile        = $"{languageCulture}.js";
                fileExists      = _nopFileProvider.FileExists($"{directoryPath}\\{langFile}");
            }

            return(fileExists ? languageCulture : string.Empty);
        }
Ejemplo n.º 5
0
        public async Task ManageSiteMapAsync(SiteMapNode rootNode)
        {
            var workingLanguage = await _workContext.GetWorkingLanguageAsync();

            var pluginMenuName = await _localizationService.GetResourceAsync("Plugins.Api.Admin.Menu.Title", workingLanguage.Id, defaultValue : "API");

            var settingsMenuName = await _localizationService.GetResourceAsync("Plugins.Api.Admin.Menu.Settings.Title", workingLanguage.Id, defaultValue : "API");

            const string adminUrlPart = "Admin/";

            var pluginMainMenu = new SiteMapNode
            {
                Title      = pluginMenuName,
                Visible    = true,
                SystemName = "Api-Main-Menu",
                IconClass  = "fa-genderless"
            };

            pluginMainMenu.ChildNodes.Add(new SiteMapNode
            {
                Title      = settingsMenuName,
                Url        = _webHelper.GetStoreLocation() + adminUrlPart + "ApiAdmin/Settings",
                Visible    = true,
                SystemName = "Api-Settings-Menu",
                IconClass  = "fa-genderless"
            });


            rootNode.ChildNodes.Add(pluginMainMenu);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get the poll model by poll system keyword
        /// </summary>
        /// <param name="systemKeyword">Poll system keyword</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the poll model
        /// </returns>
        public virtual async Task <PollModel> PreparePollModelBySystemNameAsync(string systemKeyword)
        {
            if (string.IsNullOrWhiteSpace(systemKeyword))
            {
                return(null);
            }

            var store = await _storeContext.GetCurrentStoreAsync();

            var currentLanguage = await _workContext.GetWorkingLanguageAsync();

            var cacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopModelCacheDefaults.PollBySystemNameModelKey,
                                                                         systemKeyword, currentLanguage, store);

            var cachedModel = await _staticCacheManager.GetAsync(cacheKey, async() =>
            {
                var poll = (await _pollService
                            .GetPollsAsync(store.Id, currentLanguage.Id, systemKeyword: systemKeyword))
                           .FirstOrDefault();

                //we do not cache nulls. that's why let's return an empty record (ID = 0)
                if (poll == null)
                {
                    return new PollModel {
                        Id = 0
                    }
                }
                ;

                return(await PreparePollModelAsync(poll, false));
            });
            /// <summary>
            /// Called asynchronously before the action, after model binding is complete.
            /// </summary>
            /// <param name="context">A context for action filters</param>
            /// <returns>A task that on completion indicates the necessary filter actions have been executed</returns>
            private async Task CheckLanguageSeoCodeAsync(ActionExecutingContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                if (context.HttpContext.Request == null)
                {
                    return;
                }

                //only in GET requests
                if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }

                if (!await DataSettingsManager.IsDatabaseInstalledAsync())
                {
                    return;
                }

                //check whether this filter has been overridden for the Action
                var actionFilter = context.ActionDescriptor.FilterDescriptors
                                   .Where(filterDescriptor => filterDescriptor.Scope == FilterScope.Action)
                                   .Select(filterDescriptor => filterDescriptor.Filter)
                                   .OfType <CheckLanguageSeoCodeAttribute>()
                                   .FirstOrDefault();

                //ignore filter (an action doesn't need to be checked)
                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                {
                    return;
                }

                //whether SEO friendly URLs are enabled
                if (!_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
                {
                    return;
                }

                //check whether current page URL is already localized URL
                var pageUrl = _webHelper.GetRawUrl(context.HttpContext.Request);
                var result  = await pageUrl.IsLocalizedUrlAsync(context.HttpContext.Request.PathBase, true);

                if (result.IsLocalized)
                {
                    return;
                }

                //not localized yet, so redirect to the page with working language SEO code
                var language = await _workContext.GetWorkingLanguageAsync();

                pageUrl = pageUrl.AddLanguageSeoCodeToUrl(context.HttpContext.Request.PathBase, true, language);

                context.Result = new LocalRedirectResult(pageUrl, false);
            }
Ejemplo n.º 8
0
        /// <summary>
        /// Prepare blog post list model
        /// </summary>
        /// <param name="command">Blog paging filtering model</param>
        /// <returns>Blog post list model</returns>
        public virtual async Task <BlogPostListModel> PrepareBlogPostListModelAsync(BlogPagingFilteringModel command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            if (command.PageSize <= 0)
            {
                command.PageSize = _blogSettings.PostsPageSize;
            }
            if (command.PageNumber <= 0)
            {
                command.PageNumber = 1;
            }

            var dateFrom = command.GetFromMonth();
            var dateTo   = command.GetToMonth();

            var language = await _workContext.GetWorkingLanguageAsync();

            var store = await _storeContext.GetCurrentStoreAsync();

            var blogPosts = string.IsNullOrEmpty(command.Tag)
                ? await _blogService.GetAllBlogPostsAsync(store.Id, language.Id, dateFrom, dateTo, command.PageNumber - 1, command.PageSize)
                : await _blogService.GetAllBlogPostsByTagAsync(store.Id, language.Id, command.Tag, command.PageNumber - 1, command.PageSize);

            var model = new BlogPostListModel
            {
                PagingFilteringContext = { Tag = command.Tag, Month = command.Month },
                WorkingLanguageId      = language.Id,
                BlogPosts = await blogPosts.SelectAwait(async blogPost =>
                {
                    var blogPostModel = new BlogPostModel();
                    await PrepareBlogPostModelAsync(blogPostModel, blogPost, false);
                    return(blogPostModel);
                }).ToListAsync()
            };

            model.PagingFilteringContext.LoadPagedList(blogPosts);

            return(model);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Prepare the customer order list model
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the customer order list model
        /// </returns>
        public virtual async Task <CustomerOrderListModel> PrepareCustomerOrderListModelAsync()
        {
            var model    = new CustomerOrderListModel();
            var customer = await _workContext.GetCurrentCustomerAsync();

            var store = await _storeContext.GetCurrentStoreAsync();

            var orders = await _orderService.SearchOrdersAsync(storeId : store.Id,
                                                               customerId : customer.Id);

            foreach (var order in orders)
            {
                var orderModel = new CustomerOrderListModel.OrderDetailsModel
                {
                    Id                     = order.Id,
                    CreatedOn              = await _dateTimeHelper.ConvertToUserTimeAsync(order.CreatedOnUtc, DateTimeKind.Utc),
                    OrderStatusEnum        = order.OrderStatus,
                    OrderStatus            = await _localizationService.GetLocalizedEnumAsync(order.OrderStatus),
                    PaymentStatus          = await _localizationService.GetLocalizedEnumAsync(order.PaymentStatus),
                    ShippingStatus         = await _localizationService.GetLocalizedEnumAsync(order.ShippingStatus),
                    IsReturnRequestAllowed = await _orderProcessingService.IsReturnRequestAllowedAsync(order),
                    CustomOrderNumber      = order.CustomOrderNumber
                };
                var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);
                orderModel.OrderTotal = await _priceFormatter.FormatPriceAsync(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, (await _workContext.GetWorkingLanguageAsync()).Id);

                model.Orders.Add(orderModel);
            }

            var recurringPayments = await _orderService.SearchRecurringPaymentsAsync(store.Id,
                                                                                     customer.Id);

            foreach (var recurringPayment in recurringPayments)
            {
                var order = await _orderService.GetOrderByIdAsync(recurringPayment.InitialOrderId);

                var recurringPaymentModel = new CustomerOrderListModel.RecurringOrderModel
                {
                    Id                  = recurringPayment.Id,
                    StartDate           = (await _dateTimeHelper.ConvertToUserTimeAsync(recurringPayment.StartDateUtc, DateTimeKind.Utc)).ToString(),
                    CycleInfo           = $"{recurringPayment.CycleLength} {await _localizationService.GetLocalizedEnumAsync(recurringPayment.CyclePeriod)}",
                    NextPayment         = await _orderProcessingService.GetNextPaymentDateAsync(recurringPayment) is DateTime nextPaymentDate ? (await _dateTimeHelper.ConvertToUserTimeAsync(nextPaymentDate, DateTimeKind.Utc)).ToString() : "",
                    TotalCycles         = recurringPayment.TotalCycles,
                    CyclesRemaining     = await _orderProcessingService.GetCyclesRemainingAsync(recurringPayment),
                    InitialOrderId      = order.Id,
                    InitialOrderNumber  = order.CustomOrderNumber,
                    CanCancel           = await _orderProcessingService.CanCancelRecurringPaymentAsync(customer, recurringPayment),
                    CanRetryLastPayment = await _orderProcessingService.CanRetryLastRecurringPaymentAsync(customer, recurringPayment)
                };

                model.RecurringOrders.Add(recurringPaymentModel);
            }

            return(model);
        }
        /// <summary>
        /// Prepares the order item models for return request by specified order.
        /// </summary>
        /// <param name="order">Order</param>
        /// <returns>
        /// The <see cref="Task"/> containing the <see cref="IList{SubmitReturnRequestModel.OrderItemModel}"/>
        /// </returns>
        protected virtual async Task <IList <SubmitReturnRequestModel.OrderItemModel> > PrepareSubmitReturnRequestOrderItemModelsAsync(Order order)
        {
            if (order is null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var models = new List <SubmitReturnRequestModel.OrderItemModel>();

            var returnRequestAvailability = await _returnRequestService.GetReturnRequestAvailabilityAsync(order.Id);

            if (returnRequestAvailability?.IsAllowed == true)
            {
                foreach (var returnableOrderItem in returnRequestAvailability.ReturnableOrderItems)
                {
                    if (returnableOrderItem.AvailableQuantityForReturn == 0)
                    {
                        continue;
                    }

                    var orderItem = returnableOrderItem.OrderItem;
                    var product   = await _productService.GetProductByIdAsync(orderItem.ProductId);

                    var model = new SubmitReturnRequestModel.OrderItemModel
                    {
                        Id            = orderItem.Id,
                        ProductId     = product.Id,
                        ProductName   = await _localizationService.GetLocalizedAsync(product, x => x.Name),
                        ProductSeName = await _urlRecordService.GetSeNameAsync(product),
                        AttributeInfo = orderItem.AttributeDescription,
                        Quantity      = returnableOrderItem.AvailableQuantityForReturn
                    };

                    var languageId = (await _workContext.GetWorkingLanguageAsync()).Id;

                    //unit price
                    if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                    {
                        //including tax
                        var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate);
                        model.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);
                    }
                    else
                    {
                        //excluding tax
                        var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate);
                        model.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);
                    }

                    models.Add(model);
                }
            }

            return(models);
        }
        /// <summary>
        /// Prepare the language selector model
        /// </summary>
        /// <returns>Language selector model</returns>
        public virtual async Task <LanguageSelectorModel> PrepareLanguageSelectorModelAsync()
        {
            var availableLanguages = (await _languageService
                                      .GetAllLanguagesAsync(storeId: (await _storeContext.GetCurrentStoreAsync()).Id))
                                     .Select(x => new LanguageModel
            {
                Id   = x.Id,
                Name = x.Name,
                FlagImageFileName = x.FlagImageFileName,
            }).ToList();

            var model = new LanguageSelectorModel
            {
                CurrentLanguageId  = (await _workContext.GetWorkingLanguageAsync()).Id,
                AvailableLanguages = availableLanguages,
                UseImages          = _localizationSettings.UseImagesForLanguageSelection
            };

            return(model);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Prepare language selector model
        /// </summary>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the language selector model
        /// </returns>
        public virtual async Task<LanguageSelectorModel> PrepareLanguageSelectorModelAsync()
        {
            var model = new LanguageSelectorModel
            {
                CurrentLanguage = (await _workContext.GetWorkingLanguageAsync()).ToModel<LanguageModel>(),
                AvailableLanguages = (await _languageService
                    .GetAllLanguagesAsync(storeId: (await _storeContext.GetCurrentStoreAsync()).Id))
                    .Select(language => language.ToModel<LanguageModel>()).ToList()
            };

            return model;
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> SearchTermAutoComplete(string term)
        {
            if (string.IsNullOrWhiteSpace(term))
            {
                return(Content(""));
            }

            term = term.Trim();

            if (string.IsNullOrWhiteSpace(term) || term.Length < _catalogSettings.ProductSearchTermMinimumLength)
            {
                return(Content(""));
            }

            //products
            var productNumber = _catalogSettings.ProductSearchAutoCompleteNumberOfProducts > 0 ?
                                _catalogSettings.ProductSearchAutoCompleteNumberOfProducts : 10;

            IPagedList <Product> products = null;

            if (_luceneSettings.AutoCompleteSearchEnabled)
            {
                _luceneService.GetLuceneDirectory();

                var luceneProducts = _luceneService.Search(term);

                products = await luceneProducts.AsQueryable().ToPagedListAsync(0, productNumber);
            }
            else
            {
                products = await _productService.SearchProductsAsync(
                    storeId : (await _storeContext.GetCurrentStoreAsync()).Id,
                    keywords : term,
                    languageId : (await _workContext.GetWorkingLanguageAsync()).Id,
                    visibleIndividuallyOnly : true,
                    pageSize : productNumber);
            }

            var showLinkToResultSearch = _catalogSettings.ShowLinkToAllResultInSearchAutoComplete && (products.TotalCount > productNumber);

            var models = (await _productModelFactory.PrepareProductOverviewModelsAsync(products, false, _catalogSettings.ShowProductImagesInSearchAutoComplete, _mediaSettings.AutoCompleteSearchThumbPictureSize)).ToList();
            var result = (from p in models
                          select new
            {
                label = p.Name,
                producturl = Url.RouteUrl("Product", new { SeName = p.SeName }),
                productpictureurl = p.DefaultPictureModel.ImageUrl,
                showlinktoresultsearch = showLinkToResultSearch
            })
                         .ToList();

            return(Json(result));
        }
Ejemplo n.º 14
0
        public virtual async Task <IActionResult> SetLanguage(int langid, string returnUrl = "")
        {
            var language = await _languageService.GetLanguageByIdAsync(langid);

            if (!language?.Published ?? false)
            {
                language = await _workContext.GetWorkingLanguageAsync();
            }

            //home page
            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = Url.RouteUrl("Homepage");
            }

            //language part in URL
            if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                //remove current language code if it's already localized URL
                if ((await returnUrl.IsLocalizedUrlAsync(Request.PathBase, true)).IsLocalized)
                {
                    returnUrl = returnUrl.RemoveLanguageSeoCodeFromUrl(Request.PathBase, true);
                }

                //and add code of passed language
                returnUrl = returnUrl.AddLanguageSeoCodeToUrl(Request.PathBase, true, language);
            }

            await _workContext.SetWorkingLanguageAsync(language);

            //prevent open redirection attack
            if (!Url.IsLocalUrl(returnUrl))
            {
                returnUrl = Url.RouteUrl("Homepage");
            }

            return(Redirect(returnUrl));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Asynchronously executes the tag helper with the given context and output
        /// </summary>
        /// <param name="context">Contains information associated with the current HTML tag</param>
        /// <param name="output">A stateful HTML element used to generate an HTML tag</param>
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            //generate label
            var tagBuilder = Generator.GenerateLabel(ViewContext, For.ModelExplorer, For.Name, null, new { @class = "col-form-label" });

            if (tagBuilder != null)
            {
                //create a label wrapper
                output.TagName = "div";
                output.TagMode = TagMode.StartTagAndEndTag;

                //merge classes
                var classValue = output.Attributes.ContainsName("class")
                    ? $"{output.Attributes["class"].Value} label-wrapper"
                    : "label-wrapper";
                output.Attributes.SetAttribute("class", classValue);

                //add label
                output.Content.SetHtmlContent(tagBuilder);

                //add hint
                if (DisplayHint && For.Metadata.AdditionalValues.TryGetValue("NopResourceDisplayNameAttribute", out var value) &&
                    value is NopResourceDisplayNameAttribute resourceDisplayName)
                {
                    var language = await _workContext.GetWorkingLanguageAsync();

                    var hintResource = await _localizationService
                                       .GetResourceAsync($"{resourceDisplayName.ResourceKey}.Hint", language.Id, returnEmptyIfNotFound : true, logIfNotFound : false);

                    if (!string.IsNullOrEmpty(hintResource))
                    {
                        var hintContent = $"<div title='{WebUtility.HtmlEncode(hintResource)}' data-toggle='tooltip' class='ico-help'><i class='fas fa-question-circle'></i></div>";
                        output.Content.AppendHtml(hintContent);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public virtual async Task <IActionResult> Index()
        {
            //display a warning to a store owner if there are some error
            var customer = await _workContext.GetCurrentCustomerAsync();

            var hideCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.HideConfigurationStepsAttribute);

            var closeCard = await _genericAttributeService.GetAttributeAsync <bool>(customer, NopCustomerDefaults.CloseConfigurationStepsAttribute);

            if ((hideCard || closeCard) && await _permissionService.AuthorizeAsync(StandardPermissionProvider.ManageMaintenance))
            {
                var warnings = await _commonModelFactory.PrepareSystemWarningModelsAsync();

                if (warnings.Any(warning => warning.Level == SystemWarningLevel.Fail ||
                                 warning.Level == SystemWarningLevel.CopyrightRemovalKey ||
                                 warning.Level == SystemWarningLevel.Warning))
                {
                    _notificationService.WarningNotification(
                        string.Format(await _localizationService.GetResourceAsync("Admin.System.Warnings.Errors"),
                                      Url.Action("Warnings", "Common")),
                        //do not encode URLs
                        false);
                }
            }

            //progress of localozation
            var currentLanguage = await _workContext.GetWorkingLanguageAsync();

            var progress = await _genericAttributeService.GetAttributeAsync <string>(currentLanguage, NopCommonDefaults.LanguagePackProgressAttribute);

            if (!string.IsNullOrEmpty(progress))
            {
                var locale = await _localizationService.GetResourceAsync("Admin.Configuration.LanguagePackProgressMessage");

                _notificationService.SuccessNotification(string.Format(locale, progress, NopLinksDefaults.OfficialSite.Translations), false);
                await _genericAttributeService.SaveAttributeAsync(currentLanguage, NopCommonDefaults.LanguagePackProgressAttribute, string.Empty);
            }

            //prepare model
            var model = await _homeModelFactory.PrepareDashboardModelAsync(new DashboardModel());

            return(View(model));
        }
        /// <summary>
        /// Prepare the order item model
        /// </summary>
        /// <param name="orderItem">Order item</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the order item model
        /// </returns>
        public virtual async Task <SubmitReturnRequestModel.OrderItemModel> PrepareSubmitReturnRequestOrderItemModelAsync(OrderItem orderItem)
        {
            if (orderItem == null)
            {
                throw new ArgumentNullException(nameof(orderItem));
            }

            var order = await _orderService.GetOrderByIdAsync(orderItem.OrderId);

            var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

            var model = new SubmitReturnRequestModel.OrderItemModel
            {
                Id            = orderItem.Id,
                ProductId     = product.Id,
                ProductName   = await _localizationService.GetLocalizedAsync(product, x => x.Name),
                ProductSeName = await _urlRecordService.GetSeNameAsync(product),
                AttributeInfo = orderItem.AttributeDescription,
                Quantity      = orderItem.Quantity
            };

            var languageId = (await _workContext.GetWorkingLanguageAsync()).Id;

            //unit price
            if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
            {
                //including tax
                var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate);
                model.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, true);
            }
            else
            {
                //excluding tax
                var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate);
                model.UnitPrice = await _priceFormatter.FormatPriceAsync(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, languageId, false);
            }

            return(model);
        }
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="attributesXml">Attributes in XML format</param>
        /// <param name="customer">Customer</param>
        /// <param name="separator">Separator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="renderPrices">A value indicating whether to render prices</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperlink tags could be rendered (if required)</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the attributes
        /// </returns>
        public virtual async Task <string> FormatAttributesAsync(string attributesXml,
                                                                 Customer customer,
                                                                 string separator     = "<br />",
                                                                 bool htmlEncode      = true,
                                                                 bool renderPrices    = true,
                                                                 bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            var attributes = await _checkoutAttributeParser.ParseCheckoutAttributesAsync(attributesXml);

            for (var i = 0; i < attributes.Count; i++)
            {
                var attribute = attributes[i];
                var valuesStr = _checkoutAttributeParser.ParseValues(attributesXml, attribute.Id);
                for (var j = 0; j < valuesStr.Count; j++)
                {
                    var valueStr           = valuesStr[j];
                    var formattedAttribute = string.Empty;
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = await _localizationService.GetLocalizedAsync(attribute, a => a.Name, (await _workContext.GetWorkingLanguageAsync()).Id);

                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = $"{attributeName}: {HtmlHelper.FormatText(valueStr, false, true, false, false, false, false)}";
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid.TryParse(valueStr, out var downloadGuid);
                            var download = await _downloadService.GetDownloadByGuidAsync(downloadGuid);

                            if (download != null)
                            {
                                string attributeText;
                                var    fileName = $"{download.Filename ?? download.DownloadGuid.ToString()}{download.Extension}";
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = $"{_webHelper.GetStoreLocation(false)}download/getfileupload/?downloadId={download.DownloadGuid}";
                                    attributeText = $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{fileName}</a>";
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }

                                var attributeName = await _localizationService.GetLocalizedAsync(attribute, a => a.Name, (await _workContext.GetWorkingLanguageAsync()).Id);

                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = $"{attributeName}: {attributeText}";
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = $"{await _localizationService.GetLocalizedAsync(attribute, a => a.Name, (await _workContext.GetWorkingLanguageAsync()).Id)}: {valueStr}";
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        if (int.TryParse(valueStr, out var attributeValueId))
                        {
                            var attributeValue = await _checkoutAttributeService.GetCheckoutAttributeValueByIdAsync(attributeValueId);

                            if (attributeValue != null)
                            {
                                formattedAttribute = $"{await _localizationService.GetLocalizedAsync(attribute, a => a.Name, (await _workContext.GetWorkingLanguageAsync()).Id)}: {await _localizationService.GetLocalizedAsync(attributeValue, a => a.Name, (await _workContext.GetWorkingLanguageAsync()).Id)}";
                                if (renderPrices)
                                {
                                    var priceAdjustmentBase = (await _taxService.GetCheckoutAttributePriceAsync(attribute, attributeValue, customer)).price;
                                    var priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(priceAdjustmentBase, await _workContext.GetWorkingCurrencyAsync());

                                    if (priceAdjustmentBase > 0)
                                    {
                                        formattedAttribute += string.Format(
                                            await _localizationService.GetResourceAsync("FormattedAttributes.PriceAdjustment"),
                                            "+", await _priceFormatter.FormatPriceAsync(priceAdjustment), string.Empty);
                                    }
                                }
                            }

                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(formattedAttribute))
                    {
                        continue;
                    }

                    if (i != 0 || j != 0)
                    {
                        result.Append(separator);
                    }
                    result.Append(formattedAttribute);
                }
            }

            return(result.ToString());
        }
        /// <summary>
        /// Register new user
        /// </summary>
        /// <param name="parameters">Authentication parameters received from external authentication method</param>
        /// <param name="returnUrl">URL to which the user will return after authentication</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the result of an authentication
        /// </returns>
        protected virtual async Task <IActionResult> RegisterNewUserAsync(ExternalAuthenticationParameters parameters, string returnUrl)
        {
            //check whether the specified email has been already registered
            if (await _customerService.GetCustomerByEmailAsync(parameters.Email) != null)
            {
                var alreadyExistsError = string.Format(await _localizationService.GetResourceAsync("Account.AssociatedExternalAuth.EmailAlreadyExists"),
                                                       !string.IsNullOrEmpty(parameters.ExternalDisplayIdentifier) ? parameters.ExternalDisplayIdentifier : parameters.ExternalIdentifier);
                return(ErrorAuthentication(new[] { alreadyExistsError }, returnUrl));
            }

            //registration is approved if validation isn't required
            var registrationIsApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard ||
                                         (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation && !_externalAuthenticationSettings.RequireEmailValidation);

            //create registration request
            var registrationRequest = new CustomerRegistrationRequest(await _workContext.GetCurrentCustomerAsync(),
                                                                      parameters.Email, parameters.Email,
                                                                      CommonHelper.GenerateRandomDigitCode(20),
                                                                      PasswordFormat.Hashed,
                                                                      (await _storeContext.GetCurrentStoreAsync()).Id,
                                                                      registrationIsApproved);

            //whether registration request has been completed successfully
            var registrationResult = await _customerRegistrationService.RegisterCustomerAsync(registrationRequest);

            if (!registrationResult.Success)
            {
                return(ErrorAuthentication(registrationResult.Errors, returnUrl));
            }

            //allow to save other customer values by consuming this event
            await _eventPublisher.PublishAsync(new CustomerAutoRegisteredByExternalMethodEvent(await _workContext.GetCurrentCustomerAsync(), parameters));

            //raise customer registered event
            await _eventPublisher.PublishAsync(new CustomerRegisteredEvent(await _workContext.GetCurrentCustomerAsync()));

            //store owner notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                await _workflowMessageService.SendCustomerRegisteredNotificationMessageAsync(await _workContext.GetCurrentCustomerAsync(), _localizationSettings.DefaultAdminLanguageId);
            }

            //associate external account with registered user
            await AssociateExternalAccountWithUserAsync(await _workContext.GetCurrentCustomerAsync(), parameters);

            //authenticate
            if (registrationIsApproved)
            {
                await _workflowMessageService.SendCustomerWelcomeMessageAsync(await _workContext.GetCurrentCustomerAsync(), (await _workContext.GetWorkingLanguageAsync()).Id);

                //raise event
                await _eventPublisher.PublishAsync(new CustomerActivatedEvent(await _workContext.GetCurrentCustomerAsync()));

                return(await _customerRegistrationService.SignInCustomerAsync(await _workContext.GetCurrentCustomerAsync(), returnUrl, true));
            }

            //registration is succeeded but isn't activated
            if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation)
            {
                //email validation message
                await _genericAttributeService.SaveAttributeAsync(await _workContext.GetCurrentCustomerAsync(), NopCustomerDefaults.AccountActivationTokenAttribute, Guid.NewGuid().ToString());

                await _workflowMessageService.SendCustomerEmailValidationMessageAsync(await _workContext.GetCurrentCustomerAsync(), (await _workContext.GetWorkingLanguageAsync()).Id);

                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation, returnUrl }));
            }

            //registration is succeeded but isn't approved by admin
            if (_customerSettings.UserRegistrationType == UserRegistrationType.AdminApproval)
            {
                return(new RedirectToRouteResult("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval, returnUrl }));
            }

            return(ErrorAuthentication(new[] { "Error on registration" }, returnUrl));
        }
        /// <summary>
        /// Format vendor attributes
        /// </summary>
        /// <param name="attributesXml">Attributes in XML format</param>
        /// <param name="separator">Separator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the formatted attributes
        /// </returns>
        public virtual async Task <string> FormatAttributesAsync(string attributesXml, string separator = "<br />", bool htmlEncode = true)
        {
            var result          = new StringBuilder();
            var currentLanguage = await _workContext.GetWorkingLanguageAsync();

            var attributes = await _vendorAttributeParser.ParseVendorAttributesAsync(attributesXml);

            for (var i = 0; i < attributes.Count; i++)
            {
                var attribute = attributes[i];
                var valuesStr = _vendorAttributeParser.ParseValues(attributesXml, attribute.Id);
                for (var j = 0; j < valuesStr.Count; j++)
                {
                    var valueStr           = valuesStr[j];
                    var formattedAttribute = string.Empty;
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = await _localizationService.GetLocalizedAsync(attribute, a => a.Name, currentLanguage.Id);

                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = $"{attributeName}: {_htmlFormatter.FormatText(valueStr, false, true, false, false, false, false)}";
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
                        {
                            //file upload
                            //not supported for vendor attributes
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = $"{await _localizationService.GetLocalizedAsync(attribute, a => a.Name, currentLanguage.Id)}: {valueStr}";
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        if (int.TryParse(valueStr, out var attributeValueId))
                        {
                            var attributeValue = await _vendorAttributeService.GetVendorAttributeValueByIdAsync(attributeValueId);

                            if (attributeValue != null)
                            {
                                formattedAttribute = $"{await _localizationService.GetLocalizedAsync(attribute, a => a.Name, currentLanguage.Id)}: {await _localizationService.GetLocalizedAsync(attributeValue, a => a.Name, currentLanguage.Id)}";
                            }
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(formattedAttribute))
                    {
                        continue;
                    }

                    if (i != 0 || j != 0)
                    {
                        result.Append(separator);
                    }
                    result.Append(formattedAttribute);
                }
            }

            return(result.ToString());
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            var model = new PaymentInfoModel
            {
                DescriptionText = await _localizationService.GetLocalizedSettingAsync(_checkMoneyOrderPaymentSettings,
                                                                                      x => x.DescriptionText, (await _workContext.GetWorkingLanguageAsync()).Id, (await _storeContext.GetCurrentStoreAsync()).Id)
            };

            return(View("~/Plugins/Payments.CheckMoneyOrder/Views/PaymentInfo.cshtml", model));
        }
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task <IActionResult> ProductEmailAFriendSend(ProductEmailAFriendModel model, bool captchaValid)
        {
            var product = await _productService.GetProductByIdAsync(model.ProductId);

            if (product == null || product.Deleted || !product.Published || !_catalogSettings.EmailAFriendEnabled)
            {
                return(RedirectToRoute("Homepage"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnEmailProductToFriendPage && !captchaValid)
            {
                ModelState.AddModelError("", await _localizationService.GetResourceAsync("Common.WrongCaptchaMessage"));
            }

            //check whether the current customer is guest and ia allowed to email a friend
            if (await _customerService.IsGuestAsync(await _workContext.GetCurrentCustomerAsync()) && !_catalogSettings.AllowAnonymousUsersToEmailAFriend)
            {
                ModelState.AddModelError("", await _localizationService.GetResourceAsync("Products.EmailAFriend.OnlyRegisteredUsers"));
            }

            if (ModelState.IsValid)
            {
                //email
                await _workflowMessageService.SendProductEmailAFriendMessageAsync(await _workContext.GetCurrentCustomerAsync(),
                                                                                  (await _workContext.GetWorkingLanguageAsync()).Id, product,
                                                                                  model.YourEmailAddress, model.FriendEmail,
                                                                                  Core.Html.HtmlHelper.FormatText(model.PersonalMessage, false, true, false, false, false, false));

                model = await _productModelFactory.PrepareProductEmailAFriendModelAsync(model, product, true);

                model.SuccessfullySent = true;
                model.Result           = await _localizationService.GetResourceAsync("Products.EmailAFriend.SuccessfullySent");

                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            model = await _productModelFactory.PrepareProductEmailAFriendModelAsync(model, product, true);

            return(View(model));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Prepare address model
        /// </summary>
        /// <param name="model">Address model</param>
        /// <param name="address">Address entity</param>
        /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param>
        /// <param name="addressSettings">Address settings</param>
        /// <param name="loadCountries">Countries loading function; pass null if countries do not need to load</param>
        /// <param name="prePopulateWithCustomerFields">Whether to populate model properties with the customer fields (used with the customer entity)</param>
        /// <param name="customer">Customer entity; required if prePopulateWithCustomerFields is true</param>
        /// <param name="overrideAttributesXml">Overridden address attributes in XML format; pass null to use CustomAttributes of the address entity</param>
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task PrepareAddressModelAsync(AddressModel model,
                                                           Address address, bool excludeProperties,
                                                           AddressSettings addressSettings,
                                                           Func <Task <IList <Country> > > loadCountries = null,
                                                           bool prePopulateWithCustomerFields            = false,
                                                           Customer customer            = null,
                                                           string overrideAttributesXml = "")
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (addressSettings == null)
            {
                throw new ArgumentNullException(nameof(addressSettings));
            }

            if (!excludeProperties && address != null)
            {
                model.Id          = address.Id;
                model.FirstName   = address.FirstName;
                model.LastName    = address.LastName;
                model.Email       = address.Email;
                model.Company     = address.Company;
                model.CountryId   = address.CountryId;
                model.CountryName = await _countryService.GetCountryByAddressAsync(address) is Country country ? await _localizationService.GetLocalizedAsync(country, x => x.Name) : null;

                model.StateProvinceId   = address.StateProvinceId;
                model.StateProvinceName = await _stateProvinceService.GetStateProvinceByAddressAsync(address) is StateProvince stateProvince ? await _localizationService.GetLocalizedAsync(stateProvince, x => x.Name) : null;

                model.County        = address.County;
                model.City          = address.City;
                model.Address1      = address.Address1;
                model.Address2      = address.Address2;
                model.ZipPostalCode = address.ZipPostalCode;
                model.PhoneNumber   = address.PhoneNumber;
                model.FaxNumber     = address.FaxNumber;
            }

            if (address == null && prePopulateWithCustomerFields)
            {
                if (customer == null)
                {
                    throw new Exception("Customer cannot be null when prepopulating an address");
                }
                model.Email     = customer.Email;
                model.FirstName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FirstNameAttribute);

                model.LastName = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.LastNameAttribute);

                model.Company = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CompanyAttribute);

                model.Address1 = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.StreetAddressAttribute);

                model.Address2 = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.StreetAddress2Attribute);

                model.ZipPostalCode = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.ZipPostalCodeAttribute);

                model.City = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CityAttribute);

                model.County = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.CountyAttribute);

                model.PhoneNumber = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.PhoneAttribute);

                model.FaxNumber = await _genericAttributeService.GetAttributeAsync <string>(customer, NopCustomerDefaults.FaxAttribute);
            }

            //countries and states
            if (addressSettings.CountryEnabled && loadCountries != null)
            {
                var countries = await loadCountries();

                if (_addressSettings.PreselectCountryIfOnlyOne && countries.Count == 1)
                {
                    model.CountryId = countries[0].Id;
                }
                else
                {
                    model.AvailableCountries.Add(new SelectListItem {
                        Text = await _localizationService.GetResourceAsync("Address.SelectCountry"), Value = "0"
                    });
                }

                foreach (var c in countries)
                {
                    model.AvailableCountries.Add(new SelectListItem
                    {
                        Text     = await _localizationService.GetLocalizedAsync(c, x => x.Name),
                        Value    = c.Id.ToString(),
                        Selected = c.Id == model.CountryId
                    });
                }

                if (addressSettings.StateProvinceEnabled)
                {
                    var languageId = (await _workContext.GetWorkingLanguageAsync()).Id;
                    var states     = (await _stateProvinceService
                                      .GetStateProvincesByCountryIdAsync(model.CountryId ?? 0, languageId))
                                     .ToList();
                    if (states.Any())
                    {
                        model.AvailableStates.Add(new SelectListItem {
                            Text = await _localizationService.GetResourceAsync("Address.SelectState"), Value = "0"
                        });

                        foreach (var s in states)
                        {
                            model.AvailableStates.Add(new SelectListItem
                            {
                                Text     = await _localizationService.GetLocalizedAsync(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  = await _localizationService.GetResourceAsync(anyCountrySelected ? "Address.Other" : "Address.SelectState"),
                            Value = "0"
                        });
                    }
                }
            }

            //form fields
            model.CompanyEnabled         = addressSettings.CompanyEnabled;
            model.CompanyRequired        = addressSettings.CompanyRequired;
            model.StreetAddressEnabled   = addressSettings.StreetAddressEnabled;
            model.StreetAddressRequired  = addressSettings.StreetAddressRequired;
            model.StreetAddress2Enabled  = addressSettings.StreetAddress2Enabled;
            model.StreetAddress2Required = addressSettings.StreetAddress2Required;
            model.ZipPostalCodeEnabled   = addressSettings.ZipPostalCodeEnabled;
            model.ZipPostalCodeRequired  = addressSettings.ZipPostalCodeRequired;
            model.CityEnabled            = addressSettings.CityEnabled;
            model.CityRequired           = addressSettings.CityRequired;
            model.CountyEnabled          = addressSettings.CountyEnabled;
            model.CountyRequired         = addressSettings.CountyRequired;
            model.CountryEnabled         = addressSettings.CountryEnabled;
            model.StateProvinceEnabled   = addressSettings.StateProvinceEnabled;
            model.PhoneEnabled           = addressSettings.PhoneEnabled;
            model.PhoneRequired          = addressSettings.PhoneRequired;
            model.FaxEnabled             = addressSettings.FaxEnabled;
            model.FaxRequired            = addressSettings.FaxRequired;

            //customer attribute services
            if (_addressAttributeService != null && _addressAttributeParser != null)
            {
                await PrepareCustomAddressAttributesAsync(model, address, overrideAttributesXml);
            }
            if (_addressAttributeFormatter != null && address != null)
            {
                model.FormattedCustomAddressAttributes = await _addressAttributeFormatter.FormatAttributesAsync(address.CustomAttributes);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Prepare the forum topic page model
        /// </summary>
        /// <param name="forumTopic">Forum topic</param>
        /// <param name="page">Number of forum posts page</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the forum topic page model
        /// </returns>
        public virtual async Task <ForumTopicPageModel> PrepareForumTopicPageModelAsync(ForumTopic forumTopic, int page)
        {
            if (forumTopic == null)
            {
                throw new ArgumentNullException(nameof(forumTopic));
            }

            //load posts
            var posts = await _forumService.GetAllPostsAsync(forumTopic.Id, 0, string.Empty,
                                                             page - 1, _forumSettings.PostsPageSize);

            //prepare model
            var model = new ForumTopicPageModel
            {
                Id      = forumTopic.Id,
                Subject = forumTopic.Subject,
                SeName  = await _forumService.GetTopicSeNameAsync(forumTopic),

                IsCustomerAllowedToEditTopic   = await _forumService.IsCustomerAllowedToEditTopicAsync(await _workContext.GetCurrentCustomerAsync(), forumTopic),
                IsCustomerAllowedToDeleteTopic = await _forumService.IsCustomerAllowedToDeleteTopicAsync(await _workContext.GetCurrentCustomerAsync(), forumTopic),
                IsCustomerAllowedToMoveTopic   = await _forumService.IsCustomerAllowedToMoveTopicAsync(await _workContext.GetCurrentCustomerAsync(), forumTopic),
                IsCustomerAllowedToSubscribe   = await _forumService.IsCustomerAllowedToSubscribeAsync(await _workContext.GetCurrentCustomerAsync())
            };

            if (model.IsCustomerAllowedToSubscribe)
            {
                model.WatchTopicText = await _localizationService.GetResourceAsync("Forum.WatchTopic");

                var forumTopicSubscription = (await _forumService.GetAllSubscriptionsAsync((await _workContext.GetCurrentCustomerAsync()).Id, 0, forumTopic.Id, 0, 1)).FirstOrDefault();
                if (forumTopicSubscription != null)
                {
                    model.WatchTopicText = await _localizationService.GetResourceAsync("Forum.UnwatchTopic");
                }
            }
            model.PostsPageIndex    = posts.PageIndex;
            model.PostsPageSize     = posts.PageSize;
            model.PostsTotalRecords = posts.TotalCount;
            foreach (var post in posts)
            {
                var customer = await _customerService.GetCustomerByIdAsync(post.CustomerId);

                var customerIsGuest = await _customerService.IsGuestAsync(customer);

                var customerIsModerator = customerIsGuest ? false : await _customerService.IsForumModeratorAsync(customer);

                var forumPostModel = new ForumPostModel
                {
                    Id               = post.Id,
                    ForumTopicId     = post.TopicId,
                    ForumTopicSeName = await _forumService.GetTopicSeNameAsync(forumTopic),
                    FormattedText    = _forumService.FormatPostText(post),
                    IsCurrentCustomerAllowedToEditPost   = await _forumService.IsCustomerAllowedToEditPostAsync(await _workContext.GetCurrentCustomerAsync(), post),
                    IsCurrentCustomerAllowedToDeletePost = await _forumService.IsCustomerAllowedToDeletePostAsync(await _workContext.GetCurrentCustomerAsync(), post),
                    CustomerId               = post.CustomerId,
                    AllowViewingProfiles     = _customerSettings.AllowViewingProfiles && !customerIsGuest,
                    CustomerName             = await _customerService.FormatUsernameAsync(customer),
                    IsCustomerForumModerator = customerIsModerator,
                    ShowCustomersPostCount   = _forumSettings.ShowCustomersPostCount,
                    ForumPostCount           = await _genericAttributeService.GetAttributeAsync <Customer, int>(post.CustomerId, NopCustomerDefaults.ForumPostCountAttribute),
                    ShowCustomersJoinDate    = _customerSettings.ShowCustomersJoinDate && !customerIsGuest,
                    CustomerJoinDate         = customer?.CreatedOnUtc ?? DateTime.Now,
                    AllowPrivateMessages     = _forumSettings.AllowPrivateMessages && !customerIsGuest,
                    SignaturesEnabled        = _forumSettings.SignaturesEnabled,
                    FormattedSignature       = _forumService.FormatForumSignatureText(await _genericAttributeService.GetAttributeAsync <Customer, string>(post.CustomerId, NopCustomerDefaults.SignatureAttribute)),
                };
                //created on string
                var languageCode = (await _workContext.GetWorkingLanguageAsync()).LanguageCulture;
                if (_forumSettings.RelativeDateTimeFormattingEnabled)
                {
                    var postCreatedAgo = post.CreatedOnUtc.RelativeFormat(languageCode);
                    forumPostModel.PostCreatedOnStr = string.Format(await _localizationService.GetResourceAsync("Common.RelativeDateTime.Past"), postCreatedAgo);
                }
                else
                {
                    forumPostModel.PostCreatedOnStr =
                        (await _dateTimeHelper.ConvertToUserTimeAsync(post.CreatedOnUtc, DateTimeKind.Utc)).ToString("f");
                }
                //avatar
                if (_customerSettings.AllowCustomersToUploadAvatars)
                {
                    forumPostModel.CustomerAvatarUrl = await _pictureService.GetPictureUrlAsync(
                        await _genericAttributeService.GetAttributeAsync <Customer, int>(post.CustomerId, NopCustomerDefaults.AvatarPictureIdAttribute),
                        _mediaSettings.AvatarPictureSize,
                        _customerSettings.DefaultAvatarEnabled,
                        defaultPictureType : PictureType.Avatar);
                }
                //location
                forumPostModel.ShowCustomersLocation = _customerSettings.ShowCustomersLocation && !customerIsGuest;
                if (_customerSettings.ShowCustomersLocation)
                {
                    var countryId = await _genericAttributeService.GetAttributeAsync <Customer, int>(post.CustomerId, NopCustomerDefaults.CountryIdAttribute);

                    var country = await _countryService.GetCountryByIdAsync(countryId);

                    forumPostModel.CustomerLocation = country != null ? await _localizationService.GetLocalizedAsync(country, x => x.Name) : string.Empty;
                }

                //votes
                if (_forumSettings.AllowPostVoting)
                {
                    forumPostModel.AllowPostVoting = true;
                    forumPostModel.VoteCount       = post.VoteCount;
                    var postVote = await _forumService.GetPostVoteAsync(post.Id, await _workContext.GetCurrentCustomerAsync());

                    if (postVote != null)
                    {
                        forumPostModel.VoteIsUp = postVote.IsUp;
                    }
                }

                // page number is needed for creating post link in _ForumPost partial view
                forumPostModel.CurrentTopicPage = page;
                model.ForumPostModels.Add(forumPostModel);
            }

            return(model);
        }
        /// <summary>
        /// Get category breadcrumb
        /// </summary>
        /// <param name="category">Category</param>
        /// <param name="allCategories">All categories</param>
        /// <param name="showHidden">A value indicating whether to load hidden records</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the category breadcrumb
        /// </returns>
        public virtual async Task <IList <Category> > GetCategoryBreadCrumbAsync(Category category, IList <Category> allCategories = null, bool showHidden = false)
        {
            if (category == null)
            {
                throw new ArgumentNullException(nameof(category));
            }

            var breadcrumbCacheKey = _staticCacheManager.PrepareKeyForDefaultCache(NopCatalogDefaults.CategoryBreadcrumbCacheKey,
                                                                                   category,
                                                                                   await _customerService.GetCustomerRoleIdsAsync(await _workContext.GetCurrentCustomerAsync()),
                                                                                   await _storeContext.GetCurrentStoreAsync(),
                                                                                   await _workContext.GetWorkingLanguageAsync());

            return(await _staticCacheManager.GetAsync(breadcrumbCacheKey, async() =>
            {
                var result = new List <Category>();

                //used to prevent circular references
                var alreadyProcessedCategoryIds = new List <int>();

                while (category != null &&                                                    //not null
                       !category.Deleted &&                                                   //not deleted
                       (showHidden || category.Published) &&                                  //published
                       (showHidden || await _aclService.AuthorizeAsync(category)) &&          //ACL
                       (showHidden || await _storeMappingService.AuthorizeAsync(category)) && //Store mapping
                       !alreadyProcessedCategoryIds.Contains(category.Id))                    //prevent circular references
                {
                    result.Add(category);

                    alreadyProcessedCategoryIds.Add(category.Id);

                    category = allCategories != null
                        ? allCategories.FirstOrDefault(c => c.Id == category.ParentCategoryId)
                        : await GetCategoryByIdAsync(category.ParentCategoryId);
                }

                result.Reverse();

                return result;
            }));
        }
        /// <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>
        /// <returns>A task that represents the asynchronous operation</returns>
        public virtual async Task SetEmailAsync(Customer customer, string newEmail, bool requireValidation)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

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

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

            if (!CommonHelper.IsValidEmail(newEmail))
            {
                throw new NopException(await _localizationService.GetResourceAsync("Account.EmailUsernameErrors.NewEmailIsNotValid"));
            }

            if (newEmail.Length > 100)
            {
                throw new NopException(await _localizationService.GetResourceAsync("Account.EmailUsernameErrors.EmailTooLong"));
            }

            var customer2 = await _customerService.GetCustomerByEmailAsync(newEmail);

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

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

                //email re-validation message
                await _genericAttributeService.SaveAttributeAsync(customer, NopCustomerDefaults.EmailRevalidationTokenAttribute, Guid.NewGuid().ToString());

                await _workflowMessageService.SendCustomerEmailRevalidationMessageAsync(customer, (await _workContext.GetWorkingLanguageAsync()).Id);
            }
            else
            {
                customer.Email = newEmail;
                await _customerService.UpdateCustomerAsync(customer);

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

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

                    if (subscriptionOld == null)
                    {
                        continue;
                    }

                    subscriptionOld.Email = newEmail;
                    await _newsLetterSubscriptionService.UpdateNewsLetterSubscriptionAsync(subscriptionOld);
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Get states and provinces by country identifier
        /// </summary>
        /// <param name="countryId">Country identifier</param>
        /// <param name="addSelectStateItem">Whether to add "Select state" item to list of states</param>
        /// <returns>List of identifiers and names of states and provinces</returns>
        public virtual async Task <IList <StateProvinceModel> > GetStatesByCountryIdAsync(string countryId, bool addSelectStateItem)
        {
            if (string.IsNullOrEmpty(countryId))
            {
                throw new ArgumentNullException(nameof(countryId));
            }

            var country = await _countryService.GetCountryByIdAsync(Convert.ToInt32(countryId));

            var states = (await _stateProvinceService
                          .GetStateProvincesByCountryIdAsync(country?.Id ?? 0, (await _workContext.GetWorkingLanguageAsync()).Id))
                         .ToList();
            var result = new List <StateProvinceModel>();

            foreach (var state in states)
            {
                result.Add(new StateProvinceModel
                {
                    id   = state.Id,
                    name = await _localizationService.GetLocalizedAsync(state, x => x.Name)
                });
            }

            if (country == null)
            {
                //country is not selected ("choose country" item)
                if (addSelectStateItem)
                {
                    result.Insert(0, new StateProvinceModel
                    {
                        id   = 0,
                        name = await _localizationService.GetResourceAsync("Address.SelectState")
                    });
                }
                else
                {
                    result.Insert(0, new StateProvinceModel
                    {
                        id   = 0,
                        name = await _localizationService.GetResourceAsync("Address.Other")
                    });
                }
            }
            else
            {
                //some country is selected
                if (!result.Any())
                {
                    //country does not have states
                    result.Insert(0, new StateProvinceModel
                    {
                        id   = 0,
                        name = await _localizationService.GetResourceAsync("Address.Other")
                    });
                }
                else
                {
                    //country has some states
                    if (addSelectStateItem)
                    {
                        result.Insert(0, new StateProvinceModel
                        {
                            id   = 0,
                            name = await _localizationService.GetResourceAsync("Address.SelectState")
                        });
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 28
0
        public virtual async Task <IActionResult> SubscribeNewsletter(string email, bool subscribe)
        {
            string result;
            var    success = false;

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

                var subscription = await _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreIdAsync(email, (await _storeContext.GetCurrentStoreAsync()).Id);

                if (subscription != null)
                {
                    if (subscribe)
                    {
                        if (!subscription.Active)
                        {
                            await _workflowMessageService.SendNewsLetterSubscriptionActivationMessageAsync(
                                subscription,
                                (await _workContext.GetWorkingLanguageAsync()).Id
                                );
                        }
                        result = await _localizationService.GetResourceAsync("Newsletter.SubscribeEmailSent");
                    }
                    else
                    {
                        if (subscription.Active)
                        {
                            await _workflowMessageService.SendNewsLetterSubscriptionDeactivationMessageAsync(
                                subscription,
                                (await _workContext.GetWorkingLanguageAsync()).Id
                                );
                        }
                        result = await _localizationService.GetResourceAsync("Newsletter.UnsubscribeEmailSent");
                    }
                }
                else if (subscribe)
                {
                    try
                    {
                        var freshAddressResponse = await _freshAddressService.ValidateEmailAsync(email);

                        if (!freshAddressResponse.IsValid)
                        {
                            return(Json(new
                            {
                                Success = false,
                                Result = freshAddressResponse.ErrorResponse,
                            }));
                        }
                    }
                    catch (Exception ex)
                    {
                        await _logger.ErrorAsync($"An error occured while trying to validate a Newsletter signup through FreshAddress: {ex}");
                    }

                    subscription = new NewsLetterSubscription
                    {
                        NewsLetterSubscriptionGuid = Guid.NewGuid(),
                        Email        = email,
                        Active       = false,
                        StoreId      = (await _storeContext.GetCurrentStoreAsync()).Id,
                        CreatedOnUtc = DateTime.UtcNow
                    };
                    await _newsLetterSubscriptionService.InsertNewsLetterSubscriptionAsync(subscription);

                    await _workflowMessageService.SendNewsLetterSubscriptionActivationMessageAsync(subscription, (_workContext.GetWorkingLanguageAsync()).Id);

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

            return(Json(new
            {
                Success = success,
                Result = result,
            }));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Prepare the profile posts model
        /// </summary>
        /// <param name="customer">Customer</param>
        /// <param name="page">Number of posts page</param>
        /// <returns>Profile posts model</returns>
        public virtual async Task <ProfilePostsModel> PrepareProfilePostsModelAsync(Customer customer, int page)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            if (page > 0)
            {
                page -= 1;
            }

            var pageSize = _forumSettings.LatestCustomerPostsPageSize;

            var list = await _forumService.GetAllPostsAsync(0, customer.Id, string.Empty, false, page, pageSize);

            var latestPosts = new List <PostsModel>();

            foreach (var forumPost in list)
            {
                var posted = string.Empty;
                if (_forumSettings.RelativeDateTimeFormattingEnabled)
                {
                    var languageCode = (await _workContext.GetWorkingLanguageAsync()).LanguageCulture;
                    var postedAgo    = forumPost.CreatedOnUtc.RelativeFormat(languageCode);
                    posted = string.Format(await _localizationService.GetResourceAsync("Common.RelativeDateTime.Past"), postedAgo);
                }
                else
                {
                    posted = (await _dateTimeHelper.ConvertToUserTimeAsync(forumPost.CreatedOnUtc, DateTimeKind.Utc)).ToString("f");
                }

                var topic = await _forumService.GetTopicByIdAsync(forumPost.TopicId);

                latestPosts.Add(new PostsModel
                {
                    ForumTopicId    = topic.Id,
                    ForumTopicTitle = topic.Subject,
                    ForumTopicSlug  = await _forumService.GetTopicSeNameAsync(topic),
                    ForumPostText   = _forumService.FormatPostText(forumPost),
                    Posted          = posted
                });
            }

            var pagerModel = new PagerModel
            {
                PageSize         = list.PageSize,
                TotalRecords     = list.TotalCount,
                PageIndex        = list.PageIndex,
                ShowTotalSummary = false,
                RouteActionName  = "CustomerProfilePaged",
                UseRouteLinks    = true,
                RouteValues      = new RouteValues {
                    pageNumber = page, id = customer.Id
                }
            };

            var model = new ProfilePostsModel
            {
                PagerModel = pagerModel,
                Posts      = latestPosts,
            };

            return(model);
        }
        /// <summary>
        /// Prepares the checkout pickup points model
        /// </summary>
        /// <param name="cart">Cart</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the checkout pickup points model
        /// </returns>
        protected virtual async Task <CheckoutPickupPointsModel> PrepareCheckoutPickupPointsModelAsync(IList <ShoppingCartItem> cart)
        {
            var model = new CheckoutPickupPointsModel
            {
                AllowPickupInStore = _shippingSettings.AllowPickupInStore
            };

            if (!model.AllowPickupInStore)
            {
                return(model);
            }

            model.DisplayPickupPointsOnMap = _shippingSettings.DisplayPickupPointsOnMap;
            model.GoogleMapsApiKey         = _shippingSettings.GoogleMapsApiKey;
            var pickupPointProviders = await _pickupPluginManager.LoadActivePluginsAsync(await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id);

            if (pickupPointProviders.Any())
            {
                var languageId           = (await _workContext.GetWorkingLanguageAsync()).Id;
                var pickupPointsResponse = await _shippingService.GetPickupPointsAsync((await _workContext.GetCurrentCustomerAsync()).BillingAddressId ?? 0,
                                                                                       await _workContext.GetCurrentCustomerAsync(), storeId : (await _storeContext.GetCurrentStoreAsync()).Id);

                if (pickupPointsResponse.Success)
                {
                    model.PickupPoints = await pickupPointsResponse.PickupPoints.SelectAwait(async point =>
                    {
                        var country = await _countryService.GetCountryByTwoLetterIsoCodeAsync(point.CountryCode);
                        var state   = await _stateProvinceService.GetStateProvinceByAbbreviationAsync(point.StateAbbreviation, country?.Id);

                        var pickupPointModel = new CheckoutPickupPointModel
                        {
                            Id                 = point.Id,
                            Name               = point.Name,
                            Description        = point.Description,
                            ProviderSystemName = point.ProviderSystemName,
                            Address            = point.Address,
                            City               = point.City,
                            County             = point.County,
                            StateName          = state != null ? await _localizationService.GetLocalizedAsync(state, x => x.Name, languageId) : string.Empty,
                            CountryName        = country != null ? await _localizationService.GetLocalizedAsync(country, x => x.Name, languageId) : string.Empty,
                            ZipPostalCode      = point.ZipPostalCode,
                            Latitude           = point.Latitude,
                            Longitude          = point.Longitude,
                            OpeningHours       = point.OpeningHours
                        };

                        var cart   = await _shoppingCartService.GetShoppingCartAsync(await _workContext.GetCurrentCustomerAsync(), ShoppingCartType.ShoppingCart, (await _storeContext.GetCurrentStoreAsync()).Id);
                        var amount = await _orderTotalCalculationService.IsFreeShippingAsync(cart) ? 0 : point.PickupFee;

                        if (amount > 0)
                        {
                            (amount, _) = await _taxService.GetShippingPriceAsync(amount, await _workContext.GetCurrentCustomerAsync());
                            amount      = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(amount, await _workContext.GetWorkingCurrencyAsync());
                            pickupPointModel.PickupFee = await _priceFormatter.FormatShippingPriceAsync(amount, true);
                        }

                        //adjust rate
                        var(shippingTotal, _) = await _orderTotalCalculationService.AdjustShippingRateAsync(point.PickupFee, cart, true);
                        var(rateBase, _)      = await _taxService.GetShippingPriceAsync(shippingTotal, await _workContext.GetCurrentCustomerAsync());
                        var rate = await _currencyService.ConvertFromPrimaryStoreCurrencyAsync(rateBase, await _workContext.GetWorkingCurrencyAsync());
                        pickupPointModel.PickupFee = await _priceFormatter.FormatShippingPriceAsync(rate, true);

                        return(pickupPointModel);
                    }).ToListAsync();
                }
                else
                {
                    foreach (var error in pickupPointsResponse.Errors)
                    {
                        model.Warnings.Add(error);
                    }
                }
            }

            //only available pickup points
            var shippingProviders = await _shippingPluginManager.LoadActivePluginsAsync(await _workContext.GetCurrentCustomerAsync(), (await _storeContext.GetCurrentStoreAsync()).Id);

            if (!shippingProviders.Any())
            {
                if (!pickupPointProviders.Any())
                {
                    model.Warnings.Add(await _localizationService.GetResourceAsync("Checkout.ShippingIsNotAllowed"));
                    model.Warnings.Add(await _localizationService.GetResourceAsync("Checkout.PickupPoints.NotAvailable"));
                }
                model.PickupInStoreOnly = true;
                model.PickupInStore     = true;
                return(model);
            }

            return(model);
        }