Compare commits

4 Commits

Author SHA1 Message Date
Mikhail Kuznetsov
0629579cf0 reafctor(templateMatcher): сервис синхронизации неактуальных шаблонов вынесен в отдельный класс 2026-09-10 14:12:47 +10:00
Mikhail Kuznetsov
83c6a5f605 feat(templateMatcher):
- добавлен режим DryRun
- изменен подход к фильтрации шаблонов по рабочей группе - перенесено из этапа основной фильтрации в этап посторение подргупп/шаблонов
- при использовании тегов альтернативных рабочих групп фильтрация по списку пропускается
2026-09-09 17:09:57 +10:00
Mikhail Kuznetsov
e02a51f5ed fix(shortcodesService): исправлена загрузка шорткода %ТЕГ_СВЯЗИ:...% - отсутствовало требование загрузки UnitsInTemplate 2026-09-08 09:47:31 +10:00
Mikhail Kuznetsov
fb20395e53 refactor(unitFilterService): логика фильтрации связанных ЭК перенесена в класс, который за это отвечает. 2026-07-31 10:46:48 +10:00
25 changed files with 837 additions and 880 deletions

View File

@@ -4,19 +4,11 @@ namespace PARR.Core.Repositories.Interfaces.Unit
{
public interface IUnitInUnitRepository
{
Task<List<UnitInUnit>> GetByParentIdAsync(Guid parentId);
Task<List<UnitInUnit>> GetByChildIdAsync(Guid childId);
/// <summary>
/// Получает связи, где ChildUnitId unitIds (для IsParent=True).
/// Возвращает все связанные UnitId для заданного юнита в обоих направлениях.
/// Единая точка загрузки связей.
/// </summary>
Task<List<UnitInUnit>> GetParentLinksByChildIdsAsync(IEnumerable<Guid> childUnitIds);
/// <summary>
/// Получает связи, где ParentUnitId unitIds (для IsParent=False).
/// </summary>
Task<List<UnitInUnit>> GetChildLinksByParentIdsAsync(IEnumerable<Guid> parentUnitIds);
Task<List<Guid>> GetRelatedUnitIdsAsync(Guid unitId, CancellationToken ct = default);
IQueryable<UnitInUnit> Get();
}

View File

@@ -14,7 +14,7 @@ internal class RelatedUnitTagShortcodeHandler : IShortcodeHandler
private static readonly Regex _pattern = new(@"%ТЕГ_СВЯЗИ:([^%]+)%", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public Regex Pattern => _pattern;
public ShortcodeDataRequirementsEnum Requirements => ShortcodeDataRequirementsEnum.UnitsInTemplateTags;
public ShortcodeDataRequirementsEnum Requirements => ShortcodeDataRequirementsEnum.UnitsInTemplateTags | ShortcodeDataRequirementsEnum.UnitsInTemplate;
public RelatedUnitTagShortcodeHandler(ILogger<RelatedUnitTagShortcodeHandler> logger)
{

View File

@@ -209,7 +209,7 @@ internal class ShortcodesService : IShortcodesService
}
// 5. Проверка UnitTags
// 4. Проверка UnitTags
var unitTags = currentData.UnitTags;
if ((unitTags == null || unitTags.Count == 0) &&
requirements.HasFlag(ShortcodeDataRequirementsEnum.UnitTags))
@@ -223,7 +223,7 @@ internal class ShortcodesService : IShortcodesService
.Where(u => u.Id == template.UnitId)
.SelectMany(u => u.UnitValues
.Where(uv => uv.Field != null &&
uv.Field.AihitName == "ПАРР тег" &&
uv.Field.Code == "tag" &&
uv.Value != null &&
uv.Value.Value != null)
.Select(uv => uv.Value!.Value!))
@@ -231,9 +231,22 @@ internal class ShortcodesService : IShortcodesService
.ConfigureAwait(false);
}
// 6. Проверка RelatedUnitTags
// 5. Проверка RelatedUnitTags
var relatedUnitTags = currentData.RelatedUnitTags;
var relatedUnitIds = template.UnitsInTemplate?.Select(uit => uit.UnitId).Distinct().ToList() ?? new List<Guid>();
// Приводим template.UnitsInTemplate к List<UnitInTemplateForShortcode> через маппинг
var mappedTemplateUnits = template.UnitsInTemplate?
.Select(uit => new UnitInTemplateForShortcode(uit.UnitId, uit.UnitFieldValueId))
.ToList();
var actualUnitsInTemplate = unitsInTemplate
?? currentData.UnitsInTemplate
?? mappedTemplateUnits;
var relatedUnitIds = actualUnitsInTemplate?
.Select(uit => uit.UnitId)
.Distinct()
.ToList() ?? new List<Guid>();
if ((relatedUnitTags == null || relatedUnitTags.Count == 0) &&
requirements.HasFlag(ShortcodeDataRequirementsEnum.UnitsInTemplateTags) &&
@@ -248,7 +261,7 @@ internal class ShortcodesService : IShortcodesService
.Where(u => relatedUnitIds.Contains(u.Id))
.SelectMany(u => u.UnitValues
.Where(uv => uv.Field != null &&
uv.Field.AihitName == "ПАРР тег" &&
uv.Field.Code == "tag" &&
uv.Value != null &&
uv.Value.Value != null)
.Select(uv => new { UnitId = u.Id, Tag = uv.Value!.Value! }))
@@ -260,12 +273,12 @@ internal class ShortcodesService : IShortcodesService
.ToDictionary(g => g.Key, g => g.Select(x => x.Tag).ToList());
}
// 7. Возвращаем обновленный рекорд
// 6. Возвращаем обновленный рекорд
return currentData with
{
UnitName = unitName ?? string.Empty,
Job = jobData,
UnitsInTemplate = unitsInTemplate ?? currentData.UnitsInTemplate,
UnitsInTemplate = unitsInTemplate ?? currentData.UnitsInTemplate ?? new List<UnitInTemplateForShortcode>(),
UnitTags = unitTags ?? currentData.UnitTags,
RelatedUnitTags = relatedUnitTags ?? currentData.RelatedUnitTags
};

View File

@@ -4,6 +4,7 @@ using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.Unit;
namespace PARR.Core.Services.UnitFilterService.Matchers;
@@ -238,9 +239,9 @@ internal class UnitRelationshipMatcher : IUnitRelationshipMatcher
}
/// <summary>
/// Обрабатывает маску LIKE для корректной работы с SQL
/// Нормализует пользовательскую маску в формат, совместимый с PostgreSQL ILIKE.
/// </summary>
private static string NormalizeLikeMask(string valueMask)
internal static string NormalizeLikeMask(string valueMask)
{
if (string.IsNullOrWhiteSpace(valueMask))
return valueMask;
@@ -258,4 +259,62 @@ internal class UnitRelationshipMatcher : IUnitRelationshipMatcher
else
return valueMask;
}
/// <summary>
/// Проверяет соответствие значения маске в формате ILIKE.
/// Эмулирует поведение PostgreSQL ILIKE для использования в C#-коде.
/// Регистронезависима.
/// </summary>
internal static bool MatchesLikeMask(string value, string mask)
{
if (string.IsNullOrEmpty(mask))
return true;
bool startsWithWildcard = mask.StartsWith('%');
bool endsWithWildcard = mask.EndsWith('%');
var core = mask.Trim('%');
if (startsWithWildcard && endsWithWildcard)
return value.Contains(core, StringComparison.OrdinalIgnoreCase);
if (endsWithWildcard)
return value.StartsWith(core, StringComparison.OrdinalIgnoreCase);
if (startsWithWildcard)
return value.EndsWith(core, StringComparison.OrdinalIgnoreCase);
return value.Equals(core, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Проверяет, проходит ли один target-юнит один RelationshipFilter.
/// Единая точка истины для UnitRelationshipMatcher и GetRelatedUnitNamesAsync.
/// Учитывает IsInverse. Не учитывает IsFullMatch (это ответственность вызывающего кода).
/// </summary>
internal static bool TargetPassesFilter(
IReadOnlyList<UnitInValue> unitValues,
JobRelationshipFilter rf)
{
var normalizedMask = NormalizeLikeMask(rf.ValueMask?.Trim() ?? string.Empty);
if (string.IsNullOrEmpty(normalizedMask))
return true;
var matchingValues = unitValues
.Where(uv => uv.FieldId == rf.FieldId && uv.Value?.Value != null)
.ToList();
bool hasMatch;
if (!matchingValues.Any())
{
hasMatch = rf.IsInverse;
}
else
{
hasMatch = matchingValues.Any(uv => MatchesLikeMask(uv.Value!.Value!, normalizedMask));
if (rf.IsInverse)
hasMatch = !hasMatch;
}
return hasMatch;
}
}

View File

@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService.Matchers;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Core.Services.UnitService.Interfaces;
@@ -224,345 +225,6 @@ internal class UnitFilterService : IUnitFilterService
}
private async Task<Job?> LoadJobWithFiltersAsync(Guid jobId, CancellationToken cancellationToken = default)
{
return await jobRepository
@@ -575,7 +237,8 @@ internal class UnitFilterService : IUnitFilterService
}
public async Task<List<string>> GetRelatedUnitNamesAsync(Guid jobId, Guid unitId, CancellationToken cancellationToken = default)
public async Task<List<string>> GetRelatedUnitNamesAsync(
Guid jobId, Guid unitId, CancellationToken cancellationToken = default)
{
logger.LogDebug("Начало GetRelatedUnitNamesAsync. JobId: {JobId}, UnitId: {UnitId}", jobId, unitId);
@@ -590,71 +253,47 @@ internal class UnitFilterService : IUnitFilterService
throw new ArgumentException($"Job {jobId} не найден.", nameof(jobId));
}
logger.LogDebug("Найден Job: {JobName}. Количество UnitFilters: {FilterCount}", job.Name, job.UnitFilters.Count());
// Единая точка загрузки связей
var allRelatedUnitIds = await unitInUnitRepository
.GetRelatedUnitIdsAsync(unitId, cancellationToken);
if (!allRelatedUnitIds.Any())
return new List<string>();
// Загружаем значения всех связанных юнитов одним запросом
var allUnitValues = await unitInValueRepository.GetByUnitIdsAsync(allRelatedUnitIds);
var valuesByUnit = allUnitValues
.GroupBy(uv => uv.UnitId)
.ToDictionary(g => g.Key, g => g.ToList());
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var filter in job.UnitFilters)
{
if (!filter.RelationshipFilters.Any()) continue;
logger.LogDebug("Обработка UnitFilter.Id {FilterId}. Количество RelationshipFilters: {RelFilterCount}", filter.Id, filter.RelationshipFilters.Count());
// Получить все связи для юнита
var parentLinks = await unitInUnitRepository.GetByChildIdAsync(unitId);
var childLinks = await unitInUnitRepository.GetByParentIdAsync(unitId);
// Собрать все UnitId, участвующие в связях
var allRelatedUnitIds = parentLinks
.Select(l => l.ParentUnitId)
.Concat(childLinks.Select(l => l.ChildUnitId))
.Distinct()
var relFilters = filter.RelationshipFilters
.Where(rf => !string.IsNullOrWhiteSpace(rf.ValueMask?.Trim()))
.ToList();
if (!allRelatedUnitIds.Any()) continue;
if (!relFilters.Any()) continue;
// Получить значения для всех связанных юнитов
var allUnitValues = await unitInValueRepository.GetByUnitIdsAsync(allRelatedUnitIds);
// Сгруппировать значения по UnitId
var valuesByUnit = allUnitValues
.GroupBy(uv => uv.UnitId)
.ToDictionary(g => g.Key, g => g.ToList());
// Найти UnitId, которые проходят все RelationshipFilters
var matchingUnitIds = new HashSet<Guid>();
// Проверяем каждый связанный юнит через единую точку проверки
var passedUnitIds = new HashSet<Guid>();
foreach (var relatedUnitId in allRelatedUnitIds)
{
bool passesAllFilters = filter.RelationshipFilters.All(rf =>
{
var values = valuesByUnit.GetValueOrDefault(relatedUnitId, new List<UnitInValue>());
var unitValues = valuesByUnit.GetValueOrDefault(relatedUnitId, new List<UnitInValue>());
var matchingValues = values
.Where(uv => uv.FieldId == rf.FieldId && uv.Value?.Value != null)
.ToList();
// Все фильтры должны пройти (AND между фильтрами в рамках одного UnitFilter)
bool passesAll = relFilters.All(rf =>
UnitRelationshipMatcher.TargetPassesFilter(unitValues, rf));
if (!matchingValues.Any())
{
return rf.IsInverse;
}
var hasMatch = matchingValues.Any(uv => uv.Value!.Value!.Contains(rf.ValueMask.Trim('%'), StringComparison.OrdinalIgnoreCase));
if (rf.IsInverse)
hasMatch = !hasMatch;
return hasMatch;
});
if (passesAllFilters)
matchingUnitIds.Add(relatedUnitId);
if (passesAll)
passedUnitIds.Add(relatedUnitId);
}
if (matchingUnitIds.Any())
if (passedUnitIds.Any())
{
// Используем кэширующий сервис вместо прямого запроса к БД
var cachedUnits = await unitService.GetWithCachingAsync(matchingUnitIds);
var cachedUnits = await unitService.GetWithCachingAsync(passedUnitIds);
var names = cachedUnits.Values
.Select(u => u.Name)
.Where(n => !string.IsNullOrEmpty(n));

View File

@@ -27,38 +27,14 @@ namespace PARR.DAL.Repositories.Unit
}
public Task<List<UnitInUnit>> GetByParentIdAsync(Guid parentId)
public async Task<List<Guid>> GetRelatedUnitIdsAsync(Guid unitId, CancellationToken ct = default)
{
return dataContext.UnitInUnits
.Where(u => u.ParentUnitId == parentId)
.ToListAsync();
}
public Task<List<UnitInUnit>> GetByChildIdAsync(Guid childId)
{
return dataContext.UnitInUnits
.Where(u => u.ChildUnitId == childId)
.ToListAsync();
}
public async Task<List<UnitInUnit>> GetParentLinksByChildIdsAsync(IEnumerable<Guid> childUnitIds)
{
var set = childUnitIds.ToHashSet();
return await dataContext.UnitInUnits
return await Get()
.AsNoTracking()
.Where(uinu => set.Contains(uinu.ChildUnitId))
.ToListAsync();
}
public async Task<List<UnitInUnit>> GetChildLinksByParentIdsAsync(IEnumerable<Guid> parentUnitIds)
{
var set = parentUnitIds.ToHashSet();
return await dataContext.UnitInUnits
.AsNoTracking()
.Where(uinu => set.Contains(uinu.ParentUnitId))
.ToListAsync();
.Where(link => link.ChildUnitId == unitId || link.ParentUnitId == unitId)
.Select(link => link.ChildUnitId == unitId ? link.ParentUnitId : link.ChildUnitId)
.Distinct()
.ToListAsync(ct);
}
}
}

