feat(bll, dal, templateGenertartor, templateMatcher, templateUpdater): интеграция с INextRunServiceV2
This commit is contained in:
@@ -24,9 +24,14 @@ namespace PARR.BLL.Domain.Mq
|
||||
/// </summary>
|
||||
public bool IsActiveSchedule { get; set; }
|
||||
|
||||
public DateTimeOffset? LastRun { get; set; }
|
||||
//public DateTimeOffset? LastRun { get; set; }
|
||||
|
||||
public DateTimeOffset NextRun { get; set; }
|
||||
//public DateTimeOffset NextRun { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Это новый шаблон? (true - перемещаем существующий в новый Job) (false - шаблон остается в своем Job)
|
||||
/// </summary>
|
||||
public bool IsNew { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Id Юнита(единицы обслуживания)/ЭК
|
||||
|
||||
4154
PARR.DAL/Migrations/20260226023559_tblSettingsUpd26022026.Designer.cs
generated
Normal file
4154
PARR.DAL/Migrations/20260226023559_tblSettingsUpd26022026.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
PARR.DAL/Migrations/20260226023559_tblSettingsUpd26022026.cs
Normal file
28
PARR.DAL/Migrations/20260226023559_tblSettingsUpd26022026.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PARR.DAL.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class tblSettingsUpd26022026 : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.InsertData(
|
||||
table: "Settings",
|
||||
columns: new[] { "Name", "Description", "Value" },
|
||||
values: new object[] { "EsppScheduleTimezone", "Расписание регламентной работы - В каком часовом поясе", "MSK" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Settings",
|
||||
keyColumn: "Name",
|
||||
keyValue: "EsppScheduleTimezone");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2655,6 +2655,12 @@ namespace PARR.DAL.Migrations
|
||||
Value = "00:15:00"
|
||||
},
|
||||
new
|
||||
{
|
||||
Name = "EsppScheduleTimezone",
|
||||
Description = "Расписание регламентной работы - В каком часовом поясе",
|
||||
Value = "MSK"
|
||||
},
|
||||
new
|
||||
{
|
||||
Name = "ScheduleRepeatRange",
|
||||
Description = "Расписание регламентной работы - Диапазн повторов",
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
using PARR.DAL.Models.Job;
|
||||
using PARR.DAL.NextRunServices.Models;
|
||||
|
||||
namespace PARR.DAL.NextRunServices
|
||||
{
|
||||
public interface INextRunService
|
||||
{
|
||||
/// <summary>
|
||||
/// Получить продолжительность распределения в днях
|
||||
/// </summary>
|
||||
/// <param name="config"></param>
|
||||
/// <returns></returns>
|
||||
int GetDurationDays(JobGroupDistributionConfig config);
|
||||
|
||||
/// <summary>
|
||||
/// Получить список TemplateId, NextRun по jobGroupId с автораспределением (распределить шаблоны в группе работ)
|
||||
/// </summary>
|
||||
/// <param name="jobGroupId"></param>
|
||||
/// <returns></returns>
|
||||
Task<List<TemplateNextRunResultDto>?> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId);
|
||||
|
||||
|
||||
///// <summary>
|
||||
///// Получить NextRun по jobGroupId с расписанием ЕСПП
|
||||
///// </summary>
|
||||
///// <param name="jobGroupId"></param>
|
||||
///// <returns></returns>
|
||||
//Task<DateTimeOffset> GetNextRunForJobGroupWithEsppSchedulleAsync(Guid jobGroupId);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить nextRun для создаваемого шаблона, которого еще нет в БД
|
||||
/// </summary>
|
||||
/// <param name="jobGroupId"></param>
|
||||
/// <param name="responseArea">НЕ МАСКА, а прям ЗО</param>
|
||||
/// <returns></returns>
|
||||
Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId, string responseArea);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить NextRun по id существующего шаблона
|
||||
/// </summary>
|
||||
/// <param name="templateId"></param>
|
||||
/// <param name="isNew">Шаблон переведенный из unused</param>
|
||||
/// <returns></returns>
|
||||
Task<DateTimeOffset> GetNextRunForTemplateAsync(Guid templateId, bool isNew);
|
||||
|
||||
/// <summary>
|
||||
/// Получить список рабочих дней
|
||||
/// </summary>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="excludeWeekends"></param>
|
||||
/// <returns></returns>
|
||||
Task<List<DateOnly>> GetWorkDaysAsync(DateOnly start, DateOnly end, bool excludeWeekends, DateTimeOffset referenceDate);
|
||||
|
||||
/// <summary>
|
||||
/// Получить список выходных дней
|
||||
/// </summary>
|
||||
/// <param name="startDate"></param>
|
||||
/// <param name="endDate"></param>
|
||||
/// <param name="referenceDate"></param>
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
@@ -1,469 +0,0 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
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.Interfaces;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
using PARR.DAL.Services.Interfaces.Schedule;
|
||||
|
||||
namespace PARR.DAL.NextRunServices
|
||||
{
|
||||
internal class NextRunService : INextRunService
|
||||
{
|
||||
private readonly ILogger<NextRunService> logger;
|
||||
private readonly ITemplateService templateService;
|
||||
private readonly IJobGroupService jobGroupService;
|
||||
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,
|
||||
ITemplateService templateService,
|
||||
IJobGroupService jobGroupService,
|
||||
IEsppScheduleTransformService esppScheduleTransformService,
|
||||
ITemplateDistributor templateDistributor,
|
||||
IShortcodesService shortcodesService,
|
||||
SettingsFromDb settingsFromDb,
|
||||
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.templateService = templateService;
|
||||
this.jobGroupService = jobGroupService;
|
||||
this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
this.templateDistributor = templateDistributor;
|
||||
this.shortcodesService = shortcodesService;
|
||||
this.settingsFromDb = settingsFromDb;
|
||||
this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
|
||||
}
|
||||
|
||||
|
||||
public async Task<List<TemplateNextRunResultDto>?> GetNextRunForJobGroupWithAutoDistributionAsync(Guid jobGroupId)
|
||||
{
|
||||
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);
|
||||
|
||||
//получаем шаблоны только в статусе Used
|
||||
var allTemplates = await templateService.Get()
|
||||
.Include(t => t.Job)
|
||||
.Where(t => t.Job!.GroupId == jobGroupId && t.StatusTypeId == TemplateStatusTypeEnum.Used)
|
||||
.AsNoTracking()
|
||||
.ToListAsync();
|
||||
if (!allTemplates.Any())
|
||||
{
|
||||
logger.LogInformation("В группе c ИД {jobGroupId} отсутствуют шаблоны в статусе Used", jobGroupId);
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.LogDebug("Всего шаблонов для распределения в статусе Used: {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)
|
||||
//{
|
||||
// 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);
|
||||
|
||||
// return await GetNextRunForEsppStandardScheduleAsync(template);
|
||||
//}
|
||||
|
||||
|
||||
public async Task<DateTimeOffset> GetNextRunForNewTemplateAsync(Guid jobGroupId, string responseArea)
|
||||
{
|
||||
// определяю это автораспределение или нет, вызываю соответствующий расчет
|
||||
|
||||
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: {jobGroupId}.", jobGroupId);
|
||||
throw new ArgumentNullException(nameof(jobGroupId), $"Не найдена группа работ с Id: {jobGroupId}");
|
||||
}
|
||||
|
||||
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);
|
||||
var nextRun = await GetNextRunForEsppStandardScheduleAsync(jobGroupId, jobGroup.ReferenceDate, jobGroup.IsResponseAreaTimezone, responseArea);
|
||||
logger.LogDebug("Получил nextRun {nextRun} по jobGroupId {jobGroupId}, тип расписания ЕСПП", nextRun, jobGroupId);
|
||||
|
||||
return nextRun;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<DateTimeOffset> GetNextRunForTemplateAsync(Guid templateId, bool isNew)
|
||||
{
|
||||
var template = await templateService.Get()
|
||||
.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}");
|
||||
}
|
||||
|
||||
if (template.Job!.Group!.IsAutoDistributionEnabled == true)
|
||||
{
|
||||
// включено автораспределение
|
||||
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
|
||||
{
|
||||
// считаем как ЕСПП
|
||||
//var offset = GetOffsetTest();
|
||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job.Group.Id, template.Job.Group.ReferenceDate, offset);
|
||||
|
||||
//var nextRun = await GetNextRunForEsppStandardScheduleAsync(template.Job.Group.Id, template.Job.Group.ReferenceDate, template);
|
||||
var responseArea = await shortcodesService.ApplyShortcodesAsync(template.Job.ResponseAreaMask, template);
|
||||
var nextRun = await GetNextRunForEsppStandardScheduleAsync(template.Job.GroupId, template.Job.Group.ReferenceDate, template.Job.Group.IsResponseAreaTimezone, responseArea);
|
||||
|
||||
logger.LogDebug("Получил nextRun {nextRun} по templateId {templateId}, isNew: {isNew}, тип расписания: ЕСПП", nextRun, templateId, isNew);
|
||||
|
||||
return nextRun;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Расчет nextRun по расписанию ЕСПП
|
||||
/// </summary>
|
||||
/// <param name="jobGroupId"></param>
|
||||
/// <param name="referenceDate"></param>
|
||||
/// <param name="template">Template with include Job, Group</param>
|
||||
/// <returns></returns>
|
||||
private async Task<DateTimeOffset> GetNextRunForEsppStandardScheduleAsync(Guid jobGroupId, DateTimeOffset referenceDate, bool isResponseAreaTimezone, string? responseArea)
|
||||
{
|
||||
//var isResponseAreaTimezone = template.Job?.Group?.IsResponseAreaTimezone ?? false;
|
||||
//string? responseArea = null;
|
||||
|
||||
//if (isResponseAreaTimezone)
|
||||
//{
|
||||
// var responseAreaMask = template.Job!.ResponseAreaMask;
|
||||
// responseArea = await shortcodesService.ApplyShortcodesAsync(responseAreaMask, template);
|
||||
//}
|
||||
|
||||
var offset = GetTimeOffset(isResponseAreaTimezone, responseArea);
|
||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template.Job!.Group!.ReferenceDate, offset);
|
||||
var nextRun = await esppScheduleTransformService.GetNextDateAsync(jobGroupId, referenceDate, offset);
|
||||
|
||||
return nextRun;
|
||||
}
|
||||
|
||||
|
||||
#region Ok
|
||||
|
||||
/// <summary>
|
||||
/// Получить продолжительность в днях
|
||||
/// </summary>
|
||||
/// <param name="config"></param>
|
||||
/// <returns></returns>
|
||||
public 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;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
|
||||
public async Task<List<DateOnly>> GetWorkDaysAsync(DateOnly start, DateOnly end, bool excludeWeekends, DateTimeOffset referenceDate)
|
||||
{
|
||||
//return await templateDistributor.GetWorkDaysAsync(start, end, excludeWeekends);
|
||||
return await templateDistributor.GetWorkDaysV2Async(start, end, excludeWeekends, referenceDate);
|
||||
|
||||
}
|
||||
|
||||
public async Task<HashSet<DateOnly>> GetWeekendsAsync(DateOnly startDate, DateOnly endDate, DateTimeOffset referenceDate)
|
||||
{
|
||||
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;
|
||||
|
||||
var offset = GetTimeOffset(isResponseAreaTimezone ?? false, responseArea);
|
||||
|
||||
return nextRun.Add(offset);
|
||||
}
|
||||
|
||||
private TimeSpan GetTimeOffset(bool isResponseAreaTimezone, string? responseArea = null)
|
||||
{
|
||||
// logger.LogDebug("Начинаю получать nextRun с учетом УЗ ЕСПП и ЗО, входные параметры: nextRun: {nextRun}, isResponseAreaTimezone: {isResponseAreaTimezone}, responseArea: {responseArea}", nextRun, isResponseAreaTimezone, responseArea);
|
||||
|
||||
var esppOffset = GetEsppAccountOffset();
|
||||
|
||||
logger.LogDebug("Получил оффсет {esppOffset}, для параметров: isResponseAreaTimezone: {isResponseAreaTimezone}, responseArea: {responseArea}", esppOffset, isResponseAreaTimezone, responseArea);
|
||||
|
||||
//if (isResponseAreaTimezone == true && !string.IsNullOrEmpty(responseArea))
|
||||
//{
|
||||
// // resultNextRun = офсет УЗ ЕСПП - offset ЗО
|
||||
// var responseAreaOffset = scheduleResponseAreaTimeOffsetService.GetByResponseAreaOrDefault(responseArea).UtcTimeOffset;
|
||||
|
||||
// var resultOffset = esppOffset- responseAreaOffset;
|
||||
|
||||
// return resultOffset;
|
||||
// //logger.LogDebug("Смещение nextRun с учетом ЗО, смещение ЗО: {responseAreaOffset}, смещение с учетом смещения УЗ ЕСПП: {resultOffset}, новое значение: {resultNextRun}", responseAreaOffset, resultOffset, resultNextRun);
|
||||
//}
|
||||
|
||||
return esppOffset;
|
||||
|
||||
// var resultOffset =
|
||||
|
||||
//// смещение УЗ ЕСПП
|
||||
//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;
|
||||
}
|
||||
|
||||
//// был паблик
|
||||
//private 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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,6 @@ namespace PARR.DAL
|
||||
#region NextRun Services
|
||||
|
||||
services.AddTransient<IEsppScheduleTransformService, EsppScheduleTransformService>();
|
||||
services.AddTransient<INextRunService, NextRunService>();
|
||||
services.AddTransient<ITemplateDistributor, TemplateDistributor>();
|
||||
services.AddTransient<ITemplateDistributorV2, TemplateDistributorV2>();
|
||||
services.AddTransient<INextRunServiceV2, NextRunServiceV2>();
|
||||
|
||||
@@ -20,7 +20,9 @@ namespace PARR.TemplateGeneratorWorker
|
||||
private readonly IJobService jobService;
|
||||
private readonly IShortcodesService shortcodesService;
|
||||
private readonly ITemplateService templateService;
|
||||
private readonly INextRunService nextRunService;
|
||||
private readonly INextRunServiceV2 nextRunService;
|
||||
|
||||
//private readonly INextRunService nextRunService;
|
||||
|
||||
//private readonly IEsppScheduleTransformService esppScheduleTransformService;
|
||||
|
||||
@@ -31,7 +33,8 @@ namespace PARR.TemplateGeneratorWorker
|
||||
IJobService jobService,
|
||||
IShortcodesService shortcodesService,
|
||||
ITemplateService templateService,
|
||||
INextRunService nextRunService
|
||||
INextRunServiceV2 nextRunService
|
||||
//INextRunService nextRunService
|
||||
//IEsppScheduleTransformService esppScheduleTransformService
|
||||
)
|
||||
{
|
||||
@@ -42,6 +45,7 @@ namespace PARR.TemplateGeneratorWorker
|
||||
this.shortcodesService = shortcodesService;
|
||||
this.templateService = templateService;
|
||||
this.nextRunService = nextRunService;
|
||||
//this.nextRunService = nextRunService;
|
||||
//this.esppScheduleTransformService = esppScheduleTransformService;
|
||||
}
|
||||
|
||||
@@ -99,8 +103,16 @@ namespace PARR.TemplateGeneratorWorker
|
||||
var templateName = await shortcodesService.ApplyShortcodesAsync(job.TemplateNameMask!, tempTemplateForShortcodes);
|
||||
|
||||
var responseArea = await shortcodesService.ApplyShortcodesAsync(job.ResponseAreaMask, tempTemplateForShortcodes);
|
||||
var workGroup = await shortcodesService.ApplyShortcodesAsync(job.WorkGroupMask, tempTemplateForShortcodes);
|
||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(job.GroupId, job.Group!.ReferenceDate);
|
||||
var nextRun = await nextRunService.GetNextRunForNewTemplateAsync(job.GroupId, responseArea);
|
||||
//var nextRun = await nextRunService.GetNextRunForNewTemplateAsync(job.GroupId, responseArea);
|
||||
var nextRun = await nextRunService.GetNextRunForNewTemplateAsync(job.GroupId, workGroup, responseArea);
|
||||
|
||||
if (!nextRun.HasValue)
|
||||
{
|
||||
logger.LogError("Job {JobId}, пытался создать шаблон с именем {templateName}, при получении nextRun вернулся null", query.JobId, templateName);
|
||||
return;
|
||||
}
|
||||
|
||||
var template = new Template
|
||||
{
|
||||
@@ -110,7 +122,7 @@ namespace PARR.TemplateGeneratorWorker
|
||||
JobId = query.JobId,
|
||||
IsActiveTemplate = query.IsActiveTemplate ?? false,
|
||||
IsActiveSchedule = query.IsActiveSchedule ?? false,
|
||||
NextRun = nextRun,
|
||||
NextRun = nextRun.Value,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
InitiatorComment = query.HistoryInitiator?.InitiatorComment,
|
||||
InitiatorParrComponentId = query.HistoryInitiator?.InitiatorParrComponentId,
|
||||
|
||||
@@ -42,7 +42,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
private readonly ITemplateNameNormalizer templateNameNormalizer;
|
||||
private readonly ITemplateUpdaterMqSender templateUpdaterMqSender;
|
||||
private readonly IMatchingStatusService matchingStatusService;
|
||||
private readonly INextRunService nextRunService;
|
||||
//private readonly INextRunService nextRunService;
|
||||
|
||||
public GroupedTemplateSynchronizer(
|
||||
ILogger<GroupedTemplateSynchronizer> logger,
|
||||
@@ -60,8 +60,8 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
ITemplateDeactivator templateDeactivator,
|
||||
ITemplateNameNormalizer templateNameNormalizer,
|
||||
ITemplateUpdaterMqSender templateUpdaterMqSender,
|
||||
IMatchingStatusService matchingStatusService,
|
||||
INextRunService nextRunService
|
||||
IMatchingStatusService matchingStatusService
|
||||
//INextRunService nextRunService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
@@ -80,7 +80,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
this.templateNameNormalizer = templateNameNormalizer;
|
||||
this.templateUpdaterMqSender = templateUpdaterMqSender;
|
||||
this.matchingStatusService = matchingStatusService;
|
||||
this.nextRunService = nextRunService;
|
||||
//this.nextRunService = nextRunService;
|
||||
}
|
||||
|
||||
public async Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator)
|
||||
@@ -486,7 +486,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
if (!string.Equals(existingTemplateForSubGroup.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
logger.LogDebug("Шаблон {TemplateId} требует обновления имени.", existingTemplateForSubGroup.Id);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(existingTemplateForSubGroup.Id, false);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(existingTemplateForSubGroup.Id, false);
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
TemplateId = existingTemplateForSubGroup.Id,
|
||||
@@ -495,8 +495,9 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
Name = expectedName,
|
||||
IsActiveTemplate = existingTemplateForSubGroup.IsActiveTemplate,
|
||||
IsActiveSchedule = existingTemplateForSubGroup.IsActiveSchedule,
|
||||
LastRun = existingTemplateForSubGroup.LastRun,
|
||||
NextRun = nextRun,
|
||||
//LastRun = existingTemplateForSubGroup.LastRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = false,
|
||||
Index = i,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
Initiator = initiator,
|
||||
@@ -540,7 +541,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
};
|
||||
|
||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(reusableTemplate.Id, true);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(reusableTemplate.Id, true);
|
||||
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
@@ -552,7 +553,8 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
IsActiveSchedule = targetJob.AutoControl?.InitUsedScheduleState ?? DefaultUsedScheduleState,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
Initiator = initiator,
|
||||
NextRun = nextRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = true,
|
||||
Index = i,
|
||||
UnitsInTemplate = subGroup
|
||||
};
|
||||
@@ -688,7 +690,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
};
|
||||
|
||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
TemplateId = template.Id,
|
||||
@@ -697,8 +699,9 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||
Name = expectedName,
|
||||
IsActiveTemplate = template.IsActiveTemplate,
|
||||
IsActiveSchedule = template.IsActiveSchedule,
|
||||
LastRun = template.LastRun,
|
||||
NextRun = nextRun,
|
||||
//LastRun = template.LastRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = false,
|
||||
Index = newIndex,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
Initiator = initiator,
|
||||
|
||||
@@ -42,7 +42,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
private readonly ITemplateUpdaterMqSender templateUpdaterMqSender;
|
||||
private readonly IMatchingStatusService matchingStatusService;
|
||||
private readonly SettingsFromDb settingsFromDb;
|
||||
private readonly INextRunService nextRunService;
|
||||
//private readonly INextRunService nextRunService;
|
||||
private readonly IOptions<TemplateSettings> templateSettings;
|
||||
|
||||
public SimpleTemplateSynchronizer(
|
||||
@@ -64,7 +64,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
ITemplateUpdaterMqSender templateUpdaterMqSender,
|
||||
IMatchingStatusService matchingStatusService,
|
||||
SettingsFromDb settingsFromDb,
|
||||
INextRunService nextRunService,
|
||||
//INextRunService nextRunService,
|
||||
IOptions<TemplateSettings> templateSettings
|
||||
)
|
||||
{
|
||||
@@ -80,7 +80,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
this.templateUpdaterMqSender = templateUpdaterMqSender;
|
||||
this.matchingStatusService = matchingStatusService;
|
||||
this.settingsFromDb = settingsFromDb;
|
||||
this.nextRunService = nextRunService;
|
||||
//this.nextRunService = nextRunService;
|
||||
this.templateSettings = templateSettings;
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
};
|
||||
|
||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(reusableTemplate.Id, true);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(reusableTemplate.Id, true);
|
||||
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
@@ -236,7 +236,8 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
IsActiveSchedule = job.AutoControl?.InitUsedScheduleState ?? DefaultUsedScheduleState,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
Initiator = initiator,
|
||||
NextRun = nextRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = true,
|
||||
UnitsInTemplate = new List<Guid>() // для простого шаблона
|
||||
};
|
||||
|
||||
@@ -259,7 +260,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
{
|
||||
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", template.Id, template.Name, expectedName);
|
||||
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
@@ -269,8 +270,9 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
Name = expectedName,
|
||||
IsActiveTemplate = template.IsActiveTemplate,
|
||||
IsActiveSchedule = template.IsActiveSchedule,
|
||||
LastRun = template.LastRun,
|
||||
NextRun = nextRun,
|
||||
//LastRun = template.LastRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = false,
|
||||
Index = template.Index,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
Initiator = initiator,
|
||||
@@ -397,7 +399,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
{
|
||||
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", template.Id, template.Name, expectedName);
|
||||
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
@@ -407,8 +409,9 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
Name = expectedName,
|
||||
IsActiveTemplate = template.IsActiveTemplate,
|
||||
IsActiveSchedule = template.IsActiveSchedule,
|
||||
LastRun = template.LastRun,
|
||||
NextRun = nextRun,
|
||||
//LastRun = template.LastRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = false,
|
||||
Index = template.Index,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||
Initiator = initiator,
|
||||
@@ -507,7 +510,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
continue;
|
||||
}
|
||||
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
//var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
var updateRequest = new TemplateUpdaterMq
|
||||
{
|
||||
@@ -517,8 +520,9 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
||||
Name = expectedName,
|
||||
IsActiveTemplate = false,
|
||||
IsActiveSchedule = false,
|
||||
LastRun = template.LastRun,
|
||||
NextRun = nextRun,
|
||||
//LastRun = template.LastRun,
|
||||
//NextRun = nextRun,
|
||||
IsNew = false,
|
||||
Index = null,
|
||||
StatusTypeId = template.StatusTypeId,
|
||||
Initiator = initiator,
|
||||
|
||||
@@ -107,8 +107,9 @@ internal class TemplateDeactivator : ITemplateDeactivator
|
||||
Name = expectedName,
|
||||
IsActiveTemplate = DefaultUnusedTemplateState,
|
||||
IsActiveSchedule = DefaultUnusedScheduleState,
|
||||
LastRun = template.LastRun,
|
||||
NextRun = template.NextRun,
|
||||
//LastRun = template.LastRun,
|
||||
//NextRun = template.NextRun,
|
||||
IsNew = false,
|
||||
Index = template.Index,
|
||||
StatusTypeId = TemplateStatusTypeEnum.Unused,
|
||||
Initiator = initiator,
|
||||
|
||||
@@ -5,6 +5,7 @@ using PARR.Constants;
|
||||
using PARR.DAL.Contracts;
|
||||
using PARR.DAL.Extensions;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.DAL.NextRunServices;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
using PARR.DAL.Services.Interfaces.Job;
|
||||
using PARR.DAL.Services.Interfaces.Unit;
|
||||
@@ -18,13 +19,15 @@ namespace PARR.TemplateUpdater.Services
|
||||
private readonly IJobService jobService;
|
||||
private readonly IUnitService unitService;
|
||||
private readonly IRobotConfigurationService robotConfigurationService;
|
||||
private readonly INextRunServiceV2 nextRunService;
|
||||
|
||||
public TemplateUpdaterService(
|
||||
ILogger<TemplateUpdaterService> logger,
|
||||
ITemplateService templateService,
|
||||
IJobService jobService,
|
||||
IUnitService unitService,
|
||||
IRobotConfigurationService robotConfigurationService
|
||||
IRobotConfigurationService robotConfigurationService,
|
||||
INextRunServiceV2 nextRunService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
@@ -32,6 +35,7 @@ namespace PARR.TemplateUpdater.Services
|
||||
this.jobService = jobService;
|
||||
this.unitService = unitService;
|
||||
this.robotConfigurationService = robotConfigurationService;
|
||||
this.nextRunService = nextRunService;
|
||||
}
|
||||
|
||||
|
||||
@@ -84,9 +88,24 @@ namespace PARR.TemplateUpdater.Services
|
||||
scheduleIsChanged = true;
|
||||
}
|
||||
|
||||
if (template.NextRun != query.NextRun)
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, query.IsNew);
|
||||
if (!nextRun.HasValue)
|
||||
{
|
||||
template.NextRun = query.NextRun;
|
||||
logger.LogError("Ошибка при расчете нового nextRun (вернулся null) для шаблона {templateId}, {templateName}", template.Id, template.Name);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
//if (template.NextRun != query.NextRun)
|
||||
//{
|
||||
// template.NextRun = query.NextRun;
|
||||
// scheduleIsChanged = true;
|
||||
//}
|
||||
|
||||
if (template.NextRun != nextRun.Value)
|
||||
{
|
||||
template.LastRun = template.NextRun;
|
||||
template.NextRun = nextRun.Value;
|
||||
scheduleIsChanged = true;
|
||||
}
|
||||
|
||||
@@ -99,7 +118,7 @@ namespace PARR.TemplateUpdater.Services
|
||||
}
|
||||
|
||||
//просто обнволяем. не влияет ни на шаблон, ни на расписание
|
||||
template.LastRun = query.LastRun;
|
||||
//template.LastRun = query.LastRun;
|
||||
template.Index = query.Index;
|
||||
template.StatusTypeId = query.StatusTypeId;
|
||||
|
||||
@@ -170,8 +189,8 @@ namespace PARR.TemplateUpdater.Services
|
||||
/// <returns></returns>
|
||||
private async Task<bool> IsValidAsync(TemplateUpdaterMq query)
|
||||
{
|
||||
var template= await templateService.Get().AsNoTracking()
|
||||
.Include(t=>t.RobotConfigurations)
|
||||
var template = await templateService.Get().AsNoTracking()
|
||||
.Include(t => t.RobotConfigurations)
|
||||
.FirstOrDefaultAsync(t => t.Id == query.TemplateId);
|
||||
|
||||
if (template == null)
|
||||
@@ -180,7 +199,7 @@ namespace PARR.TemplateUpdater.Services
|
||||
return false;
|
||||
}
|
||||
|
||||
if(template.ScheduleEsppId == null)
|
||||
if (template.ScheduleEsppId == null)
|
||||
{
|
||||
logger.LogError("Сообщение не валидно. Номер расписания не может быть null, робот не сможет обновить шаблон: {TemplateName}", template.Name);
|
||||
return false;
|
||||
|
||||
Reference in New Issue
Block a user