Example #1
0
        private List <PropertyValue> TryToSplitMultivaluePropertyValues(CsvProduct csvProduct)
        {
            var result = new List <PropertyValue>();

            //Try to split multivalues
            foreach (var propValue in csvProduct.PropertyValues)
            {
                if (propValue.Value != null && propValue.Property != null && propValue.Property.Multivalue)
                {
                    var values = propValue.Value.ToString().Split(',', ';');
                    foreach (var value in values)
                    {
                        var multiPropValue = propValue.Clone() as PropertyValue;
                        multiPropValue.Value = value;
                        result.Add(multiPropValue);
                    }
                }
                else
                {
                    result.Add(propValue);
                }
            }
            return(result);
        }
		public void DoExport(Stream outStream, CsvExportInfo exportInfo, Action<ExportImportProgressInfo> progressCallback)
		{
			var prodgressInfo = new ExportImportProgressInfo
			{
				Description = "loading products..."
			};

			var streamWriter = new StreamWriter(outStream, Encoding.UTF8, 1024, true);
			streamWriter.AutoFlush = true;

			using (var csvWriter = new CsvWriter(streamWriter))
			{
				//Notification
				progressCallback(prodgressInfo);

				//Load all products to export
				var products = LoadProducts(exportInfo.CatalogId, exportInfo.CategoryIds, exportInfo.ProductIds);
				var allProductIds = products.Select(x => x.Id).ToArray();

				//Load prices for products
				var allProductPrices = new List<Price>();

				prodgressInfo.Description = "loading prices...";
				progressCallback(prodgressInfo);

				var priceEvalContext = new PriceEvaluationContext
				{
					ProductIds = allProductIds,
					PricelistIds = exportInfo.PriceListId == null ? null : new string[] { exportInfo.PriceListId },
					Currency = exportInfo.Currency
				};
				allProductPrices = _pricingService.EvaluateProductPrices(priceEvalContext).ToList();


				//Load inventories
				var allProductInventories = new List<InventoryInfo>();

				prodgressInfo.Description = "loading inventory information...";
				progressCallback(prodgressInfo);

				allProductInventories = _inventoryService.GetProductsInventoryInfos(allProductIds).Where(x => exportInfo.FulfilmentCenterId == null ? true : x.FulfillmentCenterId == exportInfo.FulfilmentCenterId).ToList();


				//Export configuration
				exportInfo.Configuration.PropertyCsvColumns = products.SelectMany(x => x.PropertyValues).Select(x => x.PropertyName).Distinct().ToArray();

				csvWriter.Configuration.Delimiter = exportInfo.Configuration.Delimiter;
				csvWriter.Configuration.RegisterClassMap(new CsvProductMap(exportInfo.Configuration));

				//Write header
				csvWriter.WriteHeader<CsvProduct>();

				prodgressInfo.TotalCount = products.Count();
				var notifyProductSizeLimit = 50;
				var counter = 0;
				foreach (var product in products)
				{
					try
					{
						var csvProduct = new CsvProduct(product, _blobUrlResolver, allProductPrices.FirstOrDefault(x => x.ProductId == product.Id), allProductInventories.FirstOrDefault(x => x.ProductId == product.Id));
						csvWriter.WriteRecord(csvProduct);
					}
					catch (Exception ex)
					{
						prodgressInfo.Errors.Add(ex.ToString());
						progressCallback(prodgressInfo);
					}

					//Raise notification each notifyProductSizeLimit products
					counter++;
					prodgressInfo.ProcessedCount = counter;
					prodgressInfo.Description = string.Format("{0} of {1} products processed", prodgressInfo.ProcessedCount, prodgressInfo.TotalCount);
					if (counter % notifyProductSizeLimit == 0 || counter == prodgressInfo.TotalCount)
					{
						progressCallback(prodgressInfo);
					}
				}
			}
		}
		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 = ResponseGroup.WithProducts | ResponseGroup.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) ? _propertyService.GetCategoryProperties(csvProduct.CategoryId) : _propertyService.GetCatalogProperties(csvProduct.CatalogId);

			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);
		}
        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);
        }
Example #5
0
        public void DoExport(Stream outStream, CsvExportInfo exportInfo, Action <ExportImportProgressInfo> progressCallback)
        {
            var prodgressInfo = new ExportImportProgressInfo
            {
                Description = "loading products..."
            };

            var streamWriter = new StreamWriter(outStream, Encoding.UTF8, 1024, true);

            streamWriter.AutoFlush = true;

            using (var csvWriter = new CsvWriter(streamWriter))
            {
                //Notification
                progressCallback(prodgressInfo);

                //Load all products to export
                var products      = LoadProducts(exportInfo.CatalogId, exportInfo.CategoryIds, exportInfo.ProductIds);
                var allProductIds = products.Select(x => x.Id).ToArray();

                //Load prices for products
                var allProductPrices = new List <Price>();

                prodgressInfo.Description = "loading prices...";
                progressCallback(prodgressInfo);

                var priceEvalContext = new PriceEvaluationContext
                {
                    ProductIds   = allProductIds,
                    PricelistIds = exportInfo.PriceListId == null ? null : new string[] { exportInfo.PriceListId },
                    Currency     = exportInfo.Currency
                };
                allProductPrices = _pricingService.EvaluateProductPrices(priceEvalContext).ToList();


                //Load inventories
                var allProductInventories = new List <InventoryInfo>();

                prodgressInfo.Description = "loading inventory information...";
                progressCallback(prodgressInfo);

                allProductInventories = _inventoryService.GetProductsInventoryInfos(allProductIds).Where(x => exportInfo.FulfilmentCenterId == null ? true : x.FulfillmentCenterId == exportInfo.FulfilmentCenterId).ToList();


                //Export configuration
                exportInfo.Configuration.PropertyCsvColumns = products.SelectMany(x => x.PropertyValues).Select(x => x.PropertyName).Distinct().ToArray();

                csvWriter.Configuration.Delimiter = exportInfo.Configuration.Delimiter;
                csvWriter.Configuration.RegisterClassMap(new CsvProductMap(exportInfo.Configuration));

                //Write header
                csvWriter.WriteHeader <CsvProduct>();

                prodgressInfo.TotalCount = products.Count();
                var notifyProductSizeLimit = 50;
                var counter = 0;
                foreach (var product in products)
                {
                    try
                    {
                        var csvProduct = new CsvProduct(product, _blobUrlResolver, allProductPrices.FirstOrDefault(x => x.ProductId == product.Id), allProductInventories.FirstOrDefault(x => x.ProductId == product.Id));
                        csvWriter.WriteRecord(csvProduct);
                    }
                    catch (Exception ex)
                    {
                        prodgressInfo.Errors.Add(ex.ToString());
                        progressCallback(prodgressInfo);
                    }

                    //Raise notification each notifyProductSizeLimit products
                    counter++;
                    prodgressInfo.ProcessedCount = counter;
                    prodgressInfo.Description    = string.Format("{0} of {1} products processed", prodgressInfo.ProcessedCount, prodgressInfo.TotalCount);
                    if (counter % notifyProductSizeLimit == 0 || counter == prodgressInfo.TotalCount)
                    {
                        progressCallback(prodgressInfo);
                    }
                }
            }
        }