feat(dal,api,nextRunWorker): подключена логика NextRunServiceV2 в nextRunWorker, в api RobotTaskController
This commit is contained in:
@@ -31,7 +31,7 @@ namespace PARR.API.Controllers.V1
|
|||||||
private readonly IClientService clientService;
|
private readonly IClientService clientService;
|
||||||
private readonly IRobotHistoryService robotHistoryService;
|
private readonly IRobotHistoryService robotHistoryService;
|
||||||
private readonly IShortcodesService shortcodesService;
|
private readonly IShortcodesService shortcodesService;
|
||||||
private readonly INextRunService nextRunService;
|
private readonly INextRunServiceV2 nextRunService;
|
||||||
private readonly IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService;
|
private readonly IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService;
|
||||||
|
|
||||||
public RobotTaskController(
|
public RobotTaskController(
|
||||||
@@ -43,7 +43,7 @@ namespace PARR.API.Controllers.V1
|
|||||||
IClientService clientService,
|
IClientService clientService,
|
||||||
IRobotHistoryService robotHistoryService,
|
IRobotHistoryService robotHistoryService,
|
||||||
IShortcodesService shortcodesService,
|
IShortcodesService shortcodesService,
|
||||||
INextRunService nextRunService,
|
INextRunServiceV2 nextRunService,
|
||||||
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
|
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -156,11 +156,6 @@ namespace PARR.API.Controllers.V1
|
|||||||
// сортируем по NextRun, чтобы те у которых дата след срабатывания ближе к текущей, выполнились скорее
|
// сортируем по NextRun, чтобы те у которых дата след срабатывания ближе к текущей, выполнились скорее
|
||||||
query = query.OrderBy(t => t.Template!.NextRun).ThenBy(t => t.Template!.IsActiveSchedule).ThenBy(t => t.Template.IsActiveTemplate);
|
query = query.OrderBy(t => t.Template!.NextRun).ThenBy(t => t.Template!.IsActiveSchedule).ThenBy(t => t.Template.IsActiveTemplate);
|
||||||
|
|
||||||
#region Так нельзя делать!!! Должно всегда сортироваться по NextRun и не важно какой тип у шаблона!!!
|
|
||||||
// Сортируем сначала по StatusTypeId, т е те что used, будут первыми, потом сортируем по NextRun, чтобы ближайшие даты выполнились скорее
|
|
||||||
//query = query.OrderBy(t => t.Template!.StatusTypeId).ThenBy(t => t.Template!.NextRun);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
RobotConfiguration? task = null;
|
RobotConfiguration? task = null;
|
||||||
|
|
||||||
//ищем задание в ожидании, если нашли, выбираем его
|
//ищем задание в ожидании, если нашли, выбираем его
|
||||||
@@ -213,20 +208,35 @@ namespace PARR.API.Controllers.V1
|
|||||||
}
|
}
|
||||||
case RobotsEnum.ScheduleOrder:
|
case RobotsEnum.ScheduleOrder:
|
||||||
{ // если был запрос на расписание, проверяем у него nextRun, lastRun, обновляем их
|
{ // если был запрос на расписание, проверяем у него nextRun, lastRun, обновляем их
|
||||||
await UpdateLastNextRunDate(task);
|
var resultUpdateNextRun = await UpdateNextRunAsync(task);
|
||||||
|
if (!resultUpdateNextRun)
|
||||||
|
{
|
||||||
|
logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}", task.TemplateId);
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при расчете NextRun" } }));
|
||||||
|
}
|
||||||
|
|
||||||
//RobotTaskScheduleResponse
|
//RobotTaskScheduleResponse
|
||||||
var robotTaskScheduleResponse = mapper.Map<RobotTaskScheduleResponse>(task);
|
var robotTaskScheduleResponse = mapper.Map<RobotTaskScheduleResponse>(task);
|
||||||
|
|
||||||
robotTaskScheduleResponse.Timezone = GetTimezoneForTemplate(task.Template!);
|
robotTaskScheduleResponse.Timezone = settingsFromDb.EsppScheduleTimezone;
|
||||||
|
|
||||||
robotTaskScheduleResponse.WorkGroup = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.WorkGroup, task.Template!);
|
robotTaskScheduleResponse.WorkGroup = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.WorkGroup, task.Template!);
|
||||||
robotTaskScheduleResponse.ResponseArea = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.ResponseArea, task.Template!);
|
robotTaskScheduleResponse.ResponseArea = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.ResponseArea, task.Template!);
|
||||||
|
|
||||||
var nextRunWithTimezone = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(task.Template!.NextRun, task.Template!.Job?.Group?.IsResponseAreaTimezone, robotTaskScheduleResponse.ResponseArea);
|
//var nextRunWithRobotTz = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(task.Template!.NextRun, task.Template!.Job?.Group?.IsResponseAreaTimezone, robotTaskScheduleResponse.ResponseArea);
|
||||||
|
//nextRun в часовой зоне УЗ Робота ЕСПП
|
||||||
|
var nextRunWithRobotTz = task.Template!.NextRun.Add(nextRunService.GetEsppAccountOffset());
|
||||||
|
|
||||||
robotTaskScheduleResponse.NextStart = EsppScheduleHelpers.GetNextRun(nextRunWithTimezone);
|
//на всякий случай еще раз проверяем, что дата не устарела и отправляем задание
|
||||||
robotTaskScheduleResponse.GenerationTime = EsppScheduleHelpers.GetGenerationTime(nextRunWithTimezone);
|
if (nextRunWithRobotTz < DateTimeOffset.UtcNow)
|
||||||
|
{
|
||||||
|
logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}, итоговое значение для робота, меньше чем сейчас {nextRunWithRobotTz}<{now}",
|
||||||
|
task.TemplateId, nextRunWithRobotTz, DateTimeOffset.UtcNow);
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при расчете NextRun" } }));
|
||||||
|
}
|
||||||
|
|
||||||
|
robotTaskScheduleResponse.NextStart = EsppScheduleHelpers.GetNextRun(nextRunWithRobotTz);
|
||||||
|
robotTaskScheduleResponse.GenerationTime = EsppScheduleHelpers.GetGenerationTime(nextRunWithRobotTz);
|
||||||
|
|
||||||
return Ok(new Response<RobotTaskScheduleResponse>(robotTaskScheduleResponse, true));
|
return Ok(new Response<RobotTaskScheduleResponse>(robotTaskScheduleResponse, true));
|
||||||
}
|
}
|
||||||
@@ -243,54 +253,36 @@ namespace PARR.API.Controllers.V1
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="task"></param>
|
/// <param name="task"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private async Task UpdateLastNextRunDate(RobotConfiguration task)
|
private async Task<bool> UpdateNextRunAsync(RobotConfiguration task)
|
||||||
{
|
{
|
||||||
var template = task.Template!;
|
var template = task.Template!;
|
||||||
|
|
||||||
#region old
|
|
||||||
// передаем LastRun, если его нет, то NextRun
|
|
||||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(task.Template!.ApplicationInWorkId, task.Template.ApplicationsInWork!.LastRun ?? task.Template.ApplicationsInWork.NextRun);
|
|
||||||
// всегда считаем по nextRun
|
|
||||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template.NextRun);
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
||||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||||
|
|
||||||
|
if (!nextRun.HasValue)
|
||||||
|
{
|
||||||
|
logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun=null, ошибка в расчетах.", template.Id);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nextRun.Value < DateTimeOffset.UtcNow)
|
||||||
|
{
|
||||||
|
logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun<Now [{nextRun}<{now}], ошибка в расчетах.", template.Id, nextRun.Value, DateTimeOffset.UtcNow);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (nextRun != template.NextRun)
|
if (nextRun != template.NextRun)
|
||||||
{
|
{
|
||||||
logger.LogDebug($"Для шаблона id {template.Id} обновляю nextRun, новое значение {nextRun}, старое значение {template.NextRun}");
|
logger.LogDebug($"Для шаблона id {template.Id} обновляю nextRun, новое значение {nextRun}, старое значение {template.NextRun}");
|
||||||
|
|
||||||
template.LastRun = template.NextRun;
|
template.LastRun = template.NextRun;
|
||||||
template.NextRun = nextRun;
|
template.NextRun = nextRun.Value;
|
||||||
|
|
||||||
await robotConfigurationService.CommitAsync(new HistoryInitiator { InitiatorComment = "При получении задания роботом, обновил NextRun", InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api });
|
await robotConfigurationService.CommitAsync(new HistoryInitiator { InitiatorComment = "При получении задания роботом, обновил NextRun", InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api });
|
||||||
}
|
}
|
||||||
|
|
||||||
#region Old, до выноса lastRun, nextRun в templates
|
return true;
|
||||||
//var appInWorks = task.Template!.ApplicationsInWork!;
|
|
||||||
|
|
||||||
//// передаем LastRun, если его нет, то NextRun
|
|
||||||
////var nextRun = await esppScheduleTransformService.GetNextDateAsync(task.Template!.ApplicationInWorkId, task.Template.ApplicationsInWork!.LastRun ?? task.Template.ApplicationsInWork.NextRun);
|
|
||||||
//// всегда считаем по nextRun
|
|
||||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(task.Template!.ApplicationInWorkId, task.Template.ApplicationsInWork!.NextRun);
|
|
||||||
|
|
||||||
//if (nextRun != appInWorks.NextRun)
|
|
||||||
//{
|
|
||||||
// logger.LogDebug($"Для appilcationInWork id {task.Template.ApplicationInWorkId}, шаблона id {task.TemplateId} обновляю nextRun, новое значение {nextRun}, старое значение {appInWorks.NextRun}");
|
|
||||||
|
|
||||||
// if (appInWorks.NextRun < DateTimeOffset.UtcNow)
|
|
||||||
// {
|
|
||||||
// logger.LogDebug($"Для appilcationInWork id {task.Template.ApplicationInWorkId}, шаблона id {task.TemplateId} обновляю lastRun, новое значение {appInWorks.NextRun}, старое значение {appInWorks.LastRun}");
|
|
||||||
// appInWorks.LastRun = appInWorks.NextRun;
|
|
||||||
// }
|
|
||||||
|
|
||||||
// appInWorks.NextRun = nextRun;
|
|
||||||
|
|
||||||
// await robotConfigurationService.CommitAsync();
|
|
||||||
//}
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -322,33 +314,8 @@ namespace PARR.API.Controllers.V1
|
|||||||
if (!await robotHistoryService.CreateAsync(history) || !await robotHistoryService.CommitAsync())
|
if (!await robotHistoryService.CreateAsync(history) || !await robotHistoryService.CommitAsync())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получить таймзону для шаблона
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="template"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
/// <exception cref="InvalidOperationException"></exception>
|
|
||||||
private string GetTimezoneForTemplate(Template template)
|
|
||||||
{
|
|
||||||
if (template.Job?.Group?.IsResponseAreaTimezone != true)
|
|
||||||
return scheduleResponseAreaTimeOffsetService.GetDefault.EsppValue;
|
|
||||||
|
|
||||||
var responseArea = template.Unit?.BaseFields?.ResponseArea;
|
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(responseArea))
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"У шаблона Id={template.Id}, Name='{template.Name}' не задана ResponseArea в Unit.BaseFields, " +
|
|
||||||
"но включена настройка 'использовать часовой пояс рабочей группы'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return scheduleResponseAreaTimeOffsetService.GetByResponseAreaOrDefault(responseArea).EsppValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -189,7 +189,7 @@ namespace PARR.DAL.Context
|
|||||||
new { Name = nameof(SettingsFromDb.TemplatePrefixName), Description = "Префикс имени шаблона в ЕСПП", Value = "%PREFIX%-ЭИТИ-ПТК-ПАРР" },
|
new { Name = nameof(SettingsFromDb.TemplatePrefixName), Description = "Префикс имени шаблона в ЕСПП", Value = "%PREFIX%-ЭИТИ-ПТК-ПАРР" },
|
||||||
new { Name = nameof(SettingsFromDb.RobotAttemptsNumber), Description = "Количество попыток выполнения задания роботом", Value = "3" },
|
new { Name = nameof(SettingsFromDb.RobotAttemptsNumber), Description = "Количество попыток выполнения задания роботом", Value = "3" },
|
||||||
new { Name = nameof(SettingsFromDb.RobotWaitTime), Description = "Время ожидания выполнения роботом задания", Value = "00:15:00" },
|
new { Name = nameof(SettingsFromDb.RobotWaitTime), Description = "Время ожидания выполнения роботом задания", Value = "00:15:00" },
|
||||||
//new { Name = nameof(SettingsFromDb.ScheduleTimezone), Description = "Расписание регламентной работы - В каком часовом поясе", Value = "MSK" },
|
new { Name = nameof(SettingsFromDb.EsppScheduleTimezone), Description = "Расписание регламентной работы - В каком часовом поясе", Value = "MSK" },
|
||||||
//new { Name = nameof(SettingsFromDb.ScheduleExcludeType), Description = "Расписание регламентной работы - Тип исключения", Value = "Выполнить ТОЛЬКО В указанном календаре" },
|
//new { Name = nameof(SettingsFromDb.ScheduleExcludeType), Description = "Расписание регламентной работы - Тип исключения", Value = "Выполнить ТОЛЬКО В указанном календаре" },
|
||||||
//new { Name = nameof(SettingsFromDb.ScheduleExcludeCalendar), Description = "Расписание регламентной работы - Календарь", Value = "8x5 (8.00-17.00)" },
|
//new { Name = nameof(SettingsFromDb.ScheduleExcludeCalendar), Description = "Расписание регламентной работы - Календарь", Value = "8x5 (8.00-17.00)" },
|
||||||
new { Name = nameof(SettingsFromDb.ScheduleRepeatRange), Description = "Расписание регламентной работы - Диапазн повторов", Value = "Отсутствует дата завершения" },
|
new { Name = nameof(SettingsFromDb.ScheduleRepeatRange), Description = "Расписание регламентной работы - Диапазн повторов", Value = "Отсутствует дата завершения" },
|
||||||
|
|||||||
@@ -77,10 +77,10 @@ namespace PARR.DAL.Contracts
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public TimeSpan RobotWaitTime { get; set; }
|
public TimeSpan RobotWaitTime { get; set; }
|
||||||
|
|
||||||
///// <summary>
|
/// <summary>
|
||||||
///// Расписание регламентной работы - В каком часовом поясе
|
/// Расписание регламентной работы, В каком часовом поясе
|
||||||
///// </summary>
|
/// </summary>
|
||||||
//public string ScheduleTimezone { get; set; } = string.Empty;
|
public string EsppScheduleTimezone { get; set; } = string.Empty;
|
||||||
|
|
||||||
///// <summary>
|
///// <summary>
|
||||||
///// Расписание регламентной работы - Тип исключения
|
///// Расписание регламентной работы - Тип исключения
|
||||||
|
|||||||
@@ -32,6 +32,11 @@ namespace PARR.DAL.NextRunServices
|
|||||||
/// <returns>NextRun или null, если null - то ошибка</returns>
|
/// <returns>NextRun или null, если null - то ошибка</returns>
|
||||||
Task<DateTimeOffset?> GetNextRunForTemplateAsync(Guid templateId, bool isNew);
|
Task<DateTimeOffset?> GetNextRunForTemplateAsync(Guid templateId, bool isNew);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить часовой пояс УЗ ЕСПП
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
TimeSpan GetEsppAccountOffset();
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -740,11 +740,7 @@ namespace PARR.DAL.NextRunServices
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
public TimeSpan GetEsppAccountOffset()
|
||||||
/// Получить часовой пояс УЗ ЕСПП
|
|
||||||
/// </summary>
|
|
||||||
/// <returns></returns>
|
|
||||||
private TimeSpan GetEsppAccountOffset()
|
|
||||||
{
|
{
|
||||||
var esppOffset = TimeSpan.FromHours(settingsFromDb.EsppRobotAccountTimeZoneHour);
|
var esppOffset = TimeSpan.FromHours(settingsFromDb.EsppRobotAccountTimeZoneHour);
|
||||||
logger.LogDebug("Оффсет УЗ ЕСПП: {esppOffset}", esppOffset);
|
logger.LogDebug("Оффсет УЗ ЕСПП: {esppOffset}", esppOffset);
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
namespace PARR.DAL.NextRunServices.Subservices
|
namespace PARR.DAL.NextRunServices.Subservices
|
||||||
{
|
{
|
||||||
//todo: public->internal
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Сервис трансформации расписания ЕСПП в дату/расписание
|
/// Сервис трансформации расписания ЕСПП в дату/расписание
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IEsppScheduleTransformService
|
internal interface IEsppScheduleTransformService
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить следующую дату по jobGroupId
|
/// Получить следующую дату по jobGroupId
|
||||||
|
|||||||
@@ -2,8 +2,7 @@
|
|||||||
|
|
||||||
namespace PARR.DAL.NextRunServices.Subservices
|
namespace PARR.DAL.NextRunServices.Subservices
|
||||||
{
|
{
|
||||||
//todo: -> internal
|
internal interface ITemplateDistributorV2
|
||||||
public interface ITemplateDistributorV2
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Распределить шаблоны
|
/// Распределить шаблоны
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ namespace PARR.EsppSync
|
|||||||
{
|
{
|
||||||
// Загружаем Template и TemplateForShortcodes в одном запросе
|
// Загружаем Template и TemplateForShortcodes в одном запросе
|
||||||
var query = templateService.Get()
|
var query = templateService.Get()
|
||||||
//.AsNoTracking() <- не надо так, а то потом не сохранится
|
//.AsNoTracking()
|
||||||
.Include(h => h.Unit)
|
.Include(h => h.Unit)
|
||||||
.ThenInclude(t => t!.UnitValues)
|
.ThenInclude(t => t!.UnitValues)
|
||||||
.ThenInclude(t => t.Value)
|
.ThenInclude(t => t.Value)
|
||||||
@@ -91,22 +91,26 @@ namespace PARR.EsppSync
|
|||||||
|
|
||||||
var dbObjectInEsppObject = converterToEsppObject.Invoke(template);
|
var dbObjectInEsppObject = converterToEsppObject.Invoke(template);
|
||||||
|
|
||||||
// Проверяем наличие Shortcode в полях объекта из БД
|
await ApplyShortcodesAsync(dbObjectInEsppObject, template, shortcodesService);
|
||||||
var properties = dbObjectInEsppObject.GetType().GetProperties();
|
|
||||||
|
|
||||||
foreach (PropertyInfo property in properties)
|
#region old
|
||||||
{
|
//// Проверяем наличие Shortcode в полях объекта из БД
|
||||||
if (property.PropertyType == typeof(string))
|
//var properties = dbObjectInEsppObject.GetType().GetProperties();
|
||||||
{
|
|
||||||
var value = property.GetValue(dbObjectInEsppObject)?.ToString();
|
//foreach (PropertyInfo property in properties)
|
||||||
if (!string.IsNullOrEmpty(value))
|
//{
|
||||||
{
|
// if (property.PropertyType == typeof(string))
|
||||||
// Передаём исходный template — он уже загружен с Include
|
// {
|
||||||
var processedValue = await shortcodesService.ApplyShortcodesAsync(value, template);
|
// var value = property.GetValue(dbObjectInEsppObject)?.ToString();
|
||||||
property.SetValue(dbObjectInEsppObject, processedValue);
|
// if (!string.IsNullOrEmpty(value))
|
||||||
}
|
// {
|
||||||
}
|
// // Передаём исходный template — он уже загружен с Include
|
||||||
}
|
// var processedValue = await shortcodesService.ApplyShortcodesAsync(value, template);
|
||||||
|
// property.SetValue(dbObjectInEsppObject, processedValue);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
||||||
|
#endregion
|
||||||
|
|
||||||
bool isChanged = false;
|
bool isChanged = false;
|
||||||
//TODO: FIX ME Please, BRO
|
//TODO: FIX ME Please, BRO
|
||||||
@@ -128,6 +132,8 @@ namespace PARR.EsppSync
|
|||||||
isChanged = IsChanged(esppObject, dbObjectInEsppObject, esppObject.TemplateName);
|
isChanged = IsChanged(esppObject, dbObjectInEsppObject, esppObject.TemplateName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//todo: если это сравнение расписаний, рассчитать nextRun, и сравнить все три nextRun, БД - ЕСПП - Расчитанное
|
||||||
|
|
||||||
if (isChanged)
|
if (isChanged)
|
||||||
{
|
{
|
||||||
logger.LogDebug("Есть изменения, требуется обновление. {TemplateName}", esppObject.TemplateName);
|
logger.LogDebug("Есть изменения, требуется обновление. {TemplateName}", esppObject.TemplateName);
|
||||||
@@ -185,6 +191,32 @@ namespace PARR.EsppSync
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Применяем шорткоды
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="dbObjectInEsppObject"></param>
|
||||||
|
/// <param name="template"></param>
|
||||||
|
/// <param name="shortcodesService"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
private async Task ApplyShortcodesAsync(EsppObject dbObjectInEsppObject, Template template, IShortcodesService shortcodesService)
|
||||||
|
{
|
||||||
|
// Проверяем наличие 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot)
|
private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -43,10 +43,10 @@ namespace PARR.NextRun
|
|||||||
//var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
|
//var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
|
||||||
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
|
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
|
||||||
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
|
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
|
||||||
var nextRunService = scope.ServiceProvider.GetService<INextRunService>();
|
var nextRunService = scope.ServiceProvider.GetService<INextRunServiceV2>();
|
||||||
|
|
||||||
if (templateService == null || nextRunService == null || jobGroupService == null)
|
if (templateService == null || nextRunService == null || jobGroupService == null)
|
||||||
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}");
|
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunServiceV2)} или {nameof(IJobGroupService)}");
|
||||||
|
|
||||||
await HandlerAsync(templateService, nextRunService, jobGroupService);
|
await HandlerAsync(templateService, nextRunService, jobGroupService);
|
||||||
}
|
}
|
||||||
@@ -58,7 +58,7 @@ namespace PARR.NextRun
|
|||||||
/// Рассчет следующей даты срабатываения
|
/// Рассчет следующей даты срабатываения
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
|
private async Task HandlerAsync(ITemplateService templateService, INextRunServiceV2 nextRunService, IJobGroupService jobGroupService)
|
||||||
{
|
{
|
||||||
logger.LogInformation("Начинаю обновлять NextRun по расписанию");
|
logger.LogInformation("Начинаю обновлять NextRun по расписанию");
|
||||||
|
|
||||||
@@ -74,7 +74,7 @@ namespace PARR.NextRun
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
|
private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunServiceV2 nextRunService, IJobGroupService jobGroupService)
|
||||||
{
|
{
|
||||||
// выбираем все шаблоны с просроченным nextRun в статусе Used
|
// выбираем все шаблоны с просроченным nextRun в статусе Used
|
||||||
|
|
||||||
@@ -94,8 +94,15 @@ namespace PARR.NextRun
|
|||||||
{
|
{
|
||||||
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||||
|
|
||||||
|
if (newNextRun.HasValue)
|
||||||
|
{
|
||||||
template.LastRun = template.NextRun;
|
template.LastRun = template.NextRun;
|
||||||
template.NextRun = newNextRun;
|
template.NextRun = newNextRun.Value;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun }))
|
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun }))
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ namespace PARR.Test.NextRun
|
|||||||
private readonly INextRunService nextRunService;
|
private readonly INextRunService nextRunService;
|
||||||
private readonly ITemplateService templateService;
|
private readonly ITemplateService templateService;
|
||||||
private readonly IShortcodesService shortcodesService;
|
private readonly IShortcodesService shortcodesService;
|
||||||
private readonly ITemplateDistributorV2 templateDistributorV2;
|
//private readonly ITemplateDistributorV2 templateDistributorV2;
|
||||||
private readonly INextRunServiceV2 nextRunServiceV2;
|
private readonly INextRunServiceV2 nextRunServiceV2;
|
||||||
|
|
||||||
public NextRunTest(
|
public NextRunTest(
|
||||||
@@ -21,7 +21,7 @@ namespace PARR.Test.NextRun
|
|||||||
INextRunService nextRunService,
|
INextRunService nextRunService,
|
||||||
ITemplateService templateService,
|
ITemplateService templateService,
|
||||||
IShortcodesService shortcodesService,
|
IShortcodesService shortcodesService,
|
||||||
ITemplateDistributorV2 templateDistributorV2,
|
//ITemplateDistributorV2 templateDistributorV2,
|
||||||
INextRunServiceV2 nextRunServiceV2
|
INextRunServiceV2 nextRunServiceV2
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
@@ -29,7 +29,7 @@ namespace PARR.Test.NextRun
|
|||||||
this.nextRunService = nextRunService;
|
this.nextRunService = nextRunService;
|
||||||
this.templateService = templateService;
|
this.templateService = templateService;
|
||||||
this.shortcodesService = shortcodesService;
|
this.shortcodesService = shortcodesService;
|
||||||
this.templateDistributorV2 = templateDistributorV2;
|
//this.templateDistributorV2 = templateDistributorV2;
|
||||||
this.nextRunServiceV2 = nextRunServiceV2;
|
this.nextRunServiceV2 = nextRunServiceV2;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ namespace PARR.Test.NextRun
|
|||||||
//var nextRunForExistTemplateDistib = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("05769f8d-9630-4683-b07a-070d69e1dc12"), false);
|
//var nextRunForExistTemplateDistib = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("05769f8d-9630-4683-b07a-070d69e1dc12"), false);
|
||||||
|
|
||||||
// существующий шаблон - еспп
|
// существующий шаблон - еспп
|
||||||
var nextRunForExistTemplateEspp = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("1329dfca-5e09-4b19-a2e6-560a4896080c"), false);
|
//var nextRunForExistTemplateEspp = await nextRunServiceV2.GetNextRunForTemplateAsync(Guid.Parse("1329dfca-5e09-4b19-a2e6-560a4896080c"), false);
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user