156 lines
6.9 KiB
C#
156 lines
6.9 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
||
using Microsoft.Extensions.Logging;
|
||
using PARR.DAL.Contracts;
|
||
using PARR.DAL.Models;
|
||
using PARR.DAL.Services.Interfaces;
|
||
|
||
namespace PARR.EsppTemplateSync.Services
|
||
{
|
||
internal class Manager : IManager
|
||
{
|
||
private readonly ILogger<Manager> logger;
|
||
private readonly IServiceProvider serviceProvider;
|
||
private readonly IParserService parserService;
|
||
|
||
public Manager(
|
||
ILogger<Manager> logger,
|
||
IServiceProvider serviceProvider,
|
||
IParserService parserService
|
||
)
|
||
{
|
||
this.logger = logger;
|
||
this.serviceProvider = serviceProvider;
|
||
this.parserService = parserService;
|
||
}
|
||
|
||
public Task<bool> ManageFileAsync(string path)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
|
||
public async Task<bool> ManageStringAsync(string str)
|
||
{
|
||
bool isSuccess = true;
|
||
////TODO:
|
||
// тут обязательно нужна проверка, если str не того формата, возникает exception в ParseStringAsync
|
||
if (str == null || str.Trim().Length == 0)
|
||
return false;
|
||
|
||
var template = parserService.ParseString(str);
|
||
|
||
if (template == null)
|
||
{
|
||
isSuccess = false;
|
||
logger.LogError($"Не удалось распознать строку({str}) в Template");
|
||
}
|
||
else
|
||
{
|
||
//если шаблон не аквтивен, пропускаем
|
||
if (!template.IsActive)
|
||
{
|
||
return isSuccess;
|
||
}
|
||
|
||
//TODO: !!! тут метод называет чек, но он же и сохраняет. По идее надо чтобы чек че то вернул, а исходя из этого дургой метод сохранит или ченить изменит
|
||
// и опять же, saccess всегда true получается??? или это норм.
|
||
await CheckChangesAsync(template);
|
||
}
|
||
|
||
//todo: only true?????
|
||
return isSuccess;
|
||
}
|
||
|
||
private async Task CheckChangesAsync(Template esppTemplate)
|
||
{
|
||
// --- test ---
|
||
|
||
using (var scope = serviceProvider.CreateScope())
|
||
{
|
||
var services = scope.ServiceProvider;
|
||
|
||
var templateService = services.GetService<ITemplateService>();
|
||
|
||
if (templateService == null)
|
||
{
|
||
throw new Exception($"Не найден сервис: {nameof(ITemplateService)}");
|
||
// return;
|
||
}
|
||
|
||
var template = await templateService.GetTemplateByNameAsync(esppTemplate.Name);
|
||
//существует в ЕСПП но отсутствует в ПАРР.
|
||
//TODO деактивируем и видимо ещё что-то нужно
|
||
if (template == null)
|
||
{
|
||
// создает запись-шаблон из ЕСПП в ПАРР. Возможно избыточно так как эталон в ПАРР
|
||
////esppTemplate.StatusCode = "Deactivating";
|
||
////---
|
||
//esppTemplate.StatusCode = (int)StatusTemplateEnum.Ok;
|
||
//esppTemplate.IsActive = false;
|
||
//if (!await templateService.CreateAsync(esppTemplate) || !await templateService.CommitAsync())
|
||
//{
|
||
// logger.LogError($"Не удалось создать запись Template {esppTemplate.Name}({esppTemplate.ShortDescription})");
|
||
//}
|
||
//else
|
||
// logger.LogInformation($"----- Создана запись Template {esppTemplate.Name}({esppTemplate.ShortDescription}) -----");
|
||
//---
|
||
logger.LogWarning($"----- Найден шаблон ЕСПП незарегистрированный в ПАРР {esppTemplate.Name}({esppTemplate.ShortDescription}) -----");
|
||
}
|
||
else
|
||
{
|
||
var isChanged = false;
|
||
|
||
foreach (var prop in template.GetType().GetProperties())
|
||
{
|
||
if (prop == null) continue;
|
||
|
||
if (prop.Name == "Id" ||
|
||
prop.Name == "Status" ||
|
||
prop.Name == "DateCreated" ||
|
||
prop.Name == "DateModified" ||
|
||
prop.Name == "StatusCode"
|
||
) continue;
|
||
|
||
var parrValue = template.GetType().GetProperty(prop.Name)?.GetValue(template, null);
|
||
var esppValue = esppTemplate.GetType().GetProperty(prop.Name)?.GetValue(esppTemplate, null);
|
||
|
||
if (parrValue == null || esppValue == null) continue;
|
||
|
||
if (parrValue!.ToString()!.ToLower() != esppValue!.ToString()!.ToLower())
|
||
{
|
||
isChanged = true;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (isChanged)
|
||
{
|
||
logger.LogInformation($"----- Запись в ЕСПП отличается от Template {esppTemplate.Name}({esppTemplate.ShortDescription}) -----");
|
||
|
||
//template.Status = "Updating";
|
||
template.StatusCode = (int)StatusTemplateEnum.Updating;
|
||
|
||
if (!await templateService.CommitAsync())
|
||
logger.LogError($"Не удалось обновить запись Template {esppTemplate.Name}({esppTemplate.ShortDescription})");
|
||
else
|
||
logger.LogInformation($"----- Требуется обновление шаблона в ЕСПП роботом {esppTemplate.Name}({esppTemplate.ShortDescription}) -----");
|
||
}
|
||
else
|
||
{
|
||
//if (template.Status != "Ok")
|
||
if (template.StatusCode != (int)StatusTemplateEnum.Ok)
|
||
{
|
||
template.DateModified = DateTimeOffset.UtcNow;
|
||
template.StatusCode = (int)StatusTemplateEnum.Ok;
|
||
|
||
if (!await templateService.CommitAsync())
|
||
logger.LogInformation($"Шаблон в ЕСПП соответствует шаблону в ПАРР {esppTemplate.Name}({esppTemplate.ShortDescription}). Установлен статус {StatusTemplateEnum.Ok}");
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
}
|
||
}
|
||
}
|