示例#1
0
        public string GetCombinationCode(string attributeCombinationXml)
        {
            var result = "";

            var attributes = _productAttributeParser.ParseProductAttributeMappings(attributeCombinationXml);

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

                for (var j = 0; j < valuesStr.Count; j++)
                {
                    if (attribute.ShouldHaveValues() && !string.IsNullOrEmpty(valuesStr[j]))
                    {
                        result += valuesStr[j];
                        if (i != attributes.Count - 1 || j != valuesStr.Count - 1)
                        {
                            result += "-";
                        }
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Handle the product attribute mapping deleted event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(EntityDeletedEvent <ProductAttributeMapping> eventMessage)
        {
            if (eventMessage.Entity == null)
            {
                return;
            }

            //update combinations related with deleted product attribute mapping
            var combinations = _productAttributeService.GetAllProductAttributeCombinations(eventMessage.Entity.ProductId)
                               .Where(combination => _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml)
                                      .Any(productAttributeMapping => productAttributeMapping.Id == eventMessage.Entity.Id));

            foreach (var combination in combinations)
            {
                AddRecord(EntityType.AttributeCombination, combination.Id, OperationType.Update);
            }
        }
        public CcResult GetCcResult(string attributesXml)
        {
            var mappings = _productAttributeParser.ParseProductAttributeMappings(attributesXml);
            var mapping  = mappings.FirstOrDefault(x => x.ProductAttributeId == _customersCanvasSettings.CcIdAttributeId);

            if (mapping == null)
            {
                return(null);
            }

            var values = _productAttributeParser.ParseValues(attributesXml, mapping.Id);

            if (values == null || !values.Any())
            {
                return(null);
            }

            var designId = Convert.ToInt32(values.First());

            var design = this.GetDesign(designId);

            string[] hiresUrls = null;
            if (!string.IsNullOrEmpty(design.DownloadUrlsJson))
            {
                hiresUrls = JsonConvert.DeserializeObject <string[]>(design.DownloadUrlsJson);
            }
            string[] proofImages = new[] { design.ImageUrl };

            try // для того, чтобы старые значения не ломались
            {
                if (!string.IsNullOrEmpty(design.ImageUrl))
                {
                    proofImages = JsonConvert.DeserializeObject <string[]>(design.ImageUrl);
                }
            }
            catch (Exception ex) { }

            var ccResult = new CcResult()
            {
                ProofUrls = proofImages,
                HiResUrls = hiresUrls
            };

            return(ccResult);
        }
示例#4
0
        /// <summary>
        /// If the Order Item has one of the marked Attributes, create a License string and return it
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public LicenseKey CreateLicense(OrderItem item)
        {
            LicenseKey license = new LicenseKey();

            license.ProductName = item.Product.GetLocalized(x => x.Name);

            var productKey = item.Product.GetAttribute <string>(Constants.LicenseKeyAttribute);

            if (productKey == null)
            {
                return(license);
            }

            if (_licenseSettings.DomainAttributeId != 0)
            {
                //let's see if this product has our Domain attribute
                var pva = _productAttributeParser.ParseProductAttributeMappings(item.AttributesXml).Where(a => a.ProductAttributeId == _licenseSettings.DomainAttributeId).FirstOrDefault();
                if (pva != null)
                {
                    var url = _productAttributeParser.ParseValues(item.AttributesXml, pva.Id).First();
                    license.Url         = url;
                    license.LicenseType = LicenseType.Domain.ToString();
                    license.License     = CreateLicense(LicenseType.Domain, url, productKey);
                    return(license);
                }
            }

            if (_licenseSettings.UrlAttributeId != 0)
            {
                var pva = _productAttributeParser.ParseProductAttributeMappings(item.AttributesXml).Where(a => a.ProductAttributeId == _licenseSettings.UrlAttributeId).FirstOrDefault();
                if (pva != null)
                {
                    var url = _productAttributeParser.ParseValues(item.AttributesXml, pva.Id).First();
                    license.Url         = url;
                    license.LicenseType = LicenseType.Url.ToString();
                    license.License     = CreateLicense(LicenseType.Url, url, productKey);
                    return(license);
                }
            }

            return(license);
        }
        public override 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 miscPlugins = _pluginFinder.GetPlugins <CategoryNavigationProvider>(storeId: _storeContext.CurrentStore.Id).ToList();

            if (miscPlugins.Count > 0)
            {
                var mappings = _productAttributeParser.ParseProductAttributeMappings(attributesXml);
                //find mappings with Display Order of 77
                var mappingsToDelete = mappings.Where(attribute => attribute.DisplayOrder == 77).ToList();
                foreach (var mapping in mappingsToDelete)
                {
                    attributesXml = _productAttributeParser.RemoveProductAttribute(attributesXml, mapping);
                }
            }
            var result = base.FormatAttributes(product, attributesXml, customer,
                                               serapator, htmlEncode, renderPrices, renderProductAttributes,
                                               renderGiftCardAttributes, allowHyperlinks);

            return(result.ToString());
        }
示例#6
0
        private CcCartReturnToEditReplacementModel GetCcCartReturnToEditItems()
        {
            var model      = new CcCartReturnToEditReplacementModel();
            var ccSettings = _settingService.LoadSetting <CcSettings>();

            var customer = _workContext.CurrentCustomer;
            var cart     = customer.ShoppingCartItems
                           .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                           .LimitPerStore(_storeContext.CurrentStore.Id)
                           .ToList();

            foreach (var shoppingCartItem in cart)
            {
                var attributeMappings =
                    _productAttributeParser.ParseProductAttributeMappings(shoppingCartItem.AttributesXml);
                foreach (var attributeMapping in attributeMappings)
                {
                    if (attributeMapping.ProductAttributeId == ccSettings.CcIdAttributeId)
                    {
                        var editCartItemUrl = Url.Action("EditorPage", "CcWidget", new { productId = shoppingCartItem.Product.Id });
                        editCartItemUrl += "&quantity=" + shoppingCartItem.Quantity + "&updateCartItemId=" + shoppingCartItem.Id;

                        var oldUrl = Url.RouteUrl("Product", new { SeName = shoppingCartItem.Product.GetSeName() });
                        oldUrl = _webHelper.ModifyQueryString(oldUrl, "updatecartitemid=" + shoppingCartItem.Id, null);

                        model.Items.Add(new CcCartReturnToEditReplacementModel.Item()
                        {
                            CartItemId = shoppingCartItem.Id,
                            OldUrl     = oldUrl,
                            Url        = editCartItemUrl
                        });
                    }
                }
            }
            return(model);
        }
        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);
        }
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product to copy</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product copy</returns>
        public virtual Product CopyProduct(Product product, string newName,
                                           bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }

            //product download & sample download
            int downloadId       = product.DownloadId;
            int sampleDownloadId = product.SampleDownloadId;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew,
                    };
                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId);
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product
            var productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                VendorId             = product.VendorId,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                OverriddenGiftCardAmount         = product.OverriddenGiftCardAmount,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsRental                         = product.IsRental,
                RentalPriceLength                = product.RentalPriceLength,
                RentalPricePeriod                = product.RentalPricePeriod,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                ShipSeparately                   = product.ShipSeparately,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                DeliveryDateId                   = product.DeliveryDateId,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                IsTelecommunicationsOrBroadcastingOrElectronicServices = product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
                ManageInventoryMethod      = product.ManageInventoryMethod,
                ProductAvailabilityRangeId = product.ProductAvailabilityRangeId,
                UseMultipleWarehouses      = product.UseMultipleWarehouses,
                WarehouseId                   = product.WarehouseId,
                StockQuantity                 = product.StockQuantity,
                DisplayStockAvailability      = product.DisplayStockAvailability,
                DisplayStockQuantity          = product.DisplayStockQuantity,
                MinStockQuantity              = product.MinStockQuantity,
                LowStockActivityId            = product.LowStockActivityId,
                NotifyAdminForQuantityBelow   = product.NotifyAdminForQuantityBelow,
                BackorderMode                 = product.BackorderMode,
                AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity          = product.OrderMinimumQuantity,
                OrderMaximumQuantity          = product.OrderMaximumQuantity,
                AllowedQuantities             = product.AllowedQuantities,
                AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
                NotReturnable         = product.NotReturnable,
                DisableBuyButton      = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder  = product.AvailableForPreOrder,
                PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
                CallForPrice = product.CallForPrice,
                Price        = product.Price,
                OldPrice     = product.OldPrice,
                ProductCost  = product.ProductCost,
                SpecialPrice = product.SpecialPrice,
                SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc   = product.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice          = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice  = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice  = product.MaximumCustomerEnteredPrice,
                BasepriceEnabled             = product.BasepriceEnabled,
                BasepriceAmount           = product.BasepriceAmount,
                BasepriceUnitId           = product.BasepriceUnitId,
                BasepriceBaseAmount       = product.BasepriceBaseAmount,
                BasepriceBaseUnitId       = product.BasepriceBaseUnitId,
                MarkAsNew                 = product.MarkAsNew,
                MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc   = product.MarkAsNewEndDateTimeUtc,
                Weight = product.Weight,
                Length = product.Length,
                Width  = product.Width,
                Height = product.Height,
                AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc   = product.AvailableEndDateTimeUtc,
                DisplayOrder = product.DisplayOrder,
                Published    = isPublished,
                Deleted      = product.Deleted,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            //validate search engine name
            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                }

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                }

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                }

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                }

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                }

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                }

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
            }

            //product tags
            foreach (var productTag in product.ProductTags)
            {
                productCopy.ProductTags.Add(productTag);
            }
            _productService.UpdateProduct(productCopy);

            //product pictures
            //variable to store original and new picture identifiers
            var originalNewPictureIdentifiers = new Dictionary <int, int>();

            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture     = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        picture.AltAttribute,
                        picture.TitleAttribute);
                    _productService.InsertProductPicture(new ProductPicture
                    {
                        ProductId    = productCopy.Id,
                        PictureId    = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                    originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id);
                }
            }

            // product <-> warehouses mappings
            foreach (var pwi in product.ProductWarehouseInventory)
            {
                var pwiCopy = new ProductWarehouseInventory
                {
                    ProductId        = productCopy.Id,
                    WarehouseId      = pwi.WarehouseId,
                    StockQuantity    = pwi.StockQuantity,
                    ReservedQuantity = 0,
                };

                productCopy.ProductWarehouseInventory.Add(pwiCopy);
            }
            _productService.UpdateProduct(productCopy);

            // product <-> categories mappings
            foreach (var productCategory in product.ProductCategories)
            {
                var productCategoryCopy = new ProductCategory
                {
                    ProductId         = productCopy.Id,
                    CategoryId        = productCategory.CategoryId,
                    IsFeaturedProduct = productCategory.IsFeaturedProduct,
                    DisplayOrder      = productCategory.DisplayOrder
                };

                _categoryService.InsertProductCategory(productCategoryCopy);
            }

            // product <-> manufacturers mappings
            foreach (var productManufacturers in product.ProductManufacturers)
            {
                var productManufacturerCopy = new ProductManufacturer
                {
                    ProductId         = productCopy.Id,
                    ManufacturerId    = productManufacturers.ManufacturerId,
                    IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                    DisplayOrder      = productManufacturers.DisplayOrder
                };

                _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
            }

            // product <-> releated products mappings
            foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
            {
                _productService.InsertRelatedProduct(
                    new RelatedProduct
                {
                    ProductId1   = productCopy.Id,
                    ProductId2   = relatedProduct.ProductId2,
                    DisplayOrder = relatedProduct.DisplayOrder
                });
            }

            // product <-> cross sells mappings
            foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
            {
                _productService.InsertCrossSellProduct(
                    new CrossSellProduct
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = csProduct.ProductId2,
                });
            }

            // product specifications
            foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
            {
                var psaCopy = new ProductSpecificationAttribute
                {
                    ProductId       = productCopy.Id,
                    AttributeTypeId = productSpecificationAttribute.AttributeTypeId,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    CustomValue       = productSpecificationAttribute.CustomValue,
                    AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                    ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                    DisplayOrder      = productSpecificationAttribute.DisplayOrder
                };
                _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
            }

            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

            foreach (var id in selectedStoreIds)
            {
                _storeMappingService.InsertStoreMapping(productCopy, id);
            }


            // product <-> attributes mappings
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
            {
                var productAttributeMappingCopy = new ProductAttributeMapping
                {
                    ProductId                       = productCopy.Id,
                    ProductAttributeId              = productAttributeMapping.ProductAttributeId,
                    TextPrompt                      = productAttributeMapping.TextPrompt,
                    IsRequired                      = productAttributeMapping.IsRequired,
                    AttributeControlTypeId          = productAttributeMapping.AttributeControlTypeId,
                    DisplayOrder                    = productAttributeMapping.DisplayOrder,
                    ValidationMinLength             = productAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = productAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = productAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = productAttributeMapping.DefaultValue,
                    //UNDONE copy ConditionAttributeXml (we should replace attribute IDs with new values)
                };
                _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);

                // product attribute values
                var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                foreach (var productAttributeValue in productAttributeValues)
                {
                    int attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
                    }
                    var attributeValueCopy = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMappingCopy.Id,
                        AttributeValueTypeId      = productAttributeValue.AttributeValueTypeId,
                        AssociatedProductId       = productAttributeValue.AssociatedProductId,
                        Name              = productAttributeValue.Name,
                        ColorSquaresRgb   = productAttributeValue.ColorSquaresRgb,
                        PriceAdjustment   = productAttributeValue.PriceAdjustment,
                        WeightAdjustment  = productAttributeValue.WeightAdjustment,
                        Cost              = productAttributeValue.Cost,
                        CustomerEntersQty = productAttributeValue.CustomerEntersQty,
                        Quantity          = productAttributeValue.Quantity,
                        IsPreSelected     = productAttributeValue.IsPreSelected,
                        DisplayOrder      = productAttributeValue.DisplayOrder,
                        PictureId         = attributeValuePictureId,
                    };
                    //picture associated to "iamge square" attribute type (if exists)
                    if (productAttributeValue.ImageSquaresPictureId > 0)
                    {
                        var origImageSquaresPicture = _pictureService.GetPictureById(productAttributeValue.ImageSquaresPictureId);
                        if (origImageSquaresPicture != null)
                        {
                            //copy the picture
                            var imageSquaresPictureCopy = _pictureService.InsertPicture(
                                _pictureService.LoadPictureBinary(origImageSquaresPicture),
                                origImageSquaresPicture.MimeType,
                                origImageSquaresPicture.SeoFilename,
                                origImageSquaresPicture.AltAttribute,
                                origImageSquaresPicture.TitleAttribute);
                            attributeValueCopy.ImageSquaresPictureId = imageSquaresPictureCopy.Id;
                        }
                    }


                    _productAttributeService.InsertProductAttributeValue(attributeValueCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }
            //attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml        = "";
                var    parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedProductAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);
                        if (newAttribute != null)
                        {
                            var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);
                            foreach (var oldAttributeValueStr in oldAttributeValuesStr)
                            {
                                if (newAttribute.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldAttributeValue = int.Parse(oldAttributeValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldAttributeValue))
                                    {
                                        var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);
                                        if (newAttributeValue != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newAttribute, newAttributeValue.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newAttribute, oldAttributeValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow
                };
                _productAttributeService.InsertProductAttributeCombination(combinationCopy);
            }

            //tier prices
            foreach (var tierPrice in product.TierPrices)
            {
                _productService.InsertTierPrice(
                    new TierPrice
                {
                    ProductId      = productCopy.Id,
                    StoreId        = tierPrice.StoreId,
                    CustomerRoleId = tierPrice.CustomerRoleId,
                    Quantity       = tierPrice.Quantity,
                    Price          = tierPrice.Price
                });
            }

            // product <-> discounts mapping
            foreach (var discount in product.AppliedDiscounts)
            {
                productCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProduct(productCopy);
            }


            //update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);


            //associated products
            if (copyAssociatedProducts)
            {
                var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true);
                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name),
                                                            isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;
                    _productService.UpdateProduct(productCopy);
                }
            }

            return(productCopy);
        }
