Merge branch 'distributor' into dev

This commit is contained in:
Mikhail Trubnikov
2026-01-22 11:48:06 +10:00
33 changed files with 766 additions and 785 deletions

View File

@@ -3,8 +3,8 @@ using Microsoft.Extensions.Logging;
using PARR.AIHITMainLoader.Models;
using PARR.AIHITMainLoader.Services;
using PARR.AIHITMainLoader.Settings;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace PARR.AIHITMainLoader
@@ -19,6 +19,11 @@ namespace PARR.AIHITMainLoader
private readonly IMqService mqService;
private readonly IServiceProvider serviceProvider;
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
public AihitMainLoader(
ILogger<AihitMainLoader> logger,
IIntervalService intervalService,
@@ -82,7 +87,7 @@ namespace PARR.AIHITMainLoader
var mainData = item.ToMainData();
if (mainData == null) continue;
var json = JsonSerializer.Serialize(mainData);
var json = JsonSerializer.Serialize(mainData, jsonOptions);
currentBatch.Add(json);
// Отправка, если набрали полный пакет

View File

@@ -2,6 +2,6 @@
{
public class DistributeRequest
{
public Guid ApplicationInWorkId { get; set; }
public Guid JobGroupId { get; set; }
}
}

View File

@@ -24,21 +24,21 @@ namespace PARR.API.Controllers.V1
private readonly IClientService clientService;
private readonly ITemplateService templateService;
private readonly IUnitService unitService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly ILogger<AgentTaskController> logger;
public AgentTaskController(
IClientService clientService,
ITemplateService templateService,
IUnitService unitService,
IEsppScheduleTransformService esppScheduleTransformService,
//IEsppScheduleTransformService esppScheduleTransformService,
ILogger<AgentTaskController> logger
)
{
this.clientService = clientService;
this.templateService = templateService;
this.unitService = unitService;
this.esppScheduleTransformService = esppScheduleTransformService;
//this.esppScheduleTransformService = esppScheduleTransformService;
this.logger = logger;
}
@@ -51,82 +51,84 @@ namespace PARR.API.Controllers.V1
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
public async Task<IActionResult> GetByClientIp([FromQuery] AgentTaskGetByIpQuery request)
{
//ПАРР-ДВС-ПТК__ВРТ-DVGD-SDMI-WEB-01-ДВС__ПРОЧЕЕ(РАБОТЫ)
//10.99.253.65
//2023-10-16
var ip = request.Ip ?? clientService.GetClientIp()?.ToString();
return Ok("Метод не реализован");
////ПАРР-ДВС-ПТК__ВРТ-DVGD-SDMI-WEB-01-ДВС__ПРОЧЕЕ(РАБОТЫ)
////10.99.253.65
////2023-10-16
if (string.IsNullOrEmpty(ip))
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Client IP address is null." } }));
//var ip = request.Ip ?? clientService.GetClientIp()?.ToString();
//var date = request.Date ?? DateTimeOffset.UtcNow;
var date = DateTimeOffset.UtcNow;
//if (string.IsNullOrEmpty(ip))
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Client IP address is null." } }));
//Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
////var date = request.Date ?? DateTimeOffset.UtcNow;
//var date = DateTimeOffset.UtcNow;
// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
var units = await unitService.GetWithIncludes().AsNoTracking().Where(t => t.UnitValues.Any(v => v.Field!.AihitName == "IP_АДРЕС" && v.Value!.Value == ip)).ToListAsync();
var templates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Include(t => t.Job)
.ThenInclude(t=>t!.Group)
.ThenInclude(t => t!.EsppSchValues)
.Include(t => t.Unit)
.Where(t => units.Any(u=>u.Id == t.UnitId)
//&& t.ApplicationsInWork!.IsAgent == true//TODO Migration to job
&& t.IsActiveTemplate == true
&& t.IsActiveSchedule == true
//&& t.ApplicationsInWork!.NextRun.DateTime.Date == date.Date.Date
&& t.NextRun.DateTime.Date == date.Date.Date
&& t.RobotConfigurations.All(c => c.TaskStatusCode == (int)TaskStatusEnum.Ok)
&& t.Job!.Group!.EsppSchValues.Any()//.ApplicationsInWork.EsppSchValues.Any()
).ToListAsync();
////Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
if (!templates.Any())
return NoContent();
//// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
//var units = await unitService.GetWithIncludes().AsNoTracking().Where(t => t.UnitValues.Any(v => v.Field!.AihitName == "IP_АДРЕС" && v.Value!.Value == ip)).ToListAsync();
//var templates = await templateService.Get()
// .Include(t => t.RobotConfigurations)
// .Include(t => t.Job)
// .ThenInclude(t=>t!.Group)
// .ThenInclude(t => t!.EsppSchValues)
// .Include(t => t.Unit)
// .Where(t => units.Any(u=>u.Id == t.UnitId)
// //&& t.ApplicationsInWork!.IsAgent == true//TODO Migration to job
// && t.IsActiveTemplate == true
// && t.IsActiveSchedule == true
// //&& t.ApplicationsInWork!.NextRun.DateTime.Date == date.Date.Date
// && t.NextRun.DateTime.Date == date.Date.Date
// && t.RobotConfigurations.All(c => c.TaskStatusCode == (int)TaskStatusEnum.Ok)
// && t.Job!.Group!.EsppSchValues.Any()//.ApplicationsInWork.EsppSchValues.Any()
// ).ToListAsync();
var response = new AgentTaskMinResponse
{
Scheduled = new List<AgentTaskMinScheduleResponse>()
};
//if (!templates.Any())
// return NoContent();
foreach (var template in templates)
{
//var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
//var response = new AgentTaskMinResponse
//{
// Scheduled = new List<AgentTaskMinScheduleResponse>()
//};
if (!templateSchedule.Any())
{
logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
$"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
continue;
}
//foreach (var template in templates)
//{
// //var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
// var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
{
logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
$"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
continue;
}
// if (!templateSchedule.Any())
// {
// logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
// $"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
// continue;
// }
templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
{
Name = template.Job.Group.AgentName ?? "",
Script = template.Job.Group.AgentScript ?? "",
StartAt = item,
TemplateId = template.Id
}));
}
// if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
// {
// logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
// $"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
// continue;
// }
if (!response.Scheduled.Any())
return NoContent();
// templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
// {
// Name = template.Job.Group.AgentName ?? "",
// Script = template.Job.Group.AgentScript ?? "",
// StartAt = item,
// TemplateId = template.Id
// }));
//}
response.Scheduled = response.Scheduled.OrderBy(t => t.StartAt).ToList();
//if (!response.Scheduled.Any())
// return NoContent();
logger.LogInformation($"Агент с IP-адресом {ip} получил задания: [{string.Join(';', response.Scheduled.Select(s => $"StartAt:{s.StartAt}, Name:{s.Name}, TemplateId:{s.TemplateId}"))}]");
//response.Scheduled = response.Scheduled.OrderBy(t => t.StartAt).ToList();
return Ok(response);
//logger.LogInformation($"Агент с IP-адресом {ip} получил задания: [{string.Join(';', response.Scheduled.Select(s => $"StartAt:{s.StartAt}, Name:{s.Name}, TemplateId:{s.TemplateId}"))}]");
//return Ok(response);
}
}

View File

@@ -5,10 +5,13 @@ using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace PARR.API.Controllers.V1
@@ -22,21 +25,24 @@ namespace PARR.API.Controllers.V1
private readonly IMqService mqService;
private readonly MqSettings mqSettings;
private readonly IValidator<DistributeRequest> validator;
private readonly IClientService clientService;
public DistributorController(
IMqService mqService,
MqSettings mqSettings,
IValidator<DistributeRequest> validator
IValidator<DistributeRequest> validator,
IClientService clientService
)
{
this.mqService = mqService;
this.mqSettings = mqSettings;
this.validator = validator;
this.clientService = clientService;
}
/// <summary>
/// Перераспределить шаблоны для регламентной работы
/// Перераспределить шаблоны для группы работ
/// </summary>
/// <returns></returns>
[HttpPost(ApiRoutes.Distributor.Distribute)]
@@ -48,17 +54,28 @@ namespace PARR.API.Controllers.V1
var requestToMq = new TemplateDistributorMq
{
ApplicationInWorkId = request.ApplicationInWorkId
JobGroupId = request.JobGroupId,
Initiator = new HistoryInitiator
{
InitiatorComment = "Через API отправлен запрос на распределение шаблонов",
InitiatorIp = clientService.GetClientIp()?.ToString(),
InitiatorParrComponentId = ParrComponentsEnum.Api
}
};
var msg = JsonSerializer.Serialize(requestToMq);
//var jsonOptions = new JsonSerializerOptions
//{
// Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
//};
//var msg = JsonSerializer.Serialize(requestToMq, jsonOptions);
var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new[] { msg });
//var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new[] { msg });
var sendResult = await mqService.SendAsync(mqSettings.TemplateDistributor, new List<object> { requestToMq });
if (sendResult.IsSuccess)
return Created("", new Response<string?>(null, true, new List<ErrorModel>(), "Отправлен запрос на перераспределение регламентных работ."));
else
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message="Ошибка при отправке данных."} }));
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при отправке данных." } }));
}
}

View File

@@ -72,9 +72,10 @@ namespace PARR.API.Controllers.V1
HistoryInitiator = new HistoryInitiator { InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }
};
var msg = JsonSerializer.Serialize(obj);
//var msg = JsonSerializer.Serialize(obj);
var _result = await mqService.SendAsync(mqSettings.GenerateTemplates, new[] { msg });
//var _result = await mqService.SendAsync(mqSettings.GenerateTemplates, new[] { msg });
var _result = await mqService.SendAsync(mqSettings.GenerateTemplates, new List<object> { obj });
if (_result.IsSuccess == false)
result = false;

