feat(api,bll,dal,esppScheduleSync,TemplateGenerator): изменен рассчет nextRun для задания роботу и синхронизатору, подставляется в зависимости от настроек ЗО и таймзоны УЗ робота ЕСПП. Переименование полей в БД

This commit is contained in:
Mikhail Trubnikov
2026-02-03 16:15:19 +10:00
parent c0210656d9
commit ead4653ad0
36 changed files with 13010 additions and 290 deletions

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PARR.DAL.Context;
using PARR.DAL.Contracts;
@@ -21,7 +22,7 @@ namespace PARR.DAL.Configurations.DbSettings
//если миграциями БД еще не создана, то SettingsInDbs будет недоступна
try
{
var settings = dataContext?.Setting.ToList();
var settings = dataContext?.Setting.AsNoTracking().ToList();
if (settings == null)
return;

View File

@@ -189,7 +189,7 @@ namespace PARR.DAL.Context
new { Name = nameof(SettingsFromDb.TemplatePrefixName), Description = "Префикс имени шаблона в ЕСПП", Value = "%PREFIX%-ЭИТИ-ПТК-ПАРР" },
new { Name = nameof(SettingsFromDb.RobotAttemptsNumber), Description = "Количество попыток выполнения задания роботом", Value = "3" },
new { Name = nameof(SettingsFromDb.RobotWaitTime), Description = "Время ожидания выполнения роботом задания", Value = "00:15:00" },
new { Name = nameof(SettingsFromDb.ScheduleTimezone), Description = "Расписание регламентной работы - В каком часовом поясе", Value = "MSK" },
//new { Name = nameof(SettingsFromDb.ScheduleTimezone), Description = "Расписание регламентной работы - В каком часовом поясе", Value = "MSK" },
//new { Name = nameof(SettingsFromDb.ScheduleExcludeType), Description = "Расписание регламентной работы - Тип исключения", Value = "Выполнить ТОЛЬКО В указанном календаре" },
//new { Name = nameof(SettingsFromDb.ScheduleExcludeCalendar), Description = "Расписание регламентной работы - Календарь", Value = "8x5 (8.00-17.00)" },
new { Name = nameof(SettingsFromDb.ScheduleRepeatRange), Description = "Расписание регламентной работы - Диапазн повторов", Value = "Отсутствует дата завершения" },
@@ -202,12 +202,12 @@ namespace PARR.DAL.Context
Description = "Список неизменных частей имени шаблона",
Value =
new List<TemplateNameConstantPart> {
new TemplateNameConstantPart { Name = "П-1", Value = "ЭИТИ" },
new TemplateNameConstantPart { Name = "П-2", Value = "ПАРР" }
new TemplateNameConstantPart { Name = "П-1", Value = "ЭИТИ-ПАРР" }
}.ToJson()
},
new { Name = nameof(SettingsFromDb.EsppUnitTag), Description = "Префикс тега в поле ЭК \"Дополнительная информация\"", Value = АРР_" },
new { Name = nameof(SettingsFromDb.JobIdForUnusedTemplates), Description = "Job в который перемещаем ниспользованные шаблоны", Value = "8f85a91c-a223-4686-bb69-1f0ee73624f2" }
new { Name = nameof(SettingsFromDb.JobIdForUnusedTemplates), Description = "Job в который перемещаем ниспользованные шаблоны", Value = "8f85a91c-a223-4686-bb69-1f0ee73624f2" },
new { Name = nameof(SettingsFromDb.DefaultResponseAreaToTimeOffset), Description = "Зона ответственности для получения тайм зоны по умолчанию для расписаний", Value = "17-МСК" }
);
});
#endregion

View File

