//using Microsoft.EntityFrameworkCore; //using PartSource.Automation.Jobs.Interfaces; //using PartSource.Automation.Services; //using PartSource.Data; //using PartSource.Data.Models; //using PartSource.Data.Nexpart; //using PartSource.Data.Shopify; //using PartSource.Services; //using System; //using System.Collections.Concurrent; //using System.Collections.Generic; //using System.Data; //using System.Data.SqlClient; //using System.IO; //using System.Linq; //using System.Text; //using System.Text.RegularExpressions; //using System.Threading.Tasks; //namespace PartSource.Automation.Jobs //{ // public class UpdateFitmentCopy : AddProducts, IAutomationJob // { // private readonly IServiceProvider _serviceProvider; // private readonly SuperOldShopifyService _shopifyService; // private readonly PartSourceContext _partSourceContext; // private readonly NexpartService _nexpartService; // private ConcurrentQueue _shopifyIdQueue; // private string _connectionString = "Server=tcp:ps-whi.database.windows.net,1433;Initial Catalog=ps-whi-stage;Persist Security Info=False;User ID=ps-whi;Password=9-^*N5dw!6:|.5Q;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=3600;"; // private readonly int _threadCount = 1; // public UpdateFitmentCopy(IServiceProvider serviceProvider, PartSourceContext partSourceContext, SuperOldShopifyService shopifyService, NexpartService nexpartService) : base(serviceProvider, partSourceContext, nexpartService, shopifyService) // { // _serviceProvider = serviceProvider; // _nexpartService = nexpartService; // _shopifyService = shopifyService; // _partSourceContext = partSourceContext; // } // new public void Run() // { // Console.WriteLine(""); // UpdateMetafields(26); // //UpdatePublished(); // //FitmentReport(); // // List shopifyIds = _partSourceContext.ImportData.Where(s => s.IsFitment.Value && s.ShopifyId != null).Select(s => (long)s.ShopifyId).ToList(); // //List shopifyIds = _partSourceContext.ImportData.Where(s => s.ShopifyId != null).Select(s => (long)s.ShopifyId).ToList(); // //_shopifyIdQueue = new ConcurrentQueue(shopifyIds); // //Parallel.For(0, _threadCount, i => // // { // // //Categorize(); // // }); // // }); // } // private IList GetYmmFitmentTags(BuyersGuideSearchResponse response) // { // BuyersGuideMake[] makes = response?.ResponseBody?.Apps?.Make; // if (makes == null) // { // return new List(); // } // IList fitmentTags = new List(); // foreach (BuyersGuideMake make in makes) // { // foreach (BuyersGuideModel model in make.Model) // { // IList years = new List(); // for (int year = model.FromYear; year <= model.ToYear; year++) // { // years.Add(year); // } // string tag = $"{string.Join('-', years)} {make.Name} {model.Name}"; // fitmentTags.Add(tag); // } // } // return fitmentTags; // } // //private IList GetVehicleIdFitmentTags(BuyersGuideSearchResponse response) // //{ // // BuyersGuideMake[] makes = response?.ResponseBody?.Apps?.Make; // // if (makes == null) // // { // // return new List(); // // } // // IList fitmentTags = new List(); // // foreach (BuyersGuideMake make in makes) // // { // // foreach (BuyersGuideModel model in make.Model) // // { // // foreach (BuyersGuideEngine engine in model.Engine) // // { // // IList vehicleIds = _partSourceContext.VehicleData.Where(d => // // d.EngineDescription == engine.Desc // // && d.Year == engine.Year // // && d.MakeName == make.Name // // && d.ModelName == model.Name // // ) // // .Select(d => d.VehicleToEngineConfigId) // // .ToList(); // // foreach (int id in vehicleIds) // // { // // string tag = $"v{id}"; // // fitmentTags.Add(tag); // // } // // } // // } // // } // // return fitmentTags; // //} // /* public void UpdateFitmentViaBuyersGuideSearch() // { // int i = 0; // IList products = _shopifyService.GetManyProducts(250, i).Result; // while (products.Count > 0) // { // foreach (Product product in products) // { // try // { // //if (product.Tags.Contains("-v") || product.Tags.ToLowerInvariant().Contains("zzzisfitment=false")) // //{ // // continue; // //} // ImportData importData = _partSourceContext.ImportData.FirstOrDefault(p => p.ShopifyId == product.Id); // if (importData == null || !importData.IsFitment.Value) // { // continue; // } // importData.DcfMappings = _partSourceContext.DcfMappings.Where(d => d.LineCode == importData.LineCode).ToList(); // BuyersGuideSearch buyersGuideSearch = new BuyersGuideSearch(); // List ymmFitmentTags = new List(); // List vehicleIdFitmentTags = new List(); // foreach (DcfMapping mapping in importData.DcfMappings) // { // buyersGuideSearch = new BuyersGuideSearch // { // Part = new BuyersGuidePart // { // PartNumber = importData.PartNumber, // MfrCode = mapping.WhiCode // } // }; // BuyersGuideSearchResponse response = _nexpartService.SendRequest(buyersGuideSearch).Result; // if (response.ResponseBody != null) // { // ymmFitmentTags.AddRange(GetYmmFitmentTags(response)); // //vehicleIdFitmentTags.AddRange(GetVehicleIdFitmentTags(response)); // } // } // bool published = true; // List productTags = new List // { // importData.LineCode, // importData.PartNumber // }; // published = (ymmFitmentTags.Count > 0 || vehicleIdFitmentTags.Count > 0); // productTags.Add($"zzzisFitment={importData.IsFitment}"); // productTags.AddRange(vehicleIdFitmentTags); // productTags.AddRange(ymmFitmentTags); // if (productTags.Count > 249) // { // string message = $"Truncating {importData.VariantSku} - {productTags.Count} product tags"; // // Console.WriteLine(message); // productTags = productTags.Take(249).ToList(); // } // published = (ymmFitmentTags.Count > 0 || vehicleIdFitmentTags.Count > 0); // product.Tags = string.Join(",", productTags); // product.PublishedAt = published ? (DateTime?)DateTime.Now : null; // bool updateResult = _shopifyService.UpdateProduct(product).Result; // if (updateResult) // { // if (published) // { // Console.WriteLine($"{product.Id}"); // } // } // else // { // Console.WriteLine($"Failed to update product {product.Id}"); // } // } // catch (Exception ex) // { // Console.WriteLine($"{ex.Message}"); // } // } // i++; // products = _shopifyService.GetManyProducts(250, i).Result; // } // } */ // /* private void UpdatePublished() // { // DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder(); // optionsBuilder.UseSqlServer(_connectionString); // PartSourceContext threadDbContext = new PartSourceContext(optionsBuilder.Options); // int i = 0; // int updated = 0; // IList products = _shopifyService.GetManyProducts(250, i).Result; // while (products.Count > 0) // { // foreach (Product product in products) // { // try // { // ImportData importData = threadDbContext.ImportData.FirstOrDefault(p => p.ShopifyId == product.Id); // if (importData == null || !importData.IsFitment.Value) // { // continue; // } // if (product.PublishedAt == null) // { // if (product.Tags.Contains("-v")) // { // IList tags = product.Tags.Split(','); // string fitmentTag = tags.Where(t => t.ToLowerInvariant().Contains("zzzisfitment")).FirstOrDefault(); // tags.Remove(fitmentTag); // tags.Add("zzzisFitment=True"); // product.Tags = string.Join(',', tags); // product.PublishedAt = DateTime.Now; // bool result = _shopifyService.UpdateProduct(product).Result; // updated++; // } // } // } // catch (Exception ex) // { // continue; // } // } // i++; // products = _shopifyService.GetManyProducts(250, i).Result; // Console.Write($"\ri={i}"); // } // } */ // private void FitmentReport() // { // IList importCache = _partSourceContext.ImportData.Where(s => s.IsFitment.Value && s.ShopifyId != null).ToList(); // IList mappingCache = _partSourceContext.DcfMappings.ToList(); // Regex regex = new Regex("v[0-9]{6}"); // using (StreamWriter writer = File.AppendText("c:\\users\\tommy\\desktop\\fitment report.csv")) // { // writer.WriteLine("Line Code,Part Number,WHI Match"); // int i = 0; // IList products = _shopifyService.GetManyProducts(250, i).Result; // while (products.Count > 0) // { // try // { // foreach (Product product in products) // { // ImportData importData = importCache.Join( // mappingCache, // d => d.LineCode, // m => m.LineCode, // (d, m) => d // ) // .FirstOrDefault(p => p.ShopifyId == product.Id); // if (importData == null || !importData.IsFitment.Value || product.Variants.Length == 0) // { // continue; // } // bool tagged = regex.IsMatch(product.Tags); // if (!tagged) // { // // IList whiCodes = mappingCache.Where(d => d.LineCode == importData.LineCode).Select(d => d.WhiCode).ToList(); // writer.WriteLine($"{importData.LineCode},{importData.PartNumber},{tagged}"); // } // } // i++; // products = _shopifyService.GetManyProducts(250, i).Result; // } // catch (Exception ex) // { // Console.WriteLine("whoops"); // } // } // } // } // private void UpdateMetafields(int i) // { // DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder(); // optionsBuilder.UseSqlServer(_connectionString); // ShopifyClient shopifyClient = new ShopifyClient(new Ratermania.Shopify.ShopifyOptionsBuilder // { // ShopDomain = "partsource.myshopify.com", // ApiVersion = "2020-01", // ApiKey = "88f931933b566ade1fc92c6a39f04b34", // ApiSecret = "527a3b4213c2c7ecb214728a899052df" // }); // PartSourceContext threadDbContext = new PartSourceContext(optionsBuilder.Options); // threadDbContext.Database.SetCommandTimeout(1440); // IList products = _shopifyService.GetManyProducts(250, i).Result; // while (products.Count > 0) // { // try // { // foreach (Product product in products) // { // try // { // if (product.Tags.Contains("-v") || product.Tags.ToLowerInvariant().Contains("zzzisfitment=false")) // { // continue; // } // ImportData test = threadDbContext.ImportData.First(); // ImportData importData = threadDbContext.ImportData.FirstOrDefault(p => p.ShopifyId == product.Id); // if (importData == null) // { // continue; // } // bool published = true; // List productTags = new List // { // importData.LineCode, // importData.PartNumber // }; // IDictionary> positions = new Dictionary>(); // string partNumber = Regex.Replace(importData.PartNumber, "[^a-zA-Z0-9]", string.Empty); // string sql = $"select distinct BaseVehicleId, EngineConfigId, LineCode, PartNumber, Position from dbo.Fitment where LineCode in (select WhiCode from DcfMapping where LineCode='{importData.LineCode}') and PartNumber = '{partNumber}'"; // IList fitments = _partSourceContext.Fitments.FromSql(sql).ToList(); // foreach (Fitment fitment in fitments) // { // fitment.Position = fitment.Position.Replace("\"", string.Empty); // if (string.IsNullOrEmpty(fitment.Position)) // { // continue; // } // VehicleData vehicle = _partSourceContext.VehicleData.FirstOrDefault(v => v.BaseVehicleId == fitment.BaseVehicleId && v.EngineConfigId == fitment.EngineConfigId); // if (vehicle == null) // { // continue; // } // if (positions.ContainsKey(fitment.Position)) // { // positions[fitment.Position].Add(vehicle.VehicleToEngineConfigId.ToString()); // } // else // { // positions.Add(fitment.Position, new List // { // vehicle.VehicleToEngineConfigId.ToString() // }); // } // } // foreach (KeyValuePair> position in positions) // { // Metafield metafield = new Metafield // { // OwnerId = product.Id, // OwnerResource = "product", // Namespace = "partsource", // Key = position.Key, // Value = string.Join(',', position.Value), // ValueType = "string" // }; // var x = shopifyClient.Metafields.Add(metafield).Result; // Console.WriteLine(product.Id); // } // } // catch (Exception ex) // { // Console.WriteLine($"{ex.Message}"); // } // } // i += _threadCount; // products = _shopifyService.GetManyProducts(250, i).Result; // Console.WriteLine(i); // } // catch (Exception ex) // { // Console.WriteLine($"{ex.Message}"); // } // } // } // private MenuNode[] GetMenuNodes(int menuId, int numberOfLevels, int? parentMenuNodeId = null) // { // MenuNodesLookup request = new MenuNodesLookup // { // MenuId = menuId, // NumberOfLevels = numberOfLevels, // ParentMenuNodeId = parentMenuNodeId // }; // MenuNodesLookupResponse response = _nexpartService.SendRequest(request).Result; // return response.ResponseBody.MenuNode; // } // //private bool IsFitmentLineCode(string lineCode) // //{ // // string sql = $"select WhiCode from DcfMapping where PartSourceCode='{importData.LineCode}'"; // // using (DataTable dataTable = new DataTable()) // // { // // using (SqlConnection connection = new SqlConnection(_connectionString)) // // { // // connection.Open(); // // using (SqlCommand command = new SqlCommand(sql, connection)) // // { // // SqlDataAdapter dataAdapter = new SqlDataAdapter(command); // // dataAdapter.Fill(dataTable); // // } // // } // // if (dataTable.Rows.Count == 0) // // { // // return false; // // } // // lineCode = dataTable.Rows[0]["WhiCode"].ToString(); // // } // //} // } //}