State of OMG-LEGION prior to merge

This commit is contained in:
2022-10-30 10:54:20 -04:00
parent 9924880b51
commit 48844127d7
45 changed files with 1350 additions and 868 deletions

View File

@@ -5,91 +5,128 @@ using PartSource.Data.Models;
using PartSource.Data.Nexpart; using PartSource.Data.Nexpart;
using PartSource.Services; using PartSource.Services;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Part = PartSource.Data.Models.Part;
namespace PartSource.Api.Controllers namespace PartSource.Api.Controllers
{ {
[Route("[controller]")] [Route("v2/[controller]")]
[ApiController] [ApiController]
[ApiExplorerSettings(GroupName = "v1")] [ApiExplorerSettings(GroupName = "v1")]
public class PartsController : BaseNexpartController public class PartsController : BaseNexpartController
{ {
private readonly NexpartService _nexpartService; private readonly NexpartService _nexpartService;
private readonly PartService _partService; private readonly PartService _partService;
private readonly VehicleService _vehicleService;
public PartsController(NexpartService nexpartService, PartService partService) public PartsController(NexpartService nexpartService, PartService partService, VehicleService vehicleService)
{ {
this._nexpartService = nexpartService; _nexpartService = nexpartService;
_partService = partService; _partService = partService;
_vehicleService = vehicleService;
} }
[HttpGet] [HttpGet]
[Route("PartNumber/{partNumber}/LineCode/{lineCode}")] [Route("positions")]
public ActionResult GetPart(string partNumber, string lineCode) public async Task<ActionResult> GetPositions([FromQuery] string sku, [FromQuery] int vehicleId)
{ {
new SmartPageDataSearch().Items = new Item[1] Part part = await _partService.GetPartBySku(sku);
Vehicle vehicle = await _vehicleService.GetVehicleById(vehicleId);
if (part == null)
{ {
new Item() return BadRequest(new
{ {
PartNumber = partNumber.ToUpperInvariant(), Message = $"No part data is available for SKU {sku}. Confirm it is available in the database maintained by Sound Press.",
MfrCode = lineCode.ToUpperInvariant() Reason = $"{nameof(_partService.GetPartBySku)} returned null"
} });
};
return (ActionResult)this.Ok();
} }
[HttpGet] if (vehicle == null)
[Route("search/basevehicleid/{baseVehicleId}")]
public async Task<ActionResult> Search(int baseVehicleId, [FromQuery] string query)
{ {
PartsController partsController = this; return BadRequest(new
PartTypeSearch requestContent = new PartTypeSearch()
{ {
SearchString = query, Message = $"No vehicle data is available for SKU {sku}. Confirm it is available in the database maintained by Sound Press.",
SearchType = "ALL", Reason = $"{nameof(_vehicleService.GetVehicleById)} returned null"
SearchOptions = "PARTIAL_MATCH", });
VehicleIdentifier = new VehicleIdentifier()
{
BaseVehicleId = baseVehicleId
} }
IList<DcfMapping> mappings = await _partService.GetDcfMapping(part.LineCode);
Item[] items = mappings.Select(m => new Item
{
PartNumber = part.PartNumber,
MfrCode = m.WhiCode
})
.ToArray();
SmartPageDataSearch smartPageDataSearch = new SmartPageDataSearch
{
Items = items
}; };
PartTypeSearchResponse response = await _nexpartService.SendRequest<PartTypeSearch, PartTypeSearchResponse>(requestContent); SmartPageDataSearchResponse smartPageResponse = await _nexpartService.SendRequest<SmartPageDataSearch, SmartPageDataSearchResponse>(smartPageDataSearch);
if (smartPageResponse.ResponseBody?.Item == null)
return partsController.NexpartResponse<PartTypeSearchResponse, PartTypes>(response); {
return NotFound(new
{
Message = $"No WHI data is available for SKU {sku}",
Reason = $"{nameof(SmartPageDataSearch)} returned null"
});
} }
[HttpGet] PartType[] partTypes = smartPageResponse.ResponseBody.Item.Select(i => new PartType
[Route("validate/partTypeId/{partTypeId}/baseVehicleId/{baseVehicleId}")]
public async Task<ActionResult> ValidatePartFitment(int partTypeId, int baseVehicleId)
{ {
PartsController partsController = this; Id = i.Part.PartType.Id
PartTypesValidateLookup typesValidateLookup = new PartTypesValidateLookup(); })
typesValidateLookup.PartTypes = new PartType[1] .ToArray();
ApplicationSearch applicationSearch = new ApplicationSearch
{ {
new PartType() { Id = partTypeId } VehicleIdentifier = new VehicleIdentifier
{
BaseVehicleId = vehicle.BaseVehicleId
},
MfrCode = mappings.Select(m => m.WhiCode).ToArray(),
PartType = new[] { new PartType { Id = smartPageResponse.ResponseBody.Item[0].Part.PartType.Id } },
Criterion = new[]
{
new Criterion
{
Attribute = "REGION",
Id = 2
}
},
GroupBy = "PARTTYPE"
}; };
typesValidateLookup.VehicleIdentifier = new VehicleIdentifier()
ApplicationSearchResponse response = await _nexpartService.SendRequest<ApplicationSearch, ApplicationSearchResponse>(applicationSearch);
if (response.ResponseBody == null)
{ {
BaseVehicleId = baseVehicleId return NotFound(new
}; {
PartTypesValidateLookup requestContent = typesValidateLookup; Message = $"No WHI data is available for SKU {sku}",
PartTypesValidateLookupResponse response = await partsController._nexpartService.SendRequest<PartTypesValidateLookup, PartTypesValidateLookupResponse>(requestContent); Reason = $"{nameof(ApplicationSearch)} returned null"
return partsController.NexpartResponse<PartTypesValidateLookupResponse, PartTypes>(response); });
} }
[HttpGet] IList<string> positions = new List<string>();
[Route("search/fitment")] foreach (App app in response.ResponseBody?.App)
public async Task<ActionResult> FitmentSearch([FromQuery] FitmentSearchDto fitmentSearchDto)
{ {
IList<Fitment> fitments = _partService.GetFitments(fitmentSearchDto); if (!string.IsNullOrEmpty(app.Position) && app.Part == part.PartNumber)
if (fitments == null)
{ {
return NotFound(); positions.Add(app.Position);
}
} }
return Ok(new { Data = fitments }); return Ok(new
{
VehicleId = vehicleId,
Sku = sku,
Positions = positions.Distinct()
});
} }
} }
} }

View File

@@ -0,0 +1,63 @@

using Microsoft.AspNetCore.Mvc;
using PartSource.Data.Dtos;
using PartSource.Data.Models;
using PartSource.Data.Nexpart;
using PartSource.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PartSource.Api.Controllers
{
[Route("[controller]")]
[ApiController]
[ApiExplorerSettings(GroupName = "v1")]
public class WipersController : BaseNexpartController
{
private readonly NexpartService _nexpartService;
public WipersController(NexpartService nexpartService)
{
_nexpartService = nexpartService;
}
[HttpGet]
[Route("{baseVehicleId}")]
public async Task<ActionResult> GetWipersForVehicle(int baseVehicleId)
{
ApplicationSearch applicationSearch = new ApplicationSearch
{
VehicleIdentifier = new VehicleIdentifier
{
BaseVehicleId = baseVehicleId
},
MfrCode = new[] { "BOS", "TRI" },
PartType = new[]
{
new PartType { Id = 8852 }
},
Criterion = new[]
{
new Criterion
{
Attribute = "REGION",
Id = 2
}
},
GroupBy = "PARTTYPE"
};
ApplicationSearchResponse response = await _nexpartService.SendRequest<ApplicationSearch, ApplicationSearchResponse>(applicationSearch);
if (response.ResponseBody != null)
{
return NexpartResponse<ApplicationSearchResponse, Apps>(response);
}
else
{
return NotFound();
}
}
}
}

View File

