Exemple #1
0
        protected virtual void SaveStoreMappings(NewsItem newsItem, NewsItemModel model)
        {
            newsItem.LimitedToStores = model.SelectedStoreIds.Any();

            var existingStoreMappings = _storeMappingService.GetStoreMappings(newsItem);
            var allStores             = _storeService.GetAllStores();

            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds.Contains(store.Id))
                {
                    //new store
                    if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                    {
                        _storeMappingService.InsertStoreMapping(newsItem, store.Id);
                    }
                }
                else
                {
                    //remove store
                    var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
                    if (storeMappingToDelete != null)
                    {
                        _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
                    }
                }
            }
        }
Exemple #2
0
        protected virtual void SaveStoreMappings(CheckoutAttribute checkoutAttribute, CheckoutAttributeModel model)
        {
            var existingStoreMappings = _storeMappingService.GetStoreMappings(checkoutAttribute);
            var allStores             = _storeService.GetAllStores();

            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds != null && model.SelectedStoreIds.Contains(store.Id))
                {
                    //new store
                    if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                    {
                        _storeMappingService.InsertStoreMapping(checkoutAttribute, store.Id);
                    }
                }
                else
                {
                    //remove store
                    var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
                    if (storeMappingToDelete != null)
                    {
                        _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
                    }
                }
            }
        }
Exemple #3
0
        protected void SaveStoreMappings(MessageTemplate messageTemplate, MessageTemplateModel model)
        {
            var existingStoreMappings = _storeMappingService.GetStoreMappings(messageTemplate);
            var allStores             = _storeService.GetAllStores();

            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds != null && model.SelectedStoreIds.Contains(store.Id))
                {
                    //new role
                    if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                    {
                        _storeMappingService.InsertStoreMapping(messageTemplate, store.Id);
                    }
                }
                else
                {
                    //removed role
                    var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
                    if (storeMappingToDelete != null)
                    {
                        _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
                    }
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Create a copy of message template with all depended data
        /// </summary>
        /// <param name="messageTemplate">Message template</param>
        /// <returns>Message template copy</returns>
        public virtual MessageTemplate CopyMessageTemplate(MessageTemplate messageTemplate)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException("messageTemplate");
            }

            var mtCopy = new MessageTemplate()
            {
                Name = messageTemplate.Name,
                BccEmailAddresses = messageTemplate.BccEmailAddresses,
                Subject           = messageTemplate.Subject,
                Body            = messageTemplate.Body,
                IsActive        = messageTemplate.IsActive,
                EmailAccountId  = messageTemplate.EmailAccountId,
                LimitedToStores = messageTemplate.LimitedToStores,
            };

            InsertMessageTemplate(mtCopy);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var bccEmailAddresses = messageTemplate.GetLocalized(x => x.BccEmailAddresses, lang.Id, false, false);
                if (!String.IsNullOrEmpty(bccEmailAddresses))
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.BccEmailAddresses, bccEmailAddresses, lang.Id);
                }

                var subject = messageTemplate.GetLocalized(x => x.Subject, lang.Id, false, false);
                if (!String.IsNullOrEmpty(subject))
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.Subject, subject, lang.Id);
                }

                var body = messageTemplate.GetLocalized(x => x.Body, lang.Id, false, false);
                if (!String.IsNullOrEmpty(body))
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.Body, body, lang.Id);
                }

                var emailAccountId = messageTemplate.GetLocalized(x => x.EmailAccountId, lang.Id, false, false);
                if (emailAccountId > 0)
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.EmailAccountId, emailAccountId, lang.Id);
                }
            }

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

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

            return(mtCopy);
        }
Exemple #5
0
        protected virtual void UpdateStoreMapping(Slide slide, SlideModel model)
        {
            var allStores       = _storeService.GetAllStores();
            var limitedToStores = _storeMappingService.GetStoreMappings(slide);

            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds != null && model.SelectedStoreIds.Contains(store.Id))
                {
                    //new store mapping
                    if (!limitedToStores.Any(x => x.StoreId == store.Id))
                    {
                        _storeMappingService.InsertStoreMapping(slide, store.Id);
                    }
                }
                else
                {
                    //delete mapping
                    var storeMapping = limitedToStores.FirstOrDefault(x => x.StoreId == store.Id);
                    if (storeMapping != null)
                    {
                        _storeMappingService.DeleteStoreMapping(storeMapping);
                    }
                }
            }
        }
