Whatever this is

This commit is contained in:
2025-02-12 18:12:19 -05:00
parent aed30707be
commit cc2cbd09e1
20 changed files with 496 additions and 434 deletions

View File

@@ -4,6 +4,7 @@ using PartSource.Data.Dtos;
using PartSource.Data.Models; using PartSource.Data.Models;
using PartSource.Data.Nexpart; using PartSource.Data.Nexpart;
using PartSource.Services; using PartSource.Services;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -41,14 +42,27 @@ namespace PartSource.Api.Controllers
return NotFound(); return NotFound();
} }
Item[] items = new[] try
{ {
new Item { PartNumber = vehicleFitment.PartNumber, MfrCode = vehicleFitment.LineCode } string[] segments = vehicleFitment.NoteText.Split(']');
}; vehicleFitment.PartDescription = segments[0].TrimStart('[');
vehicleFitment.DriveTypes = GetDriveTypesFromNote(vehicleFitment.NoteText);
vehicleFitment.Notes = segments[1].Split(';')
.Select(n => n.Trim())
.ToList();
}
catch
{
throw new InvalidOperationException($"The note_text field provided by WHI for {vehicleFitment.LineCode} {vehicleFitment.PartNumber} was in an invalid format.");
}
SmartPageDataSearch smartPageDataSearch = new SmartPageDataSearch SmartPageDataSearch smartPageDataSearch = new SmartPageDataSearch
{ {
Items = items Items = new[]
{
new Item { PartNumber = vehicleFitment.PartNumber, MfrCode = vehicleFitment.LineCode }
}
}; };
SmartPageDataSearchResponse smartPageResponse = await _nexpartService.SendRequest<SmartPageDataSearch, SmartPageDataSearchResponse>(smartPageDataSearch); SmartPageDataSearchResponse smartPageResponse = await _nexpartService.SendRequest<SmartPageDataSearch, SmartPageDataSearchResponse>(smartPageDataSearch);
@@ -74,10 +88,8 @@ namespace PartSource.Api.Controllers
}; };
ApplicationSearchResponse response = await _nexpartService.SendRequest<ApplicationSearch, ApplicationSearchResponse>(applicationSearch); ApplicationSearchResponse response = await _nexpartService.SendRequest<ApplicationSearch, ApplicationSearchResponse>(applicationSearch);
if (response.ResponseBody != null) if (response.ResponseBody != null && response.ResponseBody is Questions)
{ {
vehicleFitment.DriveTypes = new List<string>();
Question driveTypeQuestion = ((Questions)response.ResponseBody).Question Question driveTypeQuestion = ((Questions)response.ResponseBody).Question
.Where(q => q.Attribute == "DRIVE_TYPE") .Where(q => q.Attribute == "DRIVE_TYPE")
.FirstOrDefault(); .FirstOrDefault();
@@ -124,7 +136,7 @@ namespace PartSource.Api.Controllers
{ {
return BadRequest(new return BadRequest(new
{ {
Message = $"No vehicle data is available for SKU {sku}. Confirm it is available in the database maintained by Sound Press.", Message = $"No vehicle data is available for vehicle ID {vehicleId}. Confirm it is available in the database maintained by Sound Press.",
Reason = $"{nameof(_vehicleService.GetVehicleById)} returned null" Reason = $"{nameof(_vehicleService.GetVehicleById)} returned null"
}); });
} }
@@ -167,13 +179,13 @@ namespace PartSource.Api.Controllers
MfrCode = mappings.Select(m => m.WhiCode).ToArray(), MfrCode = mappings.Select(m => m.WhiCode).ToArray(),
PartType = new[] { new PartType { Id = smartPageResponse.ResponseBody.Item[0].Part.PartType.Id } }, PartType = new[] { new PartType { Id = smartPageResponse.ResponseBody.Item[0].Part.PartType.Id } },
Criterion = new[] Criterion = new[]
{
new Criterion
{ {
new Criterion Attribute = "REGION",
{ Id = 2
Attribute = "REGION", }
Id = 2 },
}
},
GroupBy = "PARTTYPE" GroupBy = "PARTTYPE"
}; };
@@ -205,5 +217,33 @@ namespace PartSource.Api.Controllers
}); });
} }
private IList<string> GetDriveTypesFromNote(string fitmentNote)
{
fitmentNote = fitmentNote.ToUpperInvariant();
IList<string> driveTypes = new List<string>();
if (fitmentNote.Contains("FWD"))
{
driveTypes.Add("FWD");
}
if (fitmentNote.Contains("RWD"))
{
driveTypes.Add("RWD");
}
if (fitmentNote.Contains("AWD"))
{
driveTypes.Add("AWD");
}
if (fitmentNote.Contains("4WD"))
{
driveTypes.Add("4WD");
}
return driveTypes;
}
} }
} }

View File

