383 lines
18 KiB
C#
383 lines
18 KiB
C#
|
|
using Microsoft.EntityFrameworkCore;
|
|||
|
|
using Microsoft.Extensions.Logging;
|
|||
|
|
using Microsoft.Extensions.Options;
|
|||
|
|
using PARR.Core.Repositories.Interfaces;
|
|||
|
|
using PARR.Core.Repositories.Interfaces.JobRepositories;
|
|||
|
|
using PARR.Core.Repositories.Interfaces.Unit;
|
|||
|
|
using PARR.Core.Services.MatchingStatusService;
|
|||
|
|
using PARR.Domain.Cache.Models;
|
|||
|
|
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
|
|||
|
|
using PARR.Domain.Entities;
|
|||
|
|
using PARR.Domain.Entities.Base.History;
|
|||
|
|
using PARR.Domain.Entities.JobEntities;
|
|||
|
|
using PARR.Domain.Entities.Unit;
|
|||
|
|
using PARR.Domain.Enums;
|
|||
|
|
using PARR.TemplateMatcher.Constants;
|
|||
|
|
using PARR.TemplateMatcher.Services.Interfaces;
|
|||
|
|
using PARR.TemplateMatcher.Settings;
|
|||
|
|
using System.Diagnostics;
|
|||
|
|
|
|||
|
|
namespace PARR.TemplateMatcher.Services.Implementations;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Синхронизация неиспользуемых шаблонов.
|
|||
|
|
/// Вынесен из SimpleTemplateSynchronizer для разделения ответственности.
|
|||
|
|
/// </summary>
|
|||
|
|
internal sealed class UnusedTemplatesSyncService: IUnusedTemplatesSyncService
|
|||
|
|
{
|
|||
|
|
private readonly ITemplateRepository _templateService;
|
|||
|
|
private readonly IJobRepository _jobService;
|
|||
|
|
private readonly IUnitFieldRepository _unitFieldService;
|
|||
|
|
private readonly IUnitInValueRepository _unitInValueService;
|
|||
|
|
private readonly IUnitRepository _unitRepository;
|
|||
|
|
private readonly ITemplateMqPublisher _templateMqPublisher;
|
|||
|
|
private readonly IMatchingStatusService _matchingStatusService;
|
|||
|
|
private readonly ITemplateNameNormalizer _templateNameNormalizer;
|
|||
|
|
private readonly IOptions<TemplateSettings> _templateSettings;
|
|||
|
|
private readonly ILogger<UnusedTemplatesSyncService> _logger;
|
|||
|
|
|
|||
|
|
public UnusedTemplatesSyncService(
|
|||
|
|
ITemplateRepository templateService,
|
|||
|
|
IJobRepository jobService,
|
|||
|
|
IUnitFieldRepository unitFieldService,
|
|||
|
|
IUnitInValueRepository unitInValueService,
|
|||
|
|
IUnitRepository unitRepository,
|
|||
|
|
ITemplateMqPublisher templateMqPublisher,
|
|||
|
|
IMatchingStatusService matchingStatusService,
|
|||
|
|
ITemplateNameNormalizer templateNameNormalizer,
|
|||
|
|
IOptions<TemplateSettings> templateSettings,
|
|||
|
|
ILogger<UnusedTemplatesSyncService> logger)
|
|||
|
|
{
|
|||
|
|
_templateService = templateService;
|
|||
|
|
_jobService = jobService;
|
|||
|
|
_unitFieldService = unitFieldService;
|
|||
|
|
_unitInValueService = unitInValueService;
|
|||
|
|
_unitRepository = unitRepository;
|
|||
|
|
_templateMqPublisher = templateMqPublisher;
|
|||
|
|
_matchingStatusService = matchingStatusService;
|
|||
|
|
_templateNameNormalizer = templateNameNormalizer;
|
|||
|
|
_templateSettings = templateSettings;
|
|||
|
|
_logger = logger;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
public async Task SyncAsync(
|
|||
|
|
Guid unusedJobId,
|
|||
|
|
HistoryInitiator initiator,
|
|||
|
|
bool dryRun = false,
|
|||
|
|
CancellationToken ct = default)
|
|||
|
|
{
|
|||
|
|
ct.ThrowIfCancellationRequested();
|
|||
|
|
|
|||
|
|
var existingStatus = await _matchingStatusService.GetStatusAsync(
|
|||
|
|
unusedJobId, SyncTaskEntityTypeEnum.Job);
|
|||
|
|
|
|||
|
|
if (existingStatus.DetailsJobs?.Count > 0)
|
|||
|
|
{
|
|||
|
|
_logger.LogWarning(
|
|||
|
|
"Синхронизация для Job неиспользуемых шаблонов {JobId} уже запущена. Пропускаем.",
|
|||
|
|
unusedJobId);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var statusComment = dryRun
|
|||
|
|
? "DryRun: Анализ неиспользуемых шаблонов"
|
|||
|
|
: "Синхронизация неиспользуемых шаблонов";
|
|||
|
|
|
|||
|
|
await SetStatusAsync(unusedJobId, statusComment);
|
|||
|
|
|
|||
|
|
var totalSw = Stopwatch.StartNew();
|
|||
|
|
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
// Поиск полей
|
|||
|
|
var responsableAreaField = await _unitFieldService
|
|||
|
|
.GetByAihitNameAsync(UnusedTemplateConstants.ResponsibilityAreaFieldName, ct);
|
|||
|
|
var tagField = await _unitFieldService
|
|||
|
|
.GetByAihitNameAsync(UnusedTemplateConstants.ParrTagFieldName, ct);
|
|||
|
|
|
|||
|
|
if (responsableAreaField == null || tagField == null)
|
|||
|
|
{
|
|||
|
|
_logger.LogError(
|
|||
|
|
"Не найдены поля '{Field1}' или '{Field2}'. Синхронизация прервана.",
|
|||
|
|
UnusedTemplateConstants.ResponsibilityAreaFieldName,
|
|||
|
|
UnusedTemplateConstants.NotUsedTagValue);
|
|||
|
|
await SetStatusAsync(unusedJobId, "Ошибка конфигурации полей");
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var responsableAreaFieldId = responsableAreaField.Id;
|
|||
|
|
var tagFieldId = tagField.Id;
|
|||
|
|
|
|||
|
|
// 2. Находим ValueId для тега "ПАРР-НЕИСП"
|
|||
|
|
var targetTagValueId = await _unitInValueService.Get()
|
|||
|
|
.AsNoTracking()
|
|||
|
|
.Where(uiv => uiv.FieldId == tagFieldId && uiv.Value != null && uiv.Value.Value == UnusedTemplateConstants.NotUsedTagValue)
|
|||
|
|
.Select(uiv => uiv.ValueId)
|
|||
|
|
.FirstOrDefaultAsync(ct);
|
|||
|
|
|
|||
|
|
if (targetTagValueId == Guid.Empty)
|
|||
|
|
{
|
|||
|
|
_logger.LogWarning("Значение '{TagValue}' для поля '{FieldName}' не найдено в справочнике UnitFieldValue.", UnusedTemplateConstants.NotUsedTagValue, UnusedTemplateConstants.ParrTagFieldName);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var unusedJob = await _jobService.Get().AsNoTracking()
|
|||
|
|
.Include(t => t!.Group).ThenInclude(t => t!.GroupType)
|
|||
|
|
.Include(t => t!.Tnk)
|
|||
|
|
.FirstOrDefaultAsync(j => j.Id == unusedJobId, ct);
|
|||
|
|
|
|||
|
|
if (unusedJob == null)
|
|||
|
|
{
|
|||
|
|
_logger.LogError("Job неиспользуемых шаблонов {JobId} не найден.", unusedJobId);
|
|||
|
|
await SetStatusAsync(unusedJobId, "Job не найден");
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var unusedTemplates = await _templateService.Get()
|
|||
|
|
.Include(t => t.Unit)
|
|||
|
|
.Where(t => t.StatusTypeId == TemplateStatusTypeEnum.Unused)
|
|||
|
|
.ToListAsync(ct);
|
|||
|
|
|
|||
|
|
if (!unusedTemplates.Any())
|
|||
|
|
{
|
|||
|
|
_logger.LogInformation("Не найдено шаблонов со статусом Unused.");
|
|||
|
|
await SetStatusAsync(unusedJobId, "Нет шаблонов для обработки");
|
|||
|
|
await _matchingStatusService.DeleteMatchingStatusAsync(unusedJobId, SyncTaskEntityTypeEnum.Job);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
await SetStatusAsync(unusedJobId, $"Найдено {unusedTemplates.Count} шаблонов для обработки");
|
|||
|
|
|
|||
|
|
int processed = 0;
|
|||
|
|
var allTemplateUnitIds = unusedTemplates.Select(t => t.UnitId).Distinct().ToList();
|
|||
|
|
|
|||
|
|
// Получаем значения ЗОНА_ОТВЕТСТВЕННОСТИ для всех юнитов шаблонов
|
|||
|
|
var unitResponsableAreaValues = await _unitInValueService.GetByUnitIdsAndFieldIdsAsync(allTemplateUnitIds, new List<Guid> { responsableAreaFieldId }, ct);
|
|||
|
|
var unitToResponsableAreaValueMap = unitResponsableAreaValues
|
|||
|
|
.Where(uiv => uiv.ValueId != Guid.Empty)
|
|||
|
|
.ToDictionary(uiv => uiv.UnitId, uiv => uiv.ValueId);
|
|||
|
|
|
|||
|
|
// Пакетный поиск целевых юнитов (Один запрос к БД вместо N)
|
|||
|
|
var responsableAreaToTargetUnitMap = new Dictionary<Guid, Guid>();
|
|||
|
|
var distinctResponsableAreaValues = unitToResponsableAreaValueMap.Values.Distinct().ToList();
|
|||
|
|
|
|||
|
|
if (targetTagValueId != Guid.Empty &&
|
|||
|
|
distinctResponsableAreaValues.Any())
|
|||
|
|
{
|
|||
|
|
_logger.LogDebug("Пакетный поиск целевых юнитов с тегом 'ПАРР-НЕИСП' для {Count} уникальных значений ЗОНА_ОТВЕТСТВЕННОСТИ.", distinctResponsableAreaValues.Count);
|
|||
|
|
|
|||
|
|
// Передаем ct в ToListAsync
|
|||
|
|
var matches = await _unitInValueService.Get().AsNoTracking()
|
|||
|
|
.Where(uiv => uiv.FieldId == responsableAreaFieldId && distinctResponsableAreaValues.Contains(uiv.ValueId))
|
|||
|
|
.Join(
|
|||
|
|
_unitInValueService.Get().AsNoTracking().Where(t => t.FieldId == tagFieldId && t.ValueId == targetTagValueId),
|
|||
|
|
responsableArea => responsableArea.UnitId,
|
|||
|
|
tag => tag.UnitId,
|
|||
|
|
(responsableArea, tag) => new { responsableArea.ValueId, responsableArea.UnitId }
|
|||
|
|
)
|
|||
|
|
.ToListAsync(ct);
|
|||
|
|
|
|||
|
|
responsableAreaToTargetUnitMap = matches
|
|||
|
|
.GroupBy(x => x.ValueId)
|
|||
|
|
.ToDictionary(g => g.Key, g => g.First().UnitId);
|
|||
|
|
|
|||
|
|
_logger.LogDebug("Сформирован кэш соответствий: найдено {Count} целевых юнитов.", responsableAreaToTargetUnitMap.Count);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
foreach (var template in unusedTemplates)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
// Проверка отмены внутри цикла (на случай долгих вычислений)
|
|||
|
|
ct.ThrowIfCancellationRequested();
|
|||
|
|
|
|||
|
|
if (template.Unit == null)
|
|||
|
|
{
|
|||
|
|
_logger.LogWarning("У шаблона {TemplateId} отсутствует Unit. Пропускаем.", template.Id);
|
|||
|
|
processed++;
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 1. Определяем текущее значение ЗОНА_ОТВЕТСТВЕННОСТИ
|
|||
|
|
var currentResponsableAreaValueId = Guid.Empty;
|
|||
|
|
var hasResponsableArea = unitToResponsableAreaValueMap.TryGetValue(template.UnitId, out currentResponsableAreaValueId);
|
|||
|
|
|
|||
|
|
// 2. Ищем целевой юнит в кэше
|
|||
|
|
Guid? targetUnitId = null;
|
|||
|
|
if (hasResponsableArea && currentResponsableAreaValueId != Guid.Empty)
|
|||
|
|
{
|
|||
|
|
if (responsableAreaToTargetUnitMap.TryGetValue(currentResponsableAreaValueId, out var foundUnitId) && foundUnitId != Guid.Empty)
|
|||
|
|
{
|
|||
|
|
targetUnitId = foundUnitId;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 3. Финализируем UnitId и Unit
|
|||
|
|
Guid finalUnitId = targetUnitId ?? template.UnitId;
|
|||
|
|
Unit finalUnit = template.Unit;
|
|||
|
|
|
|||
|
|
if (targetUnitId.HasValue && targetUnitId.Value != template.UnitId)
|
|||
|
|
{
|
|||
|
|
_logger.LogInformation("Для шаблона {TemplateId} найден новый UnitId {NewUnitId} (был {OldUnitId}).",
|
|||
|
|
template.Id, targetUnitId.Value, template.UnitId);
|
|||
|
|
|
|||
|
|
// Передаем ct в запрос
|
|||
|
|
var newUnit = await _unitRepository.Get().AsNoTracking()
|
|||
|
|
.FirstOrDefaultAsync(u => u.Id == targetUnitId.Value, ct);
|
|||
|
|
|
|||
|
|
if (newUnit != null)
|
|||
|
|
{
|
|||
|
|
finalUnit = newUnit;
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
_logger.LogWarning("Не удалось загрузить новый юнит {UnitId}. Используем старый.", targetUnitId.Value);
|
|||
|
|
finalUnitId = template.UnitId;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
else if (!hasResponsableArea)
|
|||
|
|
{
|
|||
|
|
_logger.LogDebug("У юнита {UnitId} шаблона {TemplateId} нет значения поля ЗОНА_ОТВЕТСТВЕННОСТИ. Оставляем текущий UnitId.", template.UnitId, template.Id);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. Генерация целевого имени
|
|||
|
|
var expectedName = await GenerateUnusedTemplateNameAsync(template, unusedJob, finalUnit);
|
|||
|
|
|
|||
|
|
// 5. Проверка необходимости обновления
|
|||
|
|
bool unitChanged = template.UnitId != finalUnitId;
|
|||
|
|
bool jobChanged = template.JobId != unusedJobId;
|
|||
|
|
bool nameChanged = !string.Equals(template.Name, expectedName, StringComparison.OrdinalIgnoreCase);
|
|||
|
|
|
|||
|
|
if (!unitChanged && !jobChanged && !nameChanged)
|
|||
|
|
{
|
|||
|
|
_logger.LogDebug("Шаблон {TemplateId} уже актуален. Пропуск отправки в MQ.", template.Id);
|
|||
|
|
processed++;
|
|||
|
|
continue;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Условие DryRun для отправки в MQ
|
|||
|
|
if (!dryRun)
|
|||
|
|
{
|
|||
|
|
await SendUpdateRequest(template, unusedJobId, expectedName, initiator, finalUnitId);
|
|||
|
|
_logger.LogDebug("Отправлен запрос на обновление шаблона {TemplateId}. Изменения: Unit={U}, Job={J}, Name={N}",
|
|||
|
|
template.Id, unitChanged, jobChanged, nameChanged);
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
_logger.LogInformation("[DryRun] Пропущена отправка запроса на обновление шаблона {TemplateId}. Изменения: Unit={U}, Job={J}, Name={N}, ExpectedName='{Name}'",
|
|||
|
|
template.Id, unitChanged, jobChanged, nameChanged, expectedName);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
processed++;
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
_logger.LogError(ex, "Ошибка при обработке шаблона {TemplateId}", template.Id);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
totalSw.Stop();
|
|||
|
|
|
|||
|
|
_logger.LogInformation("[Perf] Job '{JobName}' ({JobId}) | ИТОГО: {TotalMs} мс",
|
|||
|
|
unusedJob.Name, unusedJob.Id, totalSw.ElapsedMilliseconds);
|
|||
|
|
|
|||
|
|
var finalComment = dryRun
|
|||
|
|
? "DryRun: Анализ неиспользуемых шаблонов завершён без изменений"
|
|||
|
|
: "Синхронизация неиспользуемых шаблонов завершена";
|
|||
|
|
|
|||
|
|
await SetStatusAsync(unusedJobId, finalComment);
|
|||
|
|
await _matchingStatusService.DeleteMatchingStatusAsync(
|
|||
|
|
unusedJobId, SyncTaskEntityTypeEnum.Job);
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
totalSw.Stop();
|
|||
|
|
_logger.LogError(ex,
|
|||
|
|
"Ошибка при синхронизации неиспользуемых шаблонов для Job {JobId} через {ElapsedMs} мс",
|
|||
|
|
unusedJobId, totalSw.ElapsedMilliseconds);
|
|||
|
|
await SetStatusAsync(unusedJobId, $"Ошибка: {ex.Message}");
|
|||
|
|
throw;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
private async Task SendUpdateRequest(Template template, Guid jobId, string name, HistoryInitiator initiator, Guid unitId)
|
|||
|
|
{
|
|||
|
|
var updateRequest = new TemplateUpdaterMessage
|
|||
|
|
{
|
|||
|
|
TemplateId = template.Id,
|
|||
|
|
JobId = jobId,
|
|||
|
|
UnitId = unitId,
|
|||
|
|
Name = name,
|
|||
|
|
IsActiveTemplate = false,
|
|||
|
|
IsActiveSchedule = false,
|
|||
|
|
IsNew = false,
|
|||
|
|
Index = null,
|
|||
|
|
StatusTypeId = template.StatusTypeId,
|
|||
|
|
Initiator = initiator,
|
|||
|
|
UnitsInTemplate = new List<UnitInTemplateMessage>()
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
await _templateMqPublisher.PublishUpdateAsync(updateRequest);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
private async Task<string> GenerateUnusedTemplateNameAsync(Template template, Job unusedJob, Unit unit)
|
|||
|
|
{
|
|||
|
|
var tempJob = new Job
|
|||
|
|
{
|
|||
|
|
Id = unusedJob.Id,
|
|||
|
|
Name = unusedJob.Name,
|
|||
|
|
WorkName = unusedJob.WorkName,
|
|||
|
|
MinValueRelationships = unusedJob.MinValueRelationships,
|
|||
|
|
MaxValueRelationships = unusedJob.MaxValueRelationships,
|
|||
|
|
IsParentRelationships = unusedJob.IsParentRelationships,
|
|||
|
|
TemplateNameMask = _templateSettings.Value.UnusedTemplateNameMask,
|
|||
|
|
WorkGroupMask = unusedJob.WorkGroupMask,
|
|||
|
|
ResponseAreaMask = unusedJob.ResponseAreaMask,
|
|||
|
|
TnkId = unusedJob.TnkId,
|
|||
|
|
GroupId = unusedJob.GroupId,
|
|||
|
|
Group = unusedJob.Group,
|
|||
|
|
Tnk = unusedJob.Tnk,
|
|||
|
|
UnitFilters = unusedJob.UnitFilters,
|
|||
|
|
Templates = unusedJob.Templates,
|
|||
|
|
AutoControl = unusedJob.AutoControl
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
var tempTemplateForName = new Template
|
|||
|
|
{
|
|||
|
|
Id = template.Id,
|
|||
|
|
Name = template.Name,
|
|||
|
|
JobId = unusedJob.Id,
|
|||
|
|
UnitId = unit.Id,
|
|||
|
|
Index = null,
|
|||
|
|
Job = tempJob,
|
|||
|
|
Unit = unit,
|
|||
|
|
UnitsInTemplate = new List<UnitsInTemplate>()
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
return await _templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
private async Task SetStatusAsync(Guid jobId, string comment)
|
|||
|
|
{
|
|||
|
|
var status = new MatchingStatusItemDto
|
|||
|
|
{
|
|||
|
|
DateStart = DateTimeOffset.UtcNow,
|
|||
|
|
Action = TemplateMatcherActionEnum.Sync,
|
|||
|
|
Comment = comment
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
await _matchingStatusService.SetMatchingStatusAsync(
|
|||
|
|
jobId,
|
|||
|
|
SyncTaskEntityTypeEnum.Job,
|
|||
|
|
new MatchingStatusItem
|
|||
|
|
{
|
|||
|
|
Data = status,
|
|||
|
|
Timestamp = DateTimeOffset.UtcNow,
|
|||
|
|
Source = nameof(UnusedTemplatesSyncService)
|
|||
|
|
},
|
|||
|
|
TimeSpan.FromMinutes(30));
|
|||
|
|
}
|
|||
|
|
}
|