feat(api): JobGroupController добавлена выдача расписания и количество связанных Job

This commit is contained in:
Mikhail Kuznetsov
2025-09-04 14:51:51 +10:00
parent 0793c169f9
commit c9dcdedeca
9 changed files with 214 additions and 79 deletions

View File

@@ -37,7 +37,7 @@
//public required ScheduleRequest Schedule { get; set; } //public required ScheduleRequest Schedule { get; set; }
public List<EsppSchValueRequest> Schedule { get; set; } = new List<EsppSchValueRequest>(); //public List<EsppSchValueRequest> Schedule { get; set; } = new List<EsppSchValueRequest>();
public List<Guid> WorkGroups { get; set; } = new List<Guid>(); public List<Guid> WorkGroups { get; set; } = new List<Guid>();
} }
@@ -51,10 +51,10 @@
//} //}
public class EsppSchValueRequest //public class EsppSchValueRequest
{ //{
public Guid TypeValueId { get; set; } // public Guid TypeValueId { get; set; }
public Guid TypeConfigId { get; set; } // public Guid TypeConfigId { get; set; }
} //}
} }

View File

@@ -25,5 +25,14 @@
public int? AgentTimeOutSec { get; set; } public int? AgentTimeOutSec { get; set; }
public string? AgentScript { get; set; } public string? AgentScript { get; set; }
public List<EsppSchValueRequest> Schedule { get; set; } = new List<EsppSchValueRequest>();
}
public class EsppSchValueRequest
{
public Guid TypeValueId { get; set; }
public Guid TypeConfigId { get; set; }
} }
} }

View File

@@ -8,10 +8,5 @@ namespace PARR.API.Contracts.V1.Requests.Queries
/// Поиск по имени /// Поиск по имени
/// </summary> /// </summary>
public string? Name { get; set; } public string? Name { get; set; }
/// <summary>
/// Поиск по короткому описанию
/// </summary>
public string? ShortDescription { get; set; }
} }
} }

View File

@@ -20,19 +20,31 @@ namespace PARR.API.Contracts.V1.Responses
public DateTimeOffset ReferenceDate { get; set; } public DateTimeOffset ReferenceDate { get; set; }
public bool IsAutoDistributionEnabled { get; set; } // public bool IsAutoDistributionEnabled { get; set; }
public bool IsAgent { get; set; } // public bool IsAgent { get; set; }
public string? AgentName { get; set; } // public string? AgentName { get; set; }
public int? AgentTimeOutSec { get; set; } // public int? AgentTimeOutSec { get; set; }
public string? AgentScript { get; set; } // public string? AgentScript { get; set; }
} }
public class JobGroupResponse : JobGroupBaseResponse public class JobGroupResponse : JobGroupBaseResponse
{ {
public List<JobResponse>? Jobs { get; set; } //public List<JobResponse>? Jobs { get; set; }
public int JobsCount { get; set; }
public JobGroupScheduleResponse? Schedule { get; set; }
}
public class JobGroupScheduleResponse
{
public string Timezone { get; set; } = string.Empty;
public EsppScheduleTypeScheduleResponse? TypeSchedule { get; set; }
public List<EsppScheduleValResponse>? Values { get; set; }
} }
} }

View File

