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;
});
}

View File

@@ -0,0 +1,10 @@
namespace PARR.DAL.DomainServices.Interfaces
{
public interface IGroupedShortcodesCacheService
{
Task<string> GetAggregatedValueAsync(
Guid unitId,
string shortcodeKey,
Func<Task<string>> computeIfMissing);
}
}

View File

@@ -1,15 +0,0 @@
using PARR.DAL.Models.Job;
using PARR.DAL.Models.Unit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PARR.DAL.DomainServices.Interfaces
{
public interface ITemplateNameGeneratorService
{
Task<string> GetTemplateNameAsync(Guid jobId, Guid unitId);
}
}

View File

@@ -1,10 +1,11 @@
using PARR.DAL.DomainModels;
using PARR.DAL.DomainServices.Shortcodes.Models;
namespace PARR.DAL.DomainServices.Interfaces
namespace PARR.DAL.DomainServices.Shortcodes
{
public interface IShortcodesService
{
Task<string> ApplyShortcodesAsync(string str, Guid unitId, Guid jobId, int? index = null);
Task<string> ApplyShortcodesAsync(string str, TemplateForShortcodes template);
bool IsAnyShortcodes(string str);

View File

@@ -0,0 +1,10 @@
namespace PARR.DAL.DomainServices.Shortcodes.Models
{
public class JobForShortcodes
{
public JobGroupForShortcodes? Group { get; set; }
public TnkForShortcodes? Tnk { get; set; }
public string WorkName { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,10 @@
namespace PARR.DAL.DomainServices.Shortcodes.Models
{
public class JobGroupForShortcodes
{
public Guid Id { get; set; }
public Guid? GroupingUnitFieldId { get; set; }
public JobGroupTypeForShortcodes? GroupType { get; set; }
public string GroupName { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,9 @@
using PARR.DAL.Contracts;
namespace PARR.DAL.DomainServices.Shortcodes.Models
{
public class JobGroupTypeForShortcodes
{
public JobGroupTypesEnum Code { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace PARR.DAL.DomainServices.Shortcodes.Models
{
public class TemplateForShortcodes
{
public Guid Id { get; set; }
public int? Index { get; set; }
public Guid JobId { get; set; }
public Guid UnitId { get; set; }
public JobForShortcodes? Job { get; set; }
public List<UnitInTemplateForShortcodes> UnitsInTemplate { get; set; } = new();
}
}

View File

@@ -0,0 +1,8 @@
namespace PARR.DAL.DomainServices.Shortcodes.Models
{
public class TnkForShortcodes
{
public string Name { get; set; } = string.Empty;
public string ShortName { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,7 @@
namespace PARR.DAL.DomainServices.Shortcodes.Models
{
public class UnitInTemplateForShortcodes
{
public Guid UnitId { get; set; }
}
}

View File

@@ -0,0 +1,470 @@
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.DomainServices.Shortcodes.Models;
using PARR.DAL.Models.Unit;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
using System.Text.RegularExpressions;
namespace PARR.DAL.DomainServices.Shortcodes
{
internal class ShortcodesService : IShortcodesService
{
private const string shortcodePattern = "%[^%\\s]+%";
private const string maxShortcodePattern = @"%МАКС:([а-яА-Яa-zA-Z0-9_]+)%";
private const string lettersShortcodePattern = @"%БУКВЫ:([^%]+)%";
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 ITemplateService templateService;
private readonly IGroupedShortcodesCacheService groupedShortcodesCacheService;
private readonly IUnitFilterService unitFilterService;
public ShortcodesService(
ILogger<ShortcodesService> logger,
SettingsFromDb settingsFromDb,
IJobService jobService,
IUnitService unitService,
IUnitFilterService unitFilterService,
IUnitInValueService unitInValueService,
IUnitFieldService unitFieldService,
ITemplateService templateService,
IGroupedShortcodesCacheService groupedShortcodesCacheService
)
{
this.logger = logger;
this.settingsFromDb = settingsFromDb;
this.jobService = jobService;
this.unitService = unitService;
this.unitInValueService = unitInValueService;
this.unitFieldService = unitFieldService;
this.templateService = templateService;
this.groupedShortcodesCacheService = groupedShortcodesCacheService;
this.unitFilterService = unitFilterService;
}
public async Task<string> ApplyShortcodesAsync(string str, TemplateForShortcodes template)
{
logger.LogDebug("Начата подстановка шорткодов. Вход: '{Input}', templateId={TemplateId}, index={Index}", str, template.Id, template.Index);
var job = template.Job;
if (job == null)
{
logger.LogError("Шаблон {TemplateId} не содержит Job. Подстановка прервана.", template.Id);
return str;
}
var unit = await unitService.Get().AsNoTracking().FirstOrDefaultAsync(u => u.Id == template.UnitId);
if (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, template.Index);
iteration++;
if (resultName == oldResult)
{
logger.LogDebug("Замена стандартных шорткодов не изменила строку на итерации {Iteration}. Останов.", iteration);
break;
}
}
if (iteration >= MaxStandardIterations)
{
logger.LogWarning(
"Достигнуто максимальное число итераций ({Max}) при замене стандартных шорткодов. Текущий результат: {Result}",
MaxStandardIterations, resultName);
}
// 2.5. %МАКС:FIELD% — только для групповых job (JobGroup.Type == Group)
if (job.Group != null && job.Group.GroupType != null && job.Group.GroupType!.Code == JobGroupTypesEnum.Group)
{
var maxShortcodes = Regex.Matches(resultName, maxShortcodePattern);
if (maxShortcodes.Count > 0)
{
resultName = await ReplaceMaxShortcodesAsync(job.Group.Id, template.UnitId, resultName, maxShortcodes); // ✅ Исправлено: job.GroupId
}
}
// 2.6. %БУКВЫ:FIELD% — извлекает только буквы из значения поля
var lettersShortcodes = Regex.Matches(resultName, lettersShortcodePattern);
if (lettersShortcodes.Count > 0)
{
resultName = await ReplaceLettersShortcodesAsync(template.UnitId, resultName, lettersShortcodes);
}
// 2.7. %ГРОЛЕ-ПН% — нумерованный список UnitsInTemplate с GroupingUnitFieldId
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%ГРОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase)))
{
var unitsInTemplate = template.UnitsInTemplate;
if (unitsInTemplate == null || !unitsInTemplate.Any())
{
logger.LogDebug("Шаблон {TemplateId} не содержит UnitsInTemplate. %ГРОЛЕ-ПН% заменён на пустую строку.", template.Id);
resultName = Regex.Replace(resultName, "%ГРОЛЕ-ПН%", "", RegexOptions.IgnoreCase);
}
else
{
var unitIds = unitsInTemplate.Select(uit => uit.UnitId).ToList();
var units = await unitService.Get()
.AsNoTracking()
.Where(u => unitIds.Contains(u.Id))
.ToListAsync();
var groupingFieldId = job.Group?.GroupingUnitFieldId;
Dictionary<Guid, string> valuesByUnit = new();
if (groupingFieldId.HasValue)
{
var fieldValues = await unitInValueService.Get()
.AsNoTracking()
.Include(uv => uv.Value)
.Where(uv =>
uv.FieldId == groupingFieldId.Value &&
unitIds.Contains(uv.UnitId) &&
uv.Value != null &&
!string.IsNullOrWhiteSpace(uv.Value.Value))
.Select(uv => new { uv.UnitId, Value = uv.Value.Value })
.ToListAsync();
valuesByUnit = fieldValues
.GroupBy(x => x.UnitId)
.ToDictionary(
g => g.Key,
g => string.Join(", ", g.Select(v => v.Value).OrderBy(v => v))
);
}
var lines = unitsInTemplate
.Select((uit, indexInList) =>
{
var unitInList = units.FirstOrDefault(u => u.Id == uit.UnitId);
var unitName = unitInList?.Name ?? $"(UnitId={uit.UnitId})";
var valuesStr = valuesByUnit.TryGetValue(uit.UnitId, out var vals) ? vals : "";
return $"{indexInList + 1}. {unitName} ({valuesStr})";
})
.ToList();
var resultText = string.Join("\n", lines);
resultName = Regex.Replace(resultName, "%ГРОЛЕ-ПН%", resultText, RegexOptions.IgnoreCase);
}
}
// 3. %СВЯЗИ% или %СВЯЗИ-ПН% (если всё ещё зависят от jobId/unitId)
List<string>? relatedUnitNames = null;
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ%", StringComparison.OrdinalIgnoreCase)))
{
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(template.JobId, template.UnitId);
var linksText = string.Join("\n", relatedUnitNames);
resultName = Regex.Replace(resultName, "%СВЯЗИ%", linksText, RegexOptions.IgnoreCase);
}
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ-ПН%", StringComparison.OrdinalIgnoreCase)))
{
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(template.JobId, template.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(template.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 },
new ShortcodeInfoDto { Shortcode = "%МАКС:ИМЯ АТРИБУТА%",
Description = "Используется только с групповым типом работ. Наиболее часто встречающееся значение поля в группе (игнорирует пустые). Пример: %МАКС:РАБОЧАЯ_ГР_ОТВ_ЗАК%",
Type = ShortcodeTypeEnum.Standart },
new ShortcodeInfoDto { Shortcode = "%ГРОЛЕ-ПН%",
Description = "Нумерованный список unit-ов из шаблона: 1. ЭК-123 (Значение1, Значение2). Использует GroupingUnitFieldId из JobGroup.",
Type = ShortcodeTypeEnum.Relationship },
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)
{
var requiredFieldNames = shortcodesInMask
.Select(m => m.Value.Trim('%').ToUpperInvariant())
.ToList();
if (requiredFieldNames.Count == 0)
return resultName;
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, requiredFieldNames);
var fieldValuesMap = fieldValues
.GroupBy(x => x.FieldName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(
g => g.Key,
g => g.Select(x => x.Value).ToList(),
StringComparer.OrdinalIgnoreCase);
foreach (var match in shortcodesInMask)
{
var fieldName = match.Value.Trim('%').ToUpperInvariant();
if (fieldValuesMap.TryGetValue(fieldName, out var values))
{
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(JobForShortcodes 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;
}
private async Task<string> ReplaceMaxShortcodesAsync(Guid jobGroupId, Guid unitId, string input, MatchCollection maxShortcodes)
{
var shortcodeToMatches = maxShortcodes
.Cast<Match>()
.GroupBy(m => m.Value, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
foreach (var kvp in shortcodeToMatches)
{
var fullShortcode = kvp.Key;
var matches = kvp.Value;
var fieldName = fullShortcode.Trim('%').Split(':', 2)[1].Trim(); // "РАБОЧАЯ_ГР_ОТВ_ЗАК"
logger.LogDebug("Обработка {Shortcode} для JobGroup {JobGroupId}, Template.UnitId {UnitId}",
fullShortcode, jobGroupId, unitId);
var mostFrequentValue = await groupedShortcodesCacheService.GetAggregatedValueAsync(
unitId,
fullShortcode,
async () =>
{
// Логика вычисления, если кэш пуст
var unitIds = await jobService.Get()
.Where(j => j.GroupId == jobGroupId)
.Join(
templateService.Get()
.Where(t => t.StatusTypeId == TemplateStatusTypeEnum.Used)
.Include(t => t.UnitsInTemplate),
job => job.Id,
template => template.JobId,
(job, template) => template
)
.SelectMany(template => template.UnitsInTemplate)
.Select(uit => uit.UnitId)
.Distinct()
.ToListAsync();
// Вызываем метод из сервиса
var result = await unitInValueService.GetMostFrequentValueForFieldAsync(unitIds, fieldName);
return result ?? string.Empty;
});
foreach (var match in matches)
{
input = input.Replace(match.Value, mostFrequentValue);
}
}
return input;
}
private async Task<string> ReplaceLettersShortcodesAsync(Guid unitId, string input, MatchCollection lettersShortcodes)
{
var shortcodeToMatches = lettersShortcodes
.Cast<Match>()
.GroupBy(m => m.Value, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.ToList(), StringComparer.OrdinalIgnoreCase);
foreach (var kvp in shortcodeToMatches)
{
var fullShortcode = kvp.Key; // например, "%БУКВЫ:ЗОНА_ОТВЕТСТВЕННОСТИ%"
var matches = kvp.Value;
var fieldName = fullShortcode.Trim('%').Split(':', 2)[1].Trim(); // "ЗОНА_ОТВЕТСТВЕННОСТИ"
logger.LogDebug("Обработка {Shortcode} для unitId {UnitId}, fieldName {FieldName}", fullShortcode, unitId, fieldName);
// Получаем значение поля через unitInValueService.GetFieldValuesAsync
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, new List<string> { fieldName });
string extractedLetters = string.Empty;
if (fieldValues.Any())
{
var value = fieldValues.First().Value; // Берём первое значение, если несколько
if (value != null)
{
extractedLetters = ExtractLettersOnly(value);
logger.LogDebug("Извлечены буквы: '{Letters}' из значения '{Value}'", extractedLetters, value);
}
}
if (string.IsNullOrEmpty(extractedLetters))
{
logger.LogDebug("Для шорткода {Shortcode} не найдено подходящее значение или из него нельзя извлечь буквы", fullShortcode);
}
foreach (var match in matches)
{
input = input.Replace(match.Value, extractedLetters);
}
}
return input;
}
private static string ExtractLettersOnly(string input)
{
var result = new System.Text.StringBuilder();
foreach (char c in input)
{
if (char.IsLetter(c))
{
result.Append(c);
}
}
return result.ToString();
}
}
}