public JsonResult SaveCcAttributes(int productId, int attributeId, int attributeOptionId, string attributeValue)
        {
            try
            {
                var specificationAttributes = _specificationAttributeService.GetProductSpecificationAttributes(productId);
                var prodSpecAttr            = specificationAttributes.FirstOrDefault(
                    x => x.SpecificationAttributeOption.SpecificationAttributeId == attributeId);
                if (prodSpecAttr == null)
                {
                    prodSpecAttr = new ProductSpecificationAttribute
                    {
                        AttributeType = SpecificationAttributeType.CustomText,
                        ProductId     = productId,
                        SpecificationAttributeOptionId = attributeOptionId,
                        DisplayOrder      = 0,
                        ShowOnProductPage = false,
                        AllowFiltering    = false,
                        CustomValue       = attributeValue,
                    };
                    _specificationAttributeService.InsertProductSpecificationAttribute(prodSpecAttr);
                }
                else
                {
                    prodSpecAttr.CustomValue       = attributeValue;
                    prodSpecAttr.ShowOnProductPage = false;
                    _specificationAttributeService.UpdateProductSpecificationAttribute(prodSpecAttr);
                }

                var productAttributeMappings = _productAttributeService.GetProductAttributeMappingsByProductId(productId);
                foreach (var attrId in _ccService.GetCcAttrIds())
                {
                    if (productAttributeMappings.All(map => map.ProductAttributeId != attrId))
                    {
                        _productAttributeService.InsertProductAttributeMapping(new ProductAttributeMapping
                        {
                            AttributeControlType = AttributeControlType.TextBox,
                            DefaultValue         = "",
                            DisplayOrder         = 100,
                            ProductId            = productId,
                            ProductAttributeId   = attrId
                        });
                    }
                }

                return(Json(new { status = "success" }));
            }
            catch (Exception ex)
            {
                return(Json(new { status = "error", message = ex.Message }));
            }
        }
Esempio n. 2
0
        public IActionResult CreateProductSpecificationAttribute([ModelBinder(typeof(JsonModelBinder <ProductSpecificationAttributeDto>))] Delta <ProductSpecificationAttributeDto> productSpecificaitonAttributeDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            // Inserting the new product
            var productSpecificationAttribute = new ProductSpecificationAttribute();

            productSpecificaitonAttributeDelta.Merge(productSpecificationAttribute);

            _specificationAttributeService.InsertProductSpecificationAttribute(productSpecificationAttribute);

            CustomerActivityService.InsertActivity("AddNewProductSpecificationAttribute", productSpecificationAttribute.Id.ToString());

            // Preparing the result dto of the new product
            var productSpecificationAttributeDto = _dtoHelper.PrepareProductSpecificationAttributeDto(productSpecificationAttribute);

            var productSpecificationAttributesRootObjectDto = new ProductSpecificationAttributesRootObjectDto();

            productSpecificationAttributesRootObjectDto.ProductSpecificationAttributes.Add(productSpecificationAttributeDto);

            var json = JsonFieldsSerializer.Serialize(productSpecificationAttributesRootObjectDto, string.Empty);

            return(new RawJsonActionResult(json));
        }
        public ActionResult ProductTabPost(int id, string ArtistName)
        {
            var product = _productService.GetProductById(id);

            if (product != null)
            {
                // _genericAttributeService.SaveAttribute<string>(product, ProductArtistAttributeNames.ArtistName, ArtistName, _storeContext.CurrentStore.Id);

                var artistAttr = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "Artist").FirstOrDefault();
                if (artistAttr != null)
                {
                    var value = artistAttr.SpecificationAttributeOptions.Where(x => x.Name == ArtistName).FirstOrDefault();
                    if (value != null)
                    {
                        ProductSpecificationAttribute psA = new ProductSpecificationAttribute();
                        psA.SpecificationAttributeOption = value;
                        psA.ProductId         = product.Id;
                        psA.AllowFiltering    = true;
                        psA.AttributeType     = SpecificationAttributeType.Option;
                        psA.ShowOnProductPage = true;
                        _specificationAttributeService.InsertProductSpecificationAttribute(psA);
                    }
                    else
                    {
                        value = new SpecificationAttributeOption
                        {
                            Name = ArtistName,
                            SpecificationAttributeId = artistAttr.Id
                        };
                        _specificationAttributeService.InsertSpecificationAttributeOption(value);

                        ProductSpecificationAttribute psA = new ProductSpecificationAttribute();
                        psA.SpecificationAttributeOption = value;
                        psA.ProductId         = product.Id;
                        psA.AllowFiltering    = true;
                        psA.AttributeType     = SpecificationAttributeType.Option;
                        psA.ShowOnProductPage = true;
                        _specificationAttributeService.InsertProductSpecificationAttribute(psA);
                    }
                }
            }

            return(Content(ArtistName));
        }
        private void ProductSpecificationAttributeOptionMapping(Product productFromBase,
                                                                ProductSpecification productSpecificationAttribute, bool allowFilter)
        {
            var newProductSpecificationAttribute = new ProductSpecificationAttribute();

            newProductSpecificationAttribute.ProductId = productFromBase.Id;
            newProductSpecificationAttribute.SpecificationAttributeOptionId = productSpecificationAttribute.OptionId;
            newProductSpecificationAttribute.AllowFiltering    = allowFilter;
            newProductSpecificationAttribute.ShowOnProductPage = true;
            _specificationAttributeService.InsertProductSpecificationAttribute(newProductSpecificationAttribute);
        }
Esempio n. 5
0
 /// <summary>
 /// Copy product specifications
 /// </summary>
 /// <param name="product">Product</param>
 /// <param name="productCopy">New product</param>
 protected virtual void CopyProductSpecifications(Product product, Product productCopy)
 {
     foreach (var productSpecificationAttribute in _specificationAttributeService.GetProductSpecificationAttributes(product.Id))
     {
         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);
     }
 }