@@ -1,26 +1,14 @@
using AutoMapper; using AutoMapper;
using FluentValidation; using FluentValidation;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests; using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses; using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base; using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces; using PARR.API.Services.Interfaces;
using PARR.API.Settings; using PARR.API.Settings;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces; using PARR.BLL.Services.Interfaces;
using PARR.Constants; using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainModels;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces; using PARR.DAL.Services.Interfaces;
using System.Text.Json;
using static PARR.API.Contracts.V1.ApiRoutes;
namespace PARR.API.Controllers.V1 namespace PARR.API.Controllers.V1
{ {

View File

@@ -1,6 +1,5 @@
using AutoMapper; using AutoMapper;
using FluentValidation; using FluentValidation;
using InfluxDB.Client.Api.Domain;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -14,9 +13,9 @@ using PARR.API.Extensions;
using PARR.API.Services.Interfaces; using PARR.API.Services.Interfaces;
using PARR.Constants; using PARR.Constants;
using PARR.DAL.DomainModels; using PARR.DAL.DomainModels;
using PARR.DAL.Models;
using PARR.DAL.Models.Job; using PARR.DAL.Models.Job;
using PARR.DAL.Services.Interfaces.Job; using PARR.DAL.Services.Interfaces.Job;
using System.ComponentModel.DataAnnotations;
namespace PARR.API.Controllers.V1 namespace PARR.API.Controllers.V1
{ {
@@ -64,26 +63,23 @@ namespace PARR.API.Controllers.V1
if (!string.IsNullOrEmpty(filter.Name)) if (!string.IsNullOrEmpty(filter.Name))
query = query.Where(t => t.GroupName.ToLower().Contains(filter.Name.ToLower())); query = query.Where(t => t.GroupName.ToLower().Contains(filter.Name.ToLower()));
if (!string.IsNullOrEmpty(filter.ShortDescription))
query = query.Where(t => t.ShortDescription.ToLower().Contains(filter.ShortDescription.ToLower()));
if (filter.IsFull) if (filter.IsFull)
query = query.Include(t => t.Jobs).ThenInclude(t => t.Tnk); query = query.Include(t => t.Jobs).ThenInclude(t => t.Tnk);
var jobs = await groupService.GetPage(query, paginationFilter).ToListAsync(); var jobGroups = await groupService.GetPage(query, paginationFilter).ToListAsync();
if (!jobs.Any()) if (!jobGroups.Any())
return NoContent(); return NoContent();
if (filter.IsFull == true) if (filter.IsFull == true)
{ {
var responseFull = mapper.Map<List<JobGroupResponse>>(jobs); var responseFull = mapper.Map<List<JobGroupResponse>>(jobGroups);
var paginationResponseFull = new PagedResponse<JobGroupResponse>(responseFull, true).GetPaginatedProps(paginationFilter, query); var paginationResponseFull = new PagedResponse<JobGroupResponse>(responseFull, true).GetPaginatedProps(paginationFilter, query);
return Ok(paginationResponseFull); return Ok(paginationResponseFull);
} }
var response = mapper.Map<List<JobGroupBaseResponse>>(jobs); var response = mapper.Map<List<JobGroupBaseResponse>>(jobGroups);
var paginationResponse = new PagedResponse<JobGroupBaseResponse>(response, true).GetPaginatedProps(paginationFilter, query); var paginationResponse = new PagedResponse<JobGroupBaseResponse>(response, true).GetPaginatedProps(paginationFilter, query);
@@ -101,6 +97,7 @@ namespace PARR.API.Controllers.V1
{ {
var jobGroup = await groupService.Get() var jobGroup = await groupService.Get()
.Include(t => t.Jobs).ThenInclude(t => t.Tnk) .Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.EsppSchValues)
.FirstOrDefaultAsync(t => t.Id == id); .FirstOrDefaultAsync(t => t.Id == id);
if (jobGroup == null) if (jobGroup == null)
@@ -142,6 +139,16 @@ namespace PARR.API.Controllers.V1
AgentScript = request.AgentScript AgentScript = request.AgentScript
}; };
//Добавляем настройки планировщика
request.Schedule.ForEach(item =>
{
jobGroup.EsppSchValues.Add(new EsppSchValue
{
JobGroupId = jobGroup.Id,
TypeConfigId = item.TypeConfigId,
TypeValueId = item.TypeValueId
});
});
if (!await groupService.CreateAsync(jobGroup) || !await groupService.CommitAsync()) if (!await groupService.CreateAsync(jobGroup) || !await groupService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создании группы заданий на выполнение работ" } })); return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создании группы заданий на выполнение работ" } }));
@@ -149,7 +156,7 @@ namespace PARR.API.Controllers.V1
logger.LogInformation($"Пользователь {User.Identity?.Name} добавил группу заданий на выполнение работ: {jobGroup.Id}, {jobGroup.GroupName}, {jobGroup.ShortDescription}"); logger.LogInformation($"Пользователь {User.Identity?.Name} добавил группу заданий на выполнение работ: {jobGroup.Id}, {jobGroup.GroupName}, {jobGroup.ShortDescription}");
var createdJobGroup = await groupService.Get().Include(t=>t.Jobs).ThenInclude(t => t.Tnk) var createdJobGroup = await groupService.Get().Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.FirstAsync(t => t.Id == jobGroup.Id); .FirstAsync(t => t.Id == jobGroup.Id);
var locationUri = uriService.GetUri(ApiRoutes.JobGroup.Get, ApiRoutes.JobGroup.getParam, createdJobGroup.Id); var locationUri = uriService.GetUri(ApiRoutes.JobGroup.Get, ApiRoutes.JobGroup.getParam, createdJobGroup.Id);
@@ -175,13 +182,17 @@ namespace PARR.API.Controllers.V1
return BadRequest(new Response(resultValidate.Errors)); return BadRequest(new Response(resultValidate.Errors));
var orig = await groupService.Get() var orig = await groupService.Get()
.Include(t=>t.Jobs) .Include(t => t.Jobs)
.ThenInclude(t => t.Tnk) .ThenInclude(t => t.Tnk)
.Include(t => t.EsppSchValues)
.FirstOrDefaultAsync(t => t.Id == id); .FirstOrDefaultAsync(t => t.Id == id);
if (orig == null) if (orig == null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении группы заданий на выполнение работ. Не найдена группа с Id: {id}" } })); return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении группы заданий на выполнение работ. Не найдена группа с Id: {id}" } }));
// //Расписание было изменено, ниже добавим задание в очередь на обновление расписаний у связанных шаблонов
var isScheduleChanged = IsScheduleChanged(orig, request);
orig.GroupName = request.Name.Trim(); orig.GroupName = request.Name.Trim();
orig.IsUmbrella = request.IsUmbrella; orig.IsUmbrella = request.IsUmbrella;
orig.ShortDescription = request.ShortDescription.Trim(); orig.ShortDescription = request.ShortDescription.Trim();
@@ -194,6 +205,19 @@ namespace PARR.API.Controllers.V1
orig.AgentName = request.AgentName; orig.AgentName = request.AgentName;
orig.AgentTimeOutSec = request.AgentTimeOutSec; orig.AgentTimeOutSec = request.AgentTimeOutSec;
orig.AgentScript = request.AgentScript; orig.AgentScript = request.AgentScript;
orig.DateModified = DateTimeOffset.UtcNow;
//обновляем планировщик
orig.EsppSchValues.Clear();
request.Schedule.ForEach(item =>
{
orig.EsppSchValues.Add(new EsppSchValue
{
JobGroupId = orig.Id,
TypeConfigId = item.TypeConfigId,
TypeValueId = item.TypeValueId
});
});
if (!await groupService.CommitAsync()) if (!await groupService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ." } })); return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ." } }));
@@ -203,15 +227,35 @@ namespace PARR.API.Controllers.V1
$" {orig.Solution}, {orig.TemplateDuration}, {orig.ReferenceDate}, {orig.IsAutoDistributionEnabled}" + $" {orig.Solution}, {orig.TemplateDuration}, {orig.ReferenceDate}, {orig.IsAutoDistributionEnabled}" +
$", {orig.IsAgent}, {orig.AgentName}, {orig.AgentTimeOutSec}, {orig.AgentScript}"); $", {orig.IsAgent}, {orig.AgentName}, {orig.AgentTimeOutSec}, {orig.AgentScript}");
//TODO: Восстановить после перехода на JobGroup
//if (isScheduleChanged)
//{
// //расписание было обновлено, отправим задание в очередь на перерасчет NextRun
// var requestToMq = new TemplateDistributorMq
// {
// ApplicationInWorkId = id
// };
// var msg = JsonSerializer.Serialize(requestToMq);
// logger.LogDebug($"Расписание в РР applicationInWorkId: {id} было изменено. Отправляем задание в очередь на перерасчет NextRun");
// var sendResult = mqService.Send(mqSettings.TemplateDistributor, new[] { msg });
// if (sendResult.IsSuccess)
// logger.LogInformation($"Задание на перерасчет NextRun успешно отправлено в очередь MQ {mqSettings.TemplateDistributor.QueueName}");
// else
// logger.LogError($"Ошибка при отправке задания на перерасчет NextRun в очередь MQ {mqSettings.TemplateDistributor.QueueName}");
//}
var updatedJobGroup = await groupService.Get() var updatedJobGroup = await groupService.Get()
.Include(t => t.Jobs) .Include(t => t.Jobs)
.ThenInclude(t => t.Tnk) .ThenInclude(t => t.Tnk)
.FirstAsync(t => t.Id == orig.Id); .FirstAsync(t => t.Id == orig.Id);
var response = mapper.Map<JobResponse>(updatedJobGroup); var response = mapper.Map<JobGroupResponse>(updatedJobGroup);
return Ok(new Response<JobResponse>(response, true)); return Ok(new Response<JobGroupResponse>(response, true));
} }
@@ -220,31 +264,64 @@ namespace PARR.API.Controllers.V1
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="id"></param>
/// <returns></returns> /// <returns></returns>
[HttpDelete(ApiRoutes.JobGroup.Delete)] //[HttpDelete(ApiRoutes.JobGroup.Delete)]
public async Task<IActionResult> Delete([FromRoute] Guid id) //public async Task<IActionResult> Delete([FromRoute] Guid id)
//{
// var jobGroup = await groupService.Get()
// .Include(t => t.Jobs)
// .ThenInclude(t => t.Tnk)
// .FirstOrDefaultAsync(t => t.Id == id);
// if (jobGroup == null)
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
// Message = $"Ошибка при удалении группы заданий на выполнение работ. Не найдена группа заданий на выполнение работ Id: {id}"
// } }));
// if (!groupService.Delete(jobGroup) || !await groupService.CommitAsync())
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
// Message = $"Ошибка при удалении группы заданий на выполнение работ"
// } }));
// logger.LogInformation($"Пользователь {User.Identity?.Name} удалил задание на выполнение работ: {jobGroup.Id},{jobGroup.GroupName}," +
// $" {jobGroup.IsUmbrella}, {jobGroup.ShortDescription}, {jobGroup.FullDescription}," +
// $" {jobGroup.Solution}, {jobGroup.TemplateDuration}, {jobGroup.ReferenceDate}" +
// $"{jobGroup.IsAutoDistributionEnabled}, {jobGroup.IsAgent}, {jobGroup.AgentName}" +
// $"{jobGroup.AgentTimeOutSec}, {jobGroup.AgentScript}");
// return NoContent();
//}
/// <summary>
/// Проверка, были ли изменения в расписании
/// </summary>
/// <param name="orig"></param>
/// <param name="request"></param>
/// <returns></returns>
private bool IsScheduleChanged(JobGroup orig, JobGroupRequest request)
{ {
var jobGroup = await groupService.Get() var isScheduleChanged = false;
.Include(t => t.Jobs)
.ThenInclude(t => t.Tnk)
.FirstOrDefaultAsync(t => t.Id == id);
if (jobGroup == null) if (orig.ReferenceDate != request.ReferenceDate)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { isScheduleChanged = true;
Message = $"Ошибка при удалении группы заданий на выполнение работ. Не найдена группа заданий на выполнение работ Id: {id}"
} }));
if (!groupService.Delete(jobGroup) || !await groupService.CommitAsync()) if (request.Schedule.Count() != orig.EsppSchValues.Count())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { isScheduleChanged = true;
Message = $"Ошибка при удалении группы заданий на выполнение работ"
} }));
logger.LogInformation($"Пользователь {User.Identity?.Name} удалил задание на выполнение работ: {jobGroup.Id},{jobGroup.GroupName}," + if (request.IsAutoDistributionEnabled != orig.IsAutoDistributionEnabled)
$" {jobGroup.IsUmbrella}, {jobGroup.ShortDescription}, {jobGroup.FullDescription}," + isScheduleChanged = true;
$" {jobGroup.Solution}, {jobGroup.TemplateDuration}, {jobGroup.ReferenceDate}" +
$"{jobGroup.IsAutoDistributionEnabled}, {jobGroup.IsAgent}, {jobGroup.AgentName}" +
$"{jobGroup.AgentTimeOutSec}, {jobGroup.AgentScript}");
return NoContent(); request.Schedule.ForEach(requestSchedule =>
{
var schExist = orig.EsppSchValues.FirstOrDefault(t => t.JobGroupId == orig.Id
&& t.TypeValueId == requestSchedule.TypeValueId
&& t.TypeConfigId == requestSchedule.TypeConfigId);
if (schExist == null)
isScheduleChanged = true;
});
return isScheduleChanged;
} }
} }
} }

