feat(dal,templateMatcher): Shortcodes добавлены %МАКС:ИМЯ АТРИБУТА%, %ГР_ПОЛЕ-ПН%, %БУКВЫ:ИМЯ АТРИБУТА%, исправлена фильтрация в UnitFilter, TemplateMatcher отдельные классы для типов работ, Shortcodes теперь работает по своим моделям Dto

This commit is contained in:
Mikhail Kuznetsov
2025-12-23 18:27:31 +10:00
parent 7ca536ce52
commit 00cace4255
32 changed files with 2471 additions and 1399 deletions

View File

@@ -0,0 +1,89 @@
using Microsoft.Extensions.Logging;
using PARR.DAL.CacheServices;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Settings;
using System.Text.RegularExpressions;
namespace PARR.DAL.DomainServices.Implementations
{
public class GroupedShortcodesCacheService : IGroupedShortcodesCacheService
{
private readonly IRedisCacheService cacheService;
private readonly GroupedShortcodesCacheSettings settings;
private readonly ILogger<GroupedShortcodesCacheService> logger;
public GroupedShortcodesCacheService(
IRedisCacheService cacheService,
GroupedShortcodesCacheSettings settings,
ILogger<GroupedShortcodesCacheService> logger)
{
this.cacheService = cacheService;
this.settings = settings;
this.logger = logger;
}
public async Task<string> GetAggregatedValueAsync(
Guid unitId,
string shortcode,
Func<Task<string>> computeIfMissing)
{
if (string.IsNullOrEmpty(shortcode))
throw new ArgumentException("Ключ шорткода должен быть указан.", nameof(shortcode));
var cacheKey = GetCacheKey(unitId, shortcode);
try
{
var cachedValue = await cacheService.GetCachedDataAsync<string>(cacheKey);
if (cachedValue != null)
{
logger.LogDebug(
"Попадание в кэш для шорткода '{ShortcodeKey}': unit={UnitId} → '{Value}'",
shortcode, unitId, cachedValue);
return cachedValue;
}
logger.LogDebug(
"Промах кэша для шорткода '{ShortcodeKey}': unit={UnitId}. Вычисление...",
shortcode, unitId);
var computedValue = await computeIfMissing();
await cacheService.SetCachedDataAsync(cacheKey, computedValue, settings.ValueTtl);
logger.LogDebug(
"Вычислено и сохранено значение для '{ShortcodeKey}': unit={UnitId} → '{Value}' (срок хранения={Ttl})",
shortcode, unitId, computedValue, settings.ValueTtl);
return computedValue;
}
catch (Exception ex)
{
logger.LogWarning(
ex,
"Ошибка при получении или вычислении значения для шорткода '{ShortcodeKey}' (unit={UnitId}). Возвращена пустая строка.",
shortcode, unitId);
return string.Empty;
}
}
private static string GetCacheKey(Guid unitId, string shortcodeKey)
{
var safeKey = shortcodeKey
.Trim()
.Replace(":", "_")
.Replace(" ", "_")
.Replace(".", "_")
.Replace("%", "")
.Replace("[", "_")
.Replace("]", "_")
.Replace("/", "_")
.Replace("\\", "_");
safeKey = Regex.Replace(safeKey, @"[^a-zA-Z0-9_-]", "_");
return $"gr_shcd_{unitId:N}_{safeKey}"; // :N — без дефисов в Guid
}
}
}

View File