Exemple #6
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>
        /// <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(nameof(product));
            }

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

            var productCopy = CopyBaseProductData(product, newName, isPublished);

            //localization
            CopyLocalizationData(product, productCopy);

            //copy product tags
            foreach (var productProductTagMapping in product.ProductProductTagMappings)
            {
                productCopy.ProductProductTagMappings.Add(new ProductProductTagMapping {
                    ProductTag = productProductTagMapping.ProductTag
                });
            }

            _productService.UpdateProduct(productCopy);

            //copy product pictures
            var originalNewPictureIdentifiers = CopyProductPictures(product, newName, copyImages, productCopy);

            //product <-> categories mappings
            CopyCategoriesMapping(product, productCopy);
            //product <-> related products mappings
            CopyRelatedProductsMapping(product, productCopy);
            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

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

            //associated products
            CopyAssociatedProducts(product, isPublished, copyImages, copyAssociatedProducts, productCopy);

            return(productCopy);
        }
Exemple #7
0
        public ActionResult Create(StoreMappingModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageStores))
            {
                return(AccessDeniedView());
            }

            if (ModelState.IsValid)
            {
                var storeMapping = model.ToEntity();
                _storeMappingService.InsertStoreMapping(storeMapping);

                SuccessNotification(_localizationService.GetResource("Admin.Configuration.Stores.Added"));
                return(continueEditing ? RedirectToAction("Edit", new { id = storeMapping.Id }) : RedirectToAction("List"));
            }
            //If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemple #8
0
        protected virtual void SaveStoreMappings(BlogPost blogPost, BlogPostModel model)
        {
            blogPost.LimitedToStores = model.SelectedStoreIds.Any();

            var existingStoreMappings = _storeMappingService.GetStoreMappings(blogPost);

            #region Extensions  by QuanNH

            //stores
            var _workContext = Nop.Core.Infrastructure.EngineContext.Current.Resolve <Nop.Core.IWorkContext>();
            var allStores    = _storeService.GetAllStoresByEntityName(_workContext.CurrentCustomer.Id, "Stores");
            if (allStores.Count <= 0)
            {
                allStores = _storeService.GetAllStores();
            }

            #endregion

            foreach (var store in allStores)
            {
                if (model.SelectedStoreIds.Contains(store.Id))
                {
                    //new store
                    if (existingStoreMappings.Count(sm => sm.StoreId == store.Id) == 0)
                    {
                        _storeMappingService.InsertStoreMapping(blogPost, store.Id);
                    }
                }
                else
                {
                    //remove store
                    var storeMappingToDelete = existingStoreMappings.FirstOrDefault(sm => sm.StoreId == store.Id);
                    if (storeMappingToDelete != null)
                    {
                        _storeMappingService.DeleteStoreMapping(storeMappingToDelete);
                    }
                }
            }
        }
        /// <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);
        }
