Files
parr_api/PARR.AIHITRelationshipsSyncer/RelationshipsSyncer.cs

115 lines
5.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Logging;
using PARR.AIHITRelationshipsSyncer.Models;
using PARR.AIHITRelationshipsSyncer.Services.Interfaces;
using PARR.AIHITRelationshipsSyncer.Settings;
using PARR.Core.Common.Interfaces;
using System.Text.Json;
namespace PARR.AIHITRelationshipsSyncer
{
internal class RelationshipsSyncer : IRelationshipsSyncer
{
private readonly ILogger<RelationshipsSyncer> logger;
private readonly IIntervalService intervalService;
private readonly IAihitService aihitService;
private readonly IRelationshipsSyncService relationshipsSyncService;
private readonly WorkerSettings workerSettings;
public RelationshipsSyncer(
ILogger<RelationshipsSyncer> logger,
IIntervalService intervalService,
IAihitService aihitService,
IRelationshipsSyncService relationshipsSyncService,
WorkerSettings workerSettings
)
{
this.logger = logger;
this.intervalService = intervalService;
this.aihitService = aihitService;
this.relationshipsSyncService = relationshipsSyncService;
this.workerSettings = workerSettings;
}
public async Task StartAsync()
{
logger.LogInformation("Запуск сервиса синхронизации связей иерархии ЭК из АИХ ИТ в ПАРР");
await intervalService.IntervalInitAsync(async () =>
{
try
{
logger.LogInformation($"Начата загрузка иерархических связей между ЭК из АИХ ИТ");
List<AihitData>? aihitDataList = null;
#if DEBUG
const string mockFilePath = "MockData.json";
//Пытаемся загрузить mock-данные
if (File.Exists(mockFilePath) && new FileInfo(mockFilePath).Length > 0)
{
logger.LogInformation("Загрузка данных из mock-файла: {MockFile}", mockFilePath);
try
{
var json = await File.ReadAllTextAsync(mockFilePath);
aihitDataList = JsonSerializer.Deserialize<List<AihitData>>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
logger.LogInformation("Mock-данные успешно загружены");
}
catch (Exception ex)
{
logger.LogWarning(ex, "Не уадлось десериализовать {MockFile}. Будет выполнен запрос в базу АИХ ИТ", mockFilePath);
aihitDataList = null;
}
}
if (aihitDataList == null)
{
logger.LogInformation("Выполнение запроса в АИХ ИТ в режиме отладки");
var rawData = aihitService.GetData();
aihitDataList = rawData?.ToList();
if (aihitDataList != null && aihitDataList.Count > 0)
{
try
{
var json = JsonSerializer.Serialize(aihitDataList, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(mockFilePath, json);
logger.LogInformation("Данные сохранены в {MockFile} для будущей отладки", mockFilePath);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Не удалось сохранить данные в {MockFile}", mockFilePath);
}
}
}
#else
//Release
var rawData = aihitService.GetData();
aihitDataList = rawData?.ToList();
#endif
if (aihitDataList == null || aihitDataList.Count == 0)
{
logger.LogInformation("АИХ ИТ вернул пустые данные");
return;
}
logger.LogInformation("Получено {EkCount} записей для синхронизации", aihitDataList.Count);
await relationshipsSyncService.SyncAsync(aihitDataList);
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка синхронизации иерархических данных Unit из АИХ ИТ в ПАРР");
}
finally
{
logger.LogInformation($"Завершена загрузка иерархических связей между ЭК из АИХ ИТ");
}
}, workerSettings.RepeatEvery);
}
}
}