feat(api): jobGroup - управление автораспределением

This commit is contained in:
Mikhail Trubnikov
2026-01-23 16:18:56 +10:00
parent 9964e3388d
commit 21c957c3ca
13 changed files with 223 additions and 40 deletions

View File

@@ -489,6 +489,11 @@
public const string Distribute = Base + "/distributor/";
}
public static class DistributionPeriod
{
public const string GetAll = Base + "/distribution-periods/";
}
#endregion
#region SyncTask

View File

@@ -27,7 +27,12 @@
public Guid? ScheduleExcludeTypeCalendarId { get; set; }
//public bool IsAutoDistributionEnabled { get; set; }
public bool IsAutoDistributionEnabled { get; set; }
/// <summary>
/// Настройки автораспределения
/// </summary>
public DistributionConfigRequest? DistributionConfig { get; set; }
//public bool IsAgent { get; set; }
@@ -46,4 +51,19 @@
public Guid TypeConfigId { get; set; }
}
public class DistributionConfigRequest
{
public Guid DistributionPeriodId { get; set; }
/// <summary>
/// Исключать выходные и праздники
/// </summary>
public bool IsExcludeWeekends { get; set; }
/// <summary>
/// Группировать по рабочей группе
/// </summary>
public bool IsGroupingByWorkGroup { get; set; }
}
}

View File

@@ -0,0 +1,52 @@
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Constants;
using PARR.DAL.Services.Interfaces;
namespace PARR.API.Controllers.V1
{
/// <summary>
/// Периоды распределения РР
/// </summary>
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class DistributionPeriodController : BaseApiController
{
private readonly IDistributionPeriodService distributionPeriodService;
private readonly IMapper mapper;
public DistributionPeriodController(
IDistributionPeriodService distributionPeriodService,
IMapper mapper
)
{
this.distributionPeriodService = distributionPeriodService;
this.mapper = mapper;
}
/// <summary>
/// Список периодов распределения
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.DistributionPeriod.GetAll)]
public async Task<IActionResult> GetAll()
{
var periods = await distributionPeriodService.Get()
.OrderBy(t => t.Name)
.ToListAsync();
if (!periods.Any())
return NoContent();
var response = mapper.Map<List<DistributionPeriodResponse>>(periods);
return Ok(new Response<List<DistributionPeriodResponse>>(response, true));
}
}
}

View File