Exemple #10
0
        public virtual Product CopyProduct(
            Product product,
            string newName,
            bool isPublished,
            bool copyImages,
            bool copyAssociatedProducts = true)
        {
            Guard.NotNull(product, nameof(product));
            Guard.NotEmpty(newName, nameof(newName));

            using (_services.Chronometer.Step("Copy product " + product.Id))
            {
                Product clone     = null;
                var     utcNow    = DateTime.UtcNow;
                var     languages = _languageService.GetAllLanguages(true);

                // Media stuff
                int?sampleDownloadId = null;
                var clonedPictures   = new Dictionary <int, Picture>();              // Key = former ID, Value = cloned picture

                using (var scope = new DbContextScope(ctx: _productRepository.Context,
                                                      autoCommit: false,
                                                      autoDetectChanges: false,
                                                      proxyCreation: true,
                                                      validateOnSave: false,
                                                      forceNoTracking: true,
                                                      hooksEnabled: false))
                {
                    if (product.HasSampleDownload)
                    {
                        var sampleDownload      = _downloadService.GetDownloadById((int)product.SampleDownloadId);
                        var sampleDownloadClone = CopyDownload(sampleDownload);
                        sampleDownloadId = sampleDownloadClone.Id;
                    }

                    if (copyImages)
                    {
                        clonedPictures = CopyPictures(product, newName);
                    }

                    // Product
                    clone = new Product
                    {
                        ProductTypeId          = product.ProductTypeId,
                        ParentGroupedProductId = product.ParentGroupedProductId,
                        Visibility             = product.Visibility,
                        Name                 = newName,
                        ShortDescription     = product.ShortDescription,
                        FullDescription      = product.FullDescription,
                        ProductTemplateId    = product.ProductTemplateId,
                        AdminComment         = product.AdminComment,
                        ShowOnHomePage       = product.ShowOnHomePage,
                        HomePageDisplayOrder = product.HomePageDisplayOrder,
                        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,
                        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,
                        QuantityStep                     = product.QuantityStep,
                        QuantiyControlType               = product.QuantiyControlType,
                        HideQuantityControl              = product.HideQuantityControl,
                        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,
                        IsSystemProduct                  = product.IsSystemProduct,
                        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,
                        CustomsTariffNumber              = product.CustomsTariffNumber,
                        CountryOfOriginId                = product.CountryOfOriginId,
                        CreatedOnUtc                     = utcNow,
                        UpdatedOnUtc                     = utcNow
                    };

                    // Category mappings
                    foreach (var pc in product.ProductCategories)
                    {
                        clone.ProductCategories.Add(new ProductCategory
                        {
                            CategoryId        = pc.CategoryId,
                            IsFeaturedProduct = pc.IsFeaturedProduct,
                            DisplayOrder      = pc.DisplayOrder
                        });
                    }

                    // Manufacturer mappings
                    foreach (var pm in product.ProductManufacturers)
                    {
                        clone.ProductManufacturers.Add(new ProductManufacturer
                        {
                            ManufacturerId    = pm.ManufacturerId,
                            IsFeaturedProduct = pm.IsFeaturedProduct,
                            DisplayOrder      = pm.DisplayOrder
                        });
                    }

                    // Picture mappings
                    if (copyImages)
                    {
                        foreach (var pp in product.ProductPictures)
                        {
                            var pictureClone = clonedPictures.Get(pp.PictureId);
                            if (pictureClone != null)
                            {
                                clone.ProductPictures.Add(new ProductPicture
                                {
                                    PictureId    = pictureClone.Id,
                                    DisplayOrder = pp.DisplayOrder
                                });
                            }
                        }
                    }

                    // Product specifications
                    foreach (var psa in product.ProductSpecificationAttributes)
                    {
                        clone.ProductSpecificationAttributes.Add(new ProductSpecificationAttribute
                        {
                            SpecificationAttributeOptionId = psa.SpecificationAttributeOptionId,
                            AllowFiltering    = psa.AllowFiltering,
                            ShowOnProductPage = psa.ShowOnProductPage,
                            DisplayOrder      = psa.DisplayOrder
                        });
                    }

                    // Tier prices
                    foreach (var tp in product.TierPrices)
                    {
                        clone.TierPrices.Add(new TierPrice
                        {
                            StoreId           = tp.StoreId,
                            CustomerRoleId    = tp.CustomerRoleId,
                            Quantity          = tp.Quantity,
                            Price             = tp.Price,
                            CalculationMethod = tp.CalculationMethod
                        });
                    }

                    // Discount mapping
                    foreach (var discount in product.AppliedDiscounts)
                    {
                        clone.AppliedDiscounts.Add(discount);
                    }

                    // Tags
                    foreach (var tag in product.ProductTags)
                    {
                        clone.ProductTags.Add(tag);
                    }

                    // >>>>>>> Put clone to db (from here on we need the product clone's ID)
                    _productRepository.Insert(clone);
                    Commit();

                    // Related products mapping
                    foreach (var rp in _productService.GetRelatedProductsByProductId1(product.Id, true))
                    {
                        _relatedProductRepository.Insert(new RelatedProduct
                        {
                            ProductId1   = clone.Id,
                            ProductId2   = rp.ProductId2,
                            DisplayOrder = rp.DisplayOrder
                        });
                    }

                    // CrossSell products mapping
                    foreach (var csp in _productService.GetCrossSellProductsByProductId1(product.Id, true))
                    {
                        _crossSellProductRepository.Insert(new CrossSellProduct
                        {
                            ProductId1 = clone.Id,
                            ProductId2 = csp.ProductId2
                        });
                    }

                    // Store mapping
                    var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);
                    foreach (var id in selectedStoreIds)
                    {
                        _storeMappingService.InsertStoreMapping(clone, id);
                    }

                    // SEO
                    ProcessSlug(clone);

                    // Localization
                    ProcessLocalization(product, clone, languages);

                    // Attr stuff ...
                    ProcessAttributes(product, clone, newName, copyImages, clonedPictures, languages);

                    // update computed properties
                    clone.HasTierPrices                   = clone.TierPrices.Count > 0;
                    clone.HasDiscountsApplied             = clone.AppliedDiscounts.Count > 0;
                    clone.LowestAttributeCombinationPrice = _productAttributeService.GetLowestCombinationPrice(clone.Id);
                    clone.MainPictureId                   = clone.ProductPictures.OrderBy(x => x.DisplayOrder).Select(x => x.PictureId).FirstOrDefault();

                    // Associated products
                    if (copyAssociatedProducts && product.ProductType != ProductType.BundledProduct)
                    {
                        ProcessAssociatedProducts(product, clone, isPublished, copyImages);
                    }

                    // Bundle items
                    ProcessBundleItems(product, clone);

                    // Downloads
                    CopyDownloads(product.Id, clone.Id, "Product");

                    // >>>>>>> Our final commit
                    Commit();
                }

                return(clone);
            }
        }