Esempio n. 6
0
        public virtual async Task InsertProductSpecification(ProductDto product, ProductSpecificationAttributeDto model)
        {
            //we allow filtering only for "Option" attribute type
            if (model.AttributeType != SpecificationAttributeType.Option)
            {
                model.AllowFiltering = false;
                model.SpecificationAttributeOptionId = null;
            }

            var psa = new ProductSpecificationAttribute
            {
                AttributeTypeId = (int)model.AttributeType,
                SpecificationAttributeOptionId = model.SpecificationAttributeOptionId,
                SpecificationAttributeId       = model.SpecificationAttributeId,
                ProductId         = product.Id,
                CustomValue       = model.CustomValue,
                AllowFiltering    = model.AllowFiltering,
                ShowOnProductPage = model.ShowOnProductPage,
                DisplayOrder      = model.DisplayOrder,
            };
            await _specificationAttributeService.InsertProductSpecificationAttribute(psa);
        }
        public async Task <bool> Handle(AddProductSpecificationCommand request, CancellationToken cancellationToken)
        {
            //we allow filtering only for "Option" attribute type
            if (request.Model.AttributeType != SpecificationAttributeType.Option)
            {
                request.Model.AllowFiltering = false;
                request.Model.SpecificationAttributeOptionId = null;
            }

            var psa = new ProductSpecificationAttribute {
                AttributeTypeId = (int)request.Model.AttributeType,
                SpecificationAttributeOptionId = request.Model.SpecificationAttributeOptionId,
                SpecificationAttributeId       = request.Model.SpecificationAttributeId,
                ProductId         = request.Product.Id,
                CustomValue       = request.Model.CustomValue,
                AllowFiltering    = request.Model.AllowFiltering,
                ShowOnProductPage = request.Model.ShowOnProductPage,
                DisplayOrder      = request.Model.DisplayOrder,
            };
            await _specificationAttributeService.InsertProductSpecificationAttribute(psa);

            return(true);
        }
        /// <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);
        }
