using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using PartSource.Automation.Models; using PartSource.Data; using PartSource.Data.Contexts; using PartSource.Data.Models; using PartSource.Services; using Ratermania.Automation.Interfaces; using Ratermania.Shopify; using Ratermania.Shopify.Exceptions; using Ratermania.Shopify.Resources; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace PartSource.Automation.Jobs { public class UpdateFitment : IAutomationJob { private readonly ILogger _logger; private readonly ShopifyClient _shopifyClient; private readonly PartSourceContext _partSourceContext; private readonly FitmentContext _fitmentContext; private readonly VehicleService _vehicleService; public UpdateFitment(ILogger logger, PartSourceContext partSourceContext, FitmentContext fitmentContext, ShopifyClient shopifyClient, VehicleService vehicleService) { _logger = logger; _partSourceContext = partSourceContext; _fitmentContext = fitmentContext; _shopifyClient = shopifyClient; _vehicleService = vehicleService; } public async Task Run() { IEnumerable products = null; try { products = await _shopifyClient.Products.Get(new Dictionary { { "limit", 250 } }); } catch (Exception ex) { _logger.LogError("Failed to get products from Shopify", ex); throw; } int i = 1; while (products != null && products.Any()) { foreach (Product product in products) { // Wiper blades are a separate fitment process. if (product.ProductType.Contains("CA172-SC231")) { continue; } ImportData importData = null; try { IEnumerable metafields = await _shopifyClient.Metafields.Get(new Dictionary { { "metafield[owner_id]", product.Id }, { "metafield[owner_resource]", "product" } }); //importData = await _partSourceContext.ImportData.FirstOrDefaultAsync(parts => parts.ShopifyId == product.Id); //if (importData == null) //{ // continue; importData = new ImportData { LineCode = metafields.FirstOrDefault(m => m.Key == "custom_label_0").Value ?? string.Empty, PartNumber = product.Title.Split(' ')[0], VariantSku = product.Variants[0].Sku // They know we can't do fitment for variants }; // } bool isFitment = false; string bodyHtml = product.BodyHtml[..(product.BodyHtml.IndexOf("") + "".Length)]; IList vehicles = _vehicleService.GetVehiclesForPart(importData.PartNumber, importData.LineCode); IList vehicleIdFitment = _vehicleService.GetVehicleIdFitment(vehicles); if (vehicleIdFitment.Any()) { string vehicleIdString = string.Join('-', vehicleIdFitment.Select(j => $"v{j}")); bodyHtml += $"
{vehicleIdString}
"; isFitment = true; string json = JsonConvert.SerializeObject(vehicleIdFitment); Metafield vehicleMetafield = new Metafield { Namespace = "fitment", Key = "ids", Value = json, ValueType = "json_string", OwnerResource = "product", OwnerId = product.Id }; await _shopifyClient.Metafields.Add(vehicleMetafield); } IList ymmFitment = _vehicleService.GetYmmFitment(vehicles); if (ymmFitment.Count > 0) { isFitment = true; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(""); foreach (string fitment in ymmFitment) { try { string[] parts = fitment.Split(' ', 2); stringBuilder.AppendLine($""); } catch { // This is still a POC at this point. Oh well... } } stringBuilder.AppendLine("
This Part Fits
{parts[1]}{parts[0].Replace("-", ", ")}
"); bodyHtml += $"
{stringBuilder.ToString()}
"; string json = JsonConvert.SerializeObject(ymmFitment); Metafield ymmMetafield = new Metafield { Namespace = "fitment", Key = "seo", Value = json, ValueType = "json_string", OwnerResource = "product", OwnerId = product.Id }; await _shopifyClient.Metafields.Add(ymmMetafield); } Metafield isFitmentMetafield = new Metafield { Namespace = "Flags", Key = "IsFitment", Value = isFitment.ToString(), ValueType = "string", OwnerResource = "product", OwnerId = product.Id }; await _shopifyClient.Metafields.Add(isFitmentMetafield); Metafield lineCodeMetafield = new Metafield { Namespace = "google", Key = "custom_label_0", Value = importData.LineCode, ValueType = "string", OwnerResource = "product", OwnerId = product.Id }; // await _shopifyClient.Metafields.Add(lineCodeMetafield); Metafield partNumberMetafield = new Metafield { Namespace = "google", Key = "custom_label_1", Value = importData.PartNumber, ValueType = "string", OwnerResource = "product", OwnerId = product.Id }; //await _shopifyClient.Metafields.Add(partNumberMetafield); List tags = new List(); for (int j = 0; j < vehicleIdFitment.Count; j += 25) { tags.Add(string.Join('-', vehicleIdFitment.Skip(j).Take(25).Select(j => $"v{j}"))); } tags.AddRange(ymmFitment); if (tags.Count > 249) { tags = tags.Take(249).ToList(); } string zzzIsFitment = isFitment ? "zzzIsFitment=true" : "zzzIsFitment=false"; tags.Add(zzzIsFitment); product.Tags = string.Join(',', tags); product.BodyHtml = bodyHtml; await _shopifyClient.Products.Update(product); importData.IsFitment = isFitment; importData.UpdatedAt = DateTime.Now; importData.UpdateType = "Fitment"; } catch (Exception ex) { _logger.LogError($"Failed to updated fitment data for SKU {importData?.VariantSku} - {ex.Message}", ex); } } try { Console.WriteLine(i); _partSourceContext.SaveChanges(); products = await _shopifyClient.Products.GetNext(); i++; } catch (Exception ex) { _logger.LogWarning(ex, "Failed to get the next set of products. Retrying"); products = await _shopifyClient.Products.GetPrevious(); } } } } }