View File

@@ -0,0 +1,16 @@
namespace PARR.TemplateMatcher.Exceptions
{
/// <summary>
/// Контролируемый ранний выход из синхронизации без ошибки.
/// Например: нет данных для обработки, фильтры не вернули юнитов.
/// </summary>
public class SyncEarlyExitException : Exception
{
public string Reason { get; }
public SyncEarlyExitException(string reason) : base(reason)
{
Reason = reason;
}
}
}

View File

@@ -18,15 +18,17 @@ internal class BuildGroupsStage : IGroupedSyncStage
public async Task<GroupedSyncContext> ExecuteAsync(GroupedSyncContext context, CancellationToken ct = default)
{
var groups = await _builder.BuildAsync(context.ReverseMapping, context.JobGroup, context.MaxJob);
var templateGroups = await _builder.BuildAsync(
context.ReverseMapping,
context.JobGroup,
context.MaxJob,
context.UnitNames,
ct);
if (!groups.Any())
throw new GroupedSyncEarlyExitException("Нет данных после построения групп");
context.TemplateGroups = groups;
context.TemplateGroups = templateGroups;
_logger.LogDebug("JobGroup '{JobGroupName}' ({JobGroupId}): построено {Count} групп",
context.JobGroupName, context.JobGroupId, groups.Count);
context.JobGroupName, context.JobGroupId, templateGroups.Count);
return context;
}