@@ -1,287 +0,0 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainModels;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Models.Job;
using PARR.DAL.Models.Unit;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
using System.Text.RegularExpressions;
namespace PARR.DAL.DomainServices.Implementations
{
internal class ShortcodesService : IShortcodesService
{
private const string shortcodePattern = "%[^%\\s]+%";
private static readonly HashSet<string> SupportedShortcodes = new(StringComparer.OrdinalIgnoreCase)
{
"%ЭК%", "%ГРУППА_РАБОТ%", "%РАБОТА%", "%ТНК%", "%СВЯЗИ%", "%ТНК-КРАТКО%", "%СВЯЗИ-ПН%", "%ИНДЕКС%"
};
private readonly ILogger<ShortcodesService> logger;
private readonly SettingsFromDb settingsFromDb;
private readonly IJobService jobService;
private readonly IUnitService unitService;
private readonly IUnitInValueService unitInValueService;
private readonly IUnitFieldService unitFieldService;
private readonly IUnitFilterService unitFilterService;
public ShortcodesService(
ILogger<ShortcodesService> logger,
SettingsFromDb settingsFromDb,
IJobService jobService,
IUnitService unitService,
IUnitFilterService unitFilterService,
IUnitInValueService unitInValueService,
IUnitFieldService unitFieldService
)
{
this.logger = logger;
this.settingsFromDb = settingsFromDb;
this.jobService = jobService;
this.unitService = unitService;
this.unitInValueService = unitInValueService;
this.unitFieldService = unitFieldService;
this.unitFilterService = unitFilterService;
}
public async Task<string> ApplyShortcodesAsync(string str, Guid unitId, Guid jobId, int? index = null)
{
logger.LogDebug("Начата подстановка шорткодов. Вход: '{Input}', unitId={UnitId}, jobId={JobId}", str, unitId, jobId);
var job = await jobService
.Get().AsNoTracking()
.Include(j => j.Tnk)
.Include(j => j.Group)
.Include(j => j.UnitFilters)
.ThenInclude(uf => uf.RelationshipFilters)
.FirstOrDefaultAsync(j => j.Id == jobId);
var unit = await unitService.Get().AsNoTracking().FirstOrDefaultAsync(u => u.Id == unitId);
if (job == null || unit == null || string.IsNullOrEmpty(str))
{
logger.LogError("Переданы некорректные данные для подстановки динамических записей");
return str;
}
var resultName = str;
var shortcodesInMask = GetShortCodes(resultName);
// 1. Статические константы
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
if (shortcodesInMask.Any(m => nameConstants.Any(c => $"%{c.Name}%".Equals(m.Value, StringComparison.OrdinalIgnoreCase))))
{
resultName = ReplaceConstants(nameConstants, resultName);
}
// 2. Стандартные шорткоды — с поддержкой вложенных (%РАБОТА% → "Мониторинг | %ЭК%")
const int MaxStandardIterations = 3;
var iteration = 0;
while (iteration < MaxStandardIterations)
{
// Ищем ТОЛЬКО поддерживаемые шорткоды в текущей строке
var remainingShortcodes = GetShortCodes(resultName)
.Select(m => m.Value)
.Where(s => SupportedShortcodes.Contains(s))
.ToList();
if (!remainingShortcodes.Any())
break;
// Делаем замену
var oldResult = resultName;
resultName = ReplaceStandardShortcodes(job, unit, resultName, index);
iteration++;
// Защита от "бесполезных" итераций (строка не изменилась)
if (resultName == oldResult)
{
logger.LogDebug("Замена стандартных шорткодов не изменила строку на итерации {Iteration}. Останов.", iteration);
break;
}
}
if (iteration >= MaxStandardIterations)
{
logger.LogWarning(
"Достигнуто максимальное число итераций ({Max}) при замене стандартных шорткодов. Текущий результат: {Result}",
MaxStandardIterations, resultName);
}
// 3. %СВЯЗИ% или %СВЯЗИ-ПН%
List<string>? relatedUnitNames = null;
// 3.1. %СВЯЗИ%
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ%", StringComparison.OrdinalIgnoreCase)))
{
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(jobId, unitId);
var linksText = string.Join("\n", relatedUnitNames);
resultName = Regex.Replace(resultName, "%СВЯЗИ%", linksText, RegexOptions.IgnoreCase);
}
// 3.2. %СВЯЗИ-ПН%
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ-ПН%", StringComparison.OrdinalIgnoreCase)))
{
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(jobId, unitId);
var linksText = string.Join("\n", relatedUnitNames.Select((name, i) => $"{i + 1}. {name}"));
resultName = Regex.Replace(resultName, "%СВЯЗИ-ПН%", linksText, RegexOptions.IgnoreCase);
}
// 4. Поля (оставшиеся %FIELD_NAME%) - выполняем запрос ТОЛЬКО если после предыдущих замен остались необработанные шорткоды
shortcodesInMask = GetShortCodes(resultName);
if (shortcodesInMask.Count > 0)
resultName = await ReplaceFieldValues(unitId, resultName, shortcodesInMask);
logger.LogDebug("Подстановка завершена. Результат: '{Result}'", resultName);
return resultName;
}
public bool IsAnyShortcodes(string str)
{
return Regex.IsMatch(str, shortcodePattern);
}
private static List<Match> GetShortCodes(string resultName)
{
var shortcodesInMask = Regex.Matches(resultName, shortcodePattern).ToList();
return shortcodesInMask;
}
public async Task<List<ShortcodeInfoDto>> GetAvailableShortcodesAsync()
{
var result = new List<ShortcodeInfoDto>();
// 1. Статические константы — из settingsFromDb
foreach (var constant in settingsFromDb.TemplateNameConstantPartsList)
{
result.Add(new ShortcodeInfoDto
{
Shortcode = $"%{constant.Name}%",
Description = $"Константа: {constant.Value ?? "(пусто)"}",
Type = ShortcodeTypeEnum.Static
});
}
// 2. Стандартные шорткоды
result.AddRange(new[]
{
new ShortcodeInfoDto { Shortcode = "%ЭК%",
Description = "Наименование ЭК(Код поиска)",
Type = ShortcodeTypeEnum.Standart },
new ShortcodeInfoDto { Shortcode = "%ГРУППА_РАБОТ%",
Description = "Наименование группы работ",
Type = ShortcodeTypeEnum.Standart },
new ShortcodeInfoDto { Shortcode = "%РАБОТА%",
Description = "Наименование работы в АСУ ЕСПП",
Type = ShortcodeTypeEnum.Standart },
new ShortcodeInfoDto { Shortcode = "%ТНК%",
Description = "Полное наименование ТНК",
Type = ShortcodeTypeEnum.Standart },
new ShortcodeInfoDto { Shortcode = "%ТНК-КРАТКО%",
Description = "Краткое наименование ТНК",
Type = ShortcodeTypeEnum.Standart },
new ShortcodeInfoDto { Shortcode = "%ИНДЕКС%",
Description = "Порядковый индекс шаблона для групповых работ",
Type = ShortcodeTypeEnum.Standart }
});
// 3. Связи
result.AddRange(new[]
{
new ShortcodeInfoDto { Shortcode = "%СВЯЗИ%",
Description = "Связанные ЭК (по одному на строку), выбираются только при настроенном фильтре по полям в связанных ЭК",
Type = ShortcodeTypeEnum.Relationship },
new ShortcodeInfoDto { Shortcode = "%СВЯЗИ-ПН%",
Description = "Связанные ЭК с нумерацией (1. ..., 2. ...), выбираются только при настроенном фильтре по полям в связанных ЭК",
Type = ShortcodeTypeEnum.Relationship }
});
// 4. Все доступные поля из UnitField
var fieldNames = await unitFieldService.Get().AsNoTracking().Select(t => new { t.AihitName, t.DisplayName }).ToListAsync();
foreach (var fieldName in fieldNames.OrderBy(n => n.AihitName))
{
result.Add(new ShortcodeInfoDto
{
Shortcode = $"%{fieldName.AihitName}%",
Description = $"Атрибут: {fieldName.DisplayName ?? fieldName.AihitName}",
Type = ShortcodeTypeEnum.FieldValue
});
}
return result;
}
private async Task<string> ReplaceFieldValues(Guid unitId, string resultName, List<Match> shortcodesInMask)
{
// 1. Извлекаем имена полей из шорткодов
var requiredFieldNames = shortcodesInMask
.Select(m => m.Value.Trim('%').ToUpperInvariant())
.ToList();
if (requiredFieldNames.Count == 0)
return resultName;
// 2. Получаем значения (может быть дубль)
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, requiredFieldNames);
// 3. Группируем по FieldName → список значений
var fieldValuesMap = fieldValues
.GroupBy(x => x.FieldName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(
g => g.Key,
g => g.Select(x => x.Value).ToList(), // список значений (может быть null)
StringComparer.OrdinalIgnoreCase);
// 4. Объединяем значения через запятую (null → "null") и подставляем
foreach (var match in shortcodesInMask)
{
var fieldName = match.Value.Trim('%').ToUpperInvariant();
if (fieldValuesMap.TryGetValue(fieldName, out var values))
{
// Объединяем все значения через запятую, null заменяем на строку "null"
var combinedValue = string.Join(", ", values.Select(v => v ?? "null"));
resultName = resultName.Replace(match.Value, combinedValue);
}
else
{
logger.LogWarning("Поле '{FieldName}' не найдено для unitId={UnitId} при подстановке шорткода '{Shortcode}'",
fieldName, unitId, match.Value);
}
}
return resultName;
}
private static string ReplaceStandardShortcodes(Job job, Unit unit, string input, int? index = null)
{
return input
.Replace("%ЭК%", unit.Name, StringComparison.OrdinalIgnoreCase)
.Replace("%ГРУППА_РАБОТ%", job.Group?.GroupName ?? "", StringComparison.OrdinalIgnoreCase)
.Replace("%РАБОТА%", job.WorkName, StringComparison.OrdinalIgnoreCase)
.Replace("%ТНК%", job.Tnk?.Name ?? "", StringComparison.OrdinalIgnoreCase)
.Replace("%ТНК-КРАТКО%", job.Tnk?.ShortName ?? "", StringComparison.OrdinalIgnoreCase)
.Replace("%ИНДЕКС%", index?.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
}
private static string ReplaceConstants(List<BLL.Domain.TemplateNameConstantPart> nameConstants, string resultName)
{
foreach (var item in nameConstants)
{
resultName = resultName.Replace($"%{item.Name}%", item.Value);
}
return resultName;
}
}
}

View File

@@ -123,13 +123,9 @@ namespace PARR.DAL.DomainServices.Implementations
var parentRelFilters = filter.RelationshipFilters.Where(rf => rf.IsParent).ToList();
var childRelFilters = filter.RelationshipFilters.Where(rf => !rf.IsParent).ToList();
var parentLinks = parentRelFilters.Any()
? await unitInUnitService.GetParentLinksByChildIdsAsync(initialUnitIds)
: new List<UnitInUnit>();
var parentLinks = await unitInUnitService.GetParentLinksByChildIdsAsync(initialUnitIds);
var childLinks = childRelFilters.Any()
? await unitInUnitService.GetChildLinksByParentIdsAsync(initialUnitIds)
: new List<UnitInUnit>();
var childLinks = await unitInUnitService.GetChildLinksByParentIdsAsync(initialUnitIds);
// 4 ID родителей и детей
var parentUnitIds = parentLinks.Select(l => l.ParentUnitId).ToHashSet();
@@ -251,7 +247,7 @@ namespace PARR.DAL.DomainServices.Implementations
logger.LogDebug("После RelationshipFilter осталось {Count} юнитов", candidateUnits.Count());
// 9 Umbrella-фильтр
// 9 Umbrella-фильтр
var finalUnits = candidateUnits.AsEnumerable();
if (job.Group.GroupType.Code == JobGroupTypesEnum.Umbrella)
{
@@ -452,45 +448,71 @@ namespace PARR.DAL.DomainServices.Implementations
var isParentDirection = job.IsParentRelationships == true;
if (min == 0 && max == int.MaxValue)
{
logger.LogDebug("RelationshipCountFilter: Min и Max не заданы — пропускаем фильтр.");
return units;
}
logger.LogDebug("RelationshipCountFilter: Min={Min}, Max={Max}, IsParent={IsParent}", min, max, isParentDirection);
// Определяем, есть ли фильтры по полям
var activeFilters = relationshipFilters
.Where(rf => rf.IsParent == isParentDirection && !string.IsNullOrWhiteSpace(rf.ValueMask))
.ToList();
if (activeFilters.Count == 0)
return units;
bool hasFieldFilters = activeFilters.Count > 0;
logger.LogDebug("RelationshipFilter: Min={Min}, Max={Max}, IsParent={IsParent}, Filters={Count}",
min, max, isParentDirection, activeFilters.Count);
logger.LogDebug("RelationshipCountFilter: Найдено {Count} фильтров по полям для направления {Direction}", activeFilters.Count, isParentDirection ? "Parent" : "Child");
return units.Where(dto =>
{
var links = isParentDirection ? dto.Parents : dto.Children;
if (links == null || !links.Any())
return min == 0;
{
var result = min == 0;
logger.LogDebug("UnitId {UnitId}: связей нет (null или пусто). Min={Min}, результат фильтра: {Result}", dto.Id, min, result);
return result;
}
logger.LogDebug("UnitId {UnitId}: {Count} связей до фильтрации", dto.Id, links.Count);
int matchingCount = 0;
foreach (var link in links)
if (hasFieldFilters)
{
bool hasMatch = link.Values.Any(v =>
activeFilters.Any(f =>
v.FieldId == f.FieldId &&
v.Value != null &&
v.Value.Contains(f.ValueMask, StringComparison.OrdinalIgnoreCase)
)
);
// Есть фильтры по полям → считаем только связанные юниты, подходящие под фильтр
foreach (var link in links)
{
bool hasMatch = link.Values.Any(v =>
activeFilters.Any(f =>
v.FieldId == f.FieldId &&
v.Value != null &&
v.Value.Contains(f.ValueMask, StringComparison.OrdinalIgnoreCase)
)
);
if (hasMatch)
matchingCount++;
if (hasMatch)
matchingCount++;
if (matchingCount > max)
break;
if (matchingCount > max)
{
logger.LogDebug("UnitId {UnitId}: matchingCount ({Count}) > max ({Max}) — прерываем подсчёт", dto.Id, matchingCount, max);
break;
}
}
}
else
{
// Нет фильтров по полям → считаем общее количество связей (без учёта значений)
matchingCount = links.Count;
logger.LogDebug("UnitId {UnitId}: нет фильтров по полям — matchingCount = links.Count = {Count}", dto.Id, matchingCount);
}
return matchingCount >= min && matchingCount <= max;
var finalResult = matchingCount >= min && matchingCount <= max;
logger.LogDebug("UnitId {UnitId}: matchingCount={Count}, Min={Min}, Max={Max}, результат фильтра: {Result}", dto.Id, matchingCount, min, max, finalResult);
return finalResult;
});
}