@@ -30,14 +30,14 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.0.1" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.15" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.5" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Ratermania.Shopify" Version="1.3.1" /> <PackageReference Include="Ratermania.Shopify" Version="1.3.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
<PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="5.5.1" /> <PackageReference Include="Swashbuckle.AspNetCore.ReDoc" Version="6.3.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -67,9 +67,9 @@ namespace PartSource.Api
services.AddDbContext<PartSourceContext>(options => services.AddDbContext<PartSourceContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PartSourceDatabase")) options.UseSqlServer(Configuration.GetConnectionString("PartSourceDatabase"))
); );
services.AddDbContext<FitmentContext>(options => //services.AddDbContext<FitmentContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("FitmentDatabase")) // options.UseSqlServer(Configuration.GetConnectionString("FitmentDatabase"))
); //);
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -86,12 +86,12 @@ namespace PartSource.Api
app.UseCors("Default"); app.UseCors("Default");
app.UseSwagger(); //app.UseSwagger();
app.UseReDoc(c => //app.UseReDoc(c =>
{ //{
c.SpecUrl = "/swagger/v2/swagger.json"; // c.SpecUrl = "/swagger/v2/swagger.json";
c.ExpandResponses(string.Empty); // c.ExpandResponses(string.Empty);
}); //});
// app.UseExceptionHandler("/Error"); // app.UseExceptionHandler("/Error");
// app.UseHttpsRedirection(); // app.UseHttpsRedirection();

View File

@@ -1,7 +1,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"
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {

View File

@@ -27,7 +27,7 @@ namespace PartSource.Automation.Jobs
MenuNodesLookup menuNodesLookup = new MenuNodesLookup MenuNodesLookup menuNodesLookup = new MenuNodesLookup
{ {
MenuId = 1, MenuId = 2,
NumberOfLevels = 1 NumberOfLevels = 1
}; };
@@ -39,7 +39,7 @@ namespace PartSource.Automation.Jobs
MenuNodesLookup subgroupLookup = new MenuNodesLookup MenuNodesLookup subgroupLookup = new MenuNodesLookup
{ {
MenuId = 1, MenuId = 2,
NumberOfLevels = 1, NumberOfLevels = 1,
ParentMenuNodeId = categoryNode.Id ParentMenuNodeId = categoryNode.Id
}; };
@@ -52,7 +52,7 @@ namespace PartSource.Automation.Jobs
MenuNodesLookup thirdLookup = new MenuNodesLookup MenuNodesLookup thirdLookup = new MenuNodesLookup
{ {
MenuId = 1, MenuId = 2,
NumberOfLevels = 1, NumberOfLevels = 1,
ParentMenuNodeId = subgroupNode.Id ParentMenuNodeId = subgroupNode.Id
}; };
@@ -67,7 +67,7 @@ namespace PartSource.Automation.Jobs
} }
} }
await File.WriteAllLinesAsync("C:\\users\\Tommy\\desktop\\Partsource Menu Items.csv", rows); //await File.WriteAllLinesAsync("C:\\users\\Tommy\\desktop\\Partsource Menu Items.csv", rows);
; ;
} }

View File

@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using PartSource.Data.Contexts;
using PartSource.Data.Models;
using PartSource.Data.Nexpart;
using PartSource.Services;
using Ratermania.Automation.Interfaces;
using Ratermania.Shopify;
using Ratermania.Shopify.Resources;
namespace PartSource.Automation.Jobs.POC
{
public class UpdateBulbFitment : IAutomationJob
{
private readonly FitmentContext _fitmentContext;
private readonly NexpartService _nexpartService;
private readonly ShopifyClient _shopifyClient;
public UpdateBulbFitment(FitmentContext fitmentContext, NexpartService nexpartService, ShopifyClient shopifyClient)
{
_fitmentContext = fitmentContext;
_nexpartService = nexpartService;
_shopifyClient = shopifyClient;
}
public async Task Run()
{
await BuildDatabase();
await UpdateShopify();
}
public async Task BuildDatabase()
{
IList<int> baseVehicles = await _fitmentContext.Vehicles
.Select(v => v.BaseVehicleId)
.Distinct()
.OrderBy(i => i)
.ToListAsync();
foreach (int baseVehicleId in baseVehicles)
{
ApplicationSearch applicationSearch = new ApplicationSearch
{
VehicleIdentifier = new VehicleIdentifier
{
BaseVehicleId = baseVehicleId
},
MfrCode = new[] { "C23", "CBX", "CCH", "CCJ", "CF1", "CHU", "GOO", "GPL", "OEB", "UTY", "TYC", "ILB", "SYL", "SYR", "PLP", "FOU", },
PartType = new[] { new PartType { Id = 11696 }, new PartType { Id = 11701 }, new PartType { Id = 13343 }, new PartType { Id = 13661 }, new PartType { Id = 13662 }, new PartType { Id = 13663 }, new PartType { Id = 13675 }, new PartType { Id = 13676 }, new PartType { Id = 13677 }, new PartType { Id = 13678 }, new PartType { Id = 13716 } },
Criterion = new[]
{
new Criterion
{
Attribute = "REGION",
Id = 2
}
},
GroupBy = "PARTTYPE"
};
ApplicationSearchResponse response = await _nexpartService.SendRequest<ApplicationSearch, ApplicationSearchResponse>(applicationSearch);
if (response.ResponseBody != null)
{
foreach (App app in response.ResponseBody.App)
{
try
{
if (string.IsNullOrEmpty(app.Position))
{
app.Position = "not provided by WHI";
}
await _fitmentContext.Database.ExecuteSqlRawAsync("INSERT INTO Wiper (BaseVehicleId, LineCode, PartNumber, Position, PartName) VALUES ({0}, {1}, {2}, {3}, {4});",
baseVehicleId, app.MfrCode, Regex.Replace(app.Part, "[^a-zA-Z0-9]", string.Empty), app.Position, app.MfrLabel);
}
catch (Exception ex)
{
Console.WriteLine($"Could not save {app.MfrCode}, {app.Part}, {app.Position}, {app.MfrLabel} for {baseVehicleId}: {ex.Message}");
}
}
}
Console.WriteLine(baseVehicleId);
}
}
private async Task UpdateShopify()
{
//foreach (string productType in new[] { "CA171-SC223-FL22302_Halogen Lighting - Certified", "CA171-SC223-FL22303_Halogen Lighting - Xtra Vision", "CA171-SC223-FL22304_Halogen Lighting - Silverstar", "CA171-SC223-FL22305_Halogen Lighting - Silverstar Ultra", "CA171-SC223-FL22306_Halogen Lighting - Silverstar Zxe", "CA171-SC223-FL22307_Sealed Beams - OPP", "CA171-SC223-FL22308_Headlight Assemblies", "CA171-SC223-FL22311_Halogen Lighting - Fog Vision", "CA171-SC223-FL22314_Halogen Lighting - Sylvania Standard", "CA171-SC223-FL22315_Forward Lighting - HID", "CA171-SC223-FL22317_Sealed Beams - Silverstar", "CA171-SC223-FL22318_Sealed Beams - Xtra Vision", "CA171-SC223-FL22319_Forward Lighting - LED", "CA171-SC239-FL23910_Minibulbs - Long Life", "CA171-SC239-FL23920_Minibulbs - Silver Star", "CA171-SC239-FL23940_Minibulbs - LED" })
//{
IEnumerable<Product> products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 } });
while (products != null && products.Any())
{
foreach (Product product in products)
{
try
{
string partNumber = Regex.Replace(product.Title.Split(' ')[0], "[^a-zA-Z0-9]", string.Empty);
IList<Wiper> wipers = await _fitmentContext.Wipers
.Where(w => w.PartNumber == partNumber)
.OrderBy(w => w.Position)
.ToListAsync();
string currentPosition = wipers.FirstOrDefault()?.Position;
if (currentPosition == null)
{
continue;
}
List<int> vehicleIds = new List<int>();
foreach (Wiper wiper in wipers)
{
if (wiper.Position != currentPosition)
{
await SavePositionMetafield(product, vehicleIds, currentPosition);
currentPosition = wiper.Position;
vehicleIds = new List<int>();
}
IList<int> fitmentVehicleIds = _fitmentContext.Vehicles
.Where(v => v.BaseVehicleId == wiper.BaseVehicleId)
.Select(v => v.VehicleToEngineConfigId)
.Distinct()
.ToList();
vehicleIds.AddRange(fitmentVehicleIds);
}
await SavePositionMetafield(product, vehicleIds, currentPosition);
}
catch (Exception ex)
{
Console.WriteLine($"Could not update {product.Id}: {ex.Message}");
}
}
products = await _shopifyClient.Products.GetNext();
}
// }
}
//[SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "It's a Shopify metafield key")]
private async Task SavePositionMetafield(Product product, IList<int> vehicleIds, string position)
{
if (vehicleIds.Count == 0)
{
return;
}
string json = JsonConvert.SerializeObject(vehicleIds);
if (json.Length >= 100000)
{
// TODO: Logging
return;
}
string key = position.ToLowerInvariant().Replace(" ", "_");
if (key.Length > 20)
{
key = key.Substring(0, 20);
}
Metafield vehicleMetafield = new Metafield
{
Namespace = "position",
Key = key,
Value = json,
ValueType = "json_string",
OwnerResource = "product",
OwnerId = product.Id
};
;
System.Diagnostics.Debug.WriteLine(json);
await _shopifyClient.Metafields.Add(vehicleMetafield);
}
}
}

