protected void gvProductVariantAttributes_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "UpdateProductVariantAttribute") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = gvProductVariantAttributes.Rows[index]; HiddenField hfProductVariantAttributeId = row.FindControl("hfProductVariantAttributeId") as HiddenField; DropDownList ddlProductAttribute = row.FindControl("ddlProductAttribute") as DropDownList; TextBox txtTextPrompt = row.FindControl("txtTextPrompt") as TextBox; CheckBox cbIsRequired = row.FindControl("cbIsRequired") as CheckBox; DropDownList ddlAttributeControlType = row.FindControl("ddlAttributeControlType") as DropDownList; NumericTextBox txtDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox; int productVariantAttributeId = int.Parse(hfProductVariantAttributeId.Value); int productAttributeId = int.Parse(ddlProductAttribute.SelectedItem.Value); string textPrompt = txtTextPrompt.Text; bool isRequired = cbIsRequired.Checked; AttributeControlTypeEnum attributeControlType = (AttributeControlTypeEnum)Enum.ToObject(typeof(AttributeControlTypeEnum), int.Parse(ddlAttributeControlType.SelectedItem.Value)); int displayOrder = txtDisplayOrder.Value; ProductVariantAttribute productVariantAttribute = ProductAttributeManager.GetProductVariantAttributeById(productVariantAttributeId); if (productVariantAttribute != null) { ProductAttributeManager.UpdateProductVariantAttribute(productVariantAttribute.ProductVariantAttributeId, productVariantAttribute.ProductVariantId, productAttributeId, textPrompt, isRequired, attributeControlType, displayOrder); } BindAttributes(); BindCombinations(); RefreshSelectCombinationControl(); } }
public void Can_save_and_load_productVariantAttribute() { var pva = new ProductVariantAttribute { TextPrompt = "TextPrompt 1", IsRequired = true, AttributeControlType = AttributeControlType.DropdownList, DisplayOrder = 1, Product = GetTestProduct(), ProductAttribute = new ProductAttribute() { Name = "Name 1", Description = "Description 1", } }; var fromDb = SaveAndLoadEntity(pva); fromDb.ShouldNotBeNull(); fromDb.TextPrompt.ShouldEqual("TextPrompt 1"); fromDb.IsRequired.ShouldEqual(true); fromDb.AttributeControlType.ShouldEqual(AttributeControlType.DropdownList); fromDb.DisplayOrder.ShouldEqual(1); fromDb.Product.ShouldNotBeNull(); fromDb.ProductAttribute.ShouldNotBeNull(); fromDb.ProductAttribute.Name.ShouldEqual("Name 1"); }
protected void btnNewProductVariantAttribute_Click(object sender, EventArgs e) { try { ProductVariant productVariant = ProductManager.GetProductVariantById(this.ProductVariantId); if (productVariant != null) { if (ddlNewProductAttributes.SelectedItem == null) { return; } int productAttributeId = int.Parse(ddlNewProductAttributes.SelectedItem.Value); AttributeControlTypeEnum attributeControlType = (AttributeControlTypeEnum)Enum.ToObject(typeof(AttributeControlTypeEnum), int.Parse(this.ddlAttributeControlType.SelectedItem.Value)); ProductVariantAttribute productVariantAttribute = ProductAttributeManager.InsertProductVariantAttribute(productVariant.ProductVariantId, productAttributeId, txtNewTextPrompt.Text, cbNewProductVariantAttributeIsRequired.Checked, attributeControlType, txtNewProductVariantAttributeDisplayOrder.Value); BindAttributes(); BindCombinations(); RefreshSelectCombinationControl(); txtNewProductVariantAttributeDisplayOrder.Value = 1; } } catch (Exception exc) { processAjaxError(exc); } }
protected void btnAdd_Click(object sender, EventArgs e) { try { ProductVariantAttribute productVariantAttribute = ProductAttributeManager.GetProductVariantAttributeById(this.ProductVariantAttributeId); if (productVariantAttribute != null) { ProductVariantAttributeValue productVariantAttributeValue = ProductAttributeManager.InsertProductVariantAttributeValue(productVariantAttribute.ProductVariantAttributeId, txtNewName.Text, txtNewPriceAdjustment.Value, txtNewWeightAdjustment.Value, cbNewIsPreSelected.Checked, txtNewDisplayOrder.Value); SaveLocalizableContent(productVariantAttributeValue); BindData(); txtNewName.Text = string.Empty; txtNewPriceAdjustment.Value = 0; txtNewWeightAdjustment.Value = 0; txtNewDisplayOrder.Value = 1; } } catch (Exception exc) { ProcessException(exc); } }
protected void btnNewProductVariantAttribute_Click(object sender, EventArgs e) { try { ProductVariant productVariant = ProductManager.GetProductVariantByID(this.ProductVariantID); if (productVariant != null) { if (ddlNewProductAttributes.SelectedItem == null) { return; } //TODO check duplicate int productAttributeID = int.Parse(ddlNewProductAttributes.SelectedItem.Value); AttributeControlTypeEnum attributeControlType = (AttributeControlTypeEnum)Enum.ToObject(typeof(AttributeControlTypeEnum), int.Parse(this.ddlAttributeControlType.SelectedItem.Value)); ProductVariantAttribute productVariantAttribute = ProductAttributeManager.InsertProductVariantAttribute(productVariant.ProductVariantID, productAttributeID, txtNewTextPrompt.Text, cbNewProductVariantAttributeIsRequired.Checked, attributeControlType, txtNewProductVariantAttributeDisplayOrder.Value); BindData(); txtNewProductVariantAttributeDisplayOrder.Value = 1; } } catch (Exception exc) { ProcessException(exc); } }
public virtual void InsertProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { Guard.NotNull(productVariantAttribute, nameof(productVariantAttribute)); _productVariantAttributeRepository.Insert(productVariantAttribute); _requestCache.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _requestCache.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); }
protected void gvProductVariantAttributes_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ProductVariantAttribute productVariantAttribute = (ProductVariantAttribute)e.Row.DataItem; Button btnUpdate = e.Row.FindControl("btnUpdate") as Button; if (btnUpdate != null) { btnUpdate.CommandArgument = e.Row.RowIndex.ToString(); } DropDownList ddlProductAttribute = e.Row.FindControl("ddlProductAttribute") as DropDownList; if (ddlProductAttribute != null) { ddlProductAttribute.Items.Clear(); var productAttributes = ProductAttributeManager.GetAllProductAttributes(); foreach (ProductAttribute productAttribute in productAttributes) { ListItem item = new ListItem(productAttribute.Name, productAttribute.ProductAttributeId.ToString()); ddlProductAttribute.Items.Add(item); if (productAttribute.ProductAttributeId == productVariantAttribute.ProductAttributeId) { item.Selected = true; } } } DropDownList ddlAttributeControlType = e.Row.FindControl("ddlAttributeControlType") as DropDownList; { if (ddlAttributeControlType != null) { CommonHelper.FillDropDownWithEnum(ddlAttributeControlType, typeof(AttributeControlTypeEnum)); } CommonHelper.SelectListItem(ddlAttributeControlType, productVariantAttribute.AttributeControlTypeId); } HyperLink hlAttributeValues = e.Row.FindControl("hlAttributeValues") as HyperLink; if (hlAttributeValues != null) { if (productVariantAttribute.ShouldHaveValues) { hlAttributeValues.Visible = true; hlAttributeValues.NavigateUrl = string.Format("{0}ProductVariantAttributeValues.aspx?ProductVariantAttributeID={1}", CommonHelper.GetStoreAdminLocation(), productVariantAttribute.ProductVariantAttributeId); hlAttributeValues.Text = string.Format(GetLocaleResourceString("Admin.ProductVariantAttributes.Values.Count"), productVariantAttribute.ProductVariantAttributeValues.Count); } else { hlAttributeValues.Visible = false; } } } }
public AttributeDTO(ProductVariantAttribute p) { this.Id = p.Id; this.Name = p.ProductAttribute.Name; this.AttributeControl = p.AttributeControlType; this.Values = new List <string>(); foreach (ProductVariantAttributeValue pv in p.ProductVariantAttributeValues) { this.Values.Add(pv.Name); } this.isRequired = p.IsRequired; }
public virtual void UpdateProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { throw new ArgumentNullException("productVariantAttribute"); } _productVariantAttributeRepository.Update(productVariantAttribute); _requestCache.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _requestCache.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); }
public virtual void DeleteProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { throw new ArgumentNullException("productVariantAttribute"); } _productVariantAttributeRepository.Delete(productVariantAttribute); _requestCache.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _requestCache.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(productVariantAttribute); }
/// <summary> /// A value indicating whether this product variant attribute should have values /// </summary> /// <param name="productVariantAttribute">Product variant attribute</param> /// <returns>Result</returns> public static bool ShouldHaveValues(this ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { return(false); } if (productVariantAttribute.AttributeControlType == AttributeControlType.TextBox) { return(false); } //other attribute controle types support values return(true); }
/// <summary> /// Inserts a product variant attribute mapping /// </summary> /// <param name="productVariantAttribute">The product variant attribute mapping</param> public virtual void InsertProductVariantAttribute(ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { throw new ArgumentNullException("productVariantAttribute"); } _productVariantAttributeRepository.Insert(productVariantAttribute); _cacheManager.RemoveByPattern(PRODUCTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(PRODUCTVARIANTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(productVariantAttribute); }
private void BindData() { ProductVariantAttribute productVariantAttribute = ProductAttributeManager.GetProductVariantAttributeById(this.ProductVariantAttributeId); if (productVariantAttribute != null) { if (this.HasLocalizableContent) { var languages = this.GetLocalizableLanguagesSupported(); rptrLanguageTabs.DataSource = languages; rptrLanguageTabs.DataBind(); rptrLanguageDivs.DataSource = languages; rptrLanguageDivs.DataBind(); } ProductVariant productVariant = productVariantAttribute.ProductVariant; if (productVariant == null) { Response.Redirect("Products.aspx"); } ProductAttribute productAttribute = productVariantAttribute.ProductAttribute; if (productAttribute == null) { Response.Redirect("Products.aspx"); } this.lblTitle.Text = string.Format(GetLocaleResourceString("Admin.ProductVariantAttributeValues.AddEdit"), Server.HtmlEncode(productAttribute.Name), Server.HtmlEncode(productVariant.FullProductName)); this.hlProductURL.NavigateUrl = CommonHelper.GetStoreAdminLocation() + "ProductVariantDetails.aspx?ProductVariantID=" + productVariant.ProductVariantId; var productVariantAttributeValues = ProductAttributeManager.GetProductVariantAttributeValues(productVariantAttribute.ProductVariantAttributeId); if (productVariantAttributeValues.Count > 0) { this.gvProductVariantAttributeValues.Visible = true; this.gvProductVariantAttributeValues.DataSource = productVariantAttributeValues; this.gvProductVariantAttributeValues.DataBind(); } else { this.gvProductVariantAttributeValues.Visible = false; } } else { Response.Redirect("Products.aspx"); } }
/// <summary> /// A value indicating whether this product variant attribute should can have some validation rules /// </summary> /// <param name="productVariantAttribute">Product variant attribute</param> /// <returns>Result</returns> public static bool ValidationRulesAllowed(this ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { return(false); } if (productVariantAttribute.AttributeControlType == AttributeControlType.TextBox || productVariantAttribute.AttributeControlType == AttributeControlType.MultilineTextbox || productVariantAttribute.AttributeControlType == AttributeControlType.FileUpload) { return(true); } //other attribute controle types does not have validation return(false); }
/// <summary> /// A value indicating whether this product variant attribute should have values /// </summary> /// <param name="productVariantAttribute">Product variant attribute</param> /// <returns>Result</returns> public static bool ShouldHaveValues(this ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { return(false); } if (productVariantAttribute.AttributeControlType == AttributeControlType.TextBox || productVariantAttribute.AttributeControlType == AttributeControlType.MultilineTextbox || productVariantAttribute.AttributeControlType == AttributeControlType.Datepicker) { return(false); } else { return(true); } }
/// <summary> /// A value indicating whether this product variant attribute should have values /// </summary> /// <param name="productVariantAttribute">Product variant attribute</param> /// <returns>Result</returns> public static bool ShouldHaveValues(this ProductVariantAttribute productVariantAttribute) { if (productVariantAttribute == null) { return(false); } if (productVariantAttribute.AttributeControlType == AttributeControlType.TextBox || productVariantAttribute.AttributeControlType == AttributeControlType.MultilineTextbox || productVariantAttribute.AttributeControlType == AttributeControlType.Datepicker || productVariantAttribute.AttributeControlType == AttributeControlType.FileUpload) { return(false); } // all other attribute control types support values return(true); }
public void Can_save_and_load_productVariantAttribute() { var pva = new ProductVariantAttribute { TextPrompt = "TextPrompt 1", IsRequired = true, AttributeControlType = AttributeControlType.DropdownList, DisplayOrder = 1, ProductVariant = new ProductVariant() { Name = "Product variant name 1", CreatedOnUtc = new DateTime(2010, 01, 03), UpdatedOnUtc = new DateTime(2010, 01, 04), Product = new Product() { Name = "Name 1", Published = true, Deleted = false, CreatedOnUtc = new DateTime(2010, 01, 01), UpdatedOnUtc = new DateTime(2010, 01, 02), } }, ProductAttribute = new ProductAttribute() { Name = "Name 1", Description = "Description 1", } }; var fromDb = SaveAndLoadEntity(pva); fromDb.ShouldNotBeNull(); fromDb.TextPrompt.ShouldEqual("TextPrompt 1"); fromDb.IsRequired.ShouldEqual(true); fromDb.AttributeControlType.ShouldEqual(AttributeControlType.DropdownList); fromDb.DisplayOrder.ShouldEqual(1); fromDb.ProductVariant.ShouldNotBeNull(); fromDb.ProductVariant.Name.ShouldEqual("Product variant name 1"); fromDb.ProductAttribute.ShouldNotBeNull(); fromDb.ProductAttribute.Name.ShouldEqual("Name 1"); }
public void Can_save_and_load_productVariantAttribute() { var pva = new ProductVariantAttribute { TextPrompt = "TextPrompt 1", IsRequired = true, AttributeControlType = AttributeControlType.DropdownList, DisplayOrder = 1, ValidationMinLength = 2, ValidationMaxLength = 3, ValidationFileAllowedExtensions = "ValidationFileAllowedExtensions 1", ValidationFileMaximumSize = 4, DefaultValue = "DefaultValue 1", Product = GetTestProduct(), ProductAttribute = new ProductAttribute() { Name = "Name 1", Description = "Description 1", } }; var fromDb = SaveAndLoadEntity(pva); fromDb.ShouldNotBeNull(); fromDb.TextPrompt.ShouldEqual("TextPrompt 1"); fromDb.IsRequired.ShouldEqual(true); fromDb.AttributeControlType.ShouldEqual(AttributeControlType.DropdownList); fromDb.DisplayOrder.ShouldEqual(1); fromDb.ValidationMinLength.ShouldEqual(2); fromDb.ValidationMaxLength.ShouldEqual(3); fromDb.ValidationFileAllowedExtensions.ShouldEqual("ValidationFileAllowedExtensions 1"); fromDb.ValidationFileMaximumSize.ShouldEqual(4); fromDb.DefaultValue.ShouldEqual("DefaultValue 1"); fromDb.Product.ShouldNotBeNull(); fromDb.ProductAttribute.ShouldNotBeNull(); fromDb.ProductAttribute.Name.ShouldEqual("Name 1"); }
private void BindData() { ProductVariantAttribute productVariantAttribute = ProductAttributeManager.GetProductVariantAttributeByID(this.ProductVariantAttributeID); if (productVariantAttribute != null) { ProductVariant productVariant = productVariantAttribute.ProductVariant; if (productVariant == null) { Response.Redirect("Products.aspx"); } ProductAttribute productAttribute = productVariantAttribute.ProductAttribute; if (productAttribute == null) { Response.Redirect("Products.aspx"); } this.lblTitle.Text = string.Format(GetLocaleResourceString("Admin.ProductVariantAttributeValues.AddEdit"), Server.HtmlEncode(productAttribute.Name), Server.HtmlEncode(productVariant.FullProductName)); this.hlProductURL.NavigateUrl = CommonHelper.GetStoreAdminLocation() + "ProductVariantDetails.aspx?ProductVariantID=" + productVariant.ProductVariantID; ProductVariantAttributeValueCollection productVariantAttributeValues = productVariantAttribute.ProductVariantAttributeValues; if (productVariantAttributeValues.Count > 0) { this.gvProductVariantAttributeValues.Visible = true; this.gvProductVariantAttributeValues.DataSource = productVariantAttributeValues; this.gvProductVariantAttributeValues.DataBind(); } else { this.gvProductVariantAttributeValues.Visible = false; } } else { Response.Redirect("Products.aspx"); } }
private static dynamic ToDynamic(ProductVariantAttribute productAttribute, DataExporterContext ctx) { if (productAttribute == null) { return(null); } var languageId = ctx.LanguageId; var attribute = productAttribute.ProductAttribute; dynamic result = new DynamicEntity(productAttribute); dynamic dynAttribute = new DynamicEntity(attribute); dynAttribute.Name = ctx.GetTranslation(attribute, nameof(attribute.Name), attribute.Name); dynAttribute.Description = ctx.GetTranslation(attribute, nameof(attribute.Description), attribute.Description); dynAttribute.Values = productAttribute.ProductVariantAttributeValues .OrderBy(x => x.DisplayOrder) .Select(x => { dynamic dyn = new DynamicEntity(x); dyn.Name = ctx.GetTranslation(x, nameof(x.Name), x.Name); dyn._Localized = GetLocalized(ctx, x, y => y.Name); return(dyn); }) .ToList(); dynAttribute._Localized = GetLocalized(ctx, attribute, x => x.Name, x => x.Description); result.Attribute = dynAttribute; return(result); }
public static string AddProductAttribute(this ProductVariantAttribute pva, string attributes, string value) { string result = string.Empty; try { var xmlDoc = new XmlDocument(); if (String.IsNullOrEmpty(attributes)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributes); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); XmlElement pvaElement = null; //find existing var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductVariantAttribute"); foreach (XmlNode node1 in nodeList1) { if (node1.Attributes != null && node1.Attributes["ID"] != null) { string str1 = node1.Attributes["ID"].InnerText.Trim(); int id = 0; if (int.TryParse(str1, out id)) { if (id == pva.Id) { pvaElement = (XmlElement)node1; break; } } } } //create new one if not found if (pvaElement == null) { pvaElement = xmlDoc.CreateElement("ProductVariantAttribute"); pvaElement.SetAttribute("ID", pva.Id.ToString()); rootElement.AppendChild(pvaElement); } var pvavElement = xmlDoc.CreateElement("ProductVariantAttributeValue"); pvaElement.AppendChild(pvavElement); var pvavVElement = xmlDoc.CreateElement("Value"); pvavVElement.InnerText = value; pvavElement.AppendChild(pvavVElement); result = xmlDoc.OuterXml; } catch (Exception exc) { Debug.Write(exc.ToString()); } return(result); }
/// <summary> /// Adds an attribute /// </summary> /// <param name="attributes">Attributes</param> /// <param name="pva">Product variant attribute</param> /// <param name="value">Value</param> /// <returns>Attributes</returns> public virtual string AddProductAttribute(string attributes, ProductVariantAttribute pva, string value) { return(pva.AddProductAttribute(attributes, value)); }
private void ProcessAttributes( Product product, Product clone, string newName, bool copyImages, Dictionary <int, Picture> clonedPictures, IEnumerable <Language> languages) { // Former attribute id > clone var pvaMap = new Dictionary <int, ProductVariantAttribute>(); // Former attribute value id > clone var pvavMap = new Dictionary <int, ProductVariantAttributeValue>(); var pictureSeName = _pictureService.GetPictureSeName(newName); foreach (var pva in product.ProductVariantAttributes) { var pvaClone = new ProductVariantAttribute { ProductAttributeId = pva.ProductAttributeId, TextPrompt = pva.TextPrompt, IsRequired = pva.IsRequired, AttributeControlTypeId = pva.AttributeControlTypeId, DisplayOrder = pva.DisplayOrder }; clone.ProductVariantAttributes.Add(pvaClone); // Save associated value (used for combinations copying) pvaMap[pva.Id] = pvaClone; // Product variant attribute values foreach (var pvav in pva.ProductVariantAttributeValues) { var pvavClone = new ProductVariantAttributeValue { Name = pvav.Name, Color = pvav.Color, PriceAdjustment = pvav.PriceAdjustment, WeightAdjustment = pvav.WeightAdjustment, IsPreSelected = pvav.IsPreSelected, DisplayOrder = pvav.DisplayOrder, ValueTypeId = pvav.ValueTypeId, LinkedProductId = pvav.LinkedProductId, Quantity = pvav.Quantity, PictureId = copyImages ? pvav.PictureId : 0 // we'll clone this later }; pvaClone.ProductVariantAttributeValues.Add(pvavClone); // Save associated value (used for combinations copying) pvavMap.Add(pvav.Id, pvavClone); } } // >>>>>> Commit Commit(); // Attribute value localization foreach (var pvav in product.ProductVariantAttributes.SelectMany(x => x.ProductVariantAttributeValues).ToArray()) { foreach (var lang in languages) { var name = pvav.GetLocalized(x => x.Name, lang, false, false); if (!String.IsNullOrEmpty(name)) { var pvavClone = pvavMap.Get(pvav.Id); if (pvavClone != null) { _localizedEntityService.SaveLocalizedValue(pvavClone, x => x.Name, name, lang.Id); } } } } // Clone attribute value images if (copyImages) { // Reduce value set to those with assigned pictures var allValueClonesWithPictures = pvavMap.Values.Where(x => x.PictureId > 0).ToArray(); // Get those pictures for cloning var allPictures = _pictureService.GetPicturesByIds(allValueClonesWithPictures.Select(x => x.PictureId).ToArray(), true); foreach (var pvavClone in allValueClonesWithPictures) { var picture = allPictures.FirstOrDefault(x => x.Id == pvavClone.PictureId); if (picture != null) { var pictureClone = CopyPicture(picture, pictureSeName); clonedPictures[pvavClone.PictureId] = pictureClone; pvavClone.PictureId = pictureClone.Id; } } } // >>>>>> Commit attributes & values Commit(); // attribute combinations using (var scope = new DbContextScope(lazyLoading: false, forceNoTracking: false)) { scope.LoadCollection(product, (Product p) => p.ProductVariantAttributeCombinations); } foreach (var combination in product.ProductVariantAttributeCombinations) { // Generate new AttributesXml according to new value IDs string newAttributesXml = ""; var parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml); foreach (var oldPva in parsedProductVariantAttributes) { if (!pvaMap.ContainsKey(oldPva.Id)) { continue; } var newPva = pvaMap.Get(oldPva.Id); if (newPva == null) { continue; } var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id); foreach (var oldPvaValueStr in oldPvaValuesStr) { if (newPva.ShouldHaveValues()) { // attribute values int oldPvaValue = oldPvaValueStr.Convert <int>(); if (pvavMap.ContainsKey(oldPvaValue)) { var newPvav = pvavMap.Get(oldPvaValue); if (newPvav != null) { newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString()); } } } else { // just a text newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr); } } } var newAssignedPictureIds = new HashSet <string>(); foreach (var strPicId in combination.AssignedPictureIds.EmptyNull().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var newPic = clonedPictures.Get(strPicId.Convert <int>()); if (newPic != null) { newAssignedPictureIds.Add(newPic.Id.ToString(CultureInfo.InvariantCulture)); } } var combinationClone = new ProductVariantAttributeCombination { AttributesXml = newAttributesXml, StockQuantity = combination.StockQuantity, AllowOutOfStockOrders = combination.AllowOutOfStockOrders, Sku = combination.Sku, Gtin = combination.Gtin, ManufacturerPartNumber = combination.ManufacturerPartNumber, Price = combination.Price, AssignedPictureIds = copyImages ? String.Join(",", newAssignedPictureIds) : 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 }; clone.ProductVariantAttributeCombinations.Add(combinationClone); } // >>>>>> Commit combinations Commit(); }
/// <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); }
public IQueryable <ProductVariantAttribute> ManageAttributes(int key, ODataActionParameters parameters) { var entity = GetExpandedEntity(key, x => x.ProductVariantAttributes); var result = new List <ProductVariantAttributeValue>(); this.ProcessEntity(() => { var synchronize = parameters.GetValueSafe <bool>("Synchronize"); var data = (parameters["Attributes"] as IEnumerable <ManageAttributeType>) .Where(x => x.Name.HasValue()) .ToList(); var attributeNames = new HashSet <string>(data.Select(x => x.Name), StringComparer.InvariantCultureIgnoreCase); var pagedAttributes = _productAttributeService.Value.GetAllProductAttributes(0, 1); var attributesData = pagedAttributes.SourceQuery .Where(x => attributeNames.Contains(x.Name)) .Select(x => new { x.Id, x.Name }) .ToList(); var allAttributesDic = attributesData.ToDictionarySafe(x => x.Name, x => x, StringComparer.OrdinalIgnoreCase); foreach (var srcAttr in data) { var attributeId = 0; if (allAttributesDic.TryGetValue(srcAttr.Name, out var attributeData)) { attributeId = attributeData.Id; } else { var attribute = new ProductAttribute { Name = srcAttr.Name }; _productAttributeService.Value.InsertProductAttribute(attribute); attributeId = attribute.Id; } var productAttribute = entity.ProductVariantAttributes.FirstOrDefault(x => x.ProductAttribute.Name.IsCaseInsensitiveEqual(srcAttr.Name)); if (productAttribute == null) { productAttribute = new ProductVariantAttribute { ProductId = entity.Id, ProductAttributeId = attributeId, AttributeControlTypeId = srcAttr.ControlTypeId, DisplayOrder = entity.ProductVariantAttributes.OrderByDescending(x => x.DisplayOrder).Select(x => x.DisplayOrder).FirstOrDefault() + 1, IsRequired = srcAttr.IsRequired }; entity.ProductVariantAttributes.Add(productAttribute); Service.UpdateProduct(entity); } else if (synchronize) { if (srcAttr.Values.Count <= 0 && productAttribute.ShouldHaveValues()) { _productAttributeService.Value.DeleteProductVariantAttribute(productAttribute); } else { productAttribute.AttributeControlTypeId = srcAttr.ControlTypeId; productAttribute.IsRequired = srcAttr.IsRequired; Service.UpdateProduct(entity); } } var maxDisplayOrder = productAttribute.ProductVariantAttributeValues .OrderByDescending(x => x.DisplayOrder) .Select(x => x.DisplayOrder) .FirstOrDefault(); foreach (var srcVal in srcAttr.Values.Where(x => x.Name.HasValue())) { var value = productAttribute.ProductVariantAttributeValues.FirstOrDefault(x => x.Name.IsCaseInsensitiveEqual(srcVal.Name)); if (value == null) { value = new ProductVariantAttributeValue { ProductVariantAttributeId = productAttribute.Id, Name = srcVal.Name, Alias = srcVal.Alias, Color = srcVal.Color, PriceAdjustment = srcVal.PriceAdjustment, WeightAdjustment = srcVal.WeightAdjustment, IsPreSelected = srcVal.IsPreSelected, DisplayOrder = ++maxDisplayOrder }; productAttribute.ProductVariantAttributeValues.Add(value); Service.UpdateProduct(entity); } else if (synchronize) { value.Alias = srcVal.Alias; value.Color = srcVal.Color; value.PriceAdjustment = srcVal.PriceAdjustment; value.WeightAdjustment = srcVal.WeightAdjustment; value.IsPreSelected = srcVal.IsPreSelected; Service.UpdateProduct(entity); } } if (synchronize) { foreach (var dstVal in productAttribute.ProductVariantAttributeValues.ToList()) { if (!srcAttr.Values.Any(x => x.Name.IsCaseInsensitiveEqual(dstVal.Name))) { _productAttributeService.Value.DeleteProductVariantAttributeValue(dstVal); } } } } }); return(entity.ProductVariantAttributes.AsQueryable()); }
public IQueryable <ProductVariantAttribute> ManageAttributes(int key, ODataActionParameters parameters) { var entity = GetExpandedEntity <ICollection <ProductVariantAttribute> >(key, x => x.ProductVariantAttributes); var result = new List <ProductVariantAttributeValue>(); this.ProcessEntity(() => { bool synchronize = Convert.ToBoolean(parameters["Synchronize"]); var data = (parameters["Attributes"] as IEnumerable <ManageAttributeType>).Where(x => x.Name.HasValue()).ToList(); var allAttributes = _productAttributeService.Value.GetAllProductAttributes(); foreach (var srcAttr in data) { var productAttribute = allAttributes.FirstOrDefault(x => x.Name.IsCaseInsensitiveEqual(srcAttr.Name)); if (productAttribute == null) { productAttribute = new ProductAttribute() { Name = srcAttr.Name }; _productAttributeService.Value.InsertProductAttribute(productAttribute); } var attribute = entity.ProductVariantAttributes.FirstOrDefault(x => x.ProductAttribute.Name.IsCaseInsensitiveEqual(srcAttr.Name)); if (attribute == null) { attribute = new ProductVariantAttribute() { ProductId = entity.Id, ProductAttributeId = productAttribute.Id, AttributeControlTypeId = srcAttr.ControlTypeId, DisplayOrder = entity.ProductVariantAttributes.OrderByDescending(x => x.DisplayOrder).Select(x => x.DisplayOrder).FirstOrDefault() + 1, IsRequired = srcAttr.IsRequired }; entity.ProductVariantAttributes.Add(attribute); Service.UpdateProduct(entity); } else if (synchronize) { if (srcAttr.Values.Count <= 0) { _productAttributeService.Value.DeleteProductVariantAttribute(attribute); } else { attribute.AttributeControlTypeId = srcAttr.ControlTypeId; attribute.IsRequired = srcAttr.IsRequired; Service.UpdateProduct(entity); } } int maxDisplayOrder = attribute.ProductVariantAttributeValues.OrderByDescending(x => x.DisplayOrder).Select(x => x.DisplayOrder).FirstOrDefault(); foreach (var srcVal in srcAttr.Values.Where(x => x.Name.HasValue())) { var value = attribute.ProductVariantAttributeValues.FirstOrDefault(x => x.Name.IsCaseInsensitiveEqual(srcVal.Name)); if (value == null) { value = new ProductVariantAttributeValue() { ProductVariantAttributeId = attribute.Id, Name = srcVal.Name, Alias = srcVal.Alias, Color = srcVal.ColorSquaresRgb, PriceAdjustment = srcVal.PriceAdjustment, WeightAdjustment = srcVal.WeightAdjustment, IsPreSelected = srcVal.IsPreSelected, DisplayOrder = ++maxDisplayOrder }; attribute.ProductVariantAttributeValues.Add(value); Service.UpdateProduct(entity); } else if (synchronize) { value.Alias = srcVal.Alias; value.Color = srcVal.ColorSquaresRgb; value.PriceAdjustment = srcVal.PriceAdjustment; value.WeightAdjustment = srcVal.WeightAdjustment; value.IsPreSelected = srcVal.IsPreSelected; Service.UpdateProduct(entity); } } if (synchronize) { foreach (var dstVal in attribute.ProductVariantAttributeValues.ToList()) { if (!srcAttr.Values.Any(x => x.Name.IsCaseInsensitiveEqual(dstVal.Name))) { _productAttributeService.Value.DeleteProductVariantAttributeValue(dstVal); } } } } //return null; }); return(entity.ProductVariantAttributes.AsQueryable()); }
public virtual int CopyAttributeOptions(ProductVariantAttribute productVariantAttribute, int productAttributeOptionsSetId, bool deleteExistingValues) { Guard.NotNull(productVariantAttribute, nameof(productVariantAttribute)); Guard.NotZero(productVariantAttribute.Id, nameof(productVariantAttribute.Id)); Guard.NotZero(productAttributeOptionsSetId, nameof(productAttributeOptionsSetId)); if (deleteExistingValues) { var existingValues = productVariantAttribute.ProductVariantAttributeValues.ToList(); if (!existingValues.Any()) { existingValues = GetProductVariantAttributeValues(productVariantAttribute.Id).ToList(); } existingValues.Each(x => DeleteProductVariantAttributeValue(x)); } var result = 0; var attributeOptions = _productAttributeOptionRepository.TableUntracked .Where(x => x.ProductAttributeOptionsSetId == productAttributeOptionsSetId) .ToList(); if (!attributeOptions.Any()) { return(result); } // Do not insert already existing values (identified by name field). var existingValueNames = new HashSet <string>(_productVariantAttributeValueRepository.TableUntracked .Where(x => x.ProductVariantAttributeId == productVariantAttribute.Id) .Select(x => x.Name) .ToList()); Picture picture = null; ProductVariantAttributeValue productVariantAttributeValue = null; var pictureIds = attributeOptions.Where(x => x.PictureId != 0).Select(x => x.PictureId).Distinct().ToArray(); var pictures = _pictureService.GetPicturesByIds(pictureIds, true).ToDictionarySafe(x => x.Id); using (_localizedEntityService.BeginScope()) { foreach (var option in attributeOptions) { if (existingValueNames.Contains(option.Name)) { continue; } productVariantAttributeValue = option.Clone(); productVariantAttributeValue.PictureId = 0; productVariantAttributeValue.ProductVariantAttributeId = productVariantAttribute.Id; // Copy picture. if (option.PictureId != 0 && pictures.TryGetValue(option.PictureId, out picture)) { var pictureBinary = _pictureService.LoadPictureBinary(picture); var newPicture = _pictureService.InsertPicture( pictureBinary, picture.MimeType, picture.SeoFilename, picture.IsNew, picture.Width ?? 0, picture.Height ?? 0, picture.IsTransient ); productVariantAttributeValue.PictureId = newPicture.Id; } // No scope commit, we need new entity id. _productVariantAttributeValueRepository.Insert(productVariantAttributeValue); ++result; // Copy localized properties too. var optionProperties = _localizedEntityService.GetLocalizedProperties(option.Id, "ProductAttributeOption"); foreach (var property in optionProperties) { _localizedEntityService.InsertLocalizedProperty(new LocalizedProperty { EntityId = productVariantAttributeValue.Id, LocaleKeyGroup = "ProductVariantAttributeValue", LocaleKey = property.LocaleKey, LocaleValue = property.LocaleValue, LanguageId = property.LanguageId }); } } } return(result); }
public new void SetUp() { #region Test data //color (dropdownlist) pa1 = new ProductAttribute { Id = 1, Name = "Color", }; pva1_1 = new ProductVariantAttribute { Id = 11, ProductId = 1, TextPrompt = "Select color:", IsRequired = true, AttributeControlType = AttributeControlType.DropdownList, DisplayOrder = 1, ProductAttribute = pa1, ProductAttributeId = pa1.Id }; pvav1_1 = new ProductVariantAttributeValue { Id = 11, Name = "Green", DisplayOrder = 1, ProductVariantAttribute = pva1_1, ProductVariantAttributeId = pva1_1.Id }; pvav1_2 = new ProductVariantAttributeValue { Id = 12, Name = "Red", DisplayOrder = 2, ProductVariantAttribute = pva1_1, ProductVariantAttributeId = pva1_1.Id }; pva1_1.ProductVariantAttributeValues.Add(pvav1_1); pva1_1.ProductVariantAttributeValues.Add(pvav1_2); //custom option (checkboxes) pa2 = new ProductAttribute { Id = 2, Name = "Some custom option", }; pva2_1 = new ProductVariantAttribute { Id = 21, ProductId = 1, TextPrompt = "Select at least one option:", IsRequired = true, AttributeControlType = AttributeControlType.Checkboxes, DisplayOrder = 2, ProductAttribute = pa2, ProductAttributeId = pa2.Id }; pvav2_1 = new ProductVariantAttributeValue { Id = 21, Name = "Option 1", DisplayOrder = 1, ProductVariantAttribute = pva2_1, ProductVariantAttributeId = pva2_1.Id }; pvav2_2 = new ProductVariantAttributeValue { Id = 22, Name = "Option 2", DisplayOrder = 2, ProductVariantAttribute = pva2_1, ProductVariantAttributeId = pva2_1.Id }; pva2_1.ProductVariantAttributeValues.Add(pvav2_1); pva2_1.ProductVariantAttributeValues.Add(pvav2_2); //custom text pa3 = new ProductAttribute { Id = 3, Name = "Custom text", }; pva3_1 = new ProductVariantAttribute { Id = 31, ProductId = 1, TextPrompt = "Enter custom text:", IsRequired = true, AttributeControlType = AttributeControlType.TextBox, DisplayOrder = 1, ProductAttribute = pa1, ProductAttributeId = pa3.Id }; #endregion _productAttributeRepo = MockRepository.GenerateMock <IRepository <ProductAttribute> >(); _productAttributeRepo.Expect(x => x.Table).Return(new List <ProductAttribute>() { pa1, pa2, pa3 }.AsQueryable()); _productAttributeRepo.Expect(x => x.GetById(pa1.Id)).Return(pa1); _productAttributeRepo.Expect(x => x.GetById(pa2.Id)).Return(pa2); _productAttributeRepo.Expect(x => x.GetById(pa3.Id)).Return(pa3); _productVariantAttributeRepo = MockRepository.GenerateMock <IRepository <ProductVariantAttribute> >(); _productVariantAttributeRepo.Expect(x => x.Table).Return(new List <ProductVariantAttribute>() { pva1_1, pva2_1, pva3_1 }.AsQueryable()); _productVariantAttributeRepo.Expect(x => x.GetById(pva1_1.Id)).Return(pva1_1); _productVariantAttributeRepo.Expect(x => x.GetById(pva2_1.Id)).Return(pva2_1); _productVariantAttributeRepo.Expect(x => x.GetById(pva3_1.Id)).Return(pva3_1); _productVariantAttributeCombinationRepo = MockRepository.GenerateMock <IRepository <ProductVariantAttributeCombination> >(); _productVariantAttributeCombinationRepo.Expect(x => x.Table).Return(new List <ProductVariantAttributeCombination>().AsQueryable()); _productVariantAttributeValueRepo = MockRepository.GenerateMock <IRepository <ProductVariantAttributeValue> >(); _productVariantAttributeValueRepo.Expect(x => x.Table).Return(new List <ProductVariantAttributeValue>() { pvav1_1, pvav1_2, pvav2_1, pvav2_2 }.AsQueryable()); _productVariantAttributeValueRepo.Expect(x => x.GetById(pvav1_1.Id)).Return(pvav1_1); _productVariantAttributeValueRepo.Expect(x => x.GetById(pvav1_2.Id)).Return(pvav1_2); _productVariantAttributeValueRepo.Expect(x => x.GetById(pvav2_1.Id)).Return(pvav2_1); _productVariantAttributeValueRepo.Expect(x => x.GetById(pvav2_2.Id)).Return(pvav2_2); _productBundleItemAttributeFilter = MockRepository.GenerateMock <IRepository <ProductBundleItemAttributeFilter> >(); _eventPublisher = MockRepository.GenerateMock <IEventPublisher>(); _eventPublisher.Expect(x => x.Publish(Arg <object> .Is.Anything)); _pictureService = MockRepository.GenerateMock <IPictureService>(); var cacheManager = new NullCache(); _productAttributeService = new ProductAttributeService(cacheManager, _productAttributeRepo, _productVariantAttributeRepo, _productVariantAttributeCombinationRepo, _productVariantAttributeValueRepo, _productBundleItemAttributeFilter, _eventPublisher, _pictureService); _productAttributeParser = new ProductAttributeParser(_productAttributeService, new MemoryRepository <ProductVariantAttributeCombination>(), NullCache.Instance); var workingLanguage = new Language(); _workContext = MockRepository.GenerateMock <IWorkContext>(); _workContext.Expect(x => x.WorkingLanguage).Return(workingLanguage); _currencyService = MockRepository.GenerateMock <ICurrencyService>(); _localizationService = MockRepository.GenerateMock <ILocalizationService>(); _localizationService.Expect(x => x.GetResource("GiftCardAttribute.For.Virtual")).Return("For: {0} <{1}>"); _localizationService.Expect(x => x.GetResource("GiftCardAttribute.From.Virtual")).Return("From: {0} <{1}>"); _localizationService.Expect(x => x.GetResource("GiftCardAttribute.For.Physical")).Return("For: {0}"); _localizationService.Expect(x => x.GetResource("GiftCardAttribute.From.Physical")).Return("From: {0}"); _taxService = MockRepository.GenerateMock <ITaxService>(); _priceFormatter = MockRepository.GenerateMock <IPriceFormatter>(); _downloadService = MockRepository.GenerateMock <IDownloadService>(); _webHelper = MockRepository.GenerateMock <IWebHelper>(); _priceCalculationService = MockRepository.GenerateMock <IPriceCalculationService>(); _shoppingCartSettings = MockRepository.GenerateMock <ShoppingCartSettings>(); _productAttributeFormatter = new ProductAttributeFormatter(_workContext, _productAttributeService, _productAttributeParser, _priceCalculationService, _currencyService, _localizationService, _taxService, _priceFormatter, _downloadService, _webHelper, _shoppingCartSettings); }
/// <summary> /// Create a copy of product variant with all depended data /// </summary> /// <param name="productVariant">The product variant to copy</param> /// <param name="productId">The product identifier</param> /// <param name="newName">The name of product variant duplicate</param> /// <param name="isPublished">A value indicating whether the product variant duplicate should be published</param> /// <param name="copyImage">A value indicating whether the product variant image should be copied</param> /// <returns>Product variant copy</returns> public virtual ProductVariant CopyProductVariant(ProductVariant productVariant, int productId, string newName, bool isPublished, bool copyImage) { if (productVariant == null) { throw new ArgumentNullException("productVariant"); } var languages = _languageService.GetAllLanguages(true); // product variant picture int pictureId = 0; if (copyImage) { 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 = productId, Name = newName, 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 = isPublished, 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, Sku = combination.Sku, ManufacturerPartNumber = combination.ManufacturerPartNumber, Gtin = combination.Gtin }; _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); return(productVariantCopy); }
private void ProcessAttributes(Product product, Product clone, IEnumerable <Language> languages) { using (var scope = new DbContextScope(lazyLoading: false, forceNoTracking: false)) { scope.LoadCollection(product, (Product p) => p.ProductVariantAttributes); scope.LoadCollection(product, (Product p) => p.ProductVariantAttributeCombinations); } // Former attribute id > clone. var pvaMap = new Dictionary <int, ProductVariantAttribute>(); // Former attribute value id > clone. var pvavMap = new Dictionary <int, ProductVariantAttributeValue>(); // Product attributes. foreach (var pva in product.ProductVariantAttributes) { var pvaClone = new ProductVariantAttribute { ProductId = clone.Id, ProductAttributeId = pva.ProductAttributeId, TextPrompt = pva.TextPrompt, IsRequired = pva.IsRequired, AttributeControlTypeId = pva.AttributeControlTypeId, DisplayOrder = pva.DisplayOrder }; _productAttributeService.InsertProductVariantAttribute(pvaClone); // Save associated value (used for combinations copying). pvaMap[pva.Id] = pvaClone; } // >>>>>> Commit attributes. Commit(); // Product variant attribute values. foreach (var pva in product.ProductVariantAttributes) { var pvaClone = pvaMap[pva.Id]; foreach (var pvav in pva.ProductVariantAttributeValues) { var pvavClone = new ProductVariantAttributeValue { ProductVariantAttributeId = pvaClone.Id, Name = pvav.Name, Color = pvav.Color, PriceAdjustment = pvav.PriceAdjustment, WeightAdjustment = pvav.WeightAdjustment, IsPreSelected = pvav.IsPreSelected, DisplayOrder = pvav.DisplayOrder, ValueTypeId = pvav.ValueTypeId, LinkedProductId = pvav.LinkedProductId, Quantity = pvav.Quantity, MediaFileId = pvav.MediaFileId }; _productAttributeService.InsertProductVariantAttributeValue(pvavClone); // Save associated value (used for combinations copying) pvavMap.Add(pvav.Id, pvavClone); } } // >>>>>> Commit attribute values. Commit(); // Attribute value localization. foreach (var pvav in product.ProductVariantAttributes.SelectMany(x => x.ProductVariantAttributeValues).ToArray()) { foreach (var lang in languages) { var name = pvav.GetLocalized(x => x.Name, lang, false, false); if (!string.IsNullOrEmpty(name)) { var pvavClone = pvavMap.Get(pvav.Id); if (pvavClone != null) { _localizedEntityService.SaveLocalizedValue(pvavClone, x => x.Name, name, lang.Id); } } } } // Attribute combinations. foreach (var combination in product.ProductVariantAttributeCombinations) { // Generate new AttributesXml according to new value IDs. string newAttributesXml = ""; var parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml); foreach (var oldPva in parsedProductVariantAttributes) { if (!pvaMap.ContainsKey(oldPva.Id)) { continue; } var newPva = pvaMap.Get(oldPva.Id); if (newPva == null) { continue; } var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id); foreach (var oldPvaValueStr in oldPvaValuesStr) { if (newPva.ShouldHaveValues()) { var oldPvaValue = oldPvaValueStr.ToInt(); if (pvavMap.ContainsKey(oldPvaValue)) { var newPvav = pvavMap.Get(oldPvaValue); if (newPvav != null) { newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString()); } } } else { // Simple text value. newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr); } } } var combinationClone = new ProductVariantAttributeCombination { ProductId = clone.Id, AttributesXml = newAttributesXml, StockQuantity = combination.StockQuantity, AllowOutOfStockOrders = combination.AllowOutOfStockOrders, Sku = combination.Sku, Gtin = combination.Gtin, ManufacturerPartNumber = combination.ManufacturerPartNumber, Price = combination.Price, AssignedMediaFileIds = combination.AssignedMediaFileIds, 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(combinationClone); } // >>>>>> Commit combinations. Commit(); }