feat(templateDistributor, BLL): доделал распределение шаблонов. Сохраняет в БД + ставит задания роботам на обновление. MqService - может принимать список объектов для отправки, доработана кодировка отправки сообщений.

This commit is contained in:
Mikhail Trubnikov
2026-01-22 10:35:27 +10:00
parent e5bc42741c
commit b7fca08d28
8 changed files with 132 additions and 19 deletions

View File

@@ -1,4 +1,6 @@
namespace PARR.TemplateDistributor
using PARR.BLL.Domain.Mq;
namespace PARR.TemplateDistributor
{
public interface ITemplateDistributor
{
@@ -7,6 +9,6 @@
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
Task DistributeAsync(Guid jobGroupId);
Task DistributeAsync(TemplateDistributorMq mqResponse);
}
}

View File

@@ -65,8 +65,7 @@ namespace PARR.TemplateDistributor
if (service == null)
throw new Exception($"Не найден сервис: {nameof(ITemplateDistributor)}");
await service.DistributeAsync(query.JobGroupId);
await service.DistributeAsync(query);
}
}

View File

@@ -1,12 +1,10 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.BLL.Domain.Mq;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.Contracts;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;
using System.Reflection.Metadata.Ecma335;
namespace PARR.TemplateDistributor
{
@@ -14,19 +12,27 @@ namespace PARR.TemplateDistributor
{
private readonly ILogger<TemplateDistributor> logger;
private readonly INextRunService nextRunService;
private readonly ITemplateService templateService;
private readonly IRobotConfigurationService robotConfigurationService;
public TemplateDistributor(
ILogger<TemplateDistributor> logger,
INextRunService nextRunService
INextRunService nextRunService,
ITemplateService templateService,
IRobotConfigurationService robotConfigurationService
)
{
this.logger = logger;
this.nextRunService = nextRunService;
this.templateService = templateService;
this.robotConfigurationService = robotConfigurationService;
}
public async Task DistributeAsync(Guid jobGroupId)
public async Task DistributeAsync(TemplateDistributorMq mqResponse)
{
var jobGroupId = mqResponse.JobGroupId;
// вызвать метод распределения, и получить новые даты
var distributedTemplates = await nextRunService.GetNextRunForJobGroupWithAutoDistributionAsync(jobGroupId);
@@ -37,6 +43,61 @@ namespace PARR.TemplateDistributor
}
// получить список шаблонов, сравнить их с распределенными, обновить даты, сохранить
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);
}
}
}
}