View File

@@ -641,18 +641,20 @@ namespace PARR.API.Controllers.V1
}
};
var msg = JsonSerializer.Serialize(request);
//var msg = JsonSerializer.Serialize(request);
//var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new[] { msg });
var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new List<object> { request });
var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new[] { msg });
logger.LogDebug("Получен код отпрвки: {IsSuccess}", result.IsSuccess);
if (!result.IsSuccess)
{
logger.LogError($"Ошибка при отправке запроса в очередь на обновление связанных шаблонов, после обновления маски шаблона. {msg}");
logger.LogError($"Ошибка при отправке запроса в очередь на обновление связанных шаблонов, после обновления маски шаблона. {request.ToJson()}");
return false;
}
logger.LogInformation($"После изменения маски шаблона в jobId: {jobId}, отправлен запрос в очередь на переименование связанных шаблонов: {msg}");
logger.LogInformation($"После изменения маски шаблона в jobId: {jobId}, отправлен запрос в очередь на переименование связанных шаблонов: {request.ToJson()}");
return true;
}

View File

@@ -14,6 +14,7 @@ using PARR.DAL.Contracts;
using PARR.DAL.DomainServices.Shortcodes;
using PARR.DAL.DomainServices.Shortcodes.Models;
using PARR.DAL.Models;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;
@@ -25,31 +26,34 @@ namespace PARR.API.Controllers.V1
private readonly IMapper mapper;
private readonly SettingsFromDb settingsFromDb;
private readonly IRobotConfigurationService robotConfigurationService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly ILogger<RobotTaskController> logger;
private readonly IClientService clientService;
private readonly IRobotHistoryService robotHistoryService;
private readonly IShortcodesService shortcodesService;
private readonly INextRunService nextRunService;
public RobotTaskController(
IMapper mapper,
SettingsFromDb settingsFromDb,
IRobotConfigurationService robotConfigurationService,
IEsppScheduleTransformService esppScheduleTransformService,
//IEsppScheduleTransformService esppScheduleTransformService,
ILogger<RobotTaskController> logger,
IClientService clientService,
IRobotHistoryService robotHistoryService,
IShortcodesService shortcodesService
IShortcodesService shortcodesService,
INextRunService nextRunService
)
{
this.mapper = mapper;
this.settingsFromDb = settingsFromDb;
this.robotConfigurationService = robotConfigurationService;
this.esppScheduleTransformService = esppScheduleTransformService;
//this.esppScheduleTransformService = esppScheduleTransformService;
this.logger = logger;
this.clientService = clientService;
this.robotHistoryService = robotHistoryService;
this.shortcodesService = shortcodesService;
this.nextRunService = nextRunService;
}
@@ -306,7 +310,8 @@ namespace PARR.API.Controllers.V1
//пока у нас выключено автораспределение, считает по refDate
//TODO: когда заработает автораспределение, будем думать!!!!!
var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
if (nextRun != template.NextRun)
{

View File

@@ -73,10 +73,11 @@ namespace PARR.API.Controllers.V1
}
};
var msg = JsonSerializer.Serialize(matchTemplateTask);
logger.LogDebug("Подготовлено сообщение: {Message}", new[] { msg });
//var msg = JsonSerializer.Serialize(matchTemplateTask);
//logger.LogDebug("Подготовлено сообщение: {Message}", new[] { msg });
var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new[] { msg });
//var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new[] { msg });
var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new List<object> { matchTemplateTask });
logger.LogDebug("Получен код отпрвки: {IsSuccess}", result.IsSuccess);
if (!result.IsSuccess)

View File

@@ -67,9 +67,10 @@ namespace PARR.API.Controllers.V1
HistoryInitiator = new HistoryInitiator { InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }
};
var msg = JsonSerializer.Serialize(mqRequest);
//var msg = JsonSerializer.Serialize(mqRequest);
var sendResult = await mqService.SendAsync(mqSettings.TemplateActivator, new[] { msg });
//var sendResult = await mqService.SendAsync(mqSettings.TemplateActivator, new[] { msg });
var sendResult = await mqService.SendAsync(mqSettings.TemplateActivator, new List<object> { mqRequest });
if (!sendResult.IsSuccess)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при отправке данных." } }));

View File

@@ -25,7 +25,7 @@ namespace PARR.API.Controllers.V1
public class TestController : BaseApiController
{
private readonly IClientService clientService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly IRedisCacheService redisCacheService;
private readonly IWeekendDayService weekendDayService;
private readonly IUnitService unitService;
@@ -37,7 +37,7 @@ namespace PARR.API.Controllers.V1
public TestController(
IClientService clientService,
IEsppScheduleTransformService esppScheduleTransformService,
//IEsppScheduleTransformService esppScheduleTransformService,
IRedisCacheService redisCacheService,
IWeekendDayService weekendDayService,
IUnitService unitService,
@@ -49,7 +49,7 @@ namespace PARR.API.Controllers.V1
)
{
this.clientService = clientService;
this.esppScheduleTransformService = esppScheduleTransformService;
//this.esppScheduleTransformService = esppScheduleTransformService;
this.redisCacheService = redisCacheService;
this.weekendDayService = weekendDayService;
this.unitService = unitService;
@@ -76,32 +76,32 @@ namespace PARR.API.Controllers.V1
}
/// <summary>
/// Получить следующую дату запуска
/// </summary>
/// <param name="applicationInWorkId"></param>
/// <param name="lastRunDate"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
{
var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
return Ok(result);
}
///// <summary>
///// Получить следующую дату запуска
///// </summary>
///// <param name="applicationInWorkId"></param>
///// <param name="lastRunDate"></param>
///// <returns></returns>
//[HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
//public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
//{
// var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
// return Ok(result);
//}
/// <summary>
/// Получить следующее расписание
/// </summary>
/// <param name="applicationInWorkId"></param>
/// <param name="lastRunDate"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.Test.GetNextSchedule)]
public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
{
var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
return Ok(result);
}
///// <summary>
///// Получить следующее расписание
///// </summary>
///// <param name="applicationInWorkId"></param>
///// <param name="lastRunDate"></param>
///// <returns></returns>
//[HttpGet(ApiRoutes.Test.GetNextSchedule)]
//public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
//{
// var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
// return Ok(result);
//}
/// <summary>

View File

@@ -1,24 +1,27 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1.Requests;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
namespace PARR.API.Validators
{
public class DistributeRequestValidator : AbstractValidator<DistributeRequest>
{
private readonly IApplicationsInWorkService applicationsInWorkService;
public DistributeRequestValidator(IApplicationsInWorkService applicationsInWorkService)
public DistributeRequestValidator(IJobGroupService jobGroupService)
{
this.applicationsInWorkService = applicationsInWorkService;
RuleFor(t => t.ApplicationInWorkId).NotEmpty().MustAsync(async (entity, value, c) =>
RuleFor(t => t.JobGroupId).NotEmpty().MustAsync(async (entity, value, c) =>
{
var appInWork = await applicationsInWorkService.GetAsync(value);
return appInWork != null;
return await jobGroupService.Get().FirstOrDefaultAsync(t => t.Id == value) != null;
}).WithMessage("Недопустимое значение");
RuleFor(t => t.JobGroupId).NotEmpty().MustAsync(async (entity, value, c) =>
{
var jobGroup = await jobGroupService.Get()
.Include(t => t.DistributionConfig)
.FirstOrDefaultAsync(t => t.Id == value);
return jobGroup != null && jobGroup.IsAutoDistributionEnabled && jobGroup.DistributionConfig != null;
}).WithMessage("Отсутствуют настройки автораспределения");
}
}
}

View File

@@ -1,10 +1,14 @@
namespace PARR.BLL.Domain.Mq
using PARR.Common.Domain;
namespace PARR.BLL.Domain.Mq
{
/// <summary>
/// Модель в MQ, обновления расписаний шаблонов связанных с РР (для TemplateDistributor)
/// Модель в MQ, распределить шаблоны для JobGroupId (для TemplateDistributor)
/// </summary>
public class TemplateDistributorMq
{
public Guid ApplicationInWorkId { get; set; }
public Guid JobGroupId { get; set; }
public required HistoryInitiator Initiator { get; set; }
}
}

View File

@@ -5,6 +5,8 @@ using PARR.BLL.Services.Interfaces;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace PARR.BLL.Services.Implementations
{
@@ -17,6 +19,11 @@ namespace PARR.BLL.Services.Implementations
// реализация для RabbitMQ.Client 7.1.2
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
public MqServiceV2(ILogger<MqServiceV2> logger)
{
this.logger = logger;
@@ -108,6 +115,12 @@ namespace PARR.BLL.Services.Implementations
}
}
public async Task<MqSendResult> SendAsync(IMqSettings mqSettings, List<object> msgObjectList)
{
var msgStringList = msgObjectList.Select(t => JsonSerializer.Serialize(t, jsonOptions)).ToArray();
return await SendAsync(mqSettings, msgStringList);
}
public async Task<MqSendResult> SendAsync(IMqSettings mqSettings, string[] msgList)
{
@@ -136,7 +149,8 @@ namespace PARR.BLL.Services.Implementations
props.DeliveryMode = DeliveryModes.Persistent;
//время жизни, мс
//props.Expiration = "60000";
props.ContentType = "text/plain";//"application/json";
//props.ContentType = "text/plain";//"application/json";
props.ContentType = "text/plain; charset=utf-8";//"application/json";
channel.BasicReturnAsync += async (sender, ea) =>
{

View File

@@ -8,6 +8,22 @@ namespace PARR.BLL.Services.Interfaces
public interface IMqService : IAsyncDisposable // IDisposable
{
Task<bool> InitConsumerAsync(IMqSettings mqSettings, MqMessageHandlerDelegate messageHandler);
/// <summary>
/// Отправить сообщение в очередь используя список строк
/// !!! Избавиться от этого метода, вместо него использовать со списком объектов !!!
/// </summary>
/// <param name="mqSettings"></param>
/// <param name="msgList"></param>
/// <returns></returns>
Task<MqSendResult> SendAsync(IMqSettings mqSettings, string[] msgList);
/// <summary>
/// Отправить сообщение в очередь используя список объектов
/// </summary>
/// <param name="mqSettings"></param>
/// <param name="msgObjectList"></param>
/// <returns></returns>
Task<MqSendResult> SendAsync(IMqSettings mqSettings, List<object> msgObjectList);
}
}

View File

@@ -1,4 +1,6 @@
namespace PARR.DAL.NextRunServices
using PARR.DAL.NextRunServices.Models;
namespace PARR.DAL.NextRunServices
{
public interface INextRunService
{
@@ -7,24 +9,32 @@
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task<List<(Guid TemplateId, DateTimeOffset NextRun)>> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId);
Task<List<TemplateNextRunResultDto>?> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId);
///// <summary>
///// Получить NextRun по jobGroupId с расписанием ЕСПП
///// </summary>
///// <param name="jobGroupId"></param>
///// <returns></returns>
//Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId);
/// <summary>
/// Получить NextRun по jobGroupId с расписанием ЕСПП
/// Получить nextRun для создаваемого шаблона, которого еще нет в БД
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId);
Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId);
/// <summary>
/// Получить NextRun по id шаблона
/// Получить NextRun по id существующего шаблона
/// </summary>
/// <param name="templateId"></param>
/// <param name="isNew">Новый шаблон или шаблон переведенный из unused</param>
/// <param name="isNew">Шаблон переведенный из unused</param>
/// <returns></returns>
Task<DateTimeOffset> GetNextRunForTemplate(Guid templateId, bool isNew);
Task<DateTimeOffset> GetNextRunForTemplateAsync(Guid templateId, bool isNew);
}
}