View File

@@ -0,0 +1,182 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using PartSource.Data.Contexts;
using PartSource.Data.Models;
using PartSource.Data.Nexpart;
using PartSource.Services;
using Ratermania.Automation.Interfaces;
using Ratermania.Shopify;
using Ratermania.Shopify.Resources;
namespace PartSource.Automation.Jobs.POC
{
public class UpdateWiperFitment : IAutomationJob
{
private readonly FitmentContext _fitmentContext;
private readonly NexpartService _nexpartService;
private readonly ShopifyClient _shopifyClient;
public UpdateWiperFitment(FitmentContext fitmentContext, NexpartService nexpartService, ShopifyClient shopifyClient)
{
_fitmentContext = fitmentContext;
_nexpartService = nexpartService;
_shopifyClient = shopifyClient;
}
public async Task Run()
{
// await BuildDatabase();
await UpdateShopify();
}
public async Task BuildDatabase()
{
IList<int> baseVehicles = await _fitmentContext.Vehicles
.Select(v => v.BaseVehicleId)
.Distinct()
.OrderBy(i => i)
.ToListAsync();
foreach (int baseVehicleId in baseVehicles)
{
ApplicationSearch applicationSearch = new ApplicationSearch
{
VehicleIdentifier = new VehicleIdentifier
{
BaseVehicleId = baseVehicleId
},
MfrCode = new[] { "BOS", "TRI" },
PartType = new[] { new PartType { Id = 8852 } },
Criterion = new[]
{
new Criterion
{
Attribute = "REGION",
Id = 2
}
},
GroupBy = "PARTTYPE"
};
ApplicationSearchResponse response = await _nexpartService.SendRequest<ApplicationSearch, ApplicationSearchResponse>(applicationSearch);
if (response.ResponseBody != null)
{
foreach (App app in response.ResponseBody.App)
{
try
{
await _fitmentContext.Database.ExecuteSqlRawAsync("INSERT INTO Wiper (BaseVehicleId, LineCode, PartNumber, Position, PartName) VALUES ({0}, {1}, {2}, {3}, {4});",
baseVehicleId, app.MfrCode, Regex.Replace(app.Part, "[^a-zA-Z0-9]", string.Empty), app.Position, app.MfrLabel);
}
catch (Exception ex)
{
Console.WriteLine($"Could not save {app.MfrCode}, {app.Part}, {app.Position}, {app.MfrLabel} for {baseVehicleId}: {ex.Message}");
}
}
}
Console.WriteLine(baseVehicleId);
}
}
private async Task UpdateShopify()
{
foreach (string productType in new[] { "CA172-SC231-FL23107_(PS) Wipers - TRICO Neoform", "CA172-SC231-FL23109_(PS) Wipers - TRICO Tech/Exact Fit", "CA172-SC231-FL23110_Wiper Accessories", "CA172-SC231-FL23116_(PS) Wipers - Bosch Insight (Hybrid)", "CA172-SC231-FL23117_(PS) Wipers - Bosch Clear Advantage (Beam)" })
{
IEnumerable<Product> products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 }, { "product_type", productType } });
System.Diagnostics.Debug.WriteLine($"{productType}: Count: {products.Count()}");
while (products != null && products.Any())
{
foreach (Product product in products)
{
try
{
string partNumber = Regex.Replace(product.Title.Split(' ')[0], "[^a-zA-Z0-9]", string.Empty);
IList<Wiper> wipers = await _fitmentContext.Wipers
.Where(w => w.PartNumber == partNumber)
.OrderBy(w => w.Position)
.ToListAsync();
string currentPosition = wipers[0].Position;
List<int> vehicleIds = new List<int>();
foreach (Wiper wiper in wipers)
{
if (wiper.Position != currentPosition)
{
await SavePositionMetafield(product, vehicleIds, currentPosition);
currentPosition = wiper.Position;
vehicleIds = new List<int>();
}
IList<int> fitmentVehicleIds = _fitmentContext.Vehicles
.Where(v => v.BaseVehicleId == wiper.BaseVehicleId)
.Select(v => v.VehicleToEngineConfigId)
.Distinct()
.ToList();
vehicleIds.AddRange(fitmentVehicleIds);
}
await SavePositionMetafield(product, vehicleIds, currentPosition);
}
catch (Exception ex)
{
Console.WriteLine($"Could not update {product.Id}: {ex.Message}");
}
}
products = await _shopifyClient.Products.GetNext();
}
}
}
//[SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "It's a Shopify metafield key")]
private async Task SavePositionMetafield(Product product, IList<int> vehicleIds, string position)
{
if (vehicleIds.Count == 0)
{
return;
}
string json = JsonConvert.SerializeObject(vehicleIds);
if (json.Length >= 100000)
{
// TODO: Logging
return;
}
string key = position.ToLowerInvariant().Replace(" ", "_");
if (key.Length > 20)
{
key = key.Substring(0, 20);
}
Metafield vehicleMetafield = new Metafield
{
Namespace = "position",
Key = key,
Value = json,
ValueType = "json_string",
OwnerResource = "product",
OwnerId = product.Id
};
System.Diagnostics.Debug.WriteLine(json);
await _shopifyClient.Metafields.Add(vehicleMetafield);
}
}
}

View File