示例#9
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());
        }
示例#10
0
        /// <summary>
        /// Copy attributes mapping
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="productCopy">New product</param>
        /// <param name="originalNewPictureIdentifiers">Identifiers of pictures</param>
        protected virtual void CopyAttributesMapping(Product product, Product productCopy, Dictionary <int, int> originalNewPictureIdentifiers)
        {
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            //attribute mapping with condition attributes
            var oldCopyWithConditionAttributes = new List <ProductAttributeMapping>();

            //all product attribute mapping copies
            var productAttributeMappingCopies = new Dictionary <int, ProductAttributeMapping>();

            var languages = _languageService.GetAllLanguages(true);

            foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
            {
                var productAttributeMappingCopy = new ProductAttributeMapping
                {
                    ProductId                       = productCopy.Id,
                    ProductAttributeId              = productAttributeMapping.ProductAttributeId,
                    TextPrompt                      = productAttributeMapping.TextPrompt,
                    IsRequired                      = productAttributeMapping.IsRequired,
                    AttributeControlTypeId          = productAttributeMapping.AttributeControlTypeId,
                    DisplayOrder                    = productAttributeMapping.DisplayOrder,
                    ValidationMinLength             = productAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = productAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = productAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = productAttributeMapping.DefaultValue
                };
                _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
                //localization
                foreach (var lang in languages)
                {
                    var textPrompt = _localizationService.GetLocalized(productAttributeMapping, x => x.TextPrompt, lang.Id, false, false);
                    if (!string.IsNullOrEmpty(textPrompt))
                    {
                        _localizedEntityService.SaveLocalizedValue(productAttributeMappingCopy, x => x.TextPrompt, textPrompt,
                                                                   lang.Id);
                    }
                }

                productAttributeMappingCopies.Add(productAttributeMappingCopy.Id, productAttributeMappingCopy);

                if (!string.IsNullOrEmpty(productAttributeMapping.ConditionAttributeXml))
                {
                    oldCopyWithConditionAttributes.Add(productAttributeMapping);
                }

                //save associated value (used for combinations copying)
                associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);

                // product attribute values
                var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                foreach (var productAttributeValue in productAttributeValues)
                {
                    var attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
                    }

                    var attributeValueCopy = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMappingCopy.Id,
                        AttributeValueTypeId      = productAttributeValue.AttributeValueTypeId,
                        AssociatedProductId       = productAttributeValue.AssociatedProductId,
                        Name            = productAttributeValue.Name,
                        ColorSquaresRgb = productAttributeValue.ColorSquaresRgb,
                        PriceAdjustment = productAttributeValue.PriceAdjustment,
                        PriceAdjustmentUsePercentage = productAttributeValue.PriceAdjustmentUsePercentage,
                        WeightAdjustment             = productAttributeValue.WeightAdjustment,
                        Cost = productAttributeValue.Cost,
                        CustomerEntersQty = productAttributeValue.CustomerEntersQty,
                        Quantity          = productAttributeValue.Quantity,
                        IsPreSelected     = productAttributeValue.IsPreSelected,
                        DisplayOrder      = productAttributeValue.DisplayOrder,
                        PictureId         = attributeValuePictureId,
                    };
                    //picture associated to "iamge square" attribute type (if exists)
                    if (productAttributeValue.ImageSquaresPictureId > 0)
                    {
                        var origImageSquaresPicture =
                            _pictureService.GetPictureById(productAttributeValue.ImageSquaresPictureId);
                        if (origImageSquaresPicture != null)
                        {
                            //copy the picture
                            var imageSquaresPictureCopy = _pictureService.InsertPicture(
                                _pictureService.LoadPictureBinary(origImageSquaresPicture),
                                origImageSquaresPicture.MimeType,
                                origImageSquaresPicture.SeoFilename,
                                origImageSquaresPicture.AltAttribute,
                                origImageSquaresPicture.TitleAttribute);
                            attributeValueCopy.ImageSquaresPictureId = imageSquaresPictureCopy.Id;
                        }
                    }

                    _productAttributeService.InsertProductAttributeValue(attributeValueCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = _localizationService.GetLocalized(productAttributeValue, x => x.Name, lang.Id, false, false);
                        if (!string.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }

            //copy attribute conditions
            foreach (var productAttributeMapping in oldCopyWithConditionAttributes)
            {
                var oldConditionAttributeMapping = _productAttributeParser
                                                   .ParseProductAttributeMappings(productAttributeMapping.ConditionAttributeXml).FirstOrDefault();

                if (oldConditionAttributeMapping == null)
                {
                    continue;
                }

                var oldConditionValues =
                    _productAttributeParser.ParseProductAttributeValues(productAttributeMapping.ConditionAttributeXml,
                                                                        oldConditionAttributeMapping.Id);

                if (!oldConditionValues.Any())
                {
                    continue;
                }

                var newAttributeMappingId        = associatedAttributes[oldConditionAttributeMapping.Id];
                var newConditionAttributeMapping = productAttributeMappingCopies[newAttributeMappingId];

                var newConditionAttributeXml = string.Empty;

                foreach (var oldConditionValue in oldConditionValues)
                {
                    newConditionAttributeXml = _productAttributeParser.AddProductAttribute(newConditionAttributeXml,
                                                                                           newConditionAttributeMapping, associatedAttributeValues[oldConditionValue.Id].ToString());
                }

                var attributeMappingId = associatedAttributes[productAttributeMapping.Id];
                var conditionAttribute = productAttributeMappingCopies[attributeMappingId];
                conditionAttribute.ConditionAttributeXml = newConditionAttributeXml;

                _productAttributeService.UpdateProductAttributeMapping(conditionAttribute);
            }

            //attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                var newAttributesXml        = string.Empty;
                var parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedProductAttributes)
                {
                    if (!associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        continue;
                    }

                    var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);

                    if (newAttribute == null)
                    {
                        continue;
                    }

                    var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);

                    foreach (var oldAttributeValueStr in oldAttributeValuesStr)
                    {
                        if (newAttribute.ShouldHaveValues())
                        {
                            //attribute values
                            var oldAttributeValue = int.Parse(oldAttributeValueStr);
                            if (!associatedAttributeValues.ContainsKey(oldAttributeValue))
                            {
                                continue;
                            }

                            var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);

                            if (newAttributeValue != null)
                            {
                                newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                               newAttribute, newAttributeValue.Id.ToString());
                            }
                        }
                        else
                        {
                            //just a text
                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                           newAttribute, oldAttributeValueStr);
                        }
                    }
                }

                //picture
                originalNewPictureIdentifiers.TryGetValue(combination.PictureId, out var combinationPictureId);

                var combinationCopy = new ProductAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow,
                    PictureId                   = combinationPictureId
                };
                _productAttributeService.InsertProductAttributeCombination(combinationCopy);

                //quantity change history
                _productService.AddStockQuantityHistoryEntry(productCopy, combination.StockQuantity,
                                                             combination.StockQuantity,
                                                             message: string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.CopyProduct"), product.Id), combinationId: combination.Id);
            }
        }