Exemple #11
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>
        /// <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(nameof(product));
            }

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

            var productCopy = CopyBaseProductData(product, newName, isPublished);

            //localization
            CopyLocalizationData(product, productCopy);

            //copy product tags
            foreach (var productTag in _productTagService.GetAllProductTagsByProductId(product.Id))
            {
                _productTagService.InsertProductProductTagMapping(new ProductProductTagMapping {
                    ProductTagId = productTag.Id, ProductId = productCopy.Id
                });
            }

            _productService.UpdateProduct(productCopy);

            //copy product pictures
            var originalNewPictureIdentifiers = CopyProductPictures(product, newName, copyImages, productCopy);

            //quantity change history
            _productService.AddStockQuantityHistoryEntry(productCopy, product.StockQuantity, product.StockQuantity, product.WarehouseId,
                                                         string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.CopyProduct"), product.Id));

            //product specifications
            CopyProductSpecifications(product, productCopy);

            //product <-> warehouses mappings
            CopyWarehousesMapping(product, productCopy);
            //product <-> categories mappings
            CopyCategoriesMapping(product, productCopy);
            //product <-> manufacturers mappings
            CopyManufacturersMapping(product, productCopy);
            //product <-> related products mappings
            CopyRelatedProductsMapping(product, productCopy);
            //product <-> cross sells mappings
            CopyCrossSellsMapping(product, productCopy);
            //product <-> attributes mappings
            CopyAttributesMapping(product, productCopy, originalNewPictureIdentifiers);
            //product <-> discounts mapping
            CopyDiscountsMapping(product, productCopy);
            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

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

            //tier prices
            CopyTierPrices(product, productCopy);

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

            //associated products
            CopyAssociatedProducts(product, isPublished, copyImages, copyAssociatedProducts, productCopy);

            return(productCopy);
        }
Exemple #12
0
        public virtual MessageTemplate CopyMessageTemplate(MessageTemplate messageTemplate)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException("messageTemplate");
            }

            var mtCopy = new MessageTemplate
            {
                Name              = messageTemplate.Name,
                To                = messageTemplate.To,
                ReplyTo           = messageTemplate.ReplyTo,
                BccEmailAddresses = messageTemplate.BccEmailAddresses,
                Subject           = messageTemplate.Subject,
                Body              = messageTemplate.Body,
                IsActive          = messageTemplate.IsActive,
                EmailAccountId    = messageTemplate.EmailAccountId,
                LimitedToStores   = messageTemplate.LimitedToStores
                                    // INFO: we do not copy attachments
            };

            InsertMessageTemplate(mtCopy);

            var languages = _languageService.GetAllLanguages(true);

            // localization
            foreach (var lang in languages)
            {
                string bccEmailAddresses = messageTemplate.GetLocalized(x => x.BccEmailAddresses, lang, false, false);
                if (bccEmailAddresses.HasValue())
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.BccEmailAddresses, bccEmailAddresses, lang.Id);
                }

                string subject = messageTemplate.GetLocalized(x => x.Subject, lang, false, false);
                if (subject.HasValue())
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.Subject, subject, lang.Id);
                }

                string body = messageTemplate.GetLocalized(x => x.Body, lang, false, false);
                if (body.HasValue())
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.Body, subject, lang.Id);
                }

                int emailAccountId = messageTemplate.GetLocalized(x => x.EmailAccountId, lang, false, false);
                if (emailAccountId > 0)
                {
                    _localizedEntityService.SaveLocalizedValue(mtCopy, x => x.EmailAccountId, emailAccountId, lang.Id);
                }
            }

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

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

            return(mtCopy);
        }
Exemple #13
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);
        }
