feat(api): обновлен AppInWorkController под новый респонс, валидация для галки IsAutoDistributionEnabled

This commit is contained in:
Mikhail Trubnikov
2024-07-03 10:16:54 +10:00
parent cf5a465546
commit ff58a21cc5
11 changed files with 172 additions and 9 deletions

View File

@@ -15,7 +15,17 @@
public required string Solution { get; set; } public required string Solution { get; set; }
public DateTimeOffset NextRun { get; set; } //public DateTimeOffset NextRun { get; set; }
/// <summary>
/// Дата начала работ
/// </summary>
public DateTimeOffset ReferenceDate { get; set; }
/// <summary>
/// Включить автораспределение
/// </summary>
public bool IsAutoDistributionEnabled { get; set; }
public bool IsAgent { get; set; } public bool IsAgent { get; set; }

View File

@@ -12,9 +12,13 @@
public required string Solution { get; set; } public required string Solution { get; set; }
public DateTimeOffset? LastRun { get; set; } //public DateTimeOffset? LastRun { get; set; }
public DateTimeOffset NextRun { get; set; } //public DateTimeOffset NextRun { get; set; }
public DateTimeOffset ReferenceDate { get; set; }
public bool IsAutoDistributionEnabled { get; set; }
public bool IsAgent { get; set; } public bool IsAgent { get; set; }
@@ -32,7 +36,7 @@
public ApplicationInWorkScheduleResponse? Schedule { get; set; } public ApplicationInWorkScheduleResponse? Schedule { get; set; }
public List<WorkGroupResponse>? WorkGroups { get; set; } public List<WorkGroupResponse>? WorkGroups { get; set; }
} }

View File

