public bool UpdatePricelistItem(PricelistItem pricelistItem, int?pricelistNumber, int?customerNumber) { //Log(" -> " + pricelistItem.ProductCode + " (" + pricelistItem.Active.ToString() + " " + pricelistItem.GetIdValue().ToString() + ") " + pricelistItem.BatchSize.ToString() + "ks " + pricelistItem.ContractPrice.ToString()); decimal price = pricelistItem.ContractPrice; string articleCode = pricelistItem.ProductCode; int? quantity = (int)pricelistItem.BatchSize; if (quantity <= 1) { quantity = null; } Article article = visma.GetArticleByCode(articleCode); // If pricelist has Discount value, use it to calculate the final price from currect Article price if ((pricelistItem.ContractDiscount > 0) && (pricelistItem.ContractDiscount < 100) && (article != null)) { price = Math.Round(article.Price1 * ((100 - pricelistItem.ContractDiscount) / 100), 2); } // Check if pricelist is valid by looking at the PVM and VOIMASSA fields bool datesValid = true; DateTime validFromDate; DateTime validToDate; DateTime.TryParse(pricelistItem.PricelistDate, out validFromDate); DateTime.TryParse(pricelistItem.Valid, out validToDate); datesValid = ((validFromDate == DateTime.MinValue) || (validFromDate <= DateTime.Now)) && ((validToDate == DateTime.MinValue) || (validToDate >= DateTime.Now)); bool currencyMatch = true; if (!string.IsNullOrEmpty(article.Currency) && !string.IsNullOrEmpty(pricelistItem.Currency)) { if (article.Currency != pricelistItem.Currency) { currencyMatch = false; } } if ((article != null) && (datesValid) && (currencyMatch)) // && (article.ArticleCode == "A0112") { string pricelistItemName = article.ArticleCode; pricelistItemName += pricelistNumber.HasValue ? string.Format(" P{0}", pricelistNumber) : string.Format(" C{0}", customerNumber); if (quantity != null) { pricelistItemName += string.Format(" Q{0}", quantity); } string famiyCode = article.FamilyCode; string articleName = null; if (!string.IsNullOrEmpty(article.FamilyCode)) { articleName = visma.GetCommonArticleNameForFamilyCode(article.FamilyCode); } DataSet.ProductDataTable genericProducts = productTA.GetDataByArticleCode(shop.ID, articleCode); if (genericProducts.Count > 0) { long?shopifyProductID = genericProducts[0].ShopifyProductID; long?shopifyVariantID = null; long?shopifyVariantVatID = null; DataSet.ProductDataTable specificProducts = productTA.GetDataByArticleCodeSpecific(shop.ID, articleCode, pricelistNumber, customerNumber, quantity); if (specificProducts.Count == 0) { Log(" - Create specific price"); try { shop.CreateUpdateProductVariants(article, shopifyProductID.Value, ref shopifyVariantID, ref shopifyVariantVatID, pricelistNumber, customerNumber, quantity, price, articleName); Log(string.Format(" - Shopify Product Variant [{0}] created for specific price {1}.", shopifyVariantID, pricelistItemName)); productTA.InsertProduct(shop.ID, shopifyProductID, shopifyVariantID, shopifyVariantVatID, articleCode, pricelistNumber, customerNumber, quantity, price, famiyCode, null, null); } catch (System.Net.WebException ex) { LogError(string.Format("Unable to create specific price {0}.", pricelistItemName), ex); } } else { shopifyProductID = specificProducts[0].ShopifyProductID; shopifyVariantID = specificProducts[0].ShopifyVariantID; shopifyVariantVatID = specificProducts[0].ShopifyVariantVatID; try { shop.CreateUpdateProductVariants(article, shopifyProductID.Value, ref shopifyVariantID, ref shopifyVariantVatID, pricelistNumber, customerNumber, quantity, price, articleName); Log(string.Format(" - Shopify Product Variant [{0}] updated for specific price {1}.", shopifyVariantID, pricelistItemName)); } catch (System.Net.WebException ex) { LogError(string.Format("Unable to update specific price {0}.", pricelistItemName), ex); } } } else { //Log(" - Product not in Shopify"); } } return(true); }
public bool UpdateProducts(DateTime?startDate, int articleLimit = 0, bool updateArticleImages = false, bool updateStockData = false) { int articlesCount = 0; int articleUpdates = 0; // Read CSV file with collection mappings string collectionsFileName = visma.GetCollectionsPath(); Dictionary <string, string> collectionsDict = new Dictionary <string, string>(); try { collectionsDict = File.ReadAllLines(collectionsFileName).Select(line => line.Split(',')).ToDictionary(line => line[0], line => line[2]); } catch (Exception ex) { Log(" Unable to load collections CSV files from " + collectionsFileName); } // Get a list of Visma Articles - get all product in case of a Full update ArticleList list = visma.GetArticleList(updateStockData ? null : startDate); Log(string.Format("\n{0} products found in Visma database.", list.Count)); StatusUpdate(string.Format("Updating {0} products.", list.Count)); foreach (ArticleInfo articleInfo in list) { long? shopifyProductID = null; long? shopifyVariantID = null; long? shopifyVariantVatID = null; long? shopifyImageID = null; string images = null; string videos = null; string articleCode = articleInfo.ArticleCode; articlesCount += 1; // Get full Article object from Visma Article article = visma.GetArticleByCode(articleCode); string familyCode = article.FamilyCode; string articleName = null; decimal?vatRate = null; decimal?points = null; //Log(article.ProductGroupObject.Description.ToString()); if ((shop.articleTypes.Contains(article.ArticleType))) // && (article.FamilyCode == "532057") { Log(string.Format(" - Article {0} [{1}]", articleInfo.ArticleName, articleInfo.ArticleCode)); // Save article as Shopify Product if (!string.IsNullOrEmpty(article.ArticleName)) { if (!string.IsNullOrEmpty(article.FamilyCode)) { articleName = visma.GetCommonArticleNameForFamilyCode(article.FamilyCode); } // VAT Rate vatRate = visma.GetVatRate(article.ArticleCode); // Points points = visma.GetPoints(article.ArticleCode); // Video URL string videoUrl = null; string videoPath = visma.GetVideoFilePath(article.ArticleCode); if (File.Exists(videoPath)) { try { using (StreamReader sr = new StreamReader(videoPath)) { videoUrl = sr.ReadLine(); Log(string.Format(" - Video URL: {0}", videoUrl)); } } catch (System.Exception exp) { // Error creating stream or reading from it. Log(string.Format("Unable to open video file - {0}", exp.Message)); } } /* * if (article.ProductGroup > 0) * { * if (collectionsDict.ContainsKey(article.ProductGroup.ToString())) * { * string collectionName = collectionsDict[article.ProductGroup.ToString()]; * Log(collectionName); * } * * } */ DataSet.ProductDataTable productDT = productTA.GetDataByArticleCode(shop.ID, articleCode); if (productDT.Count == 0) { // Check if article has FamilyCode and if we already have a Shopify product with such FamilyCode if (!string.IsNullOrEmpty(familyCode)) { DataSet.ProductDataTable productFamilyDT = productTA.GetDataByFamilyCode(shop.ID, familyCode); if (productFamilyDT.Count > 0) { // Use existing Shopify Product ID and add this article as its variant shopifyProductID = productFamilyDT[0].ShopifyProductID; } } if (shopifyProductID == null) { // Create article as a new Shopify Product try { DateTime?deliveryDate = visma.GetDeliveryDate(article.ArticleCode); //Log(" - Delivery date: " + deliveryDate.ToString()); shop.CreateUpdateProduct(article, ref shopifyProductID, ref shopifyVariantID, ref shopifyVariantVatID, deliveryDate, articleName, vatRate, videoUrl, points); Log(string.Format(" - Shopify Product [{0}] created.", shopifyProductID)); //DataSet.CustomerDataTable customerDT = new DataSet.CustomerDataTable(); productTA.InsertProduct(shop.ID, shopifyProductID, shopifyVariantID, shopifyVariantVatID, articleCode, null, null, null, null, familyCode, deliveryDate, videoUrl); articleUpdates += 1; } catch (System.Net.WebException ex) { LogError("Unable to create Shopify Product", ex); } } else { // Create article as a new Variant of existing Shopify Product (with the same FamilyCode) try { shop.CreateUpdateProductVariants(article, shopifyProductID.Value, ref shopifyVariantID, ref shopifyVariantVatID, null, null, null, null, articleName); Log(string.Format(" - Shopify Product Variant [{0}] created.", shopifyVariantID)); productTA.InsertProduct(shop.ID, shopifyProductID, shopifyVariantID, shopifyVariantVatID, articleCode, null, null, null, null, familyCode, null, videoUrl); } catch (System.Net.WebException ex) { LogError("Unable to create Shopify Product Variant", ex); } } } else { //string productData = shop.GetProductDataFromVismaArticle(article, shopifyVariantID, shopifyVariantVatID); try { shopifyProductID = productDT[0].ShopifyProductID; shopifyVariantID = productDT[0].ShopifyVariantID; shopifyVariantVatID = productDT[0].ShopifyVariantVatID; shopifyImageID = productDT[0].ShopifyImageID; images = productDT[0].Images; videos = productDT[0].Videos; string videoUrlNew = (string.IsNullOrEmpty(videos)) ? videoUrl : null; DateTime?deliveryDate = visma.GetDeliveryDate(article.ArticleCode); //Log(" - Delivery date: " + deliveryDate.ToString()); shop.CreateUpdateProduct(article, ref shopifyProductID, ref shopifyVariantID, ref shopifyVariantVatID, deliveryDate, articleName, vatRate, videoUrlNew, points); Log(string.Format(" - Shopify Product [{0}] updated.", shopifyProductID)); articleUpdates += 1; } catch (System.Net.WebException ex) { LogError("Unable to update Shopify Product", ex); } //Log(" - Shopify Product already exists."); } // Product images images = (images == null) ? "" : images; List <string> productImageNameIDs = images.Split('|').Where(x => !string.IsNullOrEmpty(x)).ToList(); List <string> productImageNames = productImageNameIDs.Select(x => x.Split(':').FirstOrDefault()).ToList(); if ((shopifyProductID != null) && (updateArticleImages)) // && ((shopifyImageID == null) || (shopifyImageID == 0))) { string imagesFilter = visma.GetImageFilesFilter(articleCode); string[] imagesNames = Directory.GetFiles(visma.GetImagePath(), imagesFilter); foreach (string imagePath in imagesNames) { string imageName = imagePath.Replace(visma.GetImagePath(), ""); string articleCodeEscaped = articleCode.Replace("/", "-"); string articleCodeNoSuffix = articleCodeEscaped + "."; string articleCodeWithSuffix = articleCodeEscaped + "_img"; // Check file extension if ((imageName.StartsWith(articleCodeNoSuffix) || imageName.StartsWith(articleCodeWithSuffix)) && ((imageName.ToLower().EndsWith("jpeg")) || (imageName.ToLower().EndsWith("jpg")) || (imageName.ToLower().EndsWith("png")))) { Log(imageName); // If image with that name is not already in Shopify if ((File.Exists(imagePath)) && (!productImageNames.Contains(imageName))) { System.IO.FileStream inFile; byte[] binaryData; string base64String; try { inFile = new System.IO.FileStream(imagePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); binaryData = new Byte[inFile.Length]; long bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length); inFile.Close(); base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length); string productImageData = shop.GetProductImageData(article, base64String); //Log(productImageData); try { object response = shop.CreateProductImage(shopifyProductID.Value, productImageData); //Log("Response " + response.ToString()); JObject productResponse = JsonConvert.DeserializeObject <JObject>(response.ToString()); long imageID; long.TryParse(productResponse["image"]["id"].ToString(), out imageID); shopifyImageID = imageID; Log(string.Format(" - New product image created {0}", shopifyImageID)); /* * if (shopifyImageID > 0) * { * productTA.UpdateProductImageID(shopifyImageID, shop.ID, shopifyProductID); * } */ string nameID = imageName + ":" + imageID.ToString(); productImageNameIDs.Add(nameID); } catch (System.Net.WebException ex) { LogError("Unable to create product Image", ex); } } catch (System.Exception exp) { // Error creating stream or reading from it. Log(string.Format("Unable to open image file - {0}", exp.Message)); } } } } string newImages = string.Join("|", productImageNameIDs.ToArray()); if ((!string.IsNullOrEmpty(newImages)) && (newImages != images)) { productTA.UpdateImages(newImages, shop.ID, shopifyProductID); } } } else { Log(" - Unable to create product - No name value"); } } if ((articleLimit > 0) && (articlesCount >= articleLimit)) { break; } } return(true); }