Exemple #14
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);
        }
        public virtual ActionResult Create(UserModel model, bool continueEditing, FormCollection form)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageUsers))
            {
                return(AccessDeniedView());
            }

            if (!String.IsNullOrWhiteSpace(model.Email))
            {
                var cust2 = _customerService.GetCustomerByEmail(model.Email);

                if (cust2 != null)
                {
                    ModelState.AddModelError("", "Email is already registered");
                }
            }

            //validate customer roles
            var allCustomerRoles = _customerService.GetAllCustomerRoles(true);
            var newCustomerRoles = new List <CustomerRole>();

            foreach (var customerRole in allCustomerRoles)
            {
                if (model.SelectedCustomerRoleIds.Contains(customerRole.Id))
                {
                    newCustomerRoles.Add(customerRole);
                }
            }

            // Trick to include this customer always as Registered :)
            newCustomerRoles.Add(
                allCustomerRoles.Where(t => t.SystemName == SystemCustomerRoleNames.Registered).FirstOrDefault()
                );

            var customerRolesError = ValidateCustomerRoles(newCustomerRoles);

            if (!String.IsNullOrEmpty(customerRolesError))
            {
                ModelState.AddModelError("", customerRolesError);
                ErrorNotification(customerRolesError, false);
            }

            // Ensure that valid email address is entered if Registered role is checked to avoid registered customers with empty email address
            if (newCustomerRoles.Any() &&
                newCustomerRoles.FirstOrDefault(c => c.SystemName == SystemCustomerRoleNames.Registered) != null &&
                !CommonHelper.IsValidEmail(model.Email))
            {
                ModelState.AddModelError("", _localizationService.GetResource("Admin.Customers.Customers.ValidEmailRequiredRegisteredRole"));
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.ValidEmailRequiredRegisteredRole"), false);
            }

            if (!ModelState.IsValid)
            {
                PrepareCustomerModel(model, null, true);
                return(View(model));
            }

            var customer = new Customer
            {
                CustomerGuid        = Guid.NewGuid(),
                Email               = model.Email,
                Active              = model.Active,
                CreatedOnUtc        = DateTime.UtcNow,
                LastActivityDateUtc = DateTime.UtcNow,
                RegisteredInStoreId = _storeContext.CurrentStore.Id,
                VendorId            = 1 // Default Moveleiros Loja (URGENT: CHANGE IT)
            };

            _customerService.InsertCustomer(customer);

            // Map user automatically with
            _storeMappingService.InsertStoreMapping(
                customerId: customer.Id,
                entityName: SystemCustomerRoleNames.Stores,
                storeId: _storeContext.CurrentStore.Id
                );

            //form fields
            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);

            //password
            if (!String.IsNullOrWhiteSpace(model.Password))
            {
                var changePassRequest = new ChangePasswordRequest(model.Email,
                                                                  false,
                                                                  _customerSettings.DefaultPasswordFormat,
                                                                  model.Password
                                                                  );

                var changePassResult = _customerRegistrationService.ChangePassword(changePassRequest);

                if (!changePassResult.Success)
                {
                    foreach (var changePassError in changePassResult.Errors)
                    {
                        ErrorNotification(changePassError);
                    }
                }
            }

            //customer roles
            foreach (var customerRole in newCustomerRoles)
            {
                //ensure that the current customer cannot add to "Administrators" system role if he's not an admin himself
                if (customerRole.SystemName == SystemCustomerRoleNames.Administrators &&
                    !_workContext.CurrentCustomer.IsAdmin())
                {
                    continue;
                }

                customer.CustomerRoles.Add(customerRole);
            }
            _customerService.UpdateCustomer(customer);

            //ensure that a customer with a vendor associated is not in "Administrators" role
            //otherwise, he won't have access to other functionality in admin area
            if (customer.IsAdmin() && customer.VendorId > 0)
            {
                customer.VendorId = 0;
                _customerService.UpdateCustomer(customer);
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.AdminCouldNotbeVendor"));
            }

            //ensure that a customer in the Vendors role has a vendor account associated.
            //otherwise, he will have access to ALL products
            if (customer.IsVendor() && customer.VendorId == 0)
            {
                var vendorRole = customer
                                 .CustomerRoles
                                 .FirstOrDefault(x => x.SystemName == SystemCustomerRoleNames.Vendors);

                customer.CustomerRoles.Remove(vendorRole);
                _customerService.UpdateCustomer(customer);
                ErrorNotification(_localizationService.GetResource("Admin.Customers.Customers.CannotBeInVendoRoleWithoutVendorAssociated"));
            }

            //activity log
            _customerActivityService.InsertActivity("AddNewCustomer", _localizationService.GetResource("ActivityLog.AddNewCustomer"), customer.Id);

            SuccessNotification(_localizationService.GetResource("Moveleiros.Admin.Settings.Users.Added"));

            if (continueEditing)
            {
                //selected tab
                SaveSelectedTabName();

                return(RedirectToAction("Edit", new { id = customer.Id }));
            }

            return(RedirectToAction("List"));
        }
Exemple #16
0
 /// <summary>
 /// Inserts a store mapping record
 /// </summary>
 /// <param name="storeMapping">Store mapping</param>
 public void InsertStoreMapping([FromBody] StoreMapping storeMapping)
 {
     _storeMappingService.InsertStoreMapping(storeMapping);
 }