@@ -38,7 +38,7 @@ namespace PartSource.Automation.Jobs
public async Task Run() public async Task Run()
{ {
_whiSeoService.TruncateVehicleTable(); _whiSeoService.TruncateVehicleTables();
_whiSeoService.GetFiles(_seoDataType); _whiSeoService.GetFiles(_seoDataType);
string directory = Path.Combine(_ftpConfiguration.Destination, _seoDataType.ToString().ToLowerInvariant()); string directory = Path.Combine(_ftpConfiguration.Destination, _seoDataType.ToString().ToLowerInvariant());
@@ -79,6 +79,9 @@ namespace PartSource.Automation.Jobs
dataTable.Columns.Add("MakeName", typeof(string)); dataTable.Columns.Add("MakeName", typeof(string));
dataTable.Columns.Add("ModelId", typeof(int)); dataTable.Columns.Add("ModelId", typeof(int));
dataTable.Columns.Add("ModelName", typeof(string)); dataTable.Columns.Add("ModelName", typeof(string));
dataTable.Columns.Add("RegionId", typeof(int));
dataTable.Columns.Add("RegionName", typeof(string));
dataTable.Columns.Add("VehicleTypeId", typeof(int));
dataTable.Columns.Add("EngineConfigId", typeof(int)); dataTable.Columns.Add("EngineConfigId", typeof(int));
dataTable.Columns.Add("EngineDescription", typeof(string)); dataTable.Columns.Add("EngineDescription", typeof(string));
dataTable.Columns.Add("BaseVehicleId", typeof(int)); dataTable.Columns.Add("BaseVehicleId", typeof(int));
@@ -101,22 +104,27 @@ namespace PartSource.Automation.Jobs
string makeName = columns[4].Trim(); string makeName = columns[4].Trim();
string modelName = columns[6].Trim(); string modelName = columns[6].Trim();
string regionName = columns[8].Trim();
string submodelName = columns[34].Trim(); string submodelName = columns[34].Trim();
string engineDescription = columns[51].Trim(); string engineDescription = columns[51].Trim();
if (!string.IsNullOrEmpty(makeName) if (!string.IsNullOrEmpty(makeName)
&& !string.IsNullOrEmpty(modelName) && !string.IsNullOrEmpty(modelName)
&& !string.IsNullOrEmpty(regionName)
&& !string.IsNullOrEmpty(submodelName) && !string.IsNullOrEmpty(submodelName)
&& !string.IsNullOrEmpty(engineDescription) && !string.IsNullOrEmpty(engineDescription)
&& int.TryParse(columns[0], out int baseVehicleId) && int.TryParse(columns[0], out int baseVehicleId)
&& int.TryParse(columns[2], out int year) && int.TryParse(columns[2], out int year)
&& int.TryParse(columns[3], out int makeId) && int.TryParse(columns[3], out int makeId)
&& int.TryParse(columns[5], out int modelId) && int.TryParse(columns[5], out int modelId)
&& int.TryParse(columns[7], out int regionId)
&& int.TryParse(columns[9], out int vehicleTypeId)
&& int.TryParse(columns[33], out int submodelId) && int.TryParse(columns[33], out int submodelId)
&& int.TryParse(columns[35], out int engineConfigId) && int.TryParse(columns[35], out int engineConfigId)
&& int.TryParse(columns[36], out int vehicleToEngineConfigId)) && int.TryParse(columns[36], out int vehicleToEngineConfigId)
&& new[] { 5, 6, 7 }.Contains(vehicleTypeId))
{ {
dataTable.Rows.Add(new object[] { year, makeId, makeName, modelId, modelName, engineConfigId, engineDescription, baseVehicleId, vehicleToEngineConfigId, submodelId, submodelName }); dataTable.Rows.Add(new object[] { year, makeId, makeName, modelId, modelName, regionId, regionName, vehicleTypeId, engineConfigId, engineDescription, baseVehicleId, vehicleToEngineConfigId, submodelId, submodelName });
} }
} }

View File

@@ -1,72 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PartSource.Data.Contexts;
using PartSource.Data.Models;
using Ratermania.Automation.Interfaces;
using Ratermania.Shopify;
using Ratermania.Shopify.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PartSource.Automation.Jobs
{
/// <summary>
/// Ensures syncronization between Shopify IDs and Partsource SKUs
/// </summary>
public class SyncronizeProducts : IAutomationJob
{
private readonly PartSourceContext _partSourceContext;
private readonly ShopifyClient _shopifyClient;
private readonly ILogger<TestJob> _logger;
public SyncronizeProducts(ILogger<TestJob> logger, PartSourceContext partSourceContext, ShopifyClient shopifyClient)
{
_partSourceContext = partSourceContext;
_shopifyClient = shopifyClient;
_logger = logger;
}
public async Task Run()
{
IList<ImportData> importData = _partSourceContext.ImportData.FromSql<ImportData>($"SELECT * FROM ImportDataFilters").ToList();
IEnumerable<Product> products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 } });
while (products?.Any() == true)
{
foreach (Product product in products)
{
foreach (Variant variant in product.Variants)
{
ImportData item = importData.FirstOrDefault(i => i.VariantSku == variant.Sku);
if (item != null)
{
_partSourceContext.Database.ExecuteSqlCommand($"UPDATE ImportDataFilters SET ShopifyId = {product.Id} WHERE VariantSku = {variant.Sku}");
}
}
}
try
{
_logger.LogInformation("Did 250");
//await _partSourceContext.SaveChangesAsync();
}
catch
{
Console.WriteLine("Failed to save a batch of products");
}
finally
{
products = await _shopifyClient.Products.GetNext();
}
}
}
}
}

View File