@@ -77,10 +77,10 @@ namespace PARR.DAL.Contracts
/// </summary>
public TimeSpan RobotWaitTime { get; set; }
/// <summary>
/// Расписание регламентной работы - В каком часовом поясе
/// </summary>
public string ScheduleTimezone { get; set; } = string.Empty;
///// <summary>
///// Расписание регламентной работы - В каком часовом поясе
///// </summary>
//public string ScheduleTimezone { get; set; } = string.Empty;
///// <summary>
///// Расписание регламентной работы - Тип исключения
@@ -93,7 +93,7 @@ namespace PARR.DAL.Contracts
//public string ScheduleExcludeCalendar { get; set; } = string.Empty;
/// <summary>
/// Расписание регламентной работы - Диапазн повторов
/// Расписание регламентной работы - Диапазон повторов
/// </summary>
public string ScheduleRepeatRange { get; set; } = string.Empty;
@@ -122,6 +122,11 @@ namespace PARR.DAL.Contracts
/// </summary>
public Guid JobIdForUnusedTemplates { get; set; }
/// <summary>
/// Зона ответственности для получения тайм зоны по умолчанию для расписаний
/// </summary>
public string DefaultResponseAreaToTimeOffset { get; set; } = string.Empty;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PARR.DAL.Migrations
{
/// <inheritdoc />
public partial class tblScheduleResponseAreaTimeOffsetAddUtcTimeOffset : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<TimeSpan>(
name: "UtcTimeOffset",
schema: "schedule",
table: "ResponseAreaTimeOffsets",
type: "interval",
nullable: false,
defaultValue: new TimeSpan(0, 0, 0, 0, 0));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UtcTimeOffset",
schema: "schedule",
table: "ResponseAreaTimeOffsets");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,52 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PARR.DAL.Migrations
{
/// <inheritdoc />
public partial class tblRenameFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "TimeOffset",
schema: "schedule",
table: "ResponseAreaTimeOffsets",
newName: "EsppValue");
migrationBuilder.RenameColumn(
name: "IsWorkGroupTimezone",
schema: "job",
table: "Groups",
newName: "IsResponseAreaTimezone");
migrationBuilder.InsertData(
table: "Settings",
columns: new[] { "Name", "Description", "Value" },
values: new object[] { "DefaultResponseAreaToTimeOffset", "Зона ответственности для получения тайм зоны по умолчанию для расписаний", "17-МСК" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Settings",
keyColumn: "Name",
keyValue: "DefaultResponseAreaToTimeOffset");
migrationBuilder.RenameColumn(
name: "EsppValue",
schema: "schedule",
table: "ResponseAreaTimeOffsets",
newName: "TimeOffset");
migrationBuilder.RenameColumn(
name: "IsResponseAreaTimezone",
schema: "job",
table: "Groups",
newName: "IsWorkGroupTimezone");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,42 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PARR.DAL.Migrations
{
/// <inheritdoc />
public partial class tbsSettingsRemoveScheduleTimezone : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Settings",
keyColumn: "Name",
keyValue: "ScheduleTimezone");
migrationBuilder.UpdateData(
table: "Settings",
keyColumn: "Name",
keyValue: "TemplateNameConstantParts",
column: "Value",
value: "[{\"Name\":\"П-1\",\"Value\":\"ЭИТИ-ПАРР\"}]");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "Settings",
keyColumn: "Name",
keyValue: "TemplateNameConstantParts",
column: "Value",
value: "[{\"Name\":\"П-1\",\"Value\":\"ЭИТИ\"},{\"Name\":\"П-2\",\"Value\":\"ПАРР\"}]");
migrationBuilder.InsertData(
table: "Settings",
columns: new[] { "Name", "Description", "Value" },
values: new object[] { "ScheduleTimezone", "Расписание регламентной работы - В каком часовом поясе", "MSK" });
}
}
}

View File

