2023-10-05 16:56:02 +10:00
using AutoMapper ;
2023-12-04 10:16:00 +10:00
using Microsoft.AspNetCore.Authorization ;
2023-10-05 16:56:02 +10:00
using Microsoft.AspNetCore.Mvc ;
using Microsoft.EntityFrameworkCore ;
using PARR.API.Contracts.V1 ;
using PARR.API.Contracts.V1.Responses ;
using PARR.API.Contracts.V1.Responses.Base ;
using PARR.API.Controllers.V1.Base ;
2023-11-22 12:04:33 +10:00
using PARR.Constants ;
2023-10-05 16:56:02 +10:00
using PARR.DAL.Contracts ;
using PARR.DAL.Models ;
using PARR.DAL.Services.Interfaces ;
2023-10-17 10:53:02 +10:00
using PARR.DAL.TransformServices ;
2023-10-05 16:56:02 +10:00
namespace PARR.API.Controllers.V1
{
2023-12-04 10:16:00 +10:00
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
2023-10-05 16:56:02 +10:00
public class RobotTaskController : BaseApiController
{
private readonly IMapper mapper ;
private readonly SettingsFromDb settingsFromDb ;
private readonly IRobotConfigurationService robotConfigurationService ;
2023-10-17 10:53:02 +10:00
private readonly IEsppScheduleTransformService esppScheduleTransformService ;
2024-02-27 16:01:08 +10:00
private readonly ILogger < RobotTaskController > logger ;
2023-10-05 16:56:02 +10:00
public RobotTaskController (
IMapper mapper ,
SettingsFromDb settingsFromDb ,
2023-10-17 10:53:02 +10:00
IRobotConfigurationService robotConfigurationService ,
2024-02-27 16:01:08 +10:00
IEsppScheduleTransformService esppScheduleTransformService ,
ILogger < RobotTaskController > logger
2023-10-05 16:56:02 +10:00
)
{
this . mapper = mapper ;
this . settingsFromDb = settingsFromDb ;
this . robotConfigurationService = robotConfigurationService ;
2023-10-17 10:53:02 +10:00
this . esppScheduleTransformService = esppScheduleTransformService ;
2024-02-27 16:01:08 +10:00
this . logger = logger ;
2023-10-05 16:56:02 +10:00
}
/// <summary>
/// Получить задание для робота по коду робота и по статусу задания
/// </summary>
/// <param name="robotCode"></param>
/// <param name="taskStatusCode"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.RobotTask.GetByRobotAndStatusTask)]
public async Task < IActionResult > GetByRobotAndStatusTask ( [ FromRoute ] RobotsEnum robotCode , [ FromRoute ] TaskStatusEnum taskStatusCode )
{
//Ищем все задания с превышенным кол-вом попыток и с просроченным временем и ставим им статус ошибки
await robotConfigurationService . FindUnfulfilledTaskAndSetRobotErrorStatusAsync ( settingsFromDb . RobotAttemptsNumber , settingsFromDb . RobotWaitTime ) ;
2023-10-11 15:28:37 +10:00
2023-10-05 16:56:02 +10:00
var query = robotConfigurationService . Get ( )
2023-10-11 11:10:35 +10:00
. Where ( t = > t . RobotCode = = ( int ) robotCode & & t . TaskStatusCode = = ( int ) taskStatusCode ) ;
2023-10-05 16:56:02 +10:00
2024-03-27 11:44:15 +10:00
//var query = robotConfigurationService.GetAsync();
2023-10-11 15:28:37 +10:00
2023-10-05 16:56:02 +10:00
switch ( robotCode )
{
case RobotsEnum . TemplateOrder :
2023-10-11 15:28:37 +10:00
// шаблоны
2023-10-05 16:56:02 +10:00
query = query . Include ( t = > t . Template )
. ThenInclude ( t = > t ! . Host ) . ThenInclude ( t = > t ! . ResponseArea )
2024-06-18 15:10:12 +10:00
. ThenInclude ( t = > t ! . Hosts ) . ThenInclude ( t = > t . WorkGroup ) . ThenInclude ( t = > t ! . ResponseArea )
2023-10-05 16:56:02 +10:00
. Include ( t = > t . Template )
. ThenInclude ( a = > a ! . ApplicationsInWork )
. ThenInclude ( w = > w ! . Work )
. ThenInclude ( t = > t ! . Tnk )
. ThenInclude ( s = > s ! . Subprocess )
2024-06-04 12:03:15 +10:00
. ThenInclude ( p = > p ! . Process ) ;
2024-06-18 15:10:12 +10:00
//.AsSplitQuery();
2023-10-05 16:56:02 +10:00
break ;
case RobotsEnum . ScheduleOrder :
2023-10-11 15:28:37 +10:00
//расписание
2023-10-11 11:10:35 +10:00
// тут не делаем AsSplitQuery, не может подтянуть все таблицы
2023-10-10 16:58:05 +10:00
query = query . Include ( t = > t . Template )
2023-10-11 11:10:35 +10:00
. ThenInclude ( t = > t ! . Host ) . ThenInclude ( t = > t ! . ResponseArea )
2024-06-04 12:30:44 +10:00
. ThenInclude ( t = > t ! . Hosts ) . ThenInclude ( t = > t . WorkGroup )
2023-10-11 11:10:35 +10:00
. Include ( t = > t . Template )
. ThenInclude ( t = > t ! . ApplicationsInWork )
. ThenInclude ( t = > t ! . EsppSchValues )
. ThenInclude ( t = > t ! . EsppSchTypeConfig )
2023-10-11 15:28:37 +10:00
. ThenInclude ( t = > t ! . EsppSchTypeSchedule ) ;
//выбираем только записи с созданными шаблонами (у которых статус 30), а только потом у них ищем расписания
// сначала находим шаблоны с о статусом 30
var createdTemplates = robotConfigurationService . Get ( )
. Where ( t = > t . RobotCode = = ( int ) RobotsEnum . TemplateOrder & & t . TaskStatusCode = = ( int ) TaskStatusEnum . Ok )
. Select ( t = > t . TemplateId ) ;
//находим задания с расписанием по списку шаблонов createdTemplates
query = query . Where ( t = > t . RobotCode = = ( int ) RobotsEnum . ScheduleOrder & & createdTemplates . Contains ( t . TemplateId ) ) ;
2023-10-05 16:56:02 +10:00
break ;
default :
break ;
}
RobotConfiguration ? task = null ;
2023-10-11 15:28:37 +10:00
//ищем задание в ожидании, если нашли, выбираем е г о
2023-10-05 16:56:02 +10:00
task = await query . FirstOrDefaultAsync ( t = > t . RobotStatusCode = = ( int ) RobotStatusEnum . Wait ) ;
if ( task = = null )
{
//ищем задания в работе, которые можно перезапустить
2023-10-09 16:11:27 +10:00
//Поиск по `RobotStatusCode` = 22.
2023-10-05 16:56:02 +10:00
//Далее проверяется `LastStatusUpdated`, что время последнего смены статуса не превышает допустимого(берется из настроек, поле `RobotWaitTime`)
//и что текущая попытка не больше разрешенной(берется из настроек, поле `RobotAttemptsNumber`) - если это так, берется эта запись.
var endDate = DateTimeOffset . UtcNow . Add ( - settingsFromDb . RobotWaitTime ) ;
2023-10-11 11:10:35 +10:00
task = await query
. FirstOrDefaultAsync ( t = >
2023-10-05 16:56:02 +10:00
t . RobotStatusCode = = ( int ) RobotStatusEnum . InProgress
& & t . AttemptsNumber < settingsFromDb . RobotAttemptsNumber
2023-10-06 11:38:33 +10:00
& & t . LastRobotStatusUpdated < endDate
2023-10-05 16:56:02 +10:00
) ;
}
if ( task = = null )
return NotFound ( ) ;
switch ( robotCode )
{
case RobotsEnum . TemplateOrder :
//RobotTaskTemplateResponse
return Ok ( new Response < RobotTaskTemplateResponse > ( mapper . Map < RobotTaskTemplateResponse > ( task ) , true ) ) ;
case RobotsEnum . ScheduleOrder :
2023-10-17 10:53:02 +10:00
// если был запрос на расписание, проверяем у него nextRun, lastRun, обновляем их
await UpdateLastNextRunDate ( task ) ;
2023-10-05 16:56:02 +10:00
//RobotTaskScheduleResponse
2023-11-27 16:42:15 +10:00
var response = mapper . Map < RobotTaskScheduleResponse > ( task ) ;
return Ok ( new Response < RobotTaskScheduleResponse > ( response , true ) ) ;
2023-10-05 16:56:02 +10:00
default :
break ;
}
return BadRequest ( ) ;
}
2023-10-17 10:53:02 +10:00
private async Task UpdateLastNextRunDate ( RobotConfiguration task )
{
var appInWorks = task . Template ! . ApplicationsInWork ! ;
// передаем LastRun, если е г о нет, то NextRun
2024-02-28 08:32:57 +10:00
//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 ) ;
2023-10-17 10:53:02 +10:00
2024-02-27 16:01:08 +10:00
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 ;
}
2024-06-18 15:10:12 +10:00
2024-02-27 16:01:08 +10:00
appInWorks . NextRun = nextRun ;
await robotConfigurationService . CommitAsync ( ) ;
}
2024-02-27 08:51:40 +10:00
//if (appInWorks.LastRun != null) // if - ерунда какая-то. ошибка видимо.
2024-02-27 16:01:08 +10:00
//if (nextRun > DateTimeOffset.UtcNow)
// appInWorks.LastRun = appInWorks.NextRun;
2023-10-17 16:59:53 +10:00
2024-02-27 16:01:08 +10:00
//appInWorks.NextRun = nextRun;
2023-10-17 10:53:02 +10:00
2024-02-27 16:01:08 +10:00
//await robotConfigurationService.CommitAsync();
2023-10-17 10:53:02 +10:00
}
2023-10-05 16:56:02 +10:00
}
}