@@ -38,19 +38,12 @@ namespace PartSource.Automation.Jobs
} }
public async Task Run() public async Task Run()
{
IList<string> productTypes = new List<string>
{
"CA108-SC349-FL34907_CV Shafts, New"
};
foreach (string type in productTypes)
{ {
IEnumerable<Product> products = null; IEnumerable<Product> products = null;
try try
{ {
products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 }, { "product_type", "CA108-SC349-FL34907_CV Shafts, New" } }); products = await _shopifyClient.Products.Get(new Dictionary<string, object> { { "limit", 250 } });
} }
catch (Exception ex) catch (Exception ex)
@@ -65,6 +58,12 @@ namespace PartSource.Automation.Jobs
{ {
foreach (Product product in products) foreach (Product product in products)
{ {
// Wiper blades are a separate fitment process.
if (product.ProductType.Contains("CA172-SC231"))
{
continue;
}
ImportData importData = null; ImportData importData = null;
try try
@@ -84,24 +83,14 @@ namespace PartSource.Automation.Jobs
}; };
// } // }
//importData.PartNumber = product.Title.Split(' ')[0];
bool isFitment = false; bool isFitment = false;
string bodyHtml = product.BodyHtml.Substring(0, product.BodyHtml.IndexOf("</ul>") + "</ul>".Length); string bodyHtml = product.BodyHtml[..(product.BodyHtml.IndexOf("</ul>") + "</ul>".Length)];
IList<Vehicle> vehicles = _vehicleService.GetVehiclesForPart(importData.PartNumber, importData.LineCode); IList<Vehicle> vehicles = _vehicleService.GetVehiclesForPart(importData.PartNumber, importData.LineCode);
//if (vehicles.Count > 250)
//{
// vehicles = vehicles.Take(250)
// .ToList();
// _logger.LogInformation($"SKU {importData.VariantSku} fits more than 250 vehicles. Only the first 250 will be used.");
//}
IList<int> vehicleIdFitment = _vehicleService.GetVehicleIdFitment(vehicles); IList<int> vehicleIdFitment = _vehicleService.GetVehicleIdFitment(vehicles);
if (vehicleIdFitment.Count > 0) if (vehicleIdFitment.Any())
{ {
string vehicleIdString = string.Join('-', vehicleIdFitment.Select(j => $"v{j}")); string vehicleIdString = string.Join('-', vehicleIdFitment.Select(j => $"v{j}"));
@@ -110,8 +99,6 @@ namespace PartSource.Automation.Jobs
isFitment = true; isFitment = true;
string json = JsonConvert.SerializeObject(vehicleIdFitment); string json = JsonConvert.SerializeObject(vehicleIdFitment);
if (json.Length < 100000)
{
Metafield vehicleMetafield = new Metafield Metafield vehicleMetafield = new Metafield
{ {
Namespace = "fitment", Namespace = "fitment",
@@ -125,13 +112,6 @@ namespace PartSource.Automation.Jobs
await _shopifyClient.Metafields.Add(vehicleMetafield); 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 = _vehicleService.GetYmmFitment(vehicles); IList<string> ymmFitment = _vehicleService.GetYmmFitment(vehicles);
if (ymmFitment.Count > 0) if (ymmFitment.Count > 0)
{ {
@@ -160,8 +140,6 @@ namespace PartSource.Automation.Jobs
bodyHtml += $"<div id=\"seoData\">{stringBuilder.ToString()}</div>"; bodyHtml += $"<div id=\"seoData\">{stringBuilder.ToString()}</div>";
string json = JsonConvert.SerializeObject(ymmFitment); string json = JsonConvert.SerializeObject(ymmFitment);
if (json.Length < 100000)
{
Metafield ymmMetafield = new Metafield Metafield ymmMetafield = new Metafield
{ {
Namespace = "fitment", Namespace = "fitment",
@@ -175,13 +153,6 @@ namespace PartSource.Automation.Jobs
await _shopifyClient.Metafields.Add(ymmMetafield); 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 Metafield isFitmentMetafield = new Metafield
{ {
Namespace = "Flags", Namespace = "Flags",
@@ -204,7 +175,7 @@ namespace PartSource.Automation.Jobs
OwnerId = product.Id OwnerId = product.Id
}; };
//await _shopifyClient.Metafields.Add(lineCodeMetafield); // await _shopifyClient.Metafields.Add(lineCodeMetafield);
Metafield partNumberMetafield = new Metafield Metafield partNumberMetafield = new Metafield
{ {
@@ -216,7 +187,7 @@ namespace PartSource.Automation.Jobs
OwnerId = product.Id OwnerId = product.Id
}; };
// await _shopifyClient.Metafields.Add(partNumberMetafield); //await _shopifyClient.Metafields.Add(partNumberMetafield);
List<string> tags = new List<string>(); List<string> tags = new List<string>();
@@ -238,8 +209,9 @@ namespace PartSource.Automation.Jobs
tags.Add(zzzIsFitment); tags.Add(zzzIsFitment);
//product.Tags = string.Join(',', tags); product.Tags = string.Join(',', tags);
product.BodyHtml = bodyHtml; product.BodyHtml = bodyHtml;
await _shopifyClient.Products.Update(product); await _shopifyClient.Products.Update(product);
importData.IsFitment = isFitment; importData.IsFitment = isFitment;
@@ -270,7 +242,5 @@ namespace PartSource.Automation.Jobs
} }
} }
} }
;
} }
} }
}

View File

@@ -41,6 +41,8 @@ namespace PartSource.Automation.Jobs
IEnumerable<Product> products = await _shopifyClient.Products.Get(parameters); IEnumerable<Product> products = await _shopifyClient.Products.Get(parameters);
int i = 1;
while (products != null && products.Any()) while (products != null && products.Any())
{ {
foreach (Product product in products) foreach (Product product in products)
@@ -94,41 +96,47 @@ namespace PartSource.Automation.Jobs
await SavePositionMetafield(product, vehicleIds, currentPosition); await SavePositionMetafield(product, vehicleIds, currentPosition);
//IList<string> notes = fitments.Select(f => f.NoteText) IList<string> notes = fitments.Select(f => f.FitmentNoteHash)
.Distinct()
.ToList();
// .Distinct() IList<object> vehicleNotes = new List<object>();
// .ToList();
//IList<object> vehicleNotes = new List<object>(); foreach (string noteHash in notes)
{
FitmentNote fitmentNote = await _fitmentContext.FitmentNotes.FirstOrDefaultAsync(f => f.Hash == noteHash);
//foreach (string noteText in notes) if (fitmentNote == null)
//{ {
// vehicleIds = fitments.Where(f => f.NoteText == noteText) continue;
// .Select(f => new { f.EngineConfigId, f.BaseVehicleId }) }
// .SelectMany(f => vehicles.Where(v => v.BaseVehicleId == f.BaseVehicleId && v.EngineConfigId == f.EngineConfigId))
// .Select(v => v.VehicleToEngineConfigId)
// .ToList();
// vehicleNotes.Add(new { noteText, vehicleIds }); vehicleIds = fitments.Where(f => f.FitmentNoteHash == noteHash)
//} .Select(f => new { f.EngineConfigId, f.BaseVehicleId })
.SelectMany(f => vehicles.Where(v => v.BaseVehicleId == f.BaseVehicleId && v.EngineConfigId == f.EngineConfigId))
.Select(v => v.VehicleToEngineConfigId)
.ToList();
//string json = JsonConvert.SerializeObject(vehicleNotes); vehicleNotes.Add(new { fitmentNote.NoteText, vehicleIds });
//if (json.Length >= 100000) }
//{
// continue;
//}
//Metafield vehicleMetafield = new Metafield string json = JsonConvert.SerializeObject(vehicleNotes);
//{ if (json.Length >= 100000)
// Namespace = "fitment", {
// Key = "note_text", continue;
// Value = json, }
// ValueType = "json_string",
// OwnerResource = "product",
// OwnerId = product.Id
//};
//await _shopifyClient.Metafields.Add(vehicleMetafield); Metafield vehicleMetafield = new Metafield
{
Namespace = "fitment",
Key = "note_text",
Value = json,
ValueType = "json_string",
OwnerResource = "product",
OwnerId = product.Id
};
await _shopifyClient.Metafields.Add(vehicleMetafield);
//importData.UpdatedAt = DateTime.Now; //importData.UpdatedAt = DateTime.Now;
//importData.UpdateType = "Positioning"; //importData.UpdateType = "Positioning";
@@ -142,6 +150,7 @@ namespace PartSource.Automation.Jobs
try try
{ {
Console.WriteLine(i);
products = await _shopifyClient.Products.GetNext(); products = await _shopifyClient.Products.GetNext();
} }
@@ -200,7 +209,7 @@ namespace PartSource.Automation.Jobs
OwnerId = product.Id OwnerId = product.Id
}; };
System.Diagnostics.Debug.WriteLine(json); //System.Diagnostics.Debug.WriteLine(json);
await _shopifyClient.Metafields.Add(vehicleMetafield); await _shopifyClient.Metafields.Add(vehicleMetafield);
} }

View File

@@ -85,7 +85,7 @@ namespace PartSource.Automation.Jobs
product.Variants[i].Price = partPrice.Your_Price.Value; product.Variants[i].Price = partPrice.Your_Price.Value;
product.Variants[i].CompareAtPrice = partPrice.Compare_Price.Value; product.Variants[i].CompareAtPrice = partPrice.Compare_Price.Value;
product.PublishedAt = partPrice.Active.Trim().ToUpperInvariant() == "Y" ? (DateTime?)DateTime.Now : null; product.PublishedAt = partPrice.Active.Trim().ToUpperInvariant() == "Y" ? DateTime.Now : null;
product.PublishedScope = PublishedScope.Global; product.PublishedScope = PublishedScope.Global;
//Metafield metafield = new Metafield //Metafield metafield = new Metafield

View File

@@ -7,17 +7,17 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="10.0.0" /> <PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.0.1" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="11.0.0" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.6"> <PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.2">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.1.11" /> <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0" />
<PackageReference Include="Ratermania.Automation" Version="1.0.0" /> <PackageReference Include="Ratermania.Automation" Version="1.0.0" />
<PackageReference Include="Ratermania.Automation.Common" Version="1.0.0" /> <PackageReference Include="Ratermania.Automation.Common" Version="1.0.0" />
<PackageReference Include="Ratermania.Shopify" Version="1.3.1" /> <PackageReference Include="Ratermania.Shopify" Version="1.3.1" />

View File

