118 lines
2.7 KiB
C#
118 lines
2.7 KiB
C#
using PartSource.Automation.Jobs.Interfaces;
|
|
using PartSource.Automation.Models;
|
|
using PartSource.Data;
|
|
using PartSource.Data.Models;
|
|
using PartSource.Services.Integrations;
|
|
using Ratermania.Shopify.Entities;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace PartSource.Automation.Jobs
|
|
{
|
|
public class UpdatePricing : IAutomationJob
|
|
{
|
|
private readonly PartSourceContext _partSourceContext;
|
|
private readonly ShopifyClient _shopifyClient;
|
|
|
|
public UpdatePricing(PartSourceContext partSourceContext, ShopifyClient shopifyClient)
|
|
{
|
|
_partSourceContext = partSourceContext;
|
|
_shopifyClient = shopifyClient;
|
|
|
|
}
|
|
|
|
public async Task<AutomationJobResult> Run()
|
|
{
|
|
IEnumerable<Product> products = null;
|
|
int updateCount = 0;
|
|
|
|
try
|
|
{
|
|
products = await _shopifyClient.Products.Get();
|
|
}
|
|
|
|
catch (Exception ex)
|
|
{
|
|
// TODO: Logging
|
|
return new AutomationJobResult
|
|
{
|
|
Message = "Failed to get products from Shopify",
|
|
IsSuccess = false
|
|
};
|
|
}
|
|
|
|
while (products != null && products.Any())
|
|
{
|
|
foreach (Product product in products)
|
|
{
|
|
if (product.Variants.Length > 0)
|
|
{
|
|
ProductVariant variant = product.Variants[0];
|
|
PartPrice partPrice = _partSourceContext.PartPrices.Where(p => p.SKU == variant.Sku).FirstOrDefault();
|
|
|
|
if (partPrice == null || !partPrice.Your_Price.HasValue || !partPrice.Compare_Price.HasValue)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
if (product.Variants[0].Price != partPrice.Your_Price.Value || product.Variants[0].CompareAtPrice != partPrice.Compare_Price.Value)
|
|
{
|
|
product.Variants[0].Price = partPrice.Your_Price.Value;
|
|
product.Variants[0].CompareAtPrice = partPrice.Compare_Price.Value;
|
|
|
|
Metafield metafield = new Metafield
|
|
{
|
|
Namespace = "Pricing",
|
|
Key = "CorePrice",
|
|
Value = partPrice.Core_Price.HasValue ? partPrice.Core_Price.Value.ToString() : "0.00",
|
|
ValueType = "string",
|
|
OwnerResource = "product",
|
|
OwnerId = product.Id
|
|
};
|
|
|
|
try
|
|
{
|
|
await _shopifyClient.Products.Update(product);
|
|
|
|
updateCount++;
|
|
}
|
|
|
|
catch (Exception ex)
|
|
{
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
catch (Exception ex)
|
|
{
|
|
;
|
|
}
|
|
}
|
|
}
|
|
|
|
_partSourceContext.SaveChanges();
|
|
|
|
try
|
|
{
|
|
products = await _shopifyClient.Products.GetNext();
|
|
}
|
|
|
|
catch (Exception ex)
|
|
{
|
|
products = await _shopifyClient.Products.GetPrevious();
|
|
}
|
|
}
|
|
|
|
return new AutomationJobResult
|
|
{
|
|
Message = $"The nightly pricing update has completed. {updateCount} products were updated.",
|
|
IsSuccess = true
|
|
};
|
|
}
|
|
}
|
|
} |