Exemplo n.º 1
0
        public ActionResult GetFileUpload(Guid downloadId)
        {
            var download = _downloadService.GetDownloadByGuid(downloadId);

            if (download == null)
            {
                return(Content("Download is not available any more."));
            }

            if (download.UseDownloadUrl)
            {
                //return result
                return(new RedirectResult(download.DownloadUrl));
            }
            else
            {
                if (download.DownloadBinary == null)
                {
                    return(Content("Download data is not available any more."));
                }

                //return result
                string fileName    = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : downloadId.ToString();
                string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream";
                return(new FileContentResult(download.DownloadBinary, contentType)
                {
                    FileDownloadName = fileName + download.Extension
                });
            }
        }
Exemplo n.º 2
0
        public virtual ActionResult DownloadFile(Guid downloadGuid)
        {
            var download = _downloadService.GetDownloadByGuid(downloadGuid);

            if (download == null)
            {
                return(Content("No download record found with the specified id"));
            }

            if (download.UseDownloadUrl)
            {
                return(new RedirectResult(download.DownloadUrl));
            }

            //use stored data
            if (download.DownloadBinary == null)
            {
                return(Content(string.Format("Download data is not available any more. Download GD={0}", download.Id)));
            }

            string fileName    = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id.ToString();
            string contentType = !String.IsNullOrWhiteSpace(download.ContentType)
                ? download.ContentType
                : MimeTypes.ApplicationOctetStream;

            return(new FileContentResult(download.DownloadBinary, contentType)
            {
                FileDownloadName = fileName + download.Extension
            });
        }
Exemplo n.º 3
0
        public virtual IActionResult GetFileUpload(Guid downloadId)
        {
            var download = _downloadService.GetDownloadByGuid(downloadId);

            if (download == null)
            {
                return(Content("Download is not available any more."));
            }

            if (download.UseDownloadUrl)
            {
                return(new RedirectResult(download.DownloadUrl));
            }

            //binary download
            if (download.DownloadBinary == null)
            {
                return(Content("Download data is not available any more."));
            }

            //return result
            var fileName    = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : downloadId.ToString();
            var contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream;

            return(new FileContentResult(download.DownloadBinary, contentType)
            {
                FileDownloadName = fileName + download.Extension
            });
        }
Exemplo n.º 4
0
        public virtual IActionResult GetFileUpload(Guid downloadId)
        {
            var download = _downloadService.GetDownloadByGuid(downloadId);

            if (download == null)
            {
                return(Content("Download is not available any more."));
            }

            //A warning (SCS0027 - Open Redirect) from the "Security Code Scan" analyzer may appear at this point.
            //In this case, it is not relevant. Url may not be local.
            if (download.UseDownloadUrl)
            {
                return(new RedirectResult(download.DownloadUrl));
            }

            //binary download
            if (download.DownloadBinary == null)
            {
                return(Content("Download data is not available any more."));
            }

            //return result
            var fileName    = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : downloadId.ToString();
            var contentType = !string.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream;

            return(new FileContentResult(download.DownloadBinary, contentType)
            {
                FileDownloadName = fileName + download.Extension
            });
        }
Exemplo n.º 5
0
        public ActionResult GetFileUpload(Guid downloadId)
        {
            var download = _downloadService.GetDownloadByGuid(downloadId);

            if (download == null)
            {
                return(Content(T("Common.Download.NotAvailable")));
            }

            if (download.UseDownloadUrl)
            {
                return(new RedirectResult(download.DownloadUrl));
            }

            return(GetFileContentResultFor(download, null));
        }
Exemplo n.º 6
0
        public ActionResult GetFileUpload(Guid downloadId)
        {
            var download = _downloadService.GetDownloadByGuid(downloadId);

            if (download == null)
            {
                NotifyError(T("Common.Download.NotAvailable"));
                return(RedirectToAction("DownloadableProducts", "Customer"));
            }

            if (download.UseDownloadUrl)
            {
                return(new RedirectResult(download.DownloadUrl));
            }

            return(GetFileContentResultFor(download, null));
        }
        /// <inheritdoc cref="IProductPictureModifierService.GetDownloadFromAttributeXml"/>
        public Download GetDownloadFromAttributeXml(string customUploadAttribute)
        {
            int pFrom = customUploadAttribute.
                        IndexOf("download/getfileupload/?downloadId=", StringComparison.Ordinal)
                        + "download/getfileupload/?downloadId=".Length;

            int pTo = customUploadAttribute.IndexOf("\" class=", StringComparison.Ordinal);

            if (pTo <= pFrom || pTo == 0)
            {
                throw new InvalidDataException("Invalid Custom Attribute");
            }

            string downloadGuid = customUploadAttribute.Substring(pFrom, pTo - pFrom);

            return(_downloadService.GetDownloadByGuid(new Guid(downloadGuid)));
        }
Exemplo n.º 8
0
        public ActionResult SubmissionDelete(DataSourceRequest command, int submissionRecordId)
        {
            var submissionRec = _submissionRepo.GetById(submissionRecordId);

            //delete download file if there is such
            if (String.IsNullOrEmpty(submissionRec.DownloadLink) == false)
            {
                int startIndex = submissionRec.DownloadLink.IndexOf("downloadId=");
                int length     = "downloadId=".Length;

                string downloadGuid = submissionRec.DownloadLink.Substring(startIndex + length);

                var download = _downloadService.GetDownloadByGuid(new Guid(downloadGuid));
                _downloadService.DeleteDownload(download);
            }

            _submissionRepo.Delete(submissionRec);

            return(new NullJsonResult());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="customAttributes">Attributes</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</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 hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public virtual async Task <string> FormatAttributes(IList <CustomAttribute> customAttributes,
                                                            Customer customer,
                                                            string serapator     = "<br />",
                                                            bool htmlEncode      = true,
                                                            bool renderPrices    = true,
                                                            bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            if (customAttributes == null || !customAttributes.Any())
            {
                return(result.ToString());
            }

            var attributes = await _checkoutAttributeParser.ParseCheckoutAttributes(customAttributes);

            for (int i = 0; i < attributes.Count; i++)
            {
                var attribute = attributes[i];
                var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();
                for (var j = 0; j < valuesStr.Count; j++)
                {
                    var valueStr           = valuesStr[j];
                    var formattedAttribute = "";
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                            if (download != null)
                            {
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}/download/getfileupload/?downloadId={1}", _workContext.CurrentStore.Url.TrimEnd('/'), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        var attributeValue = attribute.CheckoutAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();
                        if (attributeValue != null)
                        {
                            formattedAttribute = string.Format("{0}: {1}", attribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id));
                            if (renderPrices)
                            {
                                double priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue, customer)).checkoutPrice;
                                double priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                if (priceAdjustmentBase > 0)
                                {
                                    string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);
                                    formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                }
                            }
                        }
                        //encode (if required)
                        if (htmlEncode)
                        {
                            formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                        }
                    }

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

            return(result.ToString());
        }
Exemplo n.º 10
0
        private async Task PrepareCheckoutAttributes(ShoppingCartModel model, GetShoppingCart request)
        {
            #region Checkout attributes

            var checkoutAttributes = await _checkoutAttributeService.GetAllCheckoutAttributes(request.Store.Id, !request.Cart.RequiresShipping());

            foreach (var attribute in checkoutAttributes)
            {
                var attributeModel = new ShoppingCartModel.CheckoutAttributeModel {
                    Id                   = attribute.Id,
                    Name                 = attribute.GetLocalized(x => x.Name, request.Language.Id),
                    TextPrompt           = attribute.GetLocalized(x => x.TextPrompt, request.Language.Id),
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType,
                    DefaultValue         = attribute.DefaultValue
                };
                if (!String.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))
                {
                    attributeModel.AllowedFileExtensions = attribute.ValidationFileAllowedExtensions
                                                           .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .ToList();
                }

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = attribute.CheckoutAttributeValues;
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributeValueModel = new ShoppingCartModel.CheckoutAttributeValueModel {
                            Id              = attributeValue.Id,
                            Name            = attributeValue.GetLocalized(x => x.Name, request.Language.Id),
                            ColorSquaresRgb = attributeValue.ColorSquaresRgb,
                            IsPreSelected   = attributeValue.IsPreSelected,
                        };
                        attributeModel.Values.Add(attributeValueModel);

                        //display price if allowed
                        if (await _permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                        {
                            decimal priceAdjustmentBase = (await _taxService.GetCheckoutAttributePrice(attribute, attributeValue)).checkoutPrice;
                            decimal priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, request.Currency);

                            if (priceAdjustmentBase > decimal.Zero)
                            {
                                attributeValueModel.PriceAdjustment = "+" + _priceFormatter.FormatPrice(priceAdjustment);
                            }
                            else if (priceAdjustmentBase < decimal.Zero)
                            {
                                attributeValueModel.PriceAdjustment = "-" + _priceFormatter.FormatPrice(-priceAdjustment);
                            }
                        }
                    }
                }
                //set already selected attributes
                var selectedCheckoutAttributes = request.Customer.GetAttributeFromEntity <string>(SystemCustomerAttributeNames.CheckoutAttributes, request.Store.Id);
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Checkboxes:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    if (!String.IsNullOrEmpty(selectedCheckoutAttributes))
                    {
                        //clear default selection
                        foreach (var item in attributeModel.Values)
                        {
                            item.IsPreSelected = false;
                        }

                        //select new values
                        var selectedValues = await _checkoutAttributeParser.ParseCheckoutAttributeValues(selectedCheckoutAttributes);

                        foreach (var attributeValue in selectedValues)
                        {
                            if (attributeModel.Id == attributeValue.CheckoutAttributeId)
                            {
                                foreach (var item in attributeModel.Values)
                                {
                                    if (attributeValue.Id == item.Id)
                                    {
                                        item.IsPreSelected = true;
                                    }
                                }
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //do nothing
                    //values are already pre-set
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    if (!String.IsNullOrEmpty(selectedCheckoutAttributes))
                    {
                        var enteredText = _checkoutAttributeParser.ParseValues(selectedCheckoutAttributes, attribute.Id);
                        if (enteredText.Any())
                        {
                            attributeModel.DefaultValue = enteredText[0];
                        }
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    //keep in mind my that the code below works only in the current culture
                    var selectedDateStr = _checkoutAttributeParser.ParseValues(selectedCheckoutAttributes, attribute.Id);
                    if (selectedDateStr.Any())
                    {
                        DateTime selectedDate;
                        if (DateTime.TryParseExact(selectedDateStr[0], "D", CultureInfo.CurrentCulture,
                                                   DateTimeStyles.None, out selectedDate))
                        {
                            //successfully parsed
                            attributeModel.SelectedDay   = selectedDate.Day;
                            attributeModel.SelectedMonth = selectedDate.Month;
                            attributeModel.SelectedYear  = selectedDate.Year;
                        }
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    if (!String.IsNullOrEmpty(selectedCheckoutAttributes))
                    {
                        var  downloadGuidStr = _checkoutAttributeParser.ParseValues(selectedCheckoutAttributes, attribute.Id).FirstOrDefault();
                        Guid downloadGuid;
                        Guid.TryParse(downloadGuidStr, out downloadGuid);
                        var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                        if (download != null)
                        {
                            attributeModel.DefaultValue = download.DownloadGuid.ToString();
                        }
                    }
                }
                break;

                default:
                    break;
                }

                model.CheckoutAttributes.Add(attributeModel);
            }
            #endregion
        }
Exemplo n.º 11
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="article">Article</param>
        /// <param name="attributesXml">Attributes in XML format</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</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="renderArticleAttributes">A value indicating whether to render article attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public virtual string FormatAttributes(Article article, string attributesXml,
                                               Customer customer, string serapator = "<br />", bool htmlEncode           = true, bool renderPrices = true,
                                               bool renderArticleAttributes        = true, bool renderGiftCardAttributes = true,
                                               bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            //attributes
            if (renderArticleAttributes)
            {
                foreach (var attribute in _articleAttributeParser.ParseArticleAttributeMappings(attributesXml))
                {
                    //attributes without values
                    if (!attribute.ShouldHaveValues())
                    {
                        foreach (var value in _articleAttributeParser.ParseValues(attributesXml, attribute.Id))
                        {
                            var formattedAttribute = string.Empty;
                            if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                            {
                                //multiline textbox
                                var attributeName = attribute.ArticleAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);

                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }

                                //we never encode multiline textbox input
                                formattedAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(value, false, true, false, false, false, false));
                            }
                            else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
                            {
                                //file upload
                                Guid downloadGuid;
                                Guid.TryParse(value, out downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);
                                if (download != null)
                                {
                                    var fileName = string.Format("{0}{1}", download.Filename ?? download.DownloadGuid.ToString(), download.Extension);

                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        fileName = HttpUtility.HtmlEncode(fileName);
                                    }

                                    //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                    var attributeText = allowHyperlinks ? string.Format("<a href=\"{0}download/getfileupload/?downloadId={1}\" class=\"fileuploadattribute\">{2}</a>",
                                                                                        _webHelper.GetStoreLocation(false), download.DownloadGuid, fileName) : fileName;

                                    var attributeName = attribute.ArticleAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);

                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        attributeName = HttpUtility.HtmlEncode(attributeName);
                                    }

                                    formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                                }
                            }
                            else
                            {
                                //other attributes (textbox, datepicker)
                                formattedAttribute = string.Format("{0}: {1}", attribute.ArticleAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), value);

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

                            if (!string.IsNullOrEmpty(formattedAttribute))
                            {
                                if (result.Length > 0)
                                {
                                    result.Append(serapator);
                                }
                                result.Append(formattedAttribute);
                            }
                        }
                    }
                    //article attribute values
                    else
                    {
                        foreach (var attributeValue in _articleAttributeParser.ParseArticleAttributeValues(attributesXml, attribute.Id))
                        {
                            var formattedAttribute = string.Format("{0}: {1}",
                                                                   attribute.ArticleAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id),
                                                                   attributeValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));

                            if (renderPrices)
                            {
                                decimal taxRate;
                                var     attributeValuePriceAdjustment = _priceCalculationService.GetArticleAttributeValuePriceAdjustment(attributeValue);
                                var     priceAdjustmentBase           = _taxService.GetArticlePrice(article, attributeValuePriceAdjustment, customer, out taxRate);
                                var     priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
                                if (priceAdjustmentBase > 0)
                                {
                                    formattedAttribute += string.Format(" [+{0}]", _priceFormatter.FormatPrice(priceAdjustment, false, false));
                                }
                                else if (priceAdjustmentBase < decimal.Zero)
                                {
                                    formattedAttribute += string.Format(" [-{0}]", _priceFormatter.FormatPrice(-priceAdjustment, false, false));
                                }
                            }

                            //display quantity
                            if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity && attributeValue.AttributeValueType == AttributeValueType.AssociatedToArticle)
                            {
                                //render only when more than 1
                                if (attributeValue.Quantity > 1)
                                {
                                    formattedAttribute += string.Format(_localizationService.GetResource("ArticleAttributes.Quantity"), attributeValue.Quantity);
                                }
                            }

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

                            if (!string.IsNullOrEmpty(formattedAttribute))
                            {
                                if (result.Length > 0)
                                {
                                    result.Append(serapator);
                                }
                                result.Append(formattedAttribute);
                            }
                        }
                    }
                }
            }


            return(result.ToString());
        }