示例#11
0
        public override decimal GetUnitPrice(Product product, Core.Domain.Customers.Customer customer, ShoppingCartType shoppingCartType, int quantity, string attributesXml, decimal customerEnteredPrice, DateTime?rentalStartDate, DateTime?rentalEndDate, bool includeDiscounts, out decimal discountAmount, out Core.Domain.Discounts.Discount appliedDiscount)
        {
            var ps = _priceForSizeService.GetPriceForSize(product.Id);

            if (ps != null && ps.HasPriceForSize)
            {
                Decimal w = 0;
                Decimal h = 0;
                Decimal d = 0;

                var mappings = _productAttributeParser.ParseProductAttributeMappings(attributesXml);


                var bAttr = mappings.SingleOrDefault(m => m.ProductAttributeId == ps.WidthAttributeId);
                if (bAttr != null)
                {
                    w = _productAttributeParser.ParseValues(attributesXml, bAttr.Id).Select(s => Convert.ToDecimal(s)).FirstOrDefault();
                }

                var hAttr = mappings.SingleOrDefault(m => m.ProductAttributeId == ps.HeightAttributeId);
                if (hAttr != null)
                {
                    h = _productAttributeParser.ParseValues(attributesXml, hAttr.Id).Select(s => Convert.ToDecimal(s)).FirstOrDefault();
                }

                var dAttr = mappings.SingleOrDefault(m => m.ProductAttributeId == ps.DepthAttributeId);
                if (dAttr != null)
                {
                    d = _productAttributeParser.ParseValues(attributesXml, hAttr.Id).Select(s => Convert.ToDecimal(s)).FirstOrDefault();
                }

                if (ps.MeasureDimension != null)
                {
                    w = _measureService.ConvertToPrimaryMeasureDimension(w, ps.MeasureDimension);
                    h = _measureService.ConvertToPrimaryMeasureDimension(h, ps.MeasureDimension);
                    d = _measureService.ConvertToPrimaryMeasureDimension(d, ps.MeasureDimension);
                }

                if (ps.MinimumWidthManageable.HasValue && w < ps.MinimumWidthManageable)
                {
                    w = ps.MinimumWidthManageable.Value;
                }
                if (ps.MaximumWidthManageable.HasValue && w > ps.MaximumWidthManageable)
                {
                    w = ps.MaximumWidthManageable.Value;
                }

                if (ps.MinimumHeightManageable.HasValue && h < ps.MinimumHeightManageable)
                {
                    h = ps.MinimumHeightManageable.Value;
                }
                if (ps.MaximumHeightManageable.HasValue && h > ps.MaximumHeightManageable)
                {
                    h = ps.MaximumHeightManageable.Value;
                }

                if (ps.MinimumDepthManageable.HasValue && d < ps.MinimumDepthManageable)
                {
                    d = ps.MinimumDepthManageable.Value;
                }
                if (ps.MaximumDepthManageable.HasValue && d > ps.MaximumDepthManageable)
                {
                    d = ps.MaximumDepthManageable.Value;
                }


                Decimal priceM1     = 0;
                Decimal priceM2     = 0;
                Decimal priceM3     = 0;
                Decimal priceBase   = 0;
                Decimal priceHeight = 0;
                Decimal priceDepth  = 0;

                var prices = _priceForSizeService.GetAttributesPrice(product.Id);
                foreach (var m in mappings)
                {
                    if (m.ProductAttributeId != ps.WidthAttributeId && m.ProductAttributeId != ps.HeightAttributeId)
                    {
                        var values = _productAttributeParser.ParseValues(attributesXml, m.Id);
                        foreach (var v in values)
                        {
                            Int32 id = 0;
                            if (Int32.TryParse(v, out id))
                            {
                                var price = (from p in prices
                                             where p.ProductAttributeValueId == id
                                             select p).FirstOrDefault();
                                if (price != null)
                                {
                                    priceM1     += price.PriceForM1.GetValueOrDefault();
                                    priceM2     += price.PriceForM2.GetValueOrDefault();
                                    priceM3     += price.PriceForM3.GetValueOrDefault();
                                    priceBase   += price.PriceForBaseLength.GetValueOrDefault();
                                    priceHeight += price.PriceForHeightLength.GetValueOrDefault();
                                    priceDepth  += price.PriceForDepthLength.GetValueOrDefault();
                                }
                            }
                        }
                    }
                }

                var per  = (w + h) * 2;
                var area = w * h;
                var vol  = w * h * d;

                if (ps.MinimumBillablePerimeter.HasValue && per < ps.MinimumBillablePerimeter.Value)
                {
                    per = ps.MinimumBillablePerimeter.Value;
                }

                if (ps.MinimumBillableArea.HasValue && area < ps.MinimumBillableArea.Value)
                {
                    area = ps.MinimumBillableArea.Value;
                }

                if (ps.MinimumBillableVolume.HasValue && vol < ps.MinimumBillableVolume.Value)
                {
                    vol = ps.MinimumBillableVolume.Value;
                }

                var standardPrice = base.GetUnitPrice(product, customer, shoppingCartType, quantity, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, includeDiscounts, out discountAmount, out appliedDiscount);

                switch (ps.StandardPriceType)
                {
                case Domain.TypeOfPrice.Perimeter:
                    standardPrice = standardPrice * per;
                    break;

                case Domain.TypeOfPrice.Area:
                    standardPrice = standardPrice * area;
                    break;

                case Domain.TypeOfPrice.Volume:
                    standardPrice = standardPrice * vol;
                    break;
                }


                return(standardPrice +
                       per * priceM1 +
                       area * priceM2 +
                       vol * priceM3 +
                       priceBase * w +
                       priceHeight * h +
                       priceDepth * d);
            }
            else
            {
                return(base.GetUnitPrice(product, customer, shoppingCartType, quantity, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, includeDiscounts, out discountAmount, out appliedDiscount));
            }
        }
