feat(api,core,dal): Группы работ - управление автокнотролем

This commit is contained in:
Mikhail Trubnikov
2026-06-18 16:39:35 +10:00
parent 108eb05853
commit 8151ea89b9
18 changed files with 4326 additions and 186 deletions

View File

@@ -1,52 +1,14 @@
using PARR.Domain.Enums;
namespace PARR.API.Contracts.V1.Requests
namespace PARR.API.Contracts.V1.Requests
{
public class JobAutoControlRequest
/// <summary>
/// Часть реквеста по управлению авто контролем для Job, JobGroup
/// </summary>
public record JobAutoControlRequest
{
/// <summary>
/// Создавать новые РР (из настроке РР)
/// </summary>
public bool CreateNew { get; set; }
public bool IsEnable { get; init; }
/// <summary>
/// Деактивировать не актуальные согласно ЭК (обратные статусы ЭК)
/// </summary>
public bool Deactivate { get; set; }
public bool InitUsedTemplateState { get; init; }
/// <summary>
/// Активировать РР после смены ЭК (согласно настройкам статусов ЭК)
/// </summary>
public bool Activate { get; set; }
/// <summary>
/// Состояние для активированных РР, шаблоны
/// </summary>
public bool OnTemplateIsActive { get; set; }
/// <summary>
/// Состояние для активированных РР, расписания
/// </summary>
public bool OnScheduleIsActive { get; set; }
/// <summary>
/// Состояние для деактивированных РР, шаблоны
/// </summary>
public bool OffTemplateIsActive { get; set; }
/// <summary>
/// Состояние для деактивированных РР, расписания
/// </summary>
public bool OffScheduleIsActive { get; set; }
/// <summary>
/// Маски ЭК
/// </summary>
public required List<string> EkMasks { get; set; }
/// <summary>
/// Статусы ЭК для которых включена генерация РР и активация
/// </summary>
public required List<EkStatusEnum> EnabledEkStatuses { get; set; }
public bool InitUsedScheduleState { get; init; }
}
}

View File

@@ -1,47 +1,47 @@
namespace PARR.API.Contracts.V1.Requests
{
public class JobGroupRequest
public record JobGroupRequest
{
public required string Name { get; set; }
public required string Name { get; init; }
//public bool? IsUmbrella { get; set; }
public Guid GroupTypeId { get; set; }
public Guid GroupTypeId { get; init; }
/// <summary>
/// Поле по которому групиируем, если тип - ГРУППА
/// </summary>
public Guid? GroupingUnitFieldId { get; set; }
public Guid? GroupingUnitFieldId { get; init; }
public bool? IsGroupByResponsible { get; set; }
public bool? IsGroupByResponsible { get; init; }
public required string ShortDescription { get; set; }
public required string ShortDescription { get; init; }
public required string FullDescription { get; set; }
public required string FullDescription { get; init; }
public required string Solution { get; set; }
public required string Solution { get; init; }
public required string TemplateDuration { get; set; }
public required string TemplateDuration { get; init; }
public DateTimeOffset ReferenceDate { get; set; }
public DateTimeOffset ReferenceDate { get; init; }
public int? UserTimeZoneOffsetMinutes { get; set; }
public int? UserTimeZoneOffsetMinutes { get; init; }
/// <summary>
/// Использовать таймзону рабочей группы ответственного за ЭК шаблона
/// </summary>
public bool IsWorkGroupTimezone { get; set; }
public bool IsWorkGroupTimezone { get; init; }
public Guid ScheduleExcludeTypeId { get; set; }
public Guid ScheduleExcludeTypeId { get; init; }
public Guid? ScheduleExcludeTypeCalendarId { get; set; }
public Guid? ScheduleExcludeTypeCalendarId { get; init; }
public bool IsAutoDistributionEnabled { get; set; }
public bool IsAutoDistributionEnabled { get; init; }
/// <summary>
/// Настройки автораспределения
/// </summary>
public DistributionConfigRequest? DistributionConfig { get; set; }
public DistributionConfigRequest? DistributionConfig { get; init; }
//public bool IsAgent { get; set; }
@@ -51,28 +51,35 @@
//public string? AgentScript { get; set; }
public List<EsppSchValueRequest> Schedule { get; set; } = new List<EsppSchValueRequest>();
public List<EsppSchValueRequest> Schedule { get; init; } = new List<EsppSchValueRequest>();
/// <summary>
/// Настройки автоконтроля (возможны только в случае, если JobGroupType.IsJobGroupAutocontrol==true)
/// </summary>
public JobAutoControlRequest? AutoControl { get; init; }
}
public class EsppSchValueRequest
public record EsppSchValueRequest
{
public Guid TypeValueId { get; set; }
public Guid TypeValueId { get; init; }
public Guid TypeConfigId { get; set; }
public Guid TypeConfigId { get; init; }
}
public class DistributionConfigRequest
public record DistributionConfigRequest
{
public Guid DistributionPeriodId { get; set; }
public Guid DistributionPeriodId { get; init; }
/// <summary>
/// Исключать выходные и праздники
/// </summary>
public bool IsExcludeWeekends { get; set; }
public bool IsExcludeWeekends { get; init; }
/// <summary>
/// Группировать по рабочей группе
/// </summary>
public bool IsGroupingByWorkGroup { get; set; }
public bool IsGroupingByWorkGroup { get; init; }
}
}

