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
{
///
/// Выдает задания Агенту сервера
///
public class AgentTaskController : BaseApiController
{
private readonly IClientService clientService;
private readonly ITemplateService templateService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly ILogger logger;
public AgentTaskController(
IClientService clientService,
ITemplateService templateService,
IEsppScheduleTransformService esppScheduleTransformService,
ILogger logger
)
{
this.clientService = clientService;
this.templateService = templateService;
this.esppScheduleTransformService = esppScheduleTransformService;
this.logger = logger;
}
///
/// Список заданий агенту по ip-адресу клиента исполнителя
///
///
///
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
public async Task 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 { new ErrorModel { Message = "Client IP address is null." } }));
//var date = request.Date ?? DateTimeOffset.UtcNow;
var date = DateTimeOffset.UtcNow;
//Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
var templates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Include(t => t.ApplicationsInWork)
.ThenInclude(t => t!.EsppSchValues)
.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)
&& t.ApplicationsInWork.EsppSchValues.Any()
).ToListAsync();
if (!templates.Any())
return NoContent();
var response = new AgentTaskMinResponse
{
Scheduled = new List()
};
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;
}
if (string.IsNullOrEmpty(template.ApplicationsInWork.AgentName) && string.IsNullOrEmpty(template.ApplicationsInWork.AgentScript))
{
logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
$"ApplicationInWorkId: {template.ApplicationInWorkId}, AgentName: {template.ApplicationsInWork.AgentName}, AgentScript: {template.ApplicationsInWork.AgentScript} , ip: {ip}, date: {date}");
continue;
}
templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
{
Name = template.ApplicationsInWork!.AgentName ?? "",
Script = template.ApplicationsInWork!.AgentScript ?? "",
StartAt = item,
TemplateId = template.Id
}));
}
if (!response.Scheduled.Any())
return NoContent();
response.Scheduled = response.Scheduled.OrderBy(t => t.StartAt).ToList();
return Ok(response);
}
}
}