View File

@@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Services.UnitFilterService;
using PARR.TemplateMatcher.Exceptions;
using PARR.TemplateMatcher.Services.GroupedSync;
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
@@ -22,7 +23,7 @@ internal class FilterUnitsStage : IGroupedSyncStage
var result = await _filterService.GetUnitsByJobFilterAsync(context.MaxJob.Id, null, ct);
if (result == null || !result.Any())
throw new GroupedSyncEarlyExitException("Фильтры не дали Unit'ов с подходящими связями");
throw new SyncEarlyExitException("Фильтры не дали Unit'ов с подходящими связями");
context.FilteredUnits = result.ToList();
context.UnitNames = result.ToDictionary(u => u.Id, u => u.Name);

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using PARR.TemplateMatcher.Exceptions;
using PARR.TemplateMatcher.Services.GroupedSync;
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
@@ -21,7 +22,7 @@ internal class GroupFilterStage : IGroupedSyncStage
var finalFiltered = await _groupedFilter.FilterAsync(context.FilteredUnits, context.JobGroup);
if (!finalFiltered.Any())
throw new GroupedSyncEarlyExitException("Нет юнитов после групповой фильтрации");
throw new SyncEarlyExitException("Нет юнитов после групповой фильтрации");
context.FilteredUnits = finalFiltered;

View File

@@ -22,6 +22,9 @@ public class GroupedSyncContext
public List<GroupedTemplateGroup> TemplateGroups { get; set; } = new();
public HashSet<(Guid JobId, Guid UnitId, int Index)> ExpectedTemplateKeys { get; set; } = new();
// Режим только для чтения — без записи в БД и отправки в MQ
public bool DryRun { get; set; } = false;
/// <summary>
/// Имена юнитов для логирования. Заполняется на этапе фильтрации.
/// </summary>

View File

@@ -1,16 +0,0 @@
namespace PARR.TemplateMatcher.Services.GroupedSync
{
/// <summary>
/// Штатное прерывание пайплайна (нет данных после этапа).
/// Не является ошибкой — оркестратор перехватывает и логирует как нормальное завершение.
/// </summary>
public class GroupedSyncEarlyExitException : Exception
{
public string Reason { get; }
public GroupedSyncEarlyExitException(string reason) : base(reason)
{
Reason = reason;
}
}
}

View File