View File

@@ -68,12 +68,23 @@
/// </summary>
public ScheduleExcludeTypeCalendarResponse? ScheduleExcludeTypeCalendar { get; set; }
public JobGroupAutoControlResponse? AutoControl { get; set; }
///// <summary>
///// Настройки автораспределения
///// </summary>
//public JobGroupDistributionConfigResponse? DistributionConfig { get; set; }
}
public class JobGroupAutoControlResponse
{
public bool IsEnable { get; set; }
public bool InitUsedTemplateState { get; set; }
public bool InitUsedScheduleState { get; set; }
}
public class JobGroupScheduleResponse
{
public string Timezone { get; set; } = string.Empty;

View File

@@ -2,14 +2,20 @@
namespace PARR.API.Contracts.V1.Responses
{
public class JobGroupTypeResponse
public record JobGroupTypeResponse
{
public Guid Id { get; set; }
public Guid Id { get; init; }
public required JobGroupTypesEnum Code { get; set; }
public required JobGroupTypesEnum Code { get; init; }
public required string Name { get; set; }
public required string Name { get; init; }
public required string Description { get; set; }
public required string Description { get; init; }
public bool IsAllowJobUnitFilter { get; init; }
public bool IsJobGroupAutoControl { get; init; }
public bool IsRelationshipsAllowed { get; init; }
}
}

View File

@@ -36,13 +36,13 @@ namespace PARR.API.Controllers.V1
private readonly ILogger<JobController> logger;
private readonly IMapper mapper;
private readonly IUriService uriService;
private readonly IJobGroupRepository groupService;
private readonly IJobRepository jobService;
private readonly IEsppSchTypeConfigRepository esppConfigService;
//private readonly IValidator<JobGroupRequest> validator;
private readonly IJobGroupTypeRepository jobGroupTypeService;
private readonly IMatchingStatusService matchingStatusService;
private readonly IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService;
private readonly IJobGroupRepository _groupRepository;
private readonly IJobRepository _jobRepository;
private readonly IEsppSchTypeConfigRepository _esppConfigRepository;
private readonly IJobGroupTypeRepository _jobGroupTypeRepository;
private readonly IMatchingStatusService _matchingStatusRepository;
private readonly IScheduleResponseAreaTimeOffsetRepository _scheduleResponseAreaTimeOffsetRepository;
private readonly IJobAutoControlRepository _jobAutoControlRepository;
private readonly IRabbitService mqService;
private readonly MqSettings mqSettings;
@@ -50,13 +50,13 @@ namespace PARR.API.Controllers.V1
ILogger<JobController> logger,
IMapper mapper,
IUriService uriService,
IJobGroupRepository groupService,
IJobRepository jobService,
IEsppSchTypeConfigRepository esppConfigService,
//IValidator<JobGroupRequest> validator,
IJobGroupTypeRepository jobGroupTypeService,
IMatchingStatusService matchingStatusService,
IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService,
IJobGroupRepository groupRepository,
IJobRepository jobRepository,
IEsppSchTypeConfigRepository esppConfigRepository,
IJobGroupTypeRepository jobGroupTypeRepository,
IMatchingStatusService matchingStatusRepository,
IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetRepository,
IJobAutoControlRepository jobAutoControlRepository,
IRabbitService mqService,
MqSettings mqSettings
)
@@ -64,20 +64,20 @@ namespace PARR.API.Controllers.V1
this.logger = logger;
this.mapper = mapper;
this.uriService = uriService;
this.groupService = groupService;
this.jobService = jobService;
this.esppConfigService = esppConfigService;
//this.validator = validator;
this.jobGroupTypeService = jobGroupTypeService;
this.matchingStatusService = matchingStatusService;
this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
_groupRepository = groupRepository;
_jobRepository = jobRepository;
_esppConfigRepository = esppConfigRepository;
_jobGroupTypeRepository = jobGroupTypeRepository;
_matchingStatusRepository = matchingStatusRepository;
_scheduleResponseAreaTimeOffsetRepository = scheduleResponseAreaTimeOffsetRepository;
_jobAutoControlRepository = jobAutoControlRepository;
this.mqService = mqService;
this.mqSettings = mqSettings;
}
/// <summary>
/// Получить список групп заданий на выполнение работ постранично
/// Получить список групп работ постранично
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.JobGroup.GetAll)]
@@ -85,11 +85,12 @@ namespace PARR.API.Controllers.V1
{
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
IQueryable<JobGroup> query = groupService.Get()
IQueryable<JobGroup> query = _groupRepository.Get()
.Include(t => t.GroupType)
.Include(t => t.GroupingUnitField)
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar);
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.AutoControl);
query = query.OrderBy(t => t.GroupName);
@@ -104,7 +105,7 @@ namespace PARR.API.Controllers.V1
.Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod);
var jobGroups = await groupService.GetPage(query, paginationFilter).ToListAsync();
var jobGroups = await _groupRepository.GetPage(query, paginationFilter).ToListAsync();
if (!jobGroups.Any())
return NoContent();
@@ -122,20 +123,21 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Получить группу заданий на выполнение работ по id
/// Получить группу работ по id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.JobGroup.Get)]
public async Task<IActionResult> GetById([FromRoute] Guid id)
{
var jobGroup = await groupService.Get()
var jobGroup = await _groupRepository.Get()
.Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.GroupType)
.Include(t => t.GroupingUnitField)
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.Include(t => t.AutoControl)
.FirstOrDefaultAsync(t => t.Id == id);
if (jobGroup == null)
@@ -149,18 +151,13 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Создать группу заданий на выполнение работ (JobGroup)
/// Создать группу работ (JobGroup)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost(ApiRoutes.JobGroup.Create)]
public async Task<IActionResult> Create([FromBody] JobGroupRequest request)
{
//var resultValidate = await validator.ValidateAsync(request);
//if (!resultValidate.IsValid)
// return BadRequest(new Response(resultValidate.Errors));
var jobGroup = new JobGroup
{
Id = Guid.NewGuid(),
@@ -199,6 +196,22 @@ namespace PARR.API.Controllers.V1
}
#endregion
#region Настройки автоконтроля
// Корректность проверяется в валидаторе
if (request.AutoControl != null)
{
jobGroup.AutoControl = new JobGroupAutoControl
{
InitUsedScheduleState = request.AutoControl.InitUsedScheduleState,
InitUsedTemplateState = request.AutoControl.InitUsedTemplateState,
IsEnable = request.AutoControl.IsEnable,
JobGroupId = jobGroup.Id
};
}
#endregion
//Добавляем настройки планировщика
request.Schedule.ForEach(item =>
{
@@ -210,18 +223,19 @@ namespace PARR.API.Controllers.V1
});
});
if (!await groupService.CreateAsync(jobGroup) || !await groupService.CommitAsync())
if (!await _groupRepository.CreateAsync(jobGroup) || !await _groupRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создании группы заданий на выполнение работ" } }));
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 _groupRepository.Get().Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.GroupType)
.Include(t => t.GroupingUnitField)
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.Include(t => t.AutoControl)
.FirstAsync(t => t.Id == jobGroup.Id);
var locationUri = uriService.GetUri(ApiRoutes.JobGroup.Get, ApiRoutes.JobGroup.getParam, createdJobGroup.Id);
@@ -234,7 +248,7 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Обновить группу заданий на выполнение работ (JobGroup)
/// Обновить группу работ (JobGroup)
/// </summary>
/// <param name="id"></param>
/// <param name="request"></param>
@@ -242,15 +256,11 @@ namespace PARR.API.Controllers.V1
[HttpPut(ApiRoutes.JobGroup.Update)]
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] JobGroupRequest request)
{
//var resultValidate = await validator.ValidateAsync(request);
//if (!resultValidate.IsValid)
// return BadRequest(new Response(resultValidate.Errors));
var orig = await groupService.Get()
var orig = await _groupRepository.Get()
.Include(t => t.Jobs)
.ThenInclude(t => t.Tnk)
.Include(t => t.EsppSchValues)
.Include(t => t.AutoControl)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.FirstOrDefaultAsync(t => t.Id == id);
@@ -309,12 +319,50 @@ namespace PARR.API.Controllers.V1
// удаляем настройки распределения если они были
if (orig.DistributionConfig != null)
{
groupService.DeleteDistributionConfig(orig.DistributionConfig);
_groupRepository.DeleteDistributionConfig(orig.DistributionConfig);
}
}
#endregion
#region Настройки автоконтроля
// валидатор проверяет корректность
if (request.AutoControl != null)
{
// автоконтролем управляет JobGroup
if (orig.AutoControl != null)
{
// обновляем
orig.AutoControl.IsEnable = request.AutoControl.IsEnable;
orig.AutoControl.InitUsedScheduleState = request.AutoControl.InitUsedScheduleState;
orig.AutoControl.InitUsedTemplateState = request.AutoControl.InitUsedTemplateState;
// удалить настройки автоконтроля для job
await RemoveJobAutoControlSettingsAsync(orig.Id);
}
else
{
// создаем новую запись
orig.AutoControl = new JobGroupAutoControl
{
InitUsedScheduleState = request.AutoControl.InitUsedScheduleState,
InitUsedTemplateState = request.AutoControl.InitUsedTemplateState,
IsEnable = request.AutoControl.IsEnable,
JobGroupId = orig.Id
};
// удалить настройки автоконтроля для job
await RemoveJobAutoControlSettingsAsync(orig.Id);
}
}
else
{
// автоконтролем управляет каждый job отдельно
// удаляем настройки, если они были
orig.AutoControl = null;
}
#endregion
//обновляем планировщик
orig.EsppSchValues.Clear();
request.Schedule.ForEach(item =>
@@ -327,7 +375,7 @@ namespace PARR.API.Controllers.V1
});
});
if (!await groupService.CommitAsync())
if (!await _groupRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ." } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} обновил группу заданий на выполнение работ: {orig.Id}," +
@@ -355,7 +403,7 @@ namespace PARR.API.Controllers.V1
#endregion
var updatedJobGroup = await groupService.Get()
var updatedJobGroup = await _groupRepository.Get()
.Include(t => t.Jobs)
.ThenInclude(t => t.Tnk)
.Include(t => t.GroupType)
@@ -363,6 +411,7 @@ namespace PARR.API.Controllers.V1
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.Include(t => t.AutoControl)
.FirstAsync(t => t.Id == orig.Id);
var response = mapper.Map<JobGroupResponse>(updatedJobGroup);
@@ -373,14 +422,14 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Удалить группу заданий на выполнение работ (только если нет связанных заданий)
/// Удалить группу работ (только если нет связанных работ)
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete(ApiRoutes.JobGroup.Delete)]
public async Task<IActionResult> Delete([FromRoute] Guid id)
{
var jobGroup = await groupService.Get()
var jobGroup = await _groupRepository.Get()
.FirstOrDefaultAsync(t => t.Id == id);
if (jobGroup == null)
@@ -388,13 +437,13 @@ namespace PARR.API.Controllers.V1
Message = $"Ошибка при удалении группы заданий на выполнение работ. Не найдена группа заданий на выполнение работ Id: {id}"
} }));
var jobCount = await jobService.Get().CountAsync(t => t.GroupId == id);
var jobCount = await _jobRepository.Get().CountAsync(t => t.GroupId == id);
if (jobCount > 0)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
Message = $"Ошибка при удалении группы заданий на выполнение работ. С данным группой связаны задания: {jobCount} шт."
} }));
if (!groupService.Delete(jobGroup) || !await groupService.CommitAsync())
if (!_groupRepository.Delete(jobGroup) || !await _groupRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
Message = $"Ошибка при удалении группы заданий на выполнение работ"
} }));
@@ -408,6 +457,22 @@ namespace PARR.API.Controllers.V1
return NoContent();
}
/// <summary>
/// Удалить настройки автоконтроля для связанных Job
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
private async Task RemoveJobAutoControlSettingsAsync(Guid jobGroupId)
{
var jobAutoControlsToRemove = await _jobAutoControlRepository.Get()
.Where(t => t.Job!.GroupId == jobGroupId)
.ToListAsync();
if (!jobAutoControlsToRemove.Any())
return;
_jobAutoControlRepository.RemoveRange(jobAutoControlsToRemove);
}
/// <summary>
/// Проверка, были ли изменения в расписании
@@ -471,7 +536,7 @@ namespace PARR.API.Controllers.V1
/// <returns></returns>
private async Task AppendMissingDataAsync(JobGroupResponse jobGroupResponse)
{
var schedule = await esppConfigService.GetEsppScheduleDtoAsync(jobGroupResponse.Id);
var schedule = await _esppConfigRepository.GetEsppScheduleDtoAsync(jobGroupResponse.Id);
if (schedule == null)
{
@@ -482,14 +547,14 @@ namespace PARR.API.Controllers.V1
var scheduleResponse = new JobGroupScheduleResponse
{
//Timezone = settingsFromDb.ScheduleTimezone,
Timezone = scheduleResponseAreaTimeOffsetService.GetDefault.EsppValue,
Timezone = _scheduleResponseAreaTimeOffsetRepository.GetDefault.EsppValue,
TypeSchedule = mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
Values = mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
};
jobGroupResponse.Schedule = scheduleResponse;
jobGroupResponse.JobsCount = await jobService.Get().CountAsync(t => t.GroupId == jobGroupResponse.Id);
jobGroupResponse.JobsCount = await _jobRepository.Get().CountAsync(t => t.GroupId == jobGroupResponse.Id);
jobGroupResponse.MatchingStatus = await GetMatchingStatusAsync(jobGroupResponse.Id);
}
@@ -506,7 +571,7 @@ namespace PARR.API.Controllers.V1
return null;
// Если есть значение, смотрим, групповой ли тип работ, и если нет, то вернем null
var groupingType = await jobGroupTypeService.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
var groupingType = await _jobGroupTypeRepository.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
if (request.GroupTypeId == groupingType.Id)
{
// это групповой тип работ, все ок
@@ -534,7 +599,7 @@ namespace PARR.API.Controllers.V1
return request.GroupingUnitFieldId;
var groupingType = await jobGroupTypeService.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
var groupingType = await _jobGroupTypeRepository.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
if (request.GroupTypeId == groupingType.Id)
{
@@ -558,7 +623,7 @@ namespace PARR.API.Controllers.V1
/// <returns></returns>
private async Task<MatchingStatusResponse?> GetMatchingStatusAsync(Guid jobGroupId)
{
var statusMatching = await matchingStatusService.GetStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
var statusMatching = await _matchingStatusRepository.GetStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
return mapper.Map<MatchingStatusResponse>(statusMatching);
}

View File

@@ -17,23 +17,29 @@ namespace PARR.API.Controllers.V1
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class JobGroupTypeController : BaseApiController
{
private readonly IJobGroupTypeRepository jobGroupTypeService;
private readonly IJobGroupTypeRepository jobGroupTypeRepository;
private readonly IMapper mapper;
public JobGroupTypeController(
IJobGroupTypeRepository jobGroupTypeService,
IJobGroupTypeRepository jobGroupTypeRepository,
IMapper mapper
)
{
this.jobGroupTypeService = jobGroupTypeService;
this.jobGroupTypeRepository = jobGroupTypeRepository;
this.mapper = mapper;
}
/// <summary>
/// Получить список типов групп работ
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.JobGroupType.GetAll)]
public async Task<IActionResult> GetAll()
{
var query = jobGroupTypeService.Get().OrderBy(t => t.Description);
var query = jobGroupTypeRepository.Get()
.AsNoTracking()
.OrderBy(t => t.Description);
var types = await query.ToListAsync();

View File

@@ -32,7 +32,7 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Получить список всех переменных составляющих
/// Применить шорткод
/// </summary>
/// <returns></returns>
[HttpPost(ApiRoutes.ShortcodeApply.Apply)]

View File

@@ -33,7 +33,7 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Получить список всех переменных составляющих
/// Получить список всех переменных составляющих (список шорткодов)
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.Shortcode.GetAll)]

View File

@@ -379,9 +379,11 @@ namespace PARR.API.MappingProfiles
CreateMap<JobGroup, JobGroupResponse>()
.ForMember(d => d.ScheduleExcludeType, o => o.MapFrom(s => s.ScheduleExcludeType))
.ForMember(d => d.ScheduleExcludeTypeCalendar, o => o.MapFrom(s => s.ScheduleExcludeTypeCalendar));
.ForMember(d => d.ScheduleExcludeTypeCalendar, o => o.MapFrom(s => s.ScheduleExcludeTypeCalendar))
.ForMember(d => d.AutoControl, o => o.MapFrom(s => s.AutoControl));
//.ForMember(d => d.DistributionConfig, o => o.MapFrom(s => s.DistributionConfig));
CreateMap<JobGroupAutoControl, JobGroupAutoControlResponse>();
#endregion

View File

@@ -1,33 +0,0 @@
using FluentValidation;
using PARR.API.Contracts.V1.Requests;
using PARR.Domain.Enums;
namespace PARR.API.Validators
{
public class JobAutoControlRequestValidator : AbstractValidator<JobAutoControlRequest>
{
public JobAutoControlRequestValidator()
{
RuleFor(t => t.EkMasks).Must(items =>
items.Count(t => t.Trim().Length > 0) > 0
).WithMessage("Должна быть указана хотя бы одна маска ЭК");
RuleFor(t => t.EnabledEkStatuses).Must(
items => items.Distinct().Count() == items.Count()
).WithMessage("Статусы ЭК не должны повторяться");
RuleFor(t => t.EnabledEkStatuses).Must(items =>
{
return !items.Any(item => !Enum.IsDefined(typeof(EkStatusEnum), item)) && !items.Any(t => t == 0);
})
.WithMessage($"Допустимые значения: {(int)EkStatusEnum.New} ({EkStatusEnum.New}), " +
$"{(int)EkStatusEnum.Preapre} ({EkStatusEnum.Preapre}), " +
$"{(int)EkStatusEnum.Exploitation} ({EkStatusEnum.Exploitation}), " +
$"{(int)EkStatusEnum.Repair} ({EkStatusEnum.Repair}), " +
$"{(int)EkStatusEnum.Reserve} ({EkStatusEnum.Reserve}), " +
$"{(int)EkStatusEnum.OutOfService} ({EkStatusEnum.OutOfService}), " +
$"{(int)EkStatusEnum.Test} ({EkStatusEnum.Test}), " +
$"{(int)EkStatusEnum.Development} ({EkStatusEnum.Development})");
}
}
}

View File

@@ -12,11 +12,11 @@ namespace PARR.API.Validators
public class JobGroupValidator : AbstractValidator<JobGroupRequest>
{
public JobGroupValidator(
IJobGroupTypeRepository jobGroupTypeService,
IUnitFieldRepository unitFieldService,
IScheduleExcludeTypeRepository scheduleExcludeTypeService,
IScheduleExcludeTypeCalendarRepository scheduleExcludeTypeCalendarService,
IDistributionPeriodRepository distributionPeriodService
IJobGroupTypeRepository jobGroupTypeRepository,
IUnitFieldRepository unitFieldRepository,
IScheduleExcludeTypeRepository scheduleExcludeTypeRepository,
IScheduleExcludeTypeCalendarRepository scheduleExcludeTypeCalendarRepository,
IDistributionPeriodRepository distributionPeriodRepository
)
{
RuleFor(t => t.Name)
@@ -35,7 +35,7 @@ namespace PARR.API.Validators
.NotNull().NotEmpty();
RuleFor(t => t.GroupTypeId)
.MustAsync(async (entity, value, c) => await jobGroupTypeService.GetAsync(value) != null)
.MustAsync(async (entity, value, c) => await jobGroupTypeRepository.GetAsync(value) != null)
.WithMessage("Указан несуществующий Id типа");
//Проверяем существует ли такой GroupingUnitFieldId в unitField
@@ -47,7 +47,7 @@ namespace PARR.API.Validators
return true;
}
return await unitFieldService.GetAsync(value.Value) != null;
return await unitFieldRepository.GetAsync(value.Value) != null;
})
.WithMessage("Указано несуществующий Id поля");
@@ -55,7 +55,7 @@ namespace PARR.API.Validators
RuleFor(t => t.GroupingUnitFieldId)
.MustAsync(async (entity, value, c) =>
{
var groupingJobType = await jobGroupTypeService.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
var groupingJobType = await jobGroupTypeRepository.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
// Если это сгруппированный тип, то у него обязательно должно быть заполнено поле GroupingUnitFieldId
if (entity.GroupTypeId == groupingJobType.Id)
@@ -68,14 +68,14 @@ namespace PARR.API.Validators
RuleFor(t => t.ScheduleExcludeTypeId)
.NotNull()
.NotEmpty()
.MustAsync(async (entity, value, c) => await scheduleExcludeTypeService.GetAsync(value) != null)
.MustAsync(async (entity, value, c) => await scheduleExcludeTypeRepository.GetAsync(value) != null)
.WithMessage("Некорректное значение");
RuleFor(t => t.ScheduleExcludeTypeCalendarId)
.MustAsync(async (entity, value, c) =>
{
// Если выбрано "Нет исключений", то это поле должно быть пустое, иначе, должно быть валидное значение
var type = await scheduleExcludeTypeService.GetAsync(entity.ScheduleExcludeTypeId);
var type = await scheduleExcludeTypeRepository.GetAsync(entity.ScheduleExcludeTypeId);
if (type == null)
return false;
@@ -89,7 +89,7 @@ namespace PARR.API.Validators
if (!value.HasValue)
return false;
return await scheduleExcludeTypeCalendarService.GetAsync(value.Value) != null;
return await scheduleExcludeTypeCalendarRepository.GetAsync(value.Value) != null;
})
.WithMessage("Некорректное значение");
@@ -115,7 +115,7 @@ namespace PARR.API.Validators
if (periodId.HasValue)
{
var exist = await distributionPeriodService.GetAsync(periodId.Value);
var exist = await distributionPeriodRepository.GetAsync(periodId.Value);
return exist != null;
}
@@ -129,7 +129,24 @@ namespace PARR.API.Validators
// если IsResponseAreaTimezone == true, то поле UserTimeZoneOffsetMinutes обязательно.
// если IsResponseAreaTimezone == false, то UserTimeZoneOffsetMinutes должно быть null
return (entity.IsWorkGroupTimezone && value != null) || (!entity.IsWorkGroupTimezone && value == null);
}).WithMessage("Некорректное значение."); ;
}).WithMessage("Некорректное значение.");
RuleFor(t => t.AutoControl)
.MustAsync(async (entity, value, c) =>
{
// Автоконтроль разрешен только типам работ у которых включен IsJobGroupAutoControl
var isAllowedAutocontrol = await jobGroupTypeRepository.Get().AsNoTracking().AnyAsync(t => t.Id == entity.GroupTypeId && t.IsJobGroupAutoControl == true);
// Разрешен автоконтроль и есть значение
if (isAllowedAutocontrol && value != null)
return true;
// Запрещен автоконтроль и нет значения
if (!isAllowedAutocontrol && value == null)
return true;
return false;
})
.WithMessage("Не верные параметры автоконтроля");
}
}