Esempio n. 9
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product</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 entity</returns>
        public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

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

            Product productCopy = null;
            var     utcNow      = DateTime.UtcNow;

            // 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.GetValueOrDefault());
                    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
            productCopy = new Product()
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                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,
                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,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                IsEsd                            = product.IsEsd,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                ManageInventoryMethod            = product.ManageInventoryMethod,
                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,
                DisableBuyButton                 = product.DisableBuyButton,
                DisableWishlistButton            = product.DisableWishlistButton,
                AvailableForPreOrder             = product.AvailableForPreOrder,
                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,
                LowestAttributeCombinationPrice  = product.LowestAttributeCombinationPrice,
                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                     = utcNow,
                UpdatedOnUtc                     = utcNow,
                DeliveryTimeId                   = product.DeliveryTimeId,
                QuantityUnitId                   = product.QuantityUnitId,
                BasePriceEnabled                 = product.BasePriceEnabled,
                BasePriceMeasureUnit             = product.BasePriceMeasureUnit,
                BasePriceAmount                  = product.BasePriceAmount,
                BasePriceBaseAmount              = product.BasePriceBaseAmount,
                BundleTitleText                  = product.BundleTitleText,
                BundlePerItemShipping            = product.BundlePerItemShipping,
                BundlePerItemPricing             = product.BundlePerItemPricing,
                BundlePerItemShoppingCart        = product.BundlePerItemShoppingCart
            };

            _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);
                }

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

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

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

            // 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,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    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 productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductId(product.Id))
            {
                var productVariantAttributeCopy = new ProductVariantAttribute()
                {
                    ProductId              = productCopy.Id,
                    ProductAttributeId     = productVariantAttribute.ProductAttributeId,
                    TextPrompt             = productVariantAttribute.TextPrompt,
                    IsRequired             = productVariantAttribute.IsRequired,
                    AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                    DisplayOrder           = productVariantAttribute.DisplayOrder
                };
                _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id);

                // product variant attribute values
                var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id);
                foreach (var productVariantAttributeValue in productVariantAttributeValues)
                {
                    var pvavCopy = new ProductVariantAttributeValue()
                    {
                        ProductVariantAttributeId = productVariantAttributeCopy.Id,
                        Name             = productVariantAttributeValue.Name,
                        ColorSquaresRgb  = productVariantAttributeValue.ColorSquaresRgb,
                        PriceAdjustment  = productVariantAttributeValue.PriceAdjustment,
                        WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                        IsPreSelected    = productVariantAttributeValue.IsPreSelected,
                        DisplayOrder     = productVariantAttributeValue.DisplayOrder,
                        ValueTypeId      = productVariantAttributeValue.ValueTypeId,
                        LinkedProductId  = productVariantAttributeValue.LinkedProductId,
                        Quantity         = productVariantAttributeValue.Quantity,
                    };
                    _productAttributeService.InsertProductVariantAttributeValue(pvavCopy);

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

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

            // attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml = "";
                var    parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml);
                foreach (var oldPva in parsedProductVariantAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldPva.Id))
                    {
                        int newPvaId = associatedAttributes[oldPva.Id];
                        var newPva   = _productAttributeService.GetProductVariantAttributeById(newPvaId);
                        if (newPva != null)
                        {
                            var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id);
                            foreach (var oldPvaValueStr in oldPvaValuesStr)
                            {
                                if (newPva.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldPvaValue = int.Parse(oldPvaValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldPvaValue))
                                    {
                                        int newPvavId = associatedAttributeValues[oldPvaValue];
                                        var newPvav   = _productAttributeService.GetProductVariantAttributeValueById(newPvavId);
                                        if (newPvav != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newPva, newPvav.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newPva, oldPvaValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductVariantAttributeCombination()
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,

                    // SmartStore extension
                    Sku  = combination.Sku,
                    Gtin = combination.Gtin,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Price = combination.Price,
                    AssignedPictureIds = copyImages ? combination.AssignedPictureIds : null,
                    Length             = combination.Length,
                    Width               = combination.Width,
                    Height              = combination.Height,
                    BasePriceAmount     = combination.BasePriceAmount,
                    BasePriceBaseAmount = combination.BasePriceBaseAmount,
                    DeliveryTimeId      = combination.DeliveryTimeId,
                    QuantityUnitId      = combination.QuantityUnitId,
                    IsActive            = combination.IsActive
                                          //IsDefaultCombination = combination.IsDefaultCombination
                };
                _productAttributeService.InsertProductVariantAttributeCombination(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.UpdateLowestAttributeCombinationPriceProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);

            // associated products
            if (copyAssociatedProducts && product.ProductType != ProductType.BundledProduct)
            {
                var searchContext = new ProductSearchContext()
                {
                    ParentGroupedProductId = product.Id,
                    PageSize   = int.MaxValue,
                    ShowHidden = true
                };

                string copyOf             = _localizationService.GetResource("Admin.Common.CopyOf");
                var    associatedProducts = _productService.SearchProducts(searchContext);

                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("{0} {1}", copyOf, associatedProduct.Name), isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;

                    _productService.UpdateProduct(productCopy);
                }
            }

            // bundled products
            var bundledItems = _productService.GetBundleItems(product.Id, true);

            foreach (var bundleItem in bundledItems)
            {
                var newBundleItem = bundleItem.Item.Clone();
                newBundleItem.BundleProductId = productCopy.Id;
                newBundleItem.CreatedOnUtc    = utcNow;
                newBundleItem.UpdatedOnUtc    = utcNow;

                _productService.InsertBundleItem(newBundleItem);

                foreach (var itemFilter in bundleItem.Item.AttributeFilters)
                {
                    var newItemFilter = itemFilter.Clone();
                    newItemFilter.BundleItemId = newBundleItem.Id;

                    _productAttributeService.InsertProductBundleItemAttributeFilter(newItemFilter);
                }
            }

            return(productCopy);
        }
Esempio n. 10
0
        /// <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>
        /// <returns>Product copy</returns>
        public virtual Product CopyProduct(Product product, string newName, bool isPublished, bool copyImages)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

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


            Product productCopy = null;

            //uncomment this line to support transactions
            //using (var scope = new System.Transactions.TransactionScope())
            {
                // product
                productCopy = new Product()
                {
                    Name                 = newName,
                    ShortDescription     = product.ShortDescription,
                    FullDescription      = product.FullDescription,
                    ProductTemplateId    = product.ProductTemplateId,
                    AdminComment         = product.AdminComment,
                    ShowOnHomePage       = product.ShowOnHomePage,
                    MetaKeywords         = product.MetaKeywords,
                    MetaDescription      = product.MetaDescription,
                    MetaTitle            = product.MetaTitle,
                    AllowCustomerReviews = product.AllowCustomerReviews,
                    LimitedToStores      = product.LimitedToStores,
                    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);
                }
                //ensure product is saved before updating totals
                _productService.UpdateProduct(product);
                foreach (var productTag in product.ProductTags)
                {
                    _productTagService.UpdateProductTagTotals(productTag);
                }

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

                // 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,
                        SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                        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 variants
                var productVariants = product.ProductVariants;
                foreach (var productVariant in productVariants)
                {
                    CopyProductVariant(productVariant, productCopy.Id, productVariant.Name, productVariant.Published, copyImages);
                }

                //uncomment this line to support transactions
                //scope.Complete();
            }

            return(productCopy);
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a copy of product with all depended data
        /// </summary>
        /// <param name="productId">The product identifier</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>
        /// <returns>Product entity</returns>
        public Product CopyProduct(int productId, string newName, bool isPublished, bool copyImages)
        {
            var product = _productService.GetProductById(productId);

            if (product == null)
            {
                throw new ArgumentException("No product found with the specified id", "productId");
            }

            Product productCopy = null;

            //uncomment this line to support transactions
            //using (var scope = new System.Transactions.TransactionScope())
            {
                // product
                productCopy = new Product()
                {
                    Name                 = newName,
                    ShortDescription     = product.ShortDescription,
                    FullDescription      = product.FullDescription,
                    ProductTemplateId    = product.ProductTemplateId,
                    AdminComment         = product.AdminComment,
                    ShowOnHomePage       = product.ShowOnHomePage,
                    MetaKeywords         = product.MetaKeywords,
                    MetaDescription      = product.MetaDescription,
                    MetaTitle            = product.MetaTitle,
                    AllowCustomerReviews = product.AllowCustomerReviews,
                    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);
                }
                //ensure product is saved before updating totals
                _productService.UpdateProduct(product);
                foreach (var productTag in product.ProductTags)
                {
                    _productTagService.UpdateProductTagTotals(productTag);
                }

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

                // 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,
                        SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                        AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                        ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                        DisplayOrder      = productSpecificationAttribute.DisplayOrder
                    };
                    _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
                }

                // product variants
                var productVariants = product.ProductVariants;
                foreach (var productVariant in productVariants)
                {
                    // product variant picture
                    int pictureId = 0;
                    if (copyImages)
                    {
                        var picture = _pictureService.GetPictureById(productVariant.PictureId);
                        if (picture != null)
                        {
                            var pictureCopy = _pictureService.InsertPicture(
                                _pictureService.LoadPictureBinary(picture),
                                picture.MimeType,
                                _pictureService.GetPictureSeName(productVariant.Name),
                                true);
                            pictureId = pictureCopy.Id;
                        }
                    }

                    // product variant download & sample download
                    int downloadId       = productVariant.DownloadId;
                    int sampleDownloadId = productVariant.SampleDownloadId;
                    if (productVariant.IsDownload)
                    {
                        var download = _downloadService.GetDownloadById(productVariant.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 (productVariant.HasSampleDownload)
                        {
                            var sampleDownload = _downloadService.GetDownloadById(productVariant.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 variant
                    var productVariantCopy = new ProductVariant()
                    {
                        ProductId                 = productCopy.Id,
                        Name                      = productVariant.Name,
                        Sku                       = productVariant.Sku,
                        Description               = productVariant.Description,
                        AdminComment              = productVariant.AdminComment,
                        ManufacturerPartNumber    = productVariant.ManufacturerPartNumber,
                        Gtin                      = productVariant.Gtin,
                        IsGiftCard                = productVariant.IsGiftCard,
                        GiftCardType              = productVariant.GiftCardType,
                        RequireOtherProducts      = productVariant.RequireOtherProducts,
                        RequiredProductVariantIds = productVariant.RequiredProductVariantIds,
                        AutomaticallyAddRequiredProductVariants = productVariant.AutomaticallyAddRequiredProductVariants,
                        IsDownload                    = productVariant.IsDownload,
                        DownloadId                    = downloadId,
                        UnlimitedDownloads            = productVariant.UnlimitedDownloads,
                        MaxNumberOfDownloads          = productVariant.MaxNumberOfDownloads,
                        DownloadExpirationDays        = productVariant.DownloadExpirationDays,
                        DownloadActivationType        = productVariant.DownloadActivationType,
                        HasSampleDownload             = productVariant.HasSampleDownload,
                        SampleDownloadId              = sampleDownloadId,
                        HasUserAgreement              = productVariant.HasUserAgreement,
                        UserAgreementText             = productVariant.UserAgreementText,
                        IsRecurring                   = productVariant.IsRecurring,
                        RecurringCycleLength          = productVariant.RecurringCycleLength,
                        RecurringCyclePeriod          = productVariant.RecurringCyclePeriod,
                        RecurringTotalCycles          = productVariant.RecurringTotalCycles,
                        IsShipEnabled                 = productVariant.IsShipEnabled,
                        IsFreeShipping                = productVariant.IsFreeShipping,
                        AdditionalShippingCharge      = productVariant.AdditionalShippingCharge,
                        IsTaxExempt                   = productVariant.IsTaxExempt,
                        TaxCategoryId                 = productVariant.TaxCategoryId,
                        ManageInventoryMethod         = productVariant.ManageInventoryMethod,
                        StockQuantity                 = productVariant.StockQuantity,
                        DisplayStockAvailability      = productVariant.DisplayStockAvailability,
                        DisplayStockQuantity          = productVariant.DisplayStockQuantity,
                        MinStockQuantity              = productVariant.MinStockQuantity,
                        LowStockActivityId            = productVariant.LowStockActivityId,
                        NotifyAdminForQuantityBelow   = productVariant.NotifyAdminForQuantityBelow,
                        BackorderMode                 = productVariant.BackorderMode,
                        AllowBackInStockSubscriptions = productVariant.AllowBackInStockSubscriptions,
                        OrderMinimumQuantity          = productVariant.OrderMinimumQuantity,
                        OrderMaximumQuantity          = productVariant.OrderMaximumQuantity,
                        AllowedQuantities             = productVariant.AllowedQuantities,
                        DisableBuyButton              = productVariant.DisableBuyButton,
                        DisableWishlistButton         = productVariant.DisableWishlistButton,
                        CallForPrice                  = productVariant.CallForPrice,
                        Price        = productVariant.Price,
                        OldPrice     = productVariant.OldPrice,
                        ProductCost  = productVariant.ProductCost,
                        SpecialPrice = productVariant.SpecialPrice,
                        SpecialPriceStartDateTimeUtc = productVariant.SpecialPriceStartDateTimeUtc,
                        SpecialPriceEndDateTimeUtc   = productVariant.SpecialPriceEndDateTimeUtc,
                        CustomerEntersPrice          = productVariant.CustomerEntersPrice,
                        MinimumCustomerEnteredPrice  = productVariant.MinimumCustomerEnteredPrice,
                        MaximumCustomerEnteredPrice  = productVariant.MaximumCustomerEnteredPrice,
                        Weight    = productVariant.Weight,
                        Length    = productVariant.Length,
                        Width     = productVariant.Width,
                        Height    = productVariant.Height,
                        PictureId = pictureId,
                        AvailableStartDateTimeUtc = productVariant.AvailableStartDateTimeUtc,
                        AvailableEndDateTimeUtc   = productVariant.AvailableEndDateTimeUtc,
                        Published    = productVariant.Published,
                        Deleted      = productVariant.Deleted,
                        DisplayOrder = productVariant.DisplayOrder,
                        CreatedOnUtc = DateTime.UtcNow,
                        UpdatedOnUtc = DateTime.UtcNow
                    };

                    _productService.InsertProductVariant(productVariantCopy);

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

                        var description = productVariant.GetLocalized(x => x.Description, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(description))
                        {
                            _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Description, description, lang.Id);
                        }
                    }

                    // product variant <-> attributes mappings
                    var associatedAttributes      = new Dictionary <int, int>();
                    var associatedAttributeValues = new Dictionary <int, int>();
                    foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductVariantId(productVariant.Id))
                    {
                        var productVariantAttributeCopy = new ProductVariantAttribute()
                        {
                            ProductVariantId       = productVariantCopy.Id,
                            ProductAttributeId     = productVariantAttribute.ProductAttributeId,
                            TextPrompt             = productVariantAttribute.TextPrompt,
                            IsRequired             = productVariantAttribute.IsRequired,
                            AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId,
                            DisplayOrder           = productVariantAttribute.DisplayOrder
                        };
                        _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy);
                        //save associated value (used for combinations copying)
                        associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id);

                        // product variant attribute values
                        var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id);
                        foreach (var productVariantAttributeValue in productVariantAttributeValues)
                        {
                            var pvavCopy = new ProductVariantAttributeValue()
                            {
                                ProductVariantAttributeId = productVariantAttributeCopy.Id,
                                Name             = productVariantAttributeValue.Name,
                                PriceAdjustment  = productVariantAttributeValue.PriceAdjustment,
                                WeightAdjustment = productVariantAttributeValue.WeightAdjustment,
                                IsPreSelected    = productVariantAttributeValue.IsPreSelected,
                                DisplayOrder     = productVariantAttributeValue.DisplayOrder
                            };
                            _productAttributeService.InsertProductVariantAttributeValue(pvavCopy);

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

                            //localization
                            foreach (var lang in languages)
                            {
                                var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                                if (!String.IsNullOrEmpty(name))
                                {
                                    _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id);
                                }
                            }
                        }
                    }
                    foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(productVariant.Id))
                    {
                        //generate new AttributesXml according to new value IDs
                        string newAttributesXml = "";
                        var    parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml);
                        foreach (var oldPva in parsedProductVariantAttributes)
                        {
                            if (associatedAttributes.ContainsKey(oldPva.Id))
                            {
                                int newPvaId = associatedAttributes[oldPva.Id];
                                var newPva   = _productAttributeService.GetProductVariantAttributeById(newPvaId);
                                if (newPva != null)
                                {
                                    var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id);
                                    foreach (var oldPvaValueStr in oldPvaValuesStr)
                                    {
                                        if (newPva.ShouldHaveValues())
                                        {
                                            //attribute values
                                            int oldPvaValue = int.Parse(oldPvaValueStr);
                                            if (associatedAttributeValues.ContainsKey(oldPvaValue))
                                            {
                                                int newPvavId = associatedAttributeValues[oldPvaValue];
                                                var newPvav   = _productAttributeService.GetProductVariantAttributeValueById(newPvavId);
                                                if (newPvav != null)
                                                {
                                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                                   newPva, newPvav.Id.ToString());
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //just a text
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newPva, oldPvaValueStr);
                                        }
                                    }
                                }
                            }
                        }
                        var combinationCopy = new ProductVariantAttributeCombination()
                        {
                            ProductVariantId      = productVariantCopy.Id,
                            AttributesXml         = newAttributesXml,
                            StockQuantity         = combination.StockQuantity,
                            AllowOutOfStockOrders = combination.AllowOutOfStockOrders
                        };
                        _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy);
                    }

                    // product variant tier prices
                    foreach (var tierPrice in productVariant.TierPrices)
                    {
                        _productService.InsertTierPrice(
                            new TierPrice()
                        {
                            ProductVariantId = productVariantCopy.Id,
                            CustomerRoleId   = tierPrice.CustomerRoleId,
                            Quantity         = tierPrice.Quantity,
                            Price            = tierPrice.Price
                        });
                    }

                    // product variant <-> discounts mapping
                    foreach (var discount in productVariant.AppliedDiscounts)
                    {
                        productVariantCopy.AppliedDiscounts.Add(discount);
                        _productService.UpdateProductVariant(productVariantCopy);
                    }


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

                //uncomment this line to support transactions
                //scope.Complete();
            }

            return(productCopy);
        }