Exemplo n.º 12
0
        /// <summary>
        /// Formats attributes.
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="attributes">Attributes</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="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to render HTML hyperlinks</param>
        /// <returns>Formatted attributes.</returns>
        public string FormatAttributes(
            Product product,
            string attributes,
            Customer customer,
            string separator              = "<br />",
            bool htmlEncode               = true,
            bool renderPrices             = true,
            bool renderProductAttributes  = true,
            bool renderGiftCardAttributes = true,
            bool allowHyperlinks          = true)
        {
            var result = new StringBuilder();

            // Attributes.
            if (renderProductAttributes)
            {
                var languageId    = _workContext.WorkingLanguage.Id;
                var pvaCollection = _productAttributeParser.ParseProductVariantAttributes(attributes);

                for (var i = 0; i < pvaCollection.Count; ++i)
                {
                    var pva       = pvaCollection[i];
                    var valuesStr = _productAttributeParser.ParseValues(attributes, pva.Id);

                    for (var j = 0; j < valuesStr.Count; ++j)
                    {
                        var valueStr     = valuesStr[j];
                        var pvaAttribute = string.Empty;

                        if (!pva.ShouldHaveValues())
                        {
                            // No values.
                            if (pva.AttributeControlType == AttributeControlType.MultilineTextbox)
                            {
                                // Multiline textbox.
                                string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId);

                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }

                                pvaAttribute = string.Format("{0}: {1}", attributeName, HtmlUtils.ConvertPlainTextToHtml(valueStr.HtmlEncode()));
                                // We never encode multiline textbox input.
                            }
                            else if (pva.AttributeControlType == AttributeControlType.FileUpload)
                            {
                                Guid.TryParse(valueStr, out var downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);

                                if (download?.MediaFile != null)
                                {
                                    // TODO: add a method for getting URL (use routing because it handles all SEO friendly URLs).
                                    var attributeText = "";
                                    var fileName      = download.MediaFile.Name;

                                    if (htmlEncode)
                                    {
                                        fileName = HttpUtility.HtmlEncode(fileName);
                                    }

                                    if (allowHyperlinks)
                                    {
                                        var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                        attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                    }
                                    else
                                    {
                                        attributeText
                                            = fileName;
                                    }
                                    string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId);

                                    if (htmlEncode)
                                    {
                                        attributeName = HttpUtility.HtmlEncode(attributeName);
                                    }

                                    pvaAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                                }
                            }
                            else
                            {
                                // Other attributes (textbox, datepicker).
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, languageId), valueStr);

                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }
                        else
                        {
                            // Attributes with values.
                            if (int.TryParse(valueStr, out var pvaId))
                            {
                                var pvaValue = _productAttributeService.GetProductVariantAttributeValueById(pvaId);
                                if (pvaValue != null)
                                {
                                    pvaAttribute = "{0}: {1}".FormatInvariant(
                                        pva.ProductAttribute.GetLocalized(a => a.Name, languageId),
                                        pvaValue.GetLocalized(a => a.Name, languageId));

                                    if (renderPrices)
                                    {
                                        var attributeValuePriceAdjustment = _priceCalculationService.GetProductVariantAttributeValuePriceAdjustment(pvaValue, product, customer, null, 1);
                                        var priceAdjustmentBase           = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out var taxRate);
                                        var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                        if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity &&
                                            pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage &&
                                            pvaValue.Quantity > 1)
                                        {
                                            pvaAttribute += string.Format(" × {0}", pvaValue.Quantity);
                                        }

                                        if (_catalogSettings.ShowVariantCombinationPriceAdjustment)
                                        {
                                            if (priceAdjustmentBase > 0)
                                            {
                                                pvaAttribute += " (+{0})".FormatInvariant(_priceFormatter.FormatPrice(priceAdjustment, true, false));
                                            }
                                            else if (priceAdjustmentBase < decimal.Zero)
                                            {
                                                pvaAttribute += " (-{0})".FormatInvariant(_priceFormatter.FormatPrice(-priceAdjustment, true, false));
                                            }
                                        }
                                    }
                                }

                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }

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

            // Gift cards.
            if (renderGiftCardAttributes)
            {
                if (product.IsGiftCard)
                {
                    _productAttributeParser.GetGiftCardAttribute(attributes, out var giftCardRecipientName, out var giftCardRecipientEmail,
                                                                 out var giftCardSenderName, out var giftCardSenderEmail, out var giftCardMessage);

                    // Sender.
                    var giftCardFrom = product.GiftCardType == GiftCardType.Virtual
                        ? string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail)
                        : string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);

                    // Recipient.
                    var giftCardFor = product.GiftCardType == GiftCardType.Virtual
                        ? string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail)
                        : string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);

                    if (htmlEncode)
                    {
                        giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
                        giftCardFor  = HttpUtility.HtmlEncode(giftCardFor);
                    }

                    if (!string.IsNullOrEmpty(result.ToString()))
                    {
                        result.Append(separator);
                    }
                    result.Append(giftCardFrom);
                    result.Append(separator);
                    result.Append(giftCardFor);
                }
            }

            return(result.ToString());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="productVariant">Product variant</param>
        /// <param name="attributes">Attributes</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</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="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public string FormatAttributes(ProductVariant productVariant, string attributes,
                                       Customer customer, string serapator = "<br />", bool htmlEncode           = true, bool renderPrices = true,
                                       bool renderProductAttributes        = true, bool renderGiftCardAttributes = true,
                                       bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            //attributes
            if (renderProductAttributes)
            {
                var pvaCollection = _productAttributeParser.ParseProductVariantAttributes(attributes);
                for (int i = 0; i < pvaCollection.Count; i++)
                {
                    var pva       = pvaCollection[i];
                    var valuesStr = _productAttributeParser.ParseValues(attributes, pva.Id);
                    for (int j = 0; j < valuesStr.Count; j++)
                    {
                        string valueStr     = valuesStr[j];
                        string pvaAttribute = string.Empty;
                        if (!pva.ShouldHaveValues())
                        {
                            //no values
                            if (pva.AttributeControlType == AttributeControlType.TextBox)
                            {
                                //multiline textbox
                                var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }
                                pvaAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr, false, true, false, false, false, false));
                                //we never encode multiline textbox input
                            }
                            else if (pva.AttributeControlType == AttributeControlType.TextBox)
                            {
                                //file upload
                                Guid downloadGuid;
                                Guid.TryParse(valueStr, out downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);
                                if (download != null)
                                {
                                    //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                    string attributeText = "";
                                    var    fileName      = string.Format("{0}{1}",
                                                                         download.Filename ?? download.DownloadGuid.ToString(),
                                                                         download.Extension);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        fileName = HttpUtility.HtmlEncode(fileName);
                                    }
                                    if (allowHyperlinks)
                                    {
                                        //hyperlinks are allowed
                                        var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                        attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                    }
                                    else
                                    {
                                        //hyperlinks aren't allowed
                                        attributeText = fileName;
                                    }
                                    var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        attributeName = HttpUtility.HtmlEncode(attributeName);
                                    }
                                    pvaAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                                }
                            }
                            else
                            {
                                //other attributes (textbox, datepicker)
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }
                        else
                        {
                            //attributes with values
                            int pvaId = 0;
                            if (int.TryParse(valueStr, out pvaId))
                            {
                                var pvaValue = _productAttributeService.GetProductVariantAttributeValueById(pvaId);
                                if (pvaValue != null)
                                {
                                    pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), pvaValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));
                                    if (renderPrices)
                                    {
                                        decimal taxRate             = decimal.Zero;
                                        decimal priceAdjustmentBase = _taxService.GetProductPrice(productVariant, pvaValue.PriceAdjustment, customer, out taxRate);
                                        decimal priceAdjustment     = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
                                        if (priceAdjustmentBase > 0)
                                        {
                                            string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false);
                                            pvaAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                        }
                                        else if (priceAdjustmentBase < decimal.Zero)
                                        {
                                            string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false);
                                            pvaAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                        }
                                    }
                                }
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }

                        if (!String.IsNullOrEmpty(pvaAttribute))
                        {
                            if (i != 0 || j != 0)
                            {
                                result.Append(serapator);
                            }
                            result.Append(pvaAttribute);
                        }
                    }
                }
            }

            //gift cards
            if (renderGiftCardAttributes)
            {
                if (productVariant.IsGiftCard)
                {
                    string giftCardRecipientName  = "";
                    string giftCardRecipientEmail = "";
                    string giftCardSenderName     = "";
                    string giftCardSenderEmail    = "";
                    string giftCardMessage        = "";
                    _productAttributeParser.GetGiftCardAttribute(attributes, out giftCardRecipientName, out giftCardRecipientEmail,
                                                                 out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                    //sender
                    var giftCardFrom = productVariant.GiftCardType == GiftCardType.Virtual ?
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) :
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);
                    //recipient
                    var giftCardFor = productVariant.GiftCardType == GiftCardType.Virtual ?
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) :
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);

                    //encode (if required)
                    if (htmlEncode)
                    {
                        giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
                        giftCardFor  = HttpUtility.HtmlEncode(giftCardFor);
                    }

                    if (!String.IsNullOrEmpty(result.ToString()))
                    {
                        result.Append(serapator);
                    }
                    result.Append(giftCardFrom);
                    result.Append(serapator);
                    result.Append(giftCardFor);
                }
            }
            return(result.ToString());
        }
        /// <inheritdoc />
        /// <summary>
        /// Function remains unmodifed and is present so custom code is called (PrepareProductAttributeModels)
        /// Prepare the product details model
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="updatecartitem">Updated shopping cart item</param>
        /// <param name="isAssociatedProduct">Whether the product is associated</param>
        /// <returns>Product details model</returns>
        //public override ProductDetailsModel PrepareProductDetailsModel(Product product,
        //    ShoppingCartItem updatecartitem = null, bool isAssociatedProduct = false)
        //{
        //    if (product == null)
        //        throw new ArgumentNullException(nameof(product));

        //    //standard properties
        //    var model = new ProductDetailsModel
        //    {
        //        Id = product.Id,
        //        Name = _localizationService.GetLocalized(product, x => x.Name),
        //        ShortDescription = _localizationService.GetLocalized(product, x => x.ShortDescription),
        //        FullDescription = _localizationService.GetLocalized(product, x => x.FullDescription),
        //        MetaKeywords = _localizationService.GetLocalized(product, x => x.MetaKeywords),
        //        MetaDescription = _localizationService.GetLocalized(product, x => x.MetaDescription),
        //        MetaTitle = _localizationService.GetLocalized(product, x => x.MetaTitle),
        //        SeName = _urlRecordService.GetSeName(product),
        //        ProductType = product.ProductType,
        //        ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage,
        //        Sku = product.Sku,
        //        ShowManufacturerPartNumber = _catalogSettings.ShowManufacturerPartNumber,
        //        FreeShippingNotificationEnabled = _catalogSettings.ShowFreeShippingNotification,
        //        ManufacturerPartNumber = product.ManufacturerPartNumber,
        //        ShowGtin = _catalogSettings.ShowGtin,
        //        Gtin = product.Gtin,
        //        ManageInventoryMethod = product.ManageInventoryMethod,
        //        StockAvailability = _productService.FormatStockMessage(product, ""),
        //        HasSampleDownload = product.IsDownload && product.HasSampleDownload,
        //        DisplayDiscontinuedMessage = !product.Published && _catalogSettings.DisplayDiscontinuedMessageForUnpublishedProducts
        //    };

        //    //automatically generate product description?
        //    if (_seoSettings.GenerateProductMetaDescription && string.IsNullOrEmpty(model.MetaDescription))
        //    {
        //        //based on short description
        //        model.MetaDescription = model.ShortDescription;
        //    }

        //    //shipping info
        //    model.IsShipEnabled = product.IsShipEnabled;
        //    if (product.IsShipEnabled)
        //    {
        //        model.IsFreeShipping = product.IsFreeShipping;
        //        //delivery date
        //        var deliveryDate = _dateRangeService.GetDeliveryDateById(product.DeliveryDateId);
        //        if (deliveryDate != null)
        //        {
        //            model.DeliveryDate = _localizationService.GetLocalized(deliveryDate, dd => dd.Name);
        //        }
        //    }

        //    //email a friend
        //    model.EmailAFriendEnabled = _catalogSettings.EmailAFriendEnabled;
        //    //compare products
        //    model.CompareProductsEnabled = _catalogSettings.CompareProductsEnabled;
        //    //store name
        //    model.CurrentStoreName = _localizationService.GetLocalized(_storeContext.CurrentStore, x => x.Name);

        //    //vendor details
        //    if (_vendorSettings.ShowVendorOnProductDetailsPage)
        //    {
        //        var vendor = _vendorService.GetVendorById(product.VendorId);
        //        if (vendor != null && !vendor.Deleted && vendor.Active)
        //        {
        //            model.ShowVendor = true;

        //            model.VendorModel = new VendorBriefInfoModel
        //            {
        //                Id = vendor.Id,
        //                Name = _localizationService.GetLocalized(vendor, x => x.Name),
        //                SeName = _urlRecordService.GetSeName(vendor),
        //            };
        //        }
        //    }

        //    //page sharing
        //    if (_catalogSettings.ShowShareButton && !string.IsNullOrEmpty(_catalogSettings.PageShareCode))
        //    {
        //        var shareCode = _catalogSettings.PageShareCode;
        //        if (_webHelper.IsCurrentConnectionSecured())
        //        {
        //            //need to change the add this link to be https linked when the page is, so that the page doesn't ask about mixed mode when viewed in https...
        //            shareCode = shareCode.Replace("http://", "https://");
        //        }
        //        model.PageShareCode = shareCode;
        //    }

        //    //back in stock subscriptions
        //    if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
        //        product.BackorderMode == BackorderMode.NoBackorders &&
        //        product.AllowBackInStockSubscriptions &&
        //        _productService.GetTotalStockQuantity(product) <= 0)
        //    {
        //        //out of stock
        //        model.DisplayBackInStockSubscription = true;
        //    }

        //    //breadcrumb
        //    //do not prepare this model for the associated products. anyway it's not used
        //    if (_catalogSettings.CategoryBreadcrumbEnabled && !isAssociatedProduct)
        //    {
        //        model.Breadcrumb = PrepareProductBreadcrumbModel(product);
        //    }

        //    //product tags
        //    //do not prepare this model for the associated products. anyway it's not used
        //    if (!isAssociatedProduct)
        //    {
        //        model.ProductTags = PrepareProductTagModels(product);
        //    }

        //    //pictures
        //    model.DefaultPictureZoomEnabled = _mediaSettings.DefaultPictureZoomEnabled;
        //    model.DefaultPictureModel = PrepareProductDetailsPictureModel(product, isAssociatedProduct, out IList<PictureModel> allPictureModels);
        //    model.PictureModels = allPictureModels;

        //    //price
        //    model.ProductPrice = PrepareProductPriceModel(product);

        //    //'Add to cart' model
        //    model.AddToCart = PrepareProductAddToCartModel(product, updatecartitem);

        //    //gift card
        //    if (product.IsGiftCard)
        //    {
        //        model.GiftCard.IsGiftCard = true;
        //        model.GiftCard.GiftCardType = product.GiftCardType;

        //        if (updatecartitem == null)
        //        {
        //            model.GiftCard.SenderName = _customerService.GetCustomerFullName(_workContext.CurrentCustomer);
        //            model.GiftCard.SenderEmail = _workContext.CurrentCustomer.Email;
        //        }
        //        else
        //        {
        //            _productAttributeParser.GetGiftCardAttribute(updatecartitem.AttributesXml,
        //                out string giftCardRecipientName, out string giftCardRecipientEmail,
        //                out string giftCardSenderName, out string giftCardSenderEmail, out string giftCardMessage);

        //            model.GiftCard.RecipientName = giftCardRecipientName;
        //            model.GiftCard.RecipientEmail = giftCardRecipientEmail;
        //            model.GiftCard.SenderName = giftCardSenderName;
        //            model.GiftCard.SenderEmail = giftCardSenderEmail;
        //            model.GiftCard.Message = giftCardMessage;
        //        }
        //    }

        //    //product attributes
        //    model.ProductAttributes = PrepareProductAttributeModels(product, updatecartitem);

        //    //product specifications
        //    //do not prepare this model for the associated products. anyway it's not used
        //    if (!isAssociatedProduct)
        //    {
        //        model.ProductSpecifications = PrepareProductSpecificationModel(product);
        //    }

        //    //product review overview
        //    model.ProductReviewOverview = PrepareProductReviewOverviewModel(product);

        //    //tier prices
        //    if (product.HasTierPrices && _permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
        //    {
        //        model.TierPrices = PrepareProductTierPriceModels(product);
        //    }

        //    //manufacturers
        //    //do not prepare this model for the associated products. anyway it's not used
        //    if (!isAssociatedProduct)
        //    {
        //        model.ProductManufacturers = PrepareProductManufacturerModels(product);
        //    }

        //    //rental products
        //    if (product.IsRental)
        //    {
        //        model.IsRental = true;
        //        //set already entered dates attributes (if we're going to update the existing shopping cart item)
        //        if (updatecartitem != null)
        //        {
        //            model.RentalStartDate = updatecartitem.RentalStartDateUtc;
        //            model.RentalEndDate = updatecartitem.RentalEndDateUtc;
        //        }
        //    }

        //    //associated products
        //    if (product.ProductType == ProductType.GroupedProduct)
        //    {
        //        //ensure no circular references
        //        if (!isAssociatedProduct)
        //        {
        //            var associatedProducts = _productService.GetAssociatedProducts(product.Id, _storeContext.CurrentStore.Id);
        //            foreach (var associatedProduct in associatedProducts)
        //                model.AssociatedProducts.Add(PrepareProductDetailsModel(associatedProduct, null, true));
        //        }
        //    }

        //    return model;
        //}


        /// <inheritdoc />
        /// <summary>
        /// See custom code region, rest of function remains unaltered
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="updatecartitem">Updated shopping cart item</param>
        /// <returns>List of product attribute model</returns>
        protected override IList <ProductDetailsModel.ProductAttributeModel> PrepareProductAttributeModels(Product product, ShoppingCartItem updatecartitem)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            var model = new List <ProductDetailsModel.ProductAttributeModel>();

            var productAttributeMapping = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id);

            foreach (var attribute in productAttributeMapping)
            {
                var attributeModel = new ProductDetailsModel.ProductAttributeModel
                {
                    Id                   = attribute.Id,
                    ProductId            = product.Id,
                    ProductAttributeId   = attribute.ProductAttributeId,
                    Name                 = _localizationService.GetLocalized(attribute.ProductAttribute, x => x.Name),
                    Description          = _localizationService.GetLocalized(attribute.ProductAttribute, x => x.Description),
                    TextPrompt           = _localizationService.GetLocalized(attribute, x => x.TextPrompt),
                    IsRequired           = attribute.IsRequired,
                    AttributeControlType = attribute.AttributeControlType,
                    DefaultValue         = updatecartitem != null ? null : _localizationService.GetLocalized(attribute, x => x.DefaultValue),
                    HasCondition         = !string.IsNullOrEmpty(attribute.ConditionAttributeXml)
                };
                if (!string.IsNullOrEmpty(attribute.ValidationFileAllowedExtensions))
                {
                    attributeModel.AllowedFileExtensions = attribute.ValidationFileAllowedExtensions
                                                           .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .ToList();
                }

                if (attribute.ShouldHaveValues())
                {
                    //values
                    var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id);

                    #region CUSTOM CODE
                    // Only custom code in function lives here!
                    FilterAttributes(product, ref attributeValues);
                    #endregion

                    foreach (var attributeValue in attributeValues)
                    {
                        var valueModel = new ProductDetailsModel.ProductAttributeValueModel
                        {
                            Id                = attributeValue.Id,
                            Name              = _localizationService.GetLocalized(attributeValue, x => x.Name),
                            ColorSquaresRgb   = attributeValue.ColorSquaresRgb, //used with "Color squares" attribute type
                            IsPreSelected     = attributeValue.IsPreSelected,
                            CustomerEntersQty = attributeValue.CustomerEntersQty,
                            Quantity          = attributeValue.Quantity
                        };
                        attributeModel.Values.Add(valueModel);

                        //display price if allowed
                        if (_permissionService.Authorize(StandardPermissionProvider.DisplayPrices))
                        {
                            var attributeValuePriceAdjustment = _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue, updatecartitem?.Customer ?? _workContext.CurrentCustomer);
                            var priceAdjustmentBase           = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, out decimal _);
                            var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                            if (attributeValue.PriceAdjustmentUsePercentage)
                            {
                                var priceAdjustmentStr = attributeValue.PriceAdjustment.ToString("G29");
                                if (attributeValue.PriceAdjustment > decimal.Zero)
                                {
                                    valueModel.PriceAdjustment = "+";
                                }
                                valueModel.PriceAdjustment += priceAdjustmentStr + "%";
                            }
                            else
                            {
                                if (priceAdjustmentBase > decimal.Zero)
                                {
                                    valueModel.PriceAdjustment = "+" + _priceFormatter.FormatPrice(priceAdjustment, false, false);
                                }
                                else if (priceAdjustmentBase < decimal.Zero)
                                {
                                    valueModel.PriceAdjustment = "-" + _priceFormatter.FormatPrice(-priceAdjustment, false, false);
                                }
                            }

                            valueModel.PriceAdjustmentValue = priceAdjustment;
                        }

                        //"image square" picture (with with "image squares" attribute type only)
                        if (attributeValue.ImageSquaresPictureId > 0)
                        {
                            var productAttributeImageSquarePictureCacheKey = string.Format(NopModelCacheDefaults.ProductAttributeImageSquarePictureModelKey,
                                                                                           attributeValue.ImageSquaresPictureId,
                                                                                           _webHelper.IsCurrentConnectionSecured(),
                                                                                           _storeContext.CurrentStore.Id);
                            valueModel.ImageSquaresPictureModel = _cacheManager.Get(productAttributeImageSquarePictureCacheKey, () =>
                            {
                                var imageSquaresPicture = _pictureService.GetPictureById(attributeValue.ImageSquaresPictureId);
                                if (imageSquaresPicture != null)
                                {
                                    return(new PictureModel
                                    {
                                        FullSizeImageUrl = _pictureService.GetPictureUrl(imageSquaresPicture),
                                        ImageUrl = _pictureService.GetPictureUrl(imageSquaresPicture, _mediaSettings.ImageSquarePictureSize)
                                    });
                                }
                                return(new PictureModel());
                            });
                        }

                        //picture of a product attribute value
                        valueModel.PictureId = attributeValue.PictureId;
                    }
                }

                //set already selected attributes (if we're going to update the existing shopping cart item)
                if (updatecartitem != null)
                {
                    switch (attribute.AttributeControlType)
                    {
                    case AttributeControlType.DropdownList:
                    case AttributeControlType.RadioList:
                    case AttributeControlType.Checkboxes:
                    case AttributeControlType.ColorSquares:
                    case AttributeControlType.ImageSquares:
                    {
                        if (!string.IsNullOrEmpty(updatecartitem.AttributesXml))
                        {
                            //clear default selection
                            foreach (var item in attributeModel.Values)
                            {
                                item.IsPreSelected = false;
                            }

                            //select new values
                            var selectedValues = _productAttributeParser.ParseProductAttributeValues(updatecartitem.AttributesXml);
                            foreach (var attributeValue in selectedValues)
                            {
                                foreach (var item in attributeModel.Values)
                                {
                                    if (attributeValue.Id == item.Id)
                                    {
                                        item.IsPreSelected = true;

                                        //set customer entered quantity
                                        if (attributeValue.CustomerEntersQty)
                                        {
                                            item.Quantity = attributeValue.Quantity;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;

                    case AttributeControlType.ReadonlyCheckboxes:
                    {
                        //values are already pre-set

                        //set customer entered quantity
                        if (!string.IsNullOrEmpty(updatecartitem.AttributesXml))
                        {
                            foreach (var attributeValue in _productAttributeParser.ParseProductAttributeValues(updatecartitem.AttributesXml)
                                     .Where(value => value.CustomerEntersQty))
                            {
                                var item = attributeModel.Values.FirstOrDefault(value => value.Id == attributeValue.Id);
                                if (item != null)
                                {
                                    item.Quantity = attributeValue.Quantity;
                                }
                            }
                        }
                    }
                    break;

                    case AttributeControlType.TextBox:
                    case AttributeControlType.MultilineTextbox:
                    {
                        if (!string.IsNullOrEmpty(updatecartitem.AttributesXml))
                        {
                            var enteredText = _productAttributeParser.ParseValues(updatecartitem.AttributesXml, attribute.Id);
                            if (enteredText.Any())
                            {
                                attributeModel.DefaultValue = enteredText[0];
                            }
                        }
                    }
                    break;

                    case AttributeControlType.Datepicker:
                    {
                        //keep in mind my that the code below works only in the current culture
                        var selectedDateStr = _productAttributeParser.ParseValues(updatecartitem.AttributesXml, attribute.Id);
                        if (selectedDateStr.Any())
                        {
                            if (DateTime.TryParseExact(selectedDateStr[0], "D", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime selectedDate))
                            {
                                //successfully parsed
                                attributeModel.SelectedDay   = selectedDate.Day;
                                attributeModel.SelectedMonth = selectedDate.Month;
                                attributeModel.SelectedYear  = selectedDate.Year;
                            }
                        }
                    }
                    break;

                    case AttributeControlType.FileUpload:
                    {
                        if (!string.IsNullOrEmpty(updatecartitem.AttributesXml))
                        {
                            var downloadGuidStr = _productAttributeParser.ParseValues(updatecartitem.AttributesXml, attribute.Id).FirstOrDefault();
                            Guid.TryParse(downloadGuidStr, out Guid downloadGuid);
                            var download = _downloadService.GetDownloadByGuid(downloadGuid);
                            if (download != null)
                            {
                                attributeModel.DefaultValue = download.DownloadGuid.ToString();
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }
                }

                model.Add(attributeModel);
            }

            return(model);
        }
        public static string CreateSelectedAttributesXml(
            this ProductVariantQuery query,
            int productId,
            int bundleItemId,
            IEnumerable <ProductVariantAttribute> variantAttributes,
            IProductAttributeParser productAttributeParser,
            ILocalizationService localization,
            IDownloadService downloadService,
            CatalogSettings catalogSettings,
            HttpRequestBase request,
            List <string> warnings)
        {
            var result = string.Empty;

            foreach (var pva in variantAttributes)
            {
                var selectedItems = query.Variants.Where(x =>
                                                         x.ProductId == productId &&
                                                         x.BundleItemId == bundleItemId &&
                                                         x.AttributeId == pva.ProductAttributeId &&
                                                         x.VariantAttributeId == pva.Id);

                switch (pva.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.Boxes:
                {
                    var firstItemValue = selectedItems.FirstOrDefault()?.Value;
                    if (firstItemValue.HasValue())
                    {
                        var selectedAttributeId = firstItemValue.SplitSafe(",").SafeGet(0).ToInt();
                        if (selectedAttributeId > 0)
                        {
                            result = productAttributeParser.AddProductAttribute(result, pva, selectedAttributeId.ToString());
                        }
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                    foreach (var item in selectedItems)
                    {
                        var selectedAttributeId = item.Value.SplitSafe(",").SafeGet(0).ToInt();
                        if (selectedAttributeId > 0)
                        {
                            result = productAttributeParser.AddProductAttribute(result, pva, selectedAttributeId.ToString());
                        }
                    }
                    break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var selectedValue = string.Join(",", selectedItems.Select(x => x.Value));
                    if (selectedValue.HasValue())
                    {
                        result = productAttributeParser.AddProductAttribute(result, pva, selectedValue);
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var firstItemDate = selectedItems.FirstOrDefault()?.Date;
                    if (firstItemDate.HasValue)
                    {
                        result = productAttributeParser.AddProductAttribute(result, pva, firstItemDate.Value.ToString("D"));
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                    if (request == null)
                    {
                        var firstItemValue = selectedItems.FirstOrDefault()?.Value;
                        Guid.TryParse(firstItemValue, out var downloadGuid);

                        var download = downloadService.GetDownloadByGuid(downloadGuid);
                        if (download != null)
                        {
                            if (download.IsTransient)
                            {
                                download.IsTransient = false;
                                downloadService.UpdateDownload(download);
                            }

                            result = productAttributeParser.AddProductAttribute(result, pva, download.DownloadGuid.ToString());
                        }
                    }
                    else
                    {
                        var postedFile = request.Files[ProductVariantQueryItem.CreateKey(productId, bundleItemId, pva.ProductAttributeId, pva.Id)];
                        if (postedFile != null && postedFile.FileName.HasValue())
                        {
                            if (postedFile.ContentLength > catalogSettings.FileUploadMaximumSizeBytes)
                            {
                                warnings.Add(localization.GetResource("ShoppingCart.MaximumUploadedFileSize").FormatInvariant((int)(catalogSettings.FileUploadMaximumSizeBytes / 1024)));
                            }
                            else
                            {
                                var download = new Download
                                {
                                    DownloadGuid   = Guid.NewGuid(),
                                    UseDownloadUrl = false,
                                    DownloadUrl    = "",
                                    UpdatedOnUtc   = DateTime.UtcNow,
                                    EntityId       = productId,
                                    EntityName     = "ProductAttribute"
                                };

                                downloadService.InsertDownload(download, postedFile.InputStream, postedFile.FileName);

                                result = productAttributeParser.AddProductAttribute(result, pva, download.DownloadGuid.ToString());
                            }
                        }
                    }
                    break;
                }
            }

            return(result);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="product">Product</param>
        /// <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="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public virtual string FormatAttributes(Product product, string attributesXml,
                                               Customer customer, string separator = "<br />", bool htmlEncode           = true, bool renderPrices = true,
                                               bool renderProductAttributes        = true, bool renderGiftCardAttributes = true,
                                               bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            //attributes
            if (renderProductAttributes)
            {
                foreach (var attribute in _productAttributeParser.ParseProductAttributeMappings(attributesXml))
                {
                    //attributes without values
                    if (!attribute.ShouldHaveValues())
                    {
                        foreach (var value in _productAttributeParser.ParseValues(attributesXml, attribute.Id))
                        {
                            var formattedAttribute = string.Empty;
                            if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                            {
                                //multiline textbox
                                var attributeName = _localizationService.GetLocalized(attribute.ProductAttribute, a => a.Name, _workContext.WorkingLanguage.Id);

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

                                //we never encode multiline textbox input
                                formattedAttribute = $"{attributeName}: {HtmlHelper.FormatText(value, false, true, false, false, false, false)}";
                            }
                            else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
                            {
                                //file upload
                                Guid.TryParse(value, out var downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);
                                if (download != null)
                                {
                                    var fileName = $"{download.Filename ?? download.DownloadGuid.ToString()}{download.Extension}";

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

                                    //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                    var attributeText = allowHyperlinks ? $"<a href=\"{_webHelper.GetStoreLocation(false)}download/getfileupload/?downloadId={download.DownloadGuid}\" class=\"fileuploadattribute\">{fileName}</a>"
                                        : fileName;

                                    var attributeName = _localizationService.GetLocalized(attribute.ProductAttribute, a => a.Name, _workContext.WorkingLanguage.Id);

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

                                    formattedAttribute = $"{attributeName}: {attributeText}";
                                }
                            }
                            else
                            {
                                //other attributes (textbox, datepicker)
                                formattedAttribute = $"{_localizationService.GetLocalized(attribute.ProductAttribute, a => a.Name, _workContext.WorkingLanguage.Id)}: {value}";

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

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

                            if (result.Length > 0)
                            {
                                result.Append(separator);
                            }
                            result.Append(formattedAttribute);
                        }
                    }
                    //product attribute values
                    else
                    {
                        foreach (var attributeValue in _productAttributeParser.ParseProductAttributeValues(attributesXml, attribute.Id))
                        {
                            var formattedAttribute = $"{_localizationService.GetLocalized(attribute.ProductAttribute, a => a.Name, _workContext.WorkingLanguage.Id)}: {_localizationService.GetLocalized(attributeValue, a => a.Name, _workContext.WorkingLanguage.Id)}";

                            if (renderPrices)
                            {
                                if (attributeValue.PriceAdjustmentUsePercentage)
                                {
                                    if (attributeValue.PriceAdjustment > decimal.Zero)
                                    {
                                        formattedAttribute += string.Format(
                                            _localizationService.GetResource("FormattedAttributes.PriceAdjustment"),
                                            "+", attributeValue.PriceAdjustment.ToString("G29"), "%");
                                    }
                                    else if (attributeValue.PriceAdjustment < decimal.Zero)
                                    {
                                        formattedAttribute += string.Format(
                                            _localizationService.GetResource("FormattedAttributes.PriceAdjustment"),
                                            string.Empty, attributeValue.PriceAdjustment.ToString("G29"), "%");
                                    }
                                }
                                else
                                {
                                    var attributeValuePriceAdjustment = _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue, customer);
                                    var priceAdjustmentBase           = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out var _);
                                    var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                    if (priceAdjustmentBase > decimal.Zero)
                                    {
                                        formattedAttribute += string.Format(
                                            _localizationService.GetResource("FormattedAttributes.PriceAdjustment"),
                                            "+", _priceFormatter.FormatPrice(priceAdjustment, false, false), string.Empty);
                                    }
                                    else if (priceAdjustmentBase < decimal.Zero)
                                    {
                                        formattedAttribute += string.Format(
                                            _localizationService.GetResource("FormattedAttributes.PriceAdjustment"),
                                            "-", _priceFormatter.FormatPrice(-priceAdjustment, false, false), string.Empty);
                                    }
                                }
                            }

                            //display quantity
                            if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity && attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
                            {
                                //render only when more than 1
                                if (attributeValue.Quantity > 1)
                                {
                                    formattedAttribute += string.Format(_localizationService.GetResource("ProductAttributes.Quantity"), attributeValue.Quantity);
                                }
                            }

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

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

                            if (result.Length > 0)
                            {
                                result.Append(separator);
                            }
                            result.Append(formattedAttribute);
                        }
                    }
                }
            }

            //gift cards
            if (!renderGiftCardAttributes)
            {
                return(result.ToString());
            }

            if (!product.IsGiftCard)
            {
                return(result.ToString());
            }

            _productAttributeParser.GetGiftCardAttribute(attributesXml, out var giftCardRecipientName, out var giftCardRecipientEmail, out var giftCardSenderName, out var giftCardSenderEmail, out var _);

            //sender
            var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ?
                               string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) :
                               string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);
            //recipient
            var giftCardFor = product.GiftCardType == GiftCardType.Virtual ?
                              string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) :
                              string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);

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

            if (!string.IsNullOrEmpty(result.ToString()))
            {
                result.Append(separator);
            }

            result.Append(giftCardFrom);
            result.Append(separator);
            result.Append(giftCardFor);

            return(result.ToString());
        }
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="attributes">Attributes</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</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 hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public string FormatAttributes(string attributes,
                                       Customer customer,
                                       string serapator     = "<br />",
                                       bool htmlEncode      = true,
                                       bool renderPrices    = true,
                                       bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            var caCollection = _checkoutAttributeParser.ParseCheckoutAttributes(attributes);

            for (int i = 0; i < caCollection.Count; i++)
            {
                var ca        = caCollection[i];
                var valuesStr = _checkoutAttributeParser.ParseValues(attributes, ca.Id);
                for (int j = 0; j < valuesStr.Count; j++)
                {
                    string valueStr    = valuesStr[j];
                    string caAttribute = "";
                    if (!ca.ShouldHaveValues())
                    {
                        //no values
                        if (ca.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = HttpUtility.HtmlEncode(attributeName);
                            }
                            caAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr, false, true, false, false, false, false));
                            //we never encode multiline textbox input
                        }
                        else if (ca.AttributeControlType == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = _downloadService.GetDownloadByGuid(downloadGuid);
                            if (download != null)
                            {
                                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = HttpUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }
                                caAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                caAttribute = HttpUtility.HtmlEncode(caAttribute);
                            }
                        }
                    }
                    else
                    {
                        int caId = 0;
                        if (int.TryParse(valueStr, out caId))
                        {
                            var caValue = _checkoutAttributeService.GetCheckoutAttributeValueById(caId);
                            if (caValue != null)
                            {
                                caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), caValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));
                                if (renderPrices)
                                {
                                    decimal priceAdjustmentBase = _taxService.GetCheckoutAttributePrice(caValue, customer);
                                    decimal priceAdjustment     = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
                                    if (priceAdjustmentBase > 0)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);
                                        caAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                    }
                                }
                            }
                            //encode (if required)
                            if (htmlEncode)
                            {
                                caAttribute = HttpUtility.HtmlEncode(caAttribute);
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(caAttribute))
                    {
                        if (i != 0 || j != 0)
                        {
                            result.Append(serapator);
                        }
                        result.Append(caAttribute);
                    }
                }
            }

            return(result.ToString());
        }
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="attributesXml">Attributes in XML format</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</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="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public virtual string FormatAttributes(Product product, string attributesXml,
                                               Customer customer, string serapator = "<br />", bool htmlEncode           = true, bool renderPrices = true,
                                               bool renderProductAttributes        = true, bool renderGiftCardAttributes = true,
                                               bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            //attributes
            if (renderProductAttributes)
            {
                var attributes = _productAttributeParser.ParseProductAttributeMappings(product, attributesXml);
                for (int i = 0; i < attributes.Count; i++)
                {
                    var productAttribute = _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);
                    var attribute        = attributes[i];
                    var valuesStr        = _productAttributeParser.ParseValues(attributesXml, attribute.Id);
                    for (int j = 0; j < valuesStr.Count; j++)
                    {
                        string valueStr           = valuesStr[j];
                        string formattedAttribute = string.Empty;
                        if (!attribute.ShouldHaveValues())
                        {
                            //no values
                            if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                            {
                                //multiline textbox
                                var attributeName = productAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", 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 downloadGuid;
                                Guid.TryParse(valueStr, out downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);
                                if (download != null)
                                {
                                    //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                    string attributeText = "";
                                    var    fileName      = string.Format("{0}{1}",
                                                                         download.Filename ?? download.DownloadGuid.ToString(),
                                                                         download.Extension);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        fileName = HttpUtility.HtmlEncode(fileName);
                                    }
                                    if (allowHyperlinks)
                                    {
                                        //hyperlinks are allowed
                                        var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                        attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                    }
                                    else
                                    {
                                        //hyperlinks aren't allowed
                                        attributeText = fileName;
                                    }
                                    var attributeName = productAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        attributeName = HttpUtility.HtmlEncode(attributeName);
                                    }
                                    formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                                }
                            }
                            else
                            {
                                //other attributes (textbox, datepicker)
                                formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    formattedAttribute = HttpUtility.HtmlEncode(formattedAttribute);
                                }
                            }
                        }
                        else
                        {
                            //attributes with values
                            int attributeValueId;
                            if (int.TryParse(valueStr, out attributeValueId))
                            {
                                if (product.ProductAttributeMappings.Where(x => x.ProductAttributeId == attributes[i].ProductAttributeId).FirstOrDefault() != null)
                                {
                                    var attributeValue = product.ProductAttributeMappings.Where(x => x.ProductAttributeId == attributes[i].ProductAttributeId).FirstOrDefault().ProductAttributeValues.Where(x => x.Id == attributeValueId).FirstOrDefault(); //_productAttributeService.GetProductAttributeValueById(attributeValueId);
                                    if (attributeValue != null)
                                    {
                                        formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));

                                        if (renderPrices)
                                        {
                                            decimal taxRate;
                                            decimal attributeValuePriceAdjustment = _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue);
                                            decimal priceAdjustmentBase           = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out taxRate);
                                            decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
                                            if (priceAdjustmentBase > 0)
                                            {
                                                string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false);
                                                formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                            }
                                            else if (priceAdjustmentBase < decimal.Zero)
                                            {
                                                string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false);
                                                formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                            }
                                        }

                                        //display quantity
                                        if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity &&
                                            attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
                                        {
                                            //render only when more than 1
                                            if (attributeValue.Quantity > 1)
                                            {
                                                //TODO localize resource
                                                formattedAttribute += string.Format(" - qty {0}", attributeValue.Quantity);
                                            }
                                        }
                                    }
                                }

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

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

            //gift cards
            if (renderGiftCardAttributes)
            {
                if (product.IsGiftCard)
                {
                    string giftCardRecipientName;
                    string giftCardRecipientEmail;
                    string giftCardSenderName;
                    string giftCardSenderEmail;
                    string giftCardMessage;
                    _productAttributeParser.GetGiftCardAttribute(attributesXml, out giftCardRecipientName, out giftCardRecipientEmail,
                                                                 out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                    //sender
                    var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ?
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) :
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);
                    //recipient
                    var giftCardFor = product.GiftCardType == GiftCardType.Virtual ?
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) :
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);

                    //encode (if required)
                    if (htmlEncode)
                    {
                        giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
                        giftCardFor  = HttpUtility.HtmlEncode(giftCardFor);
                    }

                    if (!String.IsNullOrEmpty(result.ToString()))
                    {
                        result.Append(serapator);
                    }
                    result.Append(giftCardFrom);
                    result.Append(serapator);
                    result.Append(giftCardFor);
                }
            }
            return(result.ToString());
        }
        public async Task <IList <CustomAttribute> > Handle(SaveCheckoutAttributesCommand request, CancellationToken cancellationToken)
        {
            if (request.Cart == null)
            {
                throw new ArgumentNullException("cart");
            }

            if (request.Form == null)
            {
                throw new ArgumentNullException("form");
            }

            var customAttributes   = new List <CustomAttribute>();
            var checkoutAttributes = await _checkoutAttributeService.GetAllCheckoutAttributes(request.Store.Id, !request.Cart.RequiresShipping());

            foreach (var attribute in checkoutAttributes)
            {
                string controlId = string.Format("checkout_attribute_{0}", attribute.Id);
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    var ctrlAttributes = request.Form[controlId];
                    if (!string.IsNullOrEmpty(ctrlAttributes))
                    {
                        customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,
                                                                                         attribute, ctrlAttributes).ToList();
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                {
                    var cblAttributes = request.Form[controlId].ToString();
                    if (!string.IsNullOrEmpty(cblAttributes))
                    {
                        foreach (var item in cblAttributes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes, attribute, item).ToList();
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //load read-only (already server-side selected) values
                    var attributeValues = attribute.CheckoutAttributeValues;
                    foreach (var selectedAttributeId in attributeValues
                             .Where(v => v.IsPreSelected)
                             .Select(v => v.Id)
                             .ToList())
                    {
                        customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,
                                                                                         attribute, selectedAttributeId.ToString()).ToList();
                    }
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var ctrlAttributes = request.Form[controlId].ToString();
                    if (!string.IsNullOrEmpty(ctrlAttributes))
                    {
                        string enteredText = ctrlAttributes.Trim();
                        customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,
                                                                                         attribute, enteredText).ToList();
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var      date         = request.Form[controlId + "_day"];
                    var      month        = request.Form[controlId + "_month"];
                    var      year         = request.Form[controlId + "_year"];
                    DateTime?selectedDate = null;
                    try
                    {
                        selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date));
                    }
                    catch { }
                    if (selectedDate.HasValue)
                    {
                        customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,
                                                                                         attribute, selectedDate.Value.ToString("D")).ToList();
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    Guid downloadGuid;
                    Guid.TryParse(request.Form[controlId], out downloadGuid);
                    var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                    if (download != null)
                    {
                        customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,
                                                                                         attribute, download.DownloadGuid.ToString()).ToList();
                    }
                }
                break;

                default:
                    break;
                }
            }

            //save checkout attributes
            //validate conditional attributes (if specified)
            foreach (var attribute in checkoutAttributes)
            {
                var conditionMet = await _checkoutAttributeParser.IsConditionMet(attribute, customAttributes);

                if (conditionMet.HasValue && !conditionMet.Value)
                {
                    customAttributes = _checkoutAttributeParser.RemoveCheckoutAttribute(customAttributes, attribute).ToList();
                }
            }
            await _genericAttributeService.SaveAttribute(request.Customer, SystemCustomerAttributeNames.CheckoutAttributes, customAttributes, request.Store.Id);

            return(customAttributes);
        }
