feat(api): JobGroupController добавлена выдача расписания и количество связанных Job
This commit is contained in:
@@ -1,26 +1,14 @@
|
||||
using AutoMapper;
|
||||
using FluentValidation;
|
||||
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.Queries;
|
||||
using PARR.API.Contracts.V1.Responses;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Extensions;
|
||||
using PARR.API.Services.Interfaces;
|
||||
using PARR.API.Settings;
|
||||
using PARR.BLL.Domain.Mq;
|
||||
using PARR.BLL.Services.Interfaces;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.Contracts;
|
||||
using PARR.DAL.DomainModels;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using System.Text.Json;
|
||||
using static PARR.API.Contracts.V1.ApiRoutes;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using AutoMapper;
|
||||
using FluentValidation;
|
||||
using InfluxDB.Client.Api.Domain;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -14,9 +13,9 @@ using PARR.API.Extensions;
|
||||
using PARR.API.Services.Interfaces;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.DomainModels;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.DAL.Models.Job;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
@@ -64,26 +63,23 @@ namespace PARR.API.Controllers.V1
|
||||
if (!string.IsNullOrEmpty(filter.Name))
|
||||
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)
|
||||
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();
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
@@ -101,6 +97,7 @@ namespace PARR.API.Controllers.V1
|
||||
{
|
||||
var jobGroup = await groupService.Get()
|
||||
.Include(t => t.Jobs).ThenInclude(t => t.Tnk)
|
||||
.Include(t => t.EsppSchValues)
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
|
||||
if (jobGroup == null)
|
||||
@@ -142,6 +139,16 @@ namespace PARR.API.Controllers.V1
|
||||
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())
|
||||
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}");
|
||||
|
||||
|
||||
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);
|
||||
|
||||
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));
|
||||
|
||||
var orig = await groupService.Get()
|
||||
.Include(t=>t.Jobs)
|
||||
.Include(t => t.Jobs)
|
||||
.ThenInclude(t => t.Tnk)
|
||||
.Include(t => t.EsppSchValues)
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
|
||||
if (orig == null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении группы заданий на выполнение работ. Не найдена группа с Id: {id}" } }));
|
||||
|
||||
// //Расписание было изменено, ниже добавим задание в очередь на обновление расписаний у связанных шаблонов
|
||||
var isScheduleChanged = IsScheduleChanged(orig, request);
|
||||
|
||||
orig.GroupName = request.Name.Trim();
|
||||
orig.IsUmbrella = request.IsUmbrella;
|
||||
orig.ShortDescription = request.ShortDescription.Trim();
|
||||
@@ -194,6 +205,19 @@ namespace PARR.API.Controllers.V1
|
||||
orig.AgentName = request.AgentName;
|
||||
orig.AgentTimeOutSec = request.AgentTimeOutSec;
|
||||
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())
|
||||
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.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()
|
||||
.Include(t => t.Jobs)
|
||||
.ThenInclude(t => t.Tnk)
|
||||
.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>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete(ApiRoutes.JobGroup.Delete)]
|
||||
public async Task<IActionResult> Delete([FromRoute] Guid id)
|
||||
//[HttpDelete(ApiRoutes.JobGroup.Delete)]
|
||||
//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()
|
||||
.Include(t => t.Jobs)
|
||||
.ThenInclude(t => t.Tnk)
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
var isScheduleChanged = false;
|
||||
|
||||
if (jobGroup == null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
|
||||
Message = $"Ошибка при удалении группы заданий на выполнение работ. Не найдена группа заданий на выполнение работ Id: {id}"
|
||||
} }));
|
||||
if (orig.ReferenceDate != request.ReferenceDate)
|
||||
isScheduleChanged = true;
|
||||
|
||||
if (!groupService.Delete(jobGroup) || !await groupService.CommitAsync())
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
|
||||
Message = $"Ошибка при удалении группы заданий на выполнение работ"
|
||||
} }));
|
||||
if (request.Schedule.Count() != orig.EsppSchValues.Count())
|
||||
isScheduleChanged = true;
|
||||
|
||||
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}");
|
||||
if (request.IsAutoDistributionEnabled != orig.IsAutoDistributionEnabled)
|
||||
isScheduleChanged = true;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user