feat(dal): ShortcodesService добавлена обработка динамичесих составляющих "%СВЯЗИ%", "%ТНК-КРАТКО%"
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.DAL.Contracts;
|
||||
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;
|
||||
@@ -10,65 +13,84 @@ 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 IUnitFilterService unitFilterService;
|
||||
|
||||
public ShortcodesService(
|
||||
ILogger<ShortcodesService> logger,
|
||||
SettingsFromDb settingsFromDb,
|
||||
IJobService jobService,
|
||||
IUnitService unitService
|
||||
IUnitService unitService,
|
||||
IUnitFilterService unitFilterService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.settingsFromDb = settingsFromDb;
|
||||
this.jobService = jobService;
|
||||
this.unitService = unitService;
|
||||
this.unitFilterService = unitFilterService;
|
||||
}
|
||||
|
||||
public async Task<string> ApplyShortcodesAsync(string str, Guid unitId, Guid jobId)
|
||||
{
|
||||
//TODO удалить старый в GeneralExtesions, связанные с ним Enum и написать метод. делов...
|
||||
|
||||
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
|
||||
|
||||
var job = await jobService
|
||||
.Get().AsNoTracking()
|
||||
.Include(t=>t.Tnk)
|
||||
.Include(t=>t.Group)
|
||||
.FirstOrDefaultAsync(t => t.Id == jobId);
|
||||
.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(t => t.Id == unitId);
|
||||
var unit = await unitService.Get().AsNoTracking().FirstOrDefaultAsync(u => u.Id == unitId);
|
||||
|
||||
if (job != null && unit != null && job.TemplateNameMask != null)
|
||||
if (job == null || unit == null || string.IsNullOrEmpty(str))
|
||||
{
|
||||
var resultName = str;
|
||||
|
||||
var shortcodesInMask = GetShortCodes(resultName);
|
||||
|
||||
//Проверяем и меняем наличие статичных частей в маске имени шаблона
|
||||
if (shortcodesInMask.Any(x => nameConstants.Select(x => "%" + x.Name + "%").ToList().Contains(x.Value)))
|
||||
{
|
||||
resultName = ReplaceConstants(nameConstants, resultName);
|
||||
}
|
||||
|
||||
//Проверяем и меняем Shortcodes в маске имени шаблона
|
||||
var shortCodes = GetShortcodesNames();
|
||||
if (shortcodesInMask.Any(x => shortCodes.Select(x => x).ToList().Contains(x.Value)))
|
||||
{
|
||||
resultName = ReplaceShortcodes(job, unit, resultName, shortcodesInMask);
|
||||
}
|
||||
|
||||
//Если остались %переменные% проверяем совпадение по имени поля
|
||||
shortcodesInMask = GetShortCodes(resultName);
|
||||
if (shortcodesInMask.Count > 0)
|
||||
{
|
||||
resultName = await ReplaceFieldValues(unitId, resultName, shortcodesInMask);
|
||||
}
|
||||
|
||||
return resultName;
|
||||
logger.LogError("Переданы некорректные данные для подстановки динамических записей");
|
||||
return str;
|
||||
}
|
||||
|
||||
return "";
|
||||
var resultName = str;
|
||||
var shortcodesInMask = GetShortCodes(resultName);
|
||||
|
||||
// 1. Статические константы
|
||||
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)))
|
||||
{
|
||||
resultName = ReplaceStandardShortcodes(job, unit, resultName);
|
||||
}
|
||||
|
||||
// 3. %СВЯЗИ% — отдельная обработка
|
||||
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ%", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var relatedUnitNames = await unitFilterService.GetRelatedUnitNamesAsync(jobId, unitId);//GetRelatedUnitNamesAsync(job, unit);
|
||||
var linksText = string.Join("\n", relatedUnitNames);
|
||||
resultName = Regex.Replace(resultName, "%СВЯЗИ%", linksText, RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
// 4. Поля (оставшиеся %FIELD_NAME%)
|
||||
shortcodesInMask = GetShortCodes(resultName);
|
||||
if (shortcodesInMask.Count > 0)
|
||||
{
|
||||
resultName = await ReplaceFieldValues(unitId, resultName, shortcodesInMask);
|
||||
}
|
||||
|
||||
return resultName;
|
||||
}
|
||||
|
||||
|
||||
@@ -102,21 +124,14 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
}
|
||||
|
||||
|
||||
private static string ReplaceShortcodes(Models.Job.Job job, Models.Unit.Unit unit, string resultName, List<Match> shortcodesInMask)
|
||||
private static string ReplaceStandardShortcodes(Job job, Unit unit, string input)
|
||||
{
|
||||
if (shortcodesInMask.Any(x => x.Value == "%ЭК%"))
|
||||
resultName = resultName.Replace("%ЭК%", unit.Name);
|
||||
|
||||
if (shortcodesInMask.Any(x => x.Value == "%ГРУППА_РАБОТ%"))
|
||||
resultName = resultName.Replace("%ГРУППА_РАБОТ%", job.Group!.GroupName);
|
||||
|
||||
if (shortcodesInMask.Any(x => x.Value == "%РАБОТА%"))
|
||||
resultName = resultName.Replace("%РАБОТА%", job.WorkName);
|
||||
|
||||
if (shortcodesInMask.Any(x => x.Value == "%ТНК%"))
|
||||
resultName = resultName.Replace("%ТНК%", job.Tnk!.Name);
|
||||
|
||||
return resultName;
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -136,17 +151,5 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
var shortcodesInMask = Regex.Matches(resultName, shortcodePattern).ToList();
|
||||
return shortcodesInMask;
|
||||
}
|
||||
|
||||
private List<string> GetShortcodesNames()
|
||||
{
|
||||
var result = new List<string> {
|
||||
"%ЭК%",
|
||||
"%ГРУППА_РАБОТ%",
|
||||
"%РАБОТА%",
|
||||
"%ТНК%"
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.DAL.Context;
|
||||
using PARR.DAL.Contracts;
|
||||
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
|
||||
{
|
||||
@@ -15,75 +15,54 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
private readonly ILogger<UnitFilterService> logger;
|
||||
private readonly IJobService jobService;
|
||||
private readonly IUnitService unitService;
|
||||
private readonly IUnitInUnitService unitInUnitService;
|
||||
private readonly IUnitInValueService unitInValueService;
|
||||
|
||||
public UnitFilterService(
|
||||
ILogger<UnitFilterService> logger,
|
||||
IJobService jobService,
|
||||
IUnitService unitService
|
||||
)
|
||||
IUnitService unitService,
|
||||
IUnitInUnitService unitInUnitService,
|
||||
IUnitInValueService unitInValueService)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.jobService = jobService;
|
||||
this.unitService = unitService;
|
||||
this.unitInUnitService = unitInUnitService;
|
||||
this.unitInValueService = unitInValueService;
|
||||
}
|
||||
|
||||
|
||||
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId, int? takeCount = null)
|
||||
{
|
||||
var job = await jobService
|
||||
.Get().AsNoTracking()
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.GroupType)
|
||||
.FirstOrDefaultAsync(t => t.Id == jobId);
|
||||
.Get().AsNoTracking()
|
||||
.Include(j => j.UnitFilters).ThenInclude(uf => uf.FieldFilters)
|
||||
.Include(j => j.UnitFilters).ThenInclude(uf => uf.RelationshipFilters)
|
||||
.Include(j => j.Group).ThenInclude(g => g.GroupType)
|
||||
.FirstOrDefaultAsync(j => j.Id == jobId);
|
||||
|
||||
if (job == null)
|
||||
return null;
|
||||
|
||||
return await GetUnitsIdByJobFilterAsync(job, takeCount);
|
||||
return job == null ? null : await GetUnitsIdByJobFilterAsync(job, takeCount);
|
||||
}
|
||||
|
||||
|
||||
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Job job, int? takeCount = null)
|
||||
{
|
||||
#region проверка инклудов
|
||||
#region Проверка обязательных зависимостей
|
||||
if (job.Group == null)
|
||||
{
|
||||
logger.LogWarning("JobId={JobId} не содержит Group - пропускаем фильтрацию", job.Id);
|
||||
throw new ArgumentNullException(nameof(Group));
|
||||
}
|
||||
|
||||
throw new ArgumentNullException(nameof(job.Group), $"Job {job.Id} не содержит Group");
|
||||
if (job.Group.GroupType == null)
|
||||
{
|
||||
logger.LogWarning("JobId={JobId} не содержит GroupType - пропускаем фильтрацию", job.Id);
|
||||
throw new ArgumentNullException(nameof(JobGroupType));
|
||||
}
|
||||
|
||||
throw new ArgumentNullException(nameof(job.Group.GroupType), $"Job {job.Id} не содержит GroupType");
|
||||
if (job.UnitFilters == null || !job.UnitFilters.Any())
|
||||
{
|
||||
logger.LogWarning("JobId={JobId} не содержит UnitFilters - пропускаем фильтрацию", job.Id);
|
||||
throw new ArgumentNullException(nameof(JobUnitFilter));
|
||||
}
|
||||
throw new ArgumentNullException(nameof(job.UnitFilters), $"Job {job.Id} не содержит UnitFilters");
|
||||
#endregion
|
||||
|
||||
var maxCount = takeCount ?? int.MaxValue;
|
||||
var collectedIds = new HashSet<Guid>(); // ← гарантирует уникальность
|
||||
var collectedIds = new HashSet<Guid>();
|
||||
var filterNumber = 0;
|
||||
|
||||
foreach (var filter in job.UnitFilters)
|
||||
{
|
||||
filterNumber++;
|
||||
|
||||
// Прекращаем, если набрали достаточно
|
||||
if (collectedIds.Count >= maxCount)
|
||||
{
|
||||
logger.LogDebug("Достигнут лимит takeCount={TakeCount} после {FilterCount} фильтров", maxCount, filterNumber - 1);
|
||||
break;
|
||||
}
|
||||
|
||||
if (collectedIds.Count >= maxCount) break;
|
||||
var remaining = maxCount - collectedIds.Count;
|
||||
if (remaining <= 0) break;
|
||||
|
||||
@@ -91,183 +70,34 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
{
|
||||
logger.LogDebug("Применяем фильтр #{Index} (Id={FilterId})", filterNumber, filter.Id);
|
||||
|
||||
// Стартуем с базового условия — имя Unit'а
|
||||
var query = unitService.Get().AsNoTracking()
|
||||
.Where(unit => EF.Functions.ILike(unit.Name, filter.UnitFilter));
|
||||
.Where(unit => EF.Functions.Like(unit.Name, filter.UnitFilter));
|
||||
|
||||
logger.LogDebug("Базовый фильтр по Name: {NameFilter}", filter.UnitFilter);
|
||||
|
||||
// 1. Фильтры по полям (UnitValues)
|
||||
foreach (var fieldFilter in filter.FieldFilters)
|
||||
{
|
||||
var fieldId = fieldFilter.FieldId;
|
||||
var valueMask = fieldFilter.ValueMask;
|
||||
|
||||
logger.LogDebug("Фильтр по полю: FieldId={FieldId}, ValueMask={ValueMask}", fieldId, valueMask);
|
||||
|
||||
query = query.Where(unit =>
|
||||
unit.UnitValues.Any(value =>
|
||||
value.FieldId == fieldId
|
||||
&& value.Value != null
|
||||
&& value.Value.Value != null
|
||||
&& EF.Functions.ILike(value.Value.Value, valueMask)));
|
||||
query = ApplyFieldFilter(query, fieldFilter);
|
||||
}
|
||||
|
||||
// 2. Фильтры по связям (родителям и детям)
|
||||
foreach (var relFilter in filter.RelationshipFilters)
|
||||
{
|
||||
var fieldId = relFilter.FieldId;
|
||||
var valueMask = relFilter.ValueMask;
|
||||
|
||||
logger.LogDebug("Фильтр по связи: IsParent={IsParent}, IsInverse={IsInverse}, IsFullMatch={IsFullMatch}, FieldId={FieldId}, ValueMask={ValueMask}",
|
||||
relFilter.IsParent, relFilter.IsInverse, relFilter.IsFullMatch, relFilter.FieldId, relFilter.ValueMask);
|
||||
|
||||
if (relFilter.IsParent)
|
||||
{
|
||||
if (relFilter.IsInverse)
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
// Все родители НЕ должны иметь такое значение
|
||||
query = query.Where(unit =>
|
||||
!unit.ParentUnits.Any() || // если связей нет — подходит
|
||||
unit.ParentUnits.All(parentLink =>
|
||||
!parentLink.ParentUnit!.UnitValues.Any(parentValue =>
|
||||
parentValue.FieldId == fieldId
|
||||
&& parentValue.Value != null
|
||||
&& parentValue.Value.Value != null
|
||||
&& EF.Functions.ILike(parentValue.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Хотя бы один родитель НЕ должен иметь такое значение
|
||||
query = query.Where(unit =>
|
||||
!unit.ParentUnits.Any() ||
|
||||
unit.ParentUnits.Any(parentLink =>
|
||||
!parentLink.ParentUnit!.UnitValues.Any(parentValue =>
|
||||
parentValue.FieldId == fieldId
|
||||
&& parentValue.Value != null
|
||||
&& parentValue.Value.Value != null
|
||||
&& EF.Functions.ILike(parentValue.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Прямой фильтр: связанные Unit'ы ДОЛЖНЫ иметь значение
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
// Все родители должны иметь такое значение
|
||||
query = query.Where(unit =>
|
||||
!unit.ParentUnits.Any() ||
|
||||
unit.ParentUnits.All(parentLink =>
|
||||
parentLink.ParentUnit!.UnitValues.Any(parentValue =>
|
||||
parentValue.FieldId == fieldId
|
||||
&& parentValue.Value != null
|
||||
&& parentValue.Value.Value != null
|
||||
&& EF.Functions.ILike(parentValue.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Хотя бы один родитель должен иметь такое значение
|
||||
query = query.Where(unit =>
|
||||
unit.ParentUnits.Any(parentLink =>
|
||||
parentLink.ParentUnit!.UnitValues.Any(parentValue =>
|
||||
parentValue.FieldId == fieldId
|
||||
&& parentValue.Value != null
|
||||
&& parentValue.Value.Value != null
|
||||
&& EF.Functions.ILike(parentValue.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// relFilter.IsParent == false → работаем с детьми (ChildUnits)
|
||||
if (relFilter.IsInverse)
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
query = query.Where(unit =>
|
||||
!unit.ChildUnits.Any() ||
|
||||
unit.ChildUnits.All(childLink =>
|
||||
!childLink.ChildUnit!.UnitValues.Any(childValue =>
|
||||
childValue.FieldId == fieldId
|
||||
&& childValue.Value != null
|
||||
&& childValue.Value.Value != null
|
||||
&& EF.Functions.ILike(childValue.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
query = query.Where(unit =>
|
||||
!unit.ChildUnits.Any() ||
|
||||
unit.ChildUnits.Any(childLink =>
|
||||
!childLink.ChildUnit!.UnitValues.Any(childValue =>
|
||||
childValue.FieldId == fieldId
|
||||
&& childValue.Value != null
|
||||
&& childValue.Value.Value != null
|
||||
&& EF.Functions.ILike(childValue.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
query = query.Where(unit =>
|
||||
!unit.ChildUnits.Any() ||
|
||||
unit.ChildUnits.All(childLink =>
|
||||
childLink.ChildUnit!.UnitValues.Any(childValue =>
|
||||
childValue.FieldId == fieldId
|
||||
&& childValue.Value != null
|
||||
&& childValue.Value.Value != null
|
||||
&& EF.Functions.ILike(childValue.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
query = query.Where(unit =>
|
||||
unit.ChildUnits.Any(childLink =>
|
||||
childLink.ChildUnit!.UnitValues.Any(childValue =>
|
||||
childValue.FieldId == fieldId
|
||||
&& childValue.Value != null
|
||||
&& childValue.Value.Value != null
|
||||
&& EF.Functions.ILike(childValue.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
}
|
||||
query = ApplyRelationshipFilterToQuery(query, relFilter);
|
||||
}
|
||||
|
||||
// 3. Ограничение по количеству связей (только для umbrella-групп)
|
||||
if (job.Group.GroupType.Code == JobGroupTypesEnum.Umbrella)
|
||||
{
|
||||
int min = job.MinValueRelationships.GetValueOrDefault(0);
|
||||
int max = job.MaxValueRelationships.GetValueOrDefault(int.MaxValue);
|
||||
|
||||
logger.LogDebug("Фильтр по количеству связей: Min={Min}, Max={Max}, IsParent={IsParent}", min, max, job.IsParentRelationships);
|
||||
|
||||
if (job.IsParentRelationships == true)
|
||||
{
|
||||
query = query.Where(unit =>
|
||||
unit.ParentUnits.Count >= min && unit.ParentUnits.Count <= max);
|
||||
}
|
||||
else
|
||||
{
|
||||
query = query.Where(unit =>
|
||||
unit.ChildUnits.Count >= min && unit.ChildUnits.Count <= max);
|
||||
}
|
||||
query = ApplyRelationshipCountFilter(query, job);
|
||||
}
|
||||
|
||||
// Выполняем — только Id, с учётом оставшегося лимита
|
||||
var newIds = await query
|
||||
.Select(unit => unit.Id)
|
||||
.Select(u => u.Id)
|
||||
.Take(remaining)
|
||||
.ToListAsync();
|
||||
|
||||
logger.LogDebug("Фильтр #{Index}: найдено {Count} Unit'ов", filterNumber, newIds.Count);
|
||||
|
||||
collectedIds.UnionWith(newIds);
|
||||
|
||||
logger.LogDebug(
|
||||
"Фильтр #{Index} (Id={FilterId}): найдено {Count} Unit'ов. Всего: {Total}",
|
||||
filterNumber, filter.Id, newIds.Count, collectedIds.Count);
|
||||
|
||||
logger.LogDebug("Фильтр #{Index}: найдено {Count} Unit'ов. Всего: {Total}",
|
||||
filterNumber, newIds.Count, collectedIds.Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -282,5 +112,265 @@ namespace PARR.DAL.DomainServices.Implementations
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<List<string>> GetRelatedUnitNamesAsync(Guid jobId, Guid unitId)
|
||||
{
|
||||
logger.LogDebug("Начало GetRelatedUnitNamesAsync. JobId: {JobId}, UnitId: {UnitId}", jobId, unitId);
|
||||
|
||||
var job = await jobService
|
||||
.Get().AsNoTracking()
|
||||
.Include(j => j.UnitFilters).ThenInclude(uf => uf.RelationshipFilters)
|
||||
.FirstOrDefaultAsync(j => j.Id == jobId);
|
||||
|
||||
if (job == null)
|
||||
{
|
||||
logger.LogWarning("Job с Id {JobId} не найден.", jobId);
|
||||
throw new ArgumentException($"Job {jobId} не найден.", nameof(jobId));
|
||||
}
|
||||
|
||||
logger.LogDebug("Найден Job: {JobName}. Количество UnitFilters: {FilterCount}", job.Name, job.UnitFilters.Count());
|
||||
|
||||
var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var filter in job.UnitFilters)
|
||||
{
|
||||
if (!filter.RelationshipFilters.Any())
|
||||
{
|
||||
logger.LogDebug("UnitFilter.Id {FilterId} не содержит RelationshipFilters. Пропускаем.", filter.Id);
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.LogDebug("Обработка UnitFilter.Id {FilterId}. Количество RelationshipFilters: {RelFilterCount}", filter.Id, filter.RelationshipFilters.Count());
|
||||
|
||||
foreach (var rf in filter.RelationshipFilters)
|
||||
{
|
||||
logger.LogDebug("Обработка RelationshipFilter (UnitFilterId={UnitFilterId}): IsParent={IsParent}, FieldId={FieldId}, ValueMask={ValueMask}",
|
||||
rf.UnitFilterId, rf.IsParent, rf.FieldId, rf.ValueMask);
|
||||
|
||||
var valueMask = rf.ValueMask?.Trim();
|
||||
if (string.IsNullOrEmpty(valueMask))
|
||||
{
|
||||
logger.LogDebug("ValueMask пуст. Пропускаем фильтр (UnitFilterId={UnitFilterId}).", rf.UnitFilterId);
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- НОВАЯ ЛОГИКА: Используем новые сервисы ---
|
||||
|
||||
List<UnitInUnit> relevantLinks;
|
||||
if (rf.IsParent)
|
||||
{
|
||||
// u - родитель, его ребёнок - unitId
|
||||
relevantLinks = await unitInUnitService.GetByChildIdAsync(unitId);
|
||||
}
|
||||
else
|
||||
{
|
||||
// u - ребёнок, его родитель - unitId
|
||||
relevantLinks = await unitInUnitService.GetByParentIdAsync(unitId);
|
||||
}
|
||||
|
||||
logger.LogDebug("Найдено {Count} связей через UnitInUnitService.", relevantLinks.Count);
|
||||
|
||||
// Получаем Id юнитов, которые участвуют в связях (дети или родители)
|
||||
var unitIdsToCheck = rf.IsParent
|
||||
? relevantLinks.Select(l => l.ParentUnitId).ToList()
|
||||
: relevantLinks.Select(l => l.ChildUnitId).ToList();
|
||||
|
||||
if (!unitIdsToCheck.Any())
|
||||
{
|
||||
logger.LogDebug("Нет юнитов для проверки значений.");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Получаем значения полей для этих юнитов
|
||||
var unitValues = await unitInValueService.GetByUnitIdsAsync(unitIdsToCheck);
|
||||
|
||||
logger.LogDebug("Получено {Count} значений полей через UnitInValueService.", unitValues.Count);
|
||||
|
||||
// Фильтруем юниты, у которых есть нужное значение
|
||||
var matchingUnitIds = unitValues
|
||||
.Where(uv => uv.FieldId == rf.FieldId
|
||||
&& uv.Value != null
|
||||
&& uv.Value.Value != null
|
||||
&& uv.Value.Value.ToString()!.Contains(valueMask, StringComparison.OrdinalIgnoreCase))
|
||||
.Select(uv => uv.UnitId)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
logger.LogDebug("Найдено {Count} юнитов с подходящим значением поля.", matchingUnitIds.Count);
|
||||
|
||||
// Получаем имена этих юнитов через IUnitService
|
||||
if (matchingUnitIds.Any())
|
||||
{
|
||||
var matchingUnitNames = await unitService.Get().AsNoTracking()
|
||||
.Where(u => matchingUnitIds.Contains(u.Id))
|
||||
.Select(u => u.Name)
|
||||
.ToListAsync();
|
||||
|
||||
logger.LogDebug("Найдены имена: [{Names}]", string.Join(", ", matchingUnitNames));
|
||||
result.UnionWith(matchingUnitNames);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogDebug("Итоговый результат: [{Result}]", string.Join(", ", result));
|
||||
|
||||
return result.ToList();
|
||||
}
|
||||
|
||||
#region Вспомогательные методы фильтрации
|
||||
|
||||
private IQueryable<Unit> ApplyFieldFilter(IQueryable<Unit> query, JobFieldFilter fieldFilter)
|
||||
{
|
||||
var fieldId = fieldFilter.FieldId;
|
||||
var valueMask = fieldFilter.ValueMask?.Trim();
|
||||
|
||||
if (string.IsNullOrEmpty(valueMask))
|
||||
return query;
|
||||
|
||||
logger.LogDebug("Фильтр по полю: FieldId={FieldId}, ValueMask={ValueMask}", fieldId, valueMask);
|
||||
|
||||
return query.Where(unit =>
|
||||
unit.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask)));
|
||||
}
|
||||
|
||||
private IQueryable<Unit> ApplyRelationshipFilterToQuery(IQueryable<Unit> query, JobRelationshipFilter relFilter)
|
||||
{
|
||||
var fieldId = relFilter.FieldId;
|
||||
var valueMask = relFilter.ValueMask ?? "";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(valueMask))
|
||||
return query;
|
||||
|
||||
logger.LogDebug("Фильтр по связи: IsParent={IsParent}, IsInverse={IsInverse}, IsFullMatch={IsFullMatch}, FieldId={FieldId}, ValueMask={ValueMask}",
|
||||
relFilter.IsParent, relFilter.IsInverse, relFilter.IsFullMatch, fieldId, valueMask);
|
||||
|
||||
if (relFilter.IsParent)
|
||||
{
|
||||
if (relFilter.IsInverse)
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
return query.Where(unit =>
|
||||
!unit.ParentUnits.Any() ||
|
||||
unit.ParentUnits.All(link =>
|
||||
!link.ParentUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
return query.Where(unit =>
|
||||
!unit.ParentUnits.Any() ||
|
||||
unit.ParentUnits.Any(link =>
|
||||
!link.ParentUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
return query.Where(unit =>
|
||||
!unit.ParentUnits.Any() ||
|
||||
unit.ParentUnits.All(link =>
|
||||
link.ParentUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
return query.Where(unit =>
|
||||
unit.ParentUnits.Any(link =>
|
||||
link.ParentUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (relFilter.IsInverse)
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
return query.Where(unit =>
|
||||
!unit.ChildUnits.Any() ||
|
||||
unit.ChildUnits.All(link =>
|
||||
!link.ChildUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
return query.Where(unit =>
|
||||
!unit.ChildUnits.Any() ||
|
||||
unit.ChildUnits.Any(link =>
|
||||
!link.ChildUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (relFilter.IsFullMatch)
|
||||
{
|
||||
return query.Where(unit =>
|
||||
!unit.ChildUnits.Any() ||
|
||||
unit.ChildUnits.All(link =>
|
||||
link.ChildUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
else
|
||||
{
|
||||
return query.Where(unit =>
|
||||
unit.ChildUnits.Any(link =>
|
||||
link.ChildUnit!.UnitValues.Any(v =>
|
||||
v.FieldId == fieldId &&
|
||||
v.Value != null &&
|
||||
v.Value.Value != null &&
|
||||
EF.Functions.Like(v.Value.Value, valueMask))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IQueryable<Unit> ApplyRelationshipCountFilter(IQueryable<Unit> query, Job job)
|
||||
{
|
||||
int min = job.MinValueRelationships.GetValueOrDefault(0);
|
||||
int max = job.MaxValueRelationships.GetValueOrDefault(int.MaxValue);
|
||||
|
||||
logger.LogDebug("Фильтр по количеству связей: Min={Min}, Max={Max}, IsParent={IsParent}", min, max, job.IsParentRelationships);
|
||||
|
||||
if (job.IsParentRelationships == true)
|
||||
{
|
||||
return query.Where(unit => unit.ParentUnits.Count >= min && unit.ParentUnits.Count <= max);
|
||||
}
|
||||
else
|
||||
{
|
||||
return query.Where(unit => unit.ChildUnits.Count >= min && unit.ChildUnits.Count <= max);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user