@@ -2,7 +2,7 @@
"ConnectionStrings": { "ConnectionStrings": {
"PartSourceDatabase": "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=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;", "PartSourceDatabase": "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=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
//"FitmentDatabase": "Data Source=localhost;Initial Catalog=WhiFitment;Integrated Security=true" //"FitmentDatabase": "Data Source=localhost;Initial Catalog=WhiFitment;Integrated Security=true"
"FitmentDatabase": "Server=tcp:ps-automation.eastus2.cloudapp.azure.com,1433;Initial Catalog=WhiFitment;User ID=automation;Password=)6L)XP%m(x-UU#M;Encrypt=True;TrustServerCertificate=True;Connection Timeout=300" "FitmentDatabase": "Server=tcp:ps-automation.eastus2.cloudapp.azure.com,1433;Initial Catalog=WhiFitment;User ID=sa;Password=GZ0`-ekd~[2u;Encrypt=True;TrustServerCertificate=True;Connection Timeout=300"
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {

View File

@@ -22,11 +22,13 @@ namespace PartSource.Automation.Jobs.POC
{ {
private readonly NexpartService _nexpartService; private readonly NexpartService _nexpartService;
private readonly PartSourceContext _partSourceContext; private readonly PartSourceContext _partSourceContext;
private readonly FitmentContext _fitmentContext;
public GetImageUrls(NexpartService nexpartService, PartSourceContext partSourceContext) public GetImageUrls(NexpartService nexpartService, PartSourceContext partSourceContext, FitmentContext fitmentContext)
{ {
_nexpartService = nexpartService; _nexpartService = nexpartService;
_partSourceContext = partSourceContext; _partSourceContext = partSourceContext;
_fitmentContext = fitmentContext;
} }
public async Task Run(CancellationToken token, params string[] arguments) public async Task Run(CancellationToken token, params string[] arguments)
@@ -34,45 +36,54 @@ namespace PartSource.Automation.Jobs.POC
IList<string> rows = new List<string> { IList<string> rows = new List<string> {
"\"Line Code\", \"Part Number\", \"Image URL(s)\"" "\"Line Code\", \"Part Number\", \"Image URL(s)\""
}; };
IList<ImportData> importData = await _partSourceContext.ImportData
//.Take(5000)
.ToListAsync();
foreach (ImportData item in importData) IList<Data.Models.Part> parts = await _fitmentContext.Parts.ToListAsync();
string oldLineCode = string.Empty;
IList<DcfMapping> mappings = new List<DcfMapping>();
foreach (Data.Models.Part part in parts)
{ {
SmartPageDataSearch dataSearch = new SmartPageDataSearch if (part.LineCode != oldLineCode)
{ {
Items = new Item[] mappings = await _fitmentContext.DcfMappings.Where(d => d.LineCode == part.LineCode).ToListAsync();
}
;
foreach (DcfMapping mapping in mappings)
{
SmartPageDataSearch dataSearch = new SmartPageDataSearch
{ {
Items = new Item[]
{
new Item new Item
{ {
MfrCode = item.LineCode, MfrCode = mapping.WhiCode,
PartNumber = item.PartNumber PartNumber = part.PartNumber
} }
}, },
DataOption = new[] { "DIST_LINE", "ALL" } DataOption = new[] { "ALL" }
};
SmartPageDataSearchResponse response = await _nexpartService.SendRequest<SmartPageDataSearch, SmartPageDataSearchResponse>(dataSearch);
if (response.ResponseBody.Item?.Length > 0)
{
List<string> urls = new List<string>();
if (!string.IsNullOrEmpty(response.ResponseBody.Item[0].PrimaryImg?.ImgUrl))
{
urls.Add(response.ResponseBody.Item[0].PrimaryImg?.ImgUrl);
}; };
if (response.ResponseBody.Item[0].AddImgs?.AddImg?.Length > 0) SmartPageDataSearchResponse response = await _nexpartService.SendRequest<SmartPageDataSearch, SmartPageDataSearchResponse>(dataSearch);
{
urls.AddRange(response.ResponseBody.Item[0].AddImgs.AddImg.Select(i => i.AddImgUrl));
}
if (urls.Count > 0) if (response.ResponseBody.Item?.Length > 0)
{ {
rows.Add($"\"{item.LineCode}\", \"{item.PartNumber}\", \"{string.Join(";", urls)}\""); List<string> urls = new List<string>();
if (!string.IsNullOrEmpty(response.ResponseBody.Item[0].PrimaryImg?.ImgUrl))
{
urls.Add(response.ResponseBody.Item[0].PrimaryImg?.ImgUrl);
};
if (response.ResponseBody.Item[0].AddImgs?.AddImg?.Length > 0)
{
urls.AddRange(response.ResponseBody.Item[0].AddImgs.AddImg.Select(i => i.AddImgUrl));
}
if (urls.Count > 0)
{
rows.Add($"\"{part.LineCode}\", \"{part.PartNumber}\", \"{string.Join(";", urls)}\"");
}
} }
} }

View File

@@ -0,0 +1,89 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PartSource.Automation.Models.Jobs;
using PartSource.Automation.Services;
using PartSource.Data.Contexts;
using PartSource.Data.Models;
using Ratermania.Automation.Interfaces;
using Ratermania.Shopify;
using Ratermania.Shopify.Resources;
using Ratermania.Shopify.Resources.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
namespace PartSource.Automation.Jobs
{
public class PartsSync : IAutomationJob
{
private readonly ILogger<UpdatePricing> _logger;
private readonly FitmentContext _fitmentContext;
private readonly ShopifyClient _shopifyClient;
public PartsSync(ILogger<UpdatePricing> logger, FitmentContext fitmentContext, ShopifyClient shopifyClient)
{
_logger = logger;
_fitmentContext = fitmentContext;
_shopifyClient = shopifyClient;
}
public async Task Run(CancellationToken token, params string[] arguments)
{
IEnumerable<Product> products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 } });
while (products != null && products.Any())
{
foreach (Product product in products)
{
try
{
IEnumerable<Metafield> metafields = await _shopifyClient.Metafields.Get(new Dictionary<string, object> { { "metafield[owner_id]", product.Id }, { "metafield[owner_resource]", "product" } });
Part part = new Part
{
LineCode = metafields.FirstOrDefault(m => m.Key == "custom_label_0")?.Value ?? string.Empty,
PartNumber = metafields.FirstOrDefault(m => m.Key == "custom_label_1")?.Value ?? string.Empty,
Sku = product.Variants[0].Sku // They know we can't do fitment for variants
};
// part.PartNumber = part.PartNumber.Replace("-", string.Empty);
if (
string.IsNullOrEmpty(part.LineCode)
|| string.IsNullOrEmpty(part.PartNumber)
|| int.TryParse(part.LineCode, out _)) //If the line code is numeric, it cannot have fitment data associated with it.
{
continue;
}
Part? existing = await _fitmentContext.Parts.FirstOrDefaultAsync(p => p.Sku == part.Sku);
if (existing == null)
{
await _fitmentContext.Parts.AddAsync(part);
await _fitmentContext.SaveChangesAsync();
}
}
catch (Exception ex)
{
_logger.LogInformation(ex.Message);
}
}
try
{
products = await _shopifyClient.Products.GetNext();
}
catch (Exception ex)
{
_logger.LogInformation(ex.Message);
}
}
}
}
}

View File

@@ -56,24 +56,25 @@ namespace PartSource.Automation.Jobs
fileGroups.Enqueue(fileGroup); fileGroups.Enqueue(fileGroup);
} }
Task[] taskArray = new Task[12]; Task[] taskArray = new Task[18];
for (int i = 0; i < taskArray.Length; i++) for (int i = 0; i < taskArray.Length; i++)
{ {
taskArray[i] = Task.Factory.StartNew(() => taskArray[i] = Task.Factory.StartNew(() =>
{ {
while (fileGroups.TryDequeue(out IGrouping<string, FileInfo> fileGroup)) while (fileGroups.TryDequeue(out IGrouping<string, FileInfo> fileGroup))
{ {
string tableName = string.Empty;
foreach (FileInfo fileInfo in fileGroup) foreach (FileInfo fileInfo in fileGroup)
{ {
try try
{ {
string filename = Decompress(fileInfo); string filename = Decompress(fileInfo);
string tableName = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.')); DataTable dataTable = GetDataTable(filename, out tableName);
DataTable dataTable = GetDataTable(filename); string tempTable = $"Fitment_{Guid.NewGuid():N}_{tableName}";
_whiSeoService.BulkCopyFitment(dataTable, tableName); _whiSeoService.BulkCopyFitment(dataTable, tempTable);
_logger.LogInformation($"Copied {fileInfo.Name} to the database."); _logger.LogInformation($"Copied {fileInfo.Name} to the database.");
File.Delete(filename); File.Delete(filename);
@@ -85,10 +86,9 @@ namespace PartSource.Automation.Jobs
} }
} }
string fitmentTable = fileGroup.Key.Substring(0, fileGroup.Key.IndexOf('.')); _whiSeoService.CreateFitmentTable(tableName);
_whiSeoService.CreateFitmentTable(fitmentTable);
_logger.LogInformation($"Created fitment table for part group {fitmentTable}."); _logger.LogInformation($"Created fitment table for part group {tableName}.");
} }
}); });
@@ -112,8 +112,10 @@ namespace PartSource.Automation.Jobs
return decompressedFile; return decompressedFile;
} }
private DataTable GetDataTable(string filename) private DataTable GetDataTable(string filename, out string lineCode)
{ {
lineCode = string.Empty;
using DataTable dataTable = new DataTable(); using DataTable dataTable = new DataTable();
dataTable.Columns.Add("LineCode", typeof(string)); dataTable.Columns.Add("LineCode", typeof(string));
dataTable.Columns.Add("PartNumber", typeof(string)); dataTable.Columns.Add("PartNumber", typeof(string));
@@ -121,8 +123,9 @@ namespace PartSource.Automation.Jobs
dataTable.Columns.Add("EngineConfigId", typeof(int)); dataTable.Columns.Add("EngineConfigId", typeof(int));
dataTable.Columns.Add("Position", typeof(string)); dataTable.Columns.Add("Position", typeof(string));
dataTable.Columns.Add("FitmentNoteHash", typeof(string)); dataTable.Columns.Add("FitmentNoteHash", typeof(string));
dataTable.Columns.Add("PartTerminologyId", typeof(int));
using StreamReader reader = new StreamReader(filename); using StreamReader reader = new StreamReader(filename);
string line = reader.ReadLine(); // Burn the header row string line = reader.ReadLine(); // Burn the header row
while (reader.Peek() > 0) while (reader.Peek() > 0)
@@ -135,7 +138,7 @@ namespace PartSource.Automation.Jobs
columns[i] = columns[i].Replace("\"", string.Empty); columns[i] = columns[i].Replace("\"", string.Empty);
} }
string lineCode = Regex.Replace(columns[0], "[^a-zA-Z0-9]", string.Empty).Trim(); lineCode = Regex.Replace(columns[0], "[^a-zA-Z0-9]", string.Empty).Trim();
string partNumber = Regex.Replace(columns[1], "[^a-zA-Z0-9]", string.Empty).Trim(); string partNumber = Regex.Replace(columns[1], "[^a-zA-Z0-9]", string.Empty).Trim();
string position = columns[7].Trim(); string position = columns[7].Trim();
@@ -149,10 +152,11 @@ namespace PartSource.Automation.Jobs
if (!string.IsNullOrEmpty(lineCode) if (!string.IsNullOrEmpty(lineCode)
&& !string.IsNullOrEmpty(partNumber) && !string.IsNullOrEmpty(partNumber)
&& int.TryParse(columns[2], out int partTerminologyId)
&& int.TryParse(columns[5], out int baseVehicleId) && int.TryParse(columns[5], out int baseVehicleId)
&& int.TryParse(columns[6], out int engineConfigId)) && int.TryParse(columns[6], out int engineConfigId))
{ {
dataTable.Rows.Add(new object[] { lineCode, partNumber, baseVehicleId, engineConfigId, position, noteTextHash }); dataTable.Rows.Add(new object[] { lineCode, partNumber, baseVehicleId, engineConfigId, position, noteTextHash, partTerminologyId });
} }
} }