Exemple #17
0
        /// <summary>
        /// Create a copy of article with all depended data
        /// </summary>
        /// <param name="article">The article to copy</param>
        /// <param name="newName">The name of article duplicate</param>
        /// <param name="isPublished">A value indicating whether the article duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the article images should be copied</param>
        /// <param name="copyAssociatedArticles">A value indicating whether the copy associated articles</param>
        /// <returns>Article copy</returns>
        public virtual Article CopyArticle(Article article, string newName,
                                           bool isPublished = true, bool copyImages = true, bool copyAssociatedArticles = true)
        {
            if (article == null)
            {
                throw new ArgumentNullException("article");
            }

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



            var newSku = !String.IsNullOrWhiteSpace(article.Sku)
                ? string.Format(_localizationService.GetResource("Admin.Catalog.Articles.Copy.SKU.New"), article.Sku) :
                         article.Sku;
            // article
            var articleCopy = new Article
            {
                ArticleTypeId          = article.ArticleTypeId,
                ParentGroupedArticleId = article.ParentGroupedArticleId,
                VisibleIndividually    = article.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = article.ShortDescription,
                FullDescription      = article.FullDescription,
                ContributorId        = article.ContributorId,
                ArticleTemplateId    = article.ArticleTemplateId,
                AdminComment         = article.AdminComment,
                ShowOnHomePage       = article.ShowOnHomePage,
                MetaKeywords         = article.MetaKeywords,
                MetaDescription      = article.MetaDescription,
                MetaTitle            = article.MetaTitle,
                AllowCustomerReviews = article.AllowCustomerReviews,
                LimitedToStores      = article.LimitedToStores,
                Sku = newSku,
                PublisherPartNumber = article.PublisherPartNumber,
                Gtin       = article.Gtin,
                IsGiftCard = article.IsGiftCard,

                OverriddenGiftCardAmount         = article.OverriddenGiftCardAmount,
                RequireOtherArticles             = article.RequireOtherArticles,
                RequiredArticleIds               = article.RequiredArticleIds,
                AutomaticallyAddRequiredArticles = article.AutomaticallyAddRequiredArticles,

                HasUserAgreement     = article.HasUserAgreement,
                UserAgreementText    = article.UserAgreementText,
                IsRecurring          = article.IsRecurring,
                RecurringCycleLength = article.RecurringCycleLength,
                RecurringCyclePeriod = article.RecurringCyclePeriod,
                RecurringTotalCycles = article.RecurringTotalCycles,
                IsRental             = article.IsRental,
                RentalPriceLength    = article.RentalPriceLength,
                RentalPricePeriod    = article.RentalPricePeriod,

                IsTaxExempt   = article.IsTaxExempt,
                TaxCategoryId = article.TaxCategoryId,

                AllowAddingOnlyExistingAttributeCombinations = article.AllowAddingOnlyExistingAttributeCombinations,
                NotReturnable               = article.NotReturnable,
                DisableBuyButton            = article.DisableBuyButton,
                DisableWishlistButton       = article.DisableWishlistButton,
                AvailableForPreSubscription = article.AvailableForPreSubscription,
                PreSubscriptionAvailabilityStartDateTimeUtc = article.PreSubscriptionAvailabilityStartDateTimeUtc,
                CallForPrice = article.CallForPrice,
                Price        = article.Price,
                OldPrice     = article.OldPrice,
                ArticleCost  = article.ArticleCost,

                MarkAsNew = article.MarkAsNew,
                MarkAsNewStartDateTimeUtc = article.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc   = article.MarkAsNewEndDateTimeUtc,

                AvailableStartDateTimeUtc = article.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc   = article.AvailableEndDateTimeUtc,
                DisplaySubscription       = article.DisplaySubscription,
                Published    = isPublished,
                Deleted      = article.Deleted,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            //validate search engine name
            _articleService.InsertArticle(articleCopy);

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

            var languages = _languageService.GetAllLanguages(true);

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

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

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

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

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

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

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

            //article tags
            foreach (var articleTag in article.ArticleTags)
            {
                articleCopy.ArticleTags.Add(articleTag);
            }
            _articleService.UpdateArticle(articleCopy);

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

            if (copyImages)
            {
                foreach (var articlePicture in article.ArticlePictures)
                {
                    var picture     = articlePicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        picture.AltAttribute,
                        picture.TitleAttribute);
                    _articleService.InsertArticlePicture(new ArticlePicture
                    {
                        ArticleId           = articleCopy.Id,
                        PictureId           = pictureCopy.Id,
                        DisplaySubscription = articlePicture.DisplaySubscription
                    });
                    originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id);
                }
            }


            _articleService.UpdateArticle(articleCopy);

            // article <-> categories mappings
            foreach (var articleCategory in article.ArticleCategories)
            {
                var articleCategoryCopy = new ArticleCategory
                {
                    ArticleId           = articleCopy.Id,
                    CategoryId          = articleCategory.CategoryId,
                    IsFeaturedArticle   = articleCategory.IsFeaturedArticle,
                    DisplaySubscription = articleCategory.DisplaySubscription
                };

                _categoryService.InsertArticleCategory(articleCategoryCopy);
            }

            // article <-> publishers mappings
            foreach (var articlePublishers in article.ArticlePublishers)
            {
                var articlePublisherCopy = new ArticlePublisher
                {
                    ArticleId           = articleCopy.Id,
                    PublisherId         = articlePublishers.PublisherId,
                    IsFeaturedArticle   = articlePublishers.IsFeaturedArticle,
                    DisplaySubscription = articlePublishers.DisplaySubscription
                };

                _publisherService.InsertArticlePublisher(articlePublisherCopy);
            }

            // article <-> releated articles mappings
            foreach (var relatedArticle in _articleService.GetRelatedArticlesByArticleId1(article.Id, true))
            {
                _articleService.InsertRelatedArticle(
                    new RelatedArticle
                {
                    ArticleId1          = articleCopy.Id,
                    ArticleId2          = relatedArticle.ArticleId2,
                    DisplaySubscription = relatedArticle.DisplaySubscription
                });
            }

            // article <-> cross sells mappings
            foreach (var csArticle in _articleService.GetCrossSellArticlesByArticleId1(article.Id, true))
            {
                _articleService.InsertCrossSellArticle(
                    new CrossSellArticle
                {
                    ArticleId1 = articleCopy.Id,
                    ArticleId2 = csArticle.ArticleId2,
                });
            }

            // article specifications
            foreach (var articleSpecificationAttribute in article.ArticleSpecificationAttributes)
            {
                var psaCopy = new ArticleSpecificationAttribute
                {
                    ArticleId       = articleCopy.Id,
                    AttributeTypeId = articleSpecificationAttribute.AttributeTypeId,
                    SpecificationAttributeOptionId = articleSpecificationAttribute.SpecificationAttributeOptionId,
                    CustomValue         = articleSpecificationAttribute.CustomValue,
                    AllowFiltering      = articleSpecificationAttribute.AllowFiltering,
                    ShowOnArticlePage   = articleSpecificationAttribute.ShowOnArticlePage,
                    DisplaySubscription = articleSpecificationAttribute.DisplaySubscription
                };
                _specificationAttributeService.InsertArticleSpecificationAttribute(psaCopy);
            }

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

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

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

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

            //all article attribute mapping copies
            var articleAttributeMappingCopies = new Dictionary <int, ArticleAttributeMapping>();

            foreach (var articleAttributeMapping in _articleAttributeService.GetArticleAttributeMappingsByArticleId(article.Id))
            {
                var articleAttributeMappingCopy = new ArticleAttributeMapping
                {
                    ArticleId                       = articleCopy.Id,
                    ArticleAttributeId              = articleAttributeMapping.ArticleAttributeId,
                    TextPrompt                      = articleAttributeMapping.TextPrompt,
                    IsRequired                      = articleAttributeMapping.IsRequired,
                    AttributeControlTypeId          = articleAttributeMapping.AttributeControlTypeId,
                    DisplaySubscription             = articleAttributeMapping.DisplaySubscription,
                    ValidationMinLength             = articleAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = articleAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = articleAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = articleAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = articleAttributeMapping.DefaultValue
                };
                _articleAttributeService.InsertArticleAttributeMapping(articleAttributeMappingCopy);

                articleAttributeMappingCopies.Add(articleAttributeMappingCopy.Id, articleAttributeMappingCopy);

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

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

                // article attribute values
                var articleAttributeValues = _articleAttributeService.GetArticleAttributeValues(articleAttributeMapping.Id);
                foreach (var articleAttributeValue in articleAttributeValues)
                {
                    int attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(articleAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[articleAttributeValue.PictureId];
                    }
                    var attributeValueCopy = new ArticleAttributeValue
                    {
                        ArticleAttributeMappingId = articleAttributeMappingCopy.Id,
                        AttributeValueTypeId      = articleAttributeValue.AttributeValueTypeId,
                        AssociatedArticleId       = articleAttributeValue.AssociatedArticleId,
                        Name                = articleAttributeValue.Name,
                        ColorSquaresRgb     = articleAttributeValue.ColorSquaresRgb,
                        PriceAdjustment     = articleAttributeValue.PriceAdjustment,
                        WeightAdjustment    = articleAttributeValue.WeightAdjustment,
                        Cost                = articleAttributeValue.Cost,
                        CustomerEntersQty   = articleAttributeValue.CustomerEntersQty,
                        Quantity            = articleAttributeValue.Quantity,
                        IsPreSelected       = articleAttributeValue.IsPreSelected,
                        DisplaySubscription = articleAttributeValue.DisplaySubscription,
                        PictureId           = attributeValuePictureId,
                    };
                    //picture associated to "iamge square" attribute type (if exists)
                    if (articleAttributeValue.ImageSquaresPictureId > 0)
                    {
                        var origImageSquaresPicture = _pictureService.GetPictureById(articleAttributeValue.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;
                        }
                    }

                    _articleAttributeService.InsertArticleAttributeValue(attributeValueCopy);

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

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

            //copy attribute conditions
            foreach (var articleAttributeMapping in oldCopyWithConditionAttributes)
            {
                var oldConditionAttributeMapping = _articleAttributeParser.ParseArticleAttributeMappings(articleAttributeMapping.ConditionAttributeXml).FirstOrDefault();

                if (oldConditionAttributeMapping == null)
                {
                    continue;
                }

                var oldConditionValues = _articleAttributeParser.ParseArticleAttributeValues(articleAttributeMapping.ConditionAttributeXml, oldConditionAttributeMapping.Id);

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

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

                var newConditionAttributeXml = string.Empty;

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

                var attributeMappingId = associatedAttributes[articleAttributeMapping.Id];
                var conditionAttribute = articleAttributeMappingCopies[attributeMappingId];
                conditionAttribute.ConditionAttributeXml = newConditionAttributeXml;

                _articleAttributeService.UpdateArticleAttributeMapping(conditionAttribute);
            }

            //attribute combinations
            foreach (var combination in _articleAttributeService.GetAllArticleAttributeCombinations(article.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml        = "";
                var    parsedArticleAttributes = _articleAttributeParser.ParseArticleAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedArticleAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        var newAttribute = _articleAttributeService.GetArticleAttributeMappingById(associatedAttributes[oldAttribute.Id]);
                        if (newAttribute != null)
                        {
                            var oldAttributeValuesStr = _articleAttributeParser.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 = _articleAttributeService.GetArticleAttributeValueById(associatedAttributeValues[oldAttributeValue]);
                                        if (newAttributeValue != null)
                                        {
                                            newAttributesXml = _articleAttributeParser.AddArticleAttribute(newAttributesXml,
                                                                                                           newAttribute, newAttributeValue.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _articleAttributeParser.AddArticleAttribute(newAttributesXml,
                                                                                                   newAttribute, oldAttributeValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ArticleAttributeCombination
                {
                    ArticleId     = articleCopy.Id,
                    AttributesXml = newAttributesXml,
                    StockQuantity = combination.StockQuantity,
                    AllowOutOfStockSubscriptions = combination.AllowOutOfStockSubscriptions,
                    Sku = combination.Sku,
                    PublisherPartNumber = combination.PublisherPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow
                };
                _articleAttributeService.InsertArticleAttributeCombination(combinationCopy);
            }



            _articleService.UpdateHasDiscountsApplied(articleCopy);

            //associated articles
            if (copyAssociatedArticles)
            {
                var associatedArticles = _articleService.GetAssociatedArticles(article.Id, showHidden: true);
                foreach (var associatedArticle in associatedArticles)
                {
                    var associatedArticleCopy = CopyArticle(associatedArticle, string.Format("Copy of {0}", associatedArticle.Name),
                                                            isPublished, copyImages, false);
                    associatedArticleCopy.ParentGroupedArticleId = articleCopy.Id;
                    _articleService.UpdateArticle(articleCopy);
                }
            }

            return(articleCopy);
        }
Exemple #18
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>
        /// <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");
            }

            var newSku = !String.IsNullOrWhiteSpace(product.Sku)
                ? string.Format(_localizationService.GetResource("Admin.Catalog.Products.Copy.SKU.New"), product.Sku) :
                         product.Sku;
            // product
            var 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       = newSku,
                MarkAsNew = product.MarkAsNew,
                MarkAsNewStartDateTimeUtc = product.MarkAsNewStartDateTimeUtc,
                MarkAsNewEndDateTimeUtc   = product.MarkAsNewEndDateTimeUtc,
                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);
                }
            }

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

            //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>();

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