@@ -160,14 +160,28 @@ namespace PARR.API.Controllers.V1
TemplateDuration = request.TemplateDuration.Trim(),
ReferenceDate = request.ReferenceDate,
ScheduleExcludeTypeId = request.ScheduleExcludeTypeId,
ScheduleExcludeTypeCalendarId = request.ScheduleExcludeTypeCalendarId
//IsAutoDistributionEnabled = request.IsAutoDistributionEnabled,
ScheduleExcludeTypeCalendarId = request.ScheduleExcludeTypeCalendarId,
IsAutoDistributionEnabled = request.IsAutoDistributionEnabled,
//IsAgent = request.IsAgent,
//AgentName = request.AgentName,
//AgentTimeOutSec = request.AgentTimeOutSec,
//AgentScript = request.AgentScript
};
#region Если включено автораспределение, добавляем настройки
if (request.IsAutoDistributionEnabled)
{
// на всякий проверим, но вообще это проверяется в валидаторе
if (request.DistributionConfig == null)
{
logger.LogError("Ошибка при создании группы работ '{name}', отсутствуют настройки автораспределения", request.Name);
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создании группы заданий на выполнение работ" } }));
}
jobGroup.DistributionConfig = CreateDistributionConfig(request.DistributionConfig, jobGroup.Id);
}
#endregion
//Добавляем настройки планировщика
request.Schedule.ForEach(item =>
{
@@ -220,6 +234,7 @@ namespace PARR.API.Controllers.V1
.Include(t => t.Jobs)
.ThenInclude(t => t.Tnk)
.Include(t => t.EsppSchValues)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.FirstOrDefaultAsync(t => t.Id == id);
if (orig == null)
@@ -239,12 +254,45 @@ namespace PARR.API.Controllers.V1
orig.ReferenceDate = request.ReferenceDate;
orig.ScheduleExcludeTypeId = request.ScheduleExcludeTypeId;
orig.ScheduleExcludeTypeCalendarId = request.ScheduleExcludeTypeCalendarId;
//orig.IsAutoDistributionEnabled = request.IsAutoDistributionEnabled;
orig.IsAutoDistributionEnabled = request.IsAutoDistributionEnabled;
//orig.IsAgent = request.IsAgent;
//orig.AgentName = request.AgentName;
//orig.AgentTimeOutSec = request.AgentTimeOutSec;
//orig.AgentScript = request.AgentScript;
orig.DateModified = DateTimeOffset.UtcNow;
#region Обновляем настройки автораспределения
if (request.IsAutoDistributionEnabled)
{
if (request.DistributionConfig == null)
{
logger.LogError("Ошибка при изменении группы работ '{name}', отсутствуют настройки автораспределения", request.Name);
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ" } }));
}
// если настройки были, меняем, если не было, создаем
if (orig.DistributionConfig != null)
{
orig.DistributionConfig.DistributionPeriodId = request.DistributionConfig.DistributionPeriodId;
orig.DistributionConfig.IsExcludeWeekends = request.DistributionConfig.IsExcludeWeekends;
orig.DistributionConfig.IsGroupingByWorkGroup = request.DistributionConfig.IsGroupingByWorkGroup;
}
else
{
//создаем
orig.DistributionConfig = CreateDistributionConfig(request.DistributionConfig, orig.Id);
}
}
else
{
// удаляем настройки распределения если они были
if (orig.DistributionConfig != null)
{
groupService.DeleteDistributionConfig(orig.DistributionConfig);
}
}
#endregion
//обновляем планировщик
orig.EsppSchValues.Clear();
@@ -443,5 +491,23 @@ namespace PARR.API.Controllers.V1
return mapper.Map<MatchingStatusResponse>(statusMatching);
}
/// <summary>
/// Создать конфиг распределения
/// </summary>
/// <param name="distributionConfigRequest"></param>
/// <param name="jobGroupId"></param>
/// <returns></returns>
private JobGroupDistributionConfig CreateDistributionConfig(DistributionConfigRequest distributionConfigRequest, Guid jobGroupId)
{
return new JobGroupDistributionConfig
{
GroupId = jobGroupId,
DistributionPeriodId = distributionConfigRequest.DistributionPeriodId,
IsExcludeWeekends = distributionConfigRequest.IsExcludeWeekends,
IsGroupingByWorkGroup = distributionConfigRequest.IsGroupingByWorkGroup
};
}
}
}

View File

@@ -2,6 +2,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1.Requests;
using PARR.DAL.Contracts;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Schedule;
using PARR.DAL.Services.Interfaces.Unit;
@@ -14,7 +15,8 @@ namespace PARR.API.Validators
IJobGroupTypeService jobGroupTypeService,
IUnitFieldService unitFieldService,
IScheduleExcludeTypeService scheduleExcludeTypeService,
IScheduleExcludeTypeCalendarService scheduleExcludeTypeCalendarService
IScheduleExcludeTypeCalendarService scheduleExcludeTypeCalendarService,
IDistributionPeriodService distributionPeriodService
)
{
RuleFor(t => t.Name)
@@ -91,6 +93,35 @@ namespace PARR.API.Validators
})
.WithMessage("Некорректное значение");
RuleFor(t => t.DistributionConfig)
.Must((entity, value, c) =>
{
// если включено автораспределение, должны быть настройки
if (entity.IsAutoDistributionEnabled && value != null)
return true;
// если выкл автораспределение, то валидно
if (!entity.IsAutoDistributionEnabled)
return true;
return false;
}).WithMessage("Отсутствуют настройки автораспределения");
RuleFor(t => t.DistributionConfig)
.MustAsync(async (entity, value, c) =>
{
// если есть настройка периода, проверить что она валидна
var periodId = value?.DistributionPeriodId;
if (periodId.HasValue)
{
var exist = await distributionPeriodService.GetAsync(periodId.Value);
return exist != null;
}
return true;
}).WithMessage("Некорректное значение периода распределения");
}
}