View File

@@ -0,0 +1,5 @@
namespace PARR.DAL.NextRunServices.Models
{
internal record TemplateWithWorkGroupDto(Guid Id, DateTimeOffset? NextRun, string WorkGroup);
}

View File

@@ -1,6 +1,10 @@

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Constants;
using PARR.DAL.DomainServices.Shortcodes;
using PARR.DAL.Models;
using PARR.DAL.Models.Job;
using PARR.DAL.NextRunServices.Models;
using PARR.DAL.NextRunServices.Subservices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
@@ -15,13 +19,15 @@ namespace PARR.DAL.NextRunServices
private readonly IJobGroupService jobGroupService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly ITemplateDistributor templateDistributor;
private readonly IShortcodesService shortcodesService;
public NextRunService(
ILogger<NextRunService> logger,
ITemplateService templateService,
IJobGroupService jobGroupService,
IEsppScheduleTransformService esppScheduleTransformService,
ITemplateDistributor templateDistributor
ITemplateDistributor templateDistributor,
IShortcodesService shortcodesService
)
{
this.logger = logger;
@@ -29,20 +35,121 @@ namespace PARR.DAL.NextRunServices
this.jobGroupService = jobGroupService;
this.esppScheduleTransformService = esppScheduleTransformService;
this.templateDistributor = templateDistributor;
this.shortcodesService = shortcodesService;
}
public async Task<List<(Guid TemplateId, DateTimeOffset NextRun)>> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId)
public async Task<List<TemplateNextRunResultDto>?> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId)
{
//TODO:
throw new NotImplementedException();
//var ditributedTemplateList = await templateDistributor.DistributeTemplatesAsync();
logger.LogInformation("Начинаю распределять шаблоны для группы работ {gobGroupId}", jobGroupId);
var jobGroup = await jobGroupService.Get()
.Include(t => t.DistributionConfig)
.ThenInclude(t => t.DistributionPeriod)
.AsNoTracking()
.FirstOrDefaultAsync(t => t.Id == jobGroupId);
if (jobGroup == null)
{
logger.LogError("Не найдена группа работа с id: {id}", jobGroupId);
return null;
}
if (!jobGroup.IsAutoDistributionEnabled || jobGroup.DistributionConfig == null)
{
logger.LogError("Группа работ id: {id} не подходит для автораспределения, у нее или отсутствуют настройки или не включено автораспределение. IsAutoDistributionEnabled: {IsAutoDistributionEnabled}. Есть конфиг: {DistributionConfig}", jobGroupId, jobGroup.IsAutoDistributionEnabled, jobGroup.DistributionConfig != null);
return null;
}
logger.LogInformation("Параметры распределения. groupId: {groupId}, name: {groupName}, referenceDate: {referenceDate}, " +
"distributionPeriodName: {distributionPeriodName}, distributionPeriodDuration: {distributionPeriodDuration}, " +
"distributionPeriodType: {distributionPeriodType}, IsExcludeWeekends: {IsExcludeWeekends}, IsGroupingByWorkGroup: {IsGroupingByWorkGroup}",
jobGroupId, jobGroup.GroupName, jobGroup.ReferenceDate, jobGroup.DistributionConfig.DistributionPeriod.Name, jobGroup.DistributionConfig.DistributionPeriod.Duration, jobGroup.DistributionConfig.DistributionPeriod.Type,
jobGroup.DistributionConfig.IsExcludeWeekends, jobGroup.DistributionConfig.IsGroupingByWorkGroup
);
var duration = GetDurationDays(jobGroup.DistributionConfig);
var dateStart = GetDateStart(jobGroup.ReferenceDate);
var allTemplates = await templateService.Get()
.Include(t => t.Job)
.Where(t => t.Job!.GroupId == jobGroupId)
.AsNoTracking()
.ToListAsync();
if (!allTemplates.Any())
{
logger.LogInformation("В группе c ИД {jobGroupId} отсутствуют шаблоны", jobGroupId);
return null;
}
logger.LogDebug("Всего шаблонов для распределения: {count} шт.", allTemplates.Count);
var result = new List<TemplateNextRunResultDto>();
if (jobGroup.DistributionConfig.IsGroupingByWorkGroup)
{
// Нужно группировать по РГ
// список шаблонов с полученной из шорткода РГ
var templatesWithWorkGroup = new List<TemplateWithWorkGroupDto>();
foreach (var template in allTemplates)
{
var workGroupName = await shortcodesService.ApplyShortcodesAsync(template.Job!.WorkGroupMask, template);
templatesWithWorkGroup.Add(new TemplateWithWorkGroupDto(template.Id, template.NextRun, workGroupName));
}
var grouping = templatesWithWorkGroup.GroupBy(t => t.WorkGroup);
//распределяем
foreach (var workGroupTemplates in grouping)
{
logger.LogInformation("Начинаю распределять шаблоны для рабочей группы: {workGroup}. Всего шаблонов: {countTemplates} шт.", workGroupTemplates.Key, workGroupTemplates.Count());
var templatesForDistribute = workGroupTemplates.Select(t => new TemplateNextRunDto(t.Id, t.NextRun)).ToList();
var distributedResult = await templateDistributor.DistributeTemplatesAsync(dateStart, duration, jobGroup.ReferenceDate, templatesForDistribute, jobGroup.DistributionConfig.IsExcludeWeekends);
result.AddRange(distributedResult);
}
}
else
{
// Не нужна группировка по РГ
// сразу распределяем все шаблоны
var templatesForDistribute = allTemplates.Select(t => new TemplateNextRunDto(t.Id, t.NextRun)).ToList();
result = await templateDistributor.DistributeTemplatesAsync(dateStart, duration, jobGroup.ReferenceDate, templatesForDistribute, jobGroup.DistributionConfig.IsExcludeWeekends);
}
logger.LogInformation("Завершено распределение шаблонов для группы {jobGroupId}. Всего распределено шаблонов: {count} шт.", jobGroupId, result.Count);
return result;
}
public async Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId)
//public async Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId)
//{
// var jobGroup = await jobGroupService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Id == jobGroupId);
// if (jobGroup == null)
// {
// logger.LogError("Не найдена группа работ с Id: {jobGroupId}.", jobGroupId);
// throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
// }
// // Берем из обычного расписания ЕСПП
// return await esppScheduleTransformService.GetNextDateAsync(jobGroupId, jobGroup.ReferenceDate);
//}
public async Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId)
{
var jobGroup = await jobGroupService.Get().AsNoTracking().FirstOrDefaultAsync(t => t.Id == jobGroupId);
// определяю это автораспределение или нет, вызываю соответствующий рассчет
var jobGroup = await jobGroupService.Get()
.Include(t => t.DistributionConfig)
.ThenInclude(t => t.DistributionPeriod)
.AsNoTracking()
.FirstOrDefaultAsync(t => t.Id == jobGroupId);
if (jobGroup == null)
{
@@ -50,36 +157,152 @@ namespace PARR.DAL.NextRunServices
throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
}
// Берем из обычного расписания ЕСПП
return await esppScheduleTransformService.GetNextDateAsync(jobGroupId, jobGroup.ReferenceDate);
if (jobGroup.IsAutoDistributionEnabled)
{
// тут автораспределение
if (jobGroup.DistributionConfig == null)
{
logger.LogError("Для группы работ {jobGroupId}, указано автораспределение, но отсутствует конфиг в таблице {GroupDistributionConfigs}", jobGroupId, nameof(JobGroupDistributionConfig));
throw new ArgumentNullException(nameof(JobGroupDistributionConfig), $"Для jobGroupId: {jobGroupId} отсутствует конфигурация автораспределения в таблице {nameof(JobGroupDistributionConfig)}");
}
#region Вынести в одтельный метод, почти все повторяется
var dateStart = GetDateStart(jobGroup.ReferenceDate);
var duration = GetDurationDays(jobGroup.DistributionConfig);
var result = await templateDistributor.GetValidNextRunForTemplateAsync(dateStart,
duration,
jobGroup.ReferenceDate,
new TemplateNextRunDto(Guid.Empty, null),
//TODO: тут пока не получаем список шаблонов, но позже, когда будем строить каждый раз план, нужно будет сюда передавать список связанных шаблонов
new List<TemplateNextRunDto>(),
jobGroup.DistributionConfig.IsExcludeWeekends,
isNew: true
);
#endregion
logger.LogDebug("Получил nextRun {nextRun} по jobGroupId {jobGroupId} для нового шаблона, тип расписания: автораспределение", result.NextRun, jobGroupId);
return result.NextRun;
}
else
{
// тут расписание ЕСПП
var nextRun = await esppScheduleTransformService.GetNextDateAsync(jobGroup.Id, jobGroup.ReferenceDate);
logger.LogDebug("Получил nextRun {nextRun} по jobGroupId {jobGroupId}, тип расписания ЕСПП", nextRun, jobGroupId);
return nextRun;
}
}
public async Task<DateTimeOffset> GetNextRunForTemplate(Guid templateId, bool isNew)
public async Task<DateTimeOffset> GetNextRunForTemplateAsync(Guid templateId, bool isNew)
{
var template = await templateService.Get()
.Include(t => t.Job).ThenInclude(t => t.Group)
.Include(t => t.Job)
.ThenInclude(t => t.Group).ThenInclude(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.AsNoTracking()
.FirstOrDefaultAsync(t => t.Id == templateId);
if (template == null)
{
logger.LogError("Не найдена шаблон с Id: {templateId}.", templateId);
throw new ArgumentNullException(nameof(templateId), $"Не найдена шаблон с Id: {templateId}");
logger.LogError("Не найден шаблон с Id: {templateId}.", templateId);
throw new ArgumentNullException(nameof(templateId), $"Не найден шаблон с Id: {templateId}");
}
if (template.Job!.Group!.IsAutoDistributionEnabled == true)
{
// включено автораспределение
//TODO: !!!!!!!!!!!!!!!! добавить метод рассчета с учетом распределения
throw new NotImplementedException();
//return await templateDistributor.GetValidNextRunForTemplateAsync();
if (template.Job!.Group.DistributionConfig == null)
{
logger.LogError("Для шаблона {templateId}, jobGroupId {jobGroupId}, указано автораспределение, но отсутствует конфиг в таблице {GroupDistributionConfigs}", template.Id, template.Job.GroupId, nameof(JobGroupDistributionConfig));
throw new ArgumentNullException(nameof(JobGroupDistributionConfig), $"Для jobGroupId: {template.Job.GroupId} отсутствует конфигурация автораспределения в таблице {nameof(JobGroupDistributionConfig)}");
}
#region Вынести в одтельный метод, почти все повторяется
var dateStart = GetDateStart(template.Job!.Group.ReferenceDate);
var duration = GetDurationDays(template.Job!.Group.DistributionConfig);
var result = await templateDistributor.GetValidNextRunForTemplateAsync(dateStart,
duration,
template.Job.Group.ReferenceDate,
new TemplateNextRunDto(template.Id, template.NextRun),
//TODO: тут пока не получаем список шаблонов, но позже, когда будем строить каждый раз план, нужно будет сюда передавать список связанных шаблонов
new List<TemplateNextRunDto>(),
template.Job.Group.DistributionConfig.IsExcludeWeekends,
isNew
);
#endregion
logger.LogDebug("Получил nextRun {nextRun} по templateId {templateId}, isNew: {isNew}, тип расписания: автораспределение", result.NextRun, templateId, isNew);
return result.NextRun;
}
else
{
// считаем как ЕСПП
return await esppScheduleTransformService.GetNextDateAsync(template.Job.Group.Id, template.Job.Group.ReferenceDate);
var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job.Group.Id, template.Job.Group.ReferenceDate);
logger.LogDebug("Получил nextRun {nextRun} по templateId {templateId}, isNew: {isNew}, тип расписания: ЕСПП", nextRun, templateId, isNew);
return nextRun;
}
}
/// <summary>
/// Получить продолжительность в днях
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
private int GetDurationDays(JobGroupDistributionConfig config)
{
var period = config.DistributionPeriod;
var periodType = period!.Type;
int.TryParse(period.Duration, out var duration);
var periodDays = duration;
if (periodType == DistributionPeriodTypeEnum.Day.ToString())
periodDays = duration;
if (periodType == DistributionPeriodTypeEnum.Month.ToString())
// в месяце 30 дней, duration*30
periodDays = duration * 30;
if (periodType == DistributionPeriodTypeEnum.Year.ToString())
// в году 365 дней, duration*365
periodDays = duration * 365;
logger.LogDebug("Период распределения: {name}, duration: {duration}, type: {type}. Итого в днях: {days}", period.Name, period.Duration, period.Type, periodDays);
if (periodDays == 0)
logger.LogWarning("Период распределения 0 дней. Неверный конфиг распределения в таблице {table}. {name}, duration: {duration}, type: {type}", nameof(DistributionPeriod), period.Name, period.Duration, period.Type);
return periodDays;
}
/// <summary>
/// Получить дату начала распределения
/// </summary>
/// <param name="referenceDate"></param>
/// <returns></returns>
private DateOnly GetDateStart(DateTimeOffset referenceDate)
{
var today = DateTime.UtcNow;
if (today < referenceDate)
return DateOnly.FromDateTime(referenceDate.Date);
else
return DateOnly.FromDateTime(today.Date);
}
}
}