@@ -73,22 +73,28 @@ namespace PartSource.Automation
//options.ApiKey = "9a533dad460321c6ce8f30bf5b8691ed"; //options.ApiKey = "9a533dad460321c6ce8f30bf5b8691ed";
//options.ApiSecret = "dc9e28365d9858e544d57ac7af43fee7"; //options.ApiSecret = "dc9e28365d9858e544d57ac7af43fee7";
//options.ApiVersion = "2020-01"; //options.ApiVersion = "2021-01";
//options.ShopDomain = "dev-partsource.myshopify.com"; //options.ShopDomain = "dev-partsource.myshopify.com";
}) })
.AddAutomation(options => .AddAutomation(options =>
{ {
//options.HasBaseInterval(new TimeSpan(0, 15, 0))
// .HasMaxFailures(3)
// .HasJob<ExecuteSsisPackages>(options =>
// options.HasInterval(new TimeSpan(24, 0, 0))
// .StartsAt(DateTime.Today.AddHours(26))
// )
// .HasJob<UpdatePricing>(options =>
// options.HasInterval(new TimeSpan(24, 0, 0))
// .StartsAt(DateTime.Today.AddHours(27))
// .HasDependency<ExecuteSsisPackages>()
// );
options.HasBaseInterval(new TimeSpan(0, 15, 0)) options.HasBaseInterval(new TimeSpan(0, 15, 0))
.HasMaxFailures(3) .HasMaxFailures(3)
.HasJob<ExecuteSsisPackages>(options => .HasJob<UpdateWiperFitment>(options =>
options.HasInterval(new TimeSpan(24, 0, 0)) options.HasInterval(new TimeSpan(24, 0, 0))
.StartsAt(DateTime.Today.AddHours(26))
)
.HasJob<UpdatePricing>(options =>
options.HasInterval(new TimeSpan(24, 0, 0))
.StartsAt(DateTime.Today.AddHours(27))
.HasDependency<ExecuteSsisPackages>()
); );
//.AddApiServer(); //.AddApiServer();
}) })
@@ -101,7 +107,6 @@ namespace PartSource.Automation
.AddSingleton<VehicleService>() .AddSingleton<VehicleService>()
.AddSingleton<NexpartService>() .AddSingleton<NexpartService>()
.AddAutoMapper(typeof(PartSourceProfile)); .AddAutoMapper(typeof(PartSourceProfile));
}) })
.ConfigureLogging((builder, logging) => .ConfigureLogging((builder, logging) =>

View File

@@ -1,14 +1,13 @@
#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities #pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; 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.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace PartSource.Automation.Services namespace PartSource.Automation.Services
{ {
@@ -53,12 +52,12 @@ namespace PartSource.Automation.Services
} }
} }
public void TruncateVehicleTable() public void TruncateVehicleTables()
{ {
using SqlConnection connection = new SqlConnection(_connectionString); using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open(); connection.Open();
using SqlCommand command = new SqlCommand($"truncate table dbo.Vehicle", connection); using SqlCommand command = new SqlCommand($"exec DropVehicleTables", connection);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
@@ -151,16 +150,10 @@ namespace PartSource.Automation.Services
using SqlCommand command = new SqlCommand($"exec CreateFitmentView", connection); using SqlCommand command = new SqlCommand($"exec CreateFitmentView", connection);
command.CommandTimeout = 1800; command.CommandTimeout = 1800;
command.ExecuteNonQuery(); command.ExecuteNonQuery();
using SqlCommand command2 = new SqlCommand($"exec CreateFitmentIndexes", connection);
command.CommandTimeout = 1800;
command2.ExecuteNonQuery();
} }
public void CreateVehicleTable() public void CreateVehicleTable()
{ {
return;
using SqlConnection connection = new SqlConnection(_connectionString); using SqlConnection connection = new SqlConnection(_connectionString);
connection.Open(); connection.Open();

View File

@@ -15,18 +15,23 @@ namespace PartSource.Data.Contexts
public DbSet<Fitment> Fitments { get; set; } public DbSet<Fitment> Fitments { get; set; }
public DbSet<FitmentNote> FitmentNotes { get; set; }
public DbSet<Vehicle> Vehicles { get; set; } public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Wiper> Wipers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
modelBuilder.Entity<DcfMapping>().HasKey(d => new { d.LineCode, d.WhiCode }); modelBuilder.Entity<DcfMapping>().HasKey(d => new { d.LineCode, d.WhiCode });
modelBuilder.Entity<Fitment>().HasKey(f => new { f.BaseVehicleId, f.EngineConfigId, f.LineCode, f.PartNumber }); modelBuilder.Entity<Fitment>().HasKey(f => new { f.BaseVehicleId, f.EngineConfigId, f.LineCode, f.PartNumber });
modelBuilder.Entity<Wiper>().HasKey(f => new { f.BaseVehicleId, f.PartNumber, f.LineCode, f.Position});
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
{ {
entityType.Relational().TableName = entityType.ClrType.Name; entityType.SetTableName(entityType.ClrType.Name);
} }
} }
} }

View File