View File

@@ -5,6 +5,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
using PartSource.Automation.Services; using PartSource.Automation.Services;
@@ -13,6 +14,7 @@ using PartSource.Data.Models;
using Ratermania.Automation.Interfaces; using Ratermania.Automation.Interfaces;
using Ratermania.Shopify; using Ratermania.Shopify;
using Ratermania.Shopify.Resources; using Ratermania.Shopify.Resources;
using System.Web;
namespace PartSource.Automation.Jobs namespace PartSource.Automation.Jobs
{ {
@@ -36,52 +38,22 @@ namespace PartSource.Automation.Jobs
public async Task Run(CancellationToken token, params string[] arguments) public async Task Run(CancellationToken token, params string[] arguments)
{ {
IEnumerable<Product> products = null; IList<string> productTypes = await _fitmentContext.ProductTypes
.Where(p => p.Active)
.Select(p => HttpUtility.UrlEncode(p.Name))
.ToListAsync();
IList<string> partTypes = new List<string> foreach (string productType in productTypes)
{ {
"CA115-SC118-FL11803_Custom Lighting Accessories", _logger.LogInformation("Processing {productType}", HttpUtility.UrlDecode(productType));
"CA117-SC141-FL14106_Jeep Accessories",
"CA117-SC141-FL14134_Truck Running Board and Steps",
"CA117-SC141-FL14199_Bumpers, Bull Bars & Brush Guards",
"CA117-SC157-FL15704_Headache Rack Frames",
"CA117-SC158-FL15802_Salters and Plow Accessories",
"CA117-SC699-FL69902_Crossover Boxes",
"CA117-SC699-FL69903_Specialty Boxes",
"CA117-SC699-FL69904_Transfer Tanks",
"CA135-SC176-FL17601_Trailer Lighting, Stop, Turn, Tail",
"CA135-SC186-FL18607_Roof Racks",
"CA135-SC186-FL18608_Bike Carriers",
"CA135-SC186-FL18609_Cargo Accessories",
"CA135-SC186-FL18610_Cargo Carriers",
"CA135-SC186-FL18611_Watersport Carriers",
"CA135-SC192-FL19201_Class 1 Hitches",
"CA135-SC192-FL19202_Class 2 Hitches",
"CA135-SC192-FL19203_Class 3 Hitches",
"CA135-SC192-FL19204_Towing, Heavy Duty",
"CA135-SC192-FL19205_Towing Electrical, Vehicle Specific",
"CA135-SC192-FL19206_Trailer Parts & Accessories",
"CA135-SC192-FL19207_Trailer Winches, Jacks & Couplers",
"CA135-SC192-FL19208_Class 5 Hitches",
"CA135-SC192-FL19221_Towing Electrical, Connectors & Adapters",
"CA135-SC192-FL19230_Towing Electrical, Controls & Converters",
"CA135-SC192-FL19235_Towing Electrical, Harnesses",
"CA135-SC192-FL19240_Towing Security, Non-Locking",
"CA135-SC192-FL19245_Towing Class V",
"CA135-SC192-FL19280_Towing Balls",
"CA135-SC192-FL19281_Towing Ball Mounts",
"CA135-SC192-FL19282_Towing Security, Locking",
"CA135-SC192-FL19283_Towing Kits & Acc"
};
foreach (string partType in partTypes) IEnumerable<Product> products = null;
{
try try
{ {
products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 }, { "product_type", partType } }); products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 }, { "product_type", productType } });
//products = new List<Product> //products = new List<Product>
//{ //{
// await _shopifyClient.Products.GetById(4388919574575) // await _shopifyClient.Products.GetById(7458071052335)
//}; //};
} }
@@ -91,13 +63,12 @@ namespace PartSource.Automation.Jobs
throw; throw;
} }
int i = 1;
while (products != null && products.Any()) while (products != null && products.Any())
{ {
foreach (Product product in products) foreach (Product product in products)
{ {
ImportData importData = null; ImportData importData = null;
bool isFitment = false;
try try
{ {
@@ -109,48 +80,32 @@ namespace PartSource.Automation.Jobs
VariantSku = product.Variants[0].Sku // They know we can't do fitment for variants VariantSku = product.Variants[0].Sku // They know we can't do fitment for variants
}; };
bool isFitment = false; importData.PartNumber = importData.PartNumber.Replace("-", string.Empty);
string bodyHtml = product.BodyHtml.Substring(0, product.BodyHtml.IndexOf("</ul>") + "</ul>".Length);
//If the line code is numeric, it cannot have fitment data associated with it.
if (int.TryParse(importData.LineCode, out _))
{
continue;
}
// Extract Partsource bullet points if present.
string bodyHtml = string.IsNullOrEmpty(product.BodyHtml)
? string.Empty
: product.BodyHtml.Substring(0, product.BodyHtml.IndexOf("</ul>") + "</ul>".Length);
IList<Vehicle> vehicles = _vehicleFitmentService.GetVehiclesForPart(importData.PartNumber, importData.LineCode); IList<Vehicle> vehicles = _vehicleFitmentService.GetVehiclesForPart(importData.PartNumber, importData.LineCode);
IList<int> vehicleIdFitment = _vehicleFitmentService.GetVehicleIdFitment(vehicles); IList<int> vehicleIdFitment = _vehicleFitmentService.GetVehicleIdFitment(vehicles);
if (!vehicleIdFitment.Any()) if (!vehicleIdFitment.Any())
{ {
Console.WriteLine($"No fitment data for SKU {importData.VariantSku}"); Console.WriteLine($"No fitment data for {importData.LineCode} {importData.PartNumber}");
continue; continue;
} }
if (vehicleIdFitment.Count > 0) string vehicleIdString = string.Join(',', vehicleIdFitment.Select(j => $"v{j}"));
{
string vehicleIdString = string.Join(',', vehicleIdFitment.Select(j => $"v{j}"));
bodyHtml += $"<div id=\"vehicleIDs\" style=\"display:none;\">{vehicleIdString}</div>"; bodyHtml += $"<div id=\"vehicleIDs\" style=\"display:none;\">{vehicleIdString}</div>";
isFitment = true;
isFitment = true;
string json = JsonConvert.SerializeObject(vehicleIdFitment);
if (json.Length < 100000)
{
Metafield vehicleMetafield = new Metafield
{
Namespace = "fitment",
Key = "ids",
Value = json,
Type = "json_string",
OwnerResource = "product",
OwnerId = product.Id
};
await _shopifyClient.Metafields.Add(vehicleMetafield);
}
else
{
_logger.LogWarning($"Vehicle ID fitment data for SKU {importData.VariantSku} is too large for Shopify and cannot be added.");
continue;
}
}
IList<string> ymmFitment = _vehicleFitmentService.GetYmmFitment(vehicles); IList<string> ymmFitment = _vehicleFitmentService.GetYmmFitment(vehicles);
if (ymmFitment.Count > 0) if (ymmFitment.Count > 0)
@@ -165,79 +120,20 @@ namespace PartSource.Automation.Jobs
try try
{ {
string[] parts = fitment.Split(' ', 2); string[] parts = fitment.Split(' ', 2);
stringBuilder.AppendLine($"<tr><td>{parts[1]}</td><td>{parts[0].Replace("-", ", ")}</td></tr>"); stringBuilder.AppendLine($"<tr><td>{parts[1]}</td><td>{parts[0].Replace("-", ", ")}</td></tr>");
} }
catch catch (Exception ex)
{ {
// This is still a POC at this point. Oh well... _logger.LogWarning(ex, "YMM fitment for {fitment} was in an invalid format", fitment);
} }
} }
stringBuilder.AppendLine("</table>"); stringBuilder.AppendLine("</table>");
bodyHtml += $"<div id=\"seoData\">{stringBuilder.ToString()}</div>"; bodyHtml += $"<div id=\"seoData\">{stringBuilder}</div>";
string json = JsonConvert.SerializeObject(ymmFitment);
if (json.Length < 100000)
{
Metafield ymmMetafield = new Metafield
{
Namespace = "fitment",
Key = "seo",
Value = json,
Type = "json_string",
OwnerResource = "product",
OwnerId = product.Id
};
await _shopifyClient.Metafields.Add(ymmMetafield);
}
else
{
_logger.LogWarning($"Year/make/model fitment data for SKU {importData.VariantSku} is too large for Shopify and cannot be added.");
continue;
}
} }
Metafield isFitmentMetafield = new Metafield
{
Namespace = "Flags",
Key = "IsFitment",
Value = isFitment.ToString(),
Type = "string",
OwnerResource = "product",
OwnerId = product.Id
};
await _shopifyClient.Metafields.Add(isFitmentMetafield);
//Metafield lineCodeMetafield = new Metafield
//{
// Namespace = "google",
// Key = "custom_label_0",
// Value = importData.LineCode,
// Type = "string",
// OwnerResource = "product",
// OwnerId = product.Id
//};
//await _shopifyClient.Metafields.Add(lineCodeMetafield);
//Metafield partNumberMetafield = new Metafield
//{
// Namespace = "google",
// Key = "custom_label_1",
// Value = importData.PartNumber,
// Type = "string",
// OwnerResource = "product",
// OwnerId = product.Id
//};
//await _shopifyClient.Metafields.Add(partNumberMetafield);
List<string> tags = new List<string>(); List<string> tags = new List<string>();
for (int j = 0; j < vehicleIdFitment.Count; j += 25) for (int j = 0; j < vehicleIdFitment.Count; j += 25)
@@ -275,12 +171,8 @@ namespace PartSource.Automation.Jobs
} }
try try
{ {
Console.WriteLine(i);
_partSourceContext.SaveChanges();
products = await _shopifyClient.Products.GetNext(); products = await _shopifyClient.Products.GetNext();
i++;
} }
catch (Exception ex) catch (Exception ex)
@@ -289,8 +181,6 @@ namespace PartSource.Automation.Jobs
products = await _shopifyClient.Products.GetPrevious(); products = await _shopifyClient.Products.GetPrevious();
} }
} }
Console.WriteLine($"Finished {partType}");
} }
} }
} }

