feat(esppScheduleSync, esppSync): подключена логика INextRunServiceV2
This commit is contained in:
115
PARR.EsppSync/Domain/EsppObjectSchedule.cs
Normal file
115
PARR.EsppSync/Domain/EsppObjectSchedule.cs
Normal file
@@ -0,0 +1,115 @@
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.Contracts;
|
||||
|
||||
namespace PARR.EsppSync.Domain
|
||||
{
|
||||
public class EsppObjectSchedule : IEsppObject
|
||||
{
|
||||
//Все поля описаны в документации по роботам: http://gitlab.dvgd.oao.rzd/devptk/parr/parr_api/-/wikis/EsppRobots
|
||||
|
||||
public RobotsEnum Robot => RobotsEnum.ScheduleOrder;
|
||||
|
||||
public required string TemplateName { get; set; }
|
||||
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
public string ScheduleName { get; set; } = string.Empty;
|
||||
|
||||
public bool IsActive { get; set; }
|
||||
|
||||
public string ResponseArea { get; set; } = string.Empty;
|
||||
|
||||
public string WorkGroup { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Тип повторения: Регулярно, Ежегодно...
|
||||
/// </summary>
|
||||
public EsppSchTypeScheduleEnum TypeSchedule { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Интервал времени: Ежедневно, 1 00:00:00
|
||||
/// </summary>
|
||||
public string Interval { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Еженедельно: Каждый понедельник
|
||||
/// </summary>
|
||||
public string Dayofweek { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежемесячно: Каждое 23
|
||||
/// </summary>
|
||||
public string Dayofmonth { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежемесячно-2: Каждый Первый
|
||||
/// </summary>
|
||||
public string Md1 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежемесячно-2: Каждый Понедельник
|
||||
/// </summary>
|
||||
public string Md2 { get; set; } = string.Empty;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Ежегодно: Каждый Январь
|
||||
/// </summary>
|
||||
public string Annualm { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежегодно: Каждый 12
|
||||
/// </summary>
|
||||
public string Annualday { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежегодно-2: Каждый Первый
|
||||
/// </summary>
|
||||
public string An1 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежегодно-2: Каждый Понедельник
|
||||
/// </summary>
|
||||
public string An2 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ежегодно-2: Каждый Января
|
||||
/// </summary>
|
||||
public string An3 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Тип исключения: Нет исключений
|
||||
/// </summary>
|
||||
public string TypeV60calendar { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Следующее срабатывание: 16/10/23 17:00:00
|
||||
/// </summary>
|
||||
public required string Scheduled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// В каком часовом поясе: Greenwich/Universal
|
||||
/// </summary>
|
||||
public required string Timezone { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Тип прекращения, Отсутствует дата завершения: Выбран radio button forever
|
||||
/// </summary>
|
||||
public required string TerminationType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Завершение после: 0
|
||||
/// </summary>
|
||||
public string CompleteAfter { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Рабочий график
|
||||
/// </summary>
|
||||
public string V60calendar { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Время создания наряда (чч:мм:сс)
|
||||
/// </summary>
|
||||
public string BasisTime { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.BLL.Helpers;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.Contracts;
|
||||
using PARR.DAL.DomainServices.Shortcodes;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.DAL.NextRunServices;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.EsppSync.Domain;
|
||||
using System.Reflection;
|
||||
|
||||
namespace PARR.EsppSync
|
||||
@@ -52,7 +55,7 @@ namespace PARR.EsppSync
|
||||
var templateService = GetServiceInScope<ITemplateService>(scope);
|
||||
var robotConfigurationService = GetServiceInScope<IRobotConfigurationService>(scope);
|
||||
var shortcodesService = GetServiceInScope<IShortcodesService>(scope);
|
||||
|
||||
var nextRunService = GetServiceInScope<INextRunServiceV2>(scope);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -85,7 +88,7 @@ namespace PARR.EsppSync
|
||||
|
||||
if (template == null)
|
||||
{
|
||||
logger.LogWarning("Найден объект в ЕСПП с именем шаблона {TemplateName} незарегистрированный в ПАРР. Строка: {String}", esppObject.TemplateName, str);
|
||||
logger.LogWarning("Найден объект в ЕСПП с именем шаблона '{TemplateName}' незарегистрированный в ПАРР. Строка: {String}", esppObject.TemplateName, str);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -93,28 +96,7 @@ namespace PARR.EsppSync
|
||||
|
||||
await ApplyShortcodesAsync(dbObjectInEsppObject, template, shortcodesService);
|
||||
|
||||
#region old
|
||||
//// Проверяем наличие Shortcode в полях объекта из БД
|
||||
//var properties = dbObjectInEsppObject.GetType().GetProperties();
|
||||
|
||||
//foreach (PropertyInfo property in properties)
|
||||
//{
|
||||
// if (property.PropertyType == typeof(string))
|
||||
// {
|
||||
// var value = property.GetValue(dbObjectInEsppObject)?.ToString();
|
||||
// if (!string.IsNullOrEmpty(value))
|
||||
// {
|
||||
// // Передаём исходный template — он уже загружен с Include
|
||||
// var processedValue = await shortcodesService.ApplyShortcodesAsync(value, template);
|
||||
// property.SetValue(dbObjectInEsppObject, processedValue);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
#endregion
|
||||
|
||||
bool isChanged = false;
|
||||
//TODO: FIX ME Please, BRO
|
||||
//bool isChanged;
|
||||
|
||||
// если в БД isActive == false, то синхронизировать только по полям из IEsppObject
|
||||
|
||||
@@ -130,9 +112,17 @@ namespace PARR.EsppSync
|
||||
{
|
||||
logger.LogDebug("Объект активирован в ПАРР. Сравниваем все поля. {TemplateName}", esppObject.TemplateName);
|
||||
isChanged = IsChanged(esppObject, dbObjectInEsppObject, esppObject.TemplateName);
|
||||
}
|
||||
|
||||
//todo: если это сравнение расписаний, рассчитать nextRun, и сравнить все три nextRun, БД - ЕСПП - Расчитанное
|
||||
// если это сравнение расписаний, рассчитать nextRun, и сравнить все три nextRun, БД - ЕСПП - Расчитанное
|
||||
// будем считать, только если НЕТ изменений в остальных полях, если изменения есть, зачем лишний раз напрягать, потом в контроллере все пересчитается
|
||||
if (!isChanged && dbObjectInEsppObject is EsppObjectSchedule dbValues && esppObject is EsppObjectSchedule esppValues)
|
||||
{
|
||||
var isEqualNextRun = await IsEqualNextRunAsync(nextRunService, dbValues, esppValues, template.Id);
|
||||
|
||||
if (isEqualNextRun == false)
|
||||
isChanged = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (isChanged)
|
||||
{
|
||||
@@ -157,15 +147,6 @@ namespace PARR.EsppSync
|
||||
logger.LogInformation("Есть изменения в Template {TemplateName}, но предыдущий статус TaskStatusCode: {TaskStatusCode}. Не меняем статус, будем разбираться вручную.", template.Name, (TaskStatusEnum)config.TaskStatusCode);
|
||||
}
|
||||
|
||||
#region Old logic
|
||||
|
||||
//SetUpdateStatus(ref template, robotConfigurationService, esppObject.Robot);
|
||||
|
||||
//if (!await templateService.CommitAsync())
|
||||
// logger.LogError($"Не удалось изменить запись Template {template.Name}, Robot: {esppObject.Robot}");
|
||||
//else
|
||||
// logger.LogInformation($"Установлен принудительный статус {TaskStatusEnum.Updating}, Template {template.Name}, Robot: {esppObject.Robot}");
|
||||
#endregion
|
||||
}//надо ли проверять если не изменился, но был статус Updating не понятно. Доверяем роботу пока, что после окончания работ он точно сообщит
|
||||
else
|
||||
{
|
||||
@@ -191,6 +172,7 @@ namespace PARR.EsppSync
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Применяем шорткоды
|
||||
/// </summary>
|
||||
@@ -218,6 +200,13 @@ namespace PARR.EsppSync
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Установить статус - Обновить
|
||||
/// </summary>
|
||||
/// <param name="template"></param>
|
||||
/// <param name="robotConfigurationService"></param>
|
||||
/// <param name="robot"></param>
|
||||
private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot)
|
||||
{
|
||||
var robotConfig = robotConfigurationService.GetFromTemplateByRobotCode(robot, template);
|
||||
@@ -225,6 +214,13 @@ namespace PARR.EsppSync
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить сервис из scope
|
||||
/// </summary>
|
||||
/// <typeparam name="Service"></typeparam>
|
||||
/// <param name="scope"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="Exception"></exception>
|
||||
private Service GetServiceInScope<Service>(IServiceScope scope)
|
||||
{
|
||||
var service = scope.ServiceProvider.GetService<Service>();
|
||||
@@ -235,7 +231,13 @@ namespace PARR.EsppSync
|
||||
}
|
||||
|
||||
|
||||
//private bool IsChanged(EsppObject esppObj, EsppObject dbObj)
|
||||
/// <summary>
|
||||
/// Сравнение объектов
|
||||
/// </summary>
|
||||
/// <param name="esppObj"></param>
|
||||
/// <param name="dbObj"></param>
|
||||
/// <param name="templateName"></param>
|
||||
/// <returns></returns>
|
||||
private bool IsChanged(object esppObj, object dbObj, string templateName)
|
||||
{
|
||||
foreach (var prop in dbObj.GetType().GetProperties())
|
||||
@@ -278,5 +280,73 @@ namespace PARR.EsppSync
|
||||
|
||||
return str.ToLower();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Рассчитать nextRun в часовом поясе УЗ робота
|
||||
/// </summary>
|
||||
/// <param name="nextRunService"></param>
|
||||
/// <param name="templateId"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<DateTimeOffset?> CalcNextRunAsync(INextRunServiceV2 nextRunService, Guid templateId)
|
||||
{
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(templateId, isNew: false);
|
||||
|
||||
if (nextRun.HasValue)
|
||||
{
|
||||
var nextRunWithEsppAccountTz = nextRun.Value.Add(nextRunService.GetEsppAccountOffset());
|
||||
logger.LogDebug("Расчитанный nextRun для шаблона {templateId}, UTC: {nextRun}, EsppAccountTz: {nextRunWithEsppAccountTz}", templateId, nextRun, nextRunWithEsppAccountTz);
|
||||
|
||||
return nextRunWithEsppAccountTz;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogError("При расчете nextRun для templateId: {templateId} верунлся null", templateId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Сравнить NextRun из БД, ЕСПП, рассчитанный
|
||||
/// </summary>
|
||||
/// <param name="dbValues"></param>
|
||||
/// <param name="esppValues"></param>
|
||||
/// <param name="templateId"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<bool> IsEqualNextRunAsync(INextRunServiceV2 nextRunService, EsppObjectSchedule dbValues, EsppObjectSchedule esppValues, Guid templateId)
|
||||
{
|
||||
// в часовой зоне робота
|
||||
var calculatedNextRun = await CalcNextRunAsync(nextRunService, templateId);
|
||||
if (calculatedNextRun == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var scheduledCalculated = EsppScheduleHelpers.GetNextRun(calculatedNextRun.Value);
|
||||
var basisTimeCalculated = EsppScheduleHelpers.GetGenerationTime(calculatedNextRun.Value);
|
||||
|
||||
logger.LogDebug("Рассчитанные значения для шаблона '{templateName}', {templateId}, следующее срабатывание {scheduledCalculated}, время создания наряда: {basisTimeCalculated}",
|
||||
dbValues.TemplateName, templateId, scheduledCalculated, basisTimeCalculated);
|
||||
|
||||
if (Normalize(dbValues.Scheduled) != Normalize(esppValues.Scheduled) || Normalize(dbValues.Scheduled) != scheduledCalculated || Normalize(esppValues.Scheduled) != scheduledCalculated)
|
||||
{
|
||||
logger.LogInformation("Не совпадают поля ({propName}), dbValueStr: {dbValueStr}, esppValueStr: {esppValueStr}, scheduledCalculated: {scheduledCalculated}. Имя шаблона: {templateName}",
|
||||
nameof(dbValues.Scheduled), dbValues.Scheduled, esppValues.Scheduled, scheduledCalculated, dbValues.TemplateName);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Normalize(dbValues.BasisTime) != Normalize(esppValues.BasisTime) || Normalize(dbValues.BasisTime) != basisTimeCalculated || Normalize(esppValues.BasisTime) != basisTimeCalculated)
|
||||
{
|
||||
logger.LogInformation("Не совпадают поля ({propName}), dbValueStr: {dbValueStr}, esppValueStr: {esppValueStr}, basisTimeCalculated: {basisTimeCalculated}. Имя шаблона: {templateName}",
|
||||
nameof(dbValues.BasisTime), dbValues.BasisTime, esppValues.BasisTime, basisTimeCalculated, dbValues.TemplateName);
|
||||
return false;
|
||||
}
|
||||
|
||||
logger.LogDebug("Значения nextRun в БД, ЕСПП, расчитанное, все совпадают. Scheduled: {scheduled}, basisTime: {basisTime}", scheduledCalculated, basisTimeCalculated);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user