2024-07-02 11:43:59 +10:00
using Microsoft.EntityFrameworkCore ;
2024-07-05 15:17:48 +10:00
using Microsoft.Extensions.Logging ;
2026-01-22 10:35:27 +10:00
using PARR.BLL.Domain.Mq ;
2024-07-05 15:17:48 +10:00
using PARR.Constants ;
2026-01-22 10:35:27 +10:00
using PARR.DAL.Contracts ;
2026-01-21 16:28:17 +10:00
using PARR.DAL.NextRunServices ;
2024-07-02 11:43:59 +10:00
using PARR.DAL.Services.Interfaces ;
namespace PARR.TemplateDistributor
{
internal class TemplateDistributor : ITemplateDistributor
{
2024-07-05 15:17:48 +10:00
private readonly ILogger < TemplateDistributor > logger ;
2026-01-21 16:28:17 +10:00
private readonly INextRunService nextRunService ;
2026-01-22 10:35:27 +10:00
private readonly ITemplateService templateService ;
private readonly IRobotConfigurationService robotConfigurationService ;
2024-07-02 11:43:59 +10:00
2024-07-05 15:17:48 +10:00
public TemplateDistributor (
ILogger < TemplateDistributor > logger ,
2026-01-22 10:35:27 +10:00
INextRunService nextRunService ,
ITemplateService templateService ,
IRobotConfigurationService 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-01-21 16:28:17 +10:00
// вызвать метод распределения, и получить новые даты
var distributedTemplates = await nextRunService . GetNextRunForJobGroupWithAutoDistributionAsync ( jobGroupId ) ;
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-01-21 16:28:17 +10:00
logger . LogWarning ( "При распределении шаблонов по 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 )
. Where ( t = > t . Job . GroupId = = jobGroupId )
. 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 ) ;
robotConfigurationService . ChangeTaskStatus ( TaskStatusEnum . Updating , config ) ;
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
}
}