View File

@@ -68,7 +68,7 @@ namespace PARR.DAL.TransformServices
return GetNextDate(esppSchedule, referenceDate);
}
public DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
private DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
{
var nextRun = referenceDate;
@@ -111,62 +111,62 @@ namespace PARR.DAL.TransformServices
}
private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
{
// расписание на оставшееся на сегодня время. его так мало...
referenceDate = referenceDate.UtcDateTime;
var schedules = new List<DateTimeOffset>();
var curTime = referenceDate;
//private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
//{
// // расписание на оставшееся на сегодня время. его так мало...
// referenceDate = referenceDate.UtcDateTime;
// var schedules = new List<DateTimeOffset>();
// var curTime = referenceDate;
//Если ещё не произошло то добавляем расписание, возможно это новое AiW и он ещё ниразу не запускался.
//lastRun это будущее
if (referenceDate >= DateTimeOffset.UtcNow && referenceDate <= DateTimeOffset.UtcNow.EndOfDay())
schedules.Add(referenceDate);
// //Если ещё не произошло то добавляем расписание, возможно это новое AiW и он ещё ниразу не запускался.
// //lastRun это будущее
// if (referenceDate >= DateTimeOffset.UtcNow && referenceDate <= DateTimeOffset.UtcNow.EndOfDay())
// schedules.Add(referenceDate);
while (curTime < DateTimeOffset.UtcNow.EndOfDay())
{
switch (esppSchedule.TypeSchedule.Id)
{
case (int)EsppSchTypeScheduleEnum.Regularly:
curTime = GetNextDateRegularly(esppSchedule.Values, curTime);
break;
case (int)EsppSchTypeScheduleEnum.Weekly:
curTime = GetNextDateWeekly(esppSchedule.Values, curTime);
break;
case (int)EsppSchTypeScheduleEnum.Monthly:
curTime = GetNextDateMonthly(esppSchedule.Values, curTime);
break;
case (int)EsppSchTypeScheduleEnum.Monthly2:
curTime = GetNextDateMonthly2(esppSchedule.Values, curTime);
break;
case (int)EsppSchTypeScheduleEnum.Annually:
curTime = GetNextDateAnnually(esppSchedule.Values, curTime);
break;
case (int)EsppSchTypeScheduleEnum.Annually2:
curTime = GetNextDateAnnually2(esppSchedule.Values, curTime);
break;
}
// while (curTime < DateTimeOffset.UtcNow.EndOfDay())
// {
// switch (esppSchedule.TypeSchedule.Id)
// {
// case (int)EsppSchTypeScheduleEnum.Regularly:
// curTime = GetNextDateRegularly(esppSchedule.Values, curTime);
// break;
// case (int)EsppSchTypeScheduleEnum.Weekly:
// curTime = GetNextDateWeekly(esppSchedule.Values, curTime);
// break;
// case (int)EsppSchTypeScheduleEnum.Monthly:
// curTime = GetNextDateMonthly(esppSchedule.Values, curTime);
// break;
// case (int)EsppSchTypeScheduleEnum.Monthly2:
// curTime = GetNextDateMonthly2(esppSchedule.Values, curTime);
// break;
// case (int)EsppSchTypeScheduleEnum.Annually:
// curTime = GetNextDateAnnually(esppSchedule.Values, curTime);
// break;
// case (int)EsppSchTypeScheduleEnum.Annually2:
// curTime = GetNextDateAnnually2(esppSchedule.Values, curTime);
// break;
// }
schedules.Add(curTime);
}
schedules.RemoveAll(s => s > DateTimeOffset.UtcNow.EndOfDay());
// schedules.Add(curTime);
// }
// schedules.RemoveAll(s => s > DateTimeOffset.UtcNow.EndOfDay());
return schedules.OrderBy(t => t).ToList();
}
// return schedules.OrderBy(t => t).ToList();
//}
public async Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset referenceDate)
{
//TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
//В общем проверить, когда будем тестировать агента, что с датами все ок
var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
var nextSchedule = GetNextSchedule(esppSchedule, referenceDate);
//public async Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset referenceDate)
//{
// //TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
// //В общем проверить, когда будем тестировать агента, что с датами все ок
// var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
// var nextSchedule = GetNextSchedule(esppSchedule, referenceDate);
return nextSchedule;
}
// return nextSchedule;
//}
private async Task<EsppScheduleDto> GetEsppScheduleAsync(Guid jobGroupId)
@@ -429,68 +429,68 @@ namespace PARR.DAL.TransformServices
}
public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
{
var nextRun = lastRun;
//public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
//{
// var nextRun = lastRun;
switch (periodType)
{
case (DistributionPeriodTypeEnum.Day):
nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
break;
case (DistributionPeriodTypeEnum.Month):
nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
break;
case (DistributionPeriodTypeEnum.Year):
nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
break;
}
// switch (periodType)
// {
// case (DistributionPeriodTypeEnum.Day):
// nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
// break;
// case (DistributionPeriodTypeEnum.Month):
// nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
// break;
// case (DistributionPeriodTypeEnum.Year):
// nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
// break;
// }
return nextRunModifierService.GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
}
// return nextRunModifierService.GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
//}
private DateTimeOffset GetPrevDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
{
switch (periodType)
{
case (DistributionPeriodTypeEnum.Day):
return lastRun.AddDays(-ParseInt(distributionPeriod));
//private DateTimeOffset GetPrevDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
//{
// switch (periodType)
// {
// case (DistributionPeriodTypeEnum.Day):
// return lastRun.AddDays(-ParseInt(distributionPeriod));
case (DistributionPeriodTypeEnum.Month):
return lastRun.AddMonths(-ParseInt(distributionPeriod));
// case (DistributionPeriodTypeEnum.Month):
// return lastRun.AddMonths(-ParseInt(distributionPeriod));
case (DistributionPeriodTypeEnum.Year):
return lastRun.AddYears(-ParseInt(distributionPeriod));
}
// case (DistributionPeriodTypeEnum.Year):
// return lastRun.AddYears(-ParseInt(distributionPeriod));
// }
return lastRun;
}
// return lastRun;
//}
public async Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
{
var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
//public async Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
//{
// var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
var currentStartPeriod = referenceDate;
var currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
// var currentStartPeriod = referenceDate;
// var currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
while (!(date >= currentStartPeriod && date < currentEndPeriod))
{
if (date > currentEndPeriod)
{
currentStartPeriod = currentEndPeriod;
currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
}
else
{
currentEndPeriod = currentStartPeriod;
currentStartPeriod = GetPrevDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
}
}
// while (!(date >= currentStartPeriod && date < currentEndPeriod))
// {
// if (date > currentEndPeriod)
// {
// currentStartPeriod = currentEndPeriod;
// currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
// }
// else
// {
// currentEndPeriod = currentStartPeriod;
// currentStartPeriod = GetPrevDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
// }
// }
return DateOnly.FromDateTime(currentStartPeriod.DateTime);
}
// return DateOnly.FromDateTime(currentStartPeriod.DateTime);
//}
private int ParseInt(string value)
@@ -507,12 +507,12 @@ namespace PARR.DAL.TransformServices
}
private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
{
var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
//private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
//{
// var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
return result;
}
// return result;
//}
}
}

