Compare commits
5 Commits
94bea5c46d
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2befb6b0c3 | ||
|
|
0629579cf0 | ||
|
|
83c6a5f605 | ||
|
|
e02a51f5ed | ||
|
|
fb20395e53 |
@@ -4,19 +4,11 @@ namespace PARR.Core.Repositories.Interfaces.Unit
|
|||||||
{
|
{
|
||||||
public interface IUnitInUnitRepository
|
public interface IUnitInUnitRepository
|
||||||
{
|
{
|
||||||
Task<List<UnitInUnit>> GetByParentIdAsync(Guid parentId);
|
|
||||||
Task<List<UnitInUnit>> GetByChildIdAsync(Guid childId);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получает связи, где ChildUnitId unitIds (для IsParent=True).
|
/// Возвращает все связанные UnitId для заданного юнита в обоих направлениях.
|
||||||
|
/// Единая точка загрузки связей.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task<List<UnitInUnit>> GetParentLinksByChildIdsAsync(IEnumerable<Guid> childUnitIds);
|
Task<List<Guid>> GetRelatedUnitIdsAsync(Guid unitId, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Получает связи, где ParentUnitId unitIds (для IsParent=False).
|
|
||||||
/// </summary>
|
|
||||||
Task<List<UnitInUnit>> GetChildLinksByParentIdsAsync(IEnumerable<Guid> parentUnitIds);
|
|
||||||
|
|
||||||
|
|
||||||
IQueryable<UnitInUnit> Get();
|
IQueryable<UnitInUnit> Get();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ internal class RelatedUnitTagShortcodeHandler : IShortcodeHandler
|
|||||||
private static readonly Regex _pattern = new(@"%ТЕГ_СВЯЗИ:([^%]+)%", RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
private static readonly Regex _pattern = new(@"%ТЕГ_СВЯЗИ:([^%]+)%", RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
public Regex Pattern => _pattern;
|
public Regex Pattern => _pattern;
|
||||||
|
|
||||||
public ShortcodeDataRequirementsEnum Requirements => ShortcodeDataRequirementsEnum.UnitsInTemplateTags;
|
public ShortcodeDataRequirementsEnum Requirements => ShortcodeDataRequirementsEnum.UnitsInTemplateTags | ShortcodeDataRequirementsEnum.UnitsInTemplate;
|
||||||
|
|
||||||
public RelatedUnitTagShortcodeHandler(ILogger<RelatedUnitTagShortcodeHandler> logger)
|
public RelatedUnitTagShortcodeHandler(ILogger<RelatedUnitTagShortcodeHandler> logger)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -209,7 +209,7 @@ internal class ShortcodesService : IShortcodesService
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 5. Проверка UnitTags
|
// 4. Проверка UnitTags
|
||||||
var unitTags = currentData.UnitTags;
|
var unitTags = currentData.UnitTags;
|
||||||
if ((unitTags == null || unitTags.Count == 0) &&
|
if ((unitTags == null || unitTags.Count == 0) &&
|
||||||
requirements.HasFlag(ShortcodeDataRequirementsEnum.UnitTags))
|
requirements.HasFlag(ShortcodeDataRequirementsEnum.UnitTags))
|
||||||
@@ -223,7 +223,7 @@ internal class ShortcodesService : IShortcodesService
|
|||||||
.Where(u => u.Id == template.UnitId)
|
.Where(u => u.Id == template.UnitId)
|
||||||
.SelectMany(u => u.UnitValues
|
.SelectMany(u => u.UnitValues
|
||||||
.Where(uv => uv.Field != null &&
|
.Where(uv => uv.Field != null &&
|
||||||
uv.Field.AihitName == "ПАРР тег" &&
|
uv.Field.Code == "tag" &&
|
||||||
uv.Value != null &&
|
uv.Value != null &&
|
||||||
uv.Value.Value != null)
|
uv.Value.Value != null)
|
||||||
.Select(uv => uv.Value!.Value!))
|
.Select(uv => uv.Value!.Value!))
|
||||||
@@ -231,9 +231,22 @@ internal class ShortcodesService : IShortcodesService
|
|||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Проверка RelatedUnitTags
|
// 5. Проверка RelatedUnitTags
|
||||||
var relatedUnitTags = currentData.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) &&
|
if ((relatedUnitTags == null || relatedUnitTags.Count == 0) &&
|
||||||
requirements.HasFlag(ShortcodeDataRequirementsEnum.UnitsInTemplateTags) &&
|
requirements.HasFlag(ShortcodeDataRequirementsEnum.UnitsInTemplateTags) &&
|
||||||
@@ -248,7 +261,7 @@ internal class ShortcodesService : IShortcodesService
|
|||||||
.Where(u => relatedUnitIds.Contains(u.Id))
|
.Where(u => relatedUnitIds.Contains(u.Id))
|
||||||
.SelectMany(u => u.UnitValues
|
.SelectMany(u => u.UnitValues
|
||||||
.Where(uv => uv.Field != null &&
|
.Where(uv => uv.Field != null &&
|
||||||
uv.Field.AihitName == "ПАРР тег" &&
|
uv.Field.Code == "tag" &&
|
||||||
uv.Value != null &&
|
uv.Value != null &&
|
||||||
uv.Value.Value != null)
|
uv.Value.Value != null)
|
||||||
.Select(uv => new { UnitId = u.Id, Tag = uv.Value!.Value! }))
|
.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());
|
.ToDictionary(g => g.Key, g => g.Select(x => x.Tag).ToList());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7. Возвращаем обновленный рекорд
|
// 6. Возвращаем обновленный рекорд
|
||||||
return currentData with
|
return currentData with
|
||||||
{
|
{
|
||||||
UnitName = unitName ?? string.Empty,
|
UnitName = unitName ?? string.Empty,
|
||||||
Job = jobData,
|
Job = jobData,
|
||||||
UnitsInTemplate = unitsInTemplate ?? currentData.UnitsInTemplate,
|
UnitsInTemplate = unitsInTemplate ?? currentData.UnitsInTemplate ?? new List<UnitInTemplateForShortcode>(),
|
||||||
UnitTags = unitTags ?? currentData.UnitTags,
|
UnitTags = unitTags ?? currentData.UnitTags,
|
||||||
RelatedUnitTags = relatedUnitTags ?? currentData.RelatedUnitTags
|
RelatedUnitTags = relatedUnitTags ?? currentData.RelatedUnitTags
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ using PARR.Core.Repositories.Interfaces.Unit;
|
|||||||
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
|
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
|
||||||
using PARR.Core.Services.UnitFilterService.Models;
|
using PARR.Core.Services.UnitFilterService.Models;
|
||||||
using PARR.Domain.Entities.JobEntities;
|
using PARR.Domain.Entities.JobEntities;
|
||||||
|
using PARR.Domain.Entities.Unit;
|
||||||
|
|
||||||
namespace PARR.Core.Services.UnitFilterService.Matchers;
|
namespace PARR.Core.Services.UnitFilterService.Matchers;
|
||||||
|
|
||||||
@@ -238,9 +239,9 @@ internal class UnitRelationshipMatcher : IUnitRelationshipMatcher
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Обрабатывает маску LIKE для корректной работы с SQL
|
/// Нормализует пользовательскую маску в формат, совместимый с PostgreSQL ILIKE.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static string NormalizeLikeMask(string valueMask)
|
internal static string NormalizeLikeMask(string valueMask)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(valueMask))
|
if (string.IsNullOrWhiteSpace(valueMask))
|
||||||
return valueMask;
|
return valueMask;
|
||||||
@@ -258,4 +259,62 @@ internal class UnitRelationshipMatcher : IUnitRelationshipMatcher
|
|||||||
else
|
else
|
||||||
return valueMask;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
|
|||||||
using PARR.Core.Common.Interfaces;
|
using PARR.Core.Common.Interfaces;
|
||||||
using PARR.Core.Repositories.Interfaces.JobRepositories;
|
using PARR.Core.Repositories.Interfaces.JobRepositories;
|
||||||
using PARR.Core.Repositories.Interfaces.Unit;
|
using PARR.Core.Repositories.Interfaces.Unit;
|
||||||
|
using PARR.Core.Services.UnitFilterService.Matchers;
|
||||||
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
|
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
|
||||||
using PARR.Core.Services.UnitFilterService.Models;
|
using PARR.Core.Services.UnitFilterService.Models;
|
||||||
using PARR.Core.Services.UnitService.Interfaces;
|
using PARR.Core.Services.UnitService.Interfaces;
|
||||||
@@ -224,345 +225,6 @@ internal class UnitFilterService : IUnitFilterService
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
private async Task<Job?> LoadJobWithFiltersAsync(Guid jobId, CancellationToken cancellationToken = default)
|
private async Task<Job?> LoadJobWithFiltersAsync(Guid jobId, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
return await jobRepository
|
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);
|
logger.LogDebug("Начало GetRelatedUnitNamesAsync. JobId: {JobId}, UnitId: {UnitId}", jobId, unitId);
|
||||||
|
|
||||||
@@ -590,71 +253,47 @@ internal class UnitFilterService : IUnitFilterService
|
|||||||
throw new ArgumentException($"Job {jobId} не найден.", nameof(jobId));
|
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);
|
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
foreach (var filter in job.UnitFilters)
|
foreach (var filter in job.UnitFilters)
|
||||||
{
|
{
|
||||||
if (!filter.RelationshipFilters.Any()) continue;
|
var relFilters = filter.RelationshipFilters
|
||||||
|
.Where(rf => !string.IsNullOrWhiteSpace(rf.ValueMask?.Trim()))
|
||||||
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()
|
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
if (!allRelatedUnitIds.Any()) continue;
|
if (!relFilters.Any()) continue;
|
||||||
|
|
||||||
// Получить значения для всех связанных юнитов
|
// Проверяем каждый связанный юнит через единую точку проверки
|
||||||
var allUnitValues = await unitInValueRepository.GetByUnitIdsAsync(allRelatedUnitIds);
|
var passedUnitIds = new HashSet<Guid>();
|
||||||
|
|
||||||
// Сгруппировать значения по UnitId
|
|
||||||
var valuesByUnit = allUnitValues
|
|
||||||
.GroupBy(uv => uv.UnitId)
|
|
||||||
.ToDictionary(g => g.Key, g => g.ToList());
|
|
||||||
|
|
||||||
// Найти UnitId, которые проходят все RelationshipFilters
|
|
||||||
var matchingUnitIds = new HashSet<Guid>();
|
|
||||||
|
|
||||||
foreach (var relatedUnitId in allRelatedUnitIds)
|
foreach (var relatedUnitId in allRelatedUnitIds)
|
||||||
{
|
{
|
||||||
bool passesAllFilters = filter.RelationshipFilters.All(rf =>
|
var unitValues = valuesByUnit.GetValueOrDefault(relatedUnitId, new List<UnitInValue>());
|
||||||
{
|
|
||||||
var values = valuesByUnit.GetValueOrDefault(relatedUnitId, new List<UnitInValue>());
|
|
||||||
|
|
||||||
var matchingValues = values
|
// Все фильтры должны пройти (AND между фильтрами в рамках одного UnitFilter)
|
||||||
.Where(uv => uv.FieldId == rf.FieldId && uv.Value?.Value != null)
|
bool passesAll = relFilters.All(rf =>
|
||||||
.ToList();
|
UnitRelationshipMatcher.TargetPassesFilter(unitValues, rf));
|
||||||
|
|
||||||
if (!matchingValues.Any())
|
if (passesAll)
|
||||||
{
|
passedUnitIds.Add(relatedUnitId);
|
||||||
return rf.IsInverse;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var hasMatch = matchingValues.Any(uv => uv.Value!.Value!.Contains(rf.ValueMask.Trim('%'), StringComparison.OrdinalIgnoreCase));
|
if (passedUnitIds.Any())
|
||||||
|
|
||||||
if (rf.IsInverse)
|
|
||||||
hasMatch = !hasMatch;
|
|
||||||
|
|
||||||
return hasMatch;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (passesAllFilters)
|
|
||||||
matchingUnitIds.Add(relatedUnitId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matchingUnitIds.Any())
|
|
||||||
{
|
{
|
||||||
// Используем кэширующий сервис вместо прямого запроса к БД
|
var cachedUnits = await unitService.GetWithCachingAsync(passedUnitIds);
|
||||||
var cachedUnits = await unitService.GetWithCachingAsync(matchingUnitIds);
|
|
||||||
var names = cachedUnits.Values
|
var names = cachedUnits.Values
|
||||||
.Select(u => u.Name)
|
.Select(u => u.Name)
|
||||||
.Where(n => !string.IsNullOrEmpty(n));
|
.Where(n => !string.IsNullOrEmpty(n));
|
||||||
|
|||||||
@@ -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
|
return await Get()
|
||||||
.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
|
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Where(uinu => set.Contains(uinu.ChildUnitId))
|
.Where(link => link.ChildUnitId == unitId || link.ParentUnitId == unitId)
|
||||||
.ToListAsync();
|
.Select(link => link.ChildUnitId == unitId ? link.ParentUnitId : link.ChildUnitId)
|
||||||
}
|
.Distinct()
|
||||||
|
.ToListAsync(ct);
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
16
PARR.TemplateMatcher/Exceptions/SyncEarlyExitException.cs
Normal file
16
PARR.TemplateMatcher/Exceptions/SyncEarlyExitException.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,15 +18,17 @@ internal class BuildGroupsStage : IGroupedSyncStage
|
|||||||
|
|
||||||
public async Task<GroupedSyncContext> ExecuteAsync(GroupedSyncContext context, CancellationToken ct = default)
|
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())
|
context.TemplateGroups = templateGroups;
|
||||||
throw new GroupedSyncEarlyExitException("Нет данных после построения групп");
|
|
||||||
|
|
||||||
context.TemplateGroups = groups;
|
|
||||||
|
|
||||||
_logger.LogDebug("JobGroup '{JobGroupName}' ({JobGroupId}): построено {Count} групп",
|
_logger.LogDebug("JobGroup '{JobGroupName}' ({JobGroupId}): построено {Count} групп",
|
||||||
context.JobGroupName, context.JobGroupId, groups.Count);
|
context.JobGroupName, context.JobGroupId, templateGroups.Count);
|
||||||
|
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using PARR.Core.Services.UnitFilterService;
|
using PARR.Core.Services.UnitFilterService;
|
||||||
|
using PARR.TemplateMatcher.Exceptions;
|
||||||
using PARR.TemplateMatcher.Services.GroupedSync;
|
using PARR.TemplateMatcher.Services.GroupedSync;
|
||||||
|
|
||||||
namespace PARR.TemplateMatcher.Services.Implementations.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);
|
var result = await _filterService.GetUnitsByJobFilterAsync(context.MaxJob.Id, null, ct);
|
||||||
|
|
||||||
if (result == null || !result.Any())
|
if (result == null || !result.Any())
|
||||||
throw new GroupedSyncEarlyExitException("Фильтры не дали Unit'ов с подходящими связями");
|
throw new SyncEarlyExitException("Фильтры не дали Unit'ов с подходящими связями");
|
||||||
|
|
||||||
context.FilteredUnits = result.ToList();
|
context.FilteredUnits = result.ToList();
|
||||||
context.UnitNames = result.ToDictionary(u => u.Id, u => u.Name);
|
context.UnitNames = result.ToDictionary(u => u.Id, u => u.Name);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.TemplateMatcher.Exceptions;
|
||||||
using PARR.TemplateMatcher.Services.GroupedSync;
|
using PARR.TemplateMatcher.Services.GroupedSync;
|
||||||
|
|
||||||
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
|
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
|
||||||
@@ -21,7 +22,7 @@ internal class GroupFilterStage : IGroupedSyncStage
|
|||||||
var finalFiltered = await _groupedFilter.FilterAsync(context.FilteredUnits, context.JobGroup);
|
var finalFiltered = await _groupedFilter.FilterAsync(context.FilteredUnits, context.JobGroup);
|
||||||
|
|
||||||
if (!finalFiltered.Any())
|
if (!finalFiltered.Any())
|
||||||
throw new GroupedSyncEarlyExitException("Нет юнитов после групповой фильтрации");
|
throw new SyncEarlyExitException("Нет юнитов после групповой фильтрации");
|
||||||
|
|
||||||
context.FilteredUnits = finalFiltered;
|
context.FilteredUnits = finalFiltered;
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ public class GroupedSyncContext
|
|||||||
public List<GroupedTemplateGroup> TemplateGroups { get; set; } = new();
|
public List<GroupedTemplateGroup> TemplateGroups { get; set; } = new();
|
||||||
public HashSet<(Guid JobId, Guid UnitId, int Index)> ExpectedTemplateKeys { get; set; } = new();
|
public HashSet<(Guid JobId, Guid UnitId, int Index)> ExpectedTemplateKeys { get; set; } = new();
|
||||||
|
|
||||||
|
// Режим только для чтения — без записи в БД и отправки в MQ
|
||||||
|
public bool DryRun { get; set; } = false;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Имена юнитов для логирования. Заполняется на этапе фильтрации.
|
/// Имена юнитов для логирования. Заполняется на этапе фильтрации.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,24 +16,28 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
private readonly IUnitInValueRepository unitInValueRepository;
|
private readonly IUnitInValueRepository unitInValueRepository;
|
||||||
private readonly IUnitFieldRepository unitFieldRepository;
|
private readonly IUnitFieldRepository unitFieldRepository;
|
||||||
private readonly IShortcodesService shortcodesService;
|
private readonly IShortcodesService shortcodesService;
|
||||||
|
private readonly IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository;
|
||||||
|
|
||||||
public GroupedTemplateBuilder(
|
public GroupedTemplateBuilder(
|
||||||
ILogger<GroupedTemplateBuilder> logger,
|
ILogger<GroupedTemplateBuilder> logger,
|
||||||
IUnitInValueRepository unitInValueRepository,
|
IUnitInValueRepository unitInValueRepository,
|
||||||
IUnitFieldRepository unitFieldRepository,
|
IUnitFieldRepository unitFieldRepository,
|
||||||
IShortcodesService shortcodesService
|
IShortcodesService shortcodesService,
|
||||||
|
IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.unitInValueRepository = unitInValueRepository;
|
this.unitInValueRepository = unitInValueRepository;
|
||||||
this.unitFieldRepository = unitFieldRepository;
|
this.unitFieldRepository = unitFieldRepository;
|
||||||
this.shortcodesService = shortcodesService;
|
this.shortcodesService = shortcodesService;
|
||||||
|
this.regionalEkPtkGroupRepository = regionalEkPtkGroupRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<GroupedTemplateGroup>> BuildAsync(
|
public async Task<List<GroupedTemplateGroup>> BuildAsync(
|
||||||
Dictionary<Guid, List<Guid>> initialReverseMapping,
|
Dictionary<Guid, List<Guid>> initialReverseMapping,
|
||||||
JobGroup jobGroup,
|
JobGroup jobGroup,
|
||||||
Job maxJob,
|
Job maxJob,
|
||||||
|
Dictionary<Guid, string> unitNames,
|
||||||
CancellationToken ct = default)
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
logger.LogDebug("Начало построения структуры групп для JobGroup {JobGroupId}.", jobGroup.Id);
|
logger.LogDebug("Начало построения структуры групп для JobGroup {JobGroupId}.", jobGroup.Id);
|
||||||
@@ -42,7 +46,6 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
return new List<GroupedTemplateGroup>();
|
return new List<GroupedTemplateGroup>();
|
||||||
|
|
||||||
// 1. Определяем стратегию внутренней группировки
|
// 1. Определяем стратегию внутренней группировки
|
||||||
// Если IsGroupByResponsible != true, используем WorkGroupMask через ShortcodesService
|
|
||||||
bool useWorkGroupMask = jobGroup.IsGroupByResponsible != true;
|
bool useWorkGroupMask = jobGroup.IsGroupByResponsible != true;
|
||||||
|
|
||||||
logger.LogDebug("Стратегия внутренней группировки: {Strategy}",
|
logger.LogDebug("Стратегия внутренней группировки: {Strategy}",
|
||||||
@@ -100,24 +103,48 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
// 5. Определяем значения для внутренней группировки
|
// 5. Определяем значения для внутренней группировки
|
||||||
Dictionary<Guid, string> unitIdToGroupingValueMap;
|
Dictionary<Guid, string> unitIdToGroupingValueMap;
|
||||||
|
|
||||||
|
// Загружаем список разрешённых региональных ПТК (если не нужно пропускать фильтрацию)
|
||||||
|
bool skipRegionalFilter = maxJob.WorkGroupMask.Contains("_в_ЗО_РГ", StringComparison.OrdinalIgnoreCase);
|
||||||
|
HashSet<string>? allowedWorkGroupSet = null;
|
||||||
|
|
||||||
|
if (!skipRegionalFilter)
|
||||||
|
{
|
||||||
|
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("Маска содержит тег с '_в_ЗО_РГ'. Фильтрация по списку рабочих групп ПТК пропущена.");
|
||||||
|
}
|
||||||
|
|
||||||
if (useWorkGroupMask)
|
if (useWorkGroupMask)
|
||||||
{
|
{
|
||||||
// Используем ShortcodesService для получения финальных значений WorkGroupMask
|
// Применяем WorkGroupMask для каждого юнита отдельно
|
||||||
unitIdToGroupingValueMap = new Dictionary<Guid, string>();
|
unitIdToGroupingValueMap = new Dictionary<Guid, string>();
|
||||||
|
|
||||||
foreach (var potentialUnitId in reverseMapping.Keys)
|
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)
|
foreach (var relatedUnitId in relatedUnitIds)
|
||||||
{
|
{
|
||||||
// Создаем временный Template для применения шорткодов
|
// Формируем шаблон с одним связанным юнитом
|
||||||
var tempTemplate = new Template
|
var tempTemplate = new Template
|
||||||
{
|
{
|
||||||
Id = Guid.NewGuid(),
|
Id = Guid.NewGuid(),
|
||||||
Name = "temp",
|
Name = "temp",
|
||||||
JobId = maxJob.Id,
|
JobId = maxJob.Id,
|
||||||
UnitId = potentialUnitId, // Родительский юнит шаблона
|
UnitId = potentialUnitId,
|
||||||
Job = maxJob,
|
Job = maxJob,
|
||||||
UnitsInTemplate = new List<UnitsInTemplate>
|
UnitsInTemplate = new List<UnitsInTemplate>
|
||||||
{
|
{
|
||||||
@@ -130,6 +157,27 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
tempTemplate,
|
tempTemplate,
|
||||||
nameof(GroupedTemplateBuilder));
|
nameof(GroupedTemplateBuilder));
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(workGroupValue))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Юнит {UnitId} исключён: маска вернула пустую строку.",
|
||||||
|
relatedUnitId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Фильтрация по списку рабочих групп ПТК
|
||||||
|
if (!skipRegionalFilter && !allowedWorkGroupSet!.Contains(workGroupValue))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"[FILTER] Юнит {UnitId} ИСКЛЮЧЁН: рабочая группа '{WorkGroup}' не найдена в списке разрешённых ({AllowedCount} значений).",
|
||||||
|
relatedUnitId, workGroupValue, allowedWorkGroupSet!.Count);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogDebug(
|
||||||
|
"[FILTER] Юнит {UnitId} ПРОШЁЛ: рабочая группа '{WorkGroup}' для PotentialUnit {PotentialUnitId}.",
|
||||||
|
relatedUnitId, workGroupValue, potentialUnitId);
|
||||||
|
|
||||||
unitIdToGroupingValueMap[relatedUnitId] = workGroupValue;
|
unitIdToGroupingValueMap[relatedUnitId] = workGroupValue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,9 +197,79 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
new HashSet<Guid> { innerGroupingFieldId },
|
new HashSet<Guid> { innerGroupingFieldId },
|
||||||
ct);
|
ct);
|
||||||
|
|
||||||
unitIdToGroupingValueMap = innerGroupingValues
|
// Собираем значения поля "Ответственный" для группировки
|
||||||
.Where(uv => uv.Value != null && uv.Value.Value != null && !string.IsNullOrEmpty(uv.Value.Value))
|
var responsibleValueByUnit = innerGroupingValues
|
||||||
|
.Where(uv => uv.Value != null && !string.IsNullOrEmpty(uv.Value.Value))
|
||||||
.ToDictionary(uv => uv.UnitId, uv => uv.Value!.Value!);
|
.ToDictionary(uv => uv.UnitId, uv => uv.Value!.Value!);
|
||||||
|
|
||||||
|
unitIdToGroupingValueMap = new Dictionary<Guid, string>();
|
||||||
|
|
||||||
|
// Для каждого юнита дополнительно применяем WorkGroupMask и фильтруем по RegionalEkPtkGroup
|
||||||
|
foreach (var potentialUnitId in reverseMapping.Keys)
|
||||||
|
{
|
||||||
|
var relatedUnitIds = reverseMapping[potentialUnitId]
|
||||||
|
.Select(e => e.UnitId)
|
||||||
|
.Distinct()
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
foreach (var relatedUnitId in relatedUnitIds)
|
||||||
|
{
|
||||||
|
// Юнит исключается, если у него нет значения поля "Ответственный"
|
||||||
|
if (!responsibleValueByUnit.TryGetValue(relatedUnitId, out var responsibleValue))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Юнит {UnitId} исключён: отсутствует значение поля 'Ответственный за ЭК'.",
|
||||||
|
relatedUnitId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Фильтрация по списку региональных ПТК выполняется только если не используется тег с "_в_ЗО_РГ"
|
||||||
|
if (!skipRegionalFilter)
|
||||||
|
{
|
||||||
|
// Формируем временный шаблон с одним связанным юнитом для применения WorkGroupMask
|
||||||
|
var tempTemplate = new Template
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Name = "temp",
|
||||||
|
JobId = maxJob.Id,
|
||||||
|
UnitId = potentialUnitId,
|
||||||
|
Job = maxJob,
|
||||||
|
UnitsInTemplate = new List<UnitsInTemplate>
|
||||||
|
{
|
||||||
|
new UnitsInTemplate { UnitId = relatedUnitId, UnitFieldValueId = Guid.Empty }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var workGroupValue = await shortcodesService.ApplyShortcodesAsync(
|
||||||
|
maxJob.WorkGroupMask,
|
||||||
|
tempTemplate,
|
||||||
|
nameof(GroupedTemplateBuilder));
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(workGroupValue))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Юнит {UnitId} исключён: WorkGroupMask вернула пустую строку.",
|
||||||
|
relatedUnitId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!allowedWorkGroupSet!.Contains(workGroupValue))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"[FILTER] Юнит {UnitId} ИСКЛЮЧЁН: рабочая группа '{WorkGroup}' не найдена в списке разрешённых ({AllowedCount} значений).",
|
||||||
|
relatedUnitId, workGroupValue, allowedWorkGroupSet!.Count);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogDebug(
|
||||||
|
"[FILTER] Юнит {UnitId} ПРОШЁЛ: рабочая группа '{WorkGroup}' для PotentialUnit {PotentialUnitId}.",
|
||||||
|
relatedUnitId, workGroupValue, potentialUnitId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// В маппинг группировки пишем значение поля "Ответственный" — по нему идёт группировка в этапе 6
|
||||||
|
unitIdToGroupingValueMap[relatedUnitId] = responsibleValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Формируем итоговую структуру
|
// 6. Формируем итоговую структуру
|
||||||
@@ -163,7 +281,18 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
var potentialUnitId = kvp.Key;
|
var potentialUnitId = kvp.Key;
|
||||||
var unitsInTemplateForThisPotentialUnitId = kvp.Value;
|
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, "Нет данных"))
|
.GroupBy(entry => unitIdToGroupingValueMap.GetValueOrDefault(entry.UnitId, "Нет данных"))
|
||||||
.OrderBy(g => g.Key, StringComparer.Ordinal)
|
.OrderBy(g => g.Key, StringComparer.Ordinal)
|
||||||
.ToList();
|
.ToList();
|
||||||
@@ -179,21 +308,23 @@ internal class GroupedTemplateBuilder : IGroupedTemplateBuilder
|
|||||||
|
|
||||||
var unitsInInnerGroup = innerGroup.ToList();
|
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 })
|
.Select((entry, index) => new { entry, groupIndex = index / maxValueForSplitting })
|
||||||
.GroupBy(x => x.groupIndex)
|
.GroupBy(x => x.groupIndex)
|
||||||
.Select(g => g.Select(x => x.entry).ToList())
|
.Select(g => g.Select(x => x.entry).ToList())
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
|
// ВАЖНО: добавляем подгруппы в subGroups
|
||||||
foreach (var subGroupEntries in splitSubGroups)
|
foreach (var subGroupEntries in splitSubGroups)
|
||||||
{
|
{
|
||||||
var sortedEntries = subGroupEntries
|
|
||||||
.OrderBy(e => e.UnitId)
|
|
||||||
.ThenBy(e => e.UnitFieldValueId)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
subGroups.Add(new GroupedTemplateSubGroup(
|
subGroups.Add(new GroupedTemplateSubGroup(
|
||||||
Entries: sortedEntries,
|
Entries: subGroupEntries,
|
||||||
InnerGroupName: innerGroupName,
|
InnerGroupName: innerGroupName,
|
||||||
GlobalIndex: globalIndex
|
GlobalIndex: globalIndex
|
||||||
));
|
));
|
||||||
|
|||||||
@@ -9,19 +9,13 @@ internal class GroupedTemplateUnitFilter : IGroupedTemplateUnitFilter
|
|||||||
{
|
{
|
||||||
private readonly ILogger<GroupedTemplateUnitFilter> logger;
|
private readonly ILogger<GroupedTemplateUnitFilter> logger;
|
||||||
private readonly IUnitInValueRepository unitInValueRepository;
|
private readonly IUnitInValueRepository unitInValueRepository;
|
||||||
private readonly IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository;
|
|
||||||
private readonly IUnitFieldRepository unitFieldRepository;
|
|
||||||
|
|
||||||
public GroupedTemplateUnitFilter(
|
public GroupedTemplateUnitFilter(
|
||||||
ILogger<GroupedTemplateUnitFilter> logger,
|
ILogger<GroupedTemplateUnitFilter> logger,
|
||||||
IUnitInValueRepository unitInValueRepository,
|
IUnitInValueRepository unitInValueRepository)
|
||||||
IUnitRegionalEkPtkGroupRepository regionalEkPtkGroupRepository,
|
|
||||||
IUnitFieldRepository unitFieldRepository)
|
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.unitInValueRepository = unitInValueRepository;
|
this.unitInValueRepository = unitInValueRepository;
|
||||||
this.regionalEkPtkGroupRepository = regionalEkPtkGroupRepository;
|
|
||||||
this.unitFieldRepository = unitFieldRepository;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<UnitFilterResultDto>> FilterAsync(
|
public async Task<List<UnitFilterResultDto>> FilterAsync(
|
||||||
@@ -47,53 +41,24 @@ internal class GroupedTemplateUnitFilter : IGroupedTemplateUnitFilter
|
|||||||
var groupingFieldId = jobGroup.GroupingUnitFieldId.Value;
|
var groupingFieldId = jobGroup.GroupingUnitFieldId.Value;
|
||||||
logger.LogDebug("Фильтрация по GroupingUnitFieldId (FieldId={FieldId}).", groupingFieldId);
|
logger.LogDebug("Фильтрация по GroupingUnitFieldId (FieldId={FieldId}).", groupingFieldId);
|
||||||
|
|
||||||
// 2. Фильтрация по GroupingUnitFieldId
|
// 2. Загружаем значения поля группировки для всех юнитов
|
||||||
var allUnitIds = unitsList.Select(u => u.Id).ToList();
|
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
|
var validUnitIdsAfterGrouping = groupingValues
|
||||||
.Where(uv => uv.Value != null && !string.IsNullOrEmpty(uv.Value.Value))
|
.Where(uv => uv.Value != null && !string.IsNullOrEmpty(uv.Value.Value))
|
||||||
.Select(uv => uv.UnitId)
|
.Select(uv => uv.UnitId)
|
||||||
.ToHashSet();
|
.ToHashSet();
|
||||||
|
|
||||||
|
// 4. Фильтруем исходный список
|
||||||
var filteredByGrouping = unitsList
|
var filteredByGrouping = unitsList
|
||||||
.Where(u => validUnitIdsAfterGrouping.Contains(u.Id))
|
.Where(u => validUnitIdsAfterGrouping.Contains(u.Id))
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
logger.LogDebug("После фильтрации по GroupingUnitFieldId осталось {Count} юнитов.", filteredByGrouping.Count);
|
logger.LogDebug("После фильтрации по GroupingUnitFieldId осталось {Count} юнитов.", filteredByGrouping.Count);
|
||||||
|
|
||||||
if (!filteredByGrouping.Any())
|
|
||||||
{
|
|
||||||
return filteredByGrouping;
|
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -15,5 +15,6 @@ public interface IGroupedTemplateBuilder
|
|||||||
Dictionary<Guid, List<Guid>> initialReverseMapping,
|
Dictionary<Guid, List<Guid>> initialReverseMapping,
|
||||||
JobGroup jobGroup,
|
JobGroup jobGroup,
|
||||||
Job maxJob,
|
Job maxJob,
|
||||||
|
Dictionary<Guid, string> unitNames,
|
||||||
CancellationToken ct = default);
|
CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
|
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
|
||||||
|
using PARR.TemplateMatcher.Exceptions;
|
||||||
using PARR.TemplateMatcher.Services.GroupedSync;
|
using PARR.TemplateMatcher.Services.GroupedSync;
|
||||||
|
|
||||||
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
|
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
|
||||||
@@ -32,7 +33,7 @@ internal class LoadJobGroupStage : IGroupedSyncStage
|
|||||||
.FirstOrDefaultAsync(jg => jg.Id == context.JobGroupId, ct);
|
.FirstOrDefaultAsync(jg => jg.Id == context.JobGroupId, ct);
|
||||||
|
|
||||||
if (jobGroup == null || jobGroup.Jobs == null || !jobGroup.Jobs.Any())
|
if (jobGroup == null || jobGroup.Jobs == null || !jobGroup.Jobs.Any())
|
||||||
throw new GroupedSyncEarlyExitException("JobGroup не найден или пуст");
|
throw new SyncEarlyExitException("JobGroup не найден или пуст");
|
||||||
|
|
||||||
var jobsInGroup = jobGroup.Jobs.ToList();
|
var jobsInGroup = jobGroup.Jobs.ToList();
|
||||||
var maxJob = jobsInGroup
|
var maxJob = jobsInGroup
|
||||||
@@ -41,7 +42,7 @@ internal class LoadJobGroupStage : IGroupedSyncStage
|
|||||||
.FirstOrDefault();
|
.FirstOrDefault();
|
||||||
|
|
||||||
if (maxJob == null)
|
if (maxJob == null)
|
||||||
throw new GroupedSyncEarlyExitException("Не найден Job с MaxValueRelationships");
|
throw new SyncEarlyExitException("Не найден Job с MaxValueRelationships");
|
||||||
|
|
||||||
context.JobGroup = jobGroup;
|
context.JobGroup = jobGroup;
|
||||||
context.JobGroupName = jobGroup.GroupName;
|
context.JobGroupName = jobGroup.GroupName;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.TemplateMatcher.Exceptions;
|
||||||
using PARR.TemplateMatcher.Services.GroupedSync;
|
using PARR.TemplateMatcher.Services.GroupedSync;
|
||||||
|
|
||||||
namespace PARR.TemplateMatcher.Services.Implementations.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);
|
var mapping = await _conflictMapper.BuildMappingAsync(context.FilteredUnits, context.MaxJob, ct);
|
||||||
|
|
||||||
if (!mapping.Any())
|
if (!mapping.Any())
|
||||||
throw new GroupedSyncEarlyExitException("Нет связей после разрешения конфликтов");
|
throw new SyncEarlyExitException("Нет связей после разрешения конфликтов");
|
||||||
|
|
||||||
context.ReverseMapping = mapping;
|
context.ReverseMapping = mapping;
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using PARR.Core.Services.MatchingStatusService;
|
|||||||
using PARR.Domain.Cache.Models;
|
using PARR.Domain.Cache.Models;
|
||||||
using PARR.Domain.Entities.Base.History;
|
using PARR.Domain.Entities.Base.History;
|
||||||
using PARR.Domain.Enums;
|
using PARR.Domain.Enums;
|
||||||
|
using PARR.TemplateMatcher.Exceptions;
|
||||||
using PARR.TemplateMatcher.Services.GroupedSync;
|
using PARR.TemplateMatcher.Services.GroupedSync;
|
||||||
using PARR.TemplateMatcher.Services.Implementations.GroupedSync;
|
using PARR.TemplateMatcher.Services.Implementations.GroupedSync;
|
||||||
using PARR.TemplateMatcher.Services.Interfaces;
|
using PARR.TemplateMatcher.Services.Interfaces;
|
||||||
@@ -17,6 +18,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
private readonly IMatchingStatusService _matchingStatusService;
|
private readonly IMatchingStatusService _matchingStatusService;
|
||||||
private readonly ILogger<GroupedTemplateSynchronizer> _logger;
|
private readonly ILogger<GroupedTemplateSynchronizer> _logger;
|
||||||
|
|
||||||
|
|
||||||
public GroupedTemplateSynchronizer(
|
public GroupedTemplateSynchronizer(
|
||||||
IEnumerable<IGroupedSyncStage> readStages,
|
IEnumerable<IGroupedSyncStage> readStages,
|
||||||
IEnumerable<IGroupedSyncWriteStage> writeStages,
|
IEnumerable<IGroupedSyncWriteStage> writeStages,
|
||||||
@@ -30,9 +32,10 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
_logger = logger;
|
_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);
|
var existingStatus = await _matchingStatusService.GetStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
|
||||||
if (existingStatus.DetailsJobGroups?.Count > 0)
|
if (existingStatus.DetailsJobGroups?.Count > 0)
|
||||||
@@ -41,14 +44,20 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await SetStatusAsync(jobGroupId, "Начало синхронизации");
|
await SetStatusAsync(jobGroupId, dryRun ? "DryRun: Начало анализа" : "Начало синхронизации");
|
||||||
|
|
||||||
var totalSw = Stopwatch.StartNew();
|
var totalSw = Stopwatch.StartNew();
|
||||||
|
|
||||||
try
|
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)
|
foreach (var stage in _readStages)
|
||||||
{
|
{
|
||||||
var stageSw = Stopwatch.StartNew();
|
var stageSw = Stopwatch.StartNew();
|
||||||
@@ -58,6 +67,12 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
context.JobGroupName, jobGroupId, stage.StageName, stageSw.ElapsedMilliseconds);
|
context.JobGroupName, jobGroupId, stage.StageName, stageSw.ElapsedMilliseconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Подробный отчёт по результатам read-этапов
|
||||||
|
PrintDryRunReport(context);
|
||||||
|
|
||||||
|
// Write-этапы пропускаем при DryRun
|
||||||
|
if (!dryRun)
|
||||||
|
{
|
||||||
foreach (var stage in _writeStages)
|
foreach (var stage in _writeStages)
|
||||||
{
|
{
|
||||||
var stageSw = Stopwatch.StartNew();
|
var stageSw = Stopwatch.StartNew();
|
||||||
@@ -67,16 +82,21 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
context.JobGroupName, jobGroupId, stage.StageName, stageSw.ElapsedMilliseconds);
|
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();
|
totalSw.Stop();
|
||||||
_logger.LogInformation("[Perf] JobGroup '{JobGroupName}' ({JobGroupId}) | ИТОГО: {TotalMs} мс",
|
_logger.LogInformation("[Perf] JobGroup '{JobGroupName}' ({JobGroupId}) | ИТОГО: {TotalMs} мс",
|
||||||
context.JobGroupName, jobGroupId, totalSw.ElapsedMilliseconds);
|
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();
|
totalSw.Stop();
|
||||||
_logger.LogInformation("JobGroup {JobGroupId}: {Reason} ({ElapsedMs} мс)",
|
_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);
|
_logger.LogWarning("GroupedTemplateSynchronizer: SyncTemplatesForJob вызван для JobId {JobId}. Это не поддерживаемая операция.", jobId);
|
||||||
return Task.CompletedTask;
|
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);
|
_logger.LogWarning("GroupedTemplateSynchronizer: UpdateTemplatesForJob вызван для JobId {JobId}. Это не поддерживаемая операция.", jobId);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private async Task SetStatusAsync(Guid jobGroupId, string comment)
|
private async Task SetStatusAsync(Guid jobGroupId, string comment)
|
||||||
{
|
{
|
||||||
var status = new MatchingStatusItemDto
|
var status = new MatchingStatusItemDto
|
||||||
|
|||||||
@@ -3,18 +3,14 @@ using Microsoft.Extensions.Logging;
|
|||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using PARR.Core.Repositories.Interfaces;
|
using PARR.Core.Repositories.Interfaces;
|
||||||
using PARR.Core.Repositories.Interfaces.JobRepositories;
|
using PARR.Core.Repositories.Interfaces.JobRepositories;
|
||||||
using PARR.Core.Repositories.Interfaces.Unit;
|
|
||||||
using PARR.Core.Services.MatchingStatusService;
|
using PARR.Core.Services.MatchingStatusService;
|
||||||
using PARR.Core.Services.UnitFilterService;
|
using PARR.Core.Services.UnitFilterService;
|
||||||
using PARR.Domain.Cache.Models;
|
using PARR.Domain.Cache.Models;
|
||||||
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
|
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
|
||||||
using PARR.Domain.Entities;
|
|
||||||
using PARR.Domain.Entities.Base.History;
|
using PARR.Domain.Entities.Base.History;
|
||||||
using PARR.Domain.Entities.JobEntities;
|
|
||||||
using PARR.Domain.Entities.Unit;
|
|
||||||
using PARR.Domain.Enums;
|
using PARR.Domain.Enums;
|
||||||
using PARR.Domain.Settings;
|
using PARR.Domain.Settings;
|
||||||
using PARR.TemplateMatcher.Constants;
|
using PARR.TemplateMatcher.Exceptions;
|
||||||
using PARR.TemplateMatcher.Services.Interfaces;
|
using PARR.TemplateMatcher.Services.Interfaces;
|
||||||
using PARR.TemplateMatcher.Services.SimpleSync;
|
using PARR.TemplateMatcher.Services.SimpleSync;
|
||||||
using PARR.TemplateMatcher.Settings;
|
using PARR.TemplateMatcher.Settings;
|
||||||
@@ -38,10 +34,8 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
private readonly ITemplateMqPublisher _templateMqPublisher;
|
private readonly ITemplateMqPublisher _templateMqPublisher;
|
||||||
private readonly IMatchingStatusService _matchingStatusService;
|
private readonly IMatchingStatusService _matchingStatusService;
|
||||||
private readonly SettingsFromDb _settingsFromDb;
|
private readonly SettingsFromDb _settingsFromDb;
|
||||||
private readonly IOptions<TemplateSettings> _templateSettings;
|
private readonly IUnusedTemplatesSyncService _unusedTemplatesSyncService;
|
||||||
private readonly IUnitFieldRepository _unitFieldService;
|
|
||||||
private readonly IUnitInValueRepository _unitInValueService;
|
|
||||||
private readonly IUnitRepository _unitRepository;
|
|
||||||
|
|
||||||
public SimpleTemplateSynchronizer(
|
public SimpleTemplateSynchronizer(
|
||||||
IEnumerable<ISimpleSyncStage> readStages,
|
IEnumerable<ISimpleSyncStage> readStages,
|
||||||
@@ -55,33 +49,28 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
IMatchingStatusService matchingStatusService,
|
IMatchingStatusService matchingStatusService,
|
||||||
SettingsFromDb settingsFromDb,
|
SettingsFromDb settingsFromDb,
|
||||||
IOptions<TemplateSettings> templateSettings,
|
IOptions<TemplateSettings> templateSettings,
|
||||||
IUnitFieldRepository unitFieldService,
|
IUnusedTemplatesSyncService unusedTemplatesSyncService
|
||||||
IUnitInValueRepository unitInValueService,
|
|
||||||
IUnitRepository unitRepository
|
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
this._readStages = readStages;
|
_readStages = readStages;
|
||||||
this._writeStages = writeStages;
|
_writeStages = writeStages;
|
||||||
this._logger = logger;
|
_logger = logger;
|
||||||
this._unitFilterService = unitFilterService;
|
_unitFilterService = unitFilterService;
|
||||||
this._templateService = templateService;
|
_templateService = templateService;
|
||||||
this._jobService = jobService;
|
_jobService = jobService;
|
||||||
this._templateNameNormalizer = templateNameNormalizer;
|
_templateNameNormalizer = templateNameNormalizer;
|
||||||
this._templateMqPublisher = templateMqPublisher;
|
_templateMqPublisher = templateMqPublisher;
|
||||||
this._matchingStatusService = matchingStatusService;
|
_matchingStatusService = matchingStatusService;
|
||||||
this._settingsFromDb = settingsFromDb;
|
_settingsFromDb = settingsFromDb;
|
||||||
this._templateSettings = templateSettings;
|
_unusedTemplatesSyncService = unusedTemplatesSyncService;
|
||||||
this._unitFieldService = unitFieldService;
|
|
||||||
this._unitInValueService = unitInValueService;
|
|
||||||
this._unitRepository = unitRepository;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
if (jobId == _settingsFromDb.JobIdForUnusedTemplates)
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Обработка синхронизации для Job неиспользуемых шаблонов '{JobId}'", jobId);
|
await _unusedTemplatesSyncService.SyncAsync(jobId, initiator, dryRun);
|
||||||
await SyncUnusedTemplatesAsync(jobId, initiator);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,6 +109,11 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
context.JobName, jobId, stage.StageName, stageSw.ElapsedMilliseconds);
|
context.JobName, jobId, stage.StageName, stageSw.ElapsedMilliseconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Подробный отчёт по результатам read-этапов
|
||||||
|
PrintDryRunReport(context);
|
||||||
|
|
||||||
|
if (!dryRun)
|
||||||
|
{
|
||||||
foreach (var stage in _writeStages)
|
foreach (var stage in _writeStages)
|
||||||
{
|
{
|
||||||
var stageSw = Stopwatch.StartNew();
|
var stageSw = Stopwatch.StartNew();
|
||||||
@@ -129,33 +123,93 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
context.JobName, jobId, stage.StageName, stageSw.ElapsedMilliseconds);
|
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();
|
totalSw.Stop();
|
||||||
_logger.LogInformation("[Perf] Job '{JobName}' ({JobId}) | ИТОГО: {TotalMs} мс",
|
_logger.LogInformation("[Perf] Job '{JobName}' ({JobId}) | ИТОГО: {TotalMs} мс",
|
||||||
context.JobName, jobId, totalSw.ElapsedMilliseconds);
|
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);
|
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
|
||||||
_logger.LogInformation("Синхронизация шаблонов завершена для Job '{JobName}' ({JobId})",
|
|
||||||
context.JobName, jobId);
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
totalSw.Stop();
|
totalSw.Stop();
|
||||||
_logger.LogError(ex, "Ошибка при синхронизации Job '{JobName}' ({JobId}) через {ElapsedMs} мс",
|
_logger.LogError(ex, "Ошибка при синхронизации Job '{JobName}' ({JobId}) через {ElapsedMs} мс",
|
||||||
string.Empty, jobId, totalSw.ElapsedMilliseconds);
|
context.JobName ?? string.Empty, jobId, totalSw.ElapsedMilliseconds);
|
||||||
await UpdateMatchingStatusAsync(jobId, $"Ошибка: {ex.Message}");
|
await SetStatusAsync(jobId, $"Ошибка: {ex.Message}");
|
||||||
throw;
|
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);
|
_logger.LogDebug("Обновление шаблонов для Job {JobId}", jobId);
|
||||||
|
|
||||||
@@ -195,7 +249,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
if (job == null)
|
if (job == null)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Job {JobId} не найден.", jobId);
|
_logger.LogWarning("Job {JobId} не найден.", jobId);
|
||||||
await UpdateMatchingStatusAsync(jobId, "Job не найден");
|
await SetStatusAsync(jobId, "Job не найден");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,7 +258,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
if (filteredUnits == null || !filteredUnits.Any())
|
if (filteredUnits == null || !filteredUnits.Any())
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Для Job {JobId} фильтры не дали Unit'ов.", jobId);
|
_logger.LogInformation("Для Job {JobId} фильтры не дали Unit'ов.", jobId);
|
||||||
await UpdateMatchingStatusAsync(jobId, "Нет Unit'ов — обновление не требуется");
|
await SetStatusAsync(jobId, "Нет Unit'ов — обновление не требуется");
|
||||||
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
|
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -265,306 +319,20 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await UpdateMatchingStatusAsync(jobId, "Обновление завершено");
|
await SetStatusAsync(jobId, "Обновление завершено");
|
||||||
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
|
await _matchingStatusService.DeleteMatchingStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
|
||||||
_logger.LogInformation("Обновление шаблонов завершено для Job {JobId}.", jobId);
|
_logger.LogInformation("Обновление шаблонов завершено для Job {JobId}.", jobId);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Ошибка при обновлении Job {JobId}", jobId);
|
_logger.LogError(ex, "Ошибка при обновлении Job {JobId}", jobId);
|
||||||
await UpdateMatchingStatusAsync(jobId, $"Ошибка: {ex.Message}");
|
await SetStatusAsync(jobId, $"Ошибка: {ex.Message}");
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private async Task SyncUnusedTemplatesAsync(Guid unusedJobId, HistoryInitiator initiator, CancellationToken ct = default)
|
private async Task SetStatusAsync(Guid jobId, string comment)
|
||||||
{
|
|
||||||
// Проверка отмены в самом начале
|
|
||||||
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)
|
|
||||||
{
|
{
|
||||||
var status = new MatchingStatusItemDto
|
var status = new MatchingStatusItemDto
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -130,6 +130,7 @@ namespace PARR.TemplateMatcher.Services.Implementations
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task UpdateTemplatesForJobGroup(Guid jobGroupId, HistoryInitiator initiator)
|
public async Task UpdateTemplatesForJobGroup(Guid jobGroupId, HistoryInitiator initiator)
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Начало обновления шаблонов для JobGroup {JobGroupId}", jobGroupId);
|
_logger.LogDebug("Начало обновления шаблонов для JobGroup {JobGroupId}", jobGroupId);
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,8 +4,8 @@ namespace PARR.TemplateMatcher.Services.Interfaces
|
|||||||
{
|
{
|
||||||
public interface ITemplateSynchronizer
|
public interface ITemplateSynchronizer
|
||||||
{
|
{
|
||||||
Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator);
|
Task SyncTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default);
|
||||||
Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator);
|
Task SyncTemplatesForJobGroupAsync(Guid jobGroupId, HistoryInitiator initiator, bool dryRun = false, CancellationToken ct = default);
|
||||||
Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator);
|
Task UpdateTemplatesForJobAsync(Guid jobId, HistoryInitiator initiator, CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,10 @@ namespace PARR.TemplateMatcher.Services.SimpleSync
|
|||||||
public Guid JobId { get; init; }
|
public Guid JobId { get; init; }
|
||||||
public string JobName { get; set; } = string.Empty;
|
public string JobName { get; set; } = string.Empty;
|
||||||
public HistoryInitiator Initiator { get; init; } = null!;
|
public HistoryInitiator Initiator { get; init; } = null!;
|
||||||
|
|
||||||
|
// Флаг режима сухого запуска
|
||||||
|
public bool DryRun { get; init; }
|
||||||
|
|
||||||
public Job Job { get; set; } = null!;
|
public Job Job { get; set; } = null!;
|
||||||
public HashSet<Guid> FilteredUnitIds { get; set; } = new();
|
public HashSet<Guid> FilteredUnitIds { get; set; } = new();
|
||||||
|
|
||||||
|
|||||||
@@ -78,6 +78,9 @@ namespace PARR.TemplateMatcher
|
|||||||
// Легковесные сервисы без состояния, создаются по требованию
|
// Легковесные сервисы без состояния, создаются по требованию
|
||||||
services.AddTransient<ITemplateMqPublisher, TemplateMqPublisher>();
|
services.AddTransient<ITemplateMqPublisher, TemplateMqPublisher>();
|
||||||
services.AddTransient<ITemplateNameNormalizer, TemplateNameNormalizer>();
|
services.AddTransient<ITemplateNameNormalizer, TemplateNameNormalizer>();
|
||||||
|
|
||||||
|
//Сервис для неактуальных шаблонов
|
||||||
|
services.AddScoped<IUnusedTemplatesSyncService, UnusedTemplatesSyncService>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IConfigurationBuilder AddTemplateMatcherConfigurations(this IConfigurationBuilder builder, IServiceCollection services)
|
public static IConfigurationBuilder AddTemplateMatcherConfigurations(this IConfigurationBuilder builder, IServiceCollection services)
|
||||||
|
|||||||
Reference in New Issue
Block a user