feat(templateMatcher,dal): небольшой рефакторинг, добавлен Dockerfile

This commit is contained in:
Mikhail Kuznetsov
2025-11-20 11:37:44 +10:00
parent 974ec3c9e0
commit d90924bfa2
9 changed files with 273 additions and 166 deletions

View File

@@ -1,11 +1,13 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.DAL.Contracts;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Models.Job;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
namespace PARR.DAL.DomainServices.Implementations
@@ -33,7 +35,6 @@ namespace PARR.DAL.DomainServices.Implementations
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId, int? takeCount = null)
{
var job = await jobService
.Get().AsNoTracking()
.Include(t => t.UnitFilters)
@@ -41,6 +42,7 @@ namespace PARR.DAL.DomainServices.Implementations
.Include(t => t.UnitFilters)
.ThenInclude(t => t.RelationshipFilters)
.Include(t => t.Group)
.ThenInclude(t => t.GroupType)
.FirstOrDefaultAsync(t => t.Id == jobId);
if (job == null)
@@ -52,171 +54,258 @@ namespace PARR.DAL.DomainServices.Implementations
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Job job, int? takeCount = null)
{
#region проверка инклудов
if (job.Group == null)
{
logger.LogWarning("JobId={JobId} не содержит Group - пропускаем фильтрацию", job.Id);
throw new ArgumentNullException(nameof(Group));
}
if (job.Group.GroupType == null)
{
logger.LogWarning("JobId={JobId} не содержит GroupType - пропускаем фильтрацию", job.Id);
throw new ArgumentNullException(nameof(JobGroupType));
}
if (job.UnitFilters == null || !job.UnitFilters.Any())
{
logger.LogWarning("JobId={JobId} не содержит UnitFilters - пропускаем фильтрацию", job.Id);
return Array.Empty<Guid>();
throw new ArgumentNullException(nameof(JobUnitFilter));
}
#endregion
var baseQuery = unitService
.Get().AsNoTracking()
.Include(t => t.UnitValues)
.ThenInclude(t => t.Field)
.Include(t => t.UnitValues)
.ThenInclude(t => t.Value)
.Include(t => t.ParentUnits)
.ThenInclude(t => t.ParentUnit)
.ThenInclude(t => t.UnitValues)
.ThenInclude(t => t.Field)
.Include(t => t.ParentUnits)
.ThenInclude(t => t.ParentUnit)
.ThenInclude(t => t.UnitValues)
.ThenInclude(t => t.Value)
.Include(t => t.ChildUnits)
.ThenInclude(t => t.ChildUnit)
.ThenInclude(t => t.UnitValues)
.ThenInclude(t => t.Field)
.Include(t => t.ChildUnits)
.ThenInclude(t => t.ChildUnit)
.ThenInclude(t => t.UnitValues)
.ThenInclude(t => t.Value);
var maxCount = takeCount ?? int.MaxValue;
var collectedIds = new HashSet<Guid>(); // ← гарантирует уникальность
var filterNumber = 0;
var result = new List<Guid>();
var filterIndex = 0;
foreach (var unitFilter in job.UnitFilters)
foreach (var filter in job.UnitFilters)
{
filterIndex++;
filterNumber++;
if (takeCount.HasValue && result.Count >= takeCount.Value)
// Прекращаем, если набрали достаточно
if (collectedIds.Count >= maxCount)
{
logger.LogDebug("Достигнуто ограничение takeCount={TakeCount} после {FilterIndex} фильтров", takeCount.Value, filterIndex - 1);
logger.LogDebug("Достигнут лимит takeCount={TakeCount} после {FilterCount} фильтров", maxCount, filterNumber - 1);
break;
}
var remainig = takeCount.HasValue ? takeCount.Value - result.Count : int.MaxValue;
if (remainig <= 0) break;
var remaining = maxCount - collectedIds.Count;
if (remaining <= 0) break;
try
{
//фильтруем по имени
var query = baseQuery.Where(t => EF.Functions.ILike(t.Name, unitFilter.UnitFilter));
// Стартуем с базового условия — имя Unit'а
var query = unitService.Get().AsNoTracking()
.Where(unit => EF.Functions.ILike(unit.Name, filter.UnitFilter));
//фильтруем по полям
foreach (var fieldFilter in unitFilter.FieldFilters)
// 1. Фильтры по полям (UnitValues)
foreach (var fieldFilter in filter.FieldFilters)
{
var fieldId = fieldFilter.FieldId;
var fieldValueMask = fieldFilter.ValueMask;
query = query.Where(t =>
t.UnitValues.Any(x =>
x.FieldId == fieldId &&
x.Value != null &&
x.Value.Value != null &&
EF.Functions.ILike(x.Value.Value, fieldValueMask)));
var valueMask = fieldFilter.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)));
}
//фильтруем по значениям в связях
if (unitFilter.RelationshipFilters.Any())
// 2. Фильтры по связям (родителям и детям)
foreach (var relFilter in filter.RelationshipFilters)
{
var parentFilters = unitFilter.RelationshipFilters.Where(t => t.IsParent == true).ToList();
foreach (var parentFilter in parentFilters)
var fieldId = relFilter.FieldId;
var valueMask = relFilter.ValueMask;
if (relFilter.IsParent)
{
if (parentFilter.IsInverse == false)
// Работаем с ParentUnits → pu.ParentUnit
if (relFilter.IsInverse)
{
if (parentFilter.IsFullMatch)
query = query.Where(t => !t.ParentUnits.Any() ||
t.ParentUnits.All(p => p.ParentUnit!.UnitValues.Any(pf =>
pf.FieldId == parentFilter.FieldId &&
pf.Value !=null &&
pf.Value.Value != null &&
EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask))));
// "Обратный фильтр": ищем Unit'ы, у которых связанные 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(t => !t.ParentUnits.Any() ||
t.ParentUnits.Any(p => p.ParentUnit!.UnitValues.Any(pf =>
pf.FieldId == parentFilter.FieldId &&
pf.Value !=null &&
pf.Value!.Value != null &&
EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask))));
{
// Хотя бы один родитель НЕ имеет такого значения
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
{
if (parentFilter.IsFullMatch)
query = query.Where(t => !t.ParentUnits.Any() ||
!t.ParentUnits.All(p => p.ParentUnit!.UnitValues.Any(pf =>
pf.FieldId == parentFilter.FieldId &&
pf.Value !=null &&
pf.Value!.Value != null &&
EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask))));
// Прямой фильтр: связанные 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(t => !t.ParentUnits.Any() ||
!t.ParentUnits.Any(p => p.ParentUnit!.UnitValues.Any(pf =>
pf.FieldId == parentFilter.FieldId &&
pf.Value != null &&
pf.Value!.Value != null && EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask))));
{
// Хотя бы один родитель должен иметь такое значение
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))));
}
}
}
}
//фильтруем по количеству связей
if (job.Group?.IsUmbrella == true)
// 3. Ограничение по количеству связей (только для umbrella-групп)
if (job.Group.GroupType.Code == JobGroupTypesEnum.Umbrella)
{
int min = job.MinValueRelationships.GetValueOrDefault(0);
int max = job.MaxValueRelationships.GetValueOrDefault(int.MaxValue);
if (job.IsParentRelationships == true)
query = query.Where(t => t.ParentUnits.Count >= job.MinValueRelationships && t.ParentUnits.Count <= job.MaxValueRelationships);
{
query = query.Where(unit =>
unit.ParentUnits.Count >= min && unit.ParentUnits.Count <= max);
}
else
query = query.Where(t => t.ChildUnits.Count >= job.MinValueRelationships && t.ChildUnits.Count <= job.MaxValueRelationships);
{
query = query.Where(unit =>
unit.ChildUnits.Count >= min && unit.ChildUnits.Count <= max);
}
}
var newUnits = await query
.Select(t => t.Id)
.Take(remainig)
// Запрашиваем в БД с учётом оставшегося лимита
var newIds = await query
.Select(unit => unit.Id)
.Take(remaining)
.ToListAsync();
result.AddRange(newUnits);
collectedIds.UnionWith(newIds);
logger.LogDebug(
"Фильтр #{Index} (Id={FilterId}): найдено {Count} Unit'ов. Всего: {Total}",
filterNumber, filter.Id, newIds.Count, collectedIds.Count);
logger.LogDebug("Фильтр {FilterIndex}: найдено {Count} Unit'ов (осталось набрать: {Remaining})",
filterIndex, newUnits.Count,Math.Max(0,takeCount.GetValueOrDefault(int.MaxValue)-result.Count));
}
catch (Exception ex)
{
logger.LogError(ex, "Ошибка применения UnitFilter {FilterIndex} для JobId={JobId}", filterIndex, job.Id);
continue;
logger.LogError(ex, "Ошибка при обработке фильтра {FilterId} (#{Index}) для Job {JobId}",
filter.Id, filterNumber, job.Id);
// Продолжаем — другие фильтры могут сработать
}
}
if (takeCount.HasValue && result.Count > takeCount.Value)
result = result.Take(takeCount.Value).ToList();
logger.LogInformation("JobId={JobId}: обработано {FilterCount} фильтров, найдено {UnitCount} Unit'ов", job.Id, job.UnitFilters.Count, result.Count);
var result = collectedIds.Take(maxCount).ToList();
logger.LogInformation("Job {JobId}: из {FilterCount} фильтров получено {UnitCount} уникальных Unit'ов",
job.Id, job.UnitFilters.Count, result.Count);
return result;
}
public async Task<IEnumerable<Guid>?> GetUnitsIdForExistTemplatesByJobFilterAsync(Guid jobId, int? takeCount = null)
public async Task<IEnumerable<Guid>> GetUnitsIdByJobFilterWithTemplateStatusAsync(
Guid jobId,
bool mustHaveTemplate,
int? takeCount = null
)
{
var unitIdsMustBeCreated = await GetUnitsIdByJobFilterAsync(jobId, takeCount);
var unitIds = await GetUnitsIdByJobFilterAsync(jobId, takeCount);
if (unitIds == null || !unitIds.Any())
return Array.Empty<Guid>();
if (unitIdsMustBeCreated == null || !unitIdsMustBeCreated.Any())
return null;
var unitIdSet = unitIds.ToHashSet();
var unitWithTemplates = await templateService.Get().AsNoTracking().Where(t => t.JobId == jobId && unitIdsMustBeCreated.Any(x => x == t.UnitId)).Select(t => t.UnitId).ToListAsync();
// Получаем UnitId, для которых уже есть шаблоны по этому jobId
var existingUnitIds = await templateService
.Get()
.AsNoTracking()
.Where(template =>
template.JobId == jobId &&
unitIdSet.Contains(template.UnitId))
.Select(template => template.UnitId)
.ToListAsync();
return unitWithTemplates;
}
var existingSet = existingUnitIds.ToHashSet();
public async Task<IEnumerable<Guid>?> GetUnitsIdForNotExistTemplatesByJobFilterAsync(Guid jobId, int? takeCount = null)
{
var unitIdsMustBeCreated = await GetUnitsIdByJobFilterAsync(jobId, takeCount);
if (unitIdsMustBeCreated == null || !unitIdsMustBeCreated.Any())
return null;
var unitIdsWithTemplate = await templateService.Get().AsNoTracking().Where(t => t.JobId == jobId).Select(t => t.UnitId).ToListAsync();
var unitsIdToCreateTemplate = unitIdsMustBeCreated.Where(t => !unitIdsWithTemplate.Any(x => x == t));
return unitsIdToCreateTemplate;
return mustHaveTemplate
? existingSet
: unitIdSet.Except(existingSet);
}
}
}