@@ -11,10 +11,14 @@ 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.Extensions;
using PARR.API.Services.Interfaces; using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using PARR.Constants; using PARR.Constants;
using PARR.DAL.DomainModels; using PARR.DAL.DomainModels;
using PARR.DAL.Models; using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces; using PARR.DAL.Services.Interfaces;
using System.Text.Json;
namespace PARR.API.Controllers.V1 namespace PARR.API.Controllers.V1
{ {
@@ -27,6 +31,8 @@ namespace PARR.API.Controllers.V1
private readonly IValidator<ApplicationInWorkRequest> validator; private readonly IValidator<ApplicationInWorkRequest> validator;
private readonly IUriService uriService; private readonly IUriService uriService;
private readonly ITemplateService templateService; private readonly ITemplateService templateService;
private readonly IMqService mqService;
private readonly MqSettings mqSettings;
public ApplicationInWorkController( public ApplicationInWorkController(
ILogger<ApplicationInWorkController> logger, ILogger<ApplicationInWorkController> logger,
@@ -34,7 +40,9 @@ namespace PARR.API.Controllers.V1
IApplicationsInWorkService applicationsInWorkService, IApplicationsInWorkService applicationsInWorkService,
IValidator<ApplicationInWorkRequest> validator, IValidator<ApplicationInWorkRequest> validator,
IUriService uriService, IUriService uriService,
ITemplateService templateService ITemplateService templateService,
IMqService mqService,
MqSettings mqSettings
) )
{ {
this.logger = logger; this.logger = logger;
@@ -43,6 +51,8 @@ namespace PARR.API.Controllers.V1
this.validator = validator; this.validator = validator;
this.uriService = uriService; this.uriService = uriService;
this.templateService = templateService; this.templateService = templateService;
this.mqService = mqService;
this.mqSettings = mqSettings;
} }
@@ -147,7 +157,9 @@ namespace PARR.API.Controllers.V1
ShortDescription = request.ShortDescription.Trim(), ShortDescription = request.ShortDescription.Trim(),
FullDescription = request.FullDescription.Trim(), FullDescription = request.FullDescription.Trim(),
Solution = request.Solution.Trim(), Solution = request.Solution.Trim(),
NextRun = request.NextRun, //NextRun = request.NextRun,
IsAutoDistributionEnabled = request.IsAutoDistributionEnabled,
ReferenceDate = request.ReferenceDate,
IsAgent = request.IsAgent, IsAgent = request.IsAgent,
AgentName = request.AgentName?.Trim(), AgentName = request.AgentName?.Trim(),
AgentTimeOutSec = request.AgentTimeOutSec, AgentTimeOutSec = request.AgentTimeOutSec,
@@ -225,13 +237,18 @@ namespace PARR.API.Controllers.V1
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.WorkId = request.WorkId; orig.WorkId = request.WorkId;
orig.ApplicationId = request.ApplicationId; orig.ApplicationId = request.ApplicationId;
orig.TemplateDuration = request.TemplateDuration; orig.TemplateDuration = request.TemplateDuration;
orig.ShortDescription = request.ShortDescription.Trim(); orig.ShortDescription = request.ShortDescription.Trim();
orig.FullDescription = request.FullDescription.Trim(); orig.FullDescription = request.FullDescription.Trim();
orig.Solution = request.Solution.Trim(); orig.Solution = request.Solution.Trim();
orig.NextRun = request.NextRun; //orig.NextRun = request.NextRun;
orig.ReferenceDate = request.ReferenceDate;
orig.IsAutoDistributionEnabled = request.IsAutoDistributionEnabled;
orig.IsAgent = request.IsAgent; orig.IsAgent = request.IsAgent;
orig.AgentName = request.AgentName?.Trim(); orig.AgentName = request.AgentName?.Trim();
orig.AgentTimeOutSec = request.AgentTimeOutSec; orig.AgentTimeOutSec = request.AgentTimeOutSec;
@@ -270,6 +287,26 @@ namespace PARR.API.Controllers.V1
$" {orig.FullDescription}, {orig.Solution}, {orig.NextRun}, {orig.IsAgent}, {orig.AgentName}, {orig.AgentTimeOutSec}, {orig.AgentScript}"); $" {orig.FullDescription}, {orig.Solution}, {orig.NextRun}, {orig.IsAgent}, {orig.AgentName}, {orig.AgentTimeOutSec}, {orig.AgentScript}");
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 updatedApplicationInWork = await applicationsInWorkService.Get() var updatedApplicationInWork = await applicationsInWorkService.Get()
.Include(t => t.Application).ThenInclude(t => t!.ApplicationType) .Include(t => t.Application).ThenInclude(t => t!.ApplicationType)
.Include(t => t.Work) .Include(t => t.Work)
@@ -322,5 +359,35 @@ namespace PARR.API.Controllers.V1
return NoContent(); return NoContent();
} }
/// <summary>
/// Проверка, были ли изменения в расписании
/// </summary>
/// <param name="orig"></param>
/// <param name="request"></param>
/// <returns></returns>
private bool IsScheduleChanged(ApplicationsInWork orig, ApplicationInWorkRequest request)
{
var isScheduleChanged = false;
if (orig.ReferenceDate != request.ReferenceDate)
isScheduleChanged = true;
if (request.Schedule.Count() != orig.EsppSchValues.Count())
isScheduleChanged = true;
request.Schedule.ForEach(requestSchedule =>
{
var schExist = orig.EsppSchValues.FirstOrDefault(t => t.ApplicationsInWorkId == orig.Id
&& t.TypeValueId == requestSchedule.TypeValueId
&& t.TypeConfigId == requestSchedule.TypeConfigId);
if (schExist == null)
isScheduleChanged = true;
});
return isScheduleChanged;
}
} }
} }

View File

@@ -5,6 +5,7 @@ namespace PARR.API.Settings
public class MqSettings public class MqSettings
{ {
public MqGenerateTemplates GenerateTemplates { get; set; } = new MqGenerateTemplates(); public MqGenerateTemplates GenerateTemplates { get; set; } = new MqGenerateTemplates();
public MqTemplateDistributor TemplateDistributor { get; set; } = new MqTemplateDistributor();
public MqStatistics Statistics { get; set; } = new MqStatistics(); public MqStatistics Statistics { get; set; } = new MqStatistics();
} }
@@ -16,6 +17,14 @@ namespace PARR.API.Settings
public string Password { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
} }
public class MqTemplateDistributor : IMqSettings
{
public string HostName { get; set; } = string.Empty;
public string QueueName { get; set; } = string.Empty;
public string User { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}
public class MqStatistics public class MqStatistics
{ {
public StatMqAuth StatMqAuth { get; set; } = new StatMqAuth(); public StatMqAuth StatMqAuth { get; set; } = new StatMqAuth();

View File

@@ -1,5 +1,6 @@
using FluentValidation; using FluentValidation;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using PARR.API.Contracts.V1.Requests; using PARR.API.Contracts.V1.Requests;
using PARR.DAL.Services.Interfaces; using PARR.DAL.Services.Interfaces;
@@ -11,18 +12,21 @@ namespace PARR.API.Validators
private readonly IWorkService workService; private readonly IWorkService workService;
private readonly IEsppSchTypeConfigService esppSchTypeConfigService; private readonly IEsppSchTypeConfigService esppSchTypeConfigService;
private readonly IWorkGroupService workGroupService; private readonly IWorkGroupService workGroupService;
private readonly IEsppSchTypeValueService esppSchTypeValueService;
public ApplicationInWorkValidator( public ApplicationInWorkValidator(
IApplicationsInWorkService applicationsInWorkService, IApplicationsInWorkService applicationsInWorkService,
IWorkService workService, IWorkService workService,
IEsppSchTypeConfigService esppSchTypeConfigService, IEsppSchTypeConfigService esppSchTypeConfigService,
IWorkGroupService workGroupService IWorkGroupService workGroupService,
IEsppSchTypeValueService esppSchTypeValueService
) )
{ {
this.applicationsInWorkService = applicationsInWorkService; this.applicationsInWorkService = applicationsInWorkService;
this.workService = workService; this.workService = workService;
this.esppSchTypeConfigService = esppSchTypeConfigService; this.esppSchTypeConfigService = esppSchTypeConfigService;
this.workGroupService = workGroupService; this.workGroupService = workGroupService;
this.esppSchTypeValueService = esppSchTypeValueService;
RuleFor(t => t.TemplateDuration) RuleFor(t => t.TemplateDuration)
.NotNull().NotEmpty()//.WithMessage("Длительность данного задания на выполнение работ не может быть пустым") .NotNull().NotEmpty()//.WithMessage("Длительность данного задания на выполнение работ не может быть пустым")
@@ -96,8 +100,36 @@ namespace PARR.API.Validators
RuleFor(t => t.WorkGroups) RuleFor(t => t.WorkGroups)
.MustAsync(async (entity, value, c) => await IsWorkGroupsExistAsync(entity)) .MustAsync(async (entity, value, c) => await IsWorkGroupsExistAsync(entity))
.WithMessage("Указаные несуществующие Id рабочих групп"); .WithMessage("Указаные несуществующие Id рабочих групп");
//Автораспределение может быть включено, только если у EsppSchTypeValues не пустое поле DistributionPeriodId
RuleFor(t => t.IsAutoDistributionEnabled)
.MustAsync(async (entity, value, c) => await IsAllowAutoDistributionEnabledAsync(entity, value))
.WithMessage("Нельзя включить автораспределение для этого типа расписания");
} }
private async Task<bool> IsAllowAutoDistributionEnabledAsync(ApplicationInWorkRequest entity, bool value)
{
//Автораспределение может быть включено, только если у EsppSchTypeValues не пустое поле DistributionPeriodId
if (value == false)
return true;
//Распределение включено, смотрим, разрешено ли оно в расписании
//по идее, это расписание только с одним значением в EsppSchValues, но мы проверим у всех, но такого быть не может по хорошему
foreach (var item in entity.Schedule)
{
var schVal = await esppSchTypeValueService.GetAsync(item.TypeValueId);
if (schVal != null)
if (schVal.DistributionPeriodId == null)
return false;
}
return true;
}
private async Task<bool> IsWorkGroupsExistAsync(ApplicationInWorkRequest entity) private async Task<bool> IsWorkGroupsExistAsync(ApplicationInWorkRequest entity)
{ {
var result = await workGroupService.Get().Where(t => entity.WorkGroups.Contains(t.Id)).ToListAsync(); var result = await workGroupService.Get().Where(t => entity.WorkGroups.Contains(t.Id)).ToListAsync();

View File

@@ -24,6 +24,9 @@
"GenerateTemplates": { "GenerateTemplates": {
"HostName": "10.99.253.216" "HostName": "10.99.253.216"
}, },
"TemplateDistributor": {
"HostName": "10.99.253.216"
},
"Statistics": { "Statistics": {
"StatMqAuth": { "StatMqAuth": {
"HostName": "10.99.253.216" "HostName": "10.99.253.216"

View File

@@ -45,6 +45,12 @@
"User": "generate_templates_api", "User": "generate_templates_api",
"Password": "DHhjgdsf*&%95" "Password": "DHhjgdsf*&%95"
}, },
"TemplateDistributor": {
"HostName": "parr-rabbitmq",
"QueueName": "parr-template-distributor",
"User": "espp_template_distributor_writer",
"Password": "KGgsdfu%%44qqwew"
},
"Statistics": { "Statistics": {
"StatMqAuth": { "StatMqAuth": {
"HostName": "parr-rabbitmq", "HostName": "parr-rabbitmq",

View File

@@ -89,7 +89,6 @@ namespace PARR.DAL.Models
/// </summary> /// </summary>
public DateTimeOffset ReferenceDate { get; set; } public DateTimeOffset ReferenceDate { get; set; }
/// <summary> /// <summary>
/// Выполняет агент /// Выполняет агент
/// </summary> /// </summary>

View File

@@ -82,6 +82,7 @@ namespace PARR.DAL
services.AddTransient<IEsppSchTypeScheduleService, EsppSchTypeScheduleService>(); services.AddTransient<IEsppSchTypeScheduleService, EsppSchTypeScheduleService>();
services.AddTransient<IWeekendDayService, WeekendDayService>(); services.AddTransient<IWeekendDayService, WeekendDayService>();
services.AddTransient<IDistributionPeriodService, DistributionPeriodService>(); services.AddTransient<IDistributionPeriodService, DistributionPeriodService>();
services.AddTransient<IEsppSchTypeValueService, EsppSchTypeValueService>();
// TransformServices // TransformServices
services.AddTransient<IEsppScheduleTransformService, EsppScheduleTransformService>(); services.AddTransient<IEsppScheduleTransformService, EsppScheduleTransformService>();

View File

@@ -0,0 +1,23 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.DAL.Context;
using PARR.DAL.Models;
using PARR.DAL.Services.Abstracts;
using PARR.DAL.Services.Interfaces;
namespace PARR.DAL.Services.Implementations
{
internal class EsppSchTypeValueService : BaseService<EsppSchTypeValue>, IEsppSchTypeValueService
{
private readonly DataContext dataContext;
protected override DbSet<EsppSchTypeValue> EntitySet => dataContext.EsppSchTypeValues;
protected override DataContext EntitiContext => dataContext;
public EsppSchTypeValueService(DataContext dataContext, ILogger<EsppSchTypeValueService> logger): base(logger)
{
this.dataContext = dataContext;
}
}
}

View File

@@ -0,0 +1,9 @@
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces.Base;
namespace PARR.DAL.Services.Interfaces
{
public interface IEsppSchTypeValueService : IBaseService<EsppSchTypeValue>
{
}
}