@@ -1678,7 +1678,7 @@ namespace PARR.DAL.Migrations
b.Property<bool>("IsAutoDistributionEnabled")
.HasColumnType("boolean");
b.Property<bool>("IsWorkGroupTimezone")
b.Property<bool>("IsResponseAreaTimezone")
.HasColumnType("boolean");
b.Property<DateTimeOffset>("ReferenceDate")
@@ -2581,10 +2581,13 @@ namespace PARR.DAL.Migrations
b.Property<string>("ResponseArea")
.HasColumnType("text");
b.Property<string>("TimeOffset")
b.Property<string>("EsppValue")
.IsRequired()
.HasColumnType("text");
b.Property<TimeSpan>("UtcTimeOffset")
.HasColumnType("interval");
b.HasKey("ResponseArea");
b.ToTable("ResponseAreaTimeOffsets", "schedule", t =>
@@ -2648,12 +2651,6 @@ namespace PARR.DAL.Migrations
Value = "00:15:00"
},
new
{
Name = "ScheduleTimezone",
Description = "Расписание регламентной работы - В каком часовом поясе",
Value = "MSK"
},
new
{
Name = "ScheduleRepeatRange",
Description = "Расписание регламентной работы - Диапазн повторов",
@@ -2681,7 +2678,7 @@ namespace PARR.DAL.Migrations
{
Name = "TemplateNameConstantParts",
Description = "Список неизменных частей имени шаблона",
Value = "[{\"Name\":\"П-1\",\"Value\":\"ЭИТИ\"},{\"Name\":\"П-2\",\"Value\":\"ПАРР\"}]"
Value = "[{\"Name\":\"П-1\",\"Value\":\"ЭИТИ-ПАРР\"}]"
},
new
{
@@ -2694,6 +2691,12 @@ namespace PARR.DAL.Migrations
Name = "JobIdForUnusedTemplates",
Description = "Job в который перемещаем ниспользованные шаблоны",
Value = "8f85a91c-a223-4686-bb69-1f0ee73624f2"
},
new
{
Name = "DefaultResponseAreaToTimeOffset",
Description = "Зона ответственности для получения тайм зоны по умолчанию для расписаний",
Value = "17-МСК"
});
});

View File

@@ -95,7 +95,7 @@ namespace PARR.DAL.Models.Job
/// <summary>
/// Использовать таймзону рабочей группы ответственного за ЭК шаблона
/// </summary>
public bool IsWorkGroupTimezone { get; set; } = false;
public bool IsResponseAreaTimezone { get; set; } = false;
/// <summary>

View File

@@ -15,6 +15,14 @@ namespace PARR.DAL.Models.Schedule
[Key]
public required string ResponseArea { get; set; }
public required string TimeOffset { get; set; }
/// <summary>
/// ЕСПП значение
/// </summary>
public required string EsppValue { get; set; }
/// <summary>
/// Смещение относительно UTC
/// </summary>
public required TimeSpan UtcTimeOffset { get; set; }
}
}

View File

@@ -62,5 +62,21 @@ namespace PARR.DAL.NextRunServices
/// <returns></returns>
Task<HashSet<DateOnly>> GetWeekendsAsync(DateOnly startDate, DateOnly endDate, DateTimeOffset referenceDate);
/// <summary>
/// Получить NextRun со смещением УЗ ЕСПП и если надо, выполнить смещение для ЗО
/// </summary>
/// <param name="nextRun"></param>
/// <param name="isResponseAreaTimezone">Применить таймзону ЗО</param>
/// <param name="responseArea">ЗО</param>
/// <returns></returns>
DateTimeOffset GetNextRunWithTimezoneEsppAndResponseArea(DateTimeOffset nextRun, bool? isResponseAreaTimezone = null, string? responseArea = null);
/// <summary>
/// Получить NextRun согласно таймзоны ЗО
/// </summary>
/// <param name="nextRun"></param>
/// <param name="responseArea"></param>
/// <returns></returns>
DateTimeOffset GetNextRunWithResponseAreaOffset(DateTimeOffset nextRun, string responseArea);
}
}

View File