@@ -16,24 +16,28 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
private readonly IUnitInValueRepository unitInValueRepository;
private readonly IUnitFieldRepository unitFieldRepository;
private readonly IShortcodesService shortcodesService;
private readonly IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository;
public GroupedTemplateBuilder(
ILogger<GroupedTemplateBuilder> logger,
IUnitInValueRepository unitInValueRepository,
IUnitFieldRepository unitFieldRepository,
IShortcodesService shortcodesService
IShortcodesService shortcodesService,
IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository
)
{
this.logger = logger;
this.unitInValueRepository = unitInValueRepository;
this.unitFieldRepository = unitFieldRepository;
this.shortcodesService = shortcodesService;
this.regionalEkPtkGroupRepository = regionalEkPtkGroupRepository;
}
public async Task<List<GroupedTemplateGroup>> BuildAsync(
Dictionary<Guid, List<Guid>> initialReverseMapping,
JobGroup jobGroup,
Job maxJob,
Dictionary<Guid, string> unitNames,
CancellationToken ct = default)
{
logger.LogDebug("Начало построения структуры групп для JobGroup {JobGroupId}.", jobGroup.Id);
@@ -42,7 +46,6 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
return new List<GroupedTemplateGroup>();
// 1. Определяем стратегию внутренней группировки
// Если IsGroupByResponsible != true, используем WorkGroupMask через ShortcodesService
bool useWorkGroupMask = jobGroup.IsGroupByResponsible != true;
logger.LogDebug("Стратегия внутренней группировки: {Strategy}",
@@ -102,22 +105,50 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
if (useWorkGroupMask)
{
// Используем ShortcodesService для получения финальных значений WorkGroupMask
// Определяем, нужно ли выполнять фильтрацию по списку рабочих групп ПТК.
// Если маска содержит тег с "_в_ЗО_РГ", фильтрация не выполняется.
var skipRegionalFilter = maxJob.WorkGroupMask.Contains("_в_ЗО_РГ", StringComparison.OrdinalIgnoreCase);
HashSet<string>? allowedWorkGroupSet = null;
if (!skipRegionalFilter)
{
// Загружаем разрешённые значения из regionalEkPtkGroupRepository
var allowedWorkGroupValues = await regionalEkPtkGroupRepository.Get()
.AsNoTracking()
.Include(g => g.FieldValue)
.Where(g => g.FieldValue != null && g.FieldValue.Value != null)
.Select(g => g.FieldValue!.Value!)
.ToListAsync(ct);
allowedWorkGroupSet = new HashSet<string>(allowedWorkGroupValues, StringComparer.OrdinalIgnoreCase);
logger.LogDebug("Загружено {Count} разрешённых значений рабочих групп из RegionalEkPtkGroup.", allowedWorkGroupSet.Count);
}
else
{
logger.LogDebug("Маска содержит тег с '_в_ЗО_РГ'. Фильтрация по списку рабочих групп ПТК пропущена.");
}
// Применяем WorkGroupMask для каждого юнита отдельно
unitIdToGroupingValueMap = new Dictionary<Guid, string>();
foreach (var potentialUnitId in reverseMapping.Keys)
{
var relatedUnitIds = reverseMapping[potentialUnitId].Select(e => e.UnitId).Distinct().ToList();
var relatedUnitIds = reverseMapping[potentialUnitId]
.Select(e => e.UnitId)
.Distinct()
.ToList();
foreach (var relatedUnitId in relatedUnitIds)
{
// Создаем временный Template для применения шорткодов
// Формируем шаблон с одним связанным юнитом
var tempTemplate = new Template
{
Id = Guid.NewGuid(),
Name = "temp",
JobId = maxJob.Id,
UnitId = potentialUnitId, // Родительский юнит шаблона
UnitId = potentialUnitId,
Job = maxJob,
UnitsInTemplate = new List<UnitsInTemplate>
{
@@ -130,6 +161,27 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
tempTemplate,
nameof(GroupedTemplateBuilder));
if (string.IsNullOrEmpty(workGroupValue))
{
logger.LogDebug(
"Юнит {UnitId} исключён: маска вернула пустую строку.",
relatedUnitId);
continue;
}
// Фильтрация по списку рабочих групп ПТК выполняется только если не используется тег с "_в_ЗО_РГ"
if (!skipRegionalFilter && !allowedWorkGroupSet!.Contains(workGroupValue))
{
logger.LogDebug( // Изменено с LogDebug на LogInformation для тестирования
"[FILTER] Юнит {UnitId} ИСКЛЮЧЁН: рабочая группа '{WorkGroup}' не найдена в списке разрешённых ({AllowedCount} значений).",
relatedUnitId, workGroupValue, allowedWorkGroupSet!.Count);
continue;
}
logger.LogDebug( // Добавляем лог для успешного прохождения
"[FILTER] Юнит {UnitId} ПРОШЁЛ: рабочая группа '{WorkGroup}' для PotentialUnit {PotentialUnitId}.",
relatedUnitId, workGroupValue, potentialUnitId);
unitIdToGroupingValueMap[relatedUnitId] = workGroupValue;
}
}
@@ -163,7 +215,18 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
var potentialUnitId = kvp.Key;
var unitsInTemplateForThisPotentialUnitId = kvp.Value;
var innerGroupedUnits = unitsInTemplateForThisPotentialUnitId
// Фильтруем записи: оставляем только те, которые прошли проверку
var filteredUnits = unitsInTemplateForThisPotentialUnitId
.Where(entry => unitIdToGroupingValueMap.ContainsKey(entry.UnitId))
.ToList();
if (!filteredUnits.Any())
{
logger.LogDebug("PotentialUnitId {PotentialUnitId} исключён: нет юнитов после фильтрации.", potentialUnitId);
continue;
}
var innerGroupedUnits = filteredUnits
.GroupBy(entry => unitIdToGroupingValueMap.GetValueOrDefault(entry.UnitId, "Нет данных"))
.OrderBy(g => g.Key, StringComparer.Ordinal)
.ToList();
@@ -179,21 +242,23 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
var unitsInInnerGroup = innerGroup.ToList();
var splitSubGroups = unitsInInnerGroup
// Сортируем по имени юнита, потом по UnitFieldValueId
var sortedUnitsInInnerGroup = unitsInInnerGroup
.OrderBy(e => unitNames.GetValueOrDefault(e.UnitId, e.UnitId.ToString()))
.ThenBy(e => e.UnitFieldValueId)
.ToList();
var splitSubGroups = sortedUnitsInInnerGroup
.Select((entry, index) => new { entry, groupIndex = index / maxValueForSplitting })
.GroupBy(x => x.groupIndex)
.Select(g => g.Select(x => x.entry).ToList())
.ToList();
// ВАЖНО: добавляем подгруппы в subGroups
foreach (var subGroupEntries in splitSubGroups)
{
var sortedEntries = subGroupEntries
.OrderBy(e => e.UnitId)
.ThenBy(e => e.UnitFieldValueId)
.ToList();
subGroups.Add(new GroupedTemplateSubGroup(
Entries: sortedEntries,
Entries: subGroupEntries,
InnerGroupName: innerGroupName,
GlobalIndex: globalIndex
));

View File

@@ -9,19 +9,13 @@ internal class GroupedTemplateUnitFilter : IGroupedTemplateUnitFilter
{
private readonly ILogger<GroupedTemplateUnitFilter> logger;
private readonly IUnitInValueRepository unitInValueRepository;
private readonly IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository;
private readonly IUnitFieldRepository unitFieldRepository;
public GroupedTemplateUnitFilter(
ILogger<GroupedTemplateUnitFilter> logger,
IUnitInValueRepository unitInValueRepository,
IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository,
IUnitFieldRepository unitFieldRepository)
IUnitInValueRepository unitInValueRepository)
{
this.logger = logger;
this.unitInValueRepository = unitInValueRepository;
this.regionalEkPtkGroupRepository = regionalEkPtkGroupRepository;
this.unitFieldRepository = unitFieldRepository;
}
public async Task<List<UnitFilterResultDto>> FilterAsync(
@@ -47,53 +41,24 @@ internal class GroupedTemplateUnitFilter : IGroupedTemplateUnitFilter
var groupingFieldId = jobGroup.GroupingUnitFieldId.Value;
logger.LogDebug("Фильтрация по GroupingUnitFieldId (FieldId={FieldId}).", groupingFieldId);
// 2. Фильтрация по GroupingUnitFieldId
// 2. Загружаем значения поля группировки для всех юнитов
var allUnitIds = unitsList.Select(u => u.Id).ToList();
var groupingValues = await unitInValueRepository.GetByUnitIdsAndFieldIdsAsync(allUnitIds, new HashSet<Guid> { groupingFieldId });
var groupingValues = await unitInValueRepository.GetByUnitIdsAndFieldIdsAsync(
allUnitIds, new HashSet<Guid> { groupingFieldId }, ct);
// 3. Определяем юниты, у которых есть непустое значение поля группировки
var validUnitIdsAfterGrouping = groupingValues
.Where(uv => uv.Value != null && !string.IsNullOrEmpty(uv.Value.Value))
.Select(uv => uv.UnitId)
.ToHashSet();
// 4. Фильтруем исходный список
var filteredByGrouping = unitsList
.Where(u => validUnitIdsAfterGrouping.Contains(u.Id))
.ToList();
logger.LogDebug("После фильтрации по GroupingUnitFieldId осталось {Count} юнитов.", filteredByGrouping.Count);
if (!filteredByGrouping.Any())
{
return filteredByGrouping;
}
// 3. Фильтрация по РАБОЧАЯ_ГР_ОТВ_ЗАК
var workGroupField = await unitFieldRepository.GetByAihitNameAsync("РАБОЧАЯ_ГР_ОТВ_ЗАК")
?? throw new InvalidOperationException("Поле 'РАБОЧАЯ_ГР_ОТВ_ЗАК' не найдено в справочнике полей.");
var workGroupFieldId = workGroupField.Id;
logger.LogDebug("Фильтрация по полю 'РАБОЧАЯ_ГР_ОТВ_ЗАК' (FieldId={FieldId}).", workGroupFieldId);
var filteredUnitIds = filteredByGrouping.Select(u => u.Id).ToList();
var workGroupValues = await unitInValueRepository.GetByUnitIdsAndFieldIdsAsync(filteredUnitIds, new HashSet<Guid> { workGroupFieldId });
var allowedValueIds = regionalEkPtkGroupRepository.Get()
.Select(g => g.FieldValueId)
.ToHashSet();
logger.LogDebug("Найдено {Count} разрешенных значений для поля 'РАБОЧАЯ_ГР_ОТВ_ЗАК'.", allowedValueIds.Count);
var validUnitIdsAfterWorkGroup = workGroupValues
.Where(uv => uv.Value != null && allowedValueIds.Contains(uv.Value.Id))
.Select(uv => uv.UnitId)
.ToHashSet();
var finalFiltered = filteredByGrouping
.Where(u => validUnitIdsAfterWorkGroup.Contains(u.Id))
.ToList();
logger.LogDebug("После фильтрации по 'РАБОЧАЯ_ГР_ОТВ_ЗАК' осталось {Count} юнитов.", finalFiltered.Count);
return finalFiltered;
return filteredByGrouping;
}
}

View File

@@ -15,5 +15,6 @@ public interface IGroupedTemplateBuilder
Dictionary<Guid, List<Guid>> initialReverseMapping,
JobGroup jobGroup,
Job maxJob,
Dictionary<Guid, string> unitNames,
CancellationToken ct = default);
}

View File

@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.TemplateMatcher.Exceptions;
using PARR.TemplateMatcher.Services.GroupedSync;
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
@@ -32,7 +33,7 @@ internal class LoadJobGroupStage : IGroupedSyncStage
.FirstOrDefaultAsync(jg => jg.Id == context.JobGroupId, ct);
if (jobGroup == null || jobGroup.Jobs == null || !jobGroup.Jobs.Any())
throw new GroupedSyncEarlyExitException("JobGroup не найден или пуст");
throw new SyncEarlyExitException("JobGroup не найден или пуст");
var jobsInGroup = jobGroup.Jobs.ToList();
var maxJob = jobsInGroup
@@ -41,7 +42,7 @@ internal class LoadJobGroupStage : IGroupedSyncStage
.FirstOrDefault();
if (maxJob == null)
throw new GroupedSyncEarlyExitException("Не найден Job с MaxValueRelationships");
throw new SyncEarlyExitException("Не найден Job с MaxValueRelationships");
context.JobGroup = jobGroup;
context.JobGroupName = jobGroup.GroupName;

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using PARR.TemplateMatcher.Exceptions;
using PARR.TemplateMatcher.Services.GroupedSync;
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
@@ -21,7 +22,7 @@ internal class ResolveConflictsStage : IGroupedSyncStage
var mapping = await _conflictMapper.BuildMappingAsync(context.FilteredUnits, context.MaxJob, ct);
if (!mapping.Any())
throw new GroupedSyncEarlyExitException("Нет связей после разрешения конфликтов");
throw new SyncEarlyExitException("Нет связей после разрешения конфликтов");
context.ReverseMapping = mapping;

View File

@@ -3,6 +3,7 @@ using PARR.Core.Services.MatchingStatusService;
using PARR.Domain.Cache.Models;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Enums;
using PARR.TemplateMatcher.Exceptions;
using PARR.TemplateMatcher.Services.GroupedSync;
using PARR.TemplateMatcher.Services.Implementations.GroupedSync;
using PARR.TemplateMatcher.Services.Interfaces;
@@ -17,6 +18,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
private readonly IMatchingStatusService _matchingStatusService;
private readonly ILogger<GroupedTemplateSynchronizer> _logger;
public GroupedTemplateSynchronizer(
IEnumerable<IGroupedSyncStage> readStages,
IEnumerable<IGroupedSyncWriteStage> writeStages,
@@ -30,9 +32,10 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
_logger = logger;
}
public async Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator)
public async Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default)
{
_logger.LogInformation("Начало синхронизации шаблонов для JobGroup {JobGroupId}", jobGroupId);
_logger.LogInformation("Начало синхронизации шаблонов для JobGroup {JobGroupId} (DryRun={DryRun})", jobGroupId, dryRun);
var existingStatus = await _matchingStatusService.GetStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
if (existingStatus.DetailsJobGroups?.Count > 0)
@@ -41,14 +44,20 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
return;
}
await SetStatusAsync(jobGroupId, "Начало синхронизации");
await SetStatusAsync(jobGroupId, dryRun ? "DryRun: Начало анализа" : "Начало синхронизации");
var totalSw = Stopwatch.StartNew();
try
{
var context = new GroupedSyncContext { JobGroupId = jobGroupId, Initiator = initiator };
var context = new GroupedSyncContext
{
JobGroupId = jobGroupId,
Initiator = initiator,
DryRun = dryRun
};
// Read-этапы выполняются всегда
foreach (var stage in _readStages)
{
var stageSw = Stopwatch.StartNew();
@@ -58,25 +67,36 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
context.JobGroupName, jobGroupId, stage.StageName, stageSw.ElapsedMilliseconds);
}
foreach (var stage in _writeStages)
// Подробный отчёт по результатам read-этапов
PrintDryRunReport(context);
// Write-этапы пропускаем при DryRun
if (!dryRun)
{
var stageSw = Stopwatch.StartNew();
await stage.ExecuteAsync(context);
stageSw.Stop();
_logger.LogDebug("[Perf] JobGroup '{JobGroupName}' ({JobGroupId}) | Этап: {Stage} | Время: {Ms} мс",
context.JobGroupName, jobGroupId, stage.StageName, stageSw.ElapsedMilliseconds);
foreach (var stage in _writeStages)
{
var stageSw = Stopwatch.StartNew();
await stage.ExecuteAsync(context);
stageSw.Stop();
_logger.LogDebug("[Perf] JobGroup '{JobGroupName}' ({JobGroupId}) | Этап: {Stage} | Время: {Ms} мс",
context.JobGroupName, jobGroupId, stage.StageName, stageSw.ElapsedMilliseconds);
}
await SetStatusAsync(jobGroupId, "Синхронизация завершена успешно");
await _matchingStatusService.DeleteMatchingStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
}
else
{
_logger.LogInformation("[DryRun] Write-этапы пропущены. Изменения в БД и MQ не выполнены.");
await SetStatusAsync(jobGroupId, "DryRun: Анализ завершён без изменений");
await _matchingStatusService.DeleteMatchingStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
}
totalSw.Stop();
_logger.LogInformation("[Perf] JobGroup '{JobGroupName}' ({JobGroupId}) | ИТОГО: {TotalMs} мс",
context.JobGroupName, jobGroupId, totalSw.ElapsedMilliseconds);
await SetStatusAsync(jobGroupId, "Синхронизация завершена успешно");
await _matchingStatusService.DeleteMatchingStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
_logger.LogInformation("Синхронизация шаблонов завершена для JobGroup '{JobGroupName}' ({JobGroupId})",
context.JobGroupName, jobGroupId);
}
catch (GroupedSyncEarlyExitException ex)
catch (SyncEarlyExitException ex)
{
totalSw.Stop();
_logger.LogInformation("JobGroup {JobGroupId}: {Reason} ({ElapsedMs} мс)",
@@ -94,18 +114,68 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
}
}
public Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator)
private void PrintDryRunReport(GroupedSyncContext context)
{
_logger.LogInformation("========== [DryRun] ОТЧЁТ по JobGroup '{JobGroupName}' ({JobGroupId}) ==========",
context.JobGroupName, context.JobGroupId);
_logger.LogInformation("[DryRun] Отфильтровано юнитов: {Count}", context.FilteredUnits.Count);
_logger.LogInformation("[DryRun] Разрешено конфликтов (potentialUnits): {Count}", context.ReverseMapping.Count);
_logger.LogInformation("[DryRun] Сформировано групп: {Count}", context.TemplateGroups.Count);
int totalSubGroups = 0;
int totalUnitsInTemplates = 0;
foreach (var group in context.TemplateGroups.OrderBy(g => g.PotentialUnitId))
{
_logger.LogInformation(
"[DryRun] PotentialUnit {Unit}: {SubGroupCount} подгрупп",
context.FormatUnit(group.PotentialUnitId),
group.SubGroups.Count);
foreach (var subGroup in group.SubGroups.OrderBy(s => s.GlobalIndex))
{
_logger.LogInformation(
"[DryRun] Index={Index}, группа='{Group}', экземпляров: {Count}",
subGroup.GlobalIndex,
subGroup.InnerGroupName,
subGroup.Entries.Count);
foreach (var entry in subGroup.Entries)
{
_logger.LogDebug(
"[DryRun] - {Unit} (ValueId: {ValueId})",
context.FormatUnit(entry.UnitId),
entry.UnitFieldValueId);
}
totalSubGroups++;
totalUnitsInTemplates += subGroup.Entries.Count;
}
}
_logger.LogInformation("[DryRun] ИТОГО: {GroupCount} групп, {SubGroupCount} подгрупп (=шаблонов), {UnitCount} экземпляров в шаблонах",
context.TemplateGroups.Count, totalSubGroups, totalUnitsInTemplates);
_logger.LogInformation("========== [DryRun] КОНЕЦ ОТЧЁТА ==========");
}
public Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default)
{
_logger.LogWarning("GroupedTemplateSynchronizer: SyncTemplatesForJob вызван для JobId {JobId}. Это не поддерживаемая операция.", jobId);
return Task.CompletedTask;
}
public Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator)
public Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, CancellationToken ct = default)
{
_logger.LogWarning("GroupedTemplateSynchronizer: UpdateTemplatesForJob вызван для JobId {JobId}. Это не поддерживаемая операция.", jobId);
return Task.CompletedTask;
}
private async Task SetStatusAsync(Guid jobGroupId, string comment)
{
var status = new MatchingStatusItemDto

View File

@@ -3,18 +3,14 @@ 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.Core.Services.UnitFilterService;
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.Domain.Settings;
using PARR.TemplateMatcher.Constants;
using PARR.TemplateMatcher.Exceptions;
using PARR.TemplateMatcher.Services.Interfaces;
using PARR.TemplateMatcher.Services.SimpleSync;
using PARR.TemplateMatcher.Settings;
@@ -38,10 +34,8 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
private readonly ITemplateMqPublisher _templateMqPublisher;
private readonly IMatchingStatusService _matchingStatusService;
private readonly SettingsFromDb _settingsFromDb;
private readonly IOptions<TemplateSettings> _templateSettings;
private readonly IUnitFieldRepository _unitFieldService;
private readonly IUnitInValueRepository _unitInValueService;
private readonly IUnitRepository _unitRepository;
private readonly IUnusedTemplatesSyncService _unusedTemplatesSyncService;
public SimpleTemplateSynchronizer(
IEnumerable<ISimpleSyncStage> readStages,
@@ -55,33 +49,28 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
IMatchingStatusService matchingStatusService,
SettingsFromDb settingsFromDb,
IOptions<TemplateSettings> templateSettings,
IUnitFieldRepository unitFieldService,
IUnitInValueRepository unitInValueService,
IUnitRepository unitRepository
IUnusedTemplatesSyncService unusedTemplatesSyncService
)
{
this._readStages = readStages;
this._writeStages = writeStages;
this._logger = logger;
this._unitFilterService = unitFilterService;
this._templateService = templateService;
this._jobService = jobService;
this._templateNameNormalizer = templateNameNormalizer;
this._templateMqPublisher = templateMqPublisher;
this._matchingStatusService = matchingStatusService;
this._settingsFromDb = settingsFromDb;
this._templateSettings = templateSettings;
this._unitFieldService = unitFieldService;
this._unitInValueService = unitInValueService;
this._unitRepository = unitRepository;
_readStages = readStages;
_writeStages = writeStages;
_logger = logger;
_unitFilterService = unitFilterService;
_templateService = templateService;
_jobService = jobService;
_templateNameNormalizer = templateNameNormalizer;
_templateMqPublisher = templateMqPublisher;
_matchingStatusService = matchingStatusService;
_settingsFromDb = settingsFromDb;
_unusedTemplatesSyncService = unusedTemplatesSyncService;
}
public async Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator)
public async Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default)
{
if (jobId == _settingsFromDb.JobIdForUnusedTemplates)
{
_logger.LogInformation("Обработка синхронизации для Job неиспользуемых шаблонов '{JobId}'", jobId);
await SyncUnusedTemplatesAsync(jobId, initiator);
await _unusedTemplatesSyncService.SyncAsync(jobId, initiator, dryRun);
return;
}
@@ -120,42 +109,107 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
context.JobName, jobId, stage.StageName, stageSw.ElapsedMilliseconds);
}
foreach (var stage in _writeStages)
// Подробный отчёт по результатам read-этапов
PrintDryRunReport(context);
if (!dryRun)
{
var stageSw = Stopwatch.StartNew();
await stage.ExecuteAsync(context);
stageSw.Stop();
_logger.LogDebug("[Perf] Job '{JobName}' ({JobId}) | Этап: {Stage} | Время: {Ms} мс",
context.JobName, jobId, stage.StageName, stageSw.ElapsedMilliseconds);
foreach (var stage in _writeStages)
{
var stageSw = Stopwatch.StartNew();
await stage.ExecuteAsync(context);
stageSw.Stop();
_logger.LogDebug("[Perf] Job '{JobName}' ({JobId}) | Этап: {Stage} | Время: {Ms} мс",
context.JobName, jobId, stage.StageName, stageSw.ElapsedMilliseconds);
}
await SetStatusAsync(jobId, "Синхронизация завершена успешно");
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
_logger.LogInformation("Синхронизация шаблонов завершена для Job '{JobName}' ({JobId})", context.JobName, jobId);
}
else
{
_logger.LogInformation("[DryRun] Write-этапы пропущены. Изменения в БД и MQ не выполнены.");
await SetStatusAsync(jobId, "DryRun: Анализ завершён без изменений");
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
}
totalSw.Stop();
_logger.LogInformation("[Perf] Job '{JobName}' ({JobId}) | ИТОГО: {TotalMs} мс",
context.JobName, jobId, totalSw.ElapsedMilliseconds);
await UpdateMatchingStatusAsync(jobId, "Синхронизация завершена успешно");
}
catch (SyncEarlyExitException ex)
{
totalSw.Stop();
_logger.LogInformation("Job {JobId}: {Reason} ({ElapsedMs} мс)",
jobId, ex.Reason, totalSw.ElapsedMilliseconds);
await SetStatusAsync(jobId, ex.Reason);
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
_logger.LogInformation("Синхронизация шаблонов завершена для Job '{JobName}' ({JobId})",
context.JobName, jobId);
}
catch (Exception ex)
{
totalSw.Stop();
_logger.LogError(ex, "Ошибка при синхронизации Job '{JobName}' ({JobId}) через {ElapsedMs} мс",
string.Empty, jobId, totalSw.ElapsedMilliseconds);
await UpdateMatchingStatusAsync(jobId, $"Ошибка: {ex.Message}");
context.JobName ?? string.Empty, jobId, totalSw.ElapsedMilliseconds);
await SetStatusAsync(jobId, $"Ошибка: {ex.Message}");
throw;
}
}
public async Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator)
private void PrintDryRunReport(SimpleSyncContext context)
{
_logger.LogWarning("SimpleTemplateSynchronizer: SyncTemplatesForJobGroup вызван для JobGroup {JobGroupId}. Это не поддерживаемая операция.", jobGroupId);
_logger.LogInformation("========== [DryRun] ОТЧЁТ по Job '{JobName}' ({JobId}) ==========",
context.JobName, context.JobId);
_logger.LogInformation("[DryRun] Отфильтровано юнитов: {Count}", context.FilteredUnitIds.Count);
_logger.LogInformation("[DryRun] Существующих активных шаблонов: {Count}", context.ExistingUsedTemplates.Count);
_logger.LogInformation("[DryRun] Новых юнитов (требуют аллокации): {Count}", context.NewUnitIds.Count);
_logger.LogInformation("[DryRun] Шаблонов для деактивации (Unused): {Count}", context.UnusedTemplates.Count);
_logger.LogInformation("[DryRun] Шаблонов для переименования: {Count}", context.TemplatesToRename.Count);
if (context.NewUnitIds.Any())
{
_logger.LogDebug("[DryRun] --- Новые юниты (будут созданы шаблоны) ---");
foreach (var unitId in context.NewUnitIds)
{
_logger.LogDebug("[DryRun] + {Unit}", context.FormatUnit(unitId));
}
}
if (context.UnusedTemplates.Any())
{
_logger.LogDebug("[DryRun] --- Шаблоны для деактивации ---");
foreach (var template in context.UnusedTemplates)
{
_logger.LogDebug("[DryRun] - {TemplateId} (Unit: {Unit}, Name: '{Name}')",
template.Id, context.FormatUnit(template.UnitId), template.Name);
}
}
if (context.TemplatesToRename.Any())
{
_logger.LogDebug("[DryRun] --- Шаблоны для переименования ---");
foreach (var (template, expectedName) in context.TemplatesToRename)
{
_logger.LogDebug("[DryRun] ~ {TemplateId} (Unit: {Unit}): '{OldName}' -> '{NewName}'",
template.Id, context.FormatUnit(template.UnitId), template.Name, expectedName);
}
}
_logger.LogInformation("========== [DryRun] КОНЕЦ ОТЧЁТА ==========");
}
public Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default)
{
_logger.LogWarning(
"SimpleTemplateSynchronizer: SyncTemplatesForJobGroup вызван для JobGroup {JobGroupId} (DryRun={DryRun}). Это не поддерживаемая операция.",
jobGroupId, dryRun);
return Task.CompletedTask;
}
public async Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator)
public async Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, CancellationToken ct = default)
{
_logger.LogDebug("Обновление шаблонов для Job {JobId}", jobId);
@@ -195,7 +249,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
if (job == null)
{
_logger.LogWarning("Job {JobId} не найден.", jobId);
await UpdateMatchingStatusAsync(jobId, "Job не найден");
await SetStatusAsync(jobId, "Job не найден");
return;
}
@@ -204,7 +258,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
if (filteredUnits == null || !filteredUnits.Any())
{
_logger.LogInformation("Для Job {JobId} фильтры не дали Unit'ов.", jobId);
await UpdateMatchingStatusAsync(jobId, "Нет Unit'ов — обновление не требуется");
await SetStatusAsync(jobId, "Нет Unit'ов — обновление не требуется");
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
return;
}
@@ -265,306 +319,20 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
}
}
await UpdateMatchingStatusAsync(jobId, "Обновление завершено");
await SetStatusAsync(jobId, "Обновление завершено");
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
_logger.LogInformation("Обновление шаблонов завершено для Job {JobId}.", jobId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при обновлении Job {JobId}", jobId);
await UpdateMatchingStatusAsync(jobId, $"Ошибка: {ex.Message}");
await SetStatusAsync(jobId, $"Ошибка: {ex.Message}");
throw;
}
}
private async Task SyncUnusedTemplatesAsync(Guid unusedJobId, HistoryInitiator initiator, 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 initialStatus = new MatchingStatusItemDto
{
DateStart = DateTimeOffset.UtcNow,
Action = TemplateMatcherActionEnum.Sync,
Comment = "Синхронизация неиспользуемых шаблонов"
};
await _matchingStatusService.SetMatchingStatusAsync(
unusedJobId,
SyncTaskEntityTypeEnum.Job,
new MatchingStatusItem { Data = initialStatus, Timestamp = DateTimeOffset.UtcNow, Source = nameof(SimpleTemplateSynchronizer) },
TimeSpan.FromMinutes(30)
);
var totalSw = Stopwatch.StartNew();
try
{
// 1. Находим ID нужных полей
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 UpdateMatchingStatusAsync(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 UpdateMatchingStatusAsync(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 UpdateMatchingStatusAsync(unusedJobId, "Нет шаблонов для обработки");
await _matchingStatusService.DeleteMatchingStatusAsync(unusedJobId, SyncTaskEntityTypeEnum.Job);
return;
}
await UpdateMatchingStatusAsync(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;
}
await SendUpdateRequest(template, unusedJobId, expectedName, initiator, finalUnitId);
_logger.LogDebug("Отправлен запрос на обновление шаблона {TemplateId}. Изменения: Unit={U}, Job={J}, Name={N}",
template.Id, unitChanged, jobChanged, nameChanged);
processed++;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при обработке шаблона {TemplateId}", template.Id);
}
}
totalSw.Stop();
totalSw.Stop();
_logger.LogInformation("[Perf] Job '{JobName}' ({JobId}) | ИТОГО: {TotalMs} мс",
unusedJob.Name, unusedJob.Id, totalSw.ElapsedMilliseconds);
await UpdateMatchingStatusAsync(unusedJobId, "Синхронизация неиспользуемых шаблонов завершена");
await _matchingStatusService.DeleteMatchingStatusAsync(unusedJobId, SyncTaskEntityTypeEnum.Job);
totalSw.Stop();
_logger.LogInformation(
"Синхронизация неиспользуемых шаблонов завершена. Обработано {Count} шаблонов",
unusedTemplates.Count);
}
catch (Exception ex)
{
totalSw.Stop();
_logger.LogError(ex,
"Ошибка при синхронизации неиспользуемых шаблонов для Job {JobId} через {ElapsedMs} мс",
unusedJobId, totalSw.ElapsedMilliseconds);
await UpdateMatchingStatusAsync(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 UpdateMatchingStatusAsync(Guid jobId, string comment)
private async Task SetStatusAsync(Guid jobId, string comment)
{
var status = new MatchingStatusItemDto
{

View File

@@ -130,6 +130,7 @@ namespace PARR.TemplateMatcher.Services.Implementations
}
}
public async Task UpdateTemplatesForJobGroup(Guid jobGroupId, HistoryInitiator initiator)
{
_logger.LogDebug("Начало обновления шаблонов для JobGroup {JobGroupId}", jobGroupId);

View File

@@ -0,0 +1,383 @@
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));
}
}