View File

@@ -16,5 +16,7 @@ namespace PartSource.Automation.Models.Configuration
public string Username { get; set; } public string Username { get; set; }
public string Password { get; set; } public string Password { get; set; }
public int Port { get; set; }
} }
} }

View File

@@ -77,7 +77,7 @@ namespace PartSource.Automation
.AddAutomation(options => .AddAutomation(options =>
{ {
options.HasBaseInterval(new TimeSpan(0, 1, 0)) options.HasBaseInterval(new TimeSpan(0, 15, 0))
.HasMaxFailures(1) .HasMaxFailures(1)
//.HasJob<TestJob>(options => options.HasInterval(new TimeSpan(7, 0, 0, 0))); //.HasJob<TestJob>(options => options.HasInterval(new TimeSpan(7, 0, 0, 0)));
// //
@@ -95,15 +95,16 @@ namespace PartSource.Automation
//.HasJob<StatusCheck>(options => options.HasInterval(new TimeSpan(24, 0, 0)) //.HasJob<StatusCheck>(options => options.HasInterval(new TimeSpan(24, 0, 0))
// .StartsAt(DateTime.Parse("2021-04-01 08:00:00")) // .StartsAt(DateTime.Parse("2021-04-01 08:00:00"))
//) //)
.HasJob<ProcessWhiFitment>(options =>
.HasJob<PartsSync>(options =>
options.HasInterval(new TimeSpan(24, 0, 0)) options.HasInterval(new TimeSpan(24, 0, 0))
//.StartsAt(DateTime.Today.AddHours(25)) // .StartsAt(DateTime.Today.AddMinutes(15))
// ) // )
//.HasJob<UpdatePricing>(options => options.HasInterval(new TimeSpan(24, 0, 0)) //.HasJob<UpdatePricing>(options => options.HasInterval(new TimeSpan(24, 0, 0))
// .HasDependency<ExecuteSsisPackages>() // .HasDependency<ExecuteSsisPackages>()
// // .StartsAt(DateTime.Today.AddHours(28)) // // .StartsAt(DateTime.Today.AddHours(28))
); );
//); //);
//.AddApiServer(); //.AddApiServer();
}) })