示例#12
0
        protected bool ConditionProductAttribute(CustomerAction.ActionCondition condition, Product product, string AttributesXml)
        {
            bool cond = false;

            if (condition.Condition == CustomerActionConditionEnum.OneOfThem)
            {
                var attributes = _productAttributeParser.ParseProductAttributeMappings(product, AttributesXml);
                foreach (var attr in attributes)
                {
                    var attributeValuesStr = _productAttributeParser.ParseValues(AttributesXml, attr.Id);
                    foreach (var attrV in attributeValuesStr)
                    {
                        var attrsv = attr.ProductAttributeValues.Where(x => x.Id == attrV).FirstOrDefault();
                        if (attrsv != null)
                        {
                            if (condition.ProductAttribute.Where(x => x.ProductAttributeId == attr.ProductAttributeId && x.Name == attrsv.Name).Count() > 0)
                            {
                                cond = true;
                            }
                        }
                    }
                }
            }
            if (condition.Condition == CustomerActionConditionEnum.AllOfThem)
            {
                cond = true;
                foreach (var itemPA in condition.ProductAttribute)
                {
                    var attributes = _productAttributeParser.ParseProductAttributeMappings(product, AttributesXml);
                    if (attributes.Where(x => x.ProductAttributeId == itemPA.ProductAttributeId).Count() > 0)
                    {
                        cond = false;
                        foreach (var attr in attributes.Where(x => x.ProductAttributeId == itemPA.ProductAttributeId))
                        {
                            var attributeValuesStr = _productAttributeParser.ParseValues(AttributesXml, attr.Id);
                            foreach (var attrV in attributeValuesStr)
                            {
                                var attrsv = attr.ProductAttributeValues.Where(x => x.Id == attrV).FirstOrDefault();
                                if (attrsv != null)
                                {
                                    if (attrsv.Name == itemPA.Name)
                                    {
                                        cond = true;
                                    }
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                        }
                        if (!cond)
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            return(cond);
        }
        public virtual async Task <IList <string> > GetShoppingCartItemAttributeWarnings(Customer customer,
                                                                                         Product product, ShoppingCartItem shoppingCartItem, bool ignoreNonCombinableAttributes = false)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            var warnings = new List <string>();

            //ensure it's our attributes
            var attributes1 = _productAttributeParser.ParseProductAttributeMappings(product, shoppingCartItem.Attributes).ToList();

            if (product.ProductTypeId == ProductType.BundledProduct)
            {
                foreach (var bundle in product.BundleProducts)
                {
                    var p1 = await _productService.GetProductById(bundle.ProductId);

                    if (p1 != null)
                    {
                        var a1 = _productAttributeParser.ParseProductAttributeMappings(p1, shoppingCartItem.Attributes).ToList();
                        attributes1.AddRange(a1);
                    }
                }
            }
            if (ignoreNonCombinableAttributes)
            {
                attributes1 = attributes1.Where(x => !x.IsNonCombinable()).ToList();
            }

            //foreach (var attribute in attributes1)
            //{
            //    if (string.IsNullOrEmpty(attribute.ProductId))
            //    {
            //        warnings.Add("Attribute error");
            //        return warnings;
            //    }
            //}

            //validate required product attributes (whether they're chosen/selected/entered)
            var attributes2 = product.ProductAttributeMappings.ToList();

            if (product.ProductTypeId == ProductType.BundledProduct)
            {
                foreach (var bundle in product.BundleProducts)
                {
                    var p1 = await _productService.GetProductById(bundle.ProductId);

                    if (p1 != null && p1.ProductAttributeMappings.Any())
                    {
                        attributes2.AddRange(p1.ProductAttributeMappings);
                    }
                }
            }
            if (ignoreNonCombinableAttributes)
            {
                attributes2 = attributes2.Where(x => !x.IsNonCombinable()).ToList();
            }
            //validate conditional attributes only (if specified)
            attributes2 = attributes2.Where(x =>
            {
                var conditionMet = _productAttributeParser.IsConditionMet(product, x, shoppingCartItem.Attributes);
                return(!conditionMet.HasValue || conditionMet.Value);
            }).ToList();
            foreach (var a2 in attributes2)
            {
                if (a2.IsRequired)
                {
                    bool found = false;
                    //selected product attributes
                    foreach (var a1 in attributes1)
                    {
                        if (a1.Id == a2.Id)
                        {
                            var attributeValuesStr = _productAttributeParser.ParseValues(shoppingCartItem.Attributes, a1.Id);
                            foreach (string str1 in attributeValuesStr)
                            {
                                if (!String.IsNullOrEmpty(str1.Trim()))
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
                    }

                    //if not found
                    if (!found)
                    {
                        var paa = await _productAttributeService.GetProductAttributeById(a2.ProductAttributeId);

                        if (paa != null)
                        {
                            var notFoundWarning = !string.IsNullOrEmpty(a2.TextPrompt) ?
                                                  a2.TextPrompt :
                                                  string.Format(_translationService.GetResource("ShoppingCart.SelectAttribute"), paa.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id));

                            warnings.Add(notFoundWarning);
                        }
                    }
                }

                if (a2.AttributeControlTypeId == AttributeControlType.ReadonlyCheckboxes)
                {
                    //customers cannot edit read-only attributes
                    var allowedReadOnlyValueIds = a2.ProductAttributeValues
                                                  .Where(x => x.IsPreSelected)
                                                  .Select(x => x.Id)
                                                  .ToArray();

                    var selectedReadOnlyValueIds = _productAttributeParser.ParseProductAttributeValues(product, shoppingCartItem.Attributes)
                                                   //.Where(x => x.ProductAttributeMappingId == a2.Id)
                                                   .Select(x => x.Id)
                                                   .ToArray();

                    if (!CommonHelper.ArraysEqual(allowedReadOnlyValueIds, selectedReadOnlyValueIds))
                    {
                        warnings.Add("You cannot change read-only values");
                    }
                }
            }

            //validation rules
            foreach (var pam in attributes2)
            {
                if (!pam.ValidationRulesAllowed())
                {
                    continue;
                }

                //minimum length
                if (pam.ValidationMinLength.HasValue)
                {
                    if (pam.AttributeControlTypeId == AttributeControlType.TextBox ||
                        pam.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
                    {
                        var valuesStr         = _productAttributeParser.ParseValues(shoppingCartItem.Attributes, pam.Id);
                        var enteredText       = valuesStr.FirstOrDefault();
                        int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;

                        if (pam.ValidationMinLength.Value > enteredTextLength)
                        {
                            var _pam = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);

                            warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMinimumLength"), _pam.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), pam.ValidationMinLength.Value));
                        }
                    }
                }

                //maximum length
                if (pam.ValidationMaxLength.HasValue)
                {
                    if (pam.AttributeControlTypeId == AttributeControlType.TextBox ||
                        pam.AttributeControlTypeId == AttributeControlType.MultilineTextbox)
                    {
                        var valuesStr         = _productAttributeParser.ParseValues(shoppingCartItem.Attributes, pam.Id);
                        var enteredText       = valuesStr.FirstOrDefault();
                        int enteredTextLength = string.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;

                        if (pam.ValidationMaxLength.Value < enteredTextLength)
                        {
                            var _pam = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId);

                            warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMaximumLength"), _pam.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id), pam.ValidationMaxLength.Value));
                        }
                    }
                }
            }

            if (warnings.Any())
            {
                return(warnings);
            }

            //validate bundled products
            var attributeValues = _productAttributeParser.ParseProductAttributeValues(product, shoppingCartItem.Attributes);

            foreach (var attributeValue in attributeValues)
            {
                var _productAttributeMapping = product.ProductAttributeMappings.Where(x => x.ProductAttributeValues.Any(z => z.Id == attributeValue.Id)).FirstOrDefault();
                //TODO - check product.ProductAttributeMappings.Where(x => x.Id == attributeValue.ProductAttributeMappingId).FirstOrDefault();
                if (attributeValue.AttributeValueTypeId == AttributeValueType.AssociatedToProduct && _productAttributeMapping != null)
                {
                    if (ignoreNonCombinableAttributes && _productAttributeMapping.IsNonCombinable())
                    {
                        continue;
                    }

                    //associated product (bundle)
                    var associatedProduct = await _productService.GetProductById(attributeValue.AssociatedProductId);

                    if (associatedProduct != null)
                    {
                        var totalQty = shoppingCartItem.Quantity * attributeValue.Quantity;
                        var associatedProductWarnings = await GetShoppingCartItemWarnings(customer, new ShoppingCartItem()
                        {
                            ShoppingCartTypeId = shoppingCartItem.ShoppingCartTypeId,
                            StoreId            = _workContext.CurrentStore.Id,
                            Quantity           = totalQty,
                            WarehouseId        = shoppingCartItem.WarehouseId
                        }, associatedProduct, new ShoppingCartValidatorOptions());

                        foreach (var associatedProductWarning in associatedProductWarnings)
                        {
                            var productAttribute = await _productAttributeService.GetProductAttributeById(_productAttributeMapping.ProductAttributeId);

                            var attributeName      = productAttribute.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
                            var attributeValueName = attributeValue.GetTranslation(a => a.Name, _workContext.WorkingLanguage.Id);
                            warnings.Add(string.Format(
                                             _translationService.GetResource("ShoppingCart.AssociatedAttributeWarning"),
                                             attributeName, attributeValueName, associatedProductWarning));
                        }
                    }
                    else
                    {
                        warnings.Add(string.Format("Associated product cannot be loaded - {0}", attributeValue.AssociatedProductId));
                    }
                }
            }

            return(warnings);
        }
        /// <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());
        }
示例#15
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);
        }
示例#16
0
        public override decimal GetUnitPrice(Product product, Core.Domain.Customers.Customer customer, ShoppingCartType shoppingCartType, int quantity, string attributesXml, decimal customerEnteredPrice, DateTime?rentalStartDate, DateTime?rentalEndDate, bool includeDiscounts, out decimal discountAmount, out Core.Domain.Discounts.Discount appliedDiscount)
        {
            var ps = _priceForSizeService.GetPriceForSize(product.Id);

            if (ps != null && ps.HasPriceForSize)
            {
                Int32 w = 0;
                Int32 h = 0;
                Int32 d = 0;

                var mappings = _productAttributeParser.ParseProductAttributeMappings(attributesXml);

                var bAttr = mappings.SingleOrDefault(m => m.ProductAttributeId == ps.WidthAttributeId);
                if (bAttr != null)
                {
                    w = _productAttributeParser.ParseValues(attributesXml, bAttr.Id).Select(s => Convert.ToInt32(s)).FirstOrDefault();
                }

                var hAttr = mappings.SingleOrDefault(m => m.ProductAttributeId == ps.HeightAttributeId);
                if (hAttr != null)
                {
                    h = _productAttributeParser.ParseValues(attributesXml, hAttr.Id).Select(s => Convert.ToInt32(s)).FirstOrDefault();
                }

                var dAttr = mappings.SingleOrDefault(m => m.ProductAttributeId == ps.DepthAttributeId);
                if (dAttr != null)
                {
                    d = _productAttributeParser.ParseValues(attributesXml, hAttr.Id).Select(s => Convert.ToInt32(s)).FirstOrDefault();
                }

                Decimal priceM1     = 0;
                Decimal priceM2     = 0;
                Decimal priceM3     = 0;
                Decimal priceBase   = 0;
                Decimal priceHeight = 0;
                Decimal priceDepth  = 0;

                var prices = _priceForSizeService.GetAttributesPrice(product.Id);
                foreach (var m in mappings)
                {
                    if (m.ProductAttributeId != ps.WidthAttributeId && m.ProductAttributeId != ps.HeightAttributeId)
                    {
                        var values = _productAttributeParser.ParseValues(attributesXml, m.Id);
                        foreach (var v in values)
                        {
                            Int32 id = 0;
                            if (Int32.TryParse(v, out id))
                            {
                                var price = (from p in prices
                                             where p.ProductAttributeValueId == id
                                             select p).FirstOrDefault();
                                if (price != null)
                                {
                                    priceM1     += price.PriceForM1.GetValueOrDefault();
                                    priceM2     += price.PriceForM2.GetValueOrDefault();
                                    priceM3     += price.PriceForM3.GetValueOrDefault();
                                    priceBase   += price.PriceForBaseLength.GetValueOrDefault();
                                    priceHeight += price.PriceForHeightLength.GetValueOrDefault();
                                    priceDepth  += price.PriceForDepthLength.GetValueOrDefault();
                                }
                            }
                        }
                    }
                }

                var per  = Convert.ToDecimal(w + h) * 2 / 100;
                var area = Convert.ToDecimal(w) / 100 * Convert.ToDecimal(h) / 100;
                var vol  = Convert.ToDecimal(w) / 100 * Convert.ToDecimal(h) / 100 * Convert.ToDecimal(d) / 100;

                if (ps.MinimumBillablePerimeter.HasValue && per < ps.MinimumBillablePerimeter.Value)
                {
                    per = ps.MinimumBillablePerimeter.Value;
                }

                if (ps.MinimumBillableArea.HasValue && area < ps.MinimumBillableArea.Value)
                {
                    area = ps.MinimumBillableArea.Value;
                }

                if (ps.MinimumBillableVolume.HasValue && vol < ps.MinimumBillableVolume.Value)
                {
                    vol = ps.MinimumBillableVolume.Value;
                }

                return(base.GetUnitPrice(product, customer, shoppingCartType, quantity, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, includeDiscounts, out discountAmount, out appliedDiscount) +
                       per * priceM1 +
                       area * priceM2 +
                       vol * priceM3 +
                       priceBase * w +
                       priceHeight * h +
                       priceDepth * d);
            }
            else
            {
                return(base.GetUnitPrice(product, customer, shoppingCartType, quantity, attributesXml, customerEnteredPrice, rentalStartDate, rentalEndDate, includeDiscounts, out discountAmount, out appliedDiscount));
            }
        }