Files
parr_api/PARR.API/Controllers/V1/AgentTaskController.cs
2023-10-17 16:59:53 +10:00

112 lines
5.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.DAL.Contracts;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;
namespace PARR.API.Controllers.V1
{
/// <summary>
/// Выдает задания Агенту сервера
/// </summary>
public class AgentTaskController : BaseApiController
{
private readonly IMapper mapper;
private readonly IClientService clientService;
private readonly ITemplateService templateService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly ILogger<AgentTaskController> logger;
public AgentTaskController(
IMapper mapper,
IClientService clientService,
ITemplateService templateService,
IEsppScheduleTransformService esppScheduleTransformService,
ILogger<AgentTaskController> logger
)
{
this.mapper = mapper;
this.clientService = clientService;
this.templateService = templateService;
this.esppScheduleTransformService = esppScheduleTransformService;
this.logger = logger;
}
/// <summary>
/// Список заданий агенту по ip-адресу клиента исполнителя
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
public async Task<IActionResult> GetByClientIp([FromQuery] AgentTaskGetByIpQuery request)
{
//ПАРР-ДВС-ПТК__ВРТ-DVGD-SDMI-WEB-01-ДВС__ПРОЧЕЕ(РАБОТЫ)
//10.99.253.65
//2023-10-16
var ip = request.Ip ?? clientService.GetClientIp()?.ToString();
if (string.IsNullOrEmpty(ip))
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Client IP address is null." } }));
var date = request.Date ?? DateTimeOffset.UtcNow;
//Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`.
// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
var templates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Include(t => t.ApplicationsInWork)
.Include(t => t.Host)
.Where(t => t.Host!.IP == ip
&& t.ApplicationsInWork!.IsAgent == true
&& t.IsActiveTemplate == true
&& t.IsActiveSchedule == true
&& t.ApplicationsInWork!.NextRun.DateTime.Date == date.Date.Date
&& t.RobotConfigurations.All(c => c.TaskStatusCode == (int)TaskStatusEnum.Ok)
).ToListAsync();
if (!templates.Any())
return NoContent();
// запросить расписание на день для каждого шаблона и сформировать из него список
//TODO: идти в appInWorks и отуда формировать список заданий. Так же, как делать если время у заданий совпадает?
var response = new AgentTaskMinResponse
{
Scheduled = new List<AgentTaskMinScheduleResponse>()
};
foreach (var template in templates)
{
var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
if (!templateSchedule.Any())
{
logger.LogWarning($"Запросили рапсисание для агента по LastRun и вернулся пустой список! Такого не должно быть! " +
$"ApplicationInWorkId: {template.ApplicationInWorkId}, latRun: {template.ApplicationsInWork!.LastRun}, NextRun: {template.ApplicationsInWork!.NextRun}, ip: {ip}, date: {date}");
continue;
}
// TODO: проверку что в бд есть поля AgentName, AgentScript
templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse { Name = template.ApplicationsInWork!.AgentName, Script = template.ApplicationsInWork!.AgentScript, StartAt = item }));
}
// отсортировать потом по дате
// минимальный респонс
return Ok(response);
}
}
}