View File

@@ -90,7 +90,9 @@ namespace PartSource.Automation.Services
public IList<int> GetVehicleIdFitment(IList<Vehicle> vehicles) public IList<int> GetVehicleIdFitment(IList<Vehicle> vehicles)
{ {
return vehicles.Select(v => v.VehicleToEngineConfigId).Distinct().ToArray(); return vehicles != null
? vehicles.Select(v => v.VehicleToEngineConfigId).Distinct().ToArray()
: new List<int>();
} }
public IList<Vehicle> GetVehiclesForPart(string partNumber, string lineCode, int maxVehicles = 0) public IList<Vehicle> GetVehiclesForPart(string partNumber, string lineCode, int maxVehicles = 0)
@@ -100,7 +102,7 @@ namespace PartSource.Automation.Services
return null; return null;
} }
partNumber = Regex.Replace(partNumber, "[^a-zA-Z0-9\\-]", string.Empty); partNumber = Regex.Replace(partNumber, "[^a-zA-Z0-9]", string.Empty);
IQueryable<string> whiCodes = _fitmentContext.DcfMappings IQueryable<string> whiCodes = _fitmentContext.DcfMappings
.Where(d => d.LineCode == lineCode) .Where(d => d.LineCode == lineCode)

View File

@@ -5,167 +5,154 @@ using Microsoft.Extensions.Logging;
using PartSource.Automation.Models.Configuration; using PartSource.Automation.Models.Configuration;
using PartSource.Automation.Models.Enums; using PartSource.Automation.Models.Enums;
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using System.Text; using System.Text;
using System.Threading.Tasks;
namespace PartSource.Automation.Services namespace PartSource.Automation.Services
{ {
public class WhiSeoService public class WhiSeoService
{ {
private readonly FtpService _ftpService; private readonly FtpService _ftpService;
private readonly string _connectionString; private readonly string _connectionString;
private readonly ILogger<WhiSeoService> _logger; private readonly ILogger<WhiSeoService> _logger;
public WhiSeoService(IConfiguration configuration, ILogger<WhiSeoService> logger) public WhiSeoService(IConfiguration configuration, ILogger<WhiSeoService> logger)
{ {
FtpConfiguration ftpConfiguration = configuration.GetSection("FtpServers:WhiConfiguration").Get<FtpConfiguration>(); FtpConfiguration ftpConfiguration = configuration.GetSection("FtpServers:WhiConfiguration").Get<FtpConfiguration>();
_ftpService = new FtpService(ftpConfiguration); _ftpService = new FtpService(ftpConfiguration);
_connectionString = configuration.GetConnectionString("FitmentDatabase"); _connectionString = configuration.GetConnectionString("FitmentDatabase");
_logger = logger; _logger = logger;
} }
public void GetFiles(SeoDataType seoDataType) public void GetFiles(SeoDataType seoDataType)
{ {
string seoDataTypeString = seoDataType.ToString().ToLowerInvariant(); string seoDataTypeString = seoDataType.ToString().ToLowerInvariant();
string[] files = _ftpService.ListFiles(seoDataTypeString);
// WHI changed the transfer protocol to SFTP and then messed with the directory structure.
// Since fitment isn't really all that automated anyway, just download the files manually with an SFTP client.
Console.WriteLine($"Remember to manually download the {seoDataTypeString} files with an SFTP client. Press any key to continue.");
Console.ReadLine();
}
foreach (string file in files) public void TruncateVehicleTable()
{ {
if (file.Contains(".csv")) using SqlConnection connection = new SqlConnection(_connectionString);
{ connection.Open();
try
{
_ftpService.Download($"{seoDataTypeString}/{file}");
_logger.LogInformation($"Finished downloading {file}.");
}
using SqlCommand command = new SqlCommand($"truncate table dbo.Vehicle", connection);
command.ExecuteNonQuery();
}
catch (Exception ex) public void TruncateFitmentTables()
{ {
_logger.LogWarning($"Failed to download {file}, quitting", ex); using SqlConnection connection = new SqlConnection(_connectionString);
throw; connection.Open();
}
}
}
}
public void TruncateVehicleTable() using SqlCommand command = new SqlCommand($"exec DropFitmentTables", connection);
{ command.ExecuteNonQuery();
using SqlConnection connection = new SqlConnection(_connectionString); }
connection.Open();
using SqlCommand command = new SqlCommand($"truncate table dbo.Vehicle", connection); public void SaveNotes(IDictionary<string, string> notes)
command.ExecuteNonQuery(); {
} using DataTable dataTable = new DataTable();
dataTable.Columns.Add("NoteText", typeof(string));
dataTable.Columns.Add("Hash", typeof(string));
public void TruncateFitmentTables() foreach (KeyValuePair<string, string> note in notes)
{ {
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlCommand command = new SqlCommand($"exec DropFitmentTables", connection); dataTable.Rows.Add(new string[] { note.Value, note.Key });
command.ExecuteNonQuery(); }
}
public void SaveNotes(IDictionary<string, string> notes) using SqlConnection connection = new SqlConnection(_connectionString);
{ connection.Open();
using DataTable dataTable = new DataTable();
dataTable.Columns.Add("NoteText", typeof(string));
dataTable.Columns.Add("Hash", typeof(string));
foreach (KeyValuePair<string, string> note in notes) using SqlBulkCopy bulk = new SqlBulkCopy(connection)
{ {
DestinationTableName = $"FitmentNote",
BulkCopyTimeout = 14400
};
dataTable.Rows.Add(new string[] { note.Value, note.Key }); bulk.WriteToServer(dataTable);
} }
using SqlConnection connection = new SqlConnection(_connectionString); public void BulkCopyFitment(DataTable dataTable, string tableName)
connection.Open(); {
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlBulkCopy bulk = new SqlBulkCopy(connection) string sql = string.Empty;
{
DestinationTableName = $"FitmentNote",
BulkCopyTimeout = 14400
};
bulk.WriteToServer(dataTable); using SqlCommand command = new SqlCommand($"EXEC CreateFitmentTempTable @tableName = '{tableName}'", connection);
} command.ExecuteNonQuery();
public void BulkCopyFitment(DataTable dataTable, string tableName) using SqlBulkCopy bulk = new SqlBulkCopy(connection)
{ {
using SqlConnection connection = new SqlConnection(_connectionString); DestinationTableName = $"FitmentTemp.{tableName}",
connection.Open(); BulkCopyTimeout = 14400
};
string sql = string.Empty; bulk.WriteToServer(dataTable);
}
using SqlCommand command = new SqlCommand($"EXEC CreateFitmentTempTable @tableName = '{tableName}'", connection); public void BulkCopyVehicle(DataTable dataTable, string tableName)
command.ExecuteNonQuery(); {
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlBulkCopy bulk = new SqlBulkCopy(connection) string sql = string.Empty;
{
DestinationTableName = $"FitmentTemp.{tableName}",
BulkCopyTimeout = 14400
};
bulk.WriteToServer(dataTable); using SqlCommand command = new SqlCommand($"EXEC CreateVehicleTempTable @tableName = '{tableName}'", connection);
} command.ExecuteNonQuery();
public void BulkCopyVehicle(DataTable dataTable, string tableName) using SqlBulkCopy bulk = new SqlBulkCopy(connection)
{ {
using SqlConnection connection = new SqlConnection(_connectionString); DestinationTableName = $"VehicleTemp.{tableName}",
connection.Open(); BulkCopyTimeout = 14400
};
string sql = string.Empty; bulk.WriteToServer(dataTable);
}
using SqlCommand command = new SqlCommand($"EXEC CreateVehicleTempTable @tableName = '{tableName}'", connection); public void CreateFitmentTable(string tableName)
command.ExecuteNonQuery(); {
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlBulkCopy bulk = new SqlBulkCopy(connection) using SqlCommand command = new SqlCommand($"exec CreateFitmentTable @tableName = '{tableName}'", connection);
{ command.CommandTimeout = 1800;
DestinationTableName = $"VehicleTemp.{tableName}", command.ExecuteNonQuery();
BulkCopyTimeout = 14400 }
};
bulk.WriteToServer(dataTable); public void CreateFitmentView()
} {
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
public void CreateFitmentTable(string tableName) using SqlCommand command = new SqlCommand($"exec CreateFitmentView", connection);
{ command.CommandTimeout = 1800;
using SqlConnection connection = new SqlConnection(_connectionString); command.ExecuteNonQuery();
connection.Open();
using SqlCommand command = new SqlCommand($"exec CreateFitmentTable @tableName = '{tableName}'", connection); using SqlCommand command2 = new SqlCommand($"exec CreateFitmentIndexes", connection);
command.CommandTimeout = 1800; command.CommandTimeout = 3600;
command.ExecuteNonQuery(); command2.ExecuteNonQuery();
} }
public void CreateFitmentView() public void CreateVehicleTable()
{ {
using SqlConnection connection = new SqlConnection(_connectionString); using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open(); connection.Open();
using SqlCommand command = new SqlCommand($"exec CreateFitmentView", connection); using SqlCommand command = new SqlCommand($"exec CreateVehicleTable", connection);
command.CommandTimeout = 1800; command.CommandTimeout = 1800;
command.ExecuteNonQuery(); command.ExecuteNonQuery();
}
using SqlCommand command2 = new SqlCommand($"exec CreateFitmentIndexes", connection); }
command.CommandTimeout = 3600;
command2.ExecuteNonQuery();
}
public void CreateVehicleTable()
{
using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open();
using SqlCommand command = new SqlCommand($"exec CreateVehicleTable", connection);
command.CommandTimeout = 1800;
command.ExecuteNonQuery();
}
}
} }
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities #pragma warning restore CA2100 // Review SQL queries for security vulnerabilities