View File

@@ -308,11 +308,15 @@ namespace PARR.API.MappingProfiles
#region JobGroup #region JobGroup
CreateMap<JobGroup, JobGroupBaseResponse>() CreateMap<JobGroup, JobGroupBaseResponse>()
.Include<JobGroup, JobGroupResponse>() .Include<JobGroup, JobGroupResponse>();
.ForMember(d => d.Name, o => o.MapFrom(s => s.GroupName));
CreateMap<JobGroup, JobGroupBaseResponse>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.GroupName));
CreateMap<JobGroup, JobGroupResponse>() CreateMap<JobGroup, JobGroupResponse>()
.ForMember(d => d.Jobs, o => o.MapFrom(s => s.Jobs)); .ForMember(d => d.Schedule, o => o.MapFrom<JobGroupScheduleResolver>())
.ForMember(d => d.JobsCount, o => o.MapFrom(s => s.Jobs.Count()));
#endregion #endregion
#region JobAutoControl #region JobAutoControl

View File

@@ -0,0 +1,50 @@
using AutoMapper;
using PARR.API.Contracts.V1.Responses;
using PARR.DAL.Contracts;
using PARR.DAL.Models.Job;
using PARR.DAL.Services.Interfaces;
namespace PARR.API.MappingProfiles.Resolvers
{
public class JobGroupScheduleResolver : IValueResolver<JobGroup, JobGroupResponse, JobGroupScheduleResponse?>
{
private readonly IEsppSchTypeConfigService esppConfigService;
private readonly ILogger<JobGroupScheduleResolver> logger;
private readonly IMapper mapper;
private readonly SettingsFromDb settingsFromDb;
public JobGroupScheduleResolver(
IEsppSchTypeConfigService esppConfigService,
ILogger<JobGroupScheduleResolver> logger,
IMapper mapper,
SettingsFromDb settingsFromDb
)
{
this.esppConfigService = esppConfigService;
this.logger = logger;
this.mapper = mapper;
this.settingsFromDb = settingsFromDb;
}
public JobGroupScheduleResponse? Resolve(JobGroup source, JobGroupResponse destination, JobGroupScheduleResponse? destMember, ResolutionContext context)
{
var schedule = esppConfigService.GetEsppScheduleDto(source.Id);
if (schedule == null)
{
logger.LogError($"Не смог замапить расписание, так как оно null. JobGroupId: {source.Id}");
return null;
}
var response = new JobGroupScheduleResponse
{
Timezone = settingsFromDb.ScheduleTimezone,
TypeSchedule = mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
Values = mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
};
return response;
}
}
}

