feat(bll,dal,common): в common - DateResolver - проверка даты на текущие сутки относительно часового пояса МСК. Dal - EsppScheduleTransformService - рассчет NextRun с учетом выходных дней

This commit is contained in:
Mikhail Trubnikov
2024-09-18 16:32:45 +10:00
parent 9987626478
commit 60c0ba9ec8
24 changed files with 181 additions and 29 deletions

View File

@@ -20,6 +20,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PARR.Common\PARR.Common.csproj" />
<ProjectReference Include="..\PARR.Constants\PARR.Constants.csproj" />
</ItemGroup>

View File

@@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Common;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainModels;
@@ -12,6 +13,7 @@ namespace PARR.DAL.TransformServices
{
private readonly IEsppSchTypeConfigService esppSchTypeConfigService;
private readonly IApplicationsInWorkService applicationsInWorkService;
private readonly IWeekendDayService weekendDayService;
private readonly ILogger<EsppScheduleTransformService> logger;
private readonly Dictionary<string, int> monthDict = new Dictionary<string, int>()
@@ -50,45 +52,65 @@ namespace PARR.DAL.TransformServices
{"Воскресенье", 0 }
};
public EsppScheduleTransformService(
ILogger<EsppScheduleTransformService> logger,
IEsppSchTypeConfigService esppSchTypeConfigService,
IApplicationsInWorkService applicationsInWorkService
IApplicationsInWorkService applicationsInWorkService,
IWeekendDayService weekendDayService
)
{
this.esppSchTypeConfigService = esppSchTypeConfigService;
this.applicationsInWorkService = applicationsInWorkService;
this.weekendDayService = weekendDayService;
this.logger = logger;
}
public DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun)
{
var nextRun = lastRun;
//если больше текущего вернуть lastRun. Это и есть следующая дата
if (lastRun > DateTimeOffset.UtcNow)
return lastRun;
nextRun = lastRun;
//return lastRun;
switch (esppSchedule.TypeSchedule.Id)
{
case (int)EsppSchTypeScheduleEnum.Regularly:
return GetNextDateRegularly(esppSchedule.Values, lastRun);
//return GetNextDateRegularly(esppSchedule.Values, lastRun);
nextRun = GetNextDateRegularly(esppSchedule.Values, lastRun);
break;
case (int)EsppSchTypeScheduleEnum.Weekly:
return GetNextDateWeekly(esppSchedule.Values, lastRun);
//return GetNextDateWeekly(esppSchedule.Values, lastRun);
nextRun = GetNextDateWeekly(esppSchedule.Values, lastRun);
break;
case (int)EsppSchTypeScheduleEnum.Monthly:
return GetNextDateMonthly(esppSchedule.Values, lastRun);
//return GetNextDateMonthly(esppSchedule.Values, lastRun);
nextRun = GetNextDateMonthly(esppSchedule.Values, lastRun);
break;
case (int)EsppSchTypeScheduleEnum.Monthly2:
return GetNextDateMonthly2(esppSchedule.Values, lastRun);
//return GetNextDateMonthly2(esppSchedule.Values, lastRun);
nextRun = GetNextDateMonthly2(esppSchedule.Values, lastRun);
break;
case (int)EsppSchTypeScheduleEnum.Annually:
return GetNextDateAnnually(esppSchedule.Values, lastRun);
//return GetNextDateAnnually(esppSchedule.Values, lastRun);
nextRun = GetNextDateAnnually(esppSchedule.Values, lastRun);
break;
case (int)EsppSchTypeScheduleEnum.Annually2:
return GetNextDateAnnually2(esppSchedule.Values, lastRun);
//return GetNextDateAnnually2(esppSchedule.Values, lastRun);
nextRun = GetNextDateAnnually2(esppSchedule.Values, lastRun);
break;
}
return lastRun;//todo убрать lastrun должен возвращать реальный результат
nextRun = GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
return nextRun;
}
public List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset lastRun)
private List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset lastRun)
{
// расписание на оставшееся на сегодня время. его так мало...
lastRun = lastRun.UtcDateTime;
@@ -136,7 +158,7 @@ namespace PARR.DAL.TransformServices
{
//если больше текущего вернуть lastRun. Это и есть следующая дата
if (lastRun > DateTimeOffset.UtcNow)
return lastRun;
return await GetWorkDayAsync(lastRun);
var appInWork = await applicationsInWorkService.Get()
.Include(aiw => aiw.EsppSchValues)
@@ -160,6 +182,8 @@ namespace PARR.DAL.TransformServices
public async Task<List<DateTimeOffset>> GetNextScheduleAsync(Guid applicationInWorkId, DateTimeOffset lastRun)
{
//TODO: тут не проверен переход через выходные дни!!! Переход не используется, так как тут не рассчитываем NextRun.
//В общем проверить, когда будем тестировать агента, что с датами все ок
var esppSchedule = await GetEsppScheduleAsync(applicationInWorkId);
var nextSchedule = GetNextSchedule(esppSchedule, lastRun);
@@ -179,6 +203,7 @@ namespace PARR.DAL.TransformServices
return esppSchedule;
}
private DateTimeOffset GetNextDateRegularly(List<EsppScheduleValDto> values, DateTimeOffset lastRun)
{
var regDict = new Dictionary<string, int>
@@ -359,19 +384,25 @@ namespace PARR.DAL.TransformServices
public DateTimeOffset GetNextDateForDistributionRun(DateTimeOffset lastRun, DistributionPeriodTypeEnum periodType, string distributionPeriod)
{
var nextRun = lastRun;
switch (periodType)
{
case (DistributionPeriodTypeEnum.Day):
return lastRun.AddDays(ParseInt(distributionPeriod));
//return lastRun.AddDays(ParseInt(distributionPeriod));
nextRun = lastRun.AddDays(ParseInt(distributionPeriod));
break;
case (DistributionPeriodTypeEnum.Month):
return lastRun.AddMonths(ParseInt(distributionPeriod));
//return lastRun.AddMonths(ParseInt(distributionPeriod));
nextRun = lastRun.AddMonths(ParseInt(distributionPeriod));
break;
case (DistributionPeriodTypeEnum.Year):
return lastRun.AddYears(ParseInt(distributionPeriod));
//return lastRun.AddYears(ParseInt(distributionPeriod));
nextRun = lastRun.AddYears(ParseInt(distributionPeriod));
break;
}
return lastRun;
return GetWorkDayAsync(nextRun).GetAwaiter().GetResult();
}
@@ -395,7 +426,6 @@ namespace PARR.DAL.TransformServices
public async Task<DateOnly> GetStartPeriodForDateAsync(Guid applicationInWorkId, DateTimeOffset date, DateTimeOffset referenceDate, DistributionPeriodTypeEnum periodType, string distributionPeriod)
{
var esppSchedule = await GetEsppScheduleAsync(applicationInWorkId);
var currentStartPeriod = referenceDate;
@@ -439,5 +469,47 @@ namespace PARR.DAL.TransformServices
return result;
}
/// <summary>
/// Получить рабочий день следующего срабатывания
/// </summary>
/// <param name="nextRun"></param>
/// <returns></returns>
private 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;
}
// ищем следующий рабочий день, максимум 20 итераций, если за их кол-во не нашли рабочий, берём последний не рабочий
int count = 20;
while (count > 0)
{
date = date.AddDays(1);
var isWorkDay = await weekendDayService.IsWorkDayAsync(date, true);
if (isWorkDay)
break; // это рабочий день, выбираем его
count--;
if (!isWorkDay && count == 0)
logger.LogWarning($"Не нашли рабочий день за 20 итераций, взяли последний нерабочий {date}");
}
// смотрим, если смещали из-за пояса МСК на день вперед, вычитаем этот день назад
if (!DateResolver.IsCurrentDayRelativeMskTime(nextRun))
date = date.AddDays(-1);
// считаем новый NextRun
var dayCount = date.DayNumber - DateOnly.FromDateTime(nextRun.Date).DayNumber;
return nextRun.AddDays(dayCount);
}
}
}

View File

@@ -16,13 +16,13 @@ namespace PARR.DAL.TransformServices
/// <returns></returns>
DateTimeOffset GetNextDate(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
/// <summary>
/// Получить расписание
/// </summary>
/// <param name="esppSchedule"></param>
/// <param name="lastRun"></param>
/// <returns></returns>
List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
///// <summary>
///// Получить расписание
///// </summary>
///// <param name="esppSchedule"></param>
///// <param name="lastRun"></param>
///// <returns></returns>
//List<DateTimeOffset> GetNextSchedule(EsppScheduleDto esppSchedule, DateTimeOffset lastRun);
/// <summary>
/// Получить следующую дату по applicationInWorkId