View File

@@ -1,6 +1,7 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"FitmentDatabase": "Data Source=omg-optiplex;Initial Catalog=WhiFitment;User ID=sa;Password=TNG497us?4TW!;TrustServerCertificate=True", //"FitmentDatabase": "Data Source=localhost;Initial Catalog=WhiFitment;Integrated Security=true;TrustServerCertificate=true",
"FitmentDatabase": "Server=tcp:ps-automation.eastus2.cloudapp.azure.com,1433;Initial Catalog=WhiFitment;User ID=sa;Password=GZ0`-ekd~[2u;Encrypt=True;TrustServerCertificate=True;Connection Timeout=300",
"PartSourceDatabase": "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=30;" "PartSourceDatabase": "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=30;"
}, },
"emailConfiguration": { "emailConfiguration": {
@@ -14,13 +15,15 @@
"Username": "ps-ftp\\$ps-ftp", "Username": "ps-ftp\\$ps-ftp",
"Password": "ycvXptffBxqkBXW4vuRYqn4Zi1soCvnvMMolTe5HNSeAlcl3bAyJYtNhG579", "Password": "ycvXptffBxqkBXW4vuRYqn4Zi1soCvnvMMolTe5HNSeAlcl3bAyJYtNhG579",
"Url": "ftp://waws-prod-yq1-007.ftp.azurewebsites.windows.net/site/wwwroot", "Url": "ftp://waws-prod-yq1-007.ftp.azurewebsites.windows.net/site/wwwroot",
"Destination": "C:\\Partsource.Automation\\Downloads" "Destination": "C:\\Partsource.Automation\\Downloads",
"Port": 21
}, },
"WhiConfiguration": { "WhiConfiguration": {
"Username": "ctc_seo", "Username": "ctc_seo",
"Password": "be34hz64e4", "Password": "YD3gtaQ5kPdtNKs",
"Url": "ftp://ftp.whisolutions.com", "Url": "ftp://ftp.whisolutions.com",
"Destination": "C:\\Partsource.Automation\\Downloads\\WHI" "Destination": "C:\\Partsource.Automation\\Downloads\\WHI",
"Port": 3001
} }
}, },
"ssisConfiguration": { "ssisConfiguration": {

View File

@@ -13,10 +13,14 @@ namespace PartSource.Data.Contexts
public DbSet<DcfMapping> DcfMappings { get; set; } public DbSet<DcfMapping> DcfMappings { get; set; }
public DbSet<Part> Parts { get; set; }
public DbSet<Fitment> Fitments { get; set; } public DbSet<Fitment> Fitments { get; set; }
public DbSet<FitmentNote> FitmentNotes { get; set; } public DbSet<FitmentNote> FitmentNotes { get; set; }
public DbSet<ProductType> ProductTypes { get; set; }
public DbSet<Vehicle> Vehicles { get; set; } public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<VehicleFitment> VehicleFitments { get; set; } public DbSet<VehicleFitment> VehicleFitments { get; set; }

View File

@@ -26,7 +26,7 @@ namespace PartSource.Data.Contexts
public DbSet<PartPrice> PartPrices { get; set; } public DbSet<PartPrice> PartPrices { get; set; }
public DbSet<Part> Parts { get; set; } // public DbSet<Part> Parts { get; set; }
public DbSet<ShopifyChangelog> ShopifyChangelogs { get; set; } public DbSet<ShopifyChangelog> ShopifyChangelogs { get; set; }

View File

@@ -7,8 +7,13 @@ namespace PartSource.Data.Dtos
{ {
public class VehicleFitmentDto : VehicleFitment public class VehicleFitmentDto : VehicleFitment
{ {
public string PartDescription { get; set; }
// May not be needed, but don't remove just yet
public IList<string> SubmodelNames { get; set; } public IList<string> SubmodelNames { get; set; }
public IList<string> DriveTypes { get; set; } public IList<string> DriveTypes { get; set; }
public IList<string> Notes { get; set; }
} }
} }

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PartSource.Data.Models
{
public class ProductType
{
[Key]
public string Name { get; set; }
public bool Active { get; set; }
}
}

View File

@@ -1,4 +1,6 @@
namespace PartSource.Data.Models using Newtonsoft.Json;
namespace PartSource.Data.Models
{ {
public class VehicleFitment public class VehicleFitment
{ {
@@ -8,6 +10,7 @@
public string PartNumber { get; set; } public string PartNumber { get; set; }
[JsonIgnore]
public string NoteText { get; set; } public string NoteText { get; set; }
public int Year { get; set; } public int Year { get; set; }

View File

@@ -31,12 +31,15 @@ namespace PartSource.Data.Nexpart
public bool SecondaryDCF => true; public bool SecondaryDCF => true;
[XmlElement(Order = 6)] [XmlElement(Order = 6)]
public Criterion[] Criterion { get; set; } public string[] AppOption { get; set; }
[XmlElement(Order = 7)] [XmlElement(Order = 7)]
public string GroupBy { get; set; } public Criterion[] Criterion { get; set; }
[XmlElement(Order = 8)] [XmlElement(Order = 8)]
public string GroupBy { get; set; }
[XmlElement(Order = 9)]
public string QuestionOption { get; set; } public string QuestionOption { get; set; }
} }
} }

View File

@@ -13,11 +13,11 @@ namespace PartSource.Services
{ {
public class FitmentService public class FitmentService
{ {
private readonly FitmentContext _fitmentContext; private readonly FitmentContext _fitmentContext;
public FitmentService(FitmentContext fitmentContext) public FitmentService(FitmentContext fitmentContext)
{ {
_fitmentContext = fitmentContext; _fitmentContext = fitmentContext;
} }
public async Task<VehicleFitmentDto> GetFitmentNotes(string sku, int vehicleId) public async Task<VehicleFitmentDto> GetFitmentNotes(string sku, int vehicleId)
@@ -36,120 +36,115 @@ namespace PartSource.Services
BaseVehicleId = vf.BaseVehicleId, BaseVehicleId = vf.BaseVehicleId,
EngineConfigId = vf.EngineConfigId, EngineConfigId = vf.EngineConfigId,
VehicleToEngineConfigId = vf.VehicleToEngineConfigId, VehicleToEngineConfigId = vf.VehicleToEngineConfigId,
SubmodelName = vf.SubmodelName SubmodelName = vf.SubmodelName
}) })
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
if (vehicleFitment == null)
{
return null;
}
return vehicleFitment; return vehicleFitment;
} }
public IList<string> GetYmmFitment(IList<Vehicle> vehicles) public IList<string> GetYmmFitment(IList<Vehicle> vehicles)
{ {
if (vehicles.Count == 0) if (vehicles.Count == 0)
{ {
return new string[0]; return new string[0];
} }
IList<string> fitmentTags = new List<string>(); IList<string> fitmentTags = new List<string>();
IList<string> makeModels = vehicles.OrderBy(v => v.MakeName).ThenBy(v => v.ModelName).Select(v => $"{v.MakeName},{v.ModelName}").Distinct().ToList(); IList<string> makeModels = vehicles.OrderBy(v => v.MakeName).ThenBy(v => v.ModelName).Select(v => $"{v.MakeName},{v.ModelName}").Distinct().ToList();
foreach (string makeModel in makeModels) foreach (string makeModel in makeModels)
{ {
string make = makeModel.Split(',')[0]; string make = makeModel.Split(',')[0];
string model = makeModel.Split(',')[1]; string model = makeModel.Split(',')[1];
List<string> years = vehicles List<string> years = vehicles
.Where(v => v.MakeName == make && v.ModelName == model) .Where(v => v.MakeName == make && v.ModelName == model)
.OrderBy(v => v.Year) .OrderBy(v => v.Year)
.Select(v => v.Year.ToString().Trim()) .Select(v => v.Year.ToString().Trim())
.Distinct() .Distinct()
.ToList(); .ToList();
string tag = $"{string.Join('-', years)} {make.Trim()} {model.Trim()}"; string tag = $"{string.Join('-', years)} {make.Trim()} {model.Trim()}";
System.Diagnostics.Debug.WriteLine(tag); System.Diagnostics.Debug.WriteLine(tag);
fitmentTags.Add(tag); fitmentTags.Add(tag);
} }
return fitmentTags; return fitmentTags;
} }
public IList<string> GetYmmFitmentRange(IList<Vehicle> vehicles) public IList<string> GetYmmFitmentRange(IList<Vehicle> vehicles)
{ {
if (vehicles.Count == 0) if (vehicles.Count == 0)
{ {
return new string[0]; return new string[0];
} }
IList<string> fitmentTags = new List<string>(); IList<string> fitmentTags = new List<string>();
IList<string> makeModels = vehicles.Select(v => $"{v.MakeName},{v.ModelName}").Distinct().ToList(); IList<string> makeModels = vehicles.Select(v => $"{v.MakeName},{v.ModelName}").Distinct().ToList();
foreach (string makeModel in makeModels) foreach (string makeModel in makeModels)
{ {
string make = makeModel.Split(',')[0]; string make = makeModel.Split(',')[0];
string model = makeModel.Split(',')[1]; string model = makeModel.Split(',')[1];
int minYear = vehicles int minYear = vehicles
.Where(v => v.MakeName == make && v.ModelName == model) .Where(v => v.MakeName == make && v.ModelName == model)
.Min(v => v.Year); .Min(v => v.Year);
int maxYear = vehicles int maxYear = vehicles
.Where(v => v.MakeName == make && v.ModelName == model) .Where(v => v.MakeName == make && v.ModelName == model)
.Max(v => v.Year); .Max(v => v.Year);
string tag = minYear == maxYear string tag = minYear == maxYear
? $"{minYear} {make.Trim()} {model.Trim()}" ? $"{minYear} {make.Trim()} {model.Trim()}"
: $"{minYear}-{maxYear} {make.Trim()} {model.Trim()}"; : $"{minYear}-{maxYear} {make.Trim()} {model.Trim()}";
System.Diagnostics.Debug.WriteLine(tag); System.Diagnostics.Debug.WriteLine(tag);
fitmentTags.Add(tag); fitmentTags.Add(tag);
} }
return fitmentTags; return fitmentTags;
} }
public IList<int> GetVehicleIdFitment(IList<Vehicle> vehicles) public IList<int> GetVehicleIdFitment(IList<Vehicle> vehicles)
{ {
return vehicles.Select(v => v.VehicleToEngineConfigId).Distinct().ToList(); return vehicles.Select(v => v.VehicleToEngineConfigId).Distinct().ToList();
} }
public IList<Vehicle> GetVehiclesForPart(string partNumber, string lineCode, int maxVehicles = 0) public IList<Vehicle> GetVehiclesForPart(string partNumber, string lineCode, int maxVehicles = 0)
{ {
if (string.IsNullOrEmpty(partNumber) || string.IsNullOrEmpty(lineCode)) if (string.IsNullOrEmpty(partNumber) || string.IsNullOrEmpty(lineCode))
{ {
return null; return null;
} }
partNumber = Regex.Replace(partNumber, "[^a-zA-Z0-9]", string.Empty); partNumber = Regex.Replace(partNumber, "[^a-zA-Z0-9]", string.Empty);
IQueryable<string> whiCodes = _fitmentContext.DcfMappings IQueryable<string> whiCodes = _fitmentContext.DcfMappings
.Where(d => d.LineCode == lineCode) .Where(d => d.LineCode == lineCode)
.Select(d => d.WhiCode); .Select(d => d.WhiCode);
IQueryable<Vehicle> vehicles = _fitmentContext.Fitments IQueryable<Vehicle> vehicles = _fitmentContext.Fitments
.Where(f => f.PartNumber == partNumber && whiCodes.Contains(f.LineCode)) .Where(f => f.PartNumber == partNumber && whiCodes.Contains(f.LineCode))
.Join(_fitmentContext.Vehicles, .Join(_fitmentContext.Vehicles,
f => new { f.BaseVehicleId, f.EngineConfigId }, f => new { f.BaseVehicleId, f.EngineConfigId },
v => new { v.BaseVehicleId, v.EngineConfigId }, v => new { v.BaseVehicleId, v.EngineConfigId },
(f, v) => v) (f, v) => v)
.Distinct() .Distinct()
.OrderByDescending(x => x.Year); .OrderByDescending(x => x.Year);
if (maxVehicles > 0) if (maxVehicles > 0)
{ {
vehicles = vehicles.Take(maxVehicles); vehicles = vehicles.Take(maxVehicles);
} }
return vehicles.ToList(); return vehicles.ToList();
} }
} }
} }