Exemplo n.º 20
0
        /// <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>Attributes</returns>
        public virtual string FormatAttributes(string attributesXml,
                                               Customer customer,
                                               string separator     = "<br />",
                                               bool htmlEncode      = true,
                                               bool renderPrices    = true,
                                               bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            var attributes = _checkoutAttributeParser.ParseCheckoutAttributes(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 = "";
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = _localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.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 Guid downloadGuid);
                            var download = _downloadService.GetDownloadByGuid(downloadGuid);
                            if (download != null)
                            {
                                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                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 = _localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = $"{attributeName}: {attributeText}";
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = $"{_localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}";
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        if (int.TryParse(valueStr, out int attributeValueId))
                        {
                            var attributeValue = _checkoutAttributeService.GetCheckoutAttributeValueById(attributeValueId);
                            if (attributeValue != null)
                            {
                                formattedAttribute = $"{_localizationService.GetLocalized(attribute, a => a.Name, _workContext.WorkingLanguage.Id)}: {_localizationService.GetLocalized(attributeValue, a => a.Name, _workContext.WorkingLanguage.Id)}";
                                if (renderPrices)
                                {
                                    var priceAdjustmentBase = _taxService.GetCheckoutAttributePrice(attributeValue, customer);
                                    var priceAdjustment     = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
                                    if (priceAdjustmentBase > 0)
                                    {
                                        var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);
                                        formattedAttribute += $" [+{priceAdjustmentStr}]";
                                    }
                                }
                            }
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }

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

            return(result.ToString());
        }
        public string ConvertToXml(List <ProductItemAttributeDto> attributeDtos, int productId)
        {
            string attributesXml = "";

            var productAttributes = _productAttributeService.GetProductAttributeMappingsByProductId(productId);

            foreach (var attribute in productAttributes)
            {
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    // there should be only one selected value for this attribute
                    var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault();
                    if (selectedAttribute != null)
                    {
                        int  selectedAttributeValue;
                        bool isInt = int.TryParse(selectedAttribute.Value, out selectedAttributeValue);
                        if (isInt && selectedAttributeValue > 0)
                        {
                            attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                        attribute, selectedAttributeValue.ToString());
                        }
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                {
                    // there could be more than one selected value for this attribute
                    var selectedAttributes = attributeDtos.Where(x => x.Id == attribute.Id);
                    foreach (var selectedAttribute in selectedAttributes)
                    {
                        int  selectedAttributeValue;
                        bool isInt = int.TryParse(selectedAttribute.Value, out selectedAttributeValue);
                        if (isInt && selectedAttributeValue > 0)
                        {
                            // currently there is no support for attribute quantity
                            var quantity = 1;

                            attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                        attribute, selectedAttributeValue.ToString(), quantity);
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //load read-only(already server - side selected) values
                    var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id);
                    foreach (var selectedAttributeId in attributeValues
                             .Where(v => v.IsPreSelected)
                             .Select(v => v.Id)
                             .ToList())
                    {
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, selectedAttributeId.ToString());
                    }
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault();

                    if (selectedAttribute != null)
                    {
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, selectedAttribute.Value);
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault();

                    if (selectedAttribute != null)
                    {
                        DateTime selectedDate;

                        // Since nopCommerce uses this format to keep the date in the database to keep it consisten we will expect the same format to be passed
                        bool validDate = DateTime.TryParseExact(selectedAttribute.Value, "D", CultureInfo.CurrentCulture,
                                                                DateTimeStyles.None, out selectedDate);

                        if (validDate)
                        {
                            attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                        attribute, selectedDate.ToString("D"));
                        }
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    var selectedAttribute = attributeDtos.Where(x => x.Id == attribute.Id).FirstOrDefault();

                    if (selectedAttribute != null)
                    {
                        Guid downloadGuid;
                        Guid.TryParse(selectedAttribute.Value, out downloadGuid);
                        var download = _downloadService.GetDownloadByGuid(downloadGuid);
                        if (download != null)
                        {
                            attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                        attribute, download.DownloadGuid.ToString());
                        }
                    }
                }
                break;

                default:
                    break;
                }
            }

            // No Gift Card attributes support yet

            return(attributesXml);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Gets a download by GUID
 /// </summary>
 /// <param name="downloadGuid">Download GUID</param>
 /// <returns>Download</returns>
 public Download GetDownloadByGuid(Guid downloadGuid)
 {
     return(_downloadService.GetDownloadByGuid(downloadGuid));
 }
