Merge branch 'distributor' into dev
This commit is contained in:
@@ -3,8 +3,8 @@ using Microsoft.Extensions.Logging;
|
|||||||
using PARR.AIHITMainLoader.Models;
|
using PARR.AIHITMainLoader.Models;
|
||||||
using PARR.AIHITMainLoader.Services;
|
using PARR.AIHITMainLoader.Services;
|
||||||
using PARR.AIHITMainLoader.Settings;
|
using PARR.AIHITMainLoader.Settings;
|
||||||
using PARR.BLL.Domain.Mq;
|
|
||||||
using PARR.BLL.Services.Interfaces;
|
using PARR.BLL.Services.Interfaces;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace PARR.AIHITMainLoader
|
namespace PARR.AIHITMainLoader
|
||||||
@@ -19,6 +19,11 @@ namespace PARR.AIHITMainLoader
|
|||||||
private readonly IMqService mqService;
|
private readonly IMqService mqService;
|
||||||
private readonly IServiceProvider serviceProvider;
|
private readonly IServiceProvider serviceProvider;
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
};
|
||||||
|
|
||||||
public AihitMainLoader(
|
public AihitMainLoader(
|
||||||
ILogger<AihitMainLoader> logger,
|
ILogger<AihitMainLoader> logger,
|
||||||
IIntervalService intervalService,
|
IIntervalService intervalService,
|
||||||
@@ -82,7 +87,7 @@ namespace PARR.AIHITMainLoader
|
|||||||
var mainData = item.ToMainData();
|
var mainData = item.ToMainData();
|
||||||
if (mainData == null) continue;
|
if (mainData == null) continue;
|
||||||
|
|
||||||
var json = JsonSerializer.Serialize(mainData);
|
var json = JsonSerializer.Serialize(mainData, jsonOptions);
|
||||||
currentBatch.Add(json);
|
currentBatch.Add(json);
|
||||||
|
|
||||||
// Отправка, если набрали полный пакет
|
// Отправка, если набрали полный пакет
|
||||||
|
|||||||
@@ -2,6 +2,6 @@
|
|||||||
{
|
{
|
||||||
public class DistributeRequest
|
public class DistributeRequest
|
||||||
{
|
{
|
||||||
public Guid ApplicationInWorkId { get; set; }
|
public Guid JobGroupId { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,21 +24,21 @@ namespace PARR.API.Controllers.V1
|
|||||||
private readonly IClientService clientService;
|
private readonly IClientService clientService;
|
||||||
private readonly ITemplateService templateService;
|
private readonly ITemplateService templateService;
|
||||||
private readonly IUnitService unitService;
|
private readonly IUnitService unitService;
|
||||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||||
private readonly ILogger<AgentTaskController> logger;
|
private readonly ILogger<AgentTaskController> logger;
|
||||||
|
|
||||||
public AgentTaskController(
|
public AgentTaskController(
|
||||||
IClientService clientService,
|
IClientService clientService,
|
||||||
ITemplateService templateService,
|
ITemplateService templateService,
|
||||||
IUnitService unitService,
|
IUnitService unitService,
|
||||||
IEsppScheduleTransformService esppScheduleTransformService,
|
//IEsppScheduleTransformService esppScheduleTransformService,
|
||||||
ILogger<AgentTaskController> logger
|
ILogger<AgentTaskController> logger
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.clientService = clientService;
|
this.clientService = clientService;
|
||||||
this.templateService = templateService;
|
this.templateService = templateService;
|
||||||
this.unitService = unitService;
|
this.unitService = unitService;
|
||||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,82 +51,84 @@ namespace PARR.API.Controllers.V1
|
|||||||
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
|
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
|
||||||
public async Task<IActionResult> GetByClientIp([FromQuery] AgentTaskGetByIpQuery request)
|
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))
|
//var ip = request.Ip ?? clientService.GetClientIp()?.ToString();
|
||||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Client IP address is null." } }));
|
|
||||||
|
|
||||||
//var date = request.Date ?? DateTimeOffset.UtcNow;
|
//if (string.IsNullOrEmpty(ip))
|
||||||
var date = DateTimeOffset.UtcNow;
|
// 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 может быть несколько информационных систем, так что может быть несколько хостов
|
////Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
|
||||||
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();
|
|
||||||
|
|
||||||
if (!templates.Any())
|
//// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
|
||||||
return NoContent();
|
//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
|
//if (!templates.Any())
|
||||||
{
|
// return NoContent();
|
||||||
Scheduled = new List<AgentTaskMinScheduleResponse>()
|
|
||||||
};
|
|
||||||
|
|
||||||
foreach (var template in templates)
|
//var response = new AgentTaskMinResponse
|
||||||
{
|
//{
|
||||||
//var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
|
// Scheduled = new List<AgentTaskMinScheduleResponse>()
|
||||||
var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
|
//};
|
||||||
|
|
||||||
if (!templateSchedule.Any())
|
//foreach (var template in templates)
|
||||||
{
|
//{
|
||||||
logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
|
// //var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
|
||||||
$"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
|
// var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
|
// if (!templateSchedule.Any())
|
||||||
{
|
// {
|
||||||
logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
|
// logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
|
||||||
$"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
|
// $"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
|
||||||
continue;
|
// continue;
|
||||||
}
|
// }
|
||||||
|
|
||||||
templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
|
// if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
|
||||||
{
|
// {
|
||||||
Name = template.Job.Group.AgentName ?? "",
|
// logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
|
||||||
Script = template.Job.Group.AgentScript ?? "",
|
// $"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
|
||||||
StartAt = item,
|
// continue;
|
||||||
TemplateId = template.Id
|
// }
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!response.Scheduled.Any())
|
// templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
|
||||||
return NoContent();
|
// {
|
||||||
|
// 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,13 @@ using PARR.API.Contracts.V1;
|
|||||||
using PARR.API.Contracts.V1.Requests;
|
using PARR.API.Contracts.V1.Requests;
|
||||||
using PARR.API.Contracts.V1.Responses.Base;
|
using PARR.API.Contracts.V1.Responses.Base;
|
||||||
using PARR.API.Controllers.V1.Base;
|
using PARR.API.Controllers.V1.Base;
|
||||||
|
using PARR.API.Services.Interfaces;
|
||||||
using PARR.API.Settings;
|
using PARR.API.Settings;
|
||||||
using PARR.BLL.Domain.Mq;
|
using PARR.BLL.Domain.Mq;
|
||||||
using PARR.BLL.Services.Interfaces;
|
using PARR.BLL.Services.Interfaces;
|
||||||
|
using PARR.Common.Domain;
|
||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace PARR.API.Controllers.V1
|
namespace PARR.API.Controllers.V1
|
||||||
@@ -22,21 +25,24 @@ namespace PARR.API.Controllers.V1
|
|||||||
private readonly IMqService mqService;
|
private readonly IMqService mqService;
|
||||||
private readonly MqSettings mqSettings;
|
private readonly MqSettings mqSettings;
|
||||||
private readonly IValidator<DistributeRequest> validator;
|
private readonly IValidator<DistributeRequest> validator;
|
||||||
|
private readonly IClientService clientService;
|
||||||
|
|
||||||
public DistributorController(
|
public DistributorController(
|
||||||
IMqService mqService,
|
IMqService mqService,
|
||||||
MqSettings mqSettings,
|
MqSettings mqSettings,
|
||||||
IValidator<DistributeRequest> validator
|
IValidator<DistributeRequest> validator,
|
||||||
|
IClientService clientService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.mqService = mqService;
|
this.mqService = mqService;
|
||||||
this.mqSettings = mqSettings;
|
this.mqSettings = mqSettings;
|
||||||
this.validator = validator;
|
this.validator = validator;
|
||||||
|
this.clientService = clientService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Перераспределить шаблоны для регламентной работы
|
/// Перераспределить шаблоны для группы работ
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost(ApiRoutes.Distributor.Distribute)]
|
[HttpPost(ApiRoutes.Distributor.Distribute)]
|
||||||
@@ -48,17 +54,28 @@ namespace PARR.API.Controllers.V1
|
|||||||
|
|
||||||
var requestToMq = new TemplateDistributorMq
|
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)
|
if (sendResult.IsSuccess)
|
||||||
return Created("", new Response<string?>(null, true, new List<ErrorModel>(), "Отправлен запрос на перераспределение регламентных работ."));
|
return Created("", new Response<string?>(null, true, new List<ErrorModel>(), "Отправлен запрос на перераспределение регламентных работ."));
|
||||||
else
|
else
|
||||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message="Ошибка при отправке данных."} }));
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при отправке данных." } }));
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,9 +72,10 @@ namespace PARR.API.Controllers.V1
|
|||||||
HistoryInitiator = new HistoryInitiator { InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }
|
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)
|
if (_result.IsSuccess == false)
|
||||||
result = false;
|
result = false;
|
||||||
|
|||||||
@@ -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);
|
logger.LogDebug("Получен код отпрвки: {IsSuccess}", result.IsSuccess);
|
||||||
|
|
||||||
if (!result.IsSuccess)
|
if (!result.IsSuccess)
|
||||||
{
|
{
|
||||||
logger.LogError($"Ошибка при отправке запроса в очередь на обновление связанных шаблонов, после обновления маски шаблона. {msg}");
|
logger.LogError($"Ошибка при отправке запроса в очередь на обновление связанных шаблонов, после обновления маски шаблона. {request.ToJson()}");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogInformation($"После изменения маски шаблона в jobId: {jobId}, отправлен запрос в очередь на переименование связанных шаблонов: {msg}");
|
logger.LogInformation($"После изменения маски шаблона в jobId: {jobId}, отправлен запрос в очередь на переименование связанных шаблонов: {request.ToJson()}");
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ using PARR.DAL.Contracts;
|
|||||||
using PARR.DAL.DomainServices.Shortcodes;
|
using PARR.DAL.DomainServices.Shortcodes;
|
||||||
using PARR.DAL.DomainServices.Shortcodes.Models;
|
using PARR.DAL.DomainServices.Shortcodes.Models;
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
|
using PARR.DAL.NextRunServices;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.DAL.TransformServices;
|
using PARR.DAL.TransformServices;
|
||||||
|
|
||||||
@@ -25,31 +26,34 @@ namespace PARR.API.Controllers.V1
|
|||||||
private readonly IMapper mapper;
|
private readonly IMapper mapper;
|
||||||
private readonly SettingsFromDb settingsFromDb;
|
private readonly SettingsFromDb settingsFromDb;
|
||||||
private readonly IRobotConfigurationService robotConfigurationService;
|
private readonly IRobotConfigurationService robotConfigurationService;
|
||||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||||
private readonly ILogger<RobotTaskController> logger;
|
private readonly ILogger<RobotTaskController> logger;
|
||||||
private readonly IClientService clientService;
|
private readonly IClientService clientService;
|
||||||
private readonly IRobotHistoryService robotHistoryService;
|
private readonly IRobotHistoryService robotHistoryService;
|
||||||
private readonly IShortcodesService shortcodesService;
|
private readonly IShortcodesService shortcodesService;
|
||||||
|
private readonly INextRunService nextRunService;
|
||||||
|
|
||||||
public RobotTaskController(
|
public RobotTaskController(
|
||||||
IMapper mapper,
|
IMapper mapper,
|
||||||
SettingsFromDb settingsFromDb,
|
SettingsFromDb settingsFromDb,
|
||||||
IRobotConfigurationService robotConfigurationService,
|
IRobotConfigurationService robotConfigurationService,
|
||||||
IEsppScheduleTransformService esppScheduleTransformService,
|
//IEsppScheduleTransformService esppScheduleTransformService,
|
||||||
ILogger<RobotTaskController> logger,
|
ILogger<RobotTaskController> logger,
|
||||||
IClientService clientService,
|
IClientService clientService,
|
||||||
IRobotHistoryService robotHistoryService,
|
IRobotHistoryService robotHistoryService,
|
||||||
IShortcodesService shortcodesService
|
IShortcodesService shortcodesService,
|
||||||
|
INextRunService nextRunService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
this.settingsFromDb = settingsFromDb;
|
this.settingsFromDb = settingsFromDb;
|
||||||
this.robotConfigurationService = robotConfigurationService;
|
this.robotConfigurationService = robotConfigurationService;
|
||||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.clientService = clientService;
|
this.clientService = clientService;
|
||||||
this.robotHistoryService = robotHistoryService;
|
this.robotHistoryService = robotHistoryService;
|
||||||
this.shortcodesService = shortcodesService;
|
this.shortcodesService = shortcodesService;
|
||||||
|
this.nextRunService = nextRunService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -306,7 +310,8 @@ namespace PARR.API.Controllers.V1
|
|||||||
//пока у нас выключено автораспределение, считает по refDate
|
//пока у нас выключено автораспределение, считает по refDate
|
||||||
//TODO: когда заработает автораспределение, будем думать!!!!!
|
//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)
|
if (nextRun != template.NextRun)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -73,10 +73,11 @@ namespace PARR.API.Controllers.V1
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var msg = JsonSerializer.Serialize(matchTemplateTask);
|
//var msg = JsonSerializer.Serialize(matchTemplateTask);
|
||||||
logger.LogDebug("Подготовлено сообщение: {Message}", new[] { msg });
|
//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);
|
logger.LogDebug("Получен код отпрвки: {IsSuccess}", result.IsSuccess);
|
||||||
|
|
||||||
if (!result.IsSuccess)
|
if (!result.IsSuccess)
|
||||||
|
|||||||
@@ -67,9 +67,10 @@ namespace PARR.API.Controllers.V1
|
|||||||
HistoryInitiator = new HistoryInitiator { InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }
|
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)
|
if (!sendResult.IsSuccess)
|
||||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при отправке данных." } }));
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при отправке данных." } }));
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ namespace PARR.API.Controllers.V1
|
|||||||
public class TestController : BaseApiController
|
public class TestController : BaseApiController
|
||||||
{
|
{
|
||||||
private readonly IClientService clientService;
|
private readonly IClientService clientService;
|
||||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||||
private readonly IRedisCacheService redisCacheService;
|
private readonly IRedisCacheService redisCacheService;
|
||||||
private readonly IWeekendDayService weekendDayService;
|
private readonly IWeekendDayService weekendDayService;
|
||||||
private readonly IUnitService unitService;
|
private readonly IUnitService unitService;
|
||||||
@@ -37,7 +37,7 @@ namespace PARR.API.Controllers.V1
|
|||||||
|
|
||||||
public TestController(
|
public TestController(
|
||||||
IClientService clientService,
|
IClientService clientService,
|
||||||
IEsppScheduleTransformService esppScheduleTransformService,
|
//IEsppScheduleTransformService esppScheduleTransformService,
|
||||||
IRedisCacheService redisCacheService,
|
IRedisCacheService redisCacheService,
|
||||||
IWeekendDayService weekendDayService,
|
IWeekendDayService weekendDayService,
|
||||||
IUnitService unitService,
|
IUnitService unitService,
|
||||||
@@ -49,7 +49,7 @@ namespace PARR.API.Controllers.V1
|
|||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.clientService = clientService;
|
this.clientService = clientService;
|
||||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||||
this.redisCacheService = redisCacheService;
|
this.redisCacheService = redisCacheService;
|
||||||
this.weekendDayService = weekendDayService;
|
this.weekendDayService = weekendDayService;
|
||||||
this.unitService = unitService;
|
this.unitService = unitService;
|
||||||
@@ -76,32 +76,32 @@ namespace PARR.API.Controllers.V1
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить следующую дату запуска
|
///// Получить следующую дату запуска
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="applicationInWorkId"></param>
|
///// <param name="applicationInWorkId"></param>
|
||||||
/// <param name="lastRunDate"></param>
|
///// <param name="lastRunDate"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
[HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
|
//[HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
|
||||||
public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
//public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
||||||
{
|
//{
|
||||||
var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
|
// var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
|
||||||
return Ok(result);
|
// return Ok(result);
|
||||||
}
|
//}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить следующее расписание
|
///// Получить следующее расписание
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="applicationInWorkId"></param>
|
///// <param name="applicationInWorkId"></param>
|
||||||
/// <param name="lastRunDate"></param>
|
///// <param name="lastRunDate"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
[HttpGet(ApiRoutes.Test.GetNextSchedule)]
|
//[HttpGet(ApiRoutes.Test.GetNextSchedule)]
|
||||||
public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
//public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
||||||
{
|
//{
|
||||||
var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
|
// var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
|
||||||
return Ok(result);
|
// return Ok(result);
|
||||||
}
|
//}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -1,24 +1,27 @@
|
|||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
using PARR.API.Contracts.V1.Requests;
|
using PARR.API.Contracts.V1.Requests;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
|
|
||||||
namespace PARR.API.Validators
|
namespace PARR.API.Validators
|
||||||
{
|
{
|
||||||
public class DistributeRequestValidator : AbstractValidator<DistributeRequest>
|
public class DistributeRequestValidator : AbstractValidator<DistributeRequest>
|
||||||
{
|
{
|
||||||
private readonly IApplicationsInWorkService applicationsInWorkService;
|
public DistributeRequestValidator(IJobGroupService jobGroupService)
|
||||||
|
|
||||||
public DistributeRequestValidator(IApplicationsInWorkService applicationsInWorkService)
|
|
||||||
{
|
{
|
||||||
this.applicationsInWorkService = applicationsInWorkService;
|
RuleFor(t => t.JobGroupId).NotEmpty().MustAsync(async (entity, value, c) =>
|
||||||
|
|
||||||
|
|
||||||
RuleFor(t => t.ApplicationInWorkId).NotEmpty().MustAsync(async (entity, value, c) =>
|
|
||||||
{
|
{
|
||||||
var appInWork = await applicationsInWorkService.GetAsync(value);
|
return await jobGroupService.Get().FirstOrDefaultAsync(t => t.Id == value) != null;
|
||||||
|
|
||||||
return appInWork != null;
|
|
||||||
}).WithMessage("Недопустимое значение");
|
}).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("Отсутствуют настройки автораспределения");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
namespace PARR.BLL.Domain.Mq
|
using PARR.Common.Domain;
|
||||||
|
|
||||||
|
namespace PARR.BLL.Domain.Mq
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Модель в MQ, обновления расписаний шаблонов связанных с РР (для TemplateDistributor)
|
/// Модель в MQ, распределить шаблоны для JobGroupId (для TemplateDistributor)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class TemplateDistributorMq
|
public class TemplateDistributorMq
|
||||||
{
|
{
|
||||||
public Guid ApplicationInWorkId { get; set; }
|
public Guid JobGroupId { get; set; }
|
||||||
|
|
||||||
|
public required HistoryInitiator Initiator { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ using PARR.BLL.Services.Interfaces;
|
|||||||
using RabbitMQ.Client;
|
using RabbitMQ.Client;
|
||||||
using RabbitMQ.Client.Events;
|
using RabbitMQ.Client.Events;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace PARR.BLL.Services.Implementations
|
namespace PARR.BLL.Services.Implementations
|
||||||
{
|
{
|
||||||
@@ -17,6 +19,11 @@ namespace PARR.BLL.Services.Implementations
|
|||||||
|
|
||||||
// реализация для RabbitMQ.Client 7.1.2
|
// реализация для RabbitMQ.Client 7.1.2
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
};
|
||||||
|
|
||||||
public MqServiceV2(ILogger<MqServiceV2> logger)
|
public MqServiceV2(ILogger<MqServiceV2> logger)
|
||||||
{
|
{
|
||||||
this.logger = 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)
|
public async Task<MqSendResult> SendAsync(IMqSettings mqSettings, string[] msgList)
|
||||||
{
|
{
|
||||||
@@ -136,7 +149,8 @@ namespace PARR.BLL.Services.Implementations
|
|||||||
props.DeliveryMode = DeliveryModes.Persistent;
|
props.DeliveryMode = DeliveryModes.Persistent;
|
||||||
//время жизни, мс
|
//время жизни, мс
|
||||||
//props.Expiration = "60000";
|
//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) =>
|
channel.BasicReturnAsync += async (sender, ea) =>
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,6 +8,22 @@ namespace PARR.BLL.Services.Interfaces
|
|||||||
public interface IMqService : IAsyncDisposable // IDisposable
|
public interface IMqService : IAsyncDisposable // IDisposable
|
||||||
{
|
{
|
||||||
Task<bool> InitConsumerAsync(IMqSettings mqSettings, MqMessageHandlerDelegate messageHandler);
|
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);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
namespace PARR.DAL.NextRunServices
|
using PARR.DAL.NextRunServices.Models;
|
||||||
|
|
||||||
|
namespace PARR.DAL.NextRunServices
|
||||||
{
|
{
|
||||||
public interface INextRunService
|
public interface INextRunService
|
||||||
{
|
{
|
||||||
@@ -7,24 +9,32 @@
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="jobGroupId"></param>
|
/// <param name="jobGroupId"></param>
|
||||||
/// <returns></returns>
|
/// <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>
|
/// <summary>
|
||||||
/// Получить NextRun по jobGroupId с расписанием ЕСПП
|
/// Получить nextRun для создаваемого шаблона, которого еще нет в БД
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="jobGroupId"></param>
|
/// <param name="jobGroupId"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId);
|
Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId);
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить NextRun по id шаблона
|
/// Получить NextRun по id существующего шаблона
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="templateId"></param>
|
/// <param name="templateId"></param>
|
||||||
/// <param name="isNew">Новый шаблон или шаблон переведенный из unused</param>
|
/// <param name="isNew">Шаблон переведенный из unused</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<DateTimeOffset> GetNextRunForTemplate(Guid templateId, bool isNew);
|
Task<DateTimeOffset> GetNextRunForTemplateAsync(Guid templateId, bool isNew);
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
namespace PARR.DAL.NextRunServices.Models
|
||||||
|
{
|
||||||
|
internal record TemplateWithWorkGroupDto(Guid Id, DateTimeOffset? NextRun, string WorkGroup);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.Logging;
|
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.NextRunServices.Subservices;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
@@ -15,13 +19,15 @@ namespace PARR.DAL.NextRunServices
|
|||||||
private readonly IJobGroupService jobGroupService;
|
private readonly IJobGroupService jobGroupService;
|
||||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||||
private readonly ITemplateDistributor templateDistributor;
|
private readonly ITemplateDistributor templateDistributor;
|
||||||
|
private readonly IShortcodesService shortcodesService;
|
||||||
|
|
||||||
public NextRunService(
|
public NextRunService(
|
||||||
ILogger<NextRunService> logger,
|
ILogger<NextRunService> logger,
|
||||||
ITemplateService templateService,
|
ITemplateService templateService,
|
||||||
IJobGroupService jobGroupService,
|
IJobGroupService jobGroupService,
|
||||||
IEsppScheduleTransformService esppScheduleTransformService,
|
IEsppScheduleTransformService esppScheduleTransformService,
|
||||||
ITemplateDistributor templateDistributor
|
ITemplateDistributor templateDistributor,
|
||||||
|
IShortcodesService shortcodesService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
@@ -29,20 +35,121 @@ namespace PARR.DAL.NextRunServices
|
|||||||
this.jobGroupService = jobGroupService;
|
this.jobGroupService = jobGroupService;
|
||||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
this.esppScheduleTransformService = esppScheduleTransformService;
|
||||||
this.templateDistributor = templateDistributor;
|
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:
|
logger.LogInformation("Начинаю распределять шаблоны для группы работ {gobGroupId}", jobGroupId);
|
||||||
throw new NotImplementedException();
|
|
||||||
//var ditributedTemplateList = await templateDistributor.DistributeTemplatesAsync();
|
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)
|
if (jobGroup == null)
|
||||||
{
|
{
|
||||||
@@ -50,36 +157,152 @@ namespace PARR.DAL.NextRunServices
|
|||||||
throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
|
throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Берем из обычного расписания ЕСПП
|
if (jobGroup.IsAutoDistributionEnabled)
|
||||||
return await esppScheduleTransformService.GetNextDateAsync(jobGroupId, jobGroup.ReferenceDate);
|
{
|
||||||
|
// тут автораспределение
|
||||||
|
|
||||||
|
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()
|
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()
|
.AsNoTracking()
|
||||||
.FirstOrDefaultAsync(t => t.Id == templateId);
|
.FirstOrDefaultAsync(t => t.Id == templateId);
|
||||||
|
|
||||||
if (template == null)
|
if (template == null)
|
||||||
{
|
{
|
||||||
logger.LogError("Не найдена шаблон с Id: {templateId}.", templateId);
|
logger.LogError("Не найден шаблон с Id: {templateId}.", templateId);
|
||||||
throw new ArgumentNullException(nameof(templateId), $"Не найдена шаблон с Id: {templateId}");
|
throw new ArgumentNullException(nameof(templateId), $"Не найден шаблон с Id: {templateId}");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (template.Job!.Group!.IsAutoDistributionEnabled == true)
|
if (template.Job!.Group!.IsAutoDistributionEnabled == true)
|
||||||
{
|
{
|
||||||
// включено автораспределение
|
// включено автораспределение
|
||||||
//TODO: !!!!!!!!!!!!!!!! добавить метод рассчета с учетом распределения
|
if (template.Job!.Group.DistributionConfig == null)
|
||||||
throw new NotImplementedException();
|
{
|
||||||
//return await templateDistributor.GetValidNextRunForTemplateAsync();
|
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
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ namespace PARR.DAL.TransformServices
|
|||||||
return GetNextDate(esppSchedule, referenceDate);
|
return GetNextDate(esppSchedule, referenceDate);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
private DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
||||||
{
|
{
|
||||||
var nextRun = referenceDate;
|
var nextRun = referenceDate;
|
||||||
|
|
||||||
@@ -111,62 +111,62 @@ namespace PARR.DAL.TransformServices
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
//private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
||||||
{
|
//{
|
||||||
// расписание на оставшееся на сегодня время. его так мало...
|
// // расписание на оставшееся на сегодня время. его так мало...
|
||||||
referenceDate = referenceDate.UtcDateTime;
|
// referenceDate = referenceDate.UtcDateTime;
|
||||||
var schedules = new List<DateTimeOffset>();
|
// var schedules = new List<DateTimeOffset>();
|
||||||
var curTime = referenceDate;
|
// var curTime = referenceDate;
|
||||||
|
|
||||||
//Если ещё не произошло то добавляем расписание, возможно это новое AiW и он ещё ниразу не запускался.
|
// //Если ещё не произошло то добавляем расписание, возможно это новое AiW и он ещё ниразу не запускался.
|
||||||
//lastRun это будущее
|
// //lastRun это будущее
|
||||||
if (referenceDate >= DateTimeOffset.UtcNow && referenceDate <= DateTimeOffset.UtcNow.EndOfDay())
|
// if (referenceDate >= DateTimeOffset.UtcNow && referenceDate <= DateTimeOffset.UtcNow.EndOfDay())
|
||||||
schedules.Add(referenceDate);
|
// schedules.Add(referenceDate);
|
||||||
|
|
||||||
while (curTime < DateTimeOffset.UtcNow.EndOfDay())
|
// while (curTime < DateTimeOffset.UtcNow.EndOfDay())
|
||||||
{
|
// {
|
||||||
switch (esppSchedule.TypeSchedule.Id)
|
// switch (esppSchedule.TypeSchedule.Id)
|
||||||
{
|
// {
|
||||||
case (int)EsppSchTypeScheduleEnum.Regularly:
|
// case (int)EsppSchTypeScheduleEnum.Regularly:
|
||||||
curTime = GetNextDateRegularly(esppSchedule.Values, curTime);
|
// curTime = GetNextDateRegularly(esppSchedule.Values, curTime);
|
||||||
break;
|
// break;
|
||||||
case (int)EsppSchTypeScheduleEnum.Weekly:
|
// case (int)EsppSchTypeScheduleEnum.Weekly:
|
||||||
curTime = GetNextDateWeekly(esppSchedule.Values, curTime);
|
// curTime = GetNextDateWeekly(esppSchedule.Values, curTime);
|
||||||
break;
|
// break;
|
||||||
case (int)EsppSchTypeScheduleEnum.Monthly:
|
// case (int)EsppSchTypeScheduleEnum.Monthly:
|
||||||
curTime = GetNextDateMonthly(esppSchedule.Values, curTime);
|
// curTime = GetNextDateMonthly(esppSchedule.Values, curTime);
|
||||||
break;
|
// break;
|
||||||
case (int)EsppSchTypeScheduleEnum.Monthly2:
|
// case (int)EsppSchTypeScheduleEnum.Monthly2:
|
||||||
curTime = GetNextDateMonthly2(esppSchedule.Values, curTime);
|
// curTime = GetNextDateMonthly2(esppSchedule.Values, curTime);
|
||||||
break;
|
// break;
|
||||||
case (int)EsppSchTypeScheduleEnum.Annually:
|
// case (int)EsppSchTypeScheduleEnum.Annually:
|
||||||
curTime = GetNextDateAnnually(esppSchedule.Values, curTime);
|
// curTime = GetNextDateAnnually(esppSchedule.Values, curTime);
|
||||||
break;
|
// break;
|
||||||
case (int)EsppSchTypeScheduleEnum.Annually2:
|
// case (int)EsppSchTypeScheduleEnum.Annually2:
|
||||||
curTime = GetNextDateAnnually2(esppSchedule.Values, curTime);
|
// curTime = GetNextDateAnnually2(esppSchedule.Values, curTime);
|
||||||
break;
|
// break;
|
||||||
}
|
// }
|
||||||
|
|
||||||
schedules.Add(curTime);
|
// schedules.Add(curTime);
|
||||||
}
|
// }
|
||||||
schedules.RemoveAll(s => s > DateTimeOffset.UtcNow.EndOfDay());
|
// 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)
|
//public async Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset referenceDate)
|
||||||
{
|
//{
|
||||||
//TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
|
// //TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
|
||||||
//В общем проверить, когда будем тестировать агента, что с датами все ок
|
// //В общем проверить, когда будем тестировать агента, что с датами все ок
|
||||||
var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
// var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
||||||
var nextSchedule = GetNextSchedule(esppSchedule, referenceDate);
|
// var nextSchedule = GetNextSchedule(esppSchedule, referenceDate);
|
||||||
|
|
||||||
return nextSchedule;
|
// return nextSchedule;
|
||||||
}
|
//}
|
||||||
|
|
||||||
|
|
||||||
private async Task<EsppScheduleDto> GetEsppScheduleAsync(Guid jobGroupId)
|
private async Task<EsppScheduleDto> GetEsppScheduleAsync(Guid jobGroupId)
|
||||||
@@ -429,68 +429,68 @@ namespace PARR.DAL.TransformServices
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
//public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||||
{
|
//{
|
||||||
var nextRun = lastRun;
|
// var nextRun = lastRun;
|
||||||
|
|
||||||
switch (periodType)
|
// switch (periodType)
|
||||||
{
|
// {
|
||||||
case (DistributionPeriodTypeEnum.Day):
|
// case (DistributionPeriodTypeEnum.Day):
|
||||||
nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
|
// nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
|
||||||
break;
|
// break;
|
||||||
case (DistributionPeriodTypeEnum.Month):
|
// case (DistributionPeriodTypeEnum.Month):
|
||||||
nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
|
// nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
|
||||||
break;
|
// break;
|
||||||
case (DistributionPeriodTypeEnum.Year):
|
// case (DistributionPeriodTypeEnum.Year):
|
||||||
nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
|
// nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
|
||||||
break;
|
// break;
|
||||||
}
|
// }
|
||||||
|
|
||||||
return nextRunModifierService.GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
|
// return nextRunModifierService.GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
|
||||||
}
|
//}
|
||||||
|
|
||||||
|
|
||||||
private DateTimeOffset GetPrevDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
//private DateTimeOffset GetPrevDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||||
{
|
//{
|
||||||
switch (periodType)
|
// switch (periodType)
|
||||||
{
|
// {
|
||||||
case (DistributionPeriodTypeEnum.Day):
|
// case (DistributionPeriodTypeEnum.Day):
|
||||||
return lastRun.AddDays(-ParseInt(distributionPeriod));
|
// return lastRun.AddDays(-ParseInt(distributionPeriod));
|
||||||
|
|
||||||
case (DistributionPeriodTypeEnum.Month):
|
// case (DistributionPeriodTypeEnum.Month):
|
||||||
return lastRun.AddMonths(-ParseInt(distributionPeriod));
|
// return lastRun.AddMonths(-ParseInt(distributionPeriod));
|
||||||
|
|
||||||
case (DistributionPeriodTypeEnum.Year):
|
// case (DistributionPeriodTypeEnum.Year):
|
||||||
return lastRun.AddYears(-ParseInt(distributionPeriod));
|
// return lastRun.AddYears(-ParseInt(distributionPeriod));
|
||||||
}
|
// }
|
||||||
|
|
||||||
return lastRun;
|
// return lastRun;
|
||||||
}
|
//}
|
||||||
|
|
||||||
|
|
||||||
public async Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
//public async Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||||
{
|
//{
|
||||||
var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
// var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
||||||
|
|
||||||
var currentStartPeriod = referenceDate;
|
// var currentStartPeriod = referenceDate;
|
||||||
var currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
// var currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||||
|
|
||||||
while (!(date >= currentStartPeriod && date < currentEndPeriod))
|
// while (!(date >= currentStartPeriod && date < currentEndPeriod))
|
||||||
{
|
// {
|
||||||
if (date > currentEndPeriod)
|
// if (date > currentEndPeriod)
|
||||||
{
|
// {
|
||||||
currentStartPeriod = currentEndPeriod;
|
// currentStartPeriod = currentEndPeriod;
|
||||||
currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
// currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||||
}
|
// }
|
||||||
else
|
// else
|
||||||
{
|
// {
|
||||||
currentEndPeriod = currentStartPeriod;
|
// currentEndPeriod = currentStartPeriod;
|
||||||
currentStartPeriod = GetPrevDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
// currentStartPeriod = GetPrevDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
return DateOnly.FromDateTime(currentStartPeriod.DateTime);
|
// return DateOnly.FromDateTime(currentStartPeriod.DateTime);
|
||||||
}
|
//}
|
||||||
|
|
||||||
|
|
||||||
private int ParseInt(string value)
|
private int ParseInt(string value)
|
||||||
@@ -507,12 +507,12 @@ namespace PARR.DAL.TransformServices
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
|
//private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
|
||||||
{
|
//{
|
||||||
var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
|
// var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
|
||||||
|
|
||||||
return result;
|
// return result;
|
||||||
}
|
//}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,17 @@
|
|||||||
using PARR.Constants;
|
namespace PARR.DAL.TransformServices
|
||||||
using PARR.DAL.DomainModels;
|
|
||||||
|
|
||||||
namespace PARR.DAL.TransformServices
|
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Сервис трансформации расписания ЕСПП в дату/расписание
|
/// Сервис трансформации расписания ЕСПП в дату/расписание
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IEsppScheduleTransformService
|
public interface IEsppScheduleTransformService
|
||||||
{
|
{
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить следующую дату согласно расписания
|
///// Получить следующую дату согласно расписания
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="esppSchedule"></param>
|
///// <param name="esppSchedule"></param>
|
||||||
/// <param name="lastRun"></param>
|
///// <param name="lastRun"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
|
//DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
|
||||||
|
|
||||||
///// <summary>
|
///// <summary>
|
||||||
///// Получить расписание
|
///// Получить расписание
|
||||||
@@ -32,31 +29,31 @@ namespace PARR.DAL.TransformServices
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<DateTimeOffset> GetNextDateAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
Task<DateTimeOffset> GetNextDateAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
||||||
|
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить расписание по jobGroupId
|
///// Получить расписание по jobGroupId
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="jobGroupId"></param>
|
///// <param name="jobGroupId"></param>
|
||||||
/// <param name="lastRun"></param>
|
///// <param name="lastRun"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
//Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить следующую дату срабатывания в указанном периоде
|
///// Получить следующую дату срабатывания в указанном периоде
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="lastRun"></param>
|
///// <param name="lastRun"></param>
|
||||||
/// <param name="periodType"></param>
|
///// <param name="periodType"></param>
|
||||||
/// <param name="distributionPeriod"></param>
|
///// <param name="distributionPeriod"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
//DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить дату начала периода распределения относительно опорной даты (Reference Date)
|
///// Получить дату начала периода распределения относительно опорной даты (Reference Date)
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="jobGroupId"></param>
|
///// <param name="jobGroupId"></param>
|
||||||
/// <param name="date"></param>
|
///// <param name="date"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset refrenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
//Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset refrenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,11 +14,11 @@ namespace PARR.DAL.TransformServices
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun);
|
DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun);
|
||||||
|
|
||||||
/// <summary>
|
///// <summary>
|
||||||
/// Получить РАБОЧИЙ день следующего срабатывания
|
///// Получить РАБОЧИЙ день следующего срабатывания
|
||||||
/// </summary>
|
///// </summary>
|
||||||
/// <param name="nextRun"></param>
|
///// <param name="nextRun"></param>
|
||||||
/// <returns></returns>
|
///// <returns></returns>
|
||||||
Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun);
|
//Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,40 +29,40 @@ namespace PARR.DAL.TransformServices
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun)
|
//public async Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun)
|
||||||
{
|
//{
|
||||||
// получаем день относительно часового пояса МСК
|
// // получаем день относительно часового пояса МСК
|
||||||
var date = DateOnly.FromDateTime(DateResolver.IsCurrentDayRelativeMskTime(nextRun) ? nextRun.Date : nextRun.Date.AddDays(1));
|
// var date = DateOnly.FromDateTime(DateResolver.IsCurrentDayRelativeMskTime(nextRun) ? nextRun.Date : nextRun.Date.AddDays(1));
|
||||||
|
|
||||||
if (await weekendDayService.IsWorkDayAsync(date, true))
|
// if (await weekendDayService.IsWorkDayAsync(date, true))
|
||||||
{
|
// {
|
||||||
//текущий nextRun рабочий день, возвращаем его
|
// //текущий nextRun рабочий день, возвращаем его
|
||||||
return nextRun;
|
// return nextRun;
|
||||||
}
|
// }
|
||||||
|
|
||||||
// ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
|
// // ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
|
||||||
int count = 20;
|
// int count = 20;
|
||||||
while (count > 0)
|
// while (count > 0)
|
||||||
{
|
// {
|
||||||
date = date.AddDays(1);
|
// date = date.AddDays(1);
|
||||||
var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
|
// var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
|
||||||
if (isWorkDay)
|
// if (isWorkDay)
|
||||||
break; // это рабочий день, выбираем его
|
// break; // это рабочий день, выбираем его
|
||||||
|
|
||||||
count--;
|
// count--;
|
||||||
|
|
||||||
if (!isWorkDay && count == 0)
|
// if (!isWorkDay && count == 0)
|
||||||
logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
|
// logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
|
||||||
}
|
// }
|
||||||
|
|
||||||
// смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
|
// // смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
|
||||||
if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
|
// if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
|
||||||
date = date.AddDays(-1);
|
// date = date.AddDays(-1);
|
||||||
|
|
||||||
// считаем новый NextRun
|
// // считаем новый NextRun
|
||||||
var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
|
// var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
|
||||||
|
|
||||||
return nextRun.AddDays(dayCount);
|
// return nextRun.AddDays(dayCount);
|
||||||
}
|
//}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,17 +75,18 @@ namespace PARR.JobAutoControl
|
|||||||
InitiatorIp = null,
|
InitiatorIp = null,
|
||||||
InitiatorParrComponentId = Constants.ParrComponentsEnum.JobAutoControl
|
InitiatorParrComponentId = Constants.ParrComponentsEnum.JobAutoControl
|
||||||
}
|
}
|
||||||
});
|
}).ToList();
|
||||||
|
|
||||||
var msgStrList = msgList.Select(t => JsonSerializer.Serialize(t));
|
//var msgStrList = msgList.Select(t => JsonSerializer.Serialize(t));
|
||||||
|
|
||||||
// отправляем задания в очередь template matcher`a
|
// отправляем задания в очередь 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)
|
if (!sendResult.IsSuccess)
|
||||||
logger.LogError($"Ошибка при отправке сообщений ({msgStrList.Count()} шт.) в очередь.");
|
logger.LogError($"Ошибка при отправке сообщений ({msgList.Count()} шт.) в очередь.");
|
||||||
else
|
else
|
||||||
logger.LogInformation($"Выполнена отправка сообщений в очередь, {msgStrList.Count()} шт.");
|
logger.LogInformation($"Выполнена отправка сообщений в очередь, {msgList.Count()} шт.");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ using PARR.DAL.Contracts;
|
|||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.Master.Settings;
|
using PARR.Master.Settings;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace PARR.Master.Services
|
namespace PARR.Master.Services
|
||||||
@@ -20,6 +21,11 @@ namespace PARR.Master.Services
|
|||||||
private readonly MqSettings mqSettings;
|
private readonly MqSettings mqSettings;
|
||||||
private readonly IMqService mqService;
|
private readonly IMqService mqService;
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
};
|
||||||
|
|
||||||
public OrderMasterService(
|
public OrderMasterService(
|
||||||
ILogger<OrderMasterService> logger,
|
ILogger<OrderMasterService> logger,
|
||||||
IOrderService orderService,
|
IOrderService orderService,
|
||||||
@@ -60,7 +66,7 @@ namespace PARR.Master.Services
|
|||||||
|
|
||||||
//находим наряды где статусы не равны, добавляем их в Rabbit
|
//находим наряды где статусы не равны, добавляем их в Rabbit
|
||||||
var ordersWithStatusNotEqual = await GetOrdresWithStatusCodeNotEqualAsync();
|
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.");
|
logger.LogInformation($"Ищу наряды где статусы не равны. Найдено нарядов: {ordersWithStatusNotEqual.Count()}. Добавляю их в RabbitMQ.");
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,9 @@ using Microsoft.Extensions.Logging;
|
|||||||
using PARR.BLL.Services.Interfaces;
|
using PARR.BLL.Services.Interfaces;
|
||||||
using PARR.Common.Domain;
|
using PARR.Common.Domain;
|
||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.NextRunServices;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
using PARR.DAL.TransformServices;
|
|
||||||
using PARR.NextRun.Settings;
|
using PARR.NextRun.Settings;
|
||||||
|
|
||||||
namespace PARR.NextRun
|
namespace PARR.NextRun
|
||||||
@@ -41,14 +40,15 @@ namespace PARR.NextRun
|
|||||||
using (var scope = serviceProvider.CreateScope())
|
using (var scope = serviceProvider.CreateScope())
|
||||||
{
|
{
|
||||||
//var appInWorkService = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
|
//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 templateService = scope.ServiceProvider.GetService<ITemplateService>();
|
||||||
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
|
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
|
||||||
|
var nextRunService = scope.ServiceProvider.GetService<INextRunService>();
|
||||||
|
|
||||||
if (templateService == null || esppSchService == null || jobGroupService == null)
|
if (templateService == null || nextRunService == null || jobGroupService == null)
|
||||||
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(IEsppScheduleTransformService)} или {nameof(IJobGroupService)}");
|
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}");
|
||||||
|
|
||||||
await HandlerAsync(templateService, esppSchService, jobGroupService);
|
await HandlerAsync(templateService, nextRunService, jobGroupService);
|
||||||
}
|
}
|
||||||
}, workerSettings.RepeatEvery);
|
}, workerSettings.RepeatEvery);
|
||||||
}
|
}
|
||||||
@@ -58,7 +58,7 @@ namespace PARR.NextRun
|
|||||||
/// Рассчет следующей даты срабатываения
|
/// Рассчет следующей даты срабатываения
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
private async Task HandlerAsync(ITemplateService templateService, IEsppScheduleTransformService esppScheduleTransformService, IJobGroupService jobGroupService)
|
private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
|
||||||
{
|
{
|
||||||
#region логика для групп у которых не включено автораспределение
|
#region логика для групп у которых не включено автораспределение
|
||||||
|
|
||||||
@@ -77,7 +77,8 @@ namespace PARR.NextRun
|
|||||||
foreach (var group in groups)
|
foreach (var group in groups)
|
||||||
{
|
{
|
||||||
//получаем по каждой группе следующий nextRun и сравниваем с существующим, если не равны, то обновляем
|
//получаем по каждой группе следующий 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 в БД не равен расчетному
|
// Загружаем только шаблоны текущей группы где nextRun в БД не равен расчетному
|
||||||
@@ -109,7 +110,7 @@ namespace PARR.NextRun
|
|||||||
|
|
||||||
//todo: когда будет автораспределение, для него придумать логику как считать
|
//todo: когда будет автораспределение, для него придумать логику как считать
|
||||||
|
|
||||||
|
//TODO:!!! Написать логику для групп у которых включено автораспределение!!!
|
||||||
|
|
||||||
|
|
||||||
#region old logic
|
#region old logic
|
||||||
|
|||||||
@@ -1,22 +1,14 @@
|
|||||||
using PARR.DAL.Models;
|
using PARR.BLL.Domain.Mq;
|
||||||
|
|
||||||
namespace PARR.TemplateDistributor
|
namespace PARR.TemplateDistributor
|
||||||
{
|
{
|
||||||
public interface ITemplateDistributor
|
public interface ITemplateDistributor
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Формирует расписание запуска для шаблонов относительно одной РР (без сохранения в БД), (реализует оба режима распределения РР)
|
/// Обновляет NextRun (сохраняет в БД)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="templates"></param>
|
/// <param name="jobGroupId"></param>
|
||||||
/// <param name="applicationInWorkId"></param>
|
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<List<Template>> DistributeTemplateAsync(List<Template> templates, Guid applicationInWorkId, Guid workGroupid);
|
Task DistributeAsync(TemplateDistributorMq mqResponse);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Обновляет расписание запуска шаблонов по РР (сохраняет в БД)
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="applicationInWorkId"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
Task UpdateScheduleAsync(Guid applicationInWorkId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ namespace PARR.TemplateDistributor
|
|||||||
|
|
||||||
public async Task StopAsync()
|
public async Task StopAsync()
|
||||||
{
|
{
|
||||||
await mqService.DisposeAsync();
|
await mqService.DisposeAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateScheduleAsync(string msg)
|
private async Task UpdateScheduleAsync(string msg)
|
||||||
@@ -53,9 +53,9 @@ namespace PARR.TemplateDistributor
|
|||||||
if (query == null)
|
if (query == null)
|
||||||
return;
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,10 +63,9 @@ namespace PARR.TemplateDistributor
|
|||||||
{
|
{
|
||||||
var service = scope.ServiceProvider.GetService<ITemplateDistributor>();
|
var service = scope.ServiceProvider.GetService<ITemplateDistributor>();
|
||||||
if (service == null)
|
if (service == null)
|
||||||
throw new Exception($"Не найден сервис: {nameof(service.GetType)}");
|
throw new Exception($"Не найден сервис: {nameof(ITemplateDistributor)}");
|
||||||
|
|
||||||
await service.UpdateScheduleAsync(query.ApplicationInWorkId);
|
|
||||||
|
|
||||||
|
await service.DistributeAsync(query);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,6 @@
|
|||||||
{
|
{
|
||||||
internal interface IValidatorService
|
internal interface IValidatorService
|
||||||
{
|
{
|
||||||
Task<bool> IsValidApplicationAndWorksAsync(Guid applicationInWorkId);
|
Task<bool> IsValidJobGroupAsync(Guid applicationInWorkId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.DAL.Models.Job;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
|
|
||||||
namespace PARR.TemplateDistributor.Services
|
namespace PARR.TemplateDistributor.Services
|
||||||
{
|
{
|
||||||
@@ -17,32 +19,30 @@ namespace PARR.TemplateDistributor.Services
|
|||||||
this.serviceProvider = serviceProvider;
|
this.serviceProvider = serviceProvider;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
public async Task<bool> IsValidApplicationAndWorksAsync(Guid applicationInWorkId)
|
public async Task<bool> IsValidJobGroupAsync(Guid jobGroupId)
|
||||||
{
|
{
|
||||||
using (var scope = serviceProvider.CreateScope())
|
using (var scope = serviceProvider.CreateScope())
|
||||||
{
|
{
|
||||||
//TODO Migratin to Job
|
|
||||||
//var service = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
|
|
||||||
|
|
||||||
//if (service == null)
|
var service = scope.ServiceProvider.GetService<IJobGroupService>();
|
||||||
// throw new Exception($"Не найден сервис: {nameof(IApplicationsInWorkService)}");
|
|
||||||
|
|
||||||
//var appInWork = await service.Get()//TODO Migratin to Job
|
if (service == null)
|
||||||
// //.Include(aiw => aiw.EsppSchValues)
|
throw new Exception($"Не найден сервис: {nameof(IJobGroupService)}");
|
||||||
// .FirstOrDefaultAsync(t => t.Id == applicationInWorkId);
|
|
||||||
|
|
||||||
//if (appInWork == null)
|
var jobGroup = await service.Get().Include(t => t.DistributionConfig).FirstOrDefaultAsync(t => t.Id == jobGroupId);
|
||||||
//{
|
|
||||||
// logger.LogError($"Не найдена регалментная работа {nameof(applicationInWorkId)}: {applicationInWorkId}");
|
|
||||||
// return false;
|
|
||||||
//}
|
|
||||||
|
|
||||||
//if (appInWork.IsAutoDistributionEnabled && appInWork.EsppSchValues.Count !=1)
|
if (jobGroup == null)
|
||||||
//{
|
{
|
||||||
// logger.LogError($"Регалментная работа {nameof(applicationInWorkId)}: {applicationInWorkId} должна иметь только одно значение EsppSchTypeValue" +
|
logger.LogError($"Не найдена группа работ с Id: {jobGroupId}", jobGroupId);
|
||||||
// $", соответствующее режиму равномерного распределения по периоду");
|
return false;
|
||||||
// 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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,438 +1,103 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using PARR.BLL.Services.Interfaces;
|
using PARR.BLL.Domain.Mq;
|
||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Contracts;
|
||||||
|
using PARR.DAL.NextRunServices;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.DAL.TransformServices;
|
|
||||||
using System.Reflection.Metadata.Ecma335;
|
|
||||||
|
|
||||||
namespace PARR.TemplateDistributor
|
namespace PARR.TemplateDistributor
|
||||||
{
|
{
|
||||||
internal class TemplateDistributor : ITemplateDistributor
|
internal class TemplateDistributor : ITemplateDistributor
|
||||||
{
|
{
|
||||||
private readonly ILogger<TemplateDistributor> logger;
|
private readonly ILogger<TemplateDistributor> logger;
|
||||||
|
private readonly INextRunService nextRunService;
|
||||||
private readonly ITemplateService templateService;
|
private readonly ITemplateService templateService;
|
||||||
private readonly IApplicationsInWorkService applicationsInWorkService;
|
private readonly IRobotConfigurationService robotConfigurationService;
|
||||||
private readonly ICalendarService calendarService;
|
|
||||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
|
||||||
private readonly IWeekendDayService weekendDayService;
|
|
||||||
private readonly INextRunModifierService nextRunModifierService;
|
|
||||||
|
|
||||||
public TemplateDistributor(
|
public TemplateDistributor(
|
||||||
ILogger<TemplateDistributor> logger,
|
ILogger<TemplateDistributor> logger,
|
||||||
|
INextRunService nextRunService,
|
||||||
ITemplateService templateService,
|
ITemplateService templateService,
|
||||||
IApplicationsInWorkService applicationsInWorkService,
|
IRobotConfigurationService robotConfigurationService
|
||||||
ICalendarService calendarService,
|
|
||||||
IEsppScheduleTransformService esppScheduleTransformService,
|
|
||||||
IWeekendDayService weekendDayService,
|
|
||||||
INextRunModifierService nextRunModifierService
|
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
|
this.nextRunService = nextRunService;
|
||||||
this.templateService = templateService;
|
this.templateService = templateService;
|
||||||
this.applicationsInWorkService = applicationsInWorkService;
|
this.robotConfigurationService = robotConfigurationService;
|
||||||
this.calendarService = calendarService;
|
|
||||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
|
||||||
this.weekendDayService = weekendDayService;
|
|
||||||
this.nextRunModifierService = nextRunModifierService;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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
|
var distributedTemplates = await nextRunService.GetNextRunForJobGroupWithAutoDistributionAsync(jobGroupId);
|
||||||
//.ThenInclude(h => h!.WorkGroup)
|
|
||||||
.Where(t => t.JobId == applicationInWorkId && t.Unit!.BaseFields!.WorkGroup != null)//TODO Migratin to Job
|
|
||||||
.ToListAsync();
|
|
||||||
|
|
||||||
//Группируем шаблоны по рабочим группам
|
if (distributedTemplates == null)
|
||||||
var workGroupsWithTemplates = templates.GroupBy(t => t.Unit!.BaseFields!.WorkGroup);
|
|
||||||
|
|
||||||
/*foreach (var workGroupWithTemplates in workGroupsWithTemplates)
|
|
||||||
{
|
{
|
||||||
var wgId = (Guid)workGroupWithTemplates.Key!;
|
logger.LogWarning("При распределении шаблонов по jobGroupId {jobGroupId} вернулся null. Это ошибка. Прекращаю распределение.", jobGroupId);
|
||||||
var values = workGroupWithTemplates.ToList();
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
//Обновляем сразу время при необходимости, так как дальше будем работать только с датой
|
// получить список шаблонов, сравнить их с распределенными, обновить даты, сохранить
|
||||||
var timesList = values.Select(t => t.NextRun.TimeOfDay).Distinct().ToList();
|
var groupTemplates = await templateService.Get()
|
||||||
if (timesList.Count() > 1 || (timesList.Count() == 1 && timesList[0] != appInWork!.ReferenceDate.TimeOfDay))
|
.Include(t => t.RobotConfigurations)
|
||||||
|
.Where(t => t.Job.GroupId == jobGroupId)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
if (!groupTemplates.Any())
|
||||||
|
{
|
||||||
|
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))
|
||||||
{
|
{
|
||||||
values.ForEach(t =>
|
if (templateDb.NextRun != distributedTemplate.NextRun)
|
||||||
{
|
{
|
||||||
if (t.NextRun.TimeOfDay != appInWork!.ReferenceDate.TimeOfDay)
|
templateDb.NextRun = distributedTemplate.NextRun;
|
||||||
t.NextRun = new DateTimeOffset(t.NextRun.Year, t.NextRun.Month, t.NextRun.Day,
|
templateDb.LastRun = distributedTemplate.NextRunOld;
|
||||||
appInWork!.ReferenceDate.Hour, appInWork!.ReferenceDate.Minute, appInWork!.ReferenceDate.Second,
|
templateDb.DateModified = DateTimeOffset.UtcNow;
|
||||||
new TimeSpan(0, 0, 0));
|
|
||||||
});
|
// ставим задание роботу - обновить расписания
|
||||||
if (!await templateService.CommitAsync())
|
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, templateDb);
|
||||||
{
|
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
|
||||||
logger.LogError($"Ошибка записи изменений в БД при актуализации времени NextRun шаблонов РР({applicationInWorkId})");
|
|
||||||
return;
|
updatedCount++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else
|
||||||
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(
|
logger.LogWarning("Шаблон с Id {templateId} не найден в распределённых данных.", templateDb.Id);
|
||||||
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>
|
if (updatedCount > 0)
|
||||||
/// Получить список рабочих дней из календаря и перенести прошедшие даты на следующий период по РР
|
|
||||||
/// </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 (await templateService.CommitAsync(mqResponse.Initiator))
|
||||||
if (templatesInWd.Any() && templatesInWd.Count > wd.Value)
|
|
||||||
{
|
{
|
||||||
result.AddRange(templatesInWd.Skip(wd.Value).Take(templatesInWd.Count - wd.Value).ToList());
|
logger.LogInformation("Обновлено {updatedCount} шаблонов в БД для jobGroupId {jobGroupId}. Для расписаний установлен статус: {taskStatus}", updatedCount, jobGroupId, TaskStatusEnum.Updating.ToString());
|
||||||
distributionPlan[wd.Key] -= wd.Value;
|
|
||||||
}
|
}
|
||||||
else
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private Dictionary<DateOnly, int> GetDistributionPlan(List<DateOnly> workDays, int templateCount)
|
|
||||||
{
|
|
||||||
var result = new Dictionary<DateOnly, int>();
|
|
||||||
//Заполняем будующий план датами из полученных на входе данных
|
|
||||||
foreach (var wd in workDays)
|
|
||||||
{
|
|
||||||
var workDate = new DateOnly(wd.Year, wd.Month, wd.Day);
|
|
||||||
result.Add(workDate, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
var templateDistributedCount = 0;//количество распределённых на текущий момент шаблонов
|
|
||||||
|
|
||||||
//Если количество шаблонов больше количества рабочих дней, то сразу распределяем их равным количеством по всем рабочим дням
|
|
||||||
if (templateCount >= workDays.Count)
|
|
||||||
{
|
|
||||||
//количеством шаблонов на один рабочий день
|
|
||||||
var mainPartTemplateCountToDistribute = templateCount / workDays.Count;
|
|
||||||
|
|
||||||
//перебираем рабочие дня и записываем количество шаблонов
|
|
||||||
foreach (var item in result)
|
|
||||||
{
|
{
|
||||||
result[item.Key] = mainPartTemplateCountToDistribute;
|
logger.LogError("Ошибка при обновлении записей в БД. jobGroupId {jobGroupId}, требовалось обновить шаблонов: {updatedCount}", jobGroupId, updatedCount);
|
||||||
|
|
||||||
templateDistributedCount += mainPartTemplateCountToDistribute;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else
|
||||||
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 не может быть меньше одного дня
|
logger.LogInformation("Для jobGroupId {jobGroupId} не найдено изменений. Ничего не обновлено.", jobGroupId);
|
||||||
//if (currentStepBetweenTemplates > 0)
|
|
||||||
//{
|
|
||||||
result[result.ElementAt(currentDayIndex).Key] += 1;
|
|
||||||
templateDistributedCount++;
|
|
||||||
currentDayIndex += (int)Math.Floor(currentStepBetweenTemplates);
|
|
||||||
//}
|
|
||||||
|
|
||||||
currentStepBetweenTemplates = daysBetweenTemplates + balance;
|
|
||||||
balance = daysBetweenTemplates - currentStepBetweenTemplates;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,25 +4,23 @@ namespace PARR.TemplateDistributorWorker
|
|||||||
{
|
{
|
||||||
public class Worker : BackgroundService
|
public class Worker : BackgroundService
|
||||||
{
|
{
|
||||||
private readonly ILogger<Worker> _logger;
|
|
||||||
private readonly IMqTemplateDistributor mqTemplateDistributor;
|
private readonly IMqTemplateDistributor mqTemplateDistributor;
|
||||||
|
|
||||||
public Worker(ILogger<Worker> logger, IMqTemplateDistributor mqTemplateDistributor)
|
public Worker(ILogger<Worker> logger, IMqTemplateDistributor mqTemplateDistributor)
|
||||||
{
|
{
|
||||||
_logger = logger;
|
|
||||||
this.mqTemplateDistributor = mqTemplateDistributor;
|
this.mqTemplateDistributor = mqTemplateDistributor;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||||
{
|
{
|
||||||
await mqTemplateDistributor.StartAsync();
|
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();
|
await mqTemplateDistributor.StopAsync();
|
||||||
|
await base.StopAsync(cancellationToken);
|
||||||
return base.StopAsync(cancellationToken);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,10 +10,10 @@
|
|||||||
},
|
},
|
||||||
"Serilog": {
|
"Serilog": {
|
||||||
"MinimumLevel": {
|
"MinimumLevel": {
|
||||||
"Default": "Information",
|
"Default": "Debug",
|
||||||
"Override": {
|
"Override": {
|
||||||
"Microsoft": "Warning",
|
"Microsoft": "Debug",
|
||||||
"Microsoft.Hosting.Lifetime": "Information"
|
"Microsoft.Hosting.Lifetime": "Debug"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"WriteTo": [
|
"WriteTo": [
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using PARR.DAL.NextRunServices.Models;
|
using PARR.DAL.NextRunServices;
|
||||||
|
using PARR.DAL.NextRunServices.Models;
|
||||||
using PARR.DAL.NextRunServices.Subservices;
|
using PARR.DAL.NextRunServices.Subservices;
|
||||||
|
|
||||||
namespace PARR.Test.NextRun
|
namespace PARR.Test.NextRun
|
||||||
@@ -6,10 +7,12 @@ namespace PARR.Test.NextRun
|
|||||||
internal class NextRunTest
|
internal class NextRunTest
|
||||||
{
|
{
|
||||||
private readonly ITemplateDistributor templateDistributor;
|
private readonly ITemplateDistributor templateDistributor;
|
||||||
|
private readonly INextRunService nextRunService;
|
||||||
|
|
||||||
public NextRunTest(ITemplateDistributor templateDistributor)
|
public NextRunTest(ITemplateDistributor templateDistributor, INextRunService nextRunService)
|
||||||
{
|
{
|
||||||
this.templateDistributor = templateDistributor;
|
this.templateDistributor = templateDistributor;
|
||||||
|
this.nextRunService = nextRunService;
|
||||||
}
|
}
|
||||||
|
|
||||||
int periodDays = 10;
|
int periodDays = 10;
|
||||||
@@ -17,8 +20,18 @@ namespace PARR.Test.NextRun
|
|||||||
|
|
||||||
public async Task Test()
|
public async Task Test()
|
||||||
{
|
{
|
||||||
await DistributeTemplatesAsync();
|
//await DistributeTemplatesAsync();
|
||||||
//await GetValidNextRunForTemplateAsync();
|
//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>
|
/// <summary>
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ services:
|
|||||||
fluentd-buffer-limit: '52428800'
|
fluentd-buffer-limit: '52428800'
|
||||||
tag: parr.template-distributor.serilog
|
tag: parr.template-distributor.serilog
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 2
|
replicas: 1
|
||||||
networks:
|
networks:
|
||||||
parr-network:
|
parr-network:
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user