feat(dal): ShortcodesService добавлена обработка динамичесих составляющих "%СВЯЗИ%", "%ТНК-КРАТКО%"
This commit is contained in:
@@ -106,6 +106,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.TemplateUpdaterWorker"
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.TemplateUpdater", "PARR.TemplateUpdater\PARR.TemplateUpdater.csproj", "{10905C04-A6E5-42BC-9804-8671D22C5D6E}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.TemplateUpdater", "PARR.TemplateUpdater\PARR.TemplateUpdater.csproj", "{10905C04-A6E5-42BC-9804-8671D22C5D6E}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.DAL.IntegrationTests", "PARR.DAL.IntegrationTests\PARR.DAL.IntegrationTests.csproj", "{D1C65DB8-77BC-00FD-5BA1-6C7303FD093C}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -298,6 +300,10 @@ Global
|
|||||||
{10905C04-A6E5-42BC-9804-8671D22C5D6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{10905C04-A6E5-42BC-9804-8671D22C5D6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{10905C04-A6E5-42BC-9804-8671D22C5D6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{10905C04-A6E5-42BC-9804-8671D22C5D6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{10905C04-A6E5-42BC-9804-8671D22C5D6E}.Release|Any CPU.Build.0 = Release|Any CPU
|
{10905C04-A6E5-42BC-9804-8671D22C5D6E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{D1C65DB8-77BC-00FD-5BA1-6C7303FD093C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{D1C65DB8-77BC-00FD-5BA1-6C7303FD093C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{D1C65DB8-77BC-00FD-5BA1-6C7303FD093C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{D1C65DB8-77BC-00FD-5BA1-6C7303FD093C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -10,10 +10,8 @@ using PARR.API.Contracts.V1.Responses.Base;
|
|||||||
using PARR.API.Controllers.V1.Base;
|
using PARR.API.Controllers.V1.Base;
|
||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
using PARR.DAL.DomainServices.Interfaces;
|
using PARR.DAL.DomainServices.Interfaces;
|
||||||
using PARR.DAL.Models.Job;
|
|
||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
using PARR.DAL.Services.Interfaces.Unit;
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
using static PARR.API.Contracts.V1.ApiRoutes;
|
|
||||||
using Job = PARR.DAL.Models.Job.Job;
|
using Job = PARR.DAL.Models.Job.Job;
|
||||||
|
|
||||||
namespace PARR.API.Controllers.V1
|
namespace PARR.API.Controllers.V1
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.DAL.Context;
|
||||||
|
using PARR.DAL.DomainServices.Implementations;
|
||||||
|
// Предположим, что у вас есть реализации IJobService и IUnitService
|
||||||
|
// Если нет, можно создать моки, но лучше использовать реальные, если они просты
|
||||||
|
using PARR.DAL.Services.Implementations.Job; // Пример: JobService
|
||||||
|
using PARR.DAL.Services.Implementations.Unit; // Пример: UnitService
|
||||||
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace PARR.DAL.IntegrationTests.Integration
|
||||||
|
{
|
||||||
|
public class UnitFilterServiceIntegrationTests : IAsyncLifetime
|
||||||
|
{
|
||||||
|
private DbContextOptions<DataContext> _options;
|
||||||
|
private DataContext _context;
|
||||||
|
private UnitFilterService _service;
|
||||||
|
|
||||||
|
public UnitFilterServiceIntegrationTests()
|
||||||
|
{
|
||||||
|
_options = new DbContextOptionsBuilder<DataContext>()
|
||||||
|
.UseInMemoryDatabase($"IntegrationTestDb_{Guid.NewGuid()}")
|
||||||
|
.EnableSensitiveDataLogging()
|
||||||
|
.Options;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
// Создаём контекст
|
||||||
|
_context = new DataContext(_options);
|
||||||
|
await _context.Database.EnsureCreatedAsync();
|
||||||
|
|
||||||
|
// Заполняем тестовые данные (убедитесь, что TestDataGenerator доступен)
|
||||||
|
TestDataGenerator.Seed(_context); // или async, если вы его переделаете
|
||||||
|
|
||||||
|
// Создаём ServiceProvider с реальными сервисами
|
||||||
|
var serviceCollection = new ServiceCollection();
|
||||||
|
serviceCollection.AddLogging(builder => builder.AddConsole()); // или Mock.Of<ILogger>
|
||||||
|
|
||||||
|
// Регистрируем контекст
|
||||||
|
serviceCollection.AddScoped<DataContext>(provider => _context);
|
||||||
|
|
||||||
|
serviceCollection.AddScoped<IJobService, JobService>();
|
||||||
|
serviceCollection.AddScoped<IUnitService, UnitService>();
|
||||||
|
|
||||||
|
// Добавляем новые сервисы
|
||||||
|
serviceCollection.AddScoped<IUnitInUnitService, UnitInUnitService>();
|
||||||
|
serviceCollection.AddScoped<IUnitInValueService, UnitInValueService>();
|
||||||
|
|
||||||
|
// Регистрируем тестируемый сервис
|
||||||
|
serviceCollection.AddScoped<UnitFilterService>();
|
||||||
|
|
||||||
|
var serviceProvider = serviceCollection.BuildServiceProvider();
|
||||||
|
|
||||||
|
// Получаем сервис
|
||||||
|
_service = serviceProvider.GetRequiredService<UnitFilterService>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task DisposeAsync()
|
||||||
|
{
|
||||||
|
if (_context != null)
|
||||||
|
{
|
||||||
|
await _context.DisposeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetRelatedUnitNamesAsync_WithChildRelationshipFilter_ShouldReturnExpectedNames()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var jobId = _context.Jobs.First(j => j.Name == "TestJob_2").Id;
|
||||||
|
var unitId = TestDataGenerator.UnitWId;
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await _service.GetRelatedUnitNamesAsync(jobId, unitId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().Contain(new[] { "СХД-КМТ-CISCO-MDS9148-1-ДВС", "СХД-КМТ-CISCO-MDS9148-3-ДВС" });
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetUnitsIdByJobFilterAsync_WithExistingJobId_ShouldReturnExpectedUnits()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var jobId = _context.Jobs.First(j => j.Name == "TestJob_1").Id;
|
||||||
|
var expectedUnitIds = new[] { TestDataGenerator.UnitAId, TestDataGenerator.UnitBId };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await _service.GetUnitsIdByJobFilterAsync(jobId, takeCount: 10);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull()
|
||||||
|
.And.HaveCount(2)
|
||||||
|
.And.Contain(expectedUnitIds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
33
PARR.DAL.IntegrationTests/PARR.DAL.IntegrationTests.csproj
Normal file
33
PARR.DAL.IntegrationTests/PARR.DAL.IntegrationTests.csproj
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||||
|
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.20" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.20" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
|
||||||
|
<PackageReference Include="Npgsql" Version="7.0.4" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
</PackageReference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\PARR.DAL\PARR.DAL.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
254
PARR.DAL.IntegrationTests/TestDataGenerator.cs
Normal file
254
PARR.DAL.IntegrationTests/TestDataGenerator.cs
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
using PARR.DAL.Context;
|
||||||
|
using PARR.DAL.Contracts;
|
||||||
|
using PARR.DAL.Models.Job;
|
||||||
|
using PARR.DAL.Models.Unit;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace PARR.DAL.IntegrationTests
|
||||||
|
{
|
||||||
|
public static class TestDataGenerator
|
||||||
|
{
|
||||||
|
// --- Unit IDs ---
|
||||||
|
public static readonly Guid UnitAId = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||||
|
public static readonly Guid UnitBId = Guid.Parse("00000000-0000-1111-1111-111111111111");
|
||||||
|
public static readonly Guid UnitCId = Guid.Parse("22222222-2222-2222-2222-222222222222");
|
||||||
|
public static readonly Guid UnitDId = Guid.Parse("33333333-3333-3333-3333-333333333333");
|
||||||
|
public static readonly Guid UnitWId = Guid.Parse("44444444-4444-4444-4444-444444444444");
|
||||||
|
public static readonly Guid UnitXId = Guid.Parse("55555555-5555-5555-5555-555555555555");
|
||||||
|
public static readonly Guid UnitYId = Guid.Parse("66666666-6666-6666-6666-666666666666");
|
||||||
|
public static readonly Guid UnitZId = Guid.Parse("77777777-7777-7777-7777-777777777777");
|
||||||
|
|
||||||
|
// --- Field IDs (для обхода составного ключа UnitFilterId+FieldId) ---
|
||||||
|
public static readonly Guid FieldId1 = Guid.Parse("08b42860-09a7-4a1f-aa4f-0290e86df883");//ТИП_ЭК
|
||||||
|
public static readonly Guid FieldId2 = Guid.Parse("5b2d3f5b-a9f3-4a6b-9142-70ef4357ac37"); //неуникальный
|
||||||
|
public static readonly Guid FieldId3 = Guid.Parse("5f3c7b8b-583d-411b-b9bd-1e045ddc5a8e");//ПОДКАТЕГОРИЯ_ЭК
|
||||||
|
public static readonly Guid FieldId4 = Guid.Parse("3e9ac5aa-531b-4ffc-8f93-694d00aa92a0");//активный
|
||||||
|
|
||||||
|
// --- Field Value IDs ---
|
||||||
|
public static readonly Guid FieldValueId1 = Guid.Parse("fe18edcd-ab6a-4f3e-b7bc-e54aad9ecc0d"); // система хранения данных (схд) field3
|
||||||
|
public static readonly Guid FieldValueId2 = Guid.Parse("f385b22c-42c3-4db9-bd41-b829603cc2d9"); // 1 field2+field4
|
||||||
|
public static readonly Guid FieldValueId3 = Guid.Parse("2badc139-69cb-4d52-830a-1b3c6a9faf9d"); // 0 field2+field4
|
||||||
|
public static readonly Guid FieldValueId4 = Guid.Parse("fde68ef7-a07e-4c10-872c-cd98c3d1c30b"); // коммутатор
|
||||||
|
public static readonly Guid FieldValueId5 = Guid.Parse("9f169862-3f78-49f2-b967-13b5b2f56231"); // серверное оборудование
|
||||||
|
public static readonly Guid FieldValueId6 = Guid.Parse("075b6fad-d24f-40f4-aa0e-83a4cfc46bbf"); // стойка цвк
|
||||||
|
public static readonly Guid FieldValueId7 = Guid.Parse("9679afd8-8004-4ce2-bd6f-9005b037ef96"); // схд
|
||||||
|
|
||||||
|
internal static void Seed(DataContext context)
|
||||||
|
{
|
||||||
|
if (context.Units.Any()) return;
|
||||||
|
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
// 1. Значения полей (остаются те же)
|
||||||
|
var fieldValues = new[]
|
||||||
|
{
|
||||||
|
new UnitFieldValue { Id = FieldValueId1, Value = "система хранения данных (схд)", DateCreated = now },
|
||||||
|
new UnitFieldValue { Id = FieldValueId2, Value = "1", DateCreated = now },
|
||||||
|
new UnitFieldValue { Id = FieldValueId3, Value = "0", DateCreated = now },
|
||||||
|
new UnitFieldValue { Id = FieldValueId4, Value = "коммутатор", DateCreated = now },
|
||||||
|
};
|
||||||
|
context.UnitFieldValues.AddRange(fieldValues);
|
||||||
|
|
||||||
|
// 2. Unit'ы
|
||||||
|
var units = new[]
|
||||||
|
{
|
||||||
|
new Unit { Id = UnitAId, Name = "СХД-КМТ-DVGD-MDS9148-1-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitBId, Name = "СХД-КМТ-DVGD-MDS9148-2-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitCId, Name = "СРВ-СТОЙКА-СТОЙКА-ХИВЦ-4.0-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitDId, Name = "СХД-VSP-E590-01-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitWId, Name = "СХД-КМТ-SAN1_FAB_1-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitXId, Name = "СХД-КМТ-CISCO-MDS9148-1-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitYId, Name = "СХД-КМТ-CISCO-MDS9148-3-ДВС", DateCreated = now },
|
||||||
|
};
|
||||||
|
context.Units.AddRange(units);
|
||||||
|
|
||||||
|
// 3. UnitInUnit (связи)
|
||||||
|
var unitInUnits = new[]
|
||||||
|
{
|
||||||
|
new UnitInUnit { ParentUnitId = UnitAId, ChildUnitId = UnitCId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitBId, ChildUnitId = UnitCId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitDId, ChildUnitId = UnitAId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitDId, ChildUnitId = UnitBId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitWId, ChildUnitId = UnitXId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitWId, ChildUnitId = UnitYId, DateCreated = now }
|
||||||
|
};
|
||||||
|
context.UnitInUnits.AddRange(unitInUnits);
|
||||||
|
|
||||||
|
// 4. UnitInValue
|
||||||
|
var unitInValues = new List<UnitInValue>
|
||||||
|
{
|
||||||
|
// Основные (FieldId)
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId2, ValueId = FieldValueId3, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId2, ValueId = FieldValueId3, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitCId, FieldId = FieldId3, ValueId = FieldValueId5, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitCId, FieldId = FieldId1, ValueId = FieldValueId6, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitCId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitDId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitDId, FieldId = FieldId1, ValueId = FieldValueId7, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitDId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId2, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitXId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitXId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitXId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitYId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitYId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitYId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
|
||||||
|
};
|
||||||
|
context.UnitInValues.AddRange(unitInValues);
|
||||||
|
|
||||||
|
// 5. JobGroupType и Group
|
||||||
|
var groupType = context.JobGroupTypes
|
||||||
|
.FirstOrDefault(t => t.Code == JobGroupTypesEnum.Simple)
|
||||||
|
?? throw new InvalidOperationException("JobGroupType 'Simple' не найден в контексте.");
|
||||||
|
|
||||||
|
var group = new JobGroup
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
GroupTypeId = groupType.Id,
|
||||||
|
GroupType = groupType,
|
||||||
|
GroupName = "Группа",
|
||||||
|
ShortDescription = "%ТНК-КРАТКО% %ЭК%",
|
||||||
|
FullDescription = "Подробно:\n%СВЯЗИ%",
|
||||||
|
Solution = "Решение",
|
||||||
|
TemplateDuration = "540 00:00:00",
|
||||||
|
ReferenceDate = now,
|
||||||
|
IsAutoDistributionEnabled = false,
|
||||||
|
IsAgent = false,
|
||||||
|
DateCreated = now
|
||||||
|
};
|
||||||
|
context.JobGroups.Add(group);
|
||||||
|
|
||||||
|
// 6. Jobs
|
||||||
|
var jobs = new List<Job>();
|
||||||
|
|
||||||
|
// --- TestJob ---
|
||||||
|
var job1 = new Job
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Name = "TestJob_1",
|
||||||
|
WorkName = "Работа",
|
||||||
|
TemplateNameMask = "%ЭК%",
|
||||||
|
WorkGroupMask = "%ГРУППА_РАБОТ%",
|
||||||
|
GroupId = group.Id,
|
||||||
|
TnkId = Guid.NewGuid(),
|
||||||
|
Group = group,
|
||||||
|
DateCreated = now
|
||||||
|
};
|
||||||
|
var unitFilter1Id = Guid.NewGuid();
|
||||||
|
job1.UnitFilters = new List<JobUnitFilter>
|
||||||
|
{
|
||||||
|
new JobUnitFilter
|
||||||
|
{
|
||||||
|
Id = unitFilter1Id,
|
||||||
|
UnitFilter = "СХД-%",
|
||||||
|
JobId = job1.Id,
|
||||||
|
Job = job1,
|
||||||
|
DateCreated = now,
|
||||||
|
FieldFilters = new List<JobFieldFilter>
|
||||||
|
{
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter1Id,
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask="коммутатор"
|
||||||
|
},
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter1Id,
|
||||||
|
FieldId = FieldId4,
|
||||||
|
ValueMask="1"
|
||||||
|
},
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter1Id,
|
||||||
|
FieldId = FieldId2,
|
||||||
|
ValueMask="0"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
RelationshipFilters = new List<JobRelationshipFilter>
|
||||||
|
{
|
||||||
|
new JobRelationshipFilter
|
||||||
|
{
|
||||||
|
IsParent = true,
|
||||||
|
IsInverse = true,
|
||||||
|
IsFullMatch = true,
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask = "коммутатор",
|
||||||
|
UnitFilterId = unitFilter1Id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
jobs.Add(job1);
|
||||||
|
|
||||||
|
// --- TestJob_2 (с IsParent = false для дочерних связей) ---
|
||||||
|
var job2 = new Job
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Name = "TestJob_2",
|
||||||
|
WorkName = "Работа2",
|
||||||
|
TemplateNameMask = "%ЭК%",
|
||||||
|
WorkGroupMask = "%ГРУППА_РАБОТ%",
|
||||||
|
GroupId = group.Id,
|
||||||
|
TnkId = Guid.NewGuid(),
|
||||||
|
Group = group,
|
||||||
|
DateCreated = now
|
||||||
|
};
|
||||||
|
var unitFilter2Id = Guid.NewGuid();
|
||||||
|
job2.UnitFilters = new List<JobUnitFilter>
|
||||||
|
{
|
||||||
|
new JobUnitFilter
|
||||||
|
{
|
||||||
|
Id = unitFilter2Id,
|
||||||
|
UnitFilter = "СХД-%",
|
||||||
|
JobId = job2.Id,
|
||||||
|
Job = job2,
|
||||||
|
DateCreated = now,
|
||||||
|
FieldFilters = new List<JobFieldFilter>
|
||||||
|
{
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter2Id,
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask="коммутатор"
|
||||||
|
},
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter2Id,
|
||||||
|
FieldId = FieldId4,
|
||||||
|
ValueMask="1"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
RelationshipFilters = new List<JobRelationshipFilter>
|
||||||
|
{
|
||||||
|
new JobRelationshipFilter
|
||||||
|
{
|
||||||
|
IsParent = false, // <-- Новый фильтр: ищем дочерние юниты
|
||||||
|
IsInverse = false, // <-- Простой фильтр
|
||||||
|
IsFullMatch = false, // <-- Простой фильтр
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask = "коммутатор",
|
||||||
|
UnitFilterId = unitFilter2Id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
jobs.Add(job2);
|
||||||
|
|
||||||
|
context.Jobs.AddRange(jobs);
|
||||||
|
context.SaveChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
using PARR.DAL.Context;
|
||||||
|
using PARR.DAL.DomainServices.Implementations;
|
||||||
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace PARR.DAL.Tests
|
||||||
|
{
|
||||||
|
public class UnitFilterServiceTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly DbContextOptions<DataContext> _options;
|
||||||
|
private readonly DataContext _context;
|
||||||
|
private readonly UnitFilterService _service;
|
||||||
|
|
||||||
|
public UnitFilterServiceTests()
|
||||||
|
{
|
||||||
|
_options = new DbContextOptionsBuilder<DataContext>()
|
||||||
|
.UseInMemoryDatabase($"TestDb_{Guid.NewGuid()}")
|
||||||
|
.EnableSensitiveDataLogging()
|
||||||
|
.Options;
|
||||||
|
|
||||||
|
_context = new DataContext(_options);
|
||||||
|
_context.Database.EnsureCreated();
|
||||||
|
TestDataGenerator.Seed(_context);
|
||||||
|
|
||||||
|
var logger = Mock.Of<ILogger<UnitFilterService>>();
|
||||||
|
|
||||||
|
// Используем реальные сервисы, работающие с _context
|
||||||
|
var jobServiceMock = new Mock<IJobService>();
|
||||||
|
jobServiceMock.Setup(x => x.Get()).Returns(() => _context.Jobs);
|
||||||
|
|
||||||
|
var unitServiceMock = new Mock<IUnitService>();
|
||||||
|
unitServiceMock.Setup(x => x.Get()).Returns(() => _context.Units);
|
||||||
|
|
||||||
|
_service = new UnitFilterService(logger, jobServiceMock.Object, unitServiceMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _context.Dispose();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetUnitsIdByJobFilterAsync_WithExistingJobId_ShouldReturnExpectedUnits()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var jobId = _context.Jobs.First(j => j.Name == "TestJob_1").Id;
|
||||||
|
var expectedUnitIds = new[] { TestDataGenerator.UnitAId, TestDataGenerator.UnitBId };
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await _service.GetUnitsIdByJobFilterAsync(jobId, takeCount: 10);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().NotBeNull()
|
||||||
|
.And.HaveCount(2)
|
||||||
|
.And.Contain(expectedUnitIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetRelatedUnitNamesAsync_WithChildRelationshipFilter_ShouldReturnExpectedNames()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var jobId = _context.Jobs.First(j => j.Name == "TestJob_2").Id;
|
||||||
|
var unitId = TestDataGenerator.UnitWId; // Родитель
|
||||||
|
|
||||||
|
// rf.IsParent = false
|
||||||
|
// Ищем юниты, у которых ParentUnitId = UnitWId (т.е. это дети UnitWId)
|
||||||
|
// и у этих юнитов (детей) есть FieldId1 = "коммутатор"
|
||||||
|
// Это UnitXId и UnitYId -> имена: "СХД-КМТ-CISCO-MDS9148-1-ДВС", "СХД-КМТ-CISCO-MDS9148-3-ДВС"
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = await _service.GetRelatedUnitNamesAsync(jobId, unitId);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
result.Should().Contain(new[] { "СХД-КМТ-CISCO-MDS9148-1-ДВС", "СХД-КМТ-CISCO-MDS9148-3-ДВС" });
|
||||||
|
}
|
||||||
|
//[Fact]
|
||||||
|
//public async Task GetRelatedUnitNamesAsync_WithChildRelationshipFilter_ShouldReturnExpectedNames()
|
||||||
|
//{
|
||||||
|
// // Arrange
|
||||||
|
// var jobId = _context.Jobs.First(j => j.Name == "TestJob_2").Id;
|
||||||
|
// var unitId = TestDataGenerator.UnitWId;
|
||||||
|
|
||||||
|
// // Проверим связи вручную
|
||||||
|
// var childLinks = await _context.UnitInUnits
|
||||||
|
// .Where(u => u.ParentUnitId == unitId)
|
||||||
|
// .ToListAsync();
|
||||||
|
|
||||||
|
// var childIds = childLinks.Select(l => l.ChildUnitId).ToList();
|
||||||
|
// var childUnits = await _context.Units
|
||||||
|
// .Where(u => childIds.Contains(u.Id))
|
||||||
|
// .ToListAsync();
|
||||||
|
|
||||||
|
// Console.WriteLine($"Child units of {unitId}:");
|
||||||
|
// foreach (var u in childUnits)
|
||||||
|
// {
|
||||||
|
// Console.WriteLine($" - {u.Id} ({u.Name})");
|
||||||
|
|
||||||
|
// var values = await _context.UnitInValues
|
||||||
|
// .Where(v => v.UnitId == u.Id && v.FieldId == TestDataGenerator.FieldId1)
|
||||||
|
// .ToListAsync();
|
||||||
|
|
||||||
|
// foreach (var v in values)
|
||||||
|
// {
|
||||||
|
// var val = await _context.UnitFieldValues.FindAsync(v.ValueId);
|
||||||
|
// Console.WriteLine($" FieldId1 = {val?.Value}");
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // Act
|
||||||
|
// var result = await _service.GetRelatedUnitNamesAsync(jobId, unitId);
|
||||||
|
|
||||||
|
// Console.WriteLine($"Result: [{string.Join(", ", result)}]");
|
||||||
|
|
||||||
|
// // Assert
|
||||||
|
// result.Should().Contain(new[] { "СХД-КМТ-CISCO-MDS9148-1-ДВС", "СХД-КМТ-CISCO-MDS9148-3-ДВС" });
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,8 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.20" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
|
||||||
<PackageReference Include="Moq" Version="4.20.72" />
|
<PackageReference Include="Moq" Version="4.20.72" />
|
||||||
<PackageReference Include="xunit" Version="2.4.2" />
|
<PackageReference Include="xunit" Version="2.4.2" />
|
||||||
|
|||||||
255
PARR.DAL.Tests/TestDataGenerator.cs
Normal file
255
PARR.DAL.Tests/TestDataGenerator.cs
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using PARR.DAL.Context;
|
||||||
|
using PARR.DAL.Contracts;
|
||||||
|
using PARR.DAL.Models.Job;
|
||||||
|
using PARR.DAL.Models.Unit;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
|
namespace PARR.DAL.Tests
|
||||||
|
{
|
||||||
|
public static class TestDataGenerator
|
||||||
|
{
|
||||||
|
// --- Unit IDs ---
|
||||||
|
public static readonly Guid UnitAId = Guid.Parse("11111111-1111-1111-1111-111111111111");
|
||||||
|
public static readonly Guid UnitBId = Guid.Parse("00000000-0000-1111-1111-111111111111");
|
||||||
|
public static readonly Guid UnitCId = Guid.Parse("22222222-2222-2222-2222-222222222222");
|
||||||
|
public static readonly Guid UnitDId = Guid.Parse("33333333-3333-3333-3333-333333333333");
|
||||||
|
public static readonly Guid UnitWId = Guid.Parse("44444444-4444-4444-4444-444444444444");
|
||||||
|
public static readonly Guid UnitXId = Guid.Parse("55555555-5555-5555-5555-555555555555");
|
||||||
|
public static readonly Guid UnitYId = Guid.Parse("66666666-6666-6666-6666-666666666666");
|
||||||
|
public static readonly Guid UnitZId = Guid.Parse("77777777-7777-7777-7777-777777777777");
|
||||||
|
|
||||||
|
// --- Field IDs (для обхода составного ключа UnitFilterId+FieldId) ---
|
||||||
|
public static readonly Guid FieldId1 = Guid.Parse("08b42860-09a7-4a1f-aa4f-0290e86df883");//ТИП_ЭК
|
||||||
|
public static readonly Guid FieldId2 = Guid.Parse("5b2d3f5b-a9f3-4a6b-9142-70ef4357ac37"); //неуникальный
|
||||||
|
public static readonly Guid FieldId3 = Guid.Parse("5f3c7b8b-583d-411b-b9bd-1e045ddc5a8e");//ПОДКАТЕГОРИЯ_ЭК
|
||||||
|
public static readonly Guid FieldId4 = Guid.Parse("3e9ac5aa-531b-4ffc-8f93-694d00aa92a0");//активный
|
||||||
|
|
||||||
|
// --- Field Value IDs ---
|
||||||
|
public static readonly Guid FieldValueId1 = Guid.Parse("fe18edcd-ab6a-4f3e-b7bc-e54aad9ecc0d"); // система хранения данных (схд) field3
|
||||||
|
public static readonly Guid FieldValueId2 = Guid.Parse("f385b22c-42c3-4db9-bd41-b829603cc2d9"); // 1 field2+field4
|
||||||
|
public static readonly Guid FieldValueId3 = Guid.Parse("2badc139-69cb-4d52-830a-1b3c6a9faf9d"); // 0 field2+field4
|
||||||
|
public static readonly Guid FieldValueId4 = Guid.Parse("fde68ef7-a07e-4c10-872c-cd98c3d1c30b"); // коммутатор
|
||||||
|
public static readonly Guid FieldValueId5 = Guid.Parse("9f169862-3f78-49f2-b967-13b5b2f56231"); // серверное оборудование
|
||||||
|
public static readonly Guid FieldValueId6 = Guid.Parse("075b6fad-d24f-40f4-aa0e-83a4cfc46bbf"); // стойка цвк
|
||||||
|
public static readonly Guid FieldValueId7 = Guid.Parse("9679afd8-8004-4ce2-bd6f-9005b037ef96"); // схд
|
||||||
|
|
||||||
|
internal static void Seed(DataContext context)
|
||||||
|
{
|
||||||
|
if (context.Units.Any()) return;
|
||||||
|
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
// 1. Значения полей (остаются те же)
|
||||||
|
var fieldValues = new[]
|
||||||
|
{
|
||||||
|
new UnitFieldValue { Id = FieldValueId1, Value = "система хранения данных (схд)", DateCreated = now },
|
||||||
|
new UnitFieldValue { Id = FieldValueId2, Value = "1", DateCreated = now },
|
||||||
|
new UnitFieldValue { Id = FieldValueId3, Value = "0", DateCreated = now },
|
||||||
|
new UnitFieldValue { Id = FieldValueId4, Value = "коммутатор", DateCreated = now },
|
||||||
|
};
|
||||||
|
context.UnitFieldValues.AddRange(fieldValues);
|
||||||
|
|
||||||
|
// 2. Unit'ы
|
||||||
|
var units = new[]
|
||||||
|
{
|
||||||
|
new Unit { Id = UnitAId, Name = "СХД-КМТ-DVGD-MDS9148-1-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitBId, Name = "СХД-КМТ-DVGD-MDS9148-2-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitCId, Name = "СРВ-СТОЙКА-СТОЙКА-ХИВЦ-4.0-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitDId, Name = "СХД-VSP-E590-01-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitWId, Name = "СХД-КМТ-SAN1_FAB_1-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitXId, Name = "СХД-КМТ-CISCO-MDS9148-1-ДВС", DateCreated = now },
|
||||||
|
new Unit { Id = UnitYId, Name = "СХД-КМТ-CISCO-MDS9148-3-ДВС", DateCreated = now },
|
||||||
|
};
|
||||||
|
context.Units.AddRange(units);
|
||||||
|
|
||||||
|
// 3. UnitInUnit (связи)
|
||||||
|
var unitInUnits = new[]
|
||||||
|
{
|
||||||
|
new UnitInUnit { ParentUnitId = UnitAId, ChildUnitId = UnitCId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitBId, ChildUnitId = UnitCId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitDId, ChildUnitId = UnitAId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitDId, ChildUnitId = UnitBId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitWId, ChildUnitId = UnitXId, DateCreated = now },
|
||||||
|
new UnitInUnit { ParentUnitId = UnitWId, ChildUnitId = UnitYId, DateCreated = now }
|
||||||
|
};
|
||||||
|
context.UnitInUnits.AddRange(unitInUnits);
|
||||||
|
|
||||||
|
// 4. UnitInValue
|
||||||
|
var unitInValues = new List<UnitInValue>
|
||||||
|
{
|
||||||
|
// Основные (FieldId)
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitAId, FieldId = FieldId2, ValueId = FieldValueId3, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId2, ValueId = FieldValueId3, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitBId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitCId, FieldId = FieldId3, ValueId = FieldValueId5, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitCId, FieldId = FieldId1, ValueId = FieldValueId6, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitCId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitDId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitDId, FieldId = FieldId1, ValueId = FieldValueId7, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitDId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitWId, FieldId = FieldId2, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitXId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitXId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitXId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitYId, FieldId = FieldId3, ValueId = FieldValueId1, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitYId, FieldId = FieldId1, ValueId = FieldValueId4, DateCreated = now },
|
||||||
|
new UnitInValue { UnitId = UnitYId, FieldId = FieldId4, ValueId = FieldValueId2, DateCreated = now },
|
||||||
|
|
||||||
|
};
|
||||||
|
context.UnitInValues.AddRange(unitInValues);
|
||||||
|
|
||||||
|
// 5. JobGroupType и Group
|
||||||
|
var groupType = context.JobGroupTypes
|
||||||
|
.FirstOrDefault(t => t.Code == JobGroupTypesEnum.Simple)
|
||||||
|
?? throw new InvalidOperationException("JobGroupType 'Simple' не найден в контексте.");
|
||||||
|
|
||||||
|
var group = new JobGroup
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
GroupTypeId = groupType.Id,
|
||||||
|
GroupType = groupType,
|
||||||
|
GroupName = "Группа",
|
||||||
|
ShortDescription = "%ТНК-КРАТКО% %ЭК%",
|
||||||
|
FullDescription = "Подробно:\n%СВЯЗИ%",
|
||||||
|
Solution = "Решение",
|
||||||
|
TemplateDuration = "540 00:00:00",
|
||||||
|
ReferenceDate = now,
|
||||||
|
IsAutoDistributionEnabled = false,
|
||||||
|
IsAgent = false,
|
||||||
|
DateCreated = now
|
||||||
|
};
|
||||||
|
context.JobGroups.Add(group);
|
||||||
|
|
||||||
|
// 6. Jobs
|
||||||
|
var jobs = new List<Job>();
|
||||||
|
|
||||||
|
// --- TestJob ---
|
||||||
|
var job1 = new Job
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Name = "TestJob_1",
|
||||||
|
WorkName = "Работа",
|
||||||
|
TemplateNameMask = "%ЭК%",
|
||||||
|
WorkGroupMask = "%ГРУППА_РАБОТ%",
|
||||||
|
GroupId = group.Id,
|
||||||
|
TnkId = Guid.NewGuid(),
|
||||||
|
Group = group,
|
||||||
|
DateCreated = now
|
||||||
|
};
|
||||||
|
var unitFilter1Id = Guid.NewGuid();
|
||||||
|
job1.UnitFilters = new List<JobUnitFilter>
|
||||||
|
{
|
||||||
|
new JobUnitFilter
|
||||||
|
{
|
||||||
|
Id = unitFilter1Id,
|
||||||
|
UnitFilter = "СХД-%",
|
||||||
|
JobId = job1.Id,
|
||||||
|
Job = job1,
|
||||||
|
DateCreated = now,
|
||||||
|
FieldFilters = new List<JobFieldFilter>
|
||||||
|
{
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter1Id,
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask="коммутатор"
|
||||||
|
},
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter1Id,
|
||||||
|
FieldId = FieldId4,
|
||||||
|
ValueMask="1"
|
||||||
|
},
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter1Id,
|
||||||
|
FieldId = FieldId2,
|
||||||
|
ValueMask="0"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
RelationshipFilters = new List<JobRelationshipFilter>
|
||||||
|
{
|
||||||
|
new JobRelationshipFilter
|
||||||
|
{
|
||||||
|
IsParent = true,
|
||||||
|
IsInverse = true,
|
||||||
|
IsFullMatch = true,
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask = "коммутатор",
|
||||||
|
UnitFilterId = unitFilter1Id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
jobs.Add(job1);
|
||||||
|
|
||||||
|
// --- TestJob_2 (с IsParent = false для дочерних связей) ---
|
||||||
|
var job2 = new Job
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Name = "TestJob_2",
|
||||||
|
WorkName = "Работа2",
|
||||||
|
TemplateNameMask = "%ЭК%",
|
||||||
|
WorkGroupMask = "%ГРУППА_РАБОТ%",
|
||||||
|
GroupId = group.Id,
|
||||||
|
TnkId = Guid.NewGuid(),
|
||||||
|
Group = group,
|
||||||
|
DateCreated = now
|
||||||
|
};
|
||||||
|
var unitFilter2Id = Guid.NewGuid();
|
||||||
|
job2.UnitFilters = new List<JobUnitFilter>
|
||||||
|
{
|
||||||
|
new JobUnitFilter
|
||||||
|
{
|
||||||
|
Id = unitFilter2Id,
|
||||||
|
UnitFilter = "СХД-%",
|
||||||
|
JobId = job2.Id,
|
||||||
|
Job = job2,
|
||||||
|
DateCreated = now,
|
||||||
|
FieldFilters = new List<JobFieldFilter>
|
||||||
|
{
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter2Id,
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask="коммутатор"
|
||||||
|
},
|
||||||
|
new JobFieldFilter
|
||||||
|
{
|
||||||
|
UnitFilterId = unitFilter2Id,
|
||||||
|
FieldId = FieldId4,
|
||||||
|
ValueMask="1"
|
||||||
|
},
|
||||||
|
},
|
||||||
|
RelationshipFilters = new List<JobRelationshipFilter>
|
||||||
|
{
|
||||||
|
new JobRelationshipFilter
|
||||||
|
{
|
||||||
|
IsParent = false, // <-- Новый фильтр: ищем дочерние юниты
|
||||||
|
IsInverse = false, // <-- Простой фильтр
|
||||||
|
IsFullMatch = false, // <-- Простой фильтр
|
||||||
|
FieldId = FieldId1,
|
||||||
|
ValueMask = "коммутатор",
|
||||||
|
UnitFilterId = unitFilter2Id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
jobs.Add(job2);
|
||||||
|
|
||||||
|
context.Jobs.AddRange(jobs);
|
||||||
|
context.SaveChanges();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
using PARR.DAL.Contracts;
|
using PARR.DAL.Contracts;
|
||||||
using PARR.DAL.DomainServices.Interfaces;
|
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.Job;
|
||||||
using PARR.DAL.Services.Interfaces.Unit;
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
@@ -10,55 +13,77 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
internal class ShortcodesService : IShortcodesService
|
internal class ShortcodesService : IShortcodesService
|
||||||
{
|
{
|
||||||
private const string shortcodePattern = "%[^%\\s]+%";
|
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 SettingsFromDb settingsFromDb;
|
||||||
private readonly IJobService jobService;
|
private readonly IJobService jobService;
|
||||||
private readonly IUnitService unitService;
|
private readonly IUnitService unitService;
|
||||||
|
private readonly IUnitFilterService unitFilterService;
|
||||||
|
|
||||||
public ShortcodesService(
|
public ShortcodesService(
|
||||||
|
ILogger<ShortcodesService> logger,
|
||||||
SettingsFromDb settingsFromDb,
|
SettingsFromDb settingsFromDb,
|
||||||
IJobService jobService,
|
IJobService jobService,
|
||||||
IUnitService unitService
|
IUnitService unitService,
|
||||||
|
IUnitFilterService unitFilterService
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
|
this.logger = logger;
|
||||||
this.settingsFromDb = settingsFromDb;
|
this.settingsFromDb = settingsFromDb;
|
||||||
this.jobService = jobService;
|
this.jobService = jobService;
|
||||||
this.unitService = unitService;
|
this.unitService = unitService;
|
||||||
|
this.unitFilterService = unitFilterService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<string> ApplyShortcodesAsync(string str, Guid unitId, Guid jobId)
|
public async Task<string> ApplyShortcodesAsync(string str, Guid unitId, Guid jobId)
|
||||||
{
|
{
|
||||||
//TODO удалить старый в GeneralExtesions, связанные с ним Enum и написать метод. делов...
|
|
||||||
|
|
||||||
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
|
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
|
||||||
|
|
||||||
var job = await jobService
|
var job = await jobService
|
||||||
.Get().AsNoTracking()
|
.Get().AsNoTracking()
|
||||||
.Include(t=>t.Tnk)
|
.Include(j => j.Tnk)
|
||||||
.Include(t=>t.Group)
|
.Include(j => j.Group)
|
||||||
.FirstOrDefaultAsync(t => t.Id == jobId);
|
.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;
|
logger.LogError("Переданы некорректные данные для подстановки динамических записей");
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
var resultName = str;
|
||||||
var shortcodesInMask = GetShortCodes(resultName);
|
var shortcodesInMask = GetShortCodes(resultName);
|
||||||
|
|
||||||
//Проверяем и меняем наличие статичных частей в маске имени шаблона
|
// 1. Статические константы
|
||||||
if (shortcodesInMask.Any(x => nameConstants.Select(x => "%" + x.Name + "%").ToList().Contains(x.Value)))
|
if (shortcodesInMask.Any(m => nameConstants.Any(c => $"%{c.Name}%".Equals(m.Value, StringComparison.OrdinalIgnoreCase))))
|
||||||
{
|
{
|
||||||
resultName = ReplaceConstants(nameConstants, resultName);
|
resultName = ReplaceConstants(nameConstants, resultName);
|
||||||
}
|
}
|
||||||
|
|
||||||
//Проверяем и меняем Shortcodes в маске имени шаблона
|
// 2. Стандартные шорткоды (%ЭК%, %РАБОТА% и т.д.)
|
||||||
var shortCodes = GetShortcodesNames();
|
if (shortcodesInMask.Any(m => SupportedShortcodes.Contains(m.Value)))
|
||||||
if (shortcodesInMask.Any(x => shortCodes.Select(x => x).ToList().Contains(x.Value)))
|
|
||||||
{
|
{
|
||||||
resultName = ReplaceShortcodes(job, unit, resultName, shortcodesInMask);
|
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);
|
shortcodesInMask = GetShortCodes(resultName);
|
||||||
if (shortcodesInMask.Count > 0)
|
if (shortcodesInMask.Count > 0)
|
||||||
{
|
{
|
||||||
@@ -68,9 +93,6 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
return resultName;
|
return resultName;
|
||||||
}
|
}
|
||||||
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public bool isAnyShortcodes(string str)
|
public bool isAnyShortcodes(string str)
|
||||||
{
|
{
|
||||||
@@ -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 == "%ЭК%"))
|
return input
|
||||||
resultName = resultName.Replace("%ЭК%", unit.Name);
|
.Replace("%ЭК%", unit.Name, StringComparison.OrdinalIgnoreCase)
|
||||||
|
.Replace("%ГРУППА_РАБОТ%", job.Group?.GroupName ?? "", StringComparison.OrdinalIgnoreCase)
|
||||||
if (shortcodesInMask.Any(x => x.Value == "%ГРУППА_РАБОТ%"))
|
.Replace("%РАБОТА%", job.WorkName, StringComparison.OrdinalIgnoreCase)
|
||||||
resultName = resultName.Replace("%ГРУППА_РАБОТ%", job.Group!.GroupName);
|
.Replace("%ТНК%", job.Tnk?.Name ?? "", StringComparison.OrdinalIgnoreCase)
|
||||||
|
.Replace("%ТНК-КРАТКО%", job.Tnk?.ShortName ?? "", StringComparison.OrdinalIgnoreCase);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -136,17 +151,5 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
var shortcodesInMask = Regex.Matches(resultName, shortcodePattern).ToList();
|
var shortcodesInMask = Regex.Matches(resultName, shortcodePattern).ToList();
|
||||||
return shortcodesInMask;
|
return shortcodesInMask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<string> GetShortcodesNames()
|
|
||||||
{
|
|
||||||
var result = new List<string> {
|
|
||||||
"%ЭК%",
|
|
||||||
"%ГРУППА_РАБОТ%",
|
|
||||||
"%РАБОТА%",
|
|
||||||
"%ТНК%"
|
|
||||||
};
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.DAL.Context;
|
||||||
using PARR.DAL.Contracts;
|
using PARR.DAL.Contracts;
|
||||||
using PARR.DAL.DomainServices.Interfaces;
|
using PARR.DAL.DomainServices.Interfaces;
|
||||||
using PARR.DAL.Models.Job;
|
using PARR.DAL.Models.Job;
|
||||||
|
using PARR.DAL.Models.Unit;
|
||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
using PARR.DAL.Services.Interfaces.Unit;
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
using System.Text.RegularExpressions;
|
|
||||||
|
|
||||||
|
|
||||||
namespace PARR.DAL.DomainServices.Implementations
|
namespace PARR.DAL.DomainServices.Implementations
|
||||||
{
|
{
|
||||||
@@ -15,75 +15,54 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
private readonly ILogger<UnitFilterService> logger;
|
private readonly ILogger<UnitFilterService> logger;
|
||||||
private readonly IJobService jobService;
|
private readonly IJobService jobService;
|
||||||
private readonly IUnitService unitService;
|
private readonly IUnitService unitService;
|
||||||
|
private readonly IUnitInUnitService unitInUnitService;
|
||||||
|
private readonly IUnitInValueService unitInValueService;
|
||||||
|
|
||||||
public UnitFilterService(
|
public UnitFilterService(
|
||||||
ILogger<UnitFilterService> logger,
|
ILogger<UnitFilterService> logger,
|
||||||
IJobService jobService,
|
IJobService jobService,
|
||||||
IUnitService unitService
|
IUnitService unitService,
|
||||||
)
|
IUnitInUnitService unitInUnitService,
|
||||||
|
IUnitInValueService unitInValueService)
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.jobService = jobService;
|
this.jobService = jobService;
|
||||||
this.unitService = unitService;
|
this.unitService = unitService;
|
||||||
|
this.unitInUnitService = unitInUnitService;
|
||||||
|
this.unitInValueService = unitInValueService;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId, int? takeCount = null)
|
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId, int? takeCount = null)
|
||||||
{
|
{
|
||||||
var job = await jobService
|
var job = await jobService
|
||||||
.Get().AsNoTracking()
|
.Get().AsNoTracking()
|
||||||
.Include(t => t.UnitFilters)
|
.Include(j => j.UnitFilters).ThenInclude(uf => uf.FieldFilters)
|
||||||
.ThenInclude(t => t.FieldFilters)
|
.Include(j => j.UnitFilters).ThenInclude(uf => uf.RelationshipFilters)
|
||||||
.Include(t => t.UnitFilters)
|
.Include(j => j.Group).ThenInclude(g => g.GroupType)
|
||||||
.ThenInclude(t => t.RelationshipFilters)
|
.FirstOrDefaultAsync(j => j.Id == jobId);
|
||||||
.Include(t => t.Group)
|
|
||||||
.ThenInclude(t => t.GroupType)
|
|
||||||
.FirstOrDefaultAsync(t => t.Id == jobId);
|
|
||||||
|
|
||||||
if (job == null)
|
return job == null ? null : await GetUnitsIdByJobFilterAsync(job, takeCount);
|
||||||
return null;
|
|
||||||
|
|
||||||
return await GetUnitsIdByJobFilterAsync(job, takeCount);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Job job, int? takeCount = null)
|
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Job job, int? takeCount = null)
|
||||||
{
|
{
|
||||||
#region проверка инклудов
|
#region Проверка обязательных зависимостей
|
||||||
if (job.Group == null)
|
if (job.Group == null)
|
||||||
{
|
throw new ArgumentNullException(nameof(job.Group), $"Job {job.Id} не содержит Group");
|
||||||
logger.LogWarning("JobId={JobId} не содержит Group - пропускаем фильтрацию", job.Id);
|
|
||||||
throw new ArgumentNullException(nameof(Group));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (job.Group.GroupType == null)
|
if (job.Group.GroupType == null)
|
||||||
{
|
throw new ArgumentNullException(nameof(job.Group.GroupType), $"Job {job.Id} не содержит GroupType");
|
||||||
logger.LogWarning("JobId={JobId} не содержит GroupType - пропускаем фильтрацию", job.Id);
|
|
||||||
throw new ArgumentNullException(nameof(JobGroupType));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (job.UnitFilters == null || !job.UnitFilters.Any())
|
if (job.UnitFilters == null || !job.UnitFilters.Any())
|
||||||
{
|
throw new ArgumentNullException(nameof(job.UnitFilters), $"Job {job.Id} не содержит UnitFilters");
|
||||||
logger.LogWarning("JobId={JobId} не содержит UnitFilters - пропускаем фильтрацию", job.Id);
|
|
||||||
throw new ArgumentNullException(nameof(JobUnitFilter));
|
|
||||||
}
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
var maxCount = takeCount ?? int.MaxValue;
|
var maxCount = takeCount ?? int.MaxValue;
|
||||||
var collectedIds = new HashSet<Guid>(); // ← гарантирует уникальность
|
var collectedIds = new HashSet<Guid>();
|
||||||
var filterNumber = 0;
|
var filterNumber = 0;
|
||||||
|
|
||||||
foreach (var filter in job.UnitFilters)
|
foreach (var filter in job.UnitFilters)
|
||||||
{
|
{
|
||||||
filterNumber++;
|
filterNumber++;
|
||||||
|
if (collectedIds.Count >= maxCount) break;
|
||||||
// Прекращаем, если набрали достаточно
|
|
||||||
if (collectedIds.Count >= maxCount)
|
|
||||||
{
|
|
||||||
logger.LogDebug("Достигнут лимит takeCount={TakeCount} после {FilterCount} фильтров", maxCount, filterNumber - 1);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
var remaining = maxCount - collectedIds.Count;
|
var remaining = maxCount - collectedIds.Count;
|
||||||
if (remaining <= 0) break;
|
if (remaining <= 0) break;
|
||||||
|
|
||||||
@@ -91,183 +70,34 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
{
|
{
|
||||||
logger.LogDebug("Применяем фильтр #{Index} (Id={FilterId})", filterNumber, filter.Id);
|
logger.LogDebug("Применяем фильтр #{Index} (Id={FilterId})", filterNumber, filter.Id);
|
||||||
|
|
||||||
// Стартуем с базового условия — имя Unit'а
|
|
||||||
var query = unitService.Get().AsNoTracking()
|
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);
|
logger.LogDebug("Базовый фильтр по Name: {NameFilter}", filter.UnitFilter);
|
||||||
|
|
||||||
// 1. Фильтры по полям (UnitValues)
|
|
||||||
foreach (var fieldFilter in filter.FieldFilters)
|
foreach (var fieldFilter in filter.FieldFilters)
|
||||||
{
|
{
|
||||||
var fieldId = fieldFilter.FieldId;
|
query = ApplyFieldFilter(query, fieldFilter);
|
||||||
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)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Фильтры по связям (родителям и детям)
|
|
||||||
foreach (var relFilter in filter.RelationshipFilters)
|
foreach (var relFilter in filter.RelationshipFilters)
|
||||||
{
|
{
|
||||||
var fieldId = relFilter.FieldId;
|
query = ApplyRelationshipFilterToQuery(query, relFilter);
|
||||||
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))));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Ограничение по количеству связей (только для umbrella-групп)
|
|
||||||
if (job.Group.GroupType.Code == JobGroupTypesEnum.Umbrella)
|
if (job.Group.GroupType.Code == JobGroupTypesEnum.Umbrella)
|
||||||
{
|
{
|
||||||
int min = job.MinValueRelationships.GetValueOrDefault(0);
|
query = ApplyRelationshipCountFilter(query, job);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Выполняем — только Id, с учётом оставшегося лимита
|
|
||||||
var newIds = await query
|
var newIds = await query
|
||||||
.Select(unit => unit.Id)
|
.Select(u => u.Id)
|
||||||
.Take(remaining)
|
.Take(remaining)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
logger.LogDebug("Фильтр #{Index}: найдено {Count} Unit'ов", filterNumber, newIds.Count);
|
|
||||||
|
|
||||||
collectedIds.UnionWith(newIds);
|
collectedIds.UnionWith(newIds);
|
||||||
|
logger.LogDebug("Фильтр #{Index}: найдено {Count} Unit'ов. Всего: {Total}",
|
||||||
logger.LogDebug(
|
filterNumber, newIds.Count, collectedIds.Count);
|
||||||
"Фильтр #{Index} (Id={FilterId}): найдено {Count} Unit'ов. Всего: {Total}",
|
|
||||||
filterNumber, filter.Id, newIds.Count, collectedIds.Count);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -282,5 +112,265 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
|
|
||||||
return result;
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,18 +5,35 @@ namespace PARR.DAL.DomainServices.Interfaces
|
|||||||
public interface IUnitFilterService
|
public interface IUnitFilterService
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить все Unit.Id соответствующие настройкам фильтрации Job
|
/// Получает список ID Unit'ов, соответствующих фильтрам Job.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="jobId">Id работы</param>
|
/// <param name="jobId">ID Job</param>
|
||||||
/// <returns></returns>
|
/// <param name="takeCount">Максимальное количество Unit'ов (опционально)</param>
|
||||||
Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId, int? takeCount = null);
|
/// <returns>Список ID Unit'ов или null, если Job не найден</returns>
|
||||||
|
Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(
|
||||||
|
Guid jobId,
|
||||||
|
int? takeCount = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить все Unit.Id соответствующие настройкам фильтрации Job
|
/// Получает список ID Unit'ов, соответствующих фильтрам Job.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="job">Job обязательно должен содержать UnitFilter, Group и GroupType</param>
|
/// <param name="job">Job с предзагруженными UnitFilters, Group, GroupType</param>
|
||||||
/// <returns></returns>
|
/// <param name="takeCount">Максимальное количество Unit'ов (опционально)</param>
|
||||||
Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Job job, int? takeCount = null);
|
/// <returns>Список ID Unit'ов</returns>
|
||||||
|
Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(
|
||||||
|
Models.Job.Job job,
|
||||||
|
int? takeCount = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получает имена связанных Unit'ов для заданного Unit, отфильтрованных по RelationshipFilters Job.
|
||||||
|
/// Используется для шорткода %СВЯЗИ%.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="jobId">ID Job</param>
|
||||||
|
/// <param name="unitId">ID Unit, для которого ищутся связи</param>
|
||||||
|
/// <param name="ct">Токен отмены (опционально)</param>
|
||||||
|
/// <returns>Список имён связанных Unit'ов (уникальные, без дублей)</returns>
|
||||||
|
Task<List<string>> GetRelatedUnitNamesAsync(
|
||||||
|
Guid jobId,
|
||||||
|
Guid unitId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,11 +24,4 @@
|
|||||||
<ProjectReference Include="..\PARR.Common\PARR.Common.csproj" />
|
<ProjectReference Include="..\PARR.Common\PARR.Common.csproj" />
|
||||||
<ProjectReference Include="..\PARR.Constants\PARR.Constants.csproj" />
|
<ProjectReference Include="..\PARR.Constants\PARR.Constants.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
|
||||||
<_Parameter1>PARR.DAL.Tests</_Parameter1>
|
|
||||||
</AssemblyAttribute>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -98,6 +98,8 @@ namespace PARR.DAL
|
|||||||
services.AddTransient<IUnitService, UnitService>();
|
services.AddTransient<IUnitService, UnitService>();
|
||||||
services.AddTransient<IUnitFieldValueService, UnitFieldValueService>();
|
services.AddTransient<IUnitFieldValueService, UnitFieldValueService>();
|
||||||
services.AddTransient<IUnitFieldService, UnitFieldService>();
|
services.AddTransient<IUnitFieldService, UnitFieldService>();
|
||||||
|
services.AddTransient<IUnitInUnitService, UnitInUnitService>();
|
||||||
|
services.AddTransient<IUnitInValueService, UnitInValueService>();
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|||||||
5
PARR.DAL/Properties/AssemblyInfo.cs
Normal file
5
PARR.DAL/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[assembly: InternalsVisibleTo("PARR.DAL.Tests")]
|
||||||
|
[assembly: InternalsVisibleTo("PARR.DAL.IntegrationTests")]
|
||||||
|
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
|
||||||
40
PARR.DAL/Services/Implementations/Unit/UnitInUnitService.cs
Normal file
40
PARR.DAL/Services/Implementations/Unit/UnitInUnitService.cs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.DAL.Context;
|
||||||
|
using PARR.DAL.Models.Unit;
|
||||||
|
using PARR.DAL.Services.Abstracts;
|
||||||
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
|
|
||||||
|
namespace PARR.DAL.Services.Implementations.Unit
|
||||||
|
{
|
||||||
|
internal class UnitInUnitService : IUnitInUnitService
|
||||||
|
{
|
||||||
|
private readonly DataContext dataContext;
|
||||||
|
private readonly ILogger<UnitInUnitService> logger;
|
||||||
|
|
||||||
|
public UnitInUnitService(
|
||||||
|
DataContext dataContext,
|
||||||
|
ILogger<UnitInUnitService> logger
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.dataContext = dataContext;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public Task<List<UnitInUnit>> GetByParentIdAsync(Guid parentId)
|
||||||
|
{
|
||||||
|
return dataContext.UnitInUnits
|
||||||
|
.Where(u => u.ParentUnitId == parentId)
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<List<UnitInUnit>> GetByChildIdAsync(Guid childId)
|
||||||
|
{
|
||||||
|
return dataContext.UnitInUnits
|
||||||
|
.Where(u => u.ChildUnitId == childId)
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
37
PARR.DAL/Services/Implementations/Unit/UnitInValueService.cs
Normal file
37
PARR.DAL/Services/Implementations/Unit/UnitInValueService.cs
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using PARR.DAL.Context;
|
||||||
|
using PARR.DAL.Models.Unit;
|
||||||
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
|
|
||||||
|
namespace PARR.DAL.Services.Implementations.Unit
|
||||||
|
{
|
||||||
|
internal class UnitInValueService : IUnitInValueService
|
||||||
|
{
|
||||||
|
private readonly ILogger<UnitInValueService> logger;
|
||||||
|
private readonly DataContext dataContext;
|
||||||
|
|
||||||
|
public UnitInValueService(
|
||||||
|
ILogger<UnitInValueService> logger,
|
||||||
|
DataContext dataContext
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.logger = logger;
|
||||||
|
this.dataContext = dataContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<UnitInValue>> GetByUnitIdAsync(Guid unitId)
|
||||||
|
{
|
||||||
|
return await dataContext.UnitInValues
|
||||||
|
.Where(uv => uv.UnitId == unitId)
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<UnitInValue>> GetByUnitIdsAsync(IEnumerable<Guid> unitIds)
|
||||||
|
{
|
||||||
|
return await dataContext.UnitInValues
|
||||||
|
.Where(uv => unitIds.Contains(uv.UnitId))
|
||||||
|
.ToListAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
11
PARR.DAL/Services/Interfaces/Unit/IUnitInUnitService.cs
Normal file
11
PARR.DAL/Services/Interfaces/Unit/IUnitInUnitService.cs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
using PARR.DAL.Models.Unit;
|
||||||
|
using PARR.DAL.Services.Interfaces.Base;
|
||||||
|
|
||||||
|
namespace PARR.DAL.Services.Interfaces.Unit
|
||||||
|
{
|
||||||
|
public interface IUnitInUnitService
|
||||||
|
{
|
||||||
|
Task<List<UnitInUnit>> GetByParentIdAsync(Guid parentId);
|
||||||
|
Task<List<UnitInUnit>> GetByChildIdAsync(Guid childId);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
PARR.DAL/Services/Interfaces/Unit/IUnitInValueService.cs
Normal file
15
PARR.DAL/Services/Interfaces/Unit/IUnitInValueService.cs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
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
|
||||||
|
{
|
||||||
|
public interface IUnitInValueService
|
||||||
|
{
|
||||||
|
Task<List<UnitInValue>> GetByUnitIdsAsync(IEnumerable<Guid> unitIds);
|
||||||
|
Task<List<UnitInValue>> GetByUnitIdAsync(Guid unitId);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user