feat(api, dal, nextRun): переделал вызов рассчета NextRun на INextRunService

This commit is contained in:
Mikhail Trubnikov
2026-01-22 11:46:05 +10:00
parent b34be5ccbe
commit 91082915bc
9 changed files with 280 additions and 277 deletions

View File

@@ -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);
} }
} }

View File

@@ -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)
{ {

View File

@@ -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>

View File

@@ -1,6 +1,4 @@
 using Microsoft.EntityFrameworkCore;
using InfluxDB.Client.Api.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using PARR.Constants; using PARR.Constants;
using PARR.DAL.DomainServices.Shortcodes; using PARR.DAL.DomainServices.Shortcodes;

View File

@@ -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;
} //}
} }
} }

View File

@@ -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);
} }
} }

View File

@@ -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);
} }
} }

View File

@@ -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);
} //}
} }
} }

View File

@@ -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