View File

@@ -1,20 +1,17 @@
using PARR.Constants;
using PARR.DAL.DomainModels;
namespace PARR.DAL.TransformServices
namespace PARR.DAL.TransformServices
{
/// <summary>
/// Сервис трансформации расписания ЕСПП в дату/расписание
/// </summary>
public interface IEsppScheduleTransformService
{
/// <summary>
/// Получить следующую дату согласно расписания
/// </summary>
/// <param name="esppSchedule"></param>
/// <param name="lastRun"></param>
/// <returns></returns>
DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
///// <summary>
///// Получить следующую дату согласно расписания
///// </summary>
///// <param name="esppSchedule"></param>
///// <param name="lastRun"></param>
///// <returns></returns>
//DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
///// <summary>
///// Получить расписание
@@ -32,31 +29,31 @@ namespace PARR.DAL.TransformServices
/// <returns></returns>
Task<DateTimeOffset> GetNextDateAsync(Guid jobGroupId, DateTimeOffset lastRun);
/// <summary>
/// Получить расписание по jobGroupId
/// </summary>
/// <param name="jobGroupId"></param>
/// <param name="lastRun"></param>
/// <returns></returns>
Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset lastRun);
///// <summary>
///// Получить расписание по jobGroupId
///// </summary>
///// <param name="jobGroupId"></param>
///// <param name="lastRun"></param>
///// <returns></returns>
//Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset lastRun);
/// <summary>
/// Получить следующую дату срабатывания в указанном периоде
/// </summary>
/// <param name="lastRun"></param>
/// <param name="periodType"></param>
/// <param name="distributionPeriod"></param>
/// <returns></returns>
DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod);
///// <summary>
///// Получить следующую дату срабатывания в указанном периоде
///// </summary>
///// <param name="lastRun"></param>
///// <param name="periodType"></param>
///// <param name="distributionPeriod"></param>
///// <returns></returns>
//DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod);
/// <summary>
/// Получить дату начала периода распределения относительно опорной даты (Reference Date)
/// </summary>
/// <param name="jobGroupId"></param>
/// <param name="date"></param>
/// <returns></returns>
Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset refrenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod);
///// <summary>
///// Получить дату начала периода распределения относительно опорной даты (Reference Date)
///// </summary>
///// <param name="jobGroupId"></param>
///// <param name="date"></param>
///// <returns></returns>
//Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset refrenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod);
}
}

View File

@@ -14,11 +14,11 @@ namespace PARR.DAL.TransformServices
/// <returns></returns>
DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun);
/// <summary>
/// Получить РАБОЧИЙ день следующего срабатывания
/// </summary>
/// <param name="nextRun"></param>
/// <returns></returns>
Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun);
///// <summary>
///// Получить РАБОЧИЙ день следующего срабатывания
///// </summary>
///// <param name="nextRun"></param>
///// <returns></returns>
//Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun);
}
}

View File

@@ -29,40 +29,40 @@ namespace PARR.DAL.TransformServices
}
public async Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun)
{
// получаем день относительно часового пояса МСК
var date = DateOnly.FromDateTime(DateResolver.IsCurrentDayRelativeMskTime(nextRun) ? nextRun.Date : nextRun.Date.AddDays(1));
//public async Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun)
//{
// // получаем день относительно часового пояса МСК
// var date = DateOnly.FromDateTime(DateResolver.IsCurrentDayRelativeMskTime(nextRun) ? nextRun.Date : nextRun.Date.AddDays(1));
if (await weekendDayService.IsWorkDayAsync(date, true))
{
//текущий nextRun рабочий день, возвращаем его
return nextRun;
}
// if (await weekendDayService.IsWorkDayAsync(date, true))
// {
// //текущий nextRun рабочий день, возвращаем его
// return nextRun;
// }
// ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
int count = 20;
while (count > 0)
{
date = date.AddDays(1);
var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
if (isWorkDay)
break; // это рабочий день, выбираем его
// // ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
// int count = 20;
// while (count > 0)
// {
// date = date.AddDays(1);
// var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
// if (isWorkDay)
// break; // это рабочий день, выбираем его
count--;
// count--;
if (!isWorkDay && count == 0)
logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
}
// if (!isWorkDay && count == 0)
// logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
// }
// смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
date = date.AddDays(-1);
// // смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
// if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
// date = date.AddDays(-1);
// считаем новый NextRun
var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
// // считаем новый NextRun
// var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
return nextRun.AddDays(dayCount);
}
// return nextRun.AddDays(dayCount);
//}
}
}

View File

@@ -75,17 +75,18 @@ namespace PARR.JobAutoControl
InitiatorIp = null,
InitiatorParrComponentId = Constants.ParrComponentsEnum.JobAutoControl
}
});
}).ToList();
var msgStrList = msgList.Select(t => JsonSerializer.Serialize(t));
//var msgStrList = msgList.Select(t => JsonSerializer.Serialize(t));
// отправляем задания в очередь template matcher`a
var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgStrList.ToArray());
//var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgStrList.ToArray());
var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgList.ToList<object>());
if (!sendResult.IsSuccess)
logger.LogError($"Ошибка при отправке сообщений ({msgStrList.Count()} шт.) в очередь.");
logger.LogError($"Ошибка при отправке сообщений ({msgList.Count()} шт.) в очередь.");
else
logger.LogInformation($"Выполнена отправка сообщений в очередь, {msgStrList.Count()} шт.");
logger.LogInformation($"Выполнена отправка сообщений в очередь, {msgList.Count()} шт.");
}
}

View File