@@ -1,13 +1,17 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.BLL.Helpers;
using PARR.Constants;
using PARR.DAL.Contracts;
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.Implementations.Schedule;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Schedule;
namespace PARR.DAL.NextRunServices
{
@@ -19,6 +23,8 @@ namespace PARR.DAL.NextRunServices
private readonly IEsppScheduleTransformService esppScheduleTransformService;
private readonly ITemplateDistributor templateDistributor;
private readonly IShortcodesService shortcodesService;
private readonly SettingsFromDb settingsFromDb;
private readonly IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService;
public NextRunService(
ILogger<NextRunService> logger,
@@ -26,7 +32,9 @@ namespace PARR.DAL.NextRunServices
IJobGroupService jobGroupService,
IEsppScheduleTransformService esppScheduleTransformService,
ITemplateDistributor templateDistributor,
IShortcodesService shortcodesService
IShortcodesService shortcodesService,
SettingsFromDb settingsFromDb,
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
)
{
this.logger = logger;
@@ -35,6 +43,8 @@ namespace PARR.DAL.NextRunServices
this.esppScheduleTransformService = esppScheduleTransformService;
this.templateDistributor = templateDistributor;
this.shortcodesService = shortcodesService;
this.settingsFromDb = settingsFromDb;
this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
}
@@ -317,5 +327,58 @@ namespace PARR.DAL.NextRunServices
{
return await templateDistributor.GetWeekendsV2Async(startDate, endDate, referenceDate);
}
public DateTimeOffset GetNextRunWithTimezoneEsppAndResponseArea(DateTimeOffset nextRun, bool? isResponseAreaTimezone = null, string? responseArea = null)
{
logger.LogDebug("Начинаю получать nextRun с учетом УЗ ЕСПП и ЗО, входные параметры: nextRun: {nextRun}, isResponseAreaTimezone: {isResponseAreaTimezone}, responseArea: {responseArea}", nextRun, isResponseAreaTimezone, responseArea);
var esppOffset = GetEsppAccountOffset();
// смещение УЗ ЕСПП
var resultNextRun = nextRun.Add(esppOffset);
logger.LogDebug("Смещение nextRun с учетом смещения УЗ ЕСПП, новое значение: {resultNextRun}", resultNextRun);
// если включено использовать таймзону ЗО
if (isResponseAreaTimezone == true && !string.IsNullOrEmpty(responseArea))
{
// resultNextRun = офсет УЗ ЕСПП - offset ЗО
var responseAreaOffset = scheduleResponseAreaTimeOffsetService.GetByResponseAreaOrDefault(responseArea).UtcTimeOffset;
var resultOffset = esppOffset - responseAreaOffset;
resultNextRun = resultNextRun.Add(resultOffset);
logger.LogDebug("Смещение nextRun с учетом ЗО, смещение ЗО: {responseAreaOffset}, смещение с учетом смещения УЗ ЕСПП: {resultOffset}, новое значение: {resultNextRun}", responseAreaOffset, resultOffset, resultNextRun);
}
//var resulstStr = EsppScheduleHelpers.GetNextRun(resultNextRun);
//logger.LogDebug("Результат в формате ЕСПП: {resulstStr}", resulstStr);
return resultNextRun;
}
public DateTimeOffset GetNextRunWithResponseAreaOffset(DateTimeOffset nextRun, string responseArea)
{
var responseAreaOffset = scheduleResponseAreaTimeOffsetService.GetByResponseAreaOrDefault(responseArea).UtcTimeOffset;
var resulstNextRun = nextRun.Add(responseAreaOffset);
logger.LogDebug("Смещение nextRun для ЗО {responseArea}, входящий: {nextRun}, смещение: {offset}, результат: {result}", responseArea, nextRun, responseAreaOffset, resulstNextRun);
return resulstNextRun;
}
/// <summary>
/// Получить смещение УЗ ЕСПП
/// </summary>
/// <returns></returns>
private TimeSpan GetEsppAccountOffset()
{
var esppOffset = new TimeSpan(settingsFromDb.EsppRobotAccountTimeZoneHour, 0, 0);
logger.LogDebug("Оффсет УЗ ЕСПП: {esppOffset}", esppOffset);
return esppOffset;
}
}
}

View File