Exemplo n.º 23
0
        public override void Uninstall()
        {
            //Delete all attached files before removing Submission table from DB
            List <SubmissionRecord> records = _submissionReop.Table.ToList();

            foreach (var item in records)
            {
                if (String.IsNullOrEmpty(item.DownloadLink) == false)
                {
                    int startIndex = item.DownloadLink.IndexOf("downloadId=");
                    int length     = "downloadId=".Length;

                    string downloadGuid = item.DownloadLink.Substring(startIndex + length);

                    var download = _downloadService.GetDownloadByGuid(new Guid(downloadGuid));
                    _downloadService.DeleteDownload(download);
                }
            }

            _context.Uninstall();

            _commonSettings.DeleteSetting <SubmissionAdminSettings>();

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.MenuTitle");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.FullNameLabel");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.FullNameLabel.Hint");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.FullNameRequired");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.FullNameTooLong");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EmailLabel");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EmailLabel.Hint");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EmailRequired");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EmailFormat");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.SubjectLabel");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.SubjectLabel.Hint");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.SubjectRequired");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.SubjectTooLong");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EnquiryPlaceholder");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EnquiryLabel");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EnquiryLabel.Hint");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EnquiryRequired");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.EnquiryTooLong");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.PhoneLabel");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.PhoneLabel.Hint");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.PhoneTooLong");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.SubmissionHeader");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.SubmissionSettings");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.SubmissionFilter");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.MaxFileSize");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.AllowedFiletypes");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Save");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.FullName");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Subject");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Phone");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Enquiry");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Type");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.DownloadLink");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Attachment");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.JobApplication");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.PartnerOffer");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.VendorOffer");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Other");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.NewEntry.Title");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.NewEntry.AttachFileHint");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.NewEntry.Send");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Error.MaxSizeExeeded");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Error.InvalidFiletype");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Info.SubmissionSucceeded");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Error.InvalidMaxSizeNum");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Error.NonpositiveMaxFileSize");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.Error.InvalidFiletype");

            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.EnquiryEmailSubscriber");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.JobApplicationEmailSubscriber");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.ParnterOfferEmailSubscriber");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.VendorOfferEmailSubscriber");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.OtherEmailSubscriber");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.IvnalidSuscriberEmail");
            this.DeletePluginLocaleResource("Plugins.Zingasoft.Submission.Admin.EmailNotificationIntro");

            base.Uninstall();
        }
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="attributesXml">Attributes in XML format</param>
        /// <param name="customer">Customer</param>
        /// <param name="serapator">Serapator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public virtual async Task <string> FormatAttributes(string attributesXml,
                                                            Customer customer,
                                                            string serapator     = "<br />",
                                                            bool htmlEncode      = true,
                                                            bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            var attributes = await _contactAttributeParser.ParseContactAttributes(attributesXml);

            for (int i = 0; i < attributes.Count; i++)
            {
                var attribute = attributes[i];
                var valuesStr = _contactAttributeParser.ParseValues(attributesXml, attribute.Id);
                for (int j = 0; j < valuesStr.Count; j++)
                {
                    string valueStr           = valuesStr[j];
                    string formattedAttribute = "";
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = string.Format("{0}: {1}", 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 downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                            if (download != null)
                            {
                                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = string.Format("{0}: {1}", attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        var attributeValue = attribute.ContactAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();
                        if (attributeValue != null)
                        {
                            formattedAttribute = string.Format("{0}: {1}", attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), attributeValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));
                        }
                        //encode (if required)
                        if (htmlEncode)
                        {
                            formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                        }
                    }

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

            return(result.ToString());
        }
        public async Task <string> Handle(GetParseProductAttributes request, CancellationToken cancellationToken)
        {
            string attributesXml = "";

            #region Product attributes

            var productAttributes = request.Product.ProductAttributeMappings.ToList();
            if (request.Product.ProductType == ProductType.BundledProduct)
            {
                foreach (var bundle in request.Product.BundleProducts)
                {
                    var bp = await _productService.GetProductById(bundle.ProductId);

                    if (bp.ProductAttributeMappings.Any())
                    {
                        productAttributes.AddRange(bp.ProductAttributeMappings);
                    }
                }
            }

            foreach (var attribute in productAttributes)
            {
                string controlId = string.Format("product_attribute_{0}", attribute.Id);
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    var ctrlAttributes = request.Form[controlId];
                    if (!String.IsNullOrEmpty(ctrlAttributes))
                    {
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, ctrlAttributes);
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                {
                    var ctrlAttributes = request.Form[controlId].ToString();
                    if (!String.IsNullOrEmpty(ctrlAttributes))
                    {
                        foreach (var item in ctrlAttributes.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (!String.IsNullOrEmpty(item))
                            {
                                attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                            attribute, item);
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //load read-only (already server-side selected) values
                    var attributeValues = attribute.ProductAttributeValues;
                    foreach (var selectedAttributeId in attributeValues
                             .Where(v => v.IsPreSelected)
                             .Select(v => v.Id)
                             .ToList())
                    {
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, selectedAttributeId);
                    }
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var ctrlAttributes = request.Form[controlId].ToString();
                    if (!String.IsNullOrEmpty(ctrlAttributes))
                    {
                        string enteredText = ctrlAttributes.Trim();
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, enteredText);
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var      day          = request.Form[controlId + "_day"];
                    var      month        = request.Form[controlId + "_month"];
                    var      year         = request.Form[controlId + "_year"];
                    DateTime?selectedDate = null;
                    try
                    {
                        selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(day));
                    }
                    catch { }
                    if (selectedDate.HasValue)
                    {
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, selectedDate.Value.ToString("D"));
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    Guid downloadGuid;
                    Guid.TryParse(request.Form[controlId], out downloadGuid);
                    var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                    if (download != null)
                    {
                        attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
                                                                                    attribute, download.DownloadGuid.ToString());
                    }
                }
                break;

                default:
                    break;
                }
            }
            //validate conditional attributes (if specified)
            foreach (var attribute in productAttributes)
            {
                var conditionMet = _productAttributeParser.IsConditionMet(request.Product, attribute, attributesXml);
                if (conditionMet.HasValue && !conditionMet.Value)
                {
                    attributesXml = _productAttributeParser.RemoveProductAttribute(attributesXml, attribute);
                }
            }

            #endregion

            #region Gift cards

            if (request.Product.IsGiftCard)
            {
                string recipientName   = "";
                string recipientEmail  = "";
                string senderName      = "";
                string senderEmail     = "";
                string giftCardMessage = "";
                foreach (string formKey in request.Form.Keys)
                {
                    if (formKey.Equals(string.Format("giftcard_{0}.RecipientName", request.Product.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        recipientName = request.Form[formKey];
                        continue;
                    }
                    if (formKey.Equals(string.Format("giftcard_{0}.RecipientEmail", request.Product.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        recipientEmail = request.Form[formKey];
                        continue;
                    }
                    if (formKey.Equals(string.Format("giftcard_{0}.SenderName", request.Product.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        senderName = request.Form[formKey];
                        continue;
                    }
                    if (formKey.Equals(string.Format("giftcard_{0}.SenderEmail", request.Product.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        senderEmail = request.Form[formKey];
                        continue;
                    }
                    if (formKey.Equals(string.Format("giftcard_{0}.Message", request.Product.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        giftCardMessage = request.Form[formKey];
                        continue;
                    }
                }

                attributesXml = _productAttributeParser.AddGiftCardAttribute(attributesXml,
                                                                             recipientName, recipientEmail, senderName, senderEmail, giftCardMessage);
            }

            #endregion

            return(attributesXml);
        }
		/// <summary>Takes selected elements from collection and creates a attribute XML string from it.</summary>
		/// <param name="formatWithProductId">how the name of the controls are formatted. frontend includes productId, backend does not.</param>
		public static string CreateSelectedAttributesXml(this NameValueCollection collection, int productId, IList<ProductVariantAttribute> variantAttributes,
			IProductAttributeParser productAttributeParser, ILocalizationService localizationService, IDownloadService downloadService, CatalogSettings catalogSettings,
			HttpRequestBase request, List<string> warnings, bool formatWithProductId = true, int bundleItemId = 0)
		{
			if (collection == null)
				return "";

			string controlId;
			string selectedAttributes = "";

			foreach (var attribute in variantAttributes)
			{
				controlId = AttributeFormatedName(attribute.ProductAttributeId, attribute.Id, formatWithProductId ? productId : 0, bundleItemId);

				switch (attribute.AttributeControlType)
				{
					case AttributeControlType.DropdownList:
					case AttributeControlType.RadioList:
					case AttributeControlType.ColorSquares:
						{
							var ctrlAttributes = collection[controlId];
							if (ctrlAttributes.HasValue())
							{
								int selectedAttributeId = int.Parse(ctrlAttributes);
								if (selectedAttributeId > 0)
									selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedAttributeId.ToString());
							}
						}
						break;

					case AttributeControlType.Checkboxes:
						{
							var cblAttributes = collection[controlId];
							if (cblAttributes.HasValue())
							{
								foreach (var item in cblAttributes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
								{
									int selectedAttributeId = int.Parse(item);
									if (selectedAttributeId > 0)
										selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedAttributeId.ToString());
								}
							}
						}
						break;

					case AttributeControlType.TextBox:
					case AttributeControlType.MultilineTextbox:
						{
							var txtAttribute = collection[controlId];
							if (txtAttribute.HasValue())
							{
								string enteredText = txtAttribute.Trim();
								selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, enteredText);
							}
						}
						break;

					case AttributeControlType.Datepicker:
						{
							var date = collection[controlId + "_day"];
							var month = collection[controlId + "_month"];
							var year = collection[controlId + "_year"];
							DateTime? selectedDate = null;

							try
							{
								selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date));
							}
							catch { }

							if (selectedDate.HasValue)
							{
								selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedDate.Value.ToString("D"));
							}
						}
						break;

					case AttributeControlType.FileUpload:
						if (request == null)
						{
							Guid downloadGuid;
							Guid.TryParse(collection[controlId], out downloadGuid);
							var download = downloadService.GetDownloadByGuid(downloadGuid);
							if (download != null)
							{
								selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString());
							}
						}
						else
						{
							var httpPostedFile = request.Files[controlId];
							if (httpPostedFile != null && httpPostedFile.FileName.HasValue())
							{
								int fileMaxSize = catalogSettings.FileUploadMaximumSizeBytes;
								if (httpPostedFile.ContentLength > fileMaxSize)
								{
									warnings.Add(string.Format(localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), (int)(fileMaxSize / 1024)));
								}
								else
								{
									//save an uploaded file
									var download = new Download()
									{
										DownloadGuid = Guid.NewGuid(),
										UseDownloadUrl = false,
										DownloadUrl = "",
										DownloadBinary = httpPostedFile.GetDownloadBits(),
										ContentType = httpPostedFile.ContentType,
										Filename = System.IO.Path.GetFileNameWithoutExtension(httpPostedFile.FileName),
										Extension = System.IO.Path.GetExtension(httpPostedFile.FileName),
										IsNew = true
									};
									downloadService.InsertDownload(download);
									//save attribute
									selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString());
								}
							}
						}
						break;

					default:
						break;
				}
			}
			return selectedAttributes;
		}
        /// <summary>Takes selected elements from collection and creates a attribute XML string from it.</summary>
        /// <param name="formatWithProductId">how the name of the controls are formatted. frontend includes productId, backend does not.</param>
        public static string CreateSelectedAttributesXml(this NameValueCollection collection, int productId, IList <ProductVariantAttribute> variantAttributes,
                                                         IProductAttributeParser productAttributeParser, ILocalizationService localizationService, IDownloadService downloadService, CatalogSettings catalogSettings,
                                                         HttpRequestBase request, List <string> warnings, bool formatWithProductId = true, int bundleItemId = 0)
        {
            if (collection == null)
            {
                return("");
            }

            string controlId;
            string selectedAttributes = "";

            foreach (var attribute in variantAttributes)
            {
                controlId = AttributeFormatedName(attribute.ProductAttributeId, attribute.Id, formatWithProductId ? productId : 0, bundleItemId);

                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                {
                    var ctrlAttributes = collection[controlId];
                    if (ctrlAttributes.HasValue())
                    {
                        int selectedAttributeId = int.Parse(ctrlAttributes);
                        if (selectedAttributeId > 0)
                        {
                            selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedAttributeId.ToString());
                        }
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                {
                    var cblAttributes = collection[controlId];
                    if (cblAttributes.HasValue())
                    {
                        foreach (var item in cblAttributes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            int selectedAttributeId = int.Parse(item);
                            if (selectedAttributeId > 0)
                            {
                                selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedAttributeId.ToString());
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var txtAttribute = collection[controlId];
                    if (txtAttribute.HasValue())
                    {
                        string enteredText = txtAttribute.Trim();
                        selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, enteredText);
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var      date         = collection[controlId + "_day"];
                    var      month        = collection[controlId + "_month"];
                    var      year         = collection[controlId + "_year"];
                    DateTime?selectedDate = null;

                    try
                    {
                        selectedDate = new DateTime(Int32.Parse(year), Int32.Parse(month), Int32.Parse(date));
                    }
                    catch { }

                    if (selectedDate.HasValue)
                    {
                        selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, selectedDate.Value.ToString("D"));
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                    if (request == null)
                    {
                        Guid downloadGuid;
                        Guid.TryParse(collection[controlId], out downloadGuid);
                        var download = downloadService.GetDownloadByGuid(downloadGuid);
                        if (download != null)
                        {
                            selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString());
                        }
                    }
                    else
                    {
                        var httpPostedFile = request.Files[controlId];
                        if (httpPostedFile != null && httpPostedFile.FileName.HasValue())
                        {
                            int fileMaxSize = catalogSettings.FileUploadMaximumSizeBytes;
                            if (httpPostedFile.ContentLength > fileMaxSize)
                            {
                                warnings.Add(string.Format(localizationService.GetResource("ShoppingCart.MaximumUploadedFileSize"), (int)(fileMaxSize / 1024)));
                            }
                            else
                            {
                                //save an uploaded file
                                var download = new Download
                                {
                                    DownloadGuid   = Guid.NewGuid(),
                                    UseDownloadUrl = false,
                                    DownloadUrl    = "",
                                    DownloadBinary = httpPostedFile.GetDownloadBits(),
                                    ContentType    = httpPostedFile.ContentType,
                                    Filename       = System.IO.Path.GetFileNameWithoutExtension(httpPostedFile.FileName),
                                    Extension      = System.IO.Path.GetExtension(httpPostedFile.FileName),
                                    IsNew          = true
                                };
                                downloadService.InsertDownload(download);
                                //save attribute
                                selectedAttributes = productAttributeParser.AddProductAttribute(selectedAttributes, attribute, download.DownloadGuid.ToString());
                            }
                        }
                    }
                    break;

                default:
                    break;
                }
            }
            return(selectedAttributes);
        }
Exemplo n.º 28
0
        public virtual ActionResult ReturnRequestSubmit(int orderId, SubmitReturnRequestModel model, FormCollection form)
        {
            var order = _orderService.GetOrderById(orderId);

            if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
            {
                return(new HttpUnauthorizedResult());
            }

            if (!_orderProcessingService.IsReturnRequestAllowed(order))
            {
                return(RedirectToRoute("HomePage"));
            }

            int count = 0;

            var downloadId = 0;

            if (_orderSettings.ReturnRequestsAllowFiles)
            {
                var download = _downloadService.GetDownloadByGuid(model.UploadedFileGuid);
                if (download != null)
                {
                    downloadId = download.Id;
                }
            }

            //returnable products
            var orderItems = order.OrderItems.Where(oi => !oi.Product.NotReturnable);

            foreach (var orderItem in orderItems)
            {
                int quantity = 0; //parse quantity
                foreach (string formKey in form.AllKeys)
                {
                    if (formKey.Equals(string.Format("quantity{0}", orderItem.Id), StringComparison.InvariantCultureIgnoreCase))
                    {
                        int.TryParse(form[formKey], out quantity);
                        break;
                    }
                }
                if (quantity > 0)
                {
                    var rrr = _returnRequestService.GetReturnRequestReasonById(model.ReturnRequestReasonId);
                    var rra = _returnRequestService.GetReturnRequestActionById(model.ReturnRequestActionId);

                    var rr = new ReturnRequest
                    {
                        CustomNumber    = "",
                        StoreId         = _storeContext.CurrentStore.Id,
                        OrderItemId     = orderItem.Id,
                        Quantity        = quantity,
                        CustomerId      = _workContext.CurrentCustomer.Id,
                        ReasonForReturn = rrr != null?rrr.GetLocalized(x => x.Name) : "not available",
                                              RequestedAction = rra != null?rra.GetLocalized(x => x.Name) : "not available",
                                                                    CustomerComments    = model.Comments,
                                                                    UploadedFileId      = downloadId,
                                                                    StaffNotes          = string.Empty,
                                                                    ReturnRequestStatus = ReturnRequestStatus.Pending,
                                                                    CreatedOnUtc        = DateTime.UtcNow,
                                                                    UpdatedOnUtc        = DateTime.UtcNow
                    };
                    _workContext.CurrentCustomer.ReturnRequests.Add(rr);
                    _customerService.UpdateCustomer(_workContext.CurrentCustomer);
                    //set return request custom number
                    rr.CustomNumber = _customNumberFormatter.GenerateReturnRequestCustomNumber(rr);
                    _customerService.UpdateCustomer(_workContext.CurrentCustomer);
                    //notify store owner
                    _workflowMessageService.SendNewReturnRequestStoreOwnerNotification(rr, orderItem, _localizationSettings.DefaultAdminLanguageId);
                    //notify customer
                    _workflowMessageService.SendNewReturnRequestCustomerNotification(rr, orderItem, order.CustomerLanguageId);

                    count++;
                }
            }

            model = _returnRequestModelFactory.PrepareSubmitReturnRequestModel(model, order);
            if (count > 0)
            {
                model.Result = _localizationService.GetResource("ReturnRequests.Submitted");
            }
            else
            {
                model.Result = _localizationService.GetResource("ReturnRequests.NoItemsSubmitted");
            }

            return(View(model));
        }
Exemplo n.º 29
0
        private async Task <StringBuilder> PrepareFormattedAttribute(Product product, IList <CustomAttribute> customAttributes, string langId,
                                                                     string serapator, bool htmlEncode, bool renderPrices,
                                                                     bool allowHyperlinks, bool showInAdmin)
        {
            var result     = new StringBuilder();
            var attributes = _productAttributeParser.ParseProductAttributeMappings(product, customAttributes);

            for (int i = 0; i < attributes.Count; i++)
            {
                var productAttribute = await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);

                var attribute = attributes[i];
                var valuesStr = _productAttributeParser.ParseValues(customAttributes, attribute.Id);
                for (int j = 0; j < valuesStr.Count; j++)
                {
                    string valueStr           = valuesStr[j];
                    string formattedAttribute = string.Empty;
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = productAttribute.GetTranslation(a => a.Name, langId);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = string.Format("{0}: {1}", attributeName, FormatText.ConvertText(valueStr));
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlTypeId == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                            if (download != null)
                            {
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}", download.Filename ?? download.DownloadGuid.ToString(), download.Extension);
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    var downloadLink = string.Format("{0}/download/getfileupload/?downloadId={1}", _workContext.CurrentStore.Url.TrimEnd('/'), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = productAttribute.GetTranslation(a => a.Name, langId);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = string.Format("{0}: {1}", productAttribute.GetTranslation(a => a.Name, langId), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        //attributes with values
                        if (product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault() != null)
                        {
                            var attributeValue = product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault().ProductAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();
                            if (attributeValue != null)
                            {
                                formattedAttribute = string.Format("{0}: {1}", productAttribute.GetTranslation(a => a.Name, langId), attributeValue.GetTranslation(a => a.Name, langId));

                                if (renderPrices)
                                {
                                    decimal attributeValuePriceAdjustment = await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue);

                                    var prices = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer);

                                    decimal priceAdjustmentBase = prices.productprice;
                                    decimal taxRate             = prices.taxRate;
                                    if (priceAdjustmentBase > 0)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustmentBase, false);
                                        formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                    }
                                    else if (priceAdjustmentBase < decimal.Zero)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustmentBase, false);
                                        formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                    }
                                }
                            }
                            else
                            {
                                if (showInAdmin)
                                {
                                    formattedAttribute += string.Format("{0}: {1}", productAttribute.GetTranslation(a => a.Name, langId), "");
                                }
                            }

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

                    if (!string.IsNullOrEmpty(formattedAttribute))
                    {
                        if (i != 0 || j != 0)
                        {
                            result.Append(serapator);
                        }
                        result.Append(formattedAttribute);
                    }
                }
            }
            return(result);
        }
        private async Task <StringBuilder> PrepareFormattedAttribute(Product product, string attributesXml, string langId,
                                                                     string serapator, bool htmlEncode, bool renderPrices,
                                                                     bool allowHyperlinks, bool showInAdmin)
        {
            var result     = new StringBuilder();
            var attributes = _productAttributeParser.ParseProductAttributeMappings(product, attributesXml);

            for (int i = 0; i < attributes.Count; i++)
            {
                var productAttribute = await _productAttributeService.GetProductAttributeById(attributes[i].ProductAttributeId);

                var attribute = attributes[i];
                var valuesStr = _productAttributeParser.ParseValues(attributesXml, attribute.Id);
                for (int j = 0; j < valuesStr.Count; j++)
                {
                    string valueStr           = valuesStr[j];
                    string formattedAttribute = string.Empty;
                    if (!attribute.ShouldHaveValues())
                    {
                        //no values
                        if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = productAttribute.GetLocalized(a => a.Name, langId);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = WebUtility.HtmlEncode(attributeName);
                            }
                            formattedAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr));
                            //we never encode multiline textbox input
                        }
                        else if (attribute.AttributeControlType == AttributeControlType.FileUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = await _downloadService.GetDownloadByGuid(downloadGuid);

                            if (download != null)
                            {
                                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = WebUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = productAttribute.GetLocalized(a => a.Name, langId);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = WebUtility.HtmlEncode(attributeName);
                                }
                                formattedAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
                            }
                        }
                    }
                    else
                    {
                        //attributes with values
                        if (product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault() != null)
                        {
                            var attributeValue = product.ProductAttributeMappings.Where(x => x.Id == attributes[i].Id).FirstOrDefault().ProductAttributeValues.Where(x => x.Id == valueStr).FirstOrDefault();
                            if (attributeValue != null)
                            {
                                formattedAttribute = string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), attributeValue.GetLocalized(a => a.Name, langId));

                                if (renderPrices)
                                {
                                    decimal attributeValuePriceAdjustment = await _priceCalculationService.GetProductAttributeValuePriceAdjustment(attributeValue);

                                    var prices = await _taxService.GetProductPrice(product, attributeValuePriceAdjustment, _workContext.CurrentCustomer);

                                    decimal priceAdjustmentBase = prices.productprice;
                                    decimal taxRate             = prices.taxRate;
                                    decimal priceAdjustment     = await _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                    if (priceAdjustmentBase > 0)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false);
                                        formattedAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                    }
                                    else if (priceAdjustmentBase < decimal.Zero)
                                    {
                                        string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false);
                                        formattedAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                    }
                                }

                                //display quantity
                                if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity &&
                                    attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
                                {
                                    //render only when more than 1
                                    if (attributeValue.Quantity > 1)
                                    {
                                        //TODO localize resource
                                        formattedAttribute += string.Format(" - qty {0}", attributeValue.Quantity);
                                    }
                                }
                            }
                            else
                            {
                                if (showInAdmin)
                                {
                                    formattedAttribute += string.Format("{0}: {1}", productAttribute.GetLocalized(a => a.Name, langId), "");
                                }
                            }

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

                    if (!String.IsNullOrEmpty(formattedAttribute))
                    {
                        if (i != 0 || j != 0)
                        {
                            result.Append(serapator);
                        }
                        result.Append(formattedAttribute);
                    }
                }
            }
            return(result);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Gets product attributes in XML format
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="form">Form</param>
        /// <param name="errors">Errors</param>
        /// <returns>Attributes in XML format</returns>
        protected virtual string GetProductAttributesXml(Product product, IFormCollection form, List <string> errors)
        {
            var attributesXml     = string.Empty;
            var productAttributes = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id);

            foreach (var attribute in productAttributes)
            {
                var controlId = $"{NopAttributePrefixDefaults.Product}{attribute.Id}";
                switch (attribute.AttributeControlType)
                {
                case AttributeControlType.DropdownList:
                case AttributeControlType.RadioList:
                case AttributeControlType.ColorSquares:
                case AttributeControlType.ImageSquares:
                {
                    var ctrlAttributes = form[controlId];
                    if (!StringValues.IsNullOrEmpty(ctrlAttributes))
                    {
                        var selectedAttributeId = int.Parse(ctrlAttributes);
                        if (selectedAttributeId > 0)
                        {
                            //get quantity entered by customer
                            var quantity    = 1;
                            var quantityStr = form[$"{NopAttributePrefixDefaults.Product}{attribute.Id}_{selectedAttributeId}_qty"];
                            if (!StringValues.IsNullOrEmpty(quantityStr) &&
                                (!int.TryParse(quantityStr, out quantity) || quantity < 1))
                            {
                                errors.Add(_localizationService.GetResource("Products.QuantityShouldBePositive"));
                            }

                            attributesXml = AddProductAttribute(attributesXml,
                                                                attribute, selectedAttributeId.ToString(), quantity > 1 ? (int?)quantity : null);
                        }
                    }
                }
                break;

                case AttributeControlType.Checkboxes:
                {
                    var ctrlAttributes = form[controlId];
                    if (!StringValues.IsNullOrEmpty(ctrlAttributes))
                    {
                        foreach (var item in ctrlAttributes.ToString()
                                 .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            var selectedAttributeId = int.Parse(item);
                            if (selectedAttributeId > 0)
                            {
                                //get quantity entered by customer
                                var quantity    = 1;
                                var quantityStr = form[$"{NopAttributePrefixDefaults.Product}{attribute.Id}_{item}_qty"];
                                if (!StringValues.IsNullOrEmpty(quantityStr) &&
                                    (!int.TryParse(quantityStr, out quantity) || quantity < 1))
                                {
                                    errors.Add(_localizationService.GetResource("Products.QuantityShouldBePositive"));
                                }

                                attributesXml = AddProductAttribute(attributesXml,
                                                                    attribute, selectedAttributeId.ToString(), quantity > 1 ? (int?)quantity : null);
                            }
                        }
                    }
                }
                break;

                case AttributeControlType.ReadonlyCheckboxes:
                {
                    //load read-only (already server-side selected) values
                    var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id);
                    foreach (var selectedAttributeId in attributeValues
                             .Where(v => v.IsPreSelected)
                             .Select(v => v.Id)
                             .ToList())
                    {
                        //get quantity entered by customer
                        var quantity    = 1;
                        var quantityStr = form[$"{NopAttributePrefixDefaults.Product}{attribute.Id}_{selectedAttributeId}_qty"];
                        if (!StringValues.IsNullOrEmpty(quantityStr) &&
                            (!int.TryParse(quantityStr, out quantity) || quantity < 1))
                        {
                            errors.Add(_localizationService.GetResource("Products.QuantityShouldBePositive"));
                        }

                        attributesXml = AddProductAttribute(attributesXml,
                                                            attribute, selectedAttributeId.ToString(), quantity > 1 ? (int?)quantity : null);
                    }
                }
                break;

                case AttributeControlType.TextBox:
                case AttributeControlType.MultilineTextbox:
                {
                    var ctrlAttributes = form[controlId];
                    if (!StringValues.IsNullOrEmpty(ctrlAttributes))
                    {
                        var enteredText = ctrlAttributes.ToString().Trim();
                        attributesXml = AddProductAttribute(attributesXml, attribute, enteredText);
                    }
                }
                break;

                case AttributeControlType.Datepicker:
                {
                    var      day          = form[controlId + "_day"];
                    var      month        = form[controlId + "_month"];
                    var      year         = form[controlId + "_year"];
                    DateTime?selectedDate = null;
                    try
                    {
                        selectedDate = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));
                    }
                    catch
                    {
                    }
                    if (selectedDate.HasValue)
                    {
                        attributesXml = AddProductAttribute(attributesXml, attribute, selectedDate.Value.ToString("D"));
                    }
                }
                break;

                case AttributeControlType.FileUpload:
                {
                    Guid.TryParse(form[controlId], out var downloadGuid);
                    var download = _downloadService.GetDownloadByGuid(downloadGuid);
                    if (download != null)
                    {
                        attributesXml = AddProductAttribute(attributesXml,
                                                            attribute, download.DownloadGuid.ToString());
                    }
                }
                break;

                default:
                    break;
                }
            }
            //validate conditional attributes (if specified)
            foreach (var attribute in productAttributes)
            {
                var conditionMet = IsConditionMet(attribute, attributesXml);
                if (conditionMet.HasValue && !conditionMet.Value)
                {
                    attributesXml = RemoveProductAttribute(attributesXml, attribute);
                }
            }
            return(attributesXml);
        }