Esempio n. 12
0
        private void CreateExampleProducts(CcSettings settings)
        {
            var product = new Product
            {
                ProductType       = ProductType.SimpleProduct,
                ProductTemplateId = _productTemplateService.GetAllProductTemplates().First().Id,
                Name = "Business Card",
                VisibleIndividually  = true,
                ShowOnHomePage       = true,
                AllowCustomerReviews = true,
                Price        = 10,
                Published    = true,
                CreatedOnUtc = DateTime.Now,
                UpdatedOnUtc = DateTime.Now,
                AvailableStartDateTimeUtc = new DateTime(2015, 6, 1),
                OrderMaximumQuantity      = 100,
                OrderMinimumQuantity      = 1
            };

            _productService.InsertProduct(product);
            if (settings.SampleProducts == null)
            {
                settings.SampleProducts = new List <int>();
            }
            settings.SampleProducts.Add(product.Id);

            var productDefinition = new ProductSpecificationAttribute
            {
                AllowFiltering = true,
                AttributeType  = SpecificationAttributeType.CustomText,
                SpecificationAttributeOptionId = settings.EditorDefinitionSpecificationOptionId,
                CustomValue       = @"Default editor",
                DisplayOrder      = 0,
                ProductId         = product.Id,
                ShowOnProductPage = false
            };

            _specificationAttributeService.InsertProductSpecificationAttribute(productDefinition);

            var editorConfiguration = new ProductSpecificationAttribute
            {
                AllowFiltering = true,
                AttributeType  = SpecificationAttributeType.CustomText,
                SpecificationAttributeOptionId = settings.EditorConfigurationSpecificationOptionId,
                CustomValue       = @"Default config",
                DisplayOrder      = 0,
                ProductId         = product.Id,
                ShowOnProductPage = false
            };

            _specificationAttributeService.InsertProductSpecificationAttribute(editorConfiguration);

            #region product attribute mappings
            _productAttributeService.InsertProductAttributeMapping(new ProductAttributeMapping
            {
                AttributeControlType = AttributeControlType.TextBox,
                DefaultValue         = "",
                DisplayOrder         = 100,
                ProductId            = product.Id,
                ProductAttributeId   = settings.CcIdAttributeId
            });
            #endregion

            _urlRecordService.SaveSlug(product, product.ValidateSeName(product.Name, product.Name, true), 0);
        }
