2024-07-02 11:43:59 +10:00
using Microsoft.EntityFrameworkCore ;
2024-07-05 15:17:48 +10:00
using Microsoft.Extensions.Logging ;
2026-04-30 10:35:31 +10:00
using PARR.Core.Repositories.Interfaces ;
2026-05-04 11:55:07 +10:00
using PARR.Core.Services.NextRunServices ;
2026-04-14 12:01:49 +10:00
using PARR.Domain.Common.Rabbit.Messages ;
2026-04-13 16:58:30 +10:00
using PARR.Domain.Enums ;
2024-07-02 11:43:59 +10:00
namespace PARR.TemplateDistributor
{
internal class TemplateDistributor : ITemplateDistributor
{
2024-07-05 15:17:48 +10:00
private readonly ILogger < TemplateDistributor > logger ;
2026-02-13 15:39:21 +10:00
//private readonly INextRunService nextRunService;
2026-03-05 10:19:54 +10:00
private readonly INextRunService nextRunService ;
2026-04-30 10:35:31 +10:00
private readonly ITemplateRepository templateService ;
private readonly IRobotConfigurationRepository robotConfigurationService ;
2024-07-02 11:43:59 +10:00
2024-07-05 15:17:48 +10:00
public TemplateDistributor (
ILogger < TemplateDistributor > logger ,
2026-02-13 15:39:21 +10:00
//INextRunService nextRunService,
2026-03-05 10:19:54 +10:00
INextRunService nextRunService ,
2026-04-30 10:35:31 +10:00
ITemplateRepository templateService ,
IRobotConfigurationRepository robotConfigurationService
2024-07-05 15:17:48 +10:00
)
2024-07-02 11:43:59 +10:00
{
2024-07-05 15:17:48 +10:00
this . logger = logger ;
2026-01-21 16:28:17 +10:00
this . nextRunService = nextRunService ;
2026-01-22 10:35:27 +10:00
this . templateService = templateService ;
this . robotConfigurationService = robotConfigurationService ;
2024-07-02 11:43:59 +10:00
}
2026-01-22 10:35:27 +10:00
public async Task DistributeAsync ( TemplateDistributorMq mqResponse )
2024-07-02 15:04:23 +10:00
{
2026-01-22 10:35:27 +10:00
var jobGroupId = mqResponse . JobGroupId ;
2026-02-13 15:39:21 +10:00
// распределяем шаблоны только в статусе Used
var templateStatusType = TemplateStatusTypeEnum . Used ;
2026-01-22 10:35:27 +10:00
2026-01-21 16:28:17 +10:00
// вызвать метод распределения, и получить новые даты
2026-02-13 15:39:21 +10:00
var distributedTemplates = await nextRunService . GetNextRunForJobGroupWithAutoDistributionAsync ( jobGroupId , templateStatusType ) ;
2024-07-05 15:17:48 +10:00
2026-01-21 16:28:17 +10:00
if ( distributedTemplates = = null )
2024-07-05 15:17:48 +10:00
{
2026-02-13 15:39:21 +10:00
logger . LogError ( "При распределении шаблонов по jobGroupId {jobGroupId} вернулся null. Это ошибка. Прекращаю распределение." , jobGroupId ) ;
2024-08-23 16:18:24 +10:00
return ;
}
2026-01-21 16:28:17 +10:00
// получить список шаблонов, сравнить их с распределенными, обновить даты, сохранить
2026-01-22 10:35:27 +10:00
var groupTemplates = await templateService . Get ( )
. Include ( t = > t . RobotConfigurations )
2026-02-13 15:39:21 +10:00
. Where ( t = > t . Job ! . GroupId = = jobGroupId & & t . StatusTypeId = = templateStatusType )
2026-01-22 10:35:27 +10:00
. ToListAsync ( ) ;
if ( ! groupTemplates . Any ( ) )
{
logger . LogWarning ( "Для jobGroupId {jobGroupId} не найдено ни одного шаблона в БД. Прекращаю обновление." , jobGroupId ) ;
return ;
}
// создать словарь для быстрого поиска
var distributedDict = distributedTemplates . ToDictionary ( t = > t . Id ) ;
int updatedCount = 0 ;
foreach ( var templateDb in groupTemplates )
{
if ( distributedDict . TryGetValue ( templateDb . Id , out var distributedTemplate ) )
{
if ( templateDb . NextRun ! = distributedTemplate . NextRun )
{
templateDb . NextRun = distributedTemplate . NextRun ;
templateDb . LastRun = distributedTemplate . NextRunOld ;
templateDb . DateModified = DateTimeOffset . UtcNow ;
// ставим задание роботу - обновить расписания
var config = robotConfigurationService . GetFromTemplateByRobotCode ( RobotsEnum . ScheduleOrder , templateDb ) ;
2026-03-13 10:22:13 +10:00
//robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
robotConfigurationService . SetUpdateTaskStatusIfAllow ( config ) ;
2026-01-22 10:35:27 +10:00
updatedCount + + ;
}
}
else
{
logger . LogWarning ( "Шаблон с Id {templateId} не найден в распределённых данных." , templateDb . Id ) ;
}
}
if ( updatedCount > 0 )
{
// сохранить изменения
if ( await templateService . CommitAsync ( mqResponse . Initiator ) )
{
logger . LogInformation ( "Обновлено {updatedCount} шаблонов в БД для jobGroupId {jobGroupId}. Для расписаний установлен статус: {taskStatus}" , updatedCount , jobGroupId , TaskStatusEnum . Updating . ToString ( ) ) ;
}
else
{
logger . LogError ( "Ошибка при обновлении записей в БД. jobGroupId {jobGroupId}, требовалось обновить шаблонов: {updatedCount}" , jobGroupId , updatedCount ) ;
}
}
else
{
logger . LogInformation ( "Для jobGroupId {jobGroupId} не найдено изменений. Ничего не обновлено." , jobGroupId ) ;
}
2024-07-11 11:32:14 +10:00
}
2024-07-02 11:43:59 +10:00
}
}