View File

@@ -4,8 +4,8 @@ namespace PARR.TemplateMatcher.Services.Interfaces
{
public interface ITemplateSynchronizer
{
Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator);
Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator);
Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator);
Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default);
Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default);
Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, CancellationToken ct = default);
}
}
}

View File

@@ -0,0 +1,9 @@
using PARR.Domain.Entities.Base.History;
namespace PARR.TemplateMatcher.Services.Interfaces
{
internal interface IUnusedTemplatesSyncService
{
Task SyncAsync(Guid unusedJobId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default);
}
}

View File

@@ -12,6 +12,10 @@ namespace PARR.TemplateMatcher.Services.SimpleSync
public Guid JobId { get; init; }
public string JobName { get; set; } = string.Empty;
public HistoryInitiator Initiator { get; init; } = null!;
// Флаг режима сухого запуска
public bool DryRun { get; init; }
public Job Job { get; set; } = null!;
public HashSet<Guid> FilteredUnitIds { get; set; } = new();

View File

@@ -78,6 +78,9 @@ namespace PARR.TemplateMatcher
// Легковесные сервисы без состояния, создаются по требованию
services.AddTransient<ITemplateMqPublisher, TemplateMqPublisher>();
services.AddTransient<ITemplateNameNormalizer, TemplateNameNormalizer>();
//Сервис для неактуальных шаблонов
services.AddScoped<IUnusedTemplatesSyncService, UnusedTemplatesSyncService>();
}
public static IConfigurationBuilder AddTemplateMatcherConfigurations(this IConfigurationBuilder builder, IServiceCollection services)