View File

@@ -25,17 +25,20 @@ namespace PartSource.Services
U content; U content;
string x = textWriter.ToString(); string x = textWriter.ToString();
System.Diagnostics.Debug.WriteLine(x);
using (HttpClient client = new HttpClient())
using (HttpClient client = new HttpClient())
{ {
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "QjM4ODAyMzM3QjQxNEM2QTk4M0RFMjM0Mjk4Rjk4M0UtOUIzNUUxNzNBQUYxNEE2QjhCQjI2RjZDOUY2ODk1NDU6MkMzOUVCOTYtRDBBRS00QkVBLTlCMzItMUYyNTA5MDJGQTE0"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "QjM4ODAyMzM3QjQxNEM2QTk4M0RFMjM0Mjk4Rjk4M0UtOUIzNUUxNzNBQUYxNEE2QjhCQjI2RjZDOUY2ODk1NDU6MkMzOUVCOTYtRDBBRS00QkVBLTlCMzItMUYyNTA5MDJGQTE0");
try try
{ {
//HttpResponseMessage response = await client.PostAsync(ConfigurationManager.AppSettings["NexpartUrl"], (HttpContent)new StringContent(sb.ToString(), Encoding.UTF8, "text/xml")); //HttpResponseMessage response = await client.PostAsync(ConfigurationManager.AppSettings["NexpartUrl"], (HttpContent)new StringContent(sb.ToString(), Encoding.UTF8, "text/xml"));
HttpResponseMessage response = await client.PostAsync("https://acespssprod.nexpart.com:4085/partselect/2.0/services/PartSelectService.PartSelectHttpSoap11Endpoint", new StringContent(textWriter.ToString(), Encoding.UTF8, "text/xml")); HttpResponseMessage response = await client.PostAsync("http://acespssprod.nexpart.com:8085/partselect/2.0/services/PartSelectService.PartSelectHttpSoap11Endpoint", new StringContent(textWriter.ToString(), Encoding.UTF8, "text/xml"));
Stream result = await response.Content.ReadAsStreamAsync(); Stream result = await response.Content.ReadAsStreamAsync();
string str = await response.Content.ReadAsStringAsync(); string str = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(str);
content = (U)((Envelope)serializer.Deserialize(result)).Body.Content; content = (U)((Envelope)serializer.Deserialize(result)).Body.Content;
; ;
} }
@@ -44,6 +47,7 @@ namespace PartSource.Services
throw; throw;
} }
} }
return content; return content;
} }
} }

