feat(api,dal,nextRun): добаботана логика расчета nextRun в API и NetRunWorker. Рассчет ведется относительно refDate

This commit is contained in:
Mikhail Trubnikov
2025-11-25 16:49:28 +10:00
parent ce12f1b5fe
commit 2823823784
4 changed files with 166 additions and 78 deletions

View File

@@ -3,7 +3,9 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.TransformServices;
using PARR.NextRun.Settings;
@@ -40,11 +42,12 @@ namespace PARR.NextRun
//var appInWorkService = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
if (templateService == null || esppSchService == null)
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(IEsppScheduleTransformService)}");
if (templateService == null || esppSchService == null || jobGroupService == null)
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(IEsppScheduleTransformService)} или {nameof(IJobGroupService)}");
await HandlerAsync(templateService, esppSchService);
await HandlerAsync(templateService, esppSchService, jobGroupService);
}
}, workerSettings.RepeatEvery);
}
@@ -54,33 +57,90 @@ namespace PARR.NextRun
/// Рассчет следующей даты срабатываения
/// </summary>
/// <returns></returns>
private async Task HandlerAsync(ITemplateService templateService, IEsppScheduleTransformService esppScheduleTransformService)
private async Task HandlerAsync(ITemplateService templateService, IEsppScheduleTransformService esppScheduleTransformService, IJobGroupService jobGroupService)
{
var templates = await templateService.Get()
.Include(t => t.Job)
.ThenInclude(t => t.Group)
.Where(t => t.NextRun < DateTimeOffset.UtcNow).ToListAsync();
#region логика для групп у которых не включено автораспределение
logger.LogDebug($"Шаблонов для обновления: {templates.Count()} шт.");
// выбираем шаблоны которые не учавствуют в автораспределении
// и у которых IsUnuser==false
// затем группируем по GroupId, так как nextRun и расписание настраивается для группы, то для всех дочерних шаблонов, nextRun будет одинаковым
int errorsCount = 0;
foreach (var template in templates)
var groups = await jobGroupService.Get()
.Where(t => t.IsAutoDistributionEnabled == false)
.Select(t => new { t.Id, t.ReferenceDate })
.ToListAsync();
logger.LogInformation("Найдено {GroupCount} групп для обработки.", groups.Count);
foreach (var group in groups)
{
var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template.NextRun);
template.LastRun = template.NextRun;
template.NextRun = nextRun;
//получаем по каждой группе следующий nextRun и сравниваем с существующим, если не равны, то обновляем
var nextRun = await esppScheduleTransformService.GetNextDateAsync(group.Id, group.ReferenceDate);
// Загружаем только шаблоны текущей группы где nextRun в БД не равен расчетному
var templatesToUpdate = await templateService.Get()
.Where(t => t.IsUnused == false && t.Job!.GroupId == group.Id && t.NextRun != nextRun)
.ToListAsync();
if (!templatesToUpdate.Any())
continue;
// Обновляем
foreach (var template in templatesToUpdate)
{
template.LastRun = template.NextRun;
template.NextRun = nextRun;
}
// Коммитим изменения для этой группы
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = Constants.ParrComponentsEnum.NextRun }))
logger.LogDebug($"Обновлены значения полей NextRun: {template.NextRun}, LastRun: {template.LastRun} для шаблона {template.Name}, {template.Id}");
logger.LogInformation($"Обновлены значения полей NextRun для шаблонов группы: {group.Id}, " +
$"refDate: {group.ReferenceDate}. Обновлен nextRun: {nextRun} для шаблонов {templatesToUpdate.Count} шт.");
else
{
logger.LogError($"Ошибка при обновлении значений полей NextRun: {template.NextRun}, LastRun: {template.LastRun} для шаблона {template.Name}, {template.Id}");
errorsCount++;
logger.LogError($"Ошибка при обновлении значений полей NextRun: {nextRun}, для шаблонов {templatesToUpdate.Count} шт., группы {group.Id}, refDate: {group.ReferenceDate} ");
}
}
logger.LogInformation($"Завершено обновление полей NextRun. Полей в задании: {templates.Count()}, обновлено: {templates.Count() - errorsCount}, ошибок: {errorsCount}");
#endregion
//todo: когда будет автораспределение, для него придумать логику как считать
#region old logic
//var templates = await templateService.Get()
// .Include(t => t.Job)
// .ThenInclude(t => t.Group)
// .Where(t => t.NextRun < DateTimeOffset.UtcNow).ToListAsync();
//logger.LogDebug($"Шаблонов для обновления: {templates.Count()} шт.");
//int errorsCount = 0;
//foreach (var template in templates)
//{
// var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template.NextRun);
// template.LastRun = template.NextRun;
// template.NextRun = nextRun;
// if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = Constants.ParrComponentsEnum.NextRun }))
// logger.LogDebug($"Обновлены значения полей NextRun: {template.NextRun}, LastRun: {template.LastRun} для шаблона {template.Name}, {template.Id}");
// else
// {
// logger.LogError($"Ошибка при обновлении значений полей NextRun: {template.NextRun}, LastRun: {template.LastRun} для шаблона {template.Name}, {template.Id}");
// errorsCount++;
// }
//}
//logger.LogInformation($"Завершено обновление полей NextRun. Полей в задании: {templates.Count()}, обновлено: {templates.Count() - errorsCount}, ошибок: {errorsCount}");
#endregion
logger.LogInformation($"Завершено обновление полей NextRun.");
}
}
}