feat(dal,api,nextRunWorker): подключена логика NextRunServiceV2 в nextRunWorker, в api RobotTaskController

This commit is contained in:
Mikhail Trubnikov
2026-02-16 16:54:06 +10:00
parent 62dcf80aa3
commit 35f64c051c
10 changed files with 117 additions and 112 deletions

View File

@@ -31,7 +31,7 @@ namespace PARR.API.Controllers.V1
private readonly IClientService clientService;
private readonly IRobotHistoryService robotHistoryService;
private readonly IShortcodesService shortcodesService;
private readonly INextRunService nextRunService;
private readonly INextRunServiceV2 nextRunService;
private readonly IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService;
public RobotTaskController(
@@ -43,7 +43,7 @@ namespace PARR.API.Controllers.V1
IClientService clientService,
IRobotHistoryService robotHistoryService,
IShortcodesService shortcodesService,
INextRunService nextRunService,
INextRunServiceV2 nextRunService,
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
)
{
@@ -156,11 +156,6 @@ namespace PARR.API.Controllers.V1
// сортируем по NextRun, чтобы те у которых дата след срабатывания ближе к текущей, выполнились скорее
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;
//ищем задание в ожидании, если нашли, выбираем его
@@ -213,20 +208,35 @@ namespace PARR.API.Controllers.V1
}
case RobotsEnum.ScheduleOrder:
{ // если был запрос на расписание, проверяем у него 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
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.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));
}
@@ -243,54 +253,36 @@ namespace PARR.API.Controllers.V1
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
private async Task UpdateLastNextRunDate(RobotConfiguration task)
private async Task<bool> UpdateNextRunAsync(RobotConfiguration task)
{
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 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)
{
logger.LogDebug($"Для шаблона id {template.Id} обновляю nextRun, новое значение {nextRun}, старое значение {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 });
}
#region Old, до выноса lastRun, nextRun в templates
//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
return true;
}
@@ -322,33 +314,8 @@ namespace PARR.API.Controllers.V1
if (!await robotHistoryService.CreateAsync(history) || !await robotHistoryService.CommitAsync())
return false;
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;
}
}
}