Sync products with old e5 CRM
This commit is contained in:
74
Bimix.Infrastructure/Sync/ProductSyncService.cs
Normal file
74
Bimix.Infrastructure/Sync/ProductSyncService.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System.Text.Json;
|
||||
using Bimix.Domain.Entities;
|
||||
using Bimix.Infrastructure.Data;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
namespace Bimix.Infrastructure.Sync;
|
||||
|
||||
public class ProductSyncService(HttpClient httpClient, BimixDbContext db, IConfiguration configuration)
|
||||
{
|
||||
private readonly HttpClient _httpClient = httpClient;
|
||||
private readonly BimixDbContext _db = db;
|
||||
private readonly IConfiguration _configuration = configuration;
|
||||
|
||||
public async Task RunAsync()
|
||||
{
|
||||
var apiKey = _configuration["E5_CRM:ApiKey"];
|
||||
var syncState = _db.SyncStates.FirstOrDefault(x => x.Entity == "Product") ?? new SyncState { Entity = "Product", LastSynced = 0};
|
||||
|
||||
var url = $"https://crm.e5.pl/REST/index.php?key={apiKey}&action=export.products.list&since={syncState.LastSynced}";
|
||||
var response = await _httpClient.GetStringAsync(url);
|
||||
|
||||
var products = JsonSerializer.Deserialize<List<JsonElement>>(response);
|
||||
if (products == null) return;
|
||||
|
||||
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
|
||||
foreach (var p in products)
|
||||
{
|
||||
var idStr = p.GetProperty("id").GetString() ?? "";
|
||||
var name = p.GetProperty("name").GetString() ?? "";
|
||||
|
||||
if (!Guid.TryParse(idStr, out Guid id))
|
||||
{
|
||||
Console.WriteLine($"[SYNC] Skipping product with wrong ID: '{idStr}', Name: '{name}'");
|
||||
continue;
|
||||
}
|
||||
|
||||
var existing = _db.Products.FirstOrDefault(x => x.Id == id);
|
||||
|
||||
if (existing == null)
|
||||
{
|
||||
var product = new Product
|
||||
{
|
||||
Id = id,
|
||||
Name = name,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow
|
||||
};
|
||||
_db.Products.Add(product);
|
||||
}
|
||||
else
|
||||
{
|
||||
existing.Name = name;
|
||||
existing.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
Console.WriteLine($"[SYNC] Updated product ID: '{idStr}', Name: '{name}'");
|
||||
|
||||
var exportedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var updateUrl = $"https://crm.e5.pl/REST/index.php?key={apiKey}&action=export.products.setExportedAt&id={id}&exportedAt={exportedAt}";
|
||||
await _httpClient.GetAsync(updateUrl);
|
||||
}
|
||||
syncState.LastSynced = now;
|
||||
if (_db.SyncStates.FirstOrDefault(x => x.Entity == "Product") == null)
|
||||
{
|
||||
_db.SyncStates.Add(syncState);
|
||||
}
|
||||
else
|
||||
{
|
||||
_db.SyncStates.Update(syncState);
|
||||
}
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user