2023-12-04 10:16:00 +10:00
using Microsoft.AspNetCore.Authorization ;
using Microsoft.AspNetCore.Mvc ;
2023-10-17 16:59:53 +10:00
using PARR.API.Contracts.V1 ;
using PARR.API.Contracts.V1.Requests.Queries ;
using PARR.API.Controllers.V1.Base ;
using PARR.API.Services.Interfaces ;
2023-12-04 10:16:00 +10:00
using PARR.Constants ;
2023-10-17 16:59:53 +10:00
using PARR.DAL.Services.Interfaces ;
2025-06-25 14:17:34 +10:00
using PARR.DAL.Services.Interfaces.Unit ;
2023-10-17 16:59:53 +10:00
namespace PARR.API.Controllers.V1
{
/// <summary>
/// Выдает задания Агенту сервера
/// </summary>
2023-12-04 10:16:00 +10:00
[Authorize(Roles = ParrRoles.Agent.RoleOrAdmin)]
2023-10-17 16:59:53 +10:00
public class AgentTaskController : BaseApiController
{
private readonly IClientService clientService ;
private readonly ITemplateService templateService ;
2025-06-25 14:17:34 +10:00
private readonly IUnitService unitService ;
2026-01-22 11:46:05 +10:00
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
2023-10-17 16:59:53 +10:00
private readonly ILogger < AgentTaskController > logger ;
public AgentTaskController (
IClientService clientService ,
ITemplateService templateService ,
2025-06-25 14:17:34 +10:00
IUnitService unitService ,
2026-01-22 11:46:05 +10:00
//IEsppScheduleTransformService esppScheduleTransformService,
2023-10-17 16:59:53 +10:00
ILogger < AgentTaskController > logger
)
{
this . clientService = clientService ;
this . templateService = templateService ;
2025-06-25 14:17:34 +10:00
this . unitService = unitService ;
2026-01-22 11:46:05 +10:00
//this.esppScheduleTransformService = esppScheduleTransformService;
2023-10-17 16:59:53 +10:00
this . logger = logger ;
}
/// <summary>
/// Список заданий агенту по ip-адресу клиента исполнителя
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
public async Task < IActionResult > GetByClientIp ( [ FromQuery ] AgentTaskGetByIpQuery request )
{
2026-01-22 11:46:05 +10:00
return Ok ( "Метод не реализован" ) ;
////ПАРР-ДВС-ПТ К __В Р Т -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;
//var date = DateTimeOffset.UtcNow;
////Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
//// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
//var units = await unitService.GetWithIncludes().AsNoTracking().Where(t => t.UnitValues.Any(v => v.Field!.AihitName == "IP_А ДР Е С " && v.Value!.Value == ip)).ToListAsync();
//var templates = await templateService.Get()
// .Include(t => t.RobotConfigurations)
// .Include(t => t.Job)
// .ThenInclude(t=>t!.Group)
// .ThenInclude(t => t!.EsppSchValues)
// .Include(t => t.Unit)
// .Where(t => units.Any(u=>u.Id == t.UnitId)
// //&& t.ApplicationsInWork!.IsAgent == true//TODO Migration to job
// && t.IsActiveTemplate == true
// && t.IsActiveSchedule == true
// //&& t.ApplicationsInWork!.NextRun.DateTime.Date == date.Date.Date
// && t.NextRun.DateTime.Date == date.Date.Date
// && t.RobotConfigurations.All(c => c.TaskStatusCode == (int)TaskStatusEnum.Ok)
// && t.Job!.Group!.EsppSchValues.Any()//.ApplicationsInWork.EsppSchValues.Any()
// ).ToListAsync();
//if (!templates.Any())
// return NoContent();
//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);
// var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
// if (!templateSchedule.Any())
// {
// logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
// $"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
// continue;
// }
// if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
// {
// logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
// $"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
// continue;
// }
// templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
// {
// Name = template.Job.Group.AgentName ?? "",
// Script = template.Job.Group.AgentScript ?? "",
// StartAt = item,
// TemplateId = template.Id
// }));
//}
//if (!response.Scheduled.Any())
// return NoContent();
//response.Scheduled = response.Scheduled.OrderBy(t => t.StartAt).ToList();
//logger.LogInformation($"Агент с IP-адресом {ip} получил задания: [{string.Join(';', response.Scheduled.Select(s => $"StartAt:{s.StartAt}, Name:{s.Name}, TemplateId:{s.TemplateId}"))}]");
//return Ok(response);
2023-10-17 16:59:53 +10:00
}
}
}