@@ -107,7 +107,6 @@ namespace PARR.DAL
services.AddTransient<IScheduleExcludeTypeService, ScheduleExcludeTypeService>();
services.AddTransient<IScheduleExcludeTypeCalendarService, ScheduleExcludeTypeCalendarService>();
services.AddTransient<IScheduleResponseAreaTimeOffsetService, ScheduleResponseAreaTimeOffsetService>();
#endregion
@@ -135,12 +134,11 @@ namespace PARR.DAL
#endregion
// TransformServices
services.AddTransient<IEsppScheduleTransformService, EsppScheduleTransformService>();
services.AddTransient<INextRunModifierService, NextRunModifierService>();
//services.AddTransient<INextRunModifierService, NextRunModifierService>();
#region NextRun Services
services.AddTransient<IEsppScheduleTransformService, EsppScheduleTransformService>();
services.AddTransient<INextRunService, NextRunService>();
services.AddTransient<ITemplateDistributor, TemplateDistributor>();
@@ -182,6 +180,16 @@ namespace PARR.DAL
services.AddSingleton(settingsFromDb);
PrefixSettings.PrefixWithoutVariable = settingsFromDb.TemplatePrefixWithoutVariable;
// Сервис - Расписание в ЕСПП. Смещение часового пояса относительно МСК для зоны ответственности рабочей группы
services.AddSingleton<IScheduleResponseAreaTimeOffsetService>(provider =>
{
using var scope = provider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<DataContext>();
var settingsFromDb = scope.ServiceProvider.GetRequiredService<SettingsFromDb>();
return new ScheduleResponseAreaTimeOffsetService(dbContext, settingsFromDb);
});
}
}

View File

@@ -1,29 +1,64 @@
using Microsoft.EntityFrameworkCore;
using PARR.DAL.Context;
using PARR.DAL.Contracts;
using PARR.DAL.Models.Schedule;
using PARR.DAL.Services.Interfaces.Schedule;
namespace PARR.DAL.Services.Implementations.Schedule
{
internal class ScheduleResponseAreaTimeOffsetService : IScheduleResponseAreaTimeOffsetService
internal sealed class ScheduleResponseAreaTimeOffsetService : IScheduleResponseAreaTimeOffsetService
{
private readonly DataContext dataContext;
private readonly IReadOnlyDictionary<string, ScheduleResponseAreaTimeOffset> offsetList;
/// <summary>
/// ЗО по умолчанию
/// </summary>
private readonly string defaultResponseArea;
/// <summary>
/// Настройки, если не нашли в offsetList
/// </summary>
private readonly ScheduleResponseAreaTimeOffset defaultOffset;
public ScheduleResponseAreaTimeOffsetService(DataContext dataContext)
public ScheduleResponseAreaTimeOffsetService(DataContext dataContext, SettingsFromDb settingsFromDb)
{
this.dataContext = dataContext;
offsetList = dataContext.ScheduleResponseAreaTimeOffsets
.AsNoTracking()
.ToDictionary(t => t.ResponseArea, t => t, StringComparer.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(settingsFromDb.DefaultResponseAreaToTimeOffset))
defaultResponseArea = "17-МСК";
else
defaultResponseArea = settingsFromDb.DefaultResponseAreaToTimeOffset;
defaultOffset = new ScheduleResponseAreaTimeOffset
{
ResponseArea = "17-МСК",
EsppValue = "",
UtcTimeOffset = new TimeSpan(3, 0, 0)
};
}
public IQueryable<ScheduleResponseAreaTimeOffset> Get()
public IReadOnlyDictionary<string, ScheduleResponseAreaTimeOffset> GetAll => offsetList;
public ScheduleResponseAreaTimeOffset GetDefault => GetByResponseAreaOrDefault(defaultResponseArea);
public ScheduleResponseAreaTimeOffset GetByResponseAreaOrDefault(string responseArea)
{
return dataContext.ScheduleResponseAreaTimeOffsets;
return offsetList.TryGetValue(responseArea, out var value) ? value : defaultOffset;
}
public async Task<string?> GetTimeOffsetByResponseAreaAsync(string responseArea)
{
var result = await dataContext.ScheduleResponseAreaTimeOffsets.FirstOrDefaultAsync(t => t.ResponseArea == responseArea);
return result != null ? result.TimeOffset : null;
}
//public IQueryable<ScheduleResponseAreaTimeOffset> Get()
//{
// return dataContext.ScheduleResponseAreaTimeOffsets;
//}
//public async Task<string?> GetTimeOffsetByResponseAreaAsync(string responseArea)
//{
// var result = await dataContext.ScheduleResponseAreaTimeOffsets.FirstOrDefaultAsync(t => t.ResponseArea == responseArea);
// return result != null ? result.TimeOffset : null;
//}
}
}

