feat(api, dal, nextRun): переделал вызов рассчета NextRun на INextRunService
This commit is contained in:
@@ -24,21 +24,21 @@ namespace PARR.API.Controllers.V1
|
||||
private readonly IClientService clientService;
|
||||
private readonly ITemplateService templateService;
|
||||
private readonly IUnitService unitService;
|
||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
private readonly ILogger<AgentTaskController> logger;
|
||||
|
||||
public AgentTaskController(
|
||||
IClientService clientService,
|
||||
ITemplateService templateService,
|
||||
IUnitService unitService,
|
||||
IEsppScheduleTransformService esppScheduleTransformService,
|
||||
//IEsppScheduleTransformService esppScheduleTransformService,
|
||||
ILogger<AgentTaskController> logger
|
||||
)
|
||||
{
|
||||
this.clientService = clientService;
|
||||
this.templateService = templateService;
|
||||
this.unitService = unitService;
|
||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@@ -51,82 +51,84 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpGet(ApiRoutes.AgentTask.GetByIp)]
|
||||
public async Task<IActionResult> GetByClientIp([FromQuery] AgentTaskGetByIpQuery request)
|
||||
{
|
||||
//ПАРР-ДВС-ПТК__ВРТ-DVGD-SDMI-WEB-01-ДВС__ПРОЧЕЕ(РАБОТЫ)
|
||||
//10.99.253.65
|
||||
//2023-10-16
|
||||
|
||||
var ip = request.Ip ?? clientService.GetClientIp()?.ToString();
|
||||
return Ok("Метод не реализован");
|
||||
////ПАРР-ДВС-ПТК__ВРТ-DVGD-SDMI-WEB-01-ДВС__ПРОЧЕЕ(РАБОТЫ)
|
||||
////10.99.253.65
|
||||
////2023-10-16
|
||||
|
||||
if (string.IsNullOrEmpty(ip))
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Client IP address is null." } }));
|
||||
//var ip = request.Ip ?? clientService.GetClientIp()?.ToString();
|
||||
|
||||
//var date = request.Date ?? DateTimeOffset.UtcNow;
|
||||
var date = DateTimeOffset.UtcNow;
|
||||
//if (string.IsNullOrEmpty(ip))
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Client IP address is null." } }));
|
||||
|
||||
//Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
|
||||
////var date = request.Date ?? DateTimeOffset.UtcNow;
|
||||
//var date = DateTimeOffset.UtcNow;
|
||||
|
||||
// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
|
||||
var units = await unitService.GetWithIncludes().AsNoTracking().Where(t => t.UnitValues.Any(v => v.Field!.AihitName == "IP_АДРЕС" && v.Value!.Value == ip)).ToListAsync();
|
||||
var templates = await templateService.Get()
|
||||
.Include(t => t.RobotConfigurations)
|
||||
.Include(t => t.Job)
|
||||
.ThenInclude(t=>t!.Group)
|
||||
.ThenInclude(t => t!.EsppSchValues)
|
||||
.Include(t => t.Unit)
|
||||
.Where(t => units.Any(u=>u.Id == t.UnitId)
|
||||
//&& t.ApplicationsInWork!.IsAgent == true//TODO Migration to job
|
||||
&& t.IsActiveTemplate == true
|
||||
&& t.IsActiveSchedule == true
|
||||
//&& t.ApplicationsInWork!.NextRun.DateTime.Date == date.Date.Date
|
||||
&& t.NextRun.DateTime.Date == date.Date.Date
|
||||
&& t.RobotConfigurations.All(c => c.TaskStatusCode == (int)TaskStatusEnum.Ok)
|
||||
&& t.Job!.Group!.EsppSchValues.Any()//.ApplicationsInWork.EsppSchValues.Any()
|
||||
).ToListAsync();
|
||||
////Агент получает задания, если `IsAgent = true`, шаблон и расписания активны, и статус синхронизации шаблона и расписания `= Ok`, и `NextRun = сегодня`, так же если у ApplicationInWork есть расписание.
|
||||
|
||||
if (!templates.Any())
|
||||
return NoContent();
|
||||
//// С одним IP может быть несколько информационных систем, так что может быть несколько хостов
|
||||
//var units = await unitService.GetWithIncludes().AsNoTracking().Where(t => t.UnitValues.Any(v => v.Field!.AihitName == "IP_АДРЕС" && v.Value!.Value == ip)).ToListAsync();
|
||||
//var templates = await templateService.Get()
|
||||
// .Include(t => t.RobotConfigurations)
|
||||
// .Include(t => t.Job)
|
||||
// .ThenInclude(t=>t!.Group)
|
||||
// .ThenInclude(t => t!.EsppSchValues)
|
||||
// .Include(t => t.Unit)
|
||||
// .Where(t => units.Any(u=>u.Id == t.UnitId)
|
||||
// //&& t.ApplicationsInWork!.IsAgent == true//TODO Migration to job
|
||||
// && t.IsActiveTemplate == true
|
||||
// && t.IsActiveSchedule == true
|
||||
// //&& t.ApplicationsInWork!.NextRun.DateTime.Date == date.Date.Date
|
||||
// && t.NextRun.DateTime.Date == date.Date.Date
|
||||
// && t.RobotConfigurations.All(c => c.TaskStatusCode == (int)TaskStatusEnum.Ok)
|
||||
// && t.Job!.Group!.EsppSchValues.Any()//.ApplicationsInWork.EsppSchValues.Any()
|
||||
// ).ToListAsync();
|
||||
|
||||
var response = new AgentTaskMinResponse
|
||||
{
|
||||
Scheduled = new List<AgentTaskMinScheduleResponse>()
|
||||
};
|
||||
//if (!templates.Any())
|
||||
// return NoContent();
|
||||
|
||||
foreach (var template in templates)
|
||||
{
|
||||
//var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
|
||||
var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
|
||||
//var response = new AgentTaskMinResponse
|
||||
//{
|
||||
// Scheduled = new List<AgentTaskMinScheduleResponse>()
|
||||
//};
|
||||
|
||||
if (!templateSchedule.Any())
|
||||
{
|
||||
logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
|
||||
$"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
|
||||
continue;
|
||||
}
|
||||
//foreach (var template in templates)
|
||||
//{
|
||||
// //var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.ApplicationInWorkId, template.ApplicationsInWork!.LastRun ?? template.ApplicationsInWork!.NextRun);
|
||||
// var templateSchedule = await esppScheduleTransformService.GetNextScheduleAsync(template.Job!.GroupId, template.NextRun);
|
||||
|
||||
if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
|
||||
{
|
||||
logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
|
||||
$"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
|
||||
continue;
|
||||
}
|
||||
// if (!templateSchedule.Any())
|
||||
// {
|
||||
// logger.LogWarning($"Запросили раписание для агента по NextRun и вернулся пустой список! Такого не должно быть! " +
|
||||
// $"JobGroupId: {template.Job.GroupId}, latRun: {template.LastRun}, NextRun: {template.NextRun}, ip: {ip}, date: {date}");
|
||||
// continue;
|
||||
// }
|
||||
|
||||
templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
|
||||
{
|
||||
Name = template.Job.Group.AgentName ?? "",
|
||||
Script = template.Job.Group.AgentScript ?? "",
|
||||
StartAt = item,
|
||||
TemplateId = template.Id
|
||||
}));
|
||||
}
|
||||
// if (string.IsNullOrEmpty(template.Job.Group!.AgentName) && string.IsNullOrEmpty(template.Job.Group!.AgentScript))
|
||||
// {
|
||||
// logger.LogWarning($"Запросили задание для агента с пустыми значениями AgentName && AgentScript. Такого не должно быть! " +
|
||||
// $"JobGroupId: {template.Job.GroupId}, AgentName: {template.Job.Group.AgentName}, AgentScript: {template.Job.Group.AgentScript} , ip: {ip}, date: {date}");
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (!response.Scheduled.Any())
|
||||
return NoContent();
|
||||
// templateSchedule.ForEach(item => response.Scheduled.Add(new AgentTaskMinScheduleResponse
|
||||
// {
|
||||
// Name = template.Job.Group.AgentName ?? "",
|
||||
// Script = template.Job.Group.AgentScript ?? "",
|
||||
// StartAt = item,
|
||||
// TemplateId = template.Id
|
||||
// }));
|
||||
//}
|
||||
|
||||
response.Scheduled = response.Scheduled.OrderBy(t => t.StartAt).ToList();
|
||||
//if (!response.Scheduled.Any())
|
||||
// return NoContent();
|
||||
|
||||
logger.LogInformation($"Агент с IP-адресом {ip} получил задания: [{string.Join(';', response.Scheduled.Select(s => $"StartAt:{s.StartAt}, Name:{s.Name}, TemplateId:{s.TemplateId}"))}]");
|
||||
//response.Scheduled = response.Scheduled.OrderBy(t => t.StartAt).ToList();
|
||||
|
||||
return Ok(response);
|
||||
//logger.LogInformation($"Агент с IP-адресом {ip} получил задания: [{string.Join(';', response.Scheduled.Select(s => $"StartAt:{s.StartAt}, Name:{s.Name}, TemplateId:{s.TemplateId}"))}]");
|
||||
|
||||
//return Ok(response);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ using PARR.DAL.Contracts;
|
||||
using PARR.DAL.DomainServices.Shortcodes;
|
||||
using PARR.DAL.DomainServices.Shortcodes.Models;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.DAL.NextRunServices;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.DAL.TransformServices;
|
||||
|
||||
@@ -25,31 +26,34 @@ namespace PARR.API.Controllers.V1
|
||||
private readonly IMapper mapper;
|
||||
private readonly SettingsFromDb settingsFromDb;
|
||||
private readonly IRobotConfigurationService robotConfigurationService;
|
||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
private readonly ILogger<RobotTaskController> logger;
|
||||
private readonly IClientService clientService;
|
||||
private readonly IRobotHistoryService robotHistoryService;
|
||||
private readonly IShortcodesService shortcodesService;
|
||||
private readonly INextRunService nextRunService;
|
||||
|
||||
public RobotTaskController(
|
||||
IMapper mapper,
|
||||
SettingsFromDb settingsFromDb,
|
||||
IRobotConfigurationService robotConfigurationService,
|
||||
IEsppScheduleTransformService esppScheduleTransformService,
|
||||
//IEsppScheduleTransformService esppScheduleTransformService,
|
||||
ILogger<RobotTaskController> logger,
|
||||
IClientService clientService,
|
||||
IRobotHistoryService robotHistoryService,
|
||||
IShortcodesService shortcodesService
|
||||
IShortcodesService shortcodesService,
|
||||
INextRunService nextRunService
|
||||
)
|
||||
{
|
||||
this.mapper = mapper;
|
||||
this.settingsFromDb = settingsFromDb;
|
||||
this.robotConfigurationService = robotConfigurationService;
|
||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
this.logger = logger;
|
||||
this.clientService = clientService;
|
||||
this.robotHistoryService = robotHistoryService;
|
||||
this.shortcodesService = shortcodesService;
|
||||
this.nextRunService = nextRunService;
|
||||
}
|
||||
|
||||
|
||||
@@ -306,7 +310,8 @@ namespace PARR.API.Controllers.V1
|
||||
//пока у нас выключено автораспределение, считает по refDate
|
||||
//TODO: когда заработает автораспределение, будем думать!!!!!
|
||||
|
||||
var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
if (nextRun != template.NextRun)
|
||||
{
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace PARR.API.Controllers.V1
|
||||
public class TestController : BaseApiController
|
||||
{
|
||||
private readonly IClientService clientService;
|
||||
private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
private readonly IRedisCacheService redisCacheService;
|
||||
private readonly IWeekendDayService weekendDayService;
|
||||
private readonly IUnitService unitService;
|
||||
@@ -37,7 +37,7 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
public TestController(
|
||||
IClientService clientService,
|
||||
IEsppScheduleTransformService esppScheduleTransformService,
|
||||
//IEsppScheduleTransformService esppScheduleTransformService,
|
||||
IRedisCacheService redisCacheService,
|
||||
IWeekendDayService weekendDayService,
|
||||
IUnitService unitService,
|
||||
@@ -49,7 +49,7 @@ namespace PARR.API.Controllers.V1
|
||||
)
|
||||
{
|
||||
this.clientService = clientService;
|
||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
this.redisCacheService = redisCacheService;
|
||||
this.weekendDayService = weekendDayService;
|
||||
this.unitService = unitService;
|
||||
@@ -76,32 +76,32 @@ namespace PARR.API.Controllers.V1
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить следующую дату запуска
|
||||
/// </summary>
|
||||
/// <param name="applicationInWorkId"></param>
|
||||
/// <param name="lastRunDate"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
|
||||
public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
||||
{
|
||||
var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
|
||||
return Ok(result);
|
||||
}
|
||||
///// <summary>
|
||||
///// Получить следующую дату запуска
|
||||
///// </summary>
|
||||
///// <param name="applicationInWorkId"></param>
|
||||
///// <param name="lastRunDate"></param>
|
||||
///// <returns></returns>
|
||||
//[HttpGet(ApiRoutes.Test.GetNextScheduleDate)]
|
||||
//public async Task<IActionResult> GetNextScheduleDate([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
||||
//{
|
||||
// var result = await esppScheduleTransformService.GetNextDateAsync(applicationInWorkId, lastRunDate);
|
||||
// return Ok(result);
|
||||
//}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить следующее расписание
|
||||
/// </summary>
|
||||
/// <param name="applicationInWorkId"></param>
|
||||
/// <param name="lastRunDate"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.Test.GetNextSchedule)]
|
||||
public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
||||
{
|
||||
var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
|
||||
return Ok(result);
|
||||
}
|
||||
///// <summary>
|
||||
///// Получить следующее расписание
|
||||
///// </summary>
|
||||
///// <param name="applicationInWorkId"></param>
|
||||
///// <param name="lastRunDate"></param>
|
||||
///// <returns></returns>
|
||||
//[HttpGet(ApiRoutes.Test.GetNextSchedule)]
|
||||
//public async Task<IActionResult> GetNextSchedule([FromRoute] Guid applicationInWorkId, [FromRoute] DateTimeOffset lastRunDate)
|
||||
//{
|
||||
// var result = await esppScheduleTransformService.GetNextScheduleAsync(applicationInWorkId, lastRunDate);
|
||||
// return Ok(result);
|
||||
//}
|
||||
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
|
||||
using InfluxDB.Client.Api.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.DomainServices.Shortcodes;
|
||||
|
||||
@@ -68,7 +68,7 @@ namespace PARR.DAL.TransformServices
|
||||
return GetNextDate(esppSchedule, referenceDate);
|
||||
}
|
||||
|
||||
public DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
||||
private DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
||||
{
|
||||
var nextRun = referenceDate;
|
||||
|
||||
@@ -111,62 +111,62 @@ namespace PARR.DAL.TransformServices
|
||||
}
|
||||
|
||||
|
||||
private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
||||
{
|
||||
// расписание на оставшееся на сегодня время. его так мало...
|
||||
referenceDate = referenceDate.UtcDateTime;
|
||||
var schedules = new List<DateTimeOffset>();
|
||||
var curTime = referenceDate;
|
||||
//private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset referenceDate)
|
||||
//{
|
||||
// // расписание на оставшееся на сегодня время. его так мало...
|
||||
// referenceDate = referenceDate.UtcDateTime;
|
||||
// var schedules = new List<DateTimeOffset>();
|
||||
// var curTime = referenceDate;
|
||||
|
||||
//Если ещё не произошло то добавляем расписание, возможно это новое AiW и он ещё ниразу не запускался.
|
||||
//lastRun это будущее
|
||||
if (referenceDate >= DateTimeOffset.UtcNow && referenceDate <= DateTimeOffset.UtcNow.EndOfDay())
|
||||
schedules.Add(referenceDate);
|
||||
// //Если ещё не произошло то добавляем расписание, возможно это новое AiW и он ещё ниразу не запускался.
|
||||
// //lastRun это будущее
|
||||
// if (referenceDate >= DateTimeOffset.UtcNow && referenceDate <= DateTimeOffset.UtcNow.EndOfDay())
|
||||
// schedules.Add(referenceDate);
|
||||
|
||||
while (curTime < DateTimeOffset.UtcNow.EndOfDay())
|
||||
{
|
||||
switch (esppSchedule.TypeSchedule.Id)
|
||||
{
|
||||
case (int)EsppSchTypeScheduleEnum.Regularly:
|
||||
curTime = GetNextDateRegularly(esppSchedule.Values, curTime);
|
||||
break;
|
||||
case (int)EsppSchTypeScheduleEnum.Weekly:
|
||||
curTime = GetNextDateWeekly(esppSchedule.Values, curTime);
|
||||
break;
|
||||
case (int)EsppSchTypeScheduleEnum.Monthly:
|
||||
curTime = GetNextDateMonthly(esppSchedule.Values, curTime);
|
||||
break;
|
||||
case (int)EsppSchTypeScheduleEnum.Monthly2:
|
||||
curTime = GetNextDateMonthly2(esppSchedule.Values, curTime);
|
||||
break;
|
||||
case (int)EsppSchTypeScheduleEnum.Annually:
|
||||
curTime = GetNextDateAnnually(esppSchedule.Values, curTime);
|
||||
break;
|
||||
case (int)EsppSchTypeScheduleEnum.Annually2:
|
||||
curTime = GetNextDateAnnually2(esppSchedule.Values, curTime);
|
||||
break;
|
||||
}
|
||||
// while (curTime < DateTimeOffset.UtcNow.EndOfDay())
|
||||
// {
|
||||
// switch (esppSchedule.TypeSchedule.Id)
|
||||
// {
|
||||
// case (int)EsppSchTypeScheduleEnum.Regularly:
|
||||
// curTime = GetNextDateRegularly(esppSchedule.Values, curTime);
|
||||
// break;
|
||||
// case (int)EsppSchTypeScheduleEnum.Weekly:
|
||||
// curTime = GetNextDateWeekly(esppSchedule.Values, curTime);
|
||||
// break;
|
||||
// case (int)EsppSchTypeScheduleEnum.Monthly:
|
||||
// curTime = GetNextDateMonthly(esppSchedule.Values, curTime);
|
||||
// break;
|
||||
// case (int)EsppSchTypeScheduleEnum.Monthly2:
|
||||
// curTime = GetNextDateMonthly2(esppSchedule.Values, curTime);
|
||||
// break;
|
||||
// case (int)EsppSchTypeScheduleEnum.Annually:
|
||||
// curTime = GetNextDateAnnually(esppSchedule.Values, curTime);
|
||||
// break;
|
||||
// case (int)EsppSchTypeScheduleEnum.Annually2:
|
||||
// curTime = GetNextDateAnnually2(esppSchedule.Values, curTime);
|
||||
// break;
|
||||
// }
|
||||
|
||||
schedules.Add(curTime);
|
||||
}
|
||||
schedules.RemoveAll(s => s > DateTimeOffset.UtcNow.EndOfDay());
|
||||
// schedules.Add(curTime);
|
||||
// }
|
||||
// schedules.RemoveAll(s => s > DateTimeOffset.UtcNow.EndOfDay());
|
||||
|
||||
return schedules.OrderBy(t => t).ToList();
|
||||
}
|
||||
// return schedules.OrderBy(t => t).ToList();
|
||||
//}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public async Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset referenceDate)
|
||||
{
|
||||
//TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
|
||||
//В общем проверить, когда будем тестировать агента, что с датами все ок
|
||||
var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
||||
var nextSchedule = GetNextSchedule(esppSchedule, referenceDate);
|
||||
//public async Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset referenceDate)
|
||||
//{
|
||||
// //TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
|
||||
// //В общем проверить, когда будем тестировать агента, что с датами все ок
|
||||
// var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
||||
// var nextSchedule = GetNextSchedule(esppSchedule, referenceDate);
|
||||
|
||||
return nextSchedule;
|
||||
}
|
||||
// return nextSchedule;
|
||||
//}
|
||||
|
||||
|
||||
private async Task<EsppScheduleDto> GetEsppScheduleAsync(Guid jobGroupId)
|
||||
@@ -429,68 +429,68 @@ namespace PARR.DAL.TransformServices
|
||||
}
|
||||
|
||||
|
||||
public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||
{
|
||||
var nextRun = lastRun;
|
||||
//public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||
//{
|
||||
// var nextRun = lastRun;
|
||||
|
||||
switch (periodType)
|
||||
{
|
||||
case (DistributionPeriodTypeEnum.Day):
|
||||
nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
|
||||
break;
|
||||
case (DistributionPeriodTypeEnum.Month):
|
||||
nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
|
||||
break;
|
||||
case (DistributionPeriodTypeEnum.Year):
|
||||
nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
|
||||
break;
|
||||
}
|
||||
// switch (periodType)
|
||||
// {
|
||||
// case (DistributionPeriodTypeEnum.Day):
|
||||
// nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
|
||||
// break;
|
||||
// case (DistributionPeriodTypeEnum.Month):
|
||||
// nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
|
||||
// break;
|
||||
// case (DistributionPeriodTypeEnum.Year):
|
||||
// nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
|
||||
// break;
|
||||
// }
|
||||
|
||||
return nextRunModifierService.GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
|
||||
}
|
||||
// return nextRunModifierService.GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
|
||||
//}
|
||||
|
||||
|
||||
private DateTimeOffset GetPrevDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||
{
|
||||
switch (periodType)
|
||||
{
|
||||
case (DistributionPeriodTypeEnum.Day):
|
||||
return lastRun.AddDays(-ParseInt(distributionPeriod));
|
||||
//private DateTimeOffset GetPrevDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||
//{
|
||||
// switch (periodType)
|
||||
// {
|
||||
// case (DistributionPeriodTypeEnum.Day):
|
||||
// return lastRun.AddDays(-ParseInt(distributionPeriod));
|
||||
|
||||
case (DistributionPeriodTypeEnum.Month):
|
||||
return lastRun.AddMonths(-ParseInt(distributionPeriod));
|
||||
// case (DistributionPeriodTypeEnum.Month):
|
||||
// return lastRun.AddMonths(-ParseInt(distributionPeriod));
|
||||
|
||||
case (DistributionPeriodTypeEnum.Year):
|
||||
return lastRun.AddYears(-ParseInt(distributionPeriod));
|
||||
}
|
||||
// case (DistributionPeriodTypeEnum.Year):
|
||||
// return lastRun.AddYears(-ParseInt(distributionPeriod));
|
||||
// }
|
||||
|
||||
return lastRun;
|
||||
}
|
||||
// return lastRun;
|
||||
//}
|
||||
|
||||
|
||||
public async Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||
{
|
||||
var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
||||
//public async Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
|
||||
//{
|
||||
// var esppSchedule = await GetEsppScheduleAsync(jobGroupId);
|
||||
|
||||
var currentStartPeriod = referenceDate;
|
||||
var currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||
// var currentStartPeriod = referenceDate;
|
||||
// var currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||
|
||||
while (!(date >= currentStartPeriod && date < currentEndPeriod))
|
||||
{
|
||||
if (date > currentEndPeriod)
|
||||
{
|
||||
currentStartPeriod = currentEndPeriod;
|
||||
currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||
}
|
||||
else
|
||||
{
|
||||
currentEndPeriod = currentStartPeriod;
|
||||
currentStartPeriod = GetPrevDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||
}
|
||||
}
|
||||
// while (!(date >= currentStartPeriod && date < currentEndPeriod))
|
||||
// {
|
||||
// if (date > currentEndPeriod)
|
||||
// {
|
||||
// currentStartPeriod = currentEndPeriod;
|
||||
// currentEndPeriod = GetNextDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// currentEndPeriod = currentStartPeriod;
|
||||
// currentStartPeriod = GetPrevDateForDistributionRun(currentStartPeriod, periodType, distributionPeriod);
|
||||
// }
|
||||
// }
|
||||
|
||||
return DateOnly.FromDateTime(currentStartPeriod.DateTime);
|
||||
}
|
||||
// return DateOnly.FromDateTime(currentStartPeriod.DateTime);
|
||||
//}
|
||||
|
||||
|
||||
private int ParseInt(string value)
|
||||
@@ -507,12 +507,12 @@ namespace PARR.DAL.TransformServices
|
||||
}
|
||||
|
||||
|
||||
private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
|
||||
{
|
||||
var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
|
||||
//private DistributionPeriodTypeEnum ParseDistributionPeriodType(string value)
|
||||
//{
|
||||
// var result = (DistributionPeriodTypeEnum)Enum.Parse(typeof(DistributionPeriodTypeEnum), value);
|
||||
|
||||
return result;
|
||||
}
|
||||
// return result;
|
||||
//}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.DomainModels;
|
||||
|
||||
namespace PARR.DAL.TransformServices
|
||||
namespace PARR.DAL.TransformServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Сервис трансформации расписания ЕСПП в дату/расписание
|
||||
/// </summary>
|
||||
public interface IEsppScheduleTransformService
|
||||
{
|
||||
/// <summary>
|
||||
/// Получить следующую дату согласно расписания
|
||||
/// </summary>
|
||||
/// <param name="esppSchedule"></param>
|
||||
/// <param name="lastRun"></param>
|
||||
/// <returns></returns>
|
||||
DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
|
||||
///// <summary>
|
||||
///// Получить следующую дату согласно расписания
|
||||
///// </summary>
|
||||
///// <param name="esppSchedule"></param>
|
||||
///// <param name="lastRun"></param>
|
||||
///// <returns></returns>
|
||||
//DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
|
||||
|
||||
///// <summary>
|
||||
///// Получить расписание
|
||||
@@ -32,31 +29,31 @@ namespace PARR.DAL.TransformServices
|
||||
/// <returns></returns>
|
||||
Task<DateTimeOffset> GetNextDateAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
||||
|
||||
/// <summary>
|
||||
/// Получить расписание по jobGroupId
|
||||
/// </summary>
|
||||
/// <param name="jobGroupId"></param>
|
||||
/// <param name="lastRun"></param>
|
||||
/// <returns></returns>
|
||||
Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
||||
///// <summary>
|
||||
///// Получить расписание по jobGroupId
|
||||
///// </summary>
|
||||
///// <param name="jobGroupId"></param>
|
||||
///// <param name="lastRun"></param>
|
||||
///// <returns></returns>
|
||||
//Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid jobGroupId, DateTimeOffset lastRun);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить следующую дату срабатывания в указанном периоде
|
||||
/// </summary>
|
||||
/// <param name="lastRun"></param>
|
||||
/// <param name="periodType"></param>
|
||||
/// <param name="distributionPeriod"></param>
|
||||
/// <returns></returns>
|
||||
DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
||||
///// <summary>
|
||||
///// Получить следующую дату срабатывания в указанном периоде
|
||||
///// </summary>
|
||||
///// <param name="lastRun"></param>
|
||||
///// <param name="periodType"></param>
|
||||
///// <param name="distributionPeriod"></param>
|
||||
///// <returns></returns>
|
||||
//DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить дату начала периода распределения относительно опорной даты (Reference Date)
|
||||
/// </summary>
|
||||
/// <param name="jobGroupId"></param>
|
||||
/// <param name="date"></param>
|
||||
/// <returns></returns>
|
||||
Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset refrenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
||||
///// <summary>
|
||||
///// Получить дату начала периода распределения относительно опорной даты (Reference Date)
|
||||
///// </summary>
|
||||
///// <param name="jobGroupId"></param>
|
||||
///// <param name="date"></param>
|
||||
///// <returns></returns>
|
||||
//Task<DateOnly> GetStartPeriodForDateAsync(Guid jobGroupId, DateTimeOffset date, DateTimeOffset refrenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,11 +14,11 @@ namespace PARR.DAL.TransformServices
|
||||
/// <returns></returns>
|
||||
DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun);
|
||||
|
||||
/// <summary>
|
||||
/// Получить РАБОЧИЙ день следующего срабатывания
|
||||
/// </summary>
|
||||
/// <param name="nextRun"></param>
|
||||
/// <returns></returns>
|
||||
Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun);
|
||||
///// <summary>
|
||||
///// Получить РАБОЧИЙ день следующего срабатывания
|
||||
///// </summary>
|
||||
///// <param name="nextRun"></param>
|
||||
///// <returns></returns>
|
||||
//Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,40 +29,40 @@ namespace PARR.DAL.TransformServices
|
||||
}
|
||||
|
||||
|
||||
public async Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun)
|
||||
{
|
||||
// получаем день относительно часового пояса МСК
|
||||
var date = DateOnly.FromDateTime(DateResolver.IsCurrentDayRelativeMskTime(nextRun) ? nextRun.Date : nextRun.Date.AddDays(1));
|
||||
//public async Task<DateTimeOffset> GetWorkDayAsync(DateTimeOffset nextRun)
|
||||
//{
|
||||
// // получаем день относительно часового пояса МСК
|
||||
// var date = DateOnly.FromDateTime(DateResolver.IsCurrentDayRelativeMskTime(nextRun) ? nextRun.Date : nextRun.Date.AddDays(1));
|
||||
|
||||
if (await weekendDayService.IsWorkDayAsync(date, true))
|
||||
{
|
||||
//текущий nextRun рабочий день, возвращаем его
|
||||
return nextRun;
|
||||
}
|
||||
// if (await weekendDayService.IsWorkDayAsync(date, true))
|
||||
// {
|
||||
// //текущий nextRun рабочий день, возвращаем его
|
||||
// return nextRun;
|
||||
// }
|
||||
|
||||
// ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
|
||||
int count = 20;
|
||||
while (count > 0)
|
||||
{
|
||||
date = date.AddDays(1);
|
||||
var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
|
||||
if (isWorkDay)
|
||||
break; // это рабочий день, выбираем его
|
||||
// // ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
|
||||
// int count = 20;
|
||||
// while (count > 0)
|
||||
// {
|
||||
// date = date.AddDays(1);
|
||||
// var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
|
||||
// if (isWorkDay)
|
||||
// break; // это рабочий день, выбираем его
|
||||
|
||||
count--;
|
||||
// count--;
|
||||
|
||||
if (!isWorkDay && count == 0)
|
||||
logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
|
||||
}
|
||||
// if (!isWorkDay && count == 0)
|
||||
// logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
|
||||
// }
|
||||
|
||||
// смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
|
||||
if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
|
||||
date = date.AddDays(-1);
|
||||
// // смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
|
||||
// if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
|
||||
// date = date.AddDays(-1);
|
||||
|
||||
// считаем новый NextRun
|
||||
var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
|
||||
// // считаем новый NextRun
|
||||
// var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
|
||||
|
||||
return nextRun.AddDays(dayCount);
|
||||
}
|
||||
// return nextRun.AddDays(dayCount);
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,9 @@ using Microsoft.Extensions.Logging;
|
||||
using PARR.BLL.Services.Interfaces;
|
||||
using PARR.Common.Domain;
|
||||
using PARR.Constants;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.DAL.NextRunServices;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
using PARR.DAL.TransformServices;
|
||||
using PARR.NextRun.Settings;
|
||||
|
||||
namespace PARR.NextRun
|
||||
@@ -41,14 +40,15 @@ namespace PARR.NextRun
|
||||
using (var scope = serviceProvider.CreateScope())
|
||||
{
|
||||
//var appInWorkService = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
|
||||
var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
|
||||
//var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
|
||||
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
|
||||
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
|
||||
var nextRunService = scope.ServiceProvider.GetService<INextRunService>();
|
||||
|
||||
if (templateService == null || esppSchService == null || jobGroupService == null)
|
||||
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(IEsppScheduleTransformService)} или {nameof(IJobGroupService)}");
|
||||
if (templateService == null || nextRunService == null || jobGroupService == null)
|
||||
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}");
|
||||
|
||||
await HandlerAsync(templateService, esppSchService, jobGroupService);
|
||||
await HandlerAsync(templateService, nextRunService, jobGroupService);
|
||||
}
|
||||
}, workerSettings.RepeatEvery);
|
||||
}
|
||||
@@ -58,7 +58,7 @@ namespace PARR.NextRun
|
||||
/// Рассчет следующей даты срабатываения
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private async Task HandlerAsync(ITemplateService templateService, IEsppScheduleTransformService esppScheduleTransformService, IJobGroupService jobGroupService)
|
||||
private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService)
|
||||
{
|
||||
#region логика для групп у которых не включено автораспределение
|
||||
|
||||
@@ -77,7 +77,8 @@ namespace PARR.NextRun
|
||||
foreach (var group in groups)
|
||||
{
|
||||
//получаем по каждой группе следующий nextRun и сравниваем с существующим, если не равны, то обновляем
|
||||
var nextRun = await esppScheduleTransformService.GetNextDateAsync(group.Id, group.ReferenceDate);
|
||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(group.Id, group.ReferenceDate);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(group.Id, false);
|
||||
|
||||
|
||||
// Загружаем только шаблоны текущей группы где nextRun в БД не равен расчетному
|
||||
@@ -109,7 +110,7 @@ namespace PARR.NextRun
|
||||
|
||||
//todo: когда будет автораспределение, для него придумать логику как считать
|
||||
|
||||
|
||||
//TODO:!!! Написать логику для групп у которых включено автораспределение!!!
|
||||
|
||||
|
||||
#region old logic
|
||||
|
||||
Reference in New Issue
Block a user