public static moduleModel.CatalogProduct ToModuleModel(this webModel.Product product, IBlobUrlResolver blobUrlResolver) { var retVal = new moduleModel.CatalogProduct(); retVal.InjectFrom(product); retVal.SeoInfos = product.SeoInfos; if (product.Images != null) { retVal.Images = product.Images.Select(x => x.ToCoreModel()).ToList(); var index = 0; foreach (var image in retVal.Images) { image.SortOrder = index++; } } if (product.Assets != null) { retVal.Assets = product.Assets.Select(x => x.ToCoreModel()).ToList(); } if (product.Properties != null) { retVal.PropertyValues = new List <moduleModel.PropertyValue>(); foreach (var property in product.Properties) { foreach (var propValue in property.Values) { //Need populate required fields propValue.PropertyName = property.Name; propValue.ValueType = property.ValueType; retVal.PropertyValues.Add(propValue.ToModuleModel()); } } } if (product.Variations != null) { retVal.Variations = product.Variations.Select(x => x.ToModuleModel(blobUrlResolver)).ToList(); } if (product.Links != null) { retVal.Links = product.Links.Select(x => x.ToModuleModel()).ToList(); } if (product.Reviews != null) { retVal.Reviews = product.Reviews.Select(x => x.ToModuleModel()).ToList(); } if (product.Associations != null) { retVal.Associations = product.Associations.Select(x => x.ToModuleModel()).ToList(); } retVal.MainProductId = product.TitularItemId; return(retVal); }
//initial version of product converter to amazon product. //it should be adopted to the particular customer needs as many Amazon properties (like category) are unique and can't be mapped automatically. public static Product ToAmazonModel(this moduleModel.CatalogProduct product, IBlobUrlResolver assetUrlResolver, moduleModel.Property[] properties = null) { var amazonProduct = new Product(); amazonProduct.InjectFrom(product); amazonProduct.DescriptionData = new ProductDescriptionData { Brand = "Brand", Description = "Product description", }; amazonProduct.Condition = new ConditionInfo { ConditionType = ConditionType.New }; if (product.Images != null && product.Images.Any()) { amazonProduct.ExternalProductUrl = assetUrlResolver.GetAbsoluteUrl(product.Images.First().Url.TrimStart('/')); } amazonProduct.SKU = product.Code; amazonProduct.StandardProductID = new StandardProductID { Value = amazonProduct.SKU, Type = StandardProductIDType.ASIN }; //var mainCat = new Home(); //var subCat = new Kitchen(); //mainCat.ProductType = new HomeProductType { Item = subCat }; //amazonProduct.ProductData = new ProductProductData { Item = mainCat }; return(amazonProduct); }
public static moduleModel.CatalogProduct ToModuleModel(this googleModel.Product product, IBlobUrlResolver assetUrlResolver) { var retVal = new moduleModel.CatalogProduct(); retVal.InjectFrom(product); return retVal; }
public coreModel.CatalogProduct Create(coreModel.CatalogProduct item) { Create(new[] { item }); var retVal = GetById(item.Id, coreModel.ItemResponseGroup.ItemLarge); return(retVal); }
public static moduleModel.CatalogProduct ToModuleModel(this googleModel.Product product, IBlobUrlResolver assetUrlResolver) { var retVal = new moduleModel.CatalogProduct(); retVal.InjectFrom(product); return(retVal); }
public coreModel.CatalogProduct Create(coreModel.CatalogProduct item) { var dbItem = item.ToDataModel(); using (var repository = _catalogRepositoryFactory()) { repository.Add(dbItem); item.Id = dbItem.Id; if (item.Variations != null) { foreach (var variation in item.Variations) { variation.MainProductId = dbItem.Id; variation.MainProduct = item; variation.CatalogId = dbItem.CatalogId; var dbVariation = variation.ToDataModel(); repository.Add(dbVariation); variation.Id = dbVariation.Id; } } CommitChanges(repository); } //Need add seo separately if (item.SeoInfos != null) { foreach (var seoInfo in item.SeoInfos) { seoInfo.ObjectId = dbItem.Id; seoInfo.ObjectType = typeof(coreModel.CatalogProduct).Name; _commerceService.UpsertSeo(seoInfo); } } if (item.Variations != null) { foreach (var variation in item.Variations) { if (variation.SeoInfos != null) { foreach (var seoInfo in variation.SeoInfos) { seoInfo.ObjectId = variation.Id; seoInfo.ObjectType = typeof(coreModel.CatalogProduct).Name; _commerceService.UpsertSeo(seoInfo); } } } } var retVal = GetById(dbItem.Id, coreModel.ItemResponseGroup.ItemLarge); return(retVal); }
private coreModel.Property[] GetAllProductProperies(coreModel.CatalogProduct product) { coreModel.Property[] retVal = null; if (!String.IsNullOrEmpty(product.CategoryId)) { retVal = _propertyService.GetCategoryProperties(product.CategoryId); } else { retVal = _propertyService.GetCatalogProperties(product.CatalogId); } return(retVal); }
public static googleModel.Product ToGoogleModel(this moduleModel.CatalogProduct product, IBlobUrlResolver assetUrlResolver, moduleModel.Property[] properties = null) { var retVal = new googleModel.Product(); retVal.InjectFrom(product); var langCode = product.Catalog.Languages.First().LanguageCode; retVal.Link = @"http://virtocommerce-test.azurewebsites.net/"; retVal.OfferId = product.Id; retVal.Title = product.Name; retVal.Description = product.Reviews.Any() ? product.Reviews.First(x => x.LanguageCode == langCode).Content : product.Name; retVal.Link = @"http://virtocommerce-test.azurewebsites.net/"; retVal.ImageLink = assetUrlResolver.GetAbsoluteUrl(product.Assets.First().Url).TrimStart('/'); retVal.ContentLanguage = langCode; retVal.TargetCountry = "US"; retVal.Channel = "online"; retVal.Availability = "in stock"; retVal.Condition = "new"; retVal.GoogleProductCategory = "Media > Books"; retVal.Gtin = "9780007350896"; retVal.Taxes = new[] { new googleModel.ProductTax { Country = "US", Rate = 10, Region = "CA" } }; retVal.Shipping = new[] { new googleModel.ProductShipping { Country = "US", Price = new googleModel.Price { Currency = "USD", Value = "5" } } }; return(retVal); }
public CsvProduct(CatalogProduct product, IBlobUrlResolver blobUrlResolver, Price price, InventoryInfo inventory) : this() { _blobUrlResolver = blobUrlResolver; this.InjectFrom(product); PropertyValues = product.PropertyValues; Images = product.Images; Assets = product.Assets; Links = product.Links; Variations = product.Variations; SeoInfos = product.SeoInfos; Reviews = product.Reviews; Associations = product.Associations; if (price != null) { Price = price; } if (inventory != null) { Inventory = inventory; } }
/// <summary> /// Converting to model type /// </summary> /// <returns></returns> public static coreModel.CatalogProduct ToCoreModel(this dataModel.Item dbItem, bool convertChildrens = true) { var retVal = new coreModel.CatalogProduct(); retVal.InjectFrom(dbItem); retVal.Catalog = dbItem.Catalog.ToCoreModel(); if (dbItem.Category != null) { retVal.Category = dbItem.Category.ToCoreModel(); } retVal.MainProductId = dbItem.ParentId; if(dbItem.Parent != null) { retVal.MainProduct = dbItem.Parent.ToCoreModel(convertChildrens: false); } retVal.IsActive = dbItem.IsActive; retVal.IsBuyable = dbItem.IsBuyable; retVal.TrackInventory = dbItem.TrackInventory; retVal.MaxQuantity = (int)dbItem.MaxQuantity; retVal.MinQuantity = (int)dbItem.MinQuantity; //Links retVal.Links = dbItem.CategoryLinks.Select(x => x.ToCoreModel()).ToList(); //Images retVal.Images = dbItem.Images.OrderBy(x => x.SortOrder).Select(x => x.ToCoreModel()).ToList(); //Inherit images from parent product (if its not set) if(!retVal.Images.Any() && retVal.MainProduct != null && retVal.MainProduct.Images != null) { retVal.Images = retVal.MainProduct.Images.Select(x=>x.Clone()).OfType<coreModel.Image>().ToList(); foreach(var image in retVal.Images) { image.Id = null; image.IsInherited = true; } } //Assets retVal.Assets = dbItem.Assets.OrderBy(x => x.CreatedDate).Select(x => x.ToCoreModel()).ToList(); //Inherit images from parent product (if its not set) if (!retVal.Assets.Any() && retVal.MainProduct != null && retVal.MainProduct.Assets != null) { retVal.Assets = retVal.MainProduct.Assets.Select(x => x.Clone()).OfType<coreModel.Asset>().ToList(); foreach (var asset in retVal.Assets) { asset.Id = null; asset.IsInherited = true; } } // EditorialReviews retVal.Reviews = dbItem.EditorialReviews.Select(x => x.ToCoreModel()).ToList(); //inherit editorial reviews from main product and do not inherit if variation loaded within product if (!retVal.Reviews.Any() && retVal.MainProduct != null && retVal.MainProduct.Reviews != null && convertChildrens) { retVal.Reviews = retVal.MainProduct.Reviews.Select(x => x.Clone()).OfType<coreModel.EditorialReview>().ToList(); foreach (var review in retVal.Reviews) { review.Id = null; review.IsInherited = true; } } // Associations retVal.Associations = dbItem.AssociationGroups.SelectMany(x => x.Associations).Select(x => x.ToCoreModel()).ToList(); //TaxType category inheritance if (retVal.TaxType == null && retVal.Category != null) { retVal.TaxType = retVal.Category.TaxType; } retVal.Properties = new List<coreModel.Property>(); //Properties inheritance if (retVal.Category != null) { //Add inherited from category and catalog properties retVal.Properties.AddRange(retVal.Category.Properties); } else { retVal.Properties.AddRange(retVal.Catalog.Properties); } foreach(var property in retVal.Properties) { property.IsInherited = true; } //Self item property values retVal.PropertyValues = dbItem.ItemPropertyValues.OrderBy(x => x.Name).Select(x => x.ToCoreModel()).ToList(); foreach (var propertyValue in retVal.PropertyValues.ToArray()) { //Try to find property meta information propertyValue.Property = retVal.Properties.FirstOrDefault(x => x.IsSuitableForValue(propertyValue)); //Return each localized value for selected dictionary value //Because multilingual dictionary values for all languages may not stored in db need add it in result manually from property dictionary values var localizedDictValues = propertyValue.TryGetAllLocalizedDictValues(); foreach (var localizedDictValue in localizedDictValues) { if (!retVal.PropertyValues.Any(x => x.ValueId == localizedDictValue.ValueId && x.LanguageCode == localizedDictValue.LanguageCode)) { retVal.PropertyValues.Add(localizedDictValue); } } } //inherit not overriden property values from main product if (retVal.MainProduct != null && retVal.MainProduct.PropertyValues != null) { var mainProductPopValuesGroups = retVal.MainProduct.PropertyValues.GroupBy(x => x.PropertyName); foreach (var group in mainProductPopValuesGroups) { //Inherit all values if not overriden if (!retVal.PropertyValues.Any(x => String.Equals(x.PropertyName, group.Key, StringComparison.InvariantCultureIgnoreCase))) { foreach (var inheritedpropValue in group) { inheritedpropValue.Id = null; inheritedpropValue.IsInherited = true; retVal.PropertyValues.Add(inheritedpropValue); } } } } if (convertChildrens) { // Variations retVal.Variations = new List<coreModel.CatalogProduct>(); foreach (var variation in dbItem.Childrens) { var productVariation = variation.ToCoreModel(convertChildrens: false); productVariation.MainProduct = retVal; productVariation.MainProductId = retVal.Id; retVal.Variations.Add(productVariation); } } return retVal; }
protected virtual void IndexItemPrices(ref ResultDocument doc, CatalogProduct item) { var evalContext = new Domain.Pricing.Model.PriceEvaluationContext { ProductIds = new[] { item.Id } }; var prices = _pricingService.EvaluateProductPrices(evalContext); foreach (var price in prices) { //var priceList = price.Pricelist; doc.Add(new DocumentField(string.Format("price_{0}_{1}", price.Currency, price.PricelistId), price.EffectiveValue, new[] { IndexStore.No, IndexType.NotAnalyzed })); doc.Add(new DocumentField(string.Format("price_{0}_{1}_value", price.Currency, price.PricelistId), (price.EffectiveValue).ToString(CultureInfo.InvariantCulture), new[] { IndexStore.Yes, IndexType.NotAnalyzed })); } }
protected virtual void IndexItemCustomProperties(ref ResultDocument doc, CatalogProduct item) { var properties = item.CategoryId != null ? _propertyService.GetCategoryProperties(item.CategoryId) : _propertyService.GetCatalogProperties(item.CatalogId); foreach (var propValue in item.PropertyValues.Where(x => x.Value != null)) { var property = properties.FirstOrDefault(x => string.Equals(x.Name, propValue.PropertyName, StringComparison.InvariantCultureIgnoreCase) && x.ValueType == propValue.ValueType); var contentField = string.Format("__content{0}", property != null && (property.Multilanguage && !string.IsNullOrWhiteSpace(propValue.LanguageCode)) ? "_" + propValue.LanguageCode.ToLower() : string.Empty); switch (propValue.ValueType) { case PropertyValueType.LongText: case PropertyValueType.ShortText: var stringValue = propValue.Value.ToString(); if (!string.IsNullOrWhiteSpace(stringValue)) // don't index empty values { doc.Add(new DocumentField(contentField, stringValue.ToLower(), new[] { IndexStore.Yes, IndexType.Analyzed, IndexDataType.StringCollection })); } break; } if (doc.ContainsKey(propValue.PropertyName)) continue; switch (propValue.ValueType) { case PropertyValueType.Boolean: case PropertyValueType.DateTime: case PropertyValueType.Number: doc.Add(new DocumentField(propValue.PropertyName, propValue.Value, new[] { IndexStore.Yes, IndexType.Analyzed })); break; case PropertyValueType.LongText: case PropertyValueType.ShortText: doc.Add(new DocumentField(propValue.PropertyName, propValue.Value.ToString().ToLower(), new[] { IndexStore.Yes, IndexType.Analyzed })); break; } } }
protected virtual void IndexItemCustomProperties(ref ResultDocument doc, CatalogProduct item) { var properties = item.Properties; foreach (var propValue in item.PropertyValues.Where(x => x.Value != null)) { var propertyName = propValue.PropertyName.ToLower(); var property = properties.FirstOrDefault(x => string.Equals(x.Name, propValue.PropertyName, StringComparison.InvariantCultureIgnoreCase) && x.ValueType == propValue.ValueType); var contentField = string.Concat("__content", property != null && property.Multilanguage && !string.IsNullOrWhiteSpace(propValue.LanguageCode) ? "_" + propValue.LanguageCode.ToLower() : string.Empty); switch (propValue.ValueType) { case PropertyValueType.LongText: case PropertyValueType.ShortText: var stringValue = propValue.Value.ToString(); if (!string.IsNullOrWhiteSpace(stringValue)) // don't index empty values { doc.Add(new DocumentField(contentField, stringValue.ToLower(), new[] { IndexStore.Yes, IndexType.Analyzed, IndexDataType.StringCollection })); } break; } switch (propValue.ValueType) { case PropertyValueType.Boolean: case PropertyValueType.DateTime: case PropertyValueType.Number: doc.Add(new DocumentField(propertyName, propValue.Value, new[] { IndexStore.Yes, IndexType.Analyzed })); break; case PropertyValueType.LongText: doc.Add(new DocumentField(propertyName, propValue.Value.ToString().ToLowerInvariant(), new[] { IndexStore.Yes, IndexType.Analyzed })); break; case PropertyValueType.ShortText: // do not tokenize small values as they will be used for lookups and filters doc.Add(new DocumentField(propertyName, propValue.Value.ToString(), new[] { IndexStore.Yes, IndexType.NotAnalyzed })); break; } } }
public static webModel.Product ToWebModel(this moduleModel.CatalogProduct product, IBlobUrlResolver blobUrlResolver, moduleModel.Property[] properties = null) { var retVal = new webModel.Product(); retVal.InjectFrom(product); retVal.SeoInfos = product.SeoInfos; if (product.Catalog != null) { retVal.Catalog = product.Catalog.ToWebModel(); } if (product.Category != null) { retVal.Category = product.Category.ToWebModel(); } if (product.Assets != null) { var assetBases = product.Assets.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); retVal.Images = assetBases.OfType <webModel.ProductImage>().ToList(); retVal.Assets = assetBases.OfType <webModel.ProductAsset>().ToList(); } if (product.Variations != null) { retVal.Variations = product.Variations.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.Links != null) { retVal.Links = product.Links.Select(x => x.ToWebModel()).ToList(); } if (product.Reviews != null) { retVal.Reviews = product.Reviews.Select(x => x.ToWebModel()).ToList(); } if (product.Associations != null) { retVal.Associations = product.Associations.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } retVal.TitularItemId = product.MainProductId; retVal.Properties = new List <webModel.Property>(); //Need add property for each meta info if (properties != null) { foreach (var property in properties) { var webModelProperty = property.ToWebModel(); webModelProperty.Category = null; webModelProperty.Values = new List <webModel.PropertyValue>(); webModelProperty.IsManageable = true; webModelProperty.IsReadOnly = property.Type != moduleModel.PropertyType.Product && property.Type != moduleModel.PropertyType.Variation; retVal.Properties.Add(webModelProperty); } } //Populate property values if (product.PropertyValues != null) { foreach (var propValue in product.PropertyValues.Select(x => x.ToWebModel())) { var property = retVal.Properties.FirstOrDefault(x => x.IsSuitableForValue(propValue)); if (property == null) { //Need add dummy property for each value without property property = new webModel.Property(propValue, product.CatalogId, product.CategoryId, moduleModel.PropertyType.Product); retVal.Properties.Add(property); } property.Values.Add(propValue); } } return(retVal); }
public static webModel.CatalogItem ToWebModel(this coreModel.CatalogProduct product, IBlobUrlResolver blobUrlResolver = null, coreModel.Property[] properties = null, coreInvModel.InventoryInfo inventory = null) { webModel.CatalogItem retVal = new webModel.Product(); if (product.MainProductId != null) { retVal = new webModel.ProductVariation(); } retVal.InjectFrom(product); if (product.Images != null && product.Images.Any()) { //Back compability check group to detect primary image (remove later) var primaryImage = product.Images.FirstOrDefault(x => String.Equals(x.Group, "primaryimage", StringComparison.InvariantCultureIgnoreCase)); if (primaryImage == null) { primaryImage = product.Images.OrderBy(x => x.SortOrder).First(); } retVal.PrimaryImage = primaryImage.ToWebModel(blobUrlResolver); retVal.Images = product.Images.Skip(1).Select(x => x.ToWebModel(blobUrlResolver)).ToArray(); } if (product.Assets != null) { retVal.Assets = product.Assets.Select(x => x.ToWebModel(blobUrlResolver)).ToArray(); } if (product.Variations != null && product.Variations.Any()) { ((webModel.Product)retVal).Variations = product.Variations.Select(x => x.ToWebModel(blobUrlResolver, properties)) .OfType <webModel.ProductVariation>() .ToArray(); } if (product.Reviews != null) { retVal.EditorialReviews = product.Reviews.Select(x => new webModel.EditorialReview().InjectFrom(x)) .Cast <webModel.EditorialReview>() .ToArray(); } if (product.SeoInfos != null) { retVal.Seo = product.SeoInfos.Select(x => x.ToWebModel()).ToArray(); } if (product.Associations != null && product.Associations.Any()) { retVal.Associations = product.Associations.Select(x => x.ToWebModel()).ToArray(); } if (product.PropertyValues != null) { retVal.Properties = new webModel.PropertyDictionary(); retVal.VariationProperties = new webModel.PropertyDictionary(); // dictionary properties are returned as object[], all other properties are returned as primitives foreach (var propValueGroup in product.PropertyValues.GroupBy(x => x.PropertyName)) { var displayName = propValueGroup.Key; var propertyValue = propValueGroup.FirstOrDefault(x => x.Value != null); var propertyCollection = retVal.Properties; if (propertyValue != null) { if (properties != null) { var propertyMetaInfo = properties.FirstOrDefault(x => string.Equals(propValueGroup.Key, x.Name, StringComparison.OrdinalIgnoreCase)); if (propertyMetaInfo != null && propertyMetaInfo.DisplayNames != null) { //TODO: use display name for specific language displayName = propertyMetaInfo.DisplayNames.Select(x => x.Name).FirstOrDefault(x => !String.IsNullOrEmpty(x)) ?? displayName; } if (propertyMetaInfo != null && propertyMetaInfo.Type == coreModel.PropertyType.Variation) { propertyCollection = retVal.VariationProperties; } } propertyCollection.Add(displayName, propertyValue.Value); } } } if (inventory != null) { retVal.Inventory = inventory.ToWebModel(); } return(retVal); }
/// <summary> /// Add variation to given product + asset + icon + properties /// </summary> private PublishingResult AddVariation(CatalogProduct product, ModuleManifest manifest, byte[] icon, string zipModulePath, PublishingResult publishingResult) { //add variation + asset var variationCode = string.Format("{0}_{1}", manifest.Id, manifest.Version); variationCode = Regex.Replace(variationCode, @"[^A-Za-z0-9_]", "_"); var variation = product.Variations.Where(x=>x.Code == variationCode).FirstOrDefault(); if (variation == null) { variation = new CatalogProduct { Name = string.Format("{0} ({1})", manifest.Title, manifest.Version), Code = variationCode, MainProductId = product.Id, CategoryId = product.CategoryId, CatalogId = product.CatalogId, }; AddProperty(variation, "Description", manifest.Description, PropertyValueType.LongText); AddProperty(variation, "ReleaseNote", manifest.ReleaseNotes, PropertyValueType.LongText); AddProperty(variation, "ReleaseVersion", manifest.Version, PropertyValueType.ShortText); AddProperty(variation, "Compatibility", manifest.PlatformVersion, PropertyValueType.ShortText); AddProperty(variation, "ReleaseDate", DateTime.UtcNow, PropertyValueType.DateTime); AddAsset(variation, zipModulePath); if (publishingResult == PublishingResult.None) { AddIcon(variation, Path.GetExtension(manifest.IconUrl), icon); publishingResult = PublishingResult.Variation; } _productService.Create(variation); } return publishingResult; }
/// <summary> /// Publish given module to AppStore catalog /// </summary> private PublishingResult Publish(ModuleManifest manifest, string zipModulePath, byte[] icon) { var publishingResult = PublishingResult.None; var productCode = manifest.Id; productCode = Regex.Replace(productCode, @"[^A-Za-z0-9_]", "_"); var product = GetProductByCode(productCode, _defaultCategory.Catalog.Id); if (product == null) { //add product product = new CatalogProduct { Name = manifest.Title, Code = productCode, CategoryId = _defaultCategory.Id, CatalogId = _defaultCategory.CatalogId, IsActive = false, IsBuyable = false }; if (!string.IsNullOrEmpty(manifest.Description)) { AddProperty(product, "Description", manifest.Description, PropertyValueType.LongText); } if (!string.IsNullOrEmpty(manifest.IconUrl)) { AddIcon(product, Path.GetExtension(manifest.IconUrl), icon); } product = _productService.Create(product); publishingResult = PublishingResult.Product; } return AddVariation(product, manifest, icon, zipModulePath, publishingResult); }
/// <summary> /// Add icon to given product /// </summary> private void AddIcon(CatalogProduct product, string extention, byte[] icon) { if (icon != null) { using (MemoryStream ms = new MemoryStream(icon)) { var blobRelativeUrl = Path.Combine("catalog", product.Code, HttpUtility.UrlDecode(Path.ChangeExtension("icon", extention))); using (var targetStream = _blobStorageProvider.OpenWrite(blobRelativeUrl)) { ms.CopyTo(targetStream); } product.Images = new List<Image> { new Image { Url = blobRelativeUrl } }; } } }
public void ImportProductsTest() { var catalogId = "57b2ed0c42a94eb88f1c7b97afaf183d"; var product = new coreModel.CatalogProduct(); //Auto detect mapping configuration var mappingConfiguration = new string[] { "Name", "Code", "Category", "Reviews" }.Select(x => new webModel.CsvImportMappingItem { EntityColumnName = x }).ToArray(); DoAutoMapping(mappingConfiguration); //Edit mapping configuration in UI var reviewMappingItem = mappingConfiguration.First(x => x.EntityColumnName == "Reviews"); reviewMappingItem.CsvColumnName = "Reviews"; //Start import //read objects from csv use mapping configuration var csvProducts = new List <CatalogProduct>(); using (var reader = new CsvReader(new StreamReader(@"c:\Projects\VCF\vc-community\PLATFORM\Modules\Catalog\VirtoCommerce.CatalogModule.Test\products.csv"))) { reader.Configuration.Delimiter = ";"; var initialized = false; while (reader.Read()) { if (!initialized) { var productMap = new ProductMap(reader.FieldHeaders, mappingConfiguration); reader.Configuration.RegisterClassMap(productMap); initialized = true; } var csvProduct = reader.GetRecord <coreModel.CatalogProduct>(); csvProducts.Add(csvProduct); } }; var categories = new List <coreModel.Category>(); //project product information to category structure (categories, properties etc) foreach (var csvProduct in csvProducts) { var productCategoryNames = csvProduct.Category.Path.Split('/'); ICollection <coreModel.Category> levelCategories = categories; foreach (var categoryName in productCategoryNames) { var category = levelCategories.FirstOrDefault(x => x.Name == categoryName); if (category == null) { category = new coreModel.Category() { Name = categoryName, Code = categoryName.GenerateSlug() }; category.CatalogId = catalogId; category.Children = new List <coreModel.Category>(); levelCategories.Add(category); } csvProduct.Category = category; levelCategories = category.Children; } } var categoryService = GetCategoryService(); var newCategories = new List <coreModel.Category>(); //save to db //Categories foreach (var category in categories) { var newCategory = categoryService.Create(category); newCategories.Add(newCategory); foreach (var childCategory in category.Traverse(x => x.Children)) { newCategory = categoryService.Create(childCategory); newCategories.Add(newCategory); } } var productService = GetItemService(); //Products foreach (var csvProduct in csvProducts) { var sameProduct = csvProducts.FirstOrDefault(x => x.Name == csvProduct.Name && !x.IsTransient()); if (sameProduct != null) { //Detect variation csvProduct.MainProductId = sameProduct.Id; } var category = newCategories.FirstOrDefault(x => x.Code == csvProduct.Category.Code); csvProduct.CategoryId = category.Id; csvProduct.CatalogId = catalogId; var newProduct = productService.Create(csvProduct); csvProduct.Id = newProduct.Id; } }
public static moduleModel.CatalogProduct ToModuleModel(this webModel.Product product, IBlobUrlResolver blobUrlResolver) { var retVal = new moduleModel.CatalogProduct(); retVal.InjectFrom(product); retVal.SeoInfos = product.SeoInfos; if (product.Images != null) { retVal.Images = product.Images.Select(x => x.ToCoreModel()).ToList(); var index = 0; foreach(var image in retVal.Images) { image.SortOrder = index++; } } if (product.Assets != null) { retVal.Assets = product.Assets.Select(x => x.ToCoreModel()).ToList(); } if (product.Properties != null) { retVal.PropertyValues = new List<moduleModel.PropertyValue>(); foreach (var property in product.Properties) { foreach (var propValue in property.Values) { //Need populate required fields propValue.PropertyName = property.Name; propValue.ValueType = property.ValueType; retVal.PropertyValues.Add(propValue.ToModuleModel()); } } } if (product.Variations != null) { retVal.Variations = product.Variations.Select(x => x.ToModuleModel(blobUrlResolver)).ToList(); } if (product.Links != null) { retVal.Links = product.Links.Select(x => x.ToModuleModel()).ToList(); } if (product.Reviews != null) { retVal.Reviews = product.Reviews.Select(x => x.ToModuleModel()).ToList(); } if (product.Associations != null) { retVal.Associations = product.Associations.Select(x => x.ToModuleModel()).ToList(); } retVal.MainProductId = product.TitularItemId; return retVal; }
public void WorkingWithItemTest() { var itemService = GetItemService(); var catalogService = GetCatalogService(); var categoryService = GetCategoryService(); var propertyService = GetPropertyService(); var category = categoryService.GetById("a8bfc7cd-4363-4f12-976e-3f236433b6cf"); //Add product property to category //var productProperty = new Property //{ // CategoryId = category.Id, // CatalogId = category.Catalog.Id, // Name = "testProp", // Type = PropertyType.Product, // ValueType = PropertyValueType.ShortText //}; //productProperty = propertyService.Create(productProperty); var productProperty = propertyService.GetCategoryProperties(category.Id) .Where(x=>x.Type == PropertyType.Product).FirstOrDefault(); var productPropValue = new PropertyValue { //Property = productProperty, PropertyId = productProperty.Id, Value = "some value", PropertyName = productProperty.Name }; var product = new CatalogProduct { Name = "TestProduct", Code = "Code", CatalogId = category.CatalogId, CategoryId = category.Id }; product.PropertyValues = new List<PropertyValue>(); product.PropertyValues.Add(productPropValue); product = itemService.Create(product); }
public static webModel.CatalogItem ToWebModel(this coreModel.CatalogProduct product, IBlobUrlResolver blobUrlResolver = null, coreModel.Property[] properties = null) { webModel.CatalogItem retVal = new webModel.Product(); if (product.MainProductId != null) { retVal = new webModel.ProductVariation(); } retVal.InjectFrom(product); if (product.Assets != null) { retVal.Images = product.Assets.Where(x => x.Type == coreModel.ItemAssetType.Image) .Select(x => x.ToImageWebModel(blobUrlResolver)) .ToArray(); retVal.Assets = product.Assets.Where(x => x.Type == coreModel.ItemAssetType.File) .Select(x => x.ToAssetWebModel(blobUrlResolver)) .ToArray(); } if (product.Variations != null && product.Variations.Any()) { ((webModel.Product)retVal).Variations = product.Variations.Select(x => x.ToWebModel(blobUrlResolver, properties)) .OfType <webModel.ProductVariation>() .ToArray(); } if (product.Reviews != null) { retVal.EditorialReviews = product.Reviews.Select(x => new webModel.EditorialReview().InjectFrom(x)) .Cast <webModel.EditorialReview>() .ToArray(); } if (product.Links != null) { retVal.Categories = product.Links.Select(x => x.CategoryId).ToArray(); } if (product.SeoInfos != null) { retVal.Seo = product.SeoInfos.Select(x => x.ToWebModel()).ToArray(); } if (product.Associations != null && product.Associations.Any()) { retVal.Associations = product.Associations.Select(x => x.ToWebModel()).ToArray(); } if (product.PropertyValues != null) { retVal.Properties = new webModel.PropertyDictionary(); retVal.VariationProperties = new webModel.PropertyDictionary(); // dictionary properties are returned as object[], all other properties are returned as primitives foreach (var propValueGroup in product.PropertyValues.GroupBy(x => x.PropertyName)) { var displayName = propValueGroup.Key; var propertyValue = propValueGroup.FirstOrDefault(x => x.Value != null); var propertyCollection = retVal.Properties; if (propertyValue != null) { if (properties != null) { var propertyMetaInfo = properties.FirstOrDefault(x => string.Equals(propValueGroup.Key, x.Name, StringComparison.OrdinalIgnoreCase)); if (propertyMetaInfo != null && propertyMetaInfo.DisplayNames != null) { //TODO: use display name for specific language displayName = propertyMetaInfo.DisplayNames.Select(x => x.Name).FirstOrDefault(x => !String.IsNullOrEmpty(x)) ?? displayName; } if (propertyMetaInfo != null && propertyMetaInfo.Type == coreModel.PropertyType.Variation) { propertyCollection = retVal.VariationProperties; } } propertyCollection.Add(displayName, propertyValue.Value); } } } return(retVal); }
/// <summary> /// Converting to foundation type /// </summary> /// <param name="catalog"></param> /// <returns></returns> public static dataModel.CategoryItemRelation ToDataModel(this coreModel.CategoryLink categoryLink, coreModel.CatalogProduct product) { var retVal = new dataModel.CategoryItemRelation { CategoryId = categoryLink.CategoryId, ItemId = product.Id, CatalogId = categoryLink.CatalogId, Priority = 100 }; return(retVal); }
/// <summary> /// Converting to model type /// </summary> /// <param name="catalogBase"></param> /// <returns></returns> public static coreModel.ProductAssociation ToCoreModel(this dataModel.Association dbAssociation, coreModel.CatalogProduct associatedProduct) { if (dbAssociation == null) { throw new ArgumentNullException("dbAssociation"); } var retVal = new coreModel.ProductAssociation { Name = dbAssociation.AssociationGroup.Name, Description = dbAssociation.AssociationGroup.Description, Priority = dbAssociation.Priority, AssociatedProductId = associatedProduct.Id, Type = dbAssociation.AssociationType, AssociatedProduct = associatedProduct }; return(retVal); }
/// <summary> /// Converting to model type /// </summary> /// <returns></returns> public static coreModel.CatalogProduct ToCoreModel(this dataModel.Item dbItem, dataModel.Catalog[] allCatalogs, dataModel.Category[] allCategories, bool convertChildrens = true) { var retVal = new coreModel.CatalogProduct(); retVal.InjectFrom(dbItem); retVal.Catalog = allCatalogs.First(x => x.Id == dbItem.CatalogId).ToCoreModel(); if (dbItem.CategoryId != null) { retVal.Category = allCategories.First(x => x.Id == dbItem.CategoryId) .ToCoreModel(allCatalogs, allCategories); } retVal.MainProductId = dbItem.ParentId; if (dbItem.Parent != null) { retVal.MainProduct = dbItem.Parent.ToCoreModel(allCatalogs, allCategories, convertChildrens: false); } retVal.IsActive = dbItem.IsActive; retVal.IsBuyable = dbItem.IsBuyable; retVal.TrackInventory = dbItem.TrackInventory; retVal.MaxQuantity = (int)dbItem.MaxQuantity; retVal.MinQuantity = (int)dbItem.MinQuantity; //Links retVal.Links = dbItem.CategoryLinks.Select(x => x.ToCoreModel(allCatalogs, allCategories)).ToList(); //Images retVal.Images = dbItem.Images.OrderBy(x => x.SortOrder).Select(x => x.ToCoreModel()).ToList(); //Inherit images from parent product (if its not set) if (!retVal.Images.Any() && retVal.MainProduct != null && retVal.MainProduct.Images != null) { retVal.Images = retVal.MainProduct.Images.Select(x => x.Clone()).OfType <coreModel.Image>().ToList(); foreach (var image in retVal.Images) { image.Id = null; image.IsInherited = true; } } //Assets retVal.Assets = dbItem.Assets.OrderBy(x => x.CreatedDate).Select(x => x.ToCoreModel()).ToList(); //Inherit images from parent product (if its not set) if (!retVal.Assets.Any() && retVal.MainProduct != null && retVal.MainProduct.Assets != null) { retVal.Assets = retVal.MainProduct.Assets.Select(x => x.Clone()).OfType <coreModel.Asset>().ToList(); foreach (var asset in retVal.Assets) { asset.Id = null; asset.IsInherited = true; } } // EditorialReviews retVal.Reviews = dbItem.EditorialReviews.Select(x => x.ToCoreModel()).ToList(); //inherit editorial reviews from main product and do not inherit if variation loaded within product if (!retVal.Reviews.Any() && retVal.MainProduct != null && retVal.MainProduct.Reviews != null && convertChildrens) { retVal.Reviews = retVal.MainProduct.Reviews.Select(x => x.Clone()).OfType <coreModel.EditorialReview>().ToList(); foreach (var review in retVal.Reviews) { review.Id = null; review.IsInherited = true; } } // Associations retVal.Associations = dbItem.Associations.Select(x => x.ToCoreModel(allCatalogs, allCategories)).OrderBy(x => x.Priority).ToList(); //TaxType category inheritance if (retVal.TaxType == null && retVal.Category != null) { retVal.TaxType = retVal.Category.TaxType; } retVal.Properties = new List <coreModel.Property>(); //Properties inheritance retVal.Properties.AddRange(retVal.Category != null ? retVal.Category.Properties : retVal.Catalog.Properties); foreach (var property in retVal.Properties) { property.IsInherited = true; } //Sort properties by name retVal.Properties = retVal.Properties.OrderBy(x => x.Name).ToList(); //Self item property values retVal.PropertyValues = dbItem.ItemPropertyValues.OrderBy(x => x.Name).Select(x => x.ToCoreModel()).ToList(); foreach (var propertyValue in retVal.PropertyValues.ToArray()) { //Try to find property meta information propertyValue.Property = retVal.Properties.FirstOrDefault(x => x.IsSuitableForValue(propertyValue)); //Return each localized value for selected dictionary value //Because multilingual dictionary values for all languages may not stored in db need add it in result manually from property dictionary values var localizedDictValues = propertyValue.TryGetAllLocalizedDictValues(); foreach (var localizedDictValue in localizedDictValues) { if (!retVal.PropertyValues.Any(x => x.ValueId == localizedDictValue.ValueId && x.LanguageCode == localizedDictValue.LanguageCode)) { retVal.PropertyValues.Add(localizedDictValue); } } } //inherit not overriden property values from main product if (retVal.MainProduct != null && retVal.MainProduct.PropertyValues != null) { var mainProductPopValuesGroups = retVal.MainProduct.PropertyValues.GroupBy(x => x.PropertyName); foreach (var group in mainProductPopValuesGroups) { //Inherit all values if not overriden if (!retVal.PropertyValues.Any(x => x.PropertyName.EqualsInvariant(group.Key))) { foreach (var inheritedpropValue in group) { inheritedpropValue.Id = null; inheritedpropValue.IsInherited = true; retVal.PropertyValues.Add(inheritedpropValue); } } } } if (convertChildrens) { // Variations retVal.Variations = new List <coreModel.CatalogProduct>(); foreach (var variation in dbItem.Childrens) { var productVariation = variation.ToCoreModel(allCatalogs, allCategories, convertChildrens: false); productVariation.MainProduct = retVal; productVariation.MainProductId = retVal.Id; retVal.Variations.Add(productVariation); } } return(retVal); }
/// <summary> /// Add property value to product /// </summary> private void AddProperty(CatalogProduct product, string propertyName, object value, PropertyValueType propertyValueType) { var property = _catalogProperties.FirstOrDefault(x => x.Name == propertyName); if (property != null) { var propertyValue = new PropertyValue { PropertyId = property.Id, PropertyName = property.Name, Value = value, ValueType = propertyValueType }; if (product.PropertyValues == null) { product.PropertyValues = new List<PropertyValue>(); } product.PropertyValues.Add(propertyValue); } }
public static webModel.Product ToWebModel(this moduleModel.CatalogProduct product, IBlobUrlResolver blobUrlResolver) { var retVal = new webModel.Product(); retVal.InjectFrom(product); retVal.SeoInfos = product.SeoInfos; if (product.Catalog != null) { retVal.Catalog = product.Catalog.ToWebModel(); //Reset catalog properties and languages for response size economy retVal.Catalog.Properties = null; } if (product.Category != null) { retVal.Category = product.Category.ToWebModel(blobUrlResolver); //Reset category catalog, properties for response size economy retVal.Category.Catalog = null; retVal.Category.Properties = null; } if (product.Images != null) { retVal.Images = product.Images.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.Assets != null) { retVal.Assets = product.Assets.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.Variations != null) { retVal.Variations = product.Variations.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.Links != null) { retVal.Links = product.Links.Select(x => x.ToWebModel()).ToList(); } if (product.Reviews != null) { retVal.Reviews = product.Reviews.Select(x => x.ToWebModel()).ToList(); } if (product.Associations != null) { retVal.Associations = product.Associations.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } //Init parents if (product.Category != null) { retVal.Parents = new List <webModel.Category>(); if (product.Category.Parents != null) { retVal.Parents.AddRange(product.Category.Parents.Select(x => x.ToWebModel())); } retVal.Parents.Add(product.Category.ToWebModel()); foreach (var parent in retVal.Parents) { //Reset some props to decrease size of resulting json parent.Catalog = null; parent.Properties = null; } } retVal.TitularItemId = product.MainProductId; retVal.Properties = new List <webModel.Property>(); //Need add property for each meta info if (product.Properties != null) { foreach (var property in product.Properties) { var webModelProperty = property.ToWebModel(); //Reset dict values to decrease response size webModelProperty.DictionaryValues = null; webModelProperty.Category = null; webModelProperty.Values = new List <webModel.PropertyValue>(); webModelProperty.IsManageable = true; webModelProperty.IsReadOnly = property.Type != moduleModel.PropertyType.Product && property.Type != moduleModel.PropertyType.Variation; retVal.Properties.Add(webModelProperty); } } //Populate property values if (product.PropertyValues != null) { foreach (var propValue in product.PropertyValues.Select(x => x.ToWebModel())) { var property = retVal.Properties.FirstOrDefault(x => x.Id == propValue.PropertyId); if (property == null) { //Need add dummy property for each value without property property = new webModel.Property(propValue, product.CatalogId, product.CategoryId, moduleModel.PropertyType.Product); retVal.Properties.Add(property); } property.Values.Add(propValue); } } return(retVal); }
/// <summary> /// Add asset to given product /// </summary> private void AddAsset(CatalogProduct product, string path) { using (var zipStream = new FileStream(path, FileMode.Open)) { var blobRelativeUrl = Path.Combine("catalog", product.Code, HttpUtility.UrlDecode(Path.ChangeExtension(product.Code, "zip"))); using (var targetStream = _blobStorageProvider.OpenWrite(blobRelativeUrl)) { zipStream.CopyTo(targetStream); } product.Assets = new List<Asset> { new Asset { Url = blobRelativeUrl, Name = Path.GetFileName(blobRelativeUrl) } }; } }
private void SaveProduct(coreModel.Catalog catalog, FulfillmentCenter defaultFulfillmentCenter, CsvProduct csvProduct) { var defaultLanguge = catalog.DefaultLanguage != null ? catalog.DefaultLanguage.LanguageCode : "EN-US"; coreModel.CatalogProduct alreadyExistProduct = null; //For new product try to find them by code if (csvProduct.IsTransient() && !String.IsNullOrEmpty(csvProduct.Code)) { var criteria = new SearchCriteria { CatalogId = catalog.Id, CategoryId = csvProduct.CategoryId, Code = csvProduct.Code, ResponseGroup = SearchResponseGroup.WithProducts | SearchResponseGroup.WithVariations }; var result = _searchService.Search(criteria); alreadyExistProduct = result.Products.FirstOrDefault(); csvProduct.Id = alreadyExistProduct != null ? alreadyExistProduct.Id : csvProduct.Id; } else if (!csvProduct.IsTransient()) { //If id specified need check that product really exist alreadyExistProduct = _productService.GetById(csvProduct.Id, ItemResponseGroup.ItemInfo); } var isNewProduct = alreadyExistProduct == null; csvProduct.CatalogId = catalog.Id; if (String.IsNullOrEmpty(csvProduct.Code)) { csvProduct.Code = _skuGenerator.GenerateSku(csvProduct); } //Set a parent relations if (csvProduct.MainProductId == null && csvProduct.MainProduct != null) { csvProduct.MainProductId = csvProduct.MainProduct.Id; } csvProduct.EditorialReview.LanguageCode = defaultLanguge; csvProduct.SeoInfo.LanguageCode = defaultLanguge; csvProduct.SeoInfo.SemanticUrl = String.IsNullOrEmpty(csvProduct.SeoInfo.SemanticUrl) ? csvProduct.Code : csvProduct.SeoInfo.SemanticUrl; var properties = !String.IsNullOrEmpty(csvProduct.CategoryId) ? _categoryService.GetById(csvProduct.CategoryId, CategoryResponseGroup.WithProperties).Properties : _catalogService.GetById(csvProduct.CatalogId).Properties; if (csvProduct.PropertyValues != null) { //Try to fill properties meta information for values foreach (var propertyValue in csvProduct.PropertyValues) { if (propertyValue.Value != null) { var property = properties.FirstOrDefault(x => String.Equals(x.Name, propertyValue.PropertyName)); if (property != null) { propertyValue.ValueType = property.ValueType; if (property.Dictionary) { property = _propertyService.GetById(property.Id); var dicValue = property.DictionaryValues.FirstOrDefault(x => String.Equals(x.Value, propertyValue.Value)); propertyValue.ValueId = dicValue != null ? dicValue.Id : null; } } } } } if (!isNewProduct) { _productService.Update(new coreModel.CatalogProduct[] { csvProduct }); } else { var newProduct = _productService.Create(csvProduct); csvProduct.Id = newProduct.Id; } //Create price in default price list if (csvProduct.Price.EffectiveValue > 0) { csvProduct.Price.ProductId = csvProduct.Id; if (csvProduct.Price.IsTransient() || _pricingService.GetPriceById(csvProduct.Price.Id) == null) { _pricingService.CreatePrice(csvProduct.Price); } else { _pricingService.UpdatePrices(new Price[] { csvProduct.Price }); } } //Create inventory csvProduct.Inventory.ProductId = csvProduct.Id; csvProduct.Inventory.FulfillmentCenterId = csvProduct.Inventory.FulfillmentCenterId ?? defaultFulfillmentCenter.Id; _inventoryService.UpsertInventory(csvProduct.Inventory); }
/// <summary> /// Converting to model type /// </summary> /// <returns></returns> public static coreModel.CatalogProduct ToCoreModel(this dataModel.Item dbItem, coreModel.Catalog catalog, coreModel.Category category, coreModel.CatalogProduct[] associatedProducts) { var retVal = new coreModel.CatalogProduct(); retVal.InjectFrom(dbItem); retVal.Catalog = catalog; retVal.CatalogId = catalog.Id; if (category != null) { retVal.Category = category; retVal.CategoryId = category.Id; } retVal.MainProductId = dbItem.ParentId; retVal.IsActive = dbItem.IsActive; retVal.IsBuyable = dbItem.IsBuyable; retVal.TrackInventory = dbItem.TrackInventory; retVal.MaxQuantity = (int)dbItem.MaxQuantity; retVal.MinQuantity = (int)dbItem.MinQuantity; #region Links retVal.Links = dbItem.CategoryLinks.Select(x => x.ToCoreModel()).ToList(); #endregion #region Images if (dbItem.Images != null) { retVal.Images = dbItem.Images.OrderBy(x => x.SortOrder).Select(x => x.ToCoreModel()).ToList(); } #endregion #region Assets if (dbItem.Assets != null) { retVal.Assets = dbItem.Assets.OrderBy(x=>x.CreatedDate).Select(x => x.ToCoreModel()).ToList(); } #endregion #region Property values if (dbItem.ItemPropertyValues != null) { retVal.PropertyValues = dbItem.ItemPropertyValues.OrderBy(x=>x.Name).Select(x => x.ToCoreModel(null)).ToList(); } #endregion #region Variations retVal.Variations = new List<coreModel.CatalogProduct>(); foreach (var variation in dbItem.Childrens) { var productVaraition = variation.ToCoreModel(catalog, category, associatedProducts: null); productVaraition.MainProduct = retVal; productVaraition.MainProductId = retVal.Id; retVal.Variations.Add(productVaraition); } #endregion #region EditorialReviews if (dbItem.EditorialReviews != null) { retVal.Reviews = dbItem.EditorialReviews.Select(x => x.ToCoreModel()).ToList(); } #endregion #region Associations if (dbItem.AssociationGroups != null && associatedProducts != null) { retVal.Associations = new List<coreModel.ProductAssociation>(); foreach (var association in dbItem.AssociationGroups.SelectMany(x => x.Associations)) { var associatedProduct = associatedProducts.FirstOrDefault(x => x.Id == association.ItemId); if (associatedProduct != null) { var productAssociation = association.ToCoreModel(associatedProduct); retVal.Associations.Add(productAssociation); } } } #endregion //TaxType category inheritance if(retVal.TaxType == null && category != null) { retVal.TaxType = category.TaxType; } #region Variation property, assets, review inheritance if (dbItem.Parent != null) { //TaxType from main product inheritance if(dbItem.TaxType == null && dbItem.Parent.TaxType != null) { retVal.TaxType = dbItem.Parent.TaxType; } var allProductPropertyNames = dbItem.Parent.ItemPropertyValues.Select(x => x.Name).Distinct().ToArray(); //Property inheritance if (allProductPropertyNames != null) { //Need copy not overridden property values from main product to variation var overriddenPropertyNames = retVal.PropertyValues.Select(x => x.PropertyName).ToArray(); var inheritedPropertyNames = allProductPropertyNames.Except(overriddenPropertyNames); var dbInheritedPropertyValues = dbItem.Parent.ItemPropertyValues.Where(x => inheritedPropertyNames.Contains(x.Name)); foreach (var dbInheritedPropertyValue in dbInheritedPropertyValues) { //Reset id for correct value override var propertyValue = dbInheritedPropertyValue.ToCoreModel(null); propertyValue.Id = null; retVal.PropertyValues.Add(propertyValue); } } //Image inheritance if (!retVal.Images.Any() && dbItem.Parent.Images != null) { retVal.Images = dbItem.Parent.Images.OrderBy(x => x.SortOrder).Select(x => x.ToCoreModel()).ToList(); foreach (var image in retVal.Images) { //Reset id for correct override image.Id = null; } } //Review inheritance if ((retVal.Reviews == null || !retVal.Reviews.Any()) && dbItem.Parent.EditorialReviews != null) { retVal.Reviews = dbItem.Parent.EditorialReviews.Select(x => x.ToCoreModel()).ToList(); foreach (var review in retVal.Reviews) { //Reset id for correct override review.Id = null; } } } #endregion return retVal; }
/// <summary> /// Converting to model type /// </summary> /// <returns></returns> public static coreModel.CatalogProduct ToCoreModel(this dataModel.Item dbItem, coreModel.Catalog catalog, coreModel.Category category, coreModel.CatalogProduct[] associatedProducts) { var retVal = new coreModel.CatalogProduct(); retVal.InjectFrom(dbItem); retVal.Catalog = catalog; retVal.CatalogId = catalog.Id; if (category != null) { retVal.Category = category; retVal.CategoryId = category.Id; } retVal.MainProductId = dbItem.ParentId; retVal.IsActive = dbItem.IsActive; retVal.IsBuyable = dbItem.IsBuyable; retVal.TrackInventory = dbItem.TrackInventory; retVal.MaxQuantity = (int)dbItem.MaxQuantity; retVal.MinQuantity = (int)dbItem.MinQuantity; #region Links retVal.Links = dbItem.CategoryLinks.Select(x => x.ToCoreModel()).ToList(); #endregion #region Images if (dbItem.Images != null) { retVal.Images = dbItem.Images.OrderBy(x => x.SortOrder).Select(x => x.ToCoreModel()).ToList(); } #endregion #region Assets if (dbItem.Assets != null) { retVal.Assets = dbItem.Assets.OrderBy(x => x.CreatedDate).Select(x => x.ToCoreModel()).ToList(); } #endregion #region Property values if (dbItem.ItemPropertyValues != null) { retVal.PropertyValues = dbItem.ItemPropertyValues.OrderBy(x => x.Name).Select(x => x.ToCoreModel(null)).ToList(); } #endregion #region Variations retVal.Variations = new List <coreModel.CatalogProduct>(); foreach (var variation in dbItem.Childrens) { var productVaraition = variation.ToCoreModel(catalog, category, associatedProducts: null); productVaraition.MainProduct = retVal; productVaraition.MainProductId = retVal.Id; retVal.Variations.Add(productVaraition); } #endregion #region EditorialReviews if (dbItem.EditorialReviews != null) { retVal.Reviews = dbItem.EditorialReviews.Select(x => x.ToCoreModel()).ToList(); } #endregion #region Associations if (dbItem.AssociationGroups != null && associatedProducts != null) { retVal.Associations = new List <coreModel.ProductAssociation>(); foreach (var association in dbItem.AssociationGroups.SelectMany(x => x.Associations)) { var associatedProduct = associatedProducts.FirstOrDefault(x => x.Id == association.ItemId); if (associatedProduct != null) { var productAssociation = association.ToCoreModel(associatedProduct); retVal.Associations.Add(productAssociation); } } } #endregion //TaxType category inheritance if (retVal.TaxType == null && category != null) { retVal.TaxType = category.TaxType; } #region Variation property, assets, review inheritance if (dbItem.Parent != null) { //TaxType from main product inheritance if (dbItem.TaxType == null && dbItem.Parent.TaxType != null) { retVal.TaxType = dbItem.Parent.TaxType; } var allProductPropertyNames = dbItem.Parent.ItemPropertyValues.Select(x => x.Name).Distinct().ToArray(); //Property inheritance if (allProductPropertyNames != null) { //Need copy not overridden property values from main product to variation var overriddenPropertyNames = retVal.PropertyValues.Select(x => x.PropertyName).ToArray(); var inheritedPropertyNames = allProductPropertyNames.Except(overriddenPropertyNames); var dbInheritedPropertyValues = dbItem.Parent.ItemPropertyValues.Where(x => inheritedPropertyNames.Contains(x.Name)); foreach (var dbInheritedPropertyValue in dbInheritedPropertyValues) { //Reset id for correct value override var propertyValue = dbInheritedPropertyValue.ToCoreModel(null); propertyValue.Id = null; retVal.PropertyValues.Add(propertyValue); } } //Image inheritance if (!retVal.Images.Any() && dbItem.Parent.Images != null) { retVal.Images = dbItem.Parent.Images.OrderBy(x => x.SortOrder).Select(x => x.ToCoreModel()).ToList(); foreach (var image in retVal.Images) { //Reset id for correct override image.Id = null; } } //Review inheritance if ((retVal.Reviews == null || !retVal.Reviews.Any()) && dbItem.Parent.EditorialReviews != null) { retVal.Reviews = dbItem.Parent.EditorialReviews.Select(x => x.ToCoreModel()).ToList(); foreach (var review in retVal.Reviews) { //Reset id for correct override review.Id = null; } } } #endregion return(retVal); }
public static webModel.Product ToWebModel(this moduleModel.CatalogProduct product, IBlobUrlResolver blobUrlResolver) { var retVal = new webModel.Product(); retVal.Id = product.Id; retVal.CatalogId = product.CatalogId; retVal.CategoryId = product.CategoryId; retVal.Code = product.Code; retVal.CreatedBy = product.CreatedBy; retVal.CreatedDate = product.CreatedDate; retVal.DownloadExpiration = product.DownloadExpiration; retVal.DownloadType = product.DownloadType; retVal.EnableReview = product.EnableReview; retVal.Gtin = product.Gtin; retVal.HasUserAgreement = product.HasUserAgreement; retVal.Height = product.Height; retVal.IndexingDate = product.IndexingDate; retVal.IsActive = product.IsActive; retVal.IsBuyable = product.IsBuyable; retVal.Length = product.Length; retVal.ManufacturerPartNumber = product.ManufacturerPartNumber; retVal.MaxNumberOfDownload = product.MaxNumberOfDownload; retVal.MaxQuantity = product.MaxQuantity; retVal.MeasureUnit = product.MeasureUnit; retVal.MinQuantity = product.MinQuantity; retVal.ModifiedBy = product.ModifiedBy; retVal.ModifiedDate = product.ModifiedDate; retVal.Name = product.Name; retVal.PackageType = product.PackageType; retVal.Priority = product.Priority; retVal.ProductType = product.ProductType; retVal.TaxType = product.TaxType; retVal.TrackInventory = product.TrackInventory; retVal.Vendor = product.Vendor; retVal.Weight = product.Weight; retVal.WeightUnit = product.WeightUnit; retVal.Width = product.Width; retVal.SeoInfos = product.SeoInfos; if (!product.Outlines.IsNullOrEmpty()) { //Minimize outline size retVal.Outlines = product.Outlines.Select(x => x.ToWebModel()).ToList(); } if (product.Images != null) { retVal.Images = product.Images.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.Assets != null) { retVal.Assets = product.Assets.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.Variations != null) { retVal.Variations = product.Variations.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); //For nested variations leave only variation properties to decrease resulting JSON foreach (var variation in retVal.Variations) { if (variation.Properties != null) { variation.Properties = variation.Properties.Where(x => x.Type == moduleModel.PropertyType.Variation).ToList(); } } } if (product.Links != null) { retVal.Links = product.Links.Select(x => x.ToWebModel()).ToList(); } if (product.Reviews != null) { retVal.Reviews = product.Reviews.Select(x => x.ToWebModel()).ToList(); } if (product.Associations != null) { retVal.Associations = product.Associations.Select(x => x.ToWebModel(blobUrlResolver)).ToList(); } if (product.ReferencedAssociations != null) { retVal.ReferencedAssociations = product.ReferencedAssociations.Select(a => a.ToWebModel(blobUrlResolver)).ToList(); } //Init outline and path if (product.Category != null) { var parents = new List <moduleModel.Category>(); if (product.Category.Parents != null) { parents.AddRange(product.Category.Parents); } parents.Add(product.Category); retVal.Outline = string.Join("/", parents.Select(x => x.Id)); retVal.Path = string.Join("/", parents.Select(x => x.Name)); } retVal.TitularItemId = product.MainProductId; retVal.Properties = new List <webModel.Property>(); //Need add property for each meta info if (product.Properties != null) { foreach (var property in product.Properties) { var webModelProperty = property.ToWebModel(); //Reset dict values to decrease response size webModelProperty.DictionaryValues = null; webModelProperty.Values = new List <webModel.PropertyValue>(); webModelProperty.IsManageable = true; webModelProperty.IsReadOnly = property.Type != moduleModel.PropertyType.Product && property.Type != moduleModel.PropertyType.Variation; retVal.Properties.Add(webModelProperty); } } //Populate property values if (product.PropertyValues != null) { foreach (var propValue in product.PropertyValues.Select(x => x.ToWebModel())) { var property = retVal.Properties.FirstOrDefault(x => x.Id == propValue.PropertyId); if (property == null) { property = retVal.Properties.FirstOrDefault(x => x.Name.EqualsInvariant(propValue.PropertyName)); } if (property == null) { //Need add dummy property for each value without property property = new webModel.Property(propValue, product.CatalogId, moduleModel.PropertyType.Product); retVal.Properties.Add(property); } property.Values.Add(propValue); } } return(retVal); }
/// <summary> /// Patch changes /// </summary> /// <param name="source"></param> /// <param name="target"></param> public static void Patch(this coreModel.CatalogProduct source, dataModel.Item target) { if (target == null) { throw new ArgumentNullException("target"); } //TODO: temporary solution because partial update replaced not nullable properties in db entity if (source.IsBuyable != null) { target.IsBuyable = source.IsBuyable.Value; } if (source.IsActive != null) { target.IsActive = source.IsActive.Value; } if (source.TrackInventory != null) { target.TrackInventory = source.TrackInventory.Value; } if (source.MinQuantity != null) { target.MinQuantity = source.MinQuantity.Value; } if (source.MaxQuantity != null) { target.MaxQuantity = source.MaxQuantity.Value; } var patchInjectionPolicy = new PatchInjection <dataModel.Item>(x => x.CategoryId, x => x.Name, x => x.Code, x => x.ManufacturerPartNumber, x => x.Gtin, x => x.ProductType, x => x.WeightUnit, x => x.Weight, x => x.MeasureUnit, x => x.Height, x => x.Length, x => x.Width, x => x.EnableReview, x => x.MaxNumberOfDownload, x => x.DownloadExpiration, x => x.DownloadType, x => x.HasUserAgreement, x => x.ShippingType, x => x.TaxType, x => x.Vendor); var dbSource = source.ToDataModel(); target.InjectFrom(patchInjectionPolicy, dbSource); #region Assets if (!dbSource.Assets.IsNullCollection()) { dbSource.Assets.Patch(target.Assets, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset)); } #endregion #region Images if (!dbSource.Images.IsNullCollection()) { dbSource.Images.Patch(target.Images, (sourceImage, targetImage) => sourceImage.Patch(targetImage)); } #endregion #region ItemPropertyValues if (!dbSource.ItemPropertyValues.IsNullCollection()) { //Need skip inherited properties without overridden value if (source.MainProduct != null) { var dbParent = source.MainProduct.ToDataModel(); var parentPropValues = dbParent.ItemPropertyValues.ToLookup(x => x.Name + "-" + x.ToString()); var variationPropValues = dbSource.ItemPropertyValues.ToLookup(x => x.Name + "-" + x.ToString()); dbSource.ItemPropertyValues = new ObservableCollection <dataModel.ItemPropertyValue>(variationPropValues.Where(x => !parentPropValues.Contains(x.Key)).SelectMany(x => x)); } dbSource.ItemPropertyValues.Patch(target.ItemPropertyValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region Links if (!dbSource.CategoryLinks.IsNullCollection()) { dbSource.CategoryLinks.Patch(target.CategoryLinks, new CategoryItemRelationComparer(), (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region EditorialReviews if (!dbSource.EditorialReviews.IsNullCollection()) { dbSource.EditorialReviews.Patch(target.EditorialReviews, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region Association if (!dbSource.AssociationGroups.IsNullCollection()) { var associationComparer = AnonymousComparer.Create((dataModel.AssociationGroup x) => x.Name); dbSource.AssociationGroups.Patch(target.AssociationGroups, associationComparer, (sourceGroup, targetGroup) => sourceGroup.Patch(targetGroup)); } #endregion }
/// <summary> /// Converting to foundation type /// </summary> /// <param name="product"></param> /// <param name="pkMap"></param> /// <returns></returns> public static dataModel.Item ToDataModel(this coreModel.CatalogProduct product, PrimaryKeyResolvingMap pkMap) { var retVal = new dataModel.Item(); pkMap.AddPair(product, retVal); retVal.InjectFrom(product); if (product.StartDate == default(DateTime)) { retVal.StartDate = DateTime.UtcNow; } retVal.IsActive = product.IsActive ?? true; retVal.IsBuyable = product.IsBuyable ?? true; retVal.TrackInventory = product.TrackInventory ?? true; retVal.MaxQuantity = product.MaxQuantity ?? 0; retVal.MinQuantity = product.MinQuantity ?? 0; retVal.ParentId = product.MainProductId; //Constant fields //Only for main product retVal.AvailabilityRule = (int)coreModel.AvailabilityRule.Always; retVal.MinQuantity = 1; retVal.MaxQuantity = 0; retVal.CatalogId = product.CatalogId; retVal.CategoryId = string.IsNullOrEmpty(product.CategoryId) ? null : product.CategoryId; #region ItemPropertyValues if (product.PropertyValues != null) { retVal.ItemPropertyValues = new ObservableCollection <dataModel.PropertyValue>(); retVal.ItemPropertyValues.AddRange(product.PropertyValues.Where(x => !x.IsInherited).Select(x => x.ToDataModel(pkMap))); } #endregion #region Assets if (product.Assets != null) { retVal.Assets = new ObservableCollection <dataModel.Asset>(product.Assets.Where(x => !x.IsInherited).Select(x => x.ToDataModel(pkMap))); } #endregion #region Images if (product.Images != null) { retVal.Images = new ObservableCollection <dataModel.Image>(product.Images.Where(x => !x.IsInherited).Select(x => x.ToDataModel(pkMap))); } #endregion #region Links if (product.Links != null) { retVal.CategoryLinks = new ObservableCollection <dataModel.CategoryItemRelation>(); retVal.CategoryLinks.AddRange(product.Links.Select(x => x.ToDataModel(product))); } #endregion #region EditorialReview if (product.Reviews != null) { retVal.EditorialReviews = new ObservableCollection <dataModel.EditorialReview>(); retVal.EditorialReviews.AddRange(product.Reviews.Where(x => !x.IsInherited).Select(x => x.ToDataModel(retVal, pkMap))); } #endregion #region Associations if (product.Associations != null) { retVal.Associations = new ObservableCollection <dataModel.Association>(product.Associations.Select(x => x.ToDataModel())); } #endregion return(retVal); }
/// <summary> /// Converting to foundation type /// </summary> /// <param name="catalog"></param> /// <returns></returns> public static dataModel.Item ToDataModel(this coreModel.CatalogProduct product, PrimaryKeyResolvingMap pkMap) { var retVal = new dataModel.Item(); pkMap.AddPair(product, retVal); retVal.InjectFrom(product); if (product.StartDate == default(DateTime)) { retVal.StartDate = DateTime.UtcNow; } retVal.IsActive = product.IsActive ?? true; retVal.IsBuyable = product.IsBuyable ?? true; retVal.TrackInventory = product.TrackInventory ?? true; retVal.MaxQuantity = product.MaxQuantity ?? 0; retVal.MinQuantity = product.MinQuantity ?? 0; retVal.ParentId = product.MainProductId; //Constant fields //Only for main product retVal.AvailabilityRule = (int)coreModel.AvailabilityRule.Always; retVal.MinQuantity = 1; retVal.MaxQuantity = 0; retVal.CatalogId = product.CatalogId; retVal.CategoryId = String.IsNullOrEmpty(product.CategoryId) ? null : product.CategoryId; #region ItemPropertyValues if (product.PropertyValues != null) { retVal.ItemPropertyValues = new ObservableCollection <dataModel.PropertyValue>(); retVal.ItemPropertyValues.AddRange(product.PropertyValues.Where(x => !x.IsInherited).Select(x => x.ToDataModel(pkMap))); } #endregion #region Assets if (product.Assets != null) { retVal.Assets = new ObservableCollection <dataModel.Asset>(product.Assets.Where(x => !x.IsInherited).Select(x => x.ToDataModel(pkMap))); } #endregion #region Images if (product.Images != null) { retVal.Images = new ObservableCollection <dataModel.Image>(product.Images.Where(x => !x.IsInherited).Select(x => x.ToDataModel(pkMap))); } #endregion #region Links if (product.Links != null) { retVal.CategoryLinks = new ObservableCollection <dataModel.CategoryItemRelation>(); retVal.CategoryLinks.AddRange(product.Links.Select(x => x.ToDataModel(product))); } #endregion #region EditorialReview if (product.Reviews != null) { retVal.EditorialReviews = new ObservableCollection <dataModel.EditorialReview>(); retVal.EditorialReviews.AddRange(product.Reviews.Where(x => !x.IsInherited).Select(x => x.ToDataModel(retVal, pkMap))); } #endregion #region Associations if (product.Associations != null) { retVal.AssociationGroups = new ObservableCollection <dataModel.AssociationGroup>(); var associations = product.Associations.ToArray(); for (int order = 0; order < associations.Count(); order++) { var association = associations[order]; var associationGroup = retVal.AssociationGroups.FirstOrDefault(x => x.Name == association.Name); if (associationGroup == null) { associationGroup = new dataModel.AssociationGroup { Name = association.Name, Description = association.Description, Priority = 1, }; retVal.AssociationGroups.Add(associationGroup); } var foundationAssociation = association.ToDataModel(); foundationAssociation.Priority = order; associationGroup.Associations.Add(foundationAssociation); } } #endregion return(retVal); }
/// <summary> /// Patch changes /// </summary> /// <param name="source"></param> /// <param name="target"></param> /// <param name="pkMap"></param> public static void Patch(this coreModel.CatalogProduct source, dataModel.Item target, PrimaryKeyResolvingMap pkMap) { if (target == null) { throw new ArgumentNullException(nameof(target)); } // TODO: temporary solution because partial update replaced not nullable properties in db entity if (source.IsBuyable != null) { target.IsBuyable = source.IsBuyable.Value; } if (source.IsActive != null) { target.IsActive = source.IsActive.Value; } if (source.TrackInventory != null) { target.TrackInventory = source.TrackInventory.Value; } if (source.MinQuantity != null) { target.MinQuantity = source.MinQuantity.Value; } if (source.MaxQuantity != null) { target.MaxQuantity = source.MaxQuantity.Value; } if (source.EnableReview != null) { target.EnableReview = source.EnableReview.Value; } target.CatalogId = string.IsNullOrEmpty(source.CatalogId) ? null : source.CatalogId; target.CategoryId = string.IsNullOrEmpty(source.CategoryId) ? null : source.CategoryId; target.Name = source.Name; target.Code = source.Code; target.ManufacturerPartNumber = source.ManufacturerPartNumber; target.Gtin = source.Gtin; target.ProductType = source.ProductType; target.MaxNumberOfDownload = source.MaxNumberOfDownload; target.DownloadType = source.DownloadType; target.HasUserAgreement = source.HasUserAgreement; target.DownloadExpiration = source.DownloadExpiration; target.Vendor = source.Vendor; target.TaxType = source.TaxType; target.WeightUnit = source.WeightUnit; target.Weight = source.Weight; target.MeasureUnit = source.MeasureUnit; target.PackageType = source.PackageType; target.Height = source.Height; target.Length = source.Length; target.Width = source.Width; target.ShippingType = source.ShippingType; target.Priority = source.Priority; target.ParentId = source.MainProductId; var dbSource = source.ToDataModel(pkMap); #region Assets if (!dbSource.Assets.IsNullCollection()) { dbSource.Assets.Patch(target.Assets, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset)); } #endregion #region Images if (!dbSource.Images.IsNullCollection()) { dbSource.Images.Patch(target.Images, (sourceImage, targetImage) => sourceImage.Patch(targetImage)); } #endregion #region ItemPropertyValues if (!dbSource.ItemPropertyValues.IsNullCollection()) { dbSource.ItemPropertyValues.Patch(target.ItemPropertyValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region Links if (!dbSource.CategoryLinks.IsNullCollection()) { dbSource.CategoryLinks.Patch(target.CategoryLinks, new CategoryItemRelationComparer(), (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region EditorialReviews if (!dbSource.EditorialReviews.IsNullCollection()) { dbSource.EditorialReviews.Patch(target.EditorialReviews, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region Association if (!dbSource.Associations.IsNullCollection()) { var associationComparer = AnonymousComparer.Create((dataModel.Association x) => x.AssociationType + ":" + x.AssociatedItemId + ":" + x.AssociatedCategoryId); dbSource.Associations.Patch(target.Associations, associationComparer, (sourceAssociation, targetAssociation) => sourceAssociation.Patch(targetAssociation)); } #endregion }
/// <summary> /// Patch changes /// </summary> /// <param name="source"></param> /// <param name="target"></param> public static void Patch(this coreModel.CatalogProduct source, dataModel.Item target, PrimaryKeyResolvingMap pkMap) { if (target == null) { throw new ArgumentNullException("target"); } //TODO: temporary solution because partial update replaced not nullable properties in db entity if (source.IsBuyable != null) { target.IsBuyable = source.IsBuyable.Value; } if (source.IsActive != null) { target.IsActive = source.IsActive.Value; } if (source.TrackInventory != null) { target.TrackInventory = source.TrackInventory.Value; } if (source.MinQuantity != null) { target.MinQuantity = source.MinQuantity.Value; } if (source.MaxQuantity != null) { target.MaxQuantity = source.MaxQuantity.Value; } //Handle three valuable states (null, empty and have value states) for case when need reset catalog or category if (source.CatalogId == String.Empty) { target.CatalogId = null; } if (source.CategoryId == String.Empty) { target.CategoryId = null; } var patchInjectionPolicy = new PatchInjection <dataModel.Item>(x => x.Name, x => x.Code, x => x.ManufacturerPartNumber, x => x.Gtin, x => x.ProductType, x => x.WeightUnit, x => x.Weight, x => x.MeasureUnit, x => x.Height, x => x.Length, x => x.Width, x => x.EnableReview, x => x.MaxNumberOfDownload, x => x.DownloadExpiration, x => x.DownloadType, x => x.HasUserAgreement, x => x.ShippingType, x => x.TaxType, x => x.Vendor, x => x.CatalogId, x => x.CategoryId); var dbSource = source.ToDataModel(pkMap); target.InjectFrom(patchInjectionPolicy, dbSource); #region Assets if (!dbSource.Assets.IsNullCollection()) { dbSource.Assets.Patch(target.Assets, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset)); } #endregion #region Images if (!dbSource.Images.IsNullCollection()) { dbSource.Images.Patch(target.Images, (sourceImage, targetImage) => sourceImage.Patch(targetImage)); } #endregion #region ItemPropertyValues if (!dbSource.ItemPropertyValues.IsNullCollection()) { dbSource.ItemPropertyValues.Patch(target.ItemPropertyValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region Links if (!dbSource.CategoryLinks.IsNullCollection()) { dbSource.CategoryLinks.Patch(target.CategoryLinks, new CategoryItemRelationComparer(), (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region EditorialReviews if (!dbSource.EditorialReviews.IsNullCollection()) { dbSource.EditorialReviews.Patch(target.EditorialReviews, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue)); } #endregion #region Association if (!dbSource.AssociationGroups.IsNullCollection()) { var associationComparer = AnonymousComparer.Create((dataModel.AssociationGroup x) => x.Name); dbSource.AssociationGroups.Patch(target.AssociationGroups, associationComparer, (sourceGroup, targetGroup) => sourceGroup.Patch(targetGroup)); } #endregion }
public static moduleModel.CatalogProduct ToModuleModel(this webModel.Product product, IBlobUrlResolver blobUrlResolver) { var retVal = new moduleModel.CatalogProduct(); retVal.InjectFrom(product); retVal.SeoInfos = product.SeoInfos; if (product.Images != null) { retVal.Assets = new List <moduleModel.ItemAsset>(); bool isMain = true; foreach (var productImage in product.Images) { var image = productImage.ToModuleModel(); image.Type = moduleModel.ItemAssetType.Image; image.Group = isMain ? "primaryimage" : "images"; retVal.Assets.Add(image); isMain = false; } } if (product.Assets != null) { if (retVal.Assets == null) { retVal.Assets = new List <moduleModel.ItemAsset>(); } foreach (var productAsset in product.Assets) { var asset = productAsset.ToModuleModel(); asset.Type = moduleModel.ItemAssetType.File; retVal.Assets.Add(asset); } } if (product.Properties != null) { retVal.PropertyValues = new List <moduleModel.PropertyValue>(); foreach (var property in product.Properties) { foreach (var propValue in property.Values) { //Need populate required fields propValue.PropertyName = property.Name; propValue.ValueType = property.ValueType; retVal.PropertyValues.Add(propValue.ToModuleModel()); } } } if (product.Variations != null) { retVal.Variations = product.Variations.Select(x => x.ToModuleModel(blobUrlResolver)).ToList(); } if (product.Links != null) { retVal.Links = product.Links.Select(x => x.ToModuleModel()).ToList(); } if (product.Reviews != null) { retVal.Reviews = product.Reviews.Select(x => x.ToModuleModel()).ToList(); } if (product.Associations != null) { retVal.Associations = product.Associations.Select(x => x.ToModuleModel()).ToList(); } retVal.MainProductId = product.TitularItemId; return(retVal); }
/// <summary> /// Converting to foundation type /// </summary> /// <param name="catalog"></param> /// <returns></returns> public static dataModel.Item ToDataModel(this coreModel.CatalogProduct product) { var retVal = new dataModel.Product(); var id = retVal.Id; retVal.InjectFrom(product); if (product.Id == null) { retVal.Id = id; } if (product.StartDate == default(DateTime)) { retVal.StartDate = DateTime.UtcNow; } retVal.IsActive = product.IsActive ?? true; retVal.IsBuyable = product.IsBuyable ?? true; retVal.TrackInventory = product.TrackInventory ?? true; retVal.MaxQuantity = product.MaxQuantity ?? 0; retVal.MinQuantity = product.MinQuantity ?? 0; retVal.ParentId = product.MainProductId; //Constant fields //Only for main product retVal.AvailabilityRule = (int)coreModel.AvailabilityRule.Always; retVal.MinQuantity = 1; retVal.MaxQuantity = 0; retVal.CatalogId = product.CatalogId; retVal.CategoryId = product.CategoryId; if (product.MainProduct != null) { retVal.Parent = product.MainProduct.ToDataModel(); } #region ItemPropertyValues if (product.PropertyValues != null) { retVal.ItemPropertyValues = new ObservableCollection <dataModel.ItemPropertyValue>(); foreach (var propValue in product.PropertyValues) { var dbPropValue = propValue.ToDataModel <dataModel.ItemPropertyValue>() as dataModel.ItemPropertyValue; retVal.ItemPropertyValues.Add(dbPropValue); dbPropValue.ItemId = retVal.Id; } } #endregion #region ItemAssets if (product.Assets != null) { var assets = product.Assets.ToArray(); retVal.ItemAssets = new ObservableCollection <dataModel.ItemAsset>(); for (int order = 0; order < assets.Length; order++) { var asset = assets[order]; var dbAsset = asset.ToDataModel(); dbAsset.SortOrder = order; retVal.ItemAssets.Add(dbAsset); } } #endregion #region Links if (product.Links != null) { retVal.CategoryLinks = new ObservableCollection <dataModel.CategoryItemRelation>(); retVal.CategoryLinks.AddRange(product.Links.Select(x => x.ToDataModel(product))); } #endregion #region EditorialReview if (product.Reviews != null) { retVal.EditorialReviews = new ObservableCollection <dataModel.EditorialReview>(); retVal.EditorialReviews.AddRange(product.Reviews.Select(x => x.ToDataModel(retVal))); } #endregion #region Associations if (product.Associations != null) { retVal.AssociationGroups = new ObservableCollection <dataModel.AssociationGroup>(); var associations = product.Associations.ToArray(); for (int order = 0; order < associations.Count(); order++) { var association = associations[order]; var associationGroup = retVal.AssociationGroups.FirstOrDefault(x => x.Name == association.Name); if (associationGroup == null) { associationGroup = new dataModel.AssociationGroup { Name = association.Name, Description = association.Description, Priority = 1, }; retVal.AssociationGroups.Add(associationGroup); } var foundationAssociation = association.ToDataModel(); foundationAssociation.Priority = order; associationGroup.Associations.Add(foundationAssociation); } } #endregion return(retVal); }