Esempio n. 13
0
        public async Task <ActionResult> CallApi(ConfigurationModel model)
        {
            var storeScope      = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var mappingSettings = _settingService.LoadSetting <ProductMappingSettings>(storeScope);

            var tokenebay = EbayExtensions.GetToken();

            var categoryWorldBuy = _categoryMappingRecord.Table.Where(u => u.CategoryId == model.CategoryId && u.SourceId == (int)Source.Ebay).ToList();

            if (categoryWorldBuy != null)
            {
                foreach (var cateIds in categoryWorldBuy)
                {
                    var clientapi1 = new HttpClient();
                    clientapi1.BaseAddress = new Uri("https://api.ebay.com/");
                    clientapi1.DefaultRequestHeaders.Clear();
                    clientapi1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    clientapi1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay);
                    clientapi1.Timeout = TimeSpan.FromMinutes(60);

                    var getCategoryId = _affiliateEbayService.Get(cateIds.CategorySourceId).EbayId.ToString();

                    string str = "buy/browse/v1/item_summary/search?limit=200&category_ids=" + getCategoryId;
                    if (!string.IsNullOrEmpty(model.KeyWord))
                    {
                        str = str + "&q=" + model.KeyWord;
                    }

                    HttpResponseMessage Res1 = await clientapi1.GetAsync(str);

                    if (Res1.IsSuccessStatusCode)
                    {
                        var EmpResponse1 = Res1.Content.ReadAsStringAsync().Result;
                        var result1      = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse1);

                        int temp  = int.Parse(result1.total);
                        int value = 0;
                        while (temp > 0)
                        {
                            str = str + "&offset=" + value;
                            HttpResponseMessage Res2 = await clientapi1.GetAsync(str);

                            if (Res2.IsSuccessStatusCode)
                            {
                                var EmpResponse2 = Res2.Content.ReadAsStringAsync().Result;
                                var result2      = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse2);

                                if (result2.itemSummaries != null)
                                {
                                    foreach (var item in result2.itemSummaries)
                                    {
                                        var checkProduct = _affiliateEbayService.GetProductBySourceId(productSourceId: item.itemId, source: (int)Source.Ebay);
                                        if (checkProduct.Id == 0)
                                        {
                                            var clientapi = new HttpClient();
                                            clientapi.BaseAddress = new Uri("https://api.ebay.com/");
                                            clientapi.DefaultRequestHeaders.Clear();
                                            clientapi.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                                            clientapi.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay);
                                            clientapi.Timeout = TimeSpan.FromMinutes(60);

                                            HttpResponseMessage Res = await clientapi.GetAsync("buy/browse/v1/item/" + item.itemId);

                                            if (Res.IsSuccessStatusCode)
                                            {
                                                var EmpResponse = Res.Content.ReadAsStringAsync().Result;
                                                var result      = JsonConvert.DeserializeObject <ProductModelApi>(EmpResponse);

                                                if (result.price != null)
                                                {
                                                    var price   = Convert.ToDecimal(result.price.value);
                                                    var product = new Product();
                                                    product.Name = result.title;
                                                    var currencyService = EngineContext.Current.Resolve <ICurrencyService>();
                                                    product.Price = Round(currencyService.ConvertToPrimaryStoreCurrency(price * (1 + mappingSettings.AdditionalCostPercent / 100), currencyService.GetCurrencyByCode("USD")), -3);
                                                    //if(result.marketingPrice == null)
                                                    //{
                                                    //    product.OldPrice = 0;
                                                    //}
                                                    //else
                                                    //{
                                                    //    if(result.marketingPrice.originalPrice == null)
                                                    //        product.OldPrice = 0;
                                                    //    else
                                                    //        product.OldPrice = Convert.ToDecimal(result.marketingPrice.originalPrice.value);
                                                    //}
                                                    product.ShortDescription = result.shortDescription;
                                                    product.FullDescription  = result.description;

                                                    product.VisibleIndividually         = true;
                                                    product.AllowCustomerReviews        = true;
                                                    product.UnlimitedDownloads          = true;
                                                    product.MaxNumberOfDownloads        = 10;
                                                    product.RecurringCycleLength        = 100;
                                                    product.RecurringTotalCycles        = 10;
                                                    product.RentalPriceLength           = 1;
                                                    product.IsShipEnabled               = true;
                                                    product.NotifyAdminForQuantityBelow = 1;
                                                    product.StockQuantity               = 1000;
                                                    product.OrderMaximumQuantity        = 1000;
                                                    product.OrderMinimumQuantity        = 1;
                                                    product.CreatedOnUtc = DateTime.UtcNow;
                                                    product.UpdatedOnUtc = DateTime.UtcNow;
                                                    _productService.InsertProduct(product);

                                                    var productMapping = new ProductMapping();
                                                    productMapping.ProductSourceId   = item.itemId;
                                                    productMapping.ProductSourceLink = item.itemWebUrl;
                                                    productMapping.SourceId          = (int)Source.Ebay;
                                                    productMapping.ProductId         = product.Id;
                                                    productMapping.Price             = price;
                                                    _productMappingService.InsertProduct(productMapping);

                                                    // Thêm hình chính
                                                    var imageMain = result.image.imageUrl.Split('?')[0];
                                                    System.Drawing.Image imageKey = EbayExtensions.DownloadImage(imageMain);
                                                    if (imageKey != null)
                                                    {
                                                        var contentTypeMain         = "";
                                                        var vendorPictureBinaryMain = EbayExtensions.ImageToByte(imageKey);

                                                        var fileExtensionMain = Path.GetExtension(imageMain);
                                                        if (!String.IsNullOrEmpty(fileExtensionMain))
                                                        {
                                                            fileExtensionMain = fileExtensionMain.ToLowerInvariant();
                                                        }
                                                        if (String.IsNullOrEmpty(contentTypeMain))
                                                        {
                                                            switch (fileExtensionMain)
                                                            {
                                                            case ".bmp":
                                                                contentTypeMain = MimeTypes.ImageBmp;
                                                                break;

                                                            case ".gif":
                                                                contentTypeMain = MimeTypes.ImageGif;
                                                                break;

                                                            case ".jpeg":
                                                            case ".jpg":
                                                            case ".jpe":
                                                            case ".jfif":
                                                            case ".pjpeg":
                                                            case ".pjp":
                                                                contentTypeMain = MimeTypes.ImageJpeg;
                                                                break;

                                                            case ".png":
                                                                contentTypeMain = MimeTypes.ImagePng;
                                                                break;

                                                            case ".tiff":
                                                            case ".tif":
                                                                contentTypeMain = MimeTypes.ImageTiff;
                                                                break;

                                                            default:
                                                                break;
                                                            }
                                                        }
                                                        var pictureMain = _pictureService.InsertPicture(vendorPictureBinaryMain, contentTypeMain, null);
                                                        _productService.InsertProductPicture(new ProductPicture
                                                        {
                                                            PictureId    = pictureMain.Id,
                                                            ProductId    = product.Id,
                                                            DisplayOrder = 0,
                                                        });
                                                    }

                                                    int display = 1;
                                                    if (result.additionalImages != null)
                                                    {
                                                        foreach (var ite in result.additionalImages)
                                                        {
                                                            var ima = ite.imageUrl.Split('?')[0];
                                                            System.Drawing.Image image = EbayExtensions.DownloadImage(ima);
                                                            if (image != null)
                                                            {
                                                                var contentType         = "";
                                                                var vendorPictureBinary = EbayExtensions.ImageToByte(image);

                                                                var fileExtension = Path.GetExtension(ima);
                                                                if (!String.IsNullOrEmpty(fileExtension))
                                                                {
                                                                    fileExtension = fileExtension.ToLowerInvariant();
                                                                }
                                                                if (String.IsNullOrEmpty(contentType))
                                                                {
                                                                    switch (fileExtension)
                                                                    {
                                                                    case ".bmp":
                                                                        contentType = MimeTypes.ImageBmp;
                                                                        break;

                                                                    case ".gif":
                                                                        contentType = MimeTypes.ImageGif;
                                                                        break;

                                                                    case ".jpeg":
                                                                    case ".jpg":
                                                                    case ".jpe":
                                                                    case ".jfif":
                                                                    case ".pjpeg":
                                                                    case ".pjp":
                                                                        contentType = MimeTypes.ImageJpeg;
                                                                        break;

                                                                    case ".png":
                                                                        contentType = MimeTypes.ImagePng;
                                                                        break;

                                                                    case ".tiff":
                                                                    case ".tif":
                                                                        contentType = MimeTypes.ImageTiff;
                                                                        break;

                                                                    default:
                                                                        break;
                                                                    }
                                                                }
                                                                var picture = _pictureService.InsertPicture(vendorPictureBinary, contentType, null);
                                                                _productService.InsertProductPicture(new ProductPicture
                                                                {
                                                                    PictureId    = picture.Id,
                                                                    ProductId    = product.Id,
                                                                    DisplayOrder = display++,
                                                                });
                                                            }
                                                        }
                                                    }

                                                    //Product specification attributes
                                                    if (result.localizedAspects != null)
                                                    {
                                                        foreach (var attributes in result.localizedAspects)
                                                        {
                                                            var getAttribute                 = _affiliateEbayService.GetSpecificationAttributeByName(attributes.name);
                                                            var specificationAttribute       = new SpecificationAttribute();
                                                            var specificationAttributeOption = new SpecificationAttributeOption();
                                                            if (getAttribute == null)
                                                            {
                                                                specificationAttribute.Name         = attributes.name;
                                                                specificationAttribute.DisplayOrder = 0;
                                                                _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute);

                                                                specificationAttributeOption.DisplayOrder             = 0;
                                                                specificationAttributeOption.ColorSquaresRgb          = null;
                                                                specificationAttributeOption.Name                     = attributes.value;
                                                                specificationAttributeOption.SpecificationAttributeId = specificationAttribute.Id;
                                                                _specificationAttributeService.InsertSpecificationAttributeOption(specificationAttributeOption);
                                                            }

                                                            var productSpecificationAttribute = new ProductSpecificationAttribute();
                                                            productSpecificationAttribute.AttributeTypeId = (int)SpecificationAttributeType.CustomText;
                                                            if (getAttribute == null)
                                                            {
                                                                productSpecificationAttribute.SpecificationAttributeOptionId = specificationAttributeOption.Id;
                                                            }
                                                            else
                                                            {
                                                                var options = _specificationAttributeService.GetSpecificationAttributeOptionsBySpecificationAttribute(getAttribute.Id);
                                                                productSpecificationAttribute.SpecificationAttributeOptionId = options.FirstOrDefault().Id;
                                                            }
                                                            productSpecificationAttribute.ProductId         = product.Id;
                                                            productSpecificationAttribute.CustomValue       = attributes.value;
                                                            productSpecificationAttribute.AllowFiltering    = false;
                                                            productSpecificationAttribute.ShowOnProductPage = true;
                                                            productSpecificationAttribute.DisplayOrder      = 1;
                                                            _specificationAttributeService.InsertProductSpecificationAttribute(productSpecificationAttribute);
                                                        }
                                                    }

                                                    //categories
                                                    SaveCategoryMappings(product, new List <int>()
                                                    {
                                                        model.CategoryId
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            value = value + 200;
                            temp  = temp - 200;
                        }
                    }
                }
                SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Added"));
            }
            else
            {
                ErrorNotification(_localizationService.GetResource("Plugins.AffiliateEbay.CallApi.Error"));
            }

            return(CallApi());
        }
Esempio n. 14
0
        internal static void Import(КоммерческаяИнформация source,
                                    ICategoryService categoryService,
                                    ISpecificationAttributeService specificationAttributeService,
                                    IManufacturerService manufacturerService,
                                    IProductService productService,
                                    IUrlRecordService urlRecordService,
                                    IPictureService pictureService,
                                    List <Category> categories,
                                    Dictionary <string, int> categoryMappings,
                                    List <SpecificationAttribute> attributes,
                                    Dictionary <string, int> attributesMappings,
                                    List <Manufacturer> manufacturers,
                                    Dictionary <string, int> manufacturersMappings,
                                    string mappingsFile,
                                    string logFile,
                                    ImportCatalogSettings importSettings)

        {
            logFile.Log("Начало импорта товаров");
            var stats = new[] { 0, 0 };

            var mappings = File.Exists(mappingsFile)
                ? JsonConvert.DeserializeObject <Dictionary <string, int> >(File.ReadAllText(mappingsFile))
                : new Dictionary <string, int>();

            foreach (var prod in source.Каталог.Товары)
            {
                try
                {
                    var product = mappings.ContainsKey(prod.Ид)
                        ? productService.GetProductById(mappings[prod.Ид])
                        : null;

                    var deleted = prod.Статус == "Удален";
                    if (product == null)
                    {
                        product = new Product
                        {
                            CreatedOnUtc        = DateTime.Now,
                            UpdatedOnUtc        = DateTime.Now,
                            ProductType         = ProductType.SimpleProduct,
                            ProductTemplateId   = 1,
                            VisibleIndividually = true,
                            Name                 = prod.Наименование,
                            Sku                  = prod.Артикул,
                            ShortDescription     = prod.Описание,
                            FullDescription      = prod.Описание,
                            AllowCustomerReviews = true,
                            Deleted              = deleted,
                            Published            = !deleted,
                            OrderMinimumQuantity = 1,
                            OrderMaximumQuantity = 10000
                        };
                        productService.InsertProduct(product);
                        var seName = product.ValidateSeName(null, product.Name, true);
                        urlRecordService.SaveSlug(product, seName, 0);
                        //logFile.Log($"Новый товар {product.Name} ({product.Id}): {prod.Ид}");
                        stats[0]++;
                    }
                    else
                    {
                        if (!importSettings.UpdateExisting)
                        {
                            //logFile.Log($"Пропущен товар {product.Name} ({product.Id}): {prod.Ид}");
                            stats[1]++;
                            continue;
                        }
                        product.UpdatedOnUtc = DateTime.Now;
                        product.Deleted      = deleted;
                        product.Published    = !deleted;
                        productService.UpdateProduct(product);
                        //logFile.Log($"Обновлен товар {product.Name} ({product.Id}): {prod.Ид}");
                        stats[1]++;
                    }
                    mappings[prod.Ид] = product.Id;

                    if (importSettings.OverwriteManufacturers)
                    {
                        foreach (var manufacturer in product.ProductManufacturers.ToList())
                        {
                            manufacturerService.DeleteProductManufacturer(manufacturer);
                        }
                    }
                    if (prod.Изготовитель != null && manufacturersMappings.ContainsKey(prod.Изготовитель.Ид))
                    {
                        var manufacturerId = manufacturersMappings[prod.Изготовитель.Ид];
                        var manufacturer   = product.ProductManufacturers.FirstOrDefault(m => m.ManufacturerId == manufacturerId);
                        if (manufacturer == null)
                        {
                            manufacturer = new ProductManufacturer
                            {
                                ProductId      = product.Id,
                                ManufacturerId = manufacturerId
                            };
                            manufacturerService.InsertProductManufacturer(manufacturer);
                            product.ProductManufacturers.Add(manufacturer);
                        }
                    }

                    if (importSettings.OverwriteCategories)
                    {
                        foreach (var category in product.ProductCategories.ToList())
                        {
                            categoryService.DeleteProductCategory(category);
                        }
                    }
                    if (prod.Группы != null && categoryMappings.ContainsKey(prod.Группы.Ид))
                    {
                        var categoryId = categoryMappings[prod.Группы.Ид];
                        var category   = product.ProductCategories.FirstOrDefault(c => c.CategoryId == categoryId);
                        if (category == null)
                        {
                            category = new ProductCategory
                            {
                                ProductId  = product.Id,
                                CategoryId = categoryId
                            };
                            categoryService.InsertProductCategory(category);
                            product.ProductCategories.Add(category);
                        }
                    }

                    if (importSettings.ImportSpecificationAttributes && prod.ЗначенияСвойств != null)
                    {
                        foreach (var attr in prod.ЗначенияСвойств)
                        {
                            if (attributesMappings.ContainsKey(attr.Ид))
                            {
                                var emptyOptionKey = $"{attr.Ид}.";
                                if (attributesMappings.ContainsKey(emptyOptionKey))
                                {
                                    var option = product.ProductSpecificationAttributes
                                                 .FirstOrDefault(a => a.SpecificationAttributeOptionId == attributesMappings[emptyOptionKey]);
                                    if (option == null)
                                    {
                                        option = new ProductSpecificationAttribute
                                        {
                                            ProductId         = product.Id,
                                            ShowOnProductPage = true,
                                            AllowFiltering    = false,
                                            SpecificationAttributeOptionId = attributesMappings[emptyOptionKey],
                                            AttributeType = SpecificationAttributeType.CustomText,
                                            CustomValue   = attr.Значение
                                        };
                                        specificationAttributeService.InsertProductSpecificationAttribute(option);
                                        product.ProductSpecificationAttributes.Add(option);
                                    }
                                    else if (option.CustomValue != attr.Значение)
                                    {
                                        option.CustomValue = attr.Значение;
                                        specificationAttributeService.UpdateProductSpecificationAttribute(option);
                                    }
                                }
                                else
                                {
                                    var optionKey = $"{attr.Ид}.{attr.Значение}";

                                    var option = product.ProductSpecificationAttributes
                                                 .FirstOrDefault(o => o.SpecificationAttributeOptionId == attributesMappings[optionKey]);
                                    if (option == null)
                                    {
                                        var attribute = attributes.FirstOrDefault(a => a.Id == attributesMappings[attr.Ид]);
                                        var optionIds = attribute.SpecificationAttributeOptions.Select(o => o.Id);
                                        var options   = product.ProductSpecificationAttributes
                                                        .Where(a => optionIds.Contains(a.SpecificationAttributeOptionId)).ToList();
                                        if (options != null && options.Count > 0)
                                        {
                                            foreach (var opt in options)
                                            {
                                                product.ProductSpecificationAttributes.Remove(opt);
                                                specificationAttributeService.DeleteProductSpecificationAttribute(opt);
                                            }
                                        }

                                        option = new ProductSpecificationAttribute
                                        {
                                            ProductId         = product.Id,
                                            ShowOnProductPage = true,
                                            AllowFiltering    = true,
                                            SpecificationAttributeOptionId = attributesMappings[optionKey],
                                            AttributeType = SpecificationAttributeType.Option
                                        };
                                        specificationAttributeService.InsertProductSpecificationAttribute(option);
                                        product.ProductSpecificationAttributes.Add(option);
                                    }
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(prod.Картинка))
                    {
                        // todo: compare with existing images
                        var picturePath = HttpContext.Current.Request.MapPath($"~/Content/{prod.Картинка}");
                        var picture     = LoadPicture(pictureService, picturePath, product.Name);
                        if (picture != null)
                        {
                            product.ProductPictures.Add(new ProductPicture
                            {
                                DisplayOrder = 1,
                                PictureId    = picture.Id,
                                ProductId    = product.Id
                            });
                        }
                    }

                    File.WriteAllText(mappingsFile, JsonConvert.SerializeObject(mappings, Formatting.Indented), Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    logFile.Log($"Ошибка при обработке товара {prod.Ид} ({prod.Наименование}): {ex}");
                }
            }

            logFile.Log($"Импорт товаров завершен. Добавлено: {stats[0]}. Обновлено: {stats[1]}.");
        }