@@ -7,6 +7,7 @@ using PARR.DAL.Contracts;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
using PARR.Master.Settings;
using System.Text.Encodings.Web;
using System.Text.Json;
namespace PARR.Master.Services
@@ -20,6 +21,11 @@ namespace PARR.Master.Services
private readonly MqSettings mqSettings;
private readonly IMqService mqService;
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
public OrderMasterService(
ILogger<OrderMasterService> logger,
IOrderService orderService,
@@ -60,7 +66,7 @@ namespace PARR.Master.Services
//находим наряды где статусы не равны, добавляем их в Rabbit
var ordersWithStatusNotEqual = await GetOrdresWithStatusCodeNotEqualAsync();
var objs = ordersWithStatusNotEqual.Select(t => JsonSerializer.Serialize(new OrderManageMq { OrderId = t.Id }));
var objs = ordersWithStatusNotEqual.Select(t => JsonSerializer.Serialize(new OrderManageMq { OrderId = t.Id }, jsonOptions));
logger.LogInformation($"Ищу наряды где статусы не равны. Найдено нарядов: {ordersWithStatusNotEqual.Count()}. Добавляю их в RabbitMQ.");

View File

@@ -4,10 +4,9 @@ using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.TransformServices;
using PARR.NextRun.Settings;
namespace PARR.NextRun
@@ -41,14 +40,15 @@ namespace PARR.NextRun
using (var scope = serviceProvider.CreateScope())
{
//var appInWorkService = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
//var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
var nextRunService = scope.ServiceProvider.GetService<INextRunService>();
if (templateService == null || esppSchService == null || jobGroupService == null)
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(IEsppScheduleTransformService)} или {nameof(IJobGroupService)}");
if (templateService == null || nextRunService == null || jobGroupService == null)
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}");
await HandlerAsync(templateService, esppSchService, jobGroupService);
await HandlerAsync(templateService, nextRunService, jobGroupService);
}
}, workerSettings.RepeatEvery);
}
@@ -58,7 +58,7 @@ namespace PARR.NextRun
/// Рассчет следующей даты срабатываения
/// </summary>
/// <returns></returns>
private async Task HandlerAsync(ITemplateService templateService, IEsppScheduleTransformService esppScheduleTransformService, IJobGroupService jobGroupService)
private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
{
#region логика для групп у которых не включено автораспределение
@@ -77,7 +77,8 @@ namespace PARR.NextRun
foreach (var group in groups)
{
//получаем по каждой группе следующий nextRun и сравниваем с существующим, если не равны, то обновляем
var nextRun = await esppScheduleTransformService.GetNextDateAsync(group.Id, group.ReferenceDate);
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(group.Id, group.ReferenceDate);
var nextRun = await nextRunService.GetNextRunForTemplateAsync(group.Id, false);
// Загружаем только шаблоны текущей группы где nextRun в БД не равен расчетному
@@ -109,7 +110,7 @@ namespace PARR.NextRun
//todo: когда будет автораспределение, для него придумать логику как считать
//TODO:!!! Написать логику для групп у которых включено автораспределение!!!
#region old logic

View File

@@ -1,22 +1,14 @@
using PARR.DAL.Models;
using PARR.BLL.Domain.Mq;
namespace PARR.TemplateDistributor
{
public interface ITemplateDistributor
{
/// <summary>
/// Формирует расписание запуска для шаблонов относительно одной РР (без сохранения в БД), (реализует оба режима распределения РР)
/// Обновляет NextRun (сохраняет в БД)
/// </summary>
/// <param name="templates"></param>
/// <param name="applicationInWorkId"></param>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task<List<Template>> DistributeTemplateAsync(List<Template> templates, Guid applicationInWorkId, Guid workGroupid);
/// <summary>
/// Обновляет расписание запуска шаблонов по РР (сохраняет в БД)
/// </summary>
/// <param name="applicationInWorkId"></param>
/// <returns></returns>
Task UpdateScheduleAsync(Guid applicationInWorkId);
Task DistributeAsync(TemplateDistributorMq mqResponse);
}
}

View File

@@ -53,9 +53,9 @@ namespace PARR.TemplateDistributor
if (query == null)
return;
if (!await validatorService.IsValidApplicationAndWorksAsync(query.ApplicationInWorkId))
if (!await validatorService.IsValidJobGroupAsync(query.JobGroupId))
{
logger.LogError($"Некорректные параметры регламентной работы {nameof(query.ApplicationInWorkId)}: {query.ApplicationInWorkId}");
logger.LogError("Не корректные параметры группы работ {jobGroupId}. Не буду ничего делать.", query.JobGroupId);
return;
}
@@ -63,10 +63,9 @@ namespace PARR.TemplateDistributor
{
var service = scope.ServiceProvider.GetService<ITemplateDistributor>();
if (service == null)
throw new Exception($"Не найден сервис: {nameof(service.GetType)}");
await service.UpdateScheduleAsync(query.ApplicationInWorkId);
throw new Exception($"Не найден сервис: {nameof(ITemplateDistributor)}");
await service.DistributeAsync(query);
}
}

View File

@@ -2,6 +2,6 @@
{
internal interface IValidatorService
{
Task<bool> IsValidApplicationAndWorksAsync(Guid applicationInWorkId);
Task<bool> IsValidJobGroupAsync(Guid applicationInWorkId);
}
}

View File

@@ -1,7 +1,9 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.DAL.Models.Job;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
namespace PARR.TemplateDistributor.Services
{
@@ -17,32 +19,30 @@ namespace PARR.TemplateDistributor.Services
this.serviceProvider = serviceProvider;
this.logger = logger;
}
public async Task<bool> IsValidApplicationAndWorksAsync(Guid applicationInWorkId)
public async Task<bool> IsValidJobGroupAsync(Guid jobGroupId)
{
using (var scope = serviceProvider.CreateScope())
{
//TODO Migratin to Job
//var service = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
//if (service == null)
// throw new Exception($"Не найден сервис: {nameof(IApplicationsInWorkService)}");
var service = scope.ServiceProvider.GetService<IJobGroupService>();
//var appInWork = await service.Get()//TODO Migratin to Job
// //.Include(aiw => aiw.EsppSchValues)
// .FirstOrDefaultAsync(t => t.Id == applicationInWorkId);
if (service == null)
throw new Exception($"Не найден сервис: {nameof(IJobGroupService)}");
//if (appInWork == null)
//{
// logger.LogError($"Не найдена регалментная работа {nameof(applicationInWorkId)}: {applicationInWorkId}");
// return false;
//}
var jobGroup = await service.Get().Include(t => t.DistributionConfig).FirstOrDefaultAsync(t => t.Id == jobGroupId);
//if (appInWork.IsAutoDistributionEnabled && appInWork.EsppSchValues.Count !=1)
//{
// logger.LogError($"Регалментная работа {nameof(applicationInWorkId)}: {applicationInWorkId} должна иметь только одно значение EsppSchTypeValue" +
// $", соответствующее режиму равномерного распределения по периоду");
// return false;
//}
if (jobGroup == null)
{
logger.LogError($"Не найдена группа работ с Id: {jobGroupId}", jobGroupId);
return false;
}
if (!jobGroup.IsAutoDistributionEnabled || jobGroup.DistributionConfig == null)
{
logger.LogError("Для группы работ {jobGroupId} отсутствуют настройки автораспределения. " +
"IsAutoDistributionEnabled: {IsAutoDistributionEnabled}, есть настройки в таблице {DistributionConfig}, {existConfig}", jobGroupId, jobGroup.IsAutoDistributionEnabled, nameof(JobGroupDistributionConfig), jobGroup.DistributionConfig != null);
return false;
}
return true;
}

View File

@@ -1,438 +1,103 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.BLL.Domain.Mq;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.Contracts;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;
using System.Reflection.Metadata.Ecma335;
namespace PARR.TemplateDistributor
{
internal class TemplateDistributor : ITemplateDistributor
{
private readonly ILogger<TemplateDistributor> logger;
private readonly INextRunService nextRunService;
private readonly ITemplateService templateService;
private readonly IApplicationsInWorkService applicationsInWorkService;
private readonly ICalendarService calendarService;
private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly IWeekendDayService weekendDayService;
private readonly INextRunModifierService nextRunModifierService;
private readonly IRobotConfigurationService robotConfigurationService;
public TemplateDistributor(
ILogger<TemplateDistributor> logger,
INextRunService nextRunService,
ITemplateService templateService,
IApplicationsInWorkService applicationsInWorkService,
ICalendarService calendarService,
IEsppScheduleTransformService esppScheduleTransformService,
IWeekendDayService weekendDayService,
INextRunModifierService nextRunModifierService
IRobotConfigurationService robotConfigurationService
)
{
this.logger = logger;
this.nextRunService = nextRunService;
this.templateService = templateService;
this.applicationsInWorkService = applicationsInWorkService;
this.calendarService = calendarService;
this.esppScheduleTransformService = esppScheduleTransformService;
this.weekendDayService = weekendDayService;
this.nextRunModifierService = nextRunModifierService;
this.robotConfigurationService = robotConfigurationService;
}
public async Task UpdateScheduleAsync(Guid applicationInWorkId)//TODO Migratin to Job
public async Task DistributeAsync(TemplateDistributorMq mqResponse)
{
var appInWork = await applicationsInWorkService.GetAsync(applicationInWorkId);
var jobGroupId = mqResponse.JobGroupId;
var templates = await templateService.Get()
.Include(t => t.Unit)//TODO Migratin to Job
//.ThenInclude(h => h!.WorkGroup)
.Where(t => t.JobId == applicationInWorkId && t.Unit!.BaseFields!.WorkGroup != null)//TODO Migratin to Job
// вызвать метод распределения, и получить новые даты
var distributedTemplates = await nextRunService.GetNextRunForJobGroupWithAutoDistributionAsync(jobGroupId);
if (distributedTemplates == null)
{
logger.LogWarning("При распределении шаблонов по jobGroupId {jobGroupId} вернулся null. Это ошибка. Прекращаю распределение.", jobGroupId);
return;
}
// получить список шаблонов, сравнить их с распределенными, обновить даты, сохранить
var groupTemplates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Where(t => t.Job.GroupId == jobGroupId)
.ToListAsync();
//Группируем шаблоны по рабочим группам
var workGroupsWithTemplates = templates.GroupBy(t => t.Unit!.BaseFields!.WorkGroup);
/*foreach (var workGroupWithTemplates in workGroupsWithTemplates)
if (!groupTemplates.Any())
{
var wgId = (Guid)workGroupWithTemplates.Key!;
var values = workGroupWithTemplates.ToList();
//Обновляем сразу время при необходимости, так как дальше будем работать только с датой
var timesList = values.Select(t => t.NextRun.TimeOfDay).Distinct().ToList();
if (timesList.Count() > 1 || (timesList.Count() == 1 && timesList[0] != appInWork!.ReferenceDate.TimeOfDay))
{
values.ForEach(t =>
{
if (t.NextRun.TimeOfDay != appInWork!.ReferenceDate.TimeOfDay)
t.NextRun = new DateTimeOffset(t.NextRun.Year, t.NextRun.Month, t.NextRun.Day,
appInWork!.ReferenceDate.Hour, appInWork!.ReferenceDate.Minute, appInWork!.ReferenceDate.Second,
new TimeSpan(0, 0, 0));
});
if (!await templateService.CommitAsync())
{
logger.LogError($"Ошибка записи изменений в БД при актуализации времени NextRun шаблонов РР({applicationInWorkId})");
logger.LogWarning("Для jobGroupId {jobGroupId} не найдено ни одного шаблона в БД. Прекращаю обновление.", jobGroupId);
return;
}
// создать словарь для быстрого поиска
var distributedDict = distributedTemplates.ToDictionary(t => t.Id);
int updatedCount = 0;
foreach (var templateDb in groupTemplates)
{
if (distributedDict.TryGetValue(templateDb.Id, out var distributedTemplate))
{
if (templateDb.NextRun != distributedTemplate.NextRun)
{
templateDb.NextRun = distributedTemplate.NextRun;
templateDb.LastRun = distributedTemplate.NextRunOld;
templateDb.DateModified = DateTimeOffset.UtcNow;
// ставим задание роботу - обновить расписания
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, templateDb);
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
updatedCount++;
}
var distrTemplates = await DistributeTemplateAsync(new List<Template>(), applicationInWorkId, wgId);
if (distrTemplates.Any())
if (!await templateService.CommitAsync())
logger.LogError($"Ошибка записи изменений в БД при перераспределении NextRun шаблонов РР({applicationInWorkId})");
}*/
// TODO Migratin to Job
}
public async Task<List<Template>> DistributeTemplateAsync(List<Template> templates, Guid applicationInWorkId, Guid workGroupId)
{
// var appInWork = await applicationsInWorkService.Get()
// .Include(aiw => aiw.EsppSchValues)
// .ThenInclude(esv => esv.EsppSchTypeValue)
// .ThenInclude(etv => etv!.DistributionPeriod)
// .FirstAsync(t => t.Id == applicationInWorkId);
// var refDate = appInWork.ReferenceDate;
// //Проверяем наличие распределения РР на период
// if (appInWork.IsAutoDistributionEnabled)
// {
// var existingTemplates = await templateService.Get()
// .Include(t => t.Unit)
// .Where(t => t.JobId == applicationInWorkId
// //&& t.Host!.WorkGroupId == workGroupId//TODO Migratin to Job
// )
// .ToListAsync();
// //Удалим из входных шаблонов уже существующие в БД (по идее, такого никогда не должно случиться)
// var duplicates = templates.Select(t => t.Id).Where(t => existingTemplates.Any(et => et.Id == t)).ToList();
// if (duplicates.Count > 0)
// {
// duplicates.ForEach(t =>
// {
// logger.LogWarning($"Для распределения AiW({applicationInWorkId}),workGroupId({workGroupId}) передан существующий в базе данных шаблон {t}");
// });
// templates.RemoveAll(t => duplicates.Any(dt => dt == t.Id));
// }
// existingTemplates.AddRange(templates);
// //Если распределенная РР получаем начало
// var period = appInWork.EsppSchValues.First()!.EsppSchTypeValue!.DistributionPeriod;
// var periodType = ParseDistributionPeriodType(period!.Type);
// var workDays = await GetWorkDaysAsync(appInWork);
// var result = new List<Template>();
// //распределяем РР отдельно активированные
// var activatedTemplates = existingTemplates.Where(t => t.IsActiveTemplate && t.IsActiveSchedule).ToList();
// if (activatedTemplates.Count > 0)
// {
// Distribute(ref activatedTemplates, refDate, period, periodType, workDays);
// // result.AddRange(activatedTemplates);
// }
// //распределяем РР отдельно деактивированные
// var deactivatedTemplates = existingTemplates.Where(t =>
// !t.IsActiveTemplate || !t.IsActiveSchedule || (
// !t.IsActiveTemplate && !t.IsActiveSchedule
// )).ToList();
// if (deactivatedTemplates.Count > 0)
// {
// Distribute(ref deactivatedTemplates, refDate, period, periodType, workDays);
// // result.AddRange(deactivatedTemplates);
// }
// if (templates.Any())
// {
// // это была генерация шаблонов, не нужны все шаблоны, нужны только те которые передал для получения NextRun
// result.AddRange(templates);
// }
// else
// {
// // это было распределение шаблонов, добавляем активированные и деактивированные
// result.AddRange(activatedTemplates);
// result.AddRange(deactivatedTemplates);
// }
// return result;
// #region comments
// //var d = new Dictionary<DateOnly, List<Template>>();
// //foreach (var wd in workDays)
// //{
// // var wrokDateTimeOffset = new DateTimeOffset(
// // wd.Year, wd.Month, wd.Day,
// // refDate.Hour, refDate.Minute, refDate.Second,
// // new TimeSpan(0, 0, 0));
// // if (wrokDateTimeOffset < DateTimeOffset.UtcNow)
// // wrokDateTimeOffset = esppScheduleTransformService.GetNextDateForDistributionRun(wrokDateTimeOffset, periodType, period.Duration);
// // var assignedTemplates = existingTemplates.Where(t => t.NextRun == wrokDateTimeOffset).ToList();
// // d.Add(wd, assignedTemplates);
// //}
// //var templatesPerStep = (double)templates.Count() / workDays.Count();//
// //var currentTemplateStep = (int)Math.Ceiling(templatesPerStep);
// //var delta = templatesPerStep - currentTemplateStep;
// ////templates.First().NextRun = currentDay;
// //var templateDistributed = 0;
// ////Отталкиваясь от количества
// //while (templateDistributed < templates.Count())
// //{
// // var wdCounts = d.Select(wd => wd.Value).OrderBy(count => count).ToArray();
// // var templateCountDelta = d.Max(t => t.Value.Count()) - d.Min(t => t.Value.Count());
// // var addingTemplatesCount = wdCounts.Length > 1 ?
// // (templateCountDelta == 0) ? (int)Math.Ceiling(templatesPerStep) : templateCountDelta :
// // (int)Math.Ceiling(templatesPerStep);
// // var workDaysWithMinTemplates = d.Where(wd => wd.Value == wdCounts[0]).ToArray();
// // if (workDaysWithMinTemplates.Length * addingTemplatesCount < templates.Count())
// // {
// // foreach (var wd in workDaysWithMinTemplates)
// // {
// // //Считаем DateTimeOffset, потому что у нас только дата пока
// // var currentDay = new DateTimeOffset(
// // wd.Key.Year, wd.Key.Month, wd.Key.Day,
// // refDate.Hour, refDate.Minute, refDate.Second,
// // new TimeSpan(0, 0, 0));
// // templates.Skip(templateDistributed).Take(addingTemplatesCount).ToList().ForEach(t =>
// // {
// // t.NextRun = currentDay;
// // d[wd.Key].Add(t);
// // });
// // templateDistributed += addingTemplatesCount;
// // }
// // }
// // else
// // {
// // while (templateDistributed < templates.Count())
// // {
// // var wd = d.Where(wd => wd.Value == d.Min(t => t.Value)).First();
// // //Считаем DateTimeOffset, потому что у нас только дата пока
// // var currentDay = new DateTimeOffset(
// // wd.Key.Year, wd.Key.Month, wd.Key.Day,
// // refDate.Hour, refDate.Minute, refDate.Second,
// // new TimeSpan(0, 0, 0));
// // templates.Skip(templateDistributed).Take(addingTemplatesCount).ToList().ForEach(t =>
// // {
// // t.NextRun = currentDay;
// // d[wd.Key].Add(t);
// // });
// // templateDistributed += addingTemplatesCount;
// // }
// // }
// //}
// #endregion
// }
// else
// // templates.ForEach(t => t.NextRun = appInWork!.ReferenceDate);
// // это не автораспределение, по ReferenceDate получаем ближайший рабочий день
// templates.ForEach(async t => t.NextRun = await nextRunModifierService.GetWorkDayAsync(appInWork!.ReferenceDate));
// return templates;
return new List<Template>();
}
private void Distribute(ref List<Template> templates, DateTimeOffset refDate, DistributionPeriod period, DistributionPeriodTypeEnum periodType, List<DateOnly> workDays)
{
//Готовим план распределения
var distrPlan = GetDistributionPlan(workDays, templates.Count);
//Проверяем шаблоны уже распределённые, чтобы не перемещать лишний раз
var templateToDistrib = GetTemplatesToDistribute(ref distrPlan, templates);
string? loggerWorkGroup = templates.FirstOrDefault()?.Unit?.BaseFields?.WorkGroup != null ? templates.FirstOrDefault()?.Unit.BaseFields.WorkGroup : templates.FirstOrDefault()?.Unit?.BaseFields?.WorkGroup?.ToString();
logger.LogInformation($"{GetType().Name}(AppInWId:{templates.Select(t => t.JobId).First()}, " +
$"WorkGroup:{loggerWorkGroup}) " +
$"запланировал изменение даты следующего срабатывания у {templateToDistrib.Count()} существующих шаблона(ов), {templates.Count() - templateToDistrib.Count()} остались без изменений");
if (!templateToDistrib.Any())
return;
var distributedTemplates = 0;
//Распределяем шаблоны в соответствии с планом непосредственно
foreach (var workDay in distrPlan)
{
var templatesCountForCurDay = workDay.Value;
if (templatesCountForCurDay < 1)
continue;
templateToDistrib.Skip(distributedTemplates).Take(templatesCountForCurDay).ToList().ForEach(t =>
{
var nextRun = new DateTimeOffset(
workDay.Key.Year, workDay.Key.Month, workDay.Key.Day,
refDate.Hour, refDate.Minute, refDate.Second,
new TimeSpan(0, 0, 0));
if (nextRun < DateTimeOffset.UtcNow)
nextRun = esppScheduleTransformService.GetNextDateForDistributionRun(nextRun, periodType, period.Duration);
t.NextRun = nextRun;
});
distributedTemplates += templatesCountForCurDay;
distrPlan[workDay.Key] -= templatesCountForCurDay;
}
}
/// <summary>
/// Получить список рабочих дней из календаря и перенести прошедшие даты на следующий период по РР
/// </summary>
/// <param name="appInWork"></param>
/// <returns></returns>
private async Task<List<DateOnly>> GetWorkDaysAsync(ApplicationsInWork appInWork)
{
//var period = appInWork.EsppSchValues.FirstOrDefault()?.EsppSchTypeValue?.DistributionPeriod;
//var periodType = ParseDistributionPeriodType(period!.Type);
////старт период, берем сейчас, будем получать рабочие дни с вычетом выходных на весь период сразу.
//var startPeriod = DateOnly.FromDateTime(DateTimeOffset.UtcNow.Date);
//// старт период считаем относительно refDate
////var startPeriod = await esppScheduleTransformService.GetStartPeriodForDateAsync(appInWork.Id, appInWork.ReferenceDate, appInWork.ReferenceDate, periodType, period.Duration);
//var workDays = calendarService.GetWorkDatesForPeriod(startPeriod, TimeOnly.FromDateTime(appInWork.ReferenceDate.DateTime), periodType, period.Duration, weekendDayService.GetWeekends);
//#region старая логика
////var resultWorkDays = new List<DateOnly>();
////workDays.ForEach(wd =>
////{
//// var wrokDateTimeOffset = new DateTimeOffset(
//// wd.Year, wd.Month, wd.Day,
//// appInWork.ReferenceDate.Hour, appInWork.ReferenceDate.Minute, appInWork.ReferenceDate.Second,
//// new TimeSpan(0, 0, 0));
//// if (wrokDateTimeOffset < DateTimeOffset.UtcNow)
//// {
//// wrokDateTimeOffset = esppScheduleTransformService.GetNextDateForDistributionRun(wrokDateTimeOffset, periodType, period.Duration);
//// //wd = DateOnly.FromDateTime(wrokDateTimeOffset.DateTime);
//// resultWorkDays.Add(DateOnly.FromDateTime(wrokDateTimeOffset.DateTime));
//// }
//// else
//// {
//// resultWorkDays.Add(wd);
//// }
////});
//////----- убираем даты, которые могли выйти за конец периода (из-за сдвига NextRun по рабочим дням)
////var endPeriod = calendarService.GetEndPeriodDate(DateOnly.FromDateTime(DateTimeOffset.UtcNow.Date), periodType, period.Duration);
////resultWorkDays = resultWorkDays.Where(t => t <= endPeriod).Distinct().OrderBy(t => t).ToList();
//////-----
////return resultWorkDays;
//#endregion
//return workDays;
return new List<DateOnly>();
}
/// <summary>
/// Проверить соответствие распределения существующих шаблонов нововму плану.
/// На выходе получаем шаблоны, которым требуется изменить дату следующего запуска.
/// </summary>
/// <param name="distributionPlan"></param>
/// <param name="templates"></param>
/// <returns></returns>
private List<Template> GetTemplatesToDistribute(ref Dictionary<DateOnly, int> distributionPlan, List<Template> templates)
{
var result = new List<Template>();
foreach (var wd in distributionPlan)
{
var templatesInWd = templates.Where(t => DateOnly.FromDateTime(t.NextRun.DateTime) == wd.Key).ToList();
if (templatesInWd.Any() && templatesInWd.Count > wd.Value)
{
result.AddRange(templatesInWd.Skip(wd.Value).Take(templatesInWd.Count - wd.Value).ToList());
distributionPlan[wd.Key] -= wd.Value;
}
else
distributionPlan[wd.Key] -= templatesInWd.Count;
}
//Определим шаблоны за границами рабочих дней. Их тоже необходимо перераспределить
var workDays = distributionPlan.Keys.ToList();
var templateWithNextRunOut = templates.Where(t => workDays.All(w => w != DateOnly.FromDateTime(t.NextRun.DateTime))).ToList();
if (templateWithNextRunOut.Any())
result.AddRange(templateWithNextRunOut);
if (result.Any())
//Обнулим nextRun
result.ForEach(t => t.NextRun = DateTimeOffset.MinValue);
return result;
}
private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
{
var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
return result;
logger.LogWarning("Шаблон с Id {templateId} не найден в распределённых данных.", templateDb.Id);
}
}
private Dictionary<DateOnly, int> GetDistributionPlan(List<DateOnly> workDays, int templateCount)
if (updatedCount > 0)
{
var result = new Dictionary<DateOnly, int>();
//Заполняем будующий план датами из полученных на входе данных
foreach (var wd in workDays)
// сохранить изменения
if (await templateService.CommitAsync(mqResponse.Initiator))
{
var workDate = new DateOnly(wd.Year, wd.Month, wd.Day);
result.Add(workDate, 0);
logger.LogInformation("Обновлено {updatedCount} шаблонов в БД для jobGroupId {jobGroupId}. Для расписаний установлен статус: {taskStatus}", updatedCount, jobGroupId, TaskStatusEnum.Updating.ToString());
}
var templateDistributedCount = 0;//количество распределённых на текущий момент шаблонов
//Если количество шаблонов больше количества рабочих дней, то сразу распределяем их равным количеством по всем рабочим дням
if (templateCount >= workDays.Count)
else
{
//количеством шаблонов на один рабочий день
var mainPartTemplateCountToDistribute = templateCount / workDays.Count;
//перебираем рабочие дня и записываем количество шаблонов
foreach (var item in result)
logger.LogError("Ошибка при обновлении записей в БД. jobGroupId {jobGroupId}, требовалось обновить шаблонов: {updatedCount}", jobGroupId, updatedCount);
}
}
else
{
result[item.Key] = mainPartTemplateCountToDistribute;
templateDistributedCount += mainPartTemplateCountToDistribute;
logger.LogInformation("Для jobGroupId {jobGroupId} не найдено изменений. Ничего не обновлено.", jobGroupId);
}
}
var daysBetweenTemplates = (double)workDays.Count / (templateCount % workDays.Count);//количество дней между шаблонами, если распределить их равномерно
var currentStepBetweenTemplates = (double)Math.Floor(daysBetweenTemplates);//инициализация шага перехода между датами запуска двух шаблонов
var balance = (double)daysBetweenTemplates - Math.Floor(currentStepBetweenTemplates);//остаток между датами, потому что мы берём целые дни, его нужно учесть в следующей итирации
var currentDayIndex = 0;//инициализация индекса даты словаря рабочих дней
while (templateDistributedCount < templateCount)
{
//лишняя проверка так как шагом ранее мы распределям шаблоны равным количеством и currentStepBetweenTemplates не может быть меньше одного дня
//if (currentStepBetweenTemplates > 0)
//{
result[result.ElementAt(currentDayIndex).Key] += 1;
templateDistributedCount++;
currentDayIndex += (int)Math.Floor(currentStepBetweenTemplates);
//}
currentStepBetweenTemplates = daysBetweenTemplates + balance;
balance = daysBetweenTemplates - currentStepBetweenTemplates;
}
return result;
}
}
}