View File

@@ -5,5 +5,6 @@ namespace PARR.Core.Repositories.Interfaces.Job
public interface IJobAutoControlRepository
{
IQueryable<JobAutoControl> Get();
void RemoveRange(List<JobAutoControl> autoControlList);
}
}

View File

@@ -179,9 +179,9 @@ namespace PARR.DAL.Context
modelBuilder.Entity<JobGroupType>(f =>
{
f.HasData(
new() { Id = new Guid("4FA62E79-86BB-47C2-BE1A-72A716A170FA"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Simple.ToString(), Code = JobGroupTypesEnum.Simple, Description = "Обычный", IsAllowJobUnitFilter = true, IsJobGroupAutoControl = false },
new() { Id = new Guid("6EC58B1A-5C40-47B9-B036-4FA490E8D503"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Umbrella.ToString(), Code = JobGroupTypesEnum.Umbrella, Description = "Зонтик", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true },
new() { Id = new Guid("318625E5-F833-436A-99DF-2A382A1E71C7"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Group.ToString(), Code = JobGroupTypesEnum.Group, Description = "Сгруппированный", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true }
new() { Id = new Guid("4FA62E79-86BB-47C2-BE1A-72A716A170FA"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Simple.ToString(), Code = JobGroupTypesEnum.Simple, Description = "Обычный", IsAllowJobUnitFilter = true, IsJobGroupAutoControl = false, IsRelationshipsAllowed = false },
new() { Id = new Guid("6EC58B1A-5C40-47B9-B036-4FA490E8D503"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Umbrella.ToString(), Code = JobGroupTypesEnum.Umbrella, Description = "Зонтик", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true, IsRelationshipsAllowed = true },
new() { Id = new Guid("318625E5-F833-436A-99DF-2A382A1E71C7"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Group.ToString(), Code = JobGroupTypesEnum.Group, Description = "Сгруппированный", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true, IsRelationshipsAllowed = true }
);
});
#endregion

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PARR.DAL.Migrations
{
/// <inheritdoc />
public partial class tblGroupTypesAddRelationshipsSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsRelationshipsAllowed",
schema: "jobGroup",
table: "GroupTypes",
type: "boolean",
nullable: false,
defaultValue: false,
comment: "Разрешена настройка кол-ва связей");
migrationBuilder.UpdateData(
schema: "jobGroup",
table: "GroupTypes",
keyColumn: "Id",
keyValue: new Guid("318625e5-f833-436a-99df-2a382a1e71c7"),
column: "IsRelationshipsAllowed",
value: true);
migrationBuilder.UpdateData(
schema: "jobGroup",
table: "GroupTypes",
keyColumn: "Id",
keyValue: new Guid("4fa62e79-86bb-47c2-be1a-72a716a170fa"),
column: "IsRelationshipsAllowed",
value: false);
migrationBuilder.UpdateData(
schema: "jobGroup",
table: "GroupTypes",
keyColumn: "Id",
keyValue: new Guid("6ec58b1a-5c40-47b9-b036-4fa490e8d503"),
column: "IsRelationshipsAllowed",
value: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsRelationshipsAllowed",
schema: "jobGroup",
table: "GroupTypes");
}
}
}

View File

@@ -599,6 +599,10 @@ namespace PARR.DAL.Migrations
.HasColumnType("boolean")
.HasComment("Автоконтролем управляет JobGroup? true - да JobGroup, false - Job. Влияет на интерфейс и на логику работы автоконтроля.");
b.Property<bool>("IsRelationshipsAllowed")
.HasColumnType("boolean")
.HasComment("Разрешена настройка кол-ва связей");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
@@ -619,6 +623,7 @@ namespace PARR.DAL.Migrations
Description = "Обычный",
IsAllowJobUnitFilter = true,
IsJobGroupAutoControl = false,
IsRelationshipsAllowed = false,
Name = "Simple"
},
new
@@ -629,6 +634,7 @@ namespace PARR.DAL.Migrations
Description = "Зонтик",
IsAllowJobUnitFilter = false,
IsJobGroupAutoControl = true,
IsRelationshipsAllowed = true,
Name = "Umbrella"
},
new
@@ -639,6 +645,7 @@ namespace PARR.DAL.Migrations
Description = "Сгруппированный",
IsAllowJobUnitFilter = false,
IsJobGroupAutoControl = true,
IsRelationshipsAllowed = true,
Name = "Group"
});
});

View File

@@ -17,5 +17,10 @@ namespace PARR.DAL.Repositories.Job
{
return dataContext.JobAutoControls;
}
public void RemoveRange(List<JobAutoControl> autoControlList)
{
dataContext.JobAutoControls.RemoveRange(autoControlList);
}
}
}

View File

@@ -39,6 +39,12 @@ namespace PARR.Domain.Entities.JobGroupEntities
[Comment("Автоконтролем управляет JobGroup? true - да JobGroup, false - Job. Влияет на интерфейс и на логику работы автоконтроля.")]
public bool IsJobGroupAutoControl { get; set; } = false;
/// <summary>
/// Разрешена настройка кол-ва связей
/// </summary>
[Comment("Разрешена настройка кол-ва связей")]
public bool IsRelationshipsAllowed { get; set; } = false;
public ICollection<JobGroup> JobGroups { get; set; } = new HashSet<JobGroup>();
}
}