View File

@@ -12,26 +12,28 @@ namespace PartSource.Services
{ {
public class PartService public class PartService
{ {
private readonly PartSourceContext _context; private readonly PartSourceContext _partSourceContext;
private readonly FitmentContext _fitmentContext;
public PartService(PartSourceContext context) public PartService(PartSourceContext partSourceContext, FitmentContext fitmentContext)
{ {
_context = context; _partSourceContext = partSourceContext;
_fitmentContext = fitmentContext;
} }
public async Task<PartsAvailability> GetInventory(int sku, int storeNumber) public async Task<PartsAvailability> GetInventory(int sku, int storeNumber)
{ {
return await _context.PartAvailabilities.FirstOrDefaultAsync(s => s.Store == storeNumber && s.SKU == sku); return await _partSourceContext.PartAvailabilities.FirstOrDefaultAsync(s => s.Store == storeNumber && s.SKU == sku);
} }
public async Task<Part> GetPartBySku(string sku) public async Task<Part> GetPartBySku(string sku)
{ {
return await _context.Parts.SingleOrDefaultAsync(p => p.Sku == sku); return await _fitmentContext.Parts.SingleOrDefaultAsync(p => p.Sku == sku);
} }
public async Task<IList<DcfMapping>> GetDcfMapping(string partsourceLineCode) public async Task<IList<DcfMapping>> GetDcfMapping(string partsourceLineCode)
{ {
return await _context.DcfMappings return await _fitmentContext.DcfMappings
.Where(dcf => dcf.LineCode == partsourceLineCode) .Where(dcf => dcf.LineCode == partsourceLineCode)
.ToListAsync(); .ToListAsync();
} }