View File

@@ -4,25 +4,23 @@ namespace PARR.TemplateDistributorWorker
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly IMqTemplateDistributor mqTemplateDistributor;
public Worker(ILogger<Worker> logger, IMqTemplateDistributor mqTemplateDistributor)
{
_logger = logger;
this.mqTemplateDistributor = mqTemplateDistributor;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await mqTemplateDistributor.StartAsync();
await Task.Delay(Timeout.Infinite, stoppingToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
public override async Task StopAsync(CancellationToken cancellationToken)
{
mqTemplateDistributor.StopAsync().Wait();
return base.StopAsync(cancellationToken);
await mqTemplateDistributor.StopAsync();
await base.StopAsync(cancellationToken);
}
}
}

View File

@@ -10,10 +10,10 @@
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
"Microsoft": "Debug",
"Microsoft.Hosting.Lifetime": "Debug"
}
},
"WriteTo": [

View File

@@ -1,4 +1,5 @@
using PARR.DAL.NextRunServices.Models;
using PARR.DAL.NextRunServices;
using PARR.DAL.NextRunServices.Models;
using PARR.DAL.NextRunServices.Subservices;
namespace PARR.Test.NextRun
@@ -6,10 +7,12 @@ namespace PARR.Test.NextRun
internal class NextRunTest
{
private readonly ITemplateDistributor templateDistributor;
private readonly INextRunService nextRunService;
public NextRunTest(ITemplateDistributor templateDistributor)
public NextRunTest(ITemplateDistributor templateDistributor, INextRunService nextRunService)
{
this.templateDistributor = templateDistributor;
this.nextRunService = nextRunService;
}
int periodDays = 10;
@@ -17,8 +20,18 @@ namespace PARR.Test.NextRun
public async Task Test()
{
await DistributeTemplatesAsync();
//await DistributeTemplatesAsync();
//await GetValidNextRunForTemplateAsync();
// распределить шаблоны (не сохраняя в БД)
//var result = await nextRunService.GetNextRunForJobGroupWithAutoDistributionAsync(Guid.Parse("eadc5498-dba6-4f10-9b4b-a1653e3c3e61"));
// получить nextRun для еще не созданного шаблона
//var nextRunForNullTemplate = await nextRunService.GetNextRunForNewTemplateAsync(Guid.Parse("eadc5498-dba6-4f10-9b4b-a1653e3c3e61"));
// получить nextRun для существующего шаблона
// var nextRunForExistTemplate = await nextRunService.GetNextRunForTemplateAsync(Guid.Parse("20fc3581-984e-4c9a-8b46-8a55c3401725"), false);
}
/// <summary>

View File

@@ -17,7 +17,7 @@ services:
fluentd-buffer-limit: '52428800'
tag: parr.template-distributor.serilog
deploy:
replicas: 2
replicas: 1
networks:
parr-network: