public ActionResult ProductVendorInsert(GridCommand command, ProductModel.ProductVendorModel model) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog) && !_permissionService.Authorize(StandardPermissionProvider.ManageVendor) //add by hz ) return AccessDeniedView(); var productId = model.ProductId; var vendorId = Int32.Parse(model.Vendor); //use Vendor property (not VendorId) because appropriate property is stored in it var existingProductvendors = _vendorService.GetProductVendorsByVendorId(vendorId, 0, int.MaxValue, true); if (existingProductvendors.FindProductVendor(productId, vendorId) == null) { var productVendor = new ProductVendor() { ProductId = productId, VendorId = vendorId, IsFeaturedProduct = model.IsFeaturedProduct, DisplayOrder = model.DisplayOrder }; _vendorService.InsertProductVendor(productVendor); } return ProductVendorList(command, productId); }
/// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream, bool IsHzVendor) { // ok, we can run the real code of the sample now using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found"); //the columns var properties = new string[] { "Name", "ShortDescription", "FullDescription", "ProductTemplateId", "ShowOnHomePage", "MetaKeywords", "MetaDescription", "MetaTitle", "SeName", "AllowCustomerReviews", "Published", "ProductVariantName", "SKU", "ManufacturerPartNumber", "Gtin", "IsGiftCard", "GiftCardTypeId", "RequireOtherProducts", "RequiredProductVariantIds", "AutomaticallyAddRequiredProductVariants", "IsDownload", "DownloadId", "UnlimitedDownloads", "MaxNumberOfDownloads", "DownloadActivationTypeId", "HasSampleDownload", "SampleDownloadId", "HasUserAgreement", "UserAgreementText", "IsRecurring", "RecurringCycleLength", "RecurringCyclePeriodId", "RecurringTotalCycles", "IsShipEnabled", "IsFreeShipping", "AdditionalShippingCharge", "IsTaxExempt", "TaxCategoryId", "ManageInventoryMethodId", "StockQuantity", "DisplayStockAvailability", "DisplayStockQuantity", "MinStockQuantity", "LowStockActivityId", "NotifyAdminForQuantityBelow", "BackorderModeId", "AllowBackInStockSubscriptions", "OrderMinimumQuantity", "OrderMaximumQuantity", "AllowedQuantities", "DisableBuyButton", "DisableWishlistButton", "CallForPrice", "Price", "OldPrice", "ProductCost", "SpecialPrice", "SpecialPriceStartDateTimeUtc", "SpecialPriceEndDateTimeUtc", "CustomerEntersPrice", "MinimumCustomerEnteredPrice", "MaximumCustomerEnteredPrice", "Weight", "Length", "Width", "Height", "CreatedOnUtc", "CategoryIds", "ManufacturerIds", "VendorIds",//add by hz "Picture1", "Picture2", "Picture3", }; int iRow = 2; while (true) { bool allColumnsAreEmpty = true; for (var i = 1; i <= properties.Length; i++) if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString())) { allColumnsAreEmpty = false; break; } if (allColumnsAreEmpty) break; string name = worksheet.Cells[iRow, GetColumnIndex(properties, "Name")].Value as string; string shortDescription = worksheet.Cells[iRow, GetColumnIndex(properties, "ShortDescription")].Value as string; string fullDescription = worksheet.Cells[iRow, GetColumnIndex(properties, "FullDescription")].Value as string; int productTemplateId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value); bool showOnHomePage = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShowOnHomePage")].Value); string metaKeywords = worksheet.Cells[iRow, GetColumnIndex(properties, "MetaKeywords")].Value as string; string metaDescription = worksheet.Cells[iRow, GetColumnIndex(properties, "MetaDescription")].Value as string; string metaTitle = worksheet.Cells[iRow, GetColumnIndex(properties, "MetaTitle")].Value as string; string seName = worksheet.Cells[iRow, GetColumnIndex(properties, "SeName")].Value as string; bool allowCustomerReviews = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowCustomerReviews")].Value); bool published = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "Published")].Value); string productVariantName = worksheet.Cells[iRow, GetColumnIndex(properties, "ProductVariantName")].Value as string; string sku = worksheet.Cells[iRow, GetColumnIndex(properties, "SKU")].Value as string; string manufacturerPartNumber = worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerPartNumber")].Value as string; string gtin = worksheet.Cells[iRow, GetColumnIndex(properties, "Gtin")].Value as string; bool isGiftCard = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsGiftCard")].Value); int giftCardTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "GiftCardTypeId")].Value); bool requireOtherProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "RequireOtherProducts")].Value); string requiredProductVariantIds = worksheet.Cells[iRow, GetColumnIndex(properties, "RequiredProductVariantIds")].Value as string; bool automaticallyAddRequiredProductVariants = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AutomaticallyAddRequiredProductVariants")].Value); bool isDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsDownload")].Value); int downloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadId")].Value); bool unlimitedDownloads = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UnlimitedDownloads")].Value); int maxNumberOfDownloads = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MaxNumberOfDownloads")].Value); int downloadActivationTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadActivationTypeId")].Value); bool hasSampleDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasSampleDownload")].Value); int sampleDownloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "SampleDownloadId")].Value); bool hasUserAgreement = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasUserAgreement")].Value); string userAgreementText = worksheet.Cells[iRow, GetColumnIndex(properties, "UserAgreementText")].Value as string; bool isRecurring = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRecurring")].Value); int recurringCycleLength = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCycleLength")].Value); int recurringCyclePeriodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCyclePeriodId")].Value); int recurringTotalCycles = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringTotalCycles")].Value); bool isShipEnabled = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsShipEnabled")].Value); bool isFreeShipping = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsFreeShipping")].Value); decimal additionalShippingCharge = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "AdditionalShippingCharge")].Value); bool isTaxExempt = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTaxExempt")].Value); int taxCategoryId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "TaxCategoryId")].Value); int manageInventoryMethodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ManageInventoryMethodId")].Value); int stockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "StockQuantity")].Value); bool displayStockAvailability = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockAvailability")].Value); bool displayStockQuantity = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockQuantity")].Value); int minStockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MinStockQuantity")].Value); int lowStockActivityId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "LowStockActivityId")].Value); int notifyAdminForQuantityBelow = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "NotifyAdminForQuantityBelow")].Value); int backorderModeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BackorderModeId")].Value); bool allowBackInStockSubscriptions = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowBackInStockSubscriptions")].Value); int orderMinimumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMinimumQuantity")].Value); int orderMaximumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMaximumQuantity")].Value); string allowedQuantities = worksheet.Cells[iRow, GetColumnIndex(properties, "AllowedQuantities")].Value as string; bool disableBuyButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableBuyButton")].Value); bool disableWishlistButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableWishlistButton")].Value); bool callForPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CallForPrice")].Value); decimal price = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Price")].Value); decimal oldPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "OldPrice")].Value); decimal productCost = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductCost")].Value); decimal? specialPrice = null; var specialPriceExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPrice")].Value; if (specialPriceExcel != null) specialPrice = Convert.ToDecimal(specialPriceExcel); DateTime? specialPriceStartDateTimeUtc = null; var specialPriceStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceStartDateTimeUtc")].Value; if (specialPriceStartDateTimeUtcExcel != null) specialPriceStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceStartDateTimeUtcExcel)); DateTime? specialPriceEndDateTimeUtc = null; var specialPriceEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceEndDateTimeUtc")].Value; if (specialPriceEndDateTimeUtcExcel != null) specialPriceEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceEndDateTimeUtcExcel)); bool customerEntersPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CustomerEntersPrice")].Value); decimal minimumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MinimumCustomerEnteredPrice")].Value); decimal maximumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MaximumCustomerEnteredPrice")].Value); decimal weight = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Weight")].Value); decimal length = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Length")].Value); decimal width = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Width")].Value); decimal height = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Height")].Value); DateTime createdOnUtc = DateTime.FromOADate(Convert.ToDouble(worksheet.Cells[iRow, GetColumnIndex(properties, "CreatedOnUtc")].Value)); string categoryIds = worksheet.Cells[iRow, GetColumnIndex(properties, "CategoryIds")].Value as string; string manufacturerIds = worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerIds")].Value as string; string sendorIds = worksheet.Cells[iRow, GetColumnIndex(properties, "VendorIds")].Value as string;//add by hz string picture1 = worksheet.Cells[iRow, GetColumnIndex(properties, "Picture1")].Value as string; string picture2 = worksheet.Cells[iRow, GetColumnIndex(properties, "Picture2")].Value as string; string picture3 = worksheet.Cells[iRow, GetColumnIndex(properties, "Picture3")].Value as string; var productVariant = _productService.GetProductVariantBySku(sku); if (productVariant != null) { //product var product = productVariant.Product; product.Name = name; product.ShortDescription = shortDescription; product.FullDescription = fullDescription; product.ProductTemplateId = productTemplateId; product.ShowOnHomePage = showOnHomePage; product.MetaKeywords = metaKeywords; product.MetaDescription = metaDescription; product.MetaTitle = metaTitle; product.AllowCustomerReviews = allowCustomerReviews; product.Published = published; product.CreatedOnUtc = createdOnUtc; product.UpdatedOnUtc = DateTime.UtcNow; _productService.UpdateProduct(product); //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); //variant productVariant.Name = productVariantName; productVariant.Sku = sku; productVariant.ManufacturerPartNumber = manufacturerPartNumber; productVariant.Gtin = gtin; productVariant.IsGiftCard = isGiftCard; productVariant.GiftCardTypeId = giftCardTypeId; productVariant.RequireOtherProducts = requireOtherProducts; productVariant.RequiredProductVariantIds = requiredProductVariantIds; productVariant.AutomaticallyAddRequiredProductVariants = automaticallyAddRequiredProductVariants; productVariant.IsDownload = isDownload; productVariant.DownloadId = downloadId; productVariant.UnlimitedDownloads = unlimitedDownloads; productVariant.MaxNumberOfDownloads = maxNumberOfDownloads; productVariant.DownloadActivationTypeId = downloadActivationTypeId; productVariant.HasSampleDownload = hasSampleDownload; productVariant.SampleDownloadId = sampleDownloadId; productVariant.HasUserAgreement = hasUserAgreement; productVariant.UserAgreementText = userAgreementText; productVariant.IsRecurring = isRecurring; productVariant.RecurringCycleLength = recurringCycleLength; productVariant.RecurringCyclePeriodId = recurringCyclePeriodId; productVariant.RecurringTotalCycles = recurringTotalCycles; productVariant.IsShipEnabled = isShipEnabled; productVariant.IsFreeShipping = isFreeShipping; productVariant.AdditionalShippingCharge = additionalShippingCharge; productVariant.IsTaxExempt = isTaxExempt; productVariant.TaxCategoryId = taxCategoryId; productVariant.ManageInventoryMethodId = manageInventoryMethodId; productVariant.StockQuantity = stockQuantity; productVariant.DisplayStockAvailability = displayStockAvailability; productVariant.DisplayStockQuantity = displayStockQuantity; productVariant.MinStockQuantity = minStockQuantity; productVariant.LowStockActivityId = lowStockActivityId; productVariant.NotifyAdminForQuantityBelow = notifyAdminForQuantityBelow; productVariant.BackorderModeId = backorderModeId; productVariant.AllowBackInStockSubscriptions = allowBackInStockSubscriptions; productVariant.OrderMinimumQuantity = orderMinimumQuantity; productVariant.OrderMaximumQuantity = orderMaximumQuantity; productVariant.AllowedQuantities = allowedQuantities; productVariant.DisableBuyButton = disableBuyButton; productVariant.DisableWishlistButton = disableWishlistButton; productVariant.CallForPrice = callForPrice; productVariant.Price = price; productVariant.OldPrice = oldPrice; productVariant.ProductCost = productCost; productVariant.SpecialPrice = specialPrice; productVariant.SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc; productVariant.SpecialPriceEndDateTimeUtc = specialPriceEndDateTimeUtc; productVariant.CustomerEntersPrice = customerEntersPrice; productVariant.MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice; productVariant.MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice; productVariant.Weight = weight; productVariant.Length = length; productVariant.Width = width; productVariant.Height = height; productVariant.Published = published; productVariant.CreatedOnUtc = createdOnUtc; productVariant.UpdatedOnUtc = DateTime.UtcNow; _productService.UpdateProductVariant(productVariant); } else { //product var product = new Product() { Name = name, ShortDescription = shortDescription, FullDescription = fullDescription, ShowOnHomePage = showOnHomePage, MetaKeywords = metaKeywords, MetaDescription = metaDescription, MetaTitle = metaTitle, AllowCustomerReviews = allowCustomerReviews, Published = published, CreatedOnUtc = createdOnUtc, UpdatedOnUtc = DateTime.UtcNow }; _productService.InsertProduct(product); //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); //vairant productVariant = new ProductVariant() { ProductId = product.Id, Name = productVariantName, Sku = sku, ManufacturerPartNumber = manufacturerPartNumber, Gtin = gtin, IsGiftCard = isGiftCard, GiftCardTypeId = giftCardTypeId, RequireOtherProducts = requireOtherProducts, RequiredProductVariantIds = requiredProductVariantIds, AutomaticallyAddRequiredProductVariants = automaticallyAddRequiredProductVariants, IsDownload = isDownload, DownloadId = downloadId, UnlimitedDownloads = unlimitedDownloads, MaxNumberOfDownloads = maxNumberOfDownloads, DownloadActivationTypeId = downloadActivationTypeId, HasSampleDownload = hasSampleDownload, SampleDownloadId = sampleDownloadId, HasUserAgreement = hasUserAgreement, UserAgreementText = userAgreementText, IsRecurring = isRecurring, RecurringCycleLength = recurringCycleLength, RecurringCyclePeriodId = recurringCyclePeriodId, RecurringTotalCycles = recurringTotalCycles, IsShipEnabled = isShipEnabled, IsFreeShipping = isFreeShipping, AdditionalShippingCharge = additionalShippingCharge, IsTaxExempt = isTaxExempt, TaxCategoryId = taxCategoryId, ManageInventoryMethodId = manageInventoryMethodId, StockQuantity = stockQuantity, DisplayStockAvailability = displayStockAvailability, DisplayStockQuantity = displayStockQuantity, MinStockQuantity = minStockQuantity, LowStockActivityId = lowStockActivityId, NotifyAdminForQuantityBelow = notifyAdminForQuantityBelow, BackorderModeId = backorderModeId, AllowBackInStockSubscriptions = allowBackInStockSubscriptions, OrderMinimumQuantity = orderMinimumQuantity, OrderMaximumQuantity = orderMaximumQuantity, AllowedQuantities = allowedQuantities, DisableBuyButton = disableBuyButton, CallForPrice = callForPrice, Price = price, OldPrice = oldPrice, ProductCost = productCost, SpecialPrice = specialPrice, SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc, SpecialPriceEndDateTimeUtc = specialPriceEndDateTimeUtc, CustomerEntersPrice = customerEntersPrice, MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice, MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice, Weight = weight, Length = length, Width = width, Height = height, Published = published, CreatedOnUtc = createdOnUtc, UpdatedOnUtc = DateTime.UtcNow }; _productService.InsertProductVariant(productVariant); } //category mappings if (!String.IsNullOrEmpty(categoryIds)) { foreach (var id in categoryIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (productVariant.Product.ProductCategories.Where(x => x.CategoryId == id).FirstOrDefault() == null) { //ensure that category exists var category = _categoryService.GetCategoryById(id); if (category != null) { var productCategory = new ProductCategory() { ProductId = productVariant.Product.Id, CategoryId = category.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } } } } //manufacturer mappings if (!String.IsNullOrEmpty(manufacturerIds)) { foreach (var id in manufacturerIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (productVariant.Product.ProductManufacturers.Where(x => x.ManufacturerId == id).FirstOrDefault() == null) { //ensure that manufacturer exists var manufacturer = _manufacturerService.GetManufacturerById(id); if (manufacturer != null) { var productManufacturer = new ProductManufacturer() { ProductId = productVariant.Product.Id, ManufacturerId = manufacturer.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _manufacturerService.InsertProductManufacturer(productManufacturer); } } } } //add by hz //sendor mappings if (!String.IsNullOrEmpty(sendorIds)) { foreach (var id in sendorIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (productVariant.Product.ProductVendors.Where(x => x.VendorId == id).FirstOrDefault() == null) { //ensure that sendor exists var sendor = _sendorService.GetVendorById(id); if (sendor != null) { var productVendor = new ProductVendor() { ProductId = productVariant.Product.Id, VendorId = sendor.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _sendorService.InsertProductVendor(productVendor); } } } } //end by hz //pictures foreach (var picture in new string[] { picture1, picture2, picture3 }) { if (String.IsNullOrEmpty(picture)) continue; productVariant.Product.ProductPictures.Add(new ProductPicture() { Picture = _pictureService.InsertPicture(File.ReadAllBytes(picture), "image/jpeg", _pictureService.GetPictureSeName(name), true), DisplayOrder = 1, }); _productService.UpdateProduct(productVariant.Product); } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(productVariant); _productService.UpdateHasDiscountsApplied(productVariant); //next product iRow++; } } }
/// <summary> /// Creates a copy of product with all depended data /// </summary> /// <param name="productId">The product identifier</param> /// <param name="newName">The name of product duplicate</param> /// <param name="isPublished">A value indicating whether the product duplicate should be published</param> /// <param name="copyImages">A value indicating whether the product images should be copied</param> /// <returns>Product entity</returns> public Product CopyProduct(int productId, string newName, bool isPublished, bool copyImages, bool IsHzVendor) { var product = _productService.GetProductById(productId); if (product == null) throw new ArgumentException("No product found with the specified id", "productId"); Product productCopy = null; //uncomment this line to support transactions //using (var scope = new System.Transactions.TransactionScope()) { // product productCopy = new Product() { Name = newName, ShortDescription = product.ShortDescription, FullDescription = product.FullDescription, ProductTemplateId = product.ProductTemplateId, AdminComment = product.AdminComment, ShowOnHomePage = product.ShowOnHomePage, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, MetaTitle = product.MetaTitle, AllowCustomerReviews = product.AllowCustomerReviews, Published = isPublished, Deleted = product.Deleted, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow }; //validate search engine name _productService.InsertProduct(productCopy); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0); var languages = _languageService.GetAllLanguages(true); //localization foreach (var lang in languages) { var name = product.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id); var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(shortDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id); var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(fullDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id); var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false); if (!String.IsNullOrEmpty(metaKeywords)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id); var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(metaDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id); var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false); if (!String.IsNullOrEmpty(metaTitle)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id); } //product tags foreach (var productTag in product.ProductTags) { productCopy.ProductTags.Add(productTag); } //ensure product is saved before updating totals _productService.UpdateProduct(product); foreach (var productTag in product.ProductTags) { _productTagService.UpdateProductTagTotals(productTag); } // product pictures if (copyImages) { foreach (var productPicture in product.ProductPictures) { var picture = productPicture.Picture; var pictureCopy = _pictureService.InsertPicture( _pictureService.LoadPictureBinary(picture), picture.MimeType, _pictureService.GetPictureSeName(newName), true); _productService.InsertProductPicture(new ProductPicture() { ProductId = productCopy.Id, PictureId = pictureCopy.Id, DisplayOrder = productPicture.DisplayOrder }); } } // product <-> categories mappings foreach (var productCategory in product.ProductCategories) { var productCategoryCopy = new ProductCategory() { ProductId = productCopy.Id, CategoryId = productCategory.CategoryId, IsFeaturedProduct = productCategory.IsFeaturedProduct, DisplayOrder = productCategory.DisplayOrder }; _categoryService.InsertProductCategory(productCategoryCopy); } // product <-> manufacturers mappings foreach (var productManufacturers in product.ProductManufacturers) { var productManufacturerCopy = new ProductManufacturer() { ProductId = productCopy.Id, ManufacturerId = productManufacturers.ManufacturerId, IsFeaturedProduct = productManufacturers.IsFeaturedProduct, DisplayOrder = productManufacturers.DisplayOrder }; _manufacturerService.InsertProductManufacturer(productManufacturerCopy); } //add by hz // product <-> vendors mappings foreach (var productVendors in product.ProductVendors) { var productVendorCopy = new ProductVendor() { ProductId = productCopy.Id, VendorId = productVendors.VendorId, IsFeaturedProduct = productVendors.IsFeaturedProduct, DisplayOrder = productVendors.DisplayOrder }; _vendorService.InsertProductVendor(productVendorCopy); } //end by hz // product <-> releated products mappings foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true)) { _productService.InsertRelatedProduct( new RelatedProduct() { ProductId1 = productCopy.Id, ProductId2 = relatedProduct.ProductId2, DisplayOrder = relatedProduct.DisplayOrder }); } // product <-> cross sells mappings foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true)) { _productService.InsertCrossSellProduct( new CrossSellProduct() { ProductId1 = productCopy.Id, ProductId2 = csProduct.ProductId2, }); } // product specifications foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes) { var psaCopy = new ProductSpecificationAttribute() { ProductId = productCopy.Id, SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId, AllowFiltering = productSpecificationAttribute.AllowFiltering, ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage, DisplayOrder = productSpecificationAttribute.DisplayOrder }; _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy); } // product variants var productVariants = product.ProductVariants; foreach (var productVariant in productVariants) { // product variant picture int pictureId = 0; if (copyImages) { var picture = _pictureService.GetPictureById(productVariant.PictureId); if (picture != null) { var pictureCopy = _pictureService.InsertPicture( _pictureService.LoadPictureBinary(picture), picture.MimeType, _pictureService.GetPictureSeName(productVariant.Name), true); pictureId = pictureCopy.Id; } } // product variant download & sample download int downloadId = productVariant.DownloadId; int sampleDownloadId = productVariant.SampleDownloadId; if (productVariant.IsDownload) { var download = _downloadService.GetDownloadById(productVariant.DownloadId); if (download != null) { var downloadCopy = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = download.UseDownloadUrl, DownloadUrl = download.DownloadUrl, DownloadBinary = download.DownloadBinary, ContentType = download.ContentType, Filename = download.Filename, Extension = download.Extension, IsNew = download.IsNew, }; _downloadService.InsertDownload(downloadCopy); downloadId = downloadCopy.Id; } if (productVariant.HasSampleDownload) { var sampleDownload = _downloadService.GetDownloadById(productVariant.SampleDownloadId); if (sampleDownload != null) { var sampleDownloadCopy = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = sampleDownload.UseDownloadUrl, DownloadUrl = sampleDownload.DownloadUrl, DownloadBinary = sampleDownload.DownloadBinary, ContentType = sampleDownload.ContentType, Filename = sampleDownload.Filename, Extension = sampleDownload.Extension, IsNew = sampleDownload.IsNew }; _downloadService.InsertDownload(sampleDownloadCopy); sampleDownloadId = sampleDownloadCopy.Id; } } } // product variant var productVariantCopy = new ProductVariant() { ProductId = productCopy.Id, Name = productVariant.Name, Sku = productVariant.Sku, Description = productVariant.Description, AdminComment = productVariant.AdminComment, ManufacturerPartNumber = productVariant.ManufacturerPartNumber, Gtin = productVariant.Gtin, IsGiftCard = productVariant.IsGiftCard, GiftCardType = productVariant.GiftCardType, RequireOtherProducts = productVariant.RequireOtherProducts, RequiredProductVariantIds = productVariant.RequiredProductVariantIds, AutomaticallyAddRequiredProductVariants = productVariant.AutomaticallyAddRequiredProductVariants, IsDownload = productVariant.IsDownload, DownloadId = downloadId, UnlimitedDownloads = productVariant.UnlimitedDownloads, MaxNumberOfDownloads = productVariant.MaxNumberOfDownloads, DownloadExpirationDays = productVariant.DownloadExpirationDays, DownloadActivationType = productVariant.DownloadActivationType, HasSampleDownload = productVariant.HasSampleDownload, SampleDownloadId = sampleDownloadId, HasUserAgreement = productVariant.HasUserAgreement, UserAgreementText = productVariant.UserAgreementText, IsRecurring = productVariant.IsRecurring, RecurringCycleLength = productVariant.RecurringCycleLength, RecurringCyclePeriod = productVariant.RecurringCyclePeriod, RecurringTotalCycles = productVariant.RecurringTotalCycles, IsShipEnabled = productVariant.IsShipEnabled, IsFreeShipping = productVariant.IsFreeShipping, AdditionalShippingCharge = productVariant.AdditionalShippingCharge, IsTaxExempt = productVariant.IsTaxExempt, TaxCategoryId = productVariant.TaxCategoryId, ManageInventoryMethod = productVariant.ManageInventoryMethod, StockQuantity = productVariant.StockQuantity, DisplayStockAvailability = productVariant.DisplayStockAvailability, DisplayStockQuantity = productVariant.DisplayStockQuantity, MinStockQuantity = productVariant.MinStockQuantity, LowStockActivityId = productVariant.LowStockActivityId, NotifyAdminForQuantityBelow = productVariant.NotifyAdminForQuantityBelow, BackorderMode = productVariant.BackorderMode, AllowBackInStockSubscriptions = productVariant.AllowBackInStockSubscriptions, OrderMinimumQuantity = productVariant.OrderMinimumQuantity, OrderMaximumQuantity = productVariant.OrderMaximumQuantity, AllowedQuantities = productVariant.AllowedQuantities, DisableBuyButton = productVariant.DisableBuyButton, DisableWishlistButton = productVariant.DisableWishlistButton, CallForPrice = productVariant.CallForPrice, Price = productVariant.Price, OldPrice = productVariant.OldPrice, ProductCost = productVariant.ProductCost, SpecialPrice = productVariant.SpecialPrice, SpecialPriceStartDateTimeUtc = productVariant.SpecialPriceStartDateTimeUtc, SpecialPriceEndDateTimeUtc = productVariant.SpecialPriceEndDateTimeUtc, CustomerEntersPrice = productVariant.CustomerEntersPrice, MinimumCustomerEnteredPrice = productVariant.MinimumCustomerEnteredPrice, MaximumCustomerEnteredPrice = productVariant.MaximumCustomerEnteredPrice, Weight = productVariant.Weight, Length = productVariant.Length, Width = productVariant.Width, Height = productVariant.Height, PictureId = pictureId, AvailableStartDateTimeUtc = productVariant.AvailableStartDateTimeUtc, AvailableEndDateTimeUtc = productVariant.AvailableEndDateTimeUtc, Published = productVariant.Published, Deleted = productVariant.Deleted, DisplayOrder = productVariant.DisplayOrder, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow }; _productService.InsertProductVariant(productVariantCopy); //localization foreach (var lang in languages) { var name = productVariant.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Name, name, lang.Id); var description = productVariant.GetLocalized(x => x.Description, lang.Id, false, false); if (!String.IsNullOrEmpty(description)) _localizedEntityService.SaveLocalizedValue(productVariantCopy, x => x.Description, description, lang.Id); } // product variant <-> attributes mappings var associatedAttributes = new Dictionary<int, int>(); var associatedAttributeValues = new Dictionary<int, int>(); foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductVariantId(productVariant.Id)) { var productVariantAttributeCopy = new ProductVariantAttribute() { ProductVariantId = productVariantCopy.Id, ProductAttributeId = productVariantAttribute.ProductAttributeId, TextPrompt = productVariantAttribute.TextPrompt, IsRequired = productVariantAttribute.IsRequired, AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId, DisplayOrder = productVariantAttribute.DisplayOrder }; _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy); //save associated value (used for combinations copying) associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id); // product variant attribute values var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id); foreach (var productVariantAttributeValue in productVariantAttributeValues) { var pvavCopy = new ProductVariantAttributeValue() { ProductVariantAttributeId = productVariantAttributeCopy.Id, Name = productVariantAttributeValue.Name, PriceAdjustment = productVariantAttributeValue.PriceAdjustment, WeightAdjustment = productVariantAttributeValue.WeightAdjustment, IsPreSelected = productVariantAttributeValue.IsPreSelected, DisplayOrder = productVariantAttributeValue.DisplayOrder }; _productAttributeService.InsertProductVariantAttributeValue(pvavCopy); //save associated value (used for combinations copying) associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id); //localization foreach (var lang in languages) { var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id); } } } foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(productVariant.Id)) { //generate new AttributesXml according to new value IDs string newAttributesXml = ""; var parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml); foreach (var oldPva in parsedProductVariantAttributes) { if (associatedAttributes.ContainsKey(oldPva.Id)) { int newPvaId = associatedAttributes[oldPva.Id]; var newPva = _productAttributeService.GetProductVariantAttributeById(newPvaId); if (newPva != null) { var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id); foreach (var oldPvaValueStr in oldPvaValuesStr) { if (newPva.ShouldHaveValues()) { //attribute values int oldPvaValue = int.Parse(oldPvaValueStr); if (associatedAttributeValues.ContainsKey(oldPvaValue)) { int newPvavId = associatedAttributeValues[oldPvaValue]; var newPvav = _productAttributeService.GetProductVariantAttributeValueById(newPvavId); if (newPvav != null) { newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString()); } } } else { //just a text newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr); } } } } } var combinationCopy = new ProductVariantAttributeCombination() { ProductVariantId = productVariantCopy.Id, AttributesXml = newAttributesXml, StockQuantity = combination.StockQuantity, AllowOutOfStockOrders = combination.AllowOutOfStockOrders }; _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy); } // product variant tier prices foreach (var tierPrice in productVariant.TierPrices) { _productService.InsertTierPrice( new TierPrice() { ProductVariantId = productVariantCopy.Id, CustomerRoleId = tierPrice.CustomerRoleId, Quantity = tierPrice.Quantity, Price = tierPrice.Price }); } // product variant <-> discounts mapping foreach (var discount in productVariant.AppliedDiscounts) { productVariantCopy.AppliedDiscounts.Add(discount); _productService.UpdateProductVariant(productVariantCopy); } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(productVariantCopy); _productService.UpdateHasDiscountsApplied(productVariantCopy); } //uncomment this line to support transactions //scope.Complete(); } return productCopy; }
/// <summary> /// Deletes a product vendor mapping /// </summary> /// <param name="productVendor">Product vendor mapping</param> public virtual void DeleteProductVendor(ProductVendor productVendor) { if (productVendor == null) throw new ArgumentNullException("productVendor"); _productVendorRepository.Delete(productVendor); //cache _cacheManager.RemoveByPattern(VENDORS_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVENDORS_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productVendor); }