@@ -14,9 +14,7 @@ namespace PartSource.Data.Contexts
public DbSet<ApiClient> ApiClients { get; set; } public DbSet<ApiClient> ApiClients { get; set; }
public DbSet<ProductBackup> ProductBackups { get; set; } public DbSet<DcfMapping> DcfMappings { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<ImportData> ImportData { get; set; } public DbSet<ImportData> ImportData { get; set; }
@@ -36,27 +34,22 @@ namespace PartSource.Data.Contexts
public DbSet<PartsAvailability> PartAvailabilities { get; set; } public DbSet<PartsAvailability> PartAvailabilities { get; set; }
public DbQuery<BaseVehicle> BaseVehicles { get; set; } public DbSet<BaseVehicle> BaseVehicles { get; set; }
public DbQuery<Engine> Engines { get; set; } public DbSet<Engine> Engines { get; set; }
public DbQuery<Submodel> Submodels { get; set; } public DbSet<Submodel> Submodels { get; set; }
public DbQuery<VehicleMake> VehicleMakes { get; set; } public DbSet<VehicleMake> VehicleMakes { get; set; }
public DbQuery<VehicleModel> VehicleModels { get; set; } public DbSet<VehicleModel> VehicleModels { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
modelBuilder.Query<BaseVehicle>().ToView(nameof(BaseVehicle));
modelBuilder.Query<Engine>().ToView(nameof(Engine));
modelBuilder.Query<Submodel>().ToView(nameof(Submodel));
modelBuilder.Query<VehicleMake>().ToView(nameof(VehicleMake));
modelBuilder.Query<VehicleModel>().ToView(nameof(VehicleModel));
modelBuilder.Entity<PartsAvailability>().HasKey(p => new { p.Store, p.SKU }); modelBuilder.Entity<PartsAvailability>().HasKey(p => new { p.Store, p.SKU });
modelBuilder.Entity<DcfMapping>().HasKey(d => new { d.LineCode, d.WhiCode });
modelBuilder.Entity<ShopifyChangelog>() modelBuilder.Entity<ShopifyChangelog>()
.Property(s => s.ResourceType) .Property(s => s.ResourceType)
@@ -68,7 +61,7 @@ namespace PartSource.Data.Contexts
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes()) foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
{ {
entityType.Relational().TableName = entityType.ClrType.Name; entityType.SetTableName(entityType.ClrType.Name);
} }
} }

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Text; using System.Text;
@@ -7,6 +8,7 @@ namespace PartSource.Data.Models
{ {
public class BaseVehicle public class BaseVehicle
{ {
[Key]
public int BaseVehicleId { get; set; } public int BaseVehicleId { get; set; }
public string Make { get; set; } public string Make { get; set; }

View File

@@ -1,13 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
namespace PartSource.Data.Models namespace PartSource.Data.Models
{ {
public class Engine public class Engine
{ {
[Key]
public int EngineConfigId { get; set; } public int EngineConfigId { get; set; }
public string Description { get; set; } public string Description { 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 FitmentNote
{
public string NoteText { get; set; }
[Key]
public string Hash { get; set; }
}
}

View File

@@ -1,27 +1,14 @@
// Decompiled with JetBrains decompiler using System.ComponentModel.DataAnnotations;
// Type: PartSource.Data.Models.Part
// Assembly: PartSource.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 3EDAB3F5-83E7-4F65-906E-B40192014C57
// Assembly location: C:\Users\Tommy\Desktop\PS temp\PartSource.Data.dll
namespace PartSource.Data.Models namespace PartSource.Data.Models
{ {
public class Part public class Part
{ {
public int Id { get; set; } [Key]
public string Sku { get; set; }
public int ManufacturerId { get; set; } public string LineCode { get; set; }
public long? ShopifyId { get; set; }
public int Sku { get; set; }
public string PartNumber { get; set; } public string PartNumber { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Manufacturer Manufacturer { get; set; }
} }
} }

View File

@@ -9,6 +9,7 @@ namespace PartSource.Data.Models
{ {
public class Submodel public class Submodel
{ {
[Key]
public int SubmodelId { get; set; } public int SubmodelId { get; set; }
public string Name { get; set; } public string Name { get; set; }

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Text; using System.Text;
@@ -8,6 +9,7 @@ namespace PartSource.Data.Models
public class VehicleMake public class VehicleMake
{ {
[DatabaseGenerated(DatabaseGeneratedOption.None)] [DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int MakeId { get; set; } public int MakeId { get; set; }
public string Name { get; set; } public string Name { get; set; }

View File

@@ -1,6 +1,7 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
using System.Text; using System.Text;
@@ -9,6 +10,7 @@ namespace PartSource.Data.Models
public class VehicleModel public class VehicleModel
{ {
[DatabaseGenerated(DatabaseGeneratedOption.None)] [DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int ModelId { get; set; } public int ModelId { get; set; }
public int Year { get; set; } public int Year { get; set; }

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PartSource.Data.Models
{
public class Wiper
{
public int BaseVehicleId { get; set; }
public string LineCode { get; set; }
public string PartNumber { get; set; }
public string Position { get; set; }
public string PartName { get; set; }
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public class App
{
[XmlElement]
[JsonProperty("lineCode")]
public string MfrCode { get; set; }
[XmlElement]
[JsonProperty("description")]
public string MfrLabel { get; set; }
[XmlElement]
[JsonProperty("position")]
public string Position { get; set; }
[XmlElement]
[JsonProperty("partNumber")]
public string Part { get; set; }
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")]
public class ApplicationSearch
{
public ApplicationSearch()
{
PSRequestHeader = new PSRequestHeader();
}
[XmlElement(Order = 1)]
public PSRequestHeader PSRequestHeader { get; set; }
[XmlElement(Order = 2)]
public VehicleIdentifier VehicleIdentifier { get; set; }
[XmlElement(Order = 3)]
public string[] MfrCode { get; set; }
[XmlElement(Order = 4)]
public PartType[] PartType { get; set; }
[XmlElement(Order = 5)]
public bool SecondaryDCF => true;
[XmlElement(Order = 6)]
public Criterion[] Criterion { get; set; }
[XmlElement(Order = 7)]
public string GroupBy { get; set; }
}
}

View File

@@ -1,18 +1,21 @@
using PartSource.Data.Nexpart.Interfaces; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization; using System.Xml.Serialization;
using PartSource.Data.Nexpart.Interfaces;
namespace PartSource.Data.Nexpart namespace PartSource.Data.Nexpart
{ {
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")] [XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")]
public class BuyersGuideSearchResponse : IResponseElement<BuyersGuideData> public class ApplicationSearchResponse : IResponseElement<Apps>
{ {
[XmlElement] [XmlElement]
public PSResponseHeader PSResponseHeader { get; set; } public PSResponseHeader PSResponseHeader { get; set; }
[XmlElement(ElementName = "BuyersGuideData")] [XmlElement(ElementName = nameof(Apps))]
public BuyersGuideData ResponseBody { get; set; } public Apps ResponseBody { get; set; }
} }
} }

View File

@@ -1,14 +1,13 @@
using System; using System.Xml.Serialization;
using System.Collections.Generic; using Newtonsoft.Json;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart namespace PartSource.Data.Nexpart
{ {
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")] [XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public class Apps public class Apps
{ {
[XmlElement] [XmlElement(Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public BuyersGuideMake[] Make { get; set; } [JsonProperty("wipers")]
public App[] App { get; set; }
} }
} }

View File

@@ -11,12 +11,12 @@ namespace PartSource.Data.Nexpart
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")] [XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")]
public class Body public class Body
{ {
[XmlElement(ElementName = "ApplicationSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(ApplicationSearch))]
[XmlElement(ElementName = "ApplicationSearchResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(ApplicationSearchResponse))]
[XmlElement(ElementName = "BaseVehicleDetailLookup", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleDetailLookup))] [XmlElement(ElementName = "BaseVehicleDetailLookup", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleDetailLookup))]
[XmlElement(ElementName = "BaseVehicleDetailLookupResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleDetailLookupResponse))] [XmlElement(ElementName = "BaseVehicleDetailLookupResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleDetailLookupResponse))]
[XmlElement(ElementName = "BaseVehicleSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleSearch))] [XmlElement(ElementName = "BaseVehicleSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleSearch))]
[XmlElement(ElementName = "BaseVehicleSearchResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleSearchResponse))] [XmlElement(ElementName = "BaseVehicleSearchResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BaseVehicleSearchResponse))]
[XmlElement(ElementName = "BuyersGuideSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BuyersGuideSearch))]
[XmlElement(ElementName = "BuyersGuideSearchResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(BuyersGuideSearchResponse))]
[XmlElement(ElementName = "EngineSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(EngineSearch))] [XmlElement(ElementName = "EngineSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(EngineSearch))]
[XmlElement(ElementName = "EngineSearchResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(EngineSearchResponse))] [XmlElement(ElementName = "EngineSearchResponse", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(EngineSearchResponse))]
[XmlElement(ElementName = "MakeSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(MakeSearch))] [XmlElement(ElementName = "MakeSearch", Namespace = "http://whisolutions.com/PartSelectService-v1", Type = typeof(MakeSearch))]

View File

@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")]
public class BuyersGuideData
{
[XmlElement(Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public Apps Apps { get; set; }
}
}

View File

@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public class BuyersGuideEngine
{
[XmlAttribute]
public string Desc { get; set; }
[XmlAttribute]
public int PerVehicle { get; set; }
[XmlAttribute]
public int Year { get; set; }
}
}

View File

@@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public class BuyersGuideMake
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public int FromYear { get; set; }
[XmlAttribute]
public int ToYear { get; set; }
[XmlAttribute]
public int MakeCount { get; set; }
[XmlElement]
public BuyersGuideModel[] Model { get; set; }
}
}

View File

@@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public class BuyersGuideModel
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public int FromYear { get; set; }
[XmlAttribute]
public int ToYear { get; set; }
[XmlAttribute]
public int ModelCount { get; set; }
[XmlElement]
public BuyersGuideEngine[] Engine { get; set; }
}
}

View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectServ/2011-07-21")]
public class BuyersGuidePart
{
[XmlAttribute]
public string PartNumber { get; set; }
[XmlAttribute]
public string MfrCode { get; set; }
}
}

View File

@@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace PartSource.Data.Nexpart
{
[XmlType(AnonymousType = true, Namespace = "http://whisolutions.com/PartSelectService-v1")]
public class BuyersGuideSearch
{
public BuyersGuideSearch()
{
PSRequestHeader = new PSRequestHeader();
}
[XmlElement(Order = 1)]
public PSRequestHeader PSRequestHeader { get; set; }
[XmlElement(Order = 2)]
public BuyersGuidePart Part { get; set; }
}
}

View File

@@ -13,11 +13,5 @@ namespace PartSource.Data.Nexpart
{ {
[XmlAttribute] [XmlAttribute]
public int Id { get; set; } public int Id { get; set; }
[XmlAttribute]
public int PositionGroupId { get; set; }
[XmlAttribute]
public string Description { get; set; }
} }
} }

View File

@@ -17,10 +17,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="10.0.0" /> <PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.5">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.0" /> <PrivateAssets>all</PrivateAssets>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup> </ItemGroup>

View File

@@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using PartSource.Data.Contexts;
using PartSource.Data.Dtos;
using PartSource.Data.Models;
namespace PartSource.Services
{
public class FitmentService
{
private readonly FitmentContext _fitmentContext;
public FitmentService(FitmentContext fitmentContext)
{
_fitmentContext = fitmentContext;
}
public IList<string> GetYmmFitment(IList<Vehicle> vehicles)
{
if (vehicles.Count == 0)
{
return new string[0];
}
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();
foreach (string makeModel in makeModels)
{
string make = makeModel.Split(',')[0];
string model = makeModel.Split(',')[1];
List<string> years = vehicles
.Where(v => v.MakeName == make && v.ModelName == model)
.OrderBy(v => v.Year)
.Select(v => v.Year.ToString().Trim())
.Distinct()
.ToList();
string tag = $"{string.Join('-', years)} {make.Trim()} {model.Trim()}";
System.Diagnostics.Debug.WriteLine(tag);
fitmentTags.Add(tag);
}
return fitmentTags;
}
public IList<string> GetYmmFitmentRange(IList<Vehicle> vehicles)
{
if (vehicles.Count == 0)
{
return new string[0];
}
IList<string> fitmentTags = new List<string>();
IList<string> makeModels = vehicles.Select(v => $"{v.MakeName},{v.ModelName}").Distinct().ToList();
foreach (string makeModel in makeModels)
{
string make = makeModel.Split(',')[0];
string model = makeModel.Split(',')[1];
int minYear = vehicles
.Where(v => v.MakeName == make && v.ModelName == model)
.Min(v => v.Year);
int maxYear = vehicles
.Where(v => v.MakeName == make && v.ModelName == model)
.Max(v => v.Year);
string tag = minYear == maxYear
? $"{minYear} {make.Trim()} {model.Trim()}"
: $"{minYear}-{maxYear} {make.Trim()} {model.Trim()}";
System.Diagnostics.Debug.WriteLine(tag);
fitmentTags.Add(tag);
}
return fitmentTags;
}
public IList<int> GetVehicleIdFitment(IList<Vehicle> vehicles)
{
return vehicles.Select(v => v.VehicleToEngineConfigId).Distinct().ToList();
}
public IList<Vehicle> GetVehiclesForPart(string partNumber, string lineCode, int maxVehicles = 0)
{
if (string.IsNullOrEmpty(partNumber) || string.IsNullOrEmpty(lineCode))
{
return null;
}
partNumber = Regex.Replace(partNumber, "[^a-zA-Z0-9]", string.Empty);
IQueryable<string> whiCodes = _fitmentContext.DcfMappings
.Where(d => d.LineCode == lineCode)
.Select(d => d.WhiCode);
IQueryable<Vehicle> vehicles = _fitmentContext.Fitments
.Where(f => f.PartNumber == partNumber && whiCodes.Contains(f.LineCode))
.Join(_fitmentContext.Vehicles,
f => new { f.BaseVehicleId, f.EngineConfigId },
v => new { v.BaseVehicleId, v.EngineConfigId },
(f, v) => v)
.Distinct()
.OrderByDescending(x => x.Year);
if (maxVehicles > 0)
{
vehicles = vehicles.Take(maxVehicles);
}
return vehicles.ToList();
}
public IList<VehicleFitmentDto> GetVehicleFitmentForPart(string partNumber, string lineCode, int maxVehicles = 0)
{
if (string.IsNullOrEmpty(partNumber) || string.IsNullOrEmpty(lineCode))
{
return null;
}
partNumber = Regex.Replace(partNumber, "[^a-zA-Z0-9\\-]", string.Empty);
IQueryable<string> whiCodes = _fitmentContext.DcfMappings
.Where(d => d.LineCode == lineCode)
.Select(d => d.WhiCode);
IQueryable<VehicleFitmentDto> vehicles = _fitmentContext.Fitments
.Where(f => f.PartNumber == partNumber && whiCodes.Contains(f.LineCode))
.Join(_fitmentContext.Vehicles,
f => new { f.BaseVehicleId, f.EngineConfigId },
v => new { v.BaseVehicleId, v.EngineConfigId },
(f, v) => new VehicleFitmentDto
{
Fitment = f,
Vehicle = v
})
.Distinct();
if (maxVehicles > 0)
{
vehicles = vehicles.Take(maxVehicles);
}
return vehicles.ToList();
}
}
}

View File

@@ -19,8 +19,6 @@ namespace PartSource.Services
XmlSerializer serializer = new XmlSerializer(typeof(Envelope)); XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
using (TextWriter textWriter = new StringWriter(sb)) using (TextWriter textWriter = new StringWriter(sb))
{ {
serializer.Serialize(textWriter, (object)envelope); serializer.Serialize(textWriter, (object)envelope);
@@ -37,7 +35,9 @@ namespace PartSource.Services
HttpResponseMessage response = await client.PostAsync("http://acespssprod.nexpart.com:8081/partselect/1.0/services/PartSelectService.PartSelectHttpSoap11Endpoint/", new StringContent(textWriter.ToString(), Encoding.UTF8)); HttpResponseMessage response = await client.PostAsync("http://acespssprod.nexpart.com:8081/partselect/1.0/services/PartSelectService.PartSelectHttpSoap11Endpoint/", new StringContent(textWriter.ToString(), Encoding.UTF8));
Stream result = await response.Content.ReadAsStreamAsync(); Stream result = await response.Content.ReadAsStreamAsync();
string str = await response.Content.ReadAsStringAsync(); string str = await response.Content.ReadAsStringAsync();
content = (U)((Envelope)serializer.Deserialize(result)).Body.Content; content = (U)((Envelope)serializer.Deserialize(result)).Body.Content;
;
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -10,7 +10,6 @@ using System.Threading.Tasks;
namespace PartSource.Services namespace PartSource.Services
{ {
[Obsolete]
public class PartService public class PartService
{ {
private readonly PartSourceContext _context; private readonly PartSourceContext _context;
@@ -20,31 +19,21 @@ namespace PartSource.Services
_context = context; _context = context;
} }
public Part GetPart(string partNumber, string lineCode)
{
return _context.Parts.FirstOrDefault(p => p.PartNumber == partNumber && p.Manufacturer.LineCode == lineCode);
}
public Part GetPart(int sku)
{
return _context.Parts.FirstOrDefault(p => p.Sku == sku);
}
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 _context.PartAvailabilities.FirstOrDefaultAsync(s => s.Store == storeNumber && s.SKU == sku);
} }
public IList<Fitment> GetFitments(FitmentSearchDto fitmentSearchDto) public async Task<Part> GetPartBySku(string sku)
{ {
return null; return await _context.Parts.SingleOrDefaultAsync(p => p.Sku == sku);
}
//return _context.Fitments.Where(f => public async Task<IList<DcfMapping>> GetDcfMapping(string partsourceLineCode)
// f.ManufacturerCode == fitmentSearchDto.ManufacturerCode && {
// f.PartNumber == fitmentSearchDto.PartNumber && return await _context.DcfMappings
// f.BaseVehicleId == fitmentSearchDto.BaseVehicleId && .Where(dcf => dcf.LineCode == partsourceLineCode)
// f.EngineConfigId == fitmentSearchDto.EngineConfigId .ToListAsync();
//).ToList();
} }
} }
} }

View File

@@ -12,8 +12,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="10.0.0" /> <PackageReference Include="AutoMapper" Version="11.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Ratermania.Shopify" Version="1.3.1" /> <PackageReference Include="Ratermania.Shopify" Version="1.3.1" />
</ItemGroup> </ItemGroup>
@@ -21,10 +21,4 @@
<ProjectReference Include="..\PartSource.Data\PartSource.Data.csproj" /> <ProjectReference Include="..\PartSource.Data\PartSource.Data.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@@ -1,22 +0,0 @@
{
"ConnectionStrings": {
//"PartSourceDatabase": "Server=(localdb)\\mssqllocaldb;Database=PartSource;Trusted_Connection=True;"
"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;"
},
"emailConfiguration": {
"From": "alerts@ps-shopify.canadaeast.cloudapp.azure.com",
// "To": "tom@soundpress.com,Anas.Bajwa@Partsource.ca",
"To": "tommy@localhost",
"SmtpHost": "localhost"
},
"ftpConfiguration": {
"Username": "ps-ftp\\$ps-ftp",
"Password": "ycvXptffBxqkBXW4vuRYqn4Zi1soCvnvMMolTe5HNSeAlcl3bAyJYtNhG579",
"Url": "ftp://waws-prod-yq1-007.ftp.azurewebsites.windows.net/site/wwwroot",
"Destination": "C:\\Users\\soundpress\\Desktop"
},
"ssisConfiguration": {
"Directory": "c:\\users\\soundpress\\desktop"
}
}