feat(dal): добавлен Shortcode "%СВЯЗИ-ПН%", добавлен метод GetAvailableShortcodesAsync для отображения доступных изменямеых частей в API
This commit is contained in:
11
PARR.DAL/DomainModels/ShortcodeInfoDto.cs
Normal file
11
PARR.DAL/DomainModels/ShortcodeInfoDto.cs
Normal file
@@ -0,0 +1,11 @@
|
||||
using PARR.Constants;
|
||||
|
||||
namespace PARR.DAL.DomainModels
|
||||
{
|
||||
public class ShortcodeInfoDto
|
||||
{
|
||||
public required string Shortcode { get; set; }
|
||||
public required string Description { get; set; }
|
||||
public ShortcodeTypeEnum Type { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
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;
|
||||
@@ -16,13 +18,15 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
|
||||
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(
|
||||
@@ -30,19 +34,23 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
SettingsFromDb settingsFromDb,
|
||||
IJobService jobService,
|
||||
IUnitService unitService,
|
||||
IUnitFilterService unitFilterService
|
||||
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)
|
||||
{
|
||||
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
|
||||
logger.LogDebug("Начата подстановка шорткодов. Вход: '{Input}', unitId={UnitId}, jobId={JobId}", str, unitId, jobId);
|
||||
|
||||
var job = await jobService
|
||||
.Get().AsNoTracking()
|
||||
@@ -64,60 +72,174 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
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. Стандартные шорткоды (%ЭК%, %РАБОТА% и т.д.)
|
||||
if (shortcodesInMask.Any(m => SupportedShortcodes.Contains(m.Value)))
|
||||
// 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);
|
||||
iteration++;
|
||||
|
||||
// Защита от "бесполезных" итераций (строка не изменилась)
|
||||
if (resultName == oldResult)
|
||||
{
|
||||
logger.LogWarning("Замена стандартных шорткодов не изменила строку на итерации {Iteration}. Останов.", iteration);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. %СВЯЗИ% — отдельная обработка
|
||||
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)))
|
||||
{
|
||||
var relatedUnitNames = await unitFilterService.GetRelatedUnitNamesAsync(jobId, unitId);
|
||||
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(jobId, unitId);
|
||||
var linksText = string.Join("\n", relatedUnitNames);
|
||||
resultName = Regex.Replace(resultName, "%СВЯЗИ%", linksText, RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
// 4. Поля (оставшиеся %FIELD_NAME%)
|
||||
// 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)
|
||||
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 }
|
||||
});
|
||||
|
||||
// 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 unitWithFields = await unitService.Get()
|
||||
.AsNoTracking()
|
||||
.Include(u => u.UnitValues)
|
||||
.ThenInclude(uv => uv.Field)
|
||||
.Include(u => u.UnitValues)
|
||||
.ThenInclude(uv => uv.Value)
|
||||
.FirstOrDefaultAsync(t => t.Id == unitId);
|
||||
// 1. Извлекаем имена полей из шорткодов: %IP_АДРЕС% → "IP_АДРЕС"
|
||||
var requiredFieldNames = shortcodesInMask
|
||||
.Select(m => m.Value.Trim('%').ToUpper())
|
||||
.ToList();
|
||||
|
||||
foreach (var item in shortcodesInMask)
|
||||
if (requiredFieldNames.Count == 0)
|
||||
return resultName;
|
||||
|
||||
// 2. Получаем только нужные значения
|
||||
var fieldValueMap = await unitInValueService.GetFieldValuesAsync(unitId, requiredFieldNames);
|
||||
|
||||
// 3. Подставляем значения
|
||||
foreach (var match in shortcodesInMask)
|
||||
{
|
||||
var fieldName = item.Value.Replace("%", "").ToUpper();
|
||||
|
||||
var value = unitWithFields!.UnitValues!.FirstOrDefault(t => t.Field!.AihitName!.ToUpper() == fieldName!);
|
||||
|
||||
if (value != null)
|
||||
resultName = resultName.Replace(item.Value, value!.Value!.Value);
|
||||
var fieldName = match.Value.Trim('%').ToUpper();
|
||||
if (fieldValueMap.TryGetValue(fieldName, out var fieldValue))
|
||||
resultName = resultName.Replace(match.Value, fieldValue);
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Поле '{FieldName}' не найдено для unitId={UnitId} при подстановке шорткода '{Shortcode}'",
|
||||
fieldName, unitId, match.Value);
|
||||
}
|
||||
}
|
||||
|
||||
return resultName;
|
||||
@@ -144,12 +266,5 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
|
||||
return resultName;
|
||||
}
|
||||
|
||||
|
||||
private static List<Match> GetShortCodes(string resultName)
|
||||
{
|
||||
var shortcodesInMask = Regex.Matches(resultName, shortcodePattern).ToList();
|
||||
return shortcodesInMask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
namespace PARR.DAL.DomainServices.Interfaces
|
||||
using PARR.DAL.DomainModels;
|
||||
|
||||
namespace PARR.DAL.DomainServices.Interfaces
|
||||
{
|
||||
public interface IShortcodesService
|
||||
{
|
||||
Task<string> ApplyShortcodesAsync(string str, Guid unitId, Guid jobId);
|
||||
|
||||
bool isAnyShortcodes(string str);
|
||||
bool IsAnyShortcodes(string str);
|
||||
|
||||
Task<List<ShortcodeInfoDto>> GetAvailableShortcodesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,9 +31,40 @@ namespace PARR.DAL.Services.Implementations.Unit
|
||||
public async Task<List<UnitInValue>> GetByUnitIdsAsync(IEnumerable<Guid> unitIds)
|
||||
{
|
||||
return await dataContext.UnitInValues.AsNoTracking()
|
||||
.Include(t=>t.Value)
|
||||
.Include(t => t.Value)
|
||||
.Where(uv => unitIds.Contains(uv.UnitId))
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
|
||||
public async Task<Dictionary<string, string>> GetFieldValuesAsync(Guid unitId, IReadOnlyCollection<string> aihitNames)
|
||||
{
|
||||
if (aihitNames == null || aihitNames.Count == 0)
|
||||
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var result = await dataContext.UnitInValues
|
||||
.AsNoTracking()
|
||||
.AsSplitQuery()
|
||||
.Where(uiv => uiv.UnitId == unitId
|
||||
&& uiv.Field != null
|
||||
&& uiv.Value != null
|
||||
&& aihitNames.Contains(uiv.Field.AihitName.ToUpper()))
|
||||
.ToDictionaryAsync(
|
||||
uiv => uiv.Field!.AihitName.ToUpper(),
|
||||
uiv => uiv.Value!.Value ?? "",
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// Журналируем если не нашли поля
|
||||
var missing = aihitNames
|
||||
.Where(name => !result.ContainsKey(name.ToUpper()))
|
||||
.ToList();
|
||||
if (missing.Any())
|
||||
{
|
||||
logger.LogDebug("UnitInValueService: поля не найдены для unitId={UnitId}: {Fields}",
|
||||
unitId, string.Join(", ", missing));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
using PARR.DAL.Models.Unit;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PARR.DAL.Services.Interfaces.Unit
|
||||
{
|
||||
@@ -11,5 +6,6 @@ namespace PARR.DAL.Services.Interfaces.Unit
|
||||
{
|
||||
Task<List<UnitInValue>> GetByUnitIdsAsync(IEnumerable<Guid> unitIds);
|
||||
Task<List<UnitInValue>> GetByUnitIdAsync(Guid unitId);
|
||||
Task<Dictionary<string, string>> GetFieldValuesAsync(Guid unitId, IReadOnlyCollection<string> aihitNames);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user