View File

@@ -4,8 +4,21 @@ namespace PARR.DAL.Services.Interfaces.Schedule
{
public interface IScheduleResponseAreaTimeOffsetService
{
IQueryable<ScheduleResponseAreaTimeOffset> Get();
/// <summary>
/// Список всех значений
/// </summary>
IReadOnlyDictionary<string, ScheduleResponseAreaTimeOffset> GetAll { get; }
Task<string?> GetTimeOffsetByResponseAreaAsync(string responseArea);
/// <summary>
/// Значение по умолчанию
/// </summary>
ScheduleResponseAreaTimeOffset GetDefault { get; }
/// <summary>
/// Получить значение по ЗО, если не найдет, то значение по умолчанию
/// </summary>
/// <param name="responseArea"></param>
/// <returns></returns>
ScheduleResponseAreaTimeOffset GetByResponseAreaOrDefault(string responseArea);
}
}

View File

@@ -2,23 +2,23 @@
namespace PARR.DAL.TransformServices
{
/// <summary>
/// Сервис по изменению NextRun
/// </summary>
public interface INextRunModifierService
{
/// <summary>
/// Получить NextRun с учетом тайм зоны робота ЕСПП
/// </summary>
/// <param name="nextRun"></param>
/// <returns></returns>
DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun);
///// <summary>
///// Сервис по изменению NextRun
///// </summary>
//public interface INextRunModifierService
//{
// /// <summary>
// /// Получить NextRun с учетом тайм зоны УЗ робота ЕСПП
// /// </summary>
// /// <param name="nextRun"></param>
// /// <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);
//}
}

View File

@@ -1,68 +1,32 @@
using Microsoft.Extensions.Logging;
using PARR.Common;
using PARR.DAL.Contracts;
using PARR.DAL.Services.Interfaces;
namespace PARR.DAL.TransformServices
{
internal class NextRunModifierService : INextRunModifierService
{
private readonly SettingsFromDb settingsFromDb;
private readonly ILogger<NextRunModifierService> logger;
private readonly IWeekendDayService weekendDayService;
//internal class NextRunModifierService : INextRunModifierService
//{
// private readonly SettingsFromDb settingsFromDb;
// private readonly ILogger<NextRunModifierService> logger;
// private readonly IWeekendDayService weekendDayService;
public NextRunModifierService(
SettingsFromDb settingsFromDb,
ILogger<NextRunModifierService> logger,
IWeekendDayService weekendDayService
)
{
this.settingsFromDb = settingsFromDb;
this.logger = logger;
this.weekendDayService = weekendDayService;
}
// public NextRunModifierService(
// SettingsFromDb settingsFromDb,
// ILogger<NextRunModifierService> logger,
// IWeekendDayService weekendDayService
// )
// {
// this.settingsFromDb = settingsFromDb;
// this.logger = logger;
// this.weekendDayService = weekendDayService;
// }
public DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun)
{
return nextRun.AddHours(settingsFromDb.EsppRobotAccountTimeZoneHour);
}
// public DateTimeOffset GetNextRunByAccountRobotTimeZone(DateTimeOffset nextRun)
// {
// return nextRun.AddHours(settingsFromDb.EsppRobotAccountTimeZoneHour);
// }
//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;
// }
// // ищем следующий рабочий день, максимум 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);
//}
}
//}
}