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