View File

@@ -70,12 +70,12 @@ namespace PARR.API.Validators
// .WithMessage("Не удалось найти подходящую конфигруцию планировщика задания на выполнение работ"); // .WithMessage("Не удалось найти подходящую конфигруцию планировщика задания на выполнение работ");
#endregion #endregion
RuleFor(t => t.Schedule) //RuleFor(t => t.Schedule)
.NotNull().NotEmpty() // .NotNull().NotEmpty()
.When(t => t.Schedule.Count() > 0) // .When(t => t.Schedule.Count() > 0)
.WithMessage("Настройки планировщика не могут быть пустыми") // .WithMessage("Настройки планировщика не могут быть пустыми")
.Must((entity, value, c) => IsEsppSchValuesExist(entity.Schedule)) // .Must((entity, value, c) => IsEsppSchValuesExist(entity.Schedule))
.WithMessage("Не удалось найти подходящую конфигруцию планировщика задания"); // .WithMessage("Не удалось найти подходящую конфигруцию планировщика задания");
#region comment #region comment
@@ -109,7 +109,7 @@ namespace PARR.API.Validators
} }
private async Task<bool> IsAllowAutoDistributionEnabledAsync(ApplicationInWorkRequest entity, bool value) private async Task<bool> IsAllowAutoDistributionEnabledAsync(ApplicationInWorkRequest entity, bool value)//TODO JobGroupRequest
{ {
//Автораспределение может быть включено, только если у EsppSchTypeValues не пустое поле DistributionPeriodId //Автораспределение может быть включено, только если у EsppSchTypeValues не пустое поле DistributionPeriodId
@@ -118,13 +118,13 @@ namespace PARR.API.Validators
//Распределение включено, смотрим, разрешено ли оно в расписании //Распределение включено, смотрим, разрешено ли оно в расписании
//по идее, это расписание только с одним значением в EsppSchValues, но мы проверим у всех, но такого быть не может по хорошему //по идее, это расписание только с одним значением в EsppSchValues, но мы проверим у всех, но такого быть не может по хорошему
foreach (var item in entity.Schedule) //foreach (var item in entity.Schedule)
{ //{
var schVal = await esppSchTypeValueService.GetAsync(item.TypeValueId); // var schVal = await esppSchTypeValueService.GetAsync(item.TypeValueId);
if (schVal != null) // if (schVal != null)
if (schVal.DistributionPeriodId == null) // if (schVal.DistributionPeriodId == null)
return false; // return false;
} //}
return true; return true;
} }