feat(api): JobControl переписан метод Create+Валидация
This commit is contained in:
@@ -374,6 +374,8 @@
|
||||
public const string Create = Base + "/jobs/";
|
||||
public const string Update = Base + "/jobs/" + getParam;
|
||||
|
||||
public const string Preview = Base + "/jobs/units/preview";
|
||||
|
||||
public const string getParam = "{id}";
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
public required string Name { get; set; }
|
||||
|
||||
public int? MinValueRelationships { get; set; }
|
||||
|
||||
|
||||
public int? MaxValueRelationships { get; set; }
|
||||
|
||||
public bool? isParentRelationships { get; set; }
|
||||
@@ -19,5 +19,40 @@
|
||||
public required string WorkGroupMask { get; set; }
|
||||
|
||||
public required string WorkName { get; set; }
|
||||
|
||||
public required List<UnitFilterRequest> UnitFilters { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class UnitFilterRequest
|
||||
{
|
||||
public required string UnitFilterMask { get; set; }
|
||||
|
||||
public List<FieldFilterRequest>? FieldFilters { get; set; }
|
||||
|
||||
public List<RelationshipFilterRequest>? RelationshipFilters { get; set; }
|
||||
}
|
||||
|
||||
|
||||
public class FieldFilterRequest
|
||||
{
|
||||
public Guid FieldId { get; set; }
|
||||
|
||||
public string? ValueMask { get; set; }
|
||||
|
||||
}
|
||||
|
||||
|
||||
public class RelationshipFilterRequest
|
||||
{
|
||||
public Guid FieldId { get; set; }
|
||||
|
||||
public bool? IsParent { get; set; }
|
||||
|
||||
public string? ValueMask { get; set; }
|
||||
|
||||
public bool? IsFullMatch { get; set; }
|
||||
|
||||
public bool? IsInverse { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,17 @@
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public int? MinValueRelationships { get; set; }
|
||||
|
||||
public int? MaxValueRelationships { get; set; }
|
||||
|
||||
public bool? isParentRelationships { get; set; }
|
||||
|
||||
public required string TemplateNameMask { get; set; }
|
||||
|
||||
public required string WorkName { get; set; }
|
||||
|
||||
public required string WorkGroupMask { get; set; }
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -14,9 +14,11 @@ using PARR.API.Services.Interfaces;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.Contracts;
|
||||
using PARR.DAL.DomainModels;
|
||||
using PARR.DAL.DomainServices.Interfaces;
|
||||
using PARR.DAL.Models.Job;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
using PARR.DAL.Services.Interfaces.Unit;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
@@ -31,7 +33,13 @@ namespace PARR.API.Controllers.V1
|
||||
private readonly IUriService uriService;
|
||||
private readonly IJobService jobService;
|
||||
private readonly ITemplateService templateService;
|
||||
private readonly IValidator<JobRequest> validator;
|
||||
private readonly IJobGroupService jobGroupService;
|
||||
private readonly IValidator<JobRequest> jobValidator;
|
||||
private readonly IValidator<UnitFilterRequest> unitFilterValidator;
|
||||
private readonly IValidator<FieldFilterRequest> fieldFilterValidator;
|
||||
private readonly IValidator<RelationshipFilterRequest> relationshipFilterValidator;
|
||||
private readonly IUnitFilterService unitFilterService;
|
||||
private readonly IUnitService unitService;
|
||||
|
||||
public JobController(
|
||||
ILogger<JobController> logger,
|
||||
@@ -39,7 +47,13 @@ namespace PARR.API.Controllers.V1
|
||||
IUriService uriService,
|
||||
IJobService jobService,
|
||||
ITemplateService templateService,
|
||||
IValidator<JobRequest> validator
|
||||
IJobGroupService jobGroupService,
|
||||
IValidator<JobRequest> jobValidator,
|
||||
IValidator<UnitFilterRequest> unitFilterValidator,
|
||||
IValidator<FieldFilterRequest> fieldFilterValidator,
|
||||
IValidator<RelationshipFilterRequest> relationshipFilterValidator,
|
||||
IUnitFilterService unitFilterService,
|
||||
IUnitService unitService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
@@ -47,7 +61,13 @@ namespace PARR.API.Controllers.V1
|
||||
this.uriService = uriService;
|
||||
this.jobService = jobService;
|
||||
this.templateService = templateService;
|
||||
this.validator = validator;
|
||||
this.jobGroupService = jobGroupService;
|
||||
this.jobValidator = jobValidator;
|
||||
this.unitFilterValidator = unitFilterValidator;
|
||||
this.fieldFilterValidator = fieldFilterValidator;
|
||||
this.relationshipFilterValidator = relationshipFilterValidator;
|
||||
this.unitFilterService = unitFilterService;
|
||||
this.unitService = unitService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -142,36 +162,31 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpPost(ApiRoutes.Job.Create)]
|
||||
public async Task<IActionResult> Create([FromBody] JobRequest request)
|
||||
{
|
||||
var resultValidate = await validator.ValidateAsync(request);
|
||||
#region Валидация
|
||||
var jobValidateResult = await jobValidator.ValidateAsync(request);//Валидация параметров самого задания
|
||||
|
||||
if (!resultValidate.IsValid)
|
||||
return BadRequest(new Response(resultValidate.Errors));
|
||||
|
||||
var job = new Job
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = request.Name.Trim(),
|
||||
WorkName = request.WorkName.Trim(),
|
||||
MinValueRelationships = request.MinValueRelationships,
|
||||
MaxValueRelationships = request.MaxValueRelationships,
|
||||
isParentRelationships = request.isParentRelationships,
|
||||
TemplateNameMask = request.TemplateNameMask.Trim(),
|
||||
WorkGroupMask = request.WorkGroupMask.Trim(),
|
||||
TnkId = request.TnkId,
|
||||
GroupId = request.GroupId
|
||||
};
|
||||
if (!jobValidateResult.IsValid)
|
||||
return BadRequest(new Response(jobValidateResult.Errors));
|
||||
#endregion
|
||||
|
||||
var job = mapper.Map<Job>(request);
|
||||
|
||||
if (!await jobService.CreateAsync(job) || !await jobService.CommitAsync())
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при созании задания на выполнение работ" } }));
|
||||
|
||||
logger.LogInformation($"Пользователь {User.Identity?.Name} добавил задание на выполнение работ: {job.Id}, {job.Name}, {job.WorkName}");
|
||||
|
||||
var createdJob = await jobService.Get()
|
||||
.Include(t => t.Tnk)
|
||||
.Include(t => t.Group)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.Field)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.FirstOrDefaultAsync(t => t.Id == job.Id);
|
||||
|
||||
var createdJob = await jobService.Get().Include(t => t.Tnk)
|
||||
.FirstAsync(t => t.Id == job.Id);
|
||||
|
||||
var locationUri = uriService.GetUri(ApiRoutes.Job.Get, ApiRoutes.Job.getParam, createdJob.Id);
|
||||
var locationUri = uriService.GetUri(ApiRoutes.Job.Get, ApiRoutes.Job.getParam, createdJob!.Id);
|
||||
|
||||
var response = mapper.Map<JobResponse>(createdJob);
|
||||
// так как мы только что создали Job, то у него нет шаблонов, смело ставим = 0 (ускоряем запрос)
|
||||
@@ -190,7 +205,7 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpPut(ApiRoutes.Job.Update)]
|
||||
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] JobRequest request)
|
||||
{
|
||||
var resultValidate = await validator.ValidateAsync(request);
|
||||
var resultValidate = await jobValidator.ValidateAsync(request);
|
||||
if (!resultValidate.IsValid)
|
||||
return BadRequest(new Response(resultValidate.Errors));
|
||||
|
||||
@@ -267,6 +282,38 @@ namespace PARR.API.Controllers.V1
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получить список ЭК для которых будут созданы шаблоны
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost(ApiRoutes.Job.Preview)]
|
||||
public async Task<IActionResult> Preview([FromBody] JobRequest request)
|
||||
{
|
||||
#region Валидация
|
||||
var jobValidateResult = await jobValidator.ValidateAsync(request);//Валидация параметров самого задания
|
||||
|
||||
if (!jobValidateResult.IsValid)
|
||||
return BadRequest(new Response(jobValidateResult.Errors));
|
||||
#endregion
|
||||
|
||||
var job = mapper.Map<Job>(request);
|
||||
|
||||
var group = await jobGroupService.GetAsync(request.GroupId);
|
||||
|
||||
job.Group = group;
|
||||
|
||||
var unitIds = await unitFilterService.GetUnitsIdByJobFilterAsync(job);
|
||||
|
||||
if (unitIds == null)
|
||||
return NotFound();
|
||||
|
||||
var units = await unitService.Get().Where(t => unitIds.Any(a => a == t.Id)).Take(1000).ToListAsync();
|
||||
|
||||
var response = mapper.Map<List<UnitResponse>>(units);
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Загрузка статистики
|
||||
@@ -303,7 +350,6 @@ namespace PARR.API.Controllers.V1
|
||||
//job.ScheduleStatistics = new ScheduleStats { Activated = statistics.ScheduleStatistics.Activated, Errors = statistics.ScheduleStatistics.Errors, Synchronized = statistics.ScheduleStatistics.Synchronized };
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public class JobStatModel
|
||||
@@ -312,4 +358,5 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
public required ScheduleStats ScheduleStatistics { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -104,13 +104,13 @@ 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)
|
||||
return NotFound();
|
||||
|
||||
var response = mapper.Map<JobGroupResponse>(jobGroup);
|
||||
await AppendMissingDataAsync(response);
|
||||
|
||||
return Ok(new Response<JobGroupResponse>(response, true));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using AutoMapper;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.API.Contracts.V1.Requests.Queries;
|
||||
using PARR.DAL.DomainModels;
|
||||
using PARR.DAL.Models.Job;
|
||||
|
||||
namespace PARR.API.MappingProfiles
|
||||
{
|
||||
@@ -9,6 +11,37 @@ namespace PARR.API.MappingProfiles
|
||||
public RequestToDomainProfile()
|
||||
{
|
||||
CreateMap<PaginationQuery, PaginationFilter>();
|
||||
|
||||
CreateMap<JobRequest, Job>()
|
||||
.ForMember(d => d.Id, o => o.MapFrom(s => Guid.NewGuid()))
|
||||
.ForMember(d => d.DateCreated, o => o.MapFrom(s => DateTimeOffset.UtcNow))
|
||||
.AfterMap((s, d) =>
|
||||
{
|
||||
if (d.UnitFilters != null)
|
||||
foreach (var unitFilter in d.UnitFilters)
|
||||
unitFilter.JobId = d.Id;
|
||||
});
|
||||
|
||||
CreateMap<UnitFilterRequest, JobUnitFilter>()
|
||||
.ForMember(d => d.Id, o => o.MapFrom(s => Guid.NewGuid()))
|
||||
.ForMember(d => d.DateCreated, o => o.MapFrom(s => DateTimeOffset.UtcNow))
|
||||
.ForMember(d => d.UnitFilter, o => o.MapFrom(s => s.UnitFilterMask))
|
||||
.AfterMap((s, d) =>
|
||||
{
|
||||
if (d.FieldFilters != null)
|
||||
foreach (var fieldFilter in d.FieldFilters)
|
||||
fieldFilter.UnitFilterId = d.Id;
|
||||
|
||||
if (d.RelationshipFilters != null)
|
||||
foreach (var relationshipFilter in d.RelationshipFilters)
|
||||
relationshipFilter.UnitFilterId = d.Id;
|
||||
});
|
||||
|
||||
CreateMap<FieldFilterRequest, FieldFilter>()
|
||||
.ForMember(d => d.Id, o => o.MapFrom(s => Guid.NewGuid()))
|
||||
.ForMember(d => d.DateCreated, o => o.MapFrom(s => DateTimeOffset.UtcNow));
|
||||
|
||||
CreateMap<RelationshipFilterRequest, JobRelationshipFilter>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
123
PARR.API/Validators/JobRequestValidator.cs
Normal file
123
PARR.API/Validators/JobRequestValidator.cs
Normal file
@@ -0,0 +1,123 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.DAL.Models.Job;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
using PARR.DAL.Services.Interfaces.Unit;
|
||||
|
||||
namespace PARR.API.Validators
|
||||
{
|
||||
public class JobRequestValidator : AbstractValidator<JobRequest>
|
||||
{
|
||||
private readonly ITnkService tnkService;
|
||||
private readonly IJobGroupService jobGroupService;
|
||||
private readonly IJobService jobService;
|
||||
private readonly IUnitFieldService unitFieldService;
|
||||
private JobGroup? jobGroup;
|
||||
|
||||
public JobRequestValidator(
|
||||
ITnkService tnkService,
|
||||
IJobGroupService jobGroupService,
|
||||
IJobService jobService,
|
||||
IUnitFieldService unitFieldService
|
||||
)
|
||||
{
|
||||
this.tnkService = tnkService;
|
||||
this.jobGroupService = jobGroupService;
|
||||
this.jobService = jobService;
|
||||
this.unitFieldService = unitFieldService;
|
||||
RuleFor(t => t.Name)
|
||||
.NotNull().NotEmpty();
|
||||
|
||||
RuleFor(t => t.WorkName)
|
||||
.NotNull().NotEmpty();
|
||||
|
||||
RuleFor(t => t.TnkId)
|
||||
.MustAsync(async (entity, value, c) => await IsTnkExist(entity))
|
||||
.WithMessage("Указан несуществующий Id ТНК({PropertyValue})");
|
||||
|
||||
RuleFor(t => t.GroupId)
|
||||
.MustAsync(async (entity, value, c) => await IsGroupExist(entity))
|
||||
.WithMessage("Указан несуществующий Id группы работ({PropertyValue})");
|
||||
|
||||
RuleForEach(t => t.UnitFilters)
|
||||
.NotNull().NotEmpty();
|
||||
|
||||
RuleForEach(t => t.UnitFilters)
|
||||
.MustAsync(async (entity, value, c) => await IsUnitFiltersCorrect(entity))
|
||||
.WithMessage("Неверно заданы параметры фильтров. Внимательнее, пожалуйста!");
|
||||
|
||||
RuleFor(t => t.MinValueRelationships)
|
||||
.MustAsync(async (entity, value, c) => await IsMinValueRelationShipsExist(entity))
|
||||
.WithMessage("Работа с таким минимальным количеством связей уже существует");
|
||||
|
||||
RuleFor(t => t.MaxValueRelationships)
|
||||
.GreaterThanOrEqualTo(t => t.MinValueRelationships);
|
||||
|
||||
RuleFor(t => t.MaxValueRelationships)
|
||||
.MustAsync(async (entity, value, c) => await IsMaxValueRelationShipsExist(entity))
|
||||
.WithMessage("Работа с таким максимальным количеством связей уже существует");
|
||||
|
||||
|
||||
}
|
||||
|
||||
private async Task<bool> IsUnitFiltersCorrect(JobRequest entity)
|
||||
{
|
||||
foreach (var unitFilter in entity.UnitFilters)
|
||||
{
|
||||
if (string.IsNullOrEmpty(unitFilter.UnitFilterMask))
|
||||
return false;
|
||||
|
||||
if (unitFilter.FieldFilters == null || !unitFilter.FieldFilters.Any())
|
||||
return false;
|
||||
|
||||
foreach (var fieldFilter in unitFilter.FieldFilters)
|
||||
{
|
||||
var fieldId = fieldFilter.FieldId;
|
||||
if (await unitFieldService.GetAsync(fieldId) == null)
|
||||
return false;
|
||||
}
|
||||
|
||||
if (unitFilter.RelationshipFilters != null || unitFilter.FieldFilters.Any())
|
||||
foreach (var relationshipFilter in unitFilter.RelationshipFilters!)
|
||||
{
|
||||
var fieldId = relationshipFilter.FieldId;
|
||||
if (await unitFieldService.GetAsync(fieldId) == null)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> IsGroupExist(JobRequest entity)
|
||||
{
|
||||
jobGroup = await jobGroupService.GetAsync(entity.GroupId);
|
||||
|
||||
return jobGroup != null;
|
||||
}
|
||||
|
||||
|
||||
private async Task<bool> IsTnkExist(JobRequest entity)
|
||||
{
|
||||
return await tnkService.GetAsync(entity.TnkId) != null;
|
||||
}
|
||||
|
||||
private async Task<bool> IsMinValueRelationShipsExist(JobRequest entity)
|
||||
{
|
||||
if (!jobGroup?.IsUmbrella == true)
|
||||
return true;
|
||||
|
||||
return await jobService.Get().CountAsync(t => t.GroupId == entity.GroupId && t.MinValueRelationships == entity.MinValueRelationships) == 0;
|
||||
}
|
||||
|
||||
private async Task<bool> IsMaxValueRelationShipsExist(JobRequest entity)
|
||||
{
|
||||
if (!jobGroup?.IsUmbrella == true)
|
||||
return true;
|
||||
|
||||
return await jobService.Get().CountAsync(t => t.GroupId == entity.GroupId && t.MaxValueRelationships == entity.MaxValueRelationships) == 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
using FluentValidation;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
|
||||
namespace PARR.API.Validators
|
||||
{
|
||||
public class JobValidator : AbstractValidator<JobRequest>
|
||||
{
|
||||
private readonly ITnkService tnkService;
|
||||
private readonly IJobGroupService jobGroupService;
|
||||
|
||||
public JobValidator(
|
||||
ITnkService tnkService,
|
||||
IJobGroupService jobGroupService
|
||||
)
|
||||
{
|
||||
this.tnkService = tnkService;
|
||||
this.jobGroupService = jobGroupService;
|
||||
|
||||
RuleFor(t => t.Name)
|
||||
.NotNull().NotEmpty();
|
||||
|
||||
RuleFor(t => t.WorkName)
|
||||
.NotNull().NotEmpty();
|
||||
|
||||
RuleFor(t => t.TnkId)
|
||||
.MustAsync(async (entity, value, c) => await IsTnkExist(entity))
|
||||
.WithMessage("Указан несуществующий Id ТНК");
|
||||
|
||||
RuleFor(t => t.GroupId)
|
||||
.MustAsync(async (entity, value, c) => await IsGroupExist(entity))
|
||||
.WithMessage("Указан несуществующий Id группы работ");
|
||||
}
|
||||
|
||||
|
||||
private async Task<bool> IsGroupExist(JobRequest entity)
|
||||
{
|
||||
return await jobGroupService.GetAsync(entity.GroupId) != null;
|
||||
}
|
||||
|
||||
|
||||
private async Task<bool> IsTnkExist(JobRequest entity)
|
||||
{
|
||||
return await tnkService.GetAsync(entity.TnkId) != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user