feat(dal): Реализован сервис UnitFilterService для получения Unit, для которых требуется создать или уже создан шаблон по Job.Id

This commit is contained in:
Mikhail Kuznetsov
2025-08-12 11:50:29 +10:00
parent 97af546654
commit 1272ce92ec
12 changed files with 189 additions and 114 deletions

View File

@@ -155,7 +155,7 @@ namespace PARR.AIHITMainLoader.Models
{
{"IP_АДРЕС", IP },
//{"МЕТКА", Metka },
//{"АКТИВЕН", IsActive },
{"АКТИВЕН", IsActive },
//{"ВАЖНЫЙ_ЭК", IsImportant },
//{"ВРЕМЯ_СОЗДАНИЯ", CreateTime.ToString() ?? null},
//{"ДОПОЛНИТЕЛЬНАЯ_ИНФОРМАЦИЯ", AdditionalInfo },

View File

@@ -11,7 +11,7 @@ using PARR.API.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainServices;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.TransformServices;

View File

@@ -1,23 +0,0 @@
using AutoMapper;
using PARR.API.Contracts.V1.Responses;
using PARR.DAL.DomainServices;
using PARR.DAL.Models;
namespace PARR.API.MappingProfiles.Resolvers
{
public class RobotTaskTemplateShortCodeResolver : IValueResolver<RobotConfiguration, RobotTaskTemplateResponse, string>
{
private readonly IShortcodesService shortcodesService;
public RobotTaskTemplateShortCodeResolver(
IShortcodesService shortcodesService
)
{
this.shortcodesService = shortcodesService;
}
public string Resolve(RobotConfiguration source, RobotTaskTemplateResponse destination, string destMember, ResolutionContext context)
{
throw new NotImplementedException();
}
}
}

View File

@@ -1,10 +1,11 @@
using Microsoft.EntityFrameworkCore;
using PARR.DAL.Contracts;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
using System.Text.RegularExpressions;
namespace PARR.DAL.DomainServices
namespace PARR.DAL.DomainServices.Implementations
{
internal class ShortcodesService : IShortcodesService
{

View File

@@ -1,10 +1,11 @@
using Microsoft.EntityFrameworkCore;
using PARR.DAL.Contracts;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
using System.Text.RegularExpressions;
namespace PARR.DAL.DomainServices
namespace PARR.DAL.DomainServices.Implementations
{
internal class TemplateNameGeneratorService : ITemplateNameGeneratorService
{

View File

@@ -0,0 +1,133 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.Services.Interfaces.Unit;
namespace PARR.DAL.DomainServices.Implementations
{
internal class UnitFilterService : IUnitFilterService
{
private readonly ILogger<UnitFilterService> logger;
private readonly IJobService jobService;
private readonly IUnitService unitService;
private readonly ITemplateService templateService;
public UnitFilterService(
ILogger<UnitFilterService> logger,
IJobService jobService,
IUnitService unitService,
ITemplateService templateService
)
{
this.logger = logger;
this.jobService = jobService;
this.unitService = unitService;
this.templateService = templateService;
}
public async Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId)
{
var result = new List<Guid>();
var job = await jobService
.Get().AsNoTracking()
.Include(t => t.UnitFilters)
.ThenInclude(t => t.FieldFilters)
.Include(t => t.UnitFilters)
.ThenInclude(t => t.RelationshipFilters)
.FirstOrDefaultAsync(t => t.Id == jobId);
if (job == null)
return null;
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);
logger.LogInformation($"В baseQuery записей {await baseQuery.CountAsync()}");
foreach (var unitFilter in job.UnitFilters)
{
var query = baseQuery.Where(t => EF.Functions.ILike(t.Name, unitFilter.UnitFilter));
foreach (var fieldFilter in unitFilter.FieldFilters)
query = query.Where(t => t.UnitValues.Any(x => x.FieldId == fieldFilter.FieldId && (x.Value!.Value != null && EF.Functions.ILike(x.Value!.Value, fieldFilter.ValueMask))));
if (unitFilter.RelationshipFilters.Any())
{
var parentFilters = unitFilter.RelationshipFilters.Where(t => t.IsParent == true).ToList();
foreach (var parentFilter in parentFilters)
{
if (parentFilter.IsInverse == false)
{
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!.Value != null && EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask)))));
else
query = query.Where(t => !t.ParentUnits.Any() || t.ParentUnits.Any(p => p.ParentUnit!.UnitValues.Any(pf => pf.FieldId == parentFilter.FieldId && (pf.Value!.Value != null && EF.Functions.ILike(pf.Value.Value, parentFilter.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!.Value != null && EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask)))));
else
query = query.Where(t => !t.ParentUnits.Any() || !t.ParentUnits.Any(p => p.ParentUnit!.UnitValues.Any(pf => pf.FieldId == parentFilter.FieldId && (pf.Value!.Value != null && EF.Functions.ILike(pf.Value.Value, parentFilter.ValueMask)))));
}
logger.LogInformation($"!В query записей {await query.CountAsync()}");
}
}
var newUnits = await query.Select(t => t.Id).ToListAsync();
result.AddRange(newUnits);
}
return result;
}
public async Task<IEnumerable<Guid>?> GetUnitsIdForExistTemplatesByJobFilterAsync(Guid jobId)
{
var unitIdsMustBeCreated = await GetUnitsIdByJobFilterAsync(jobId);
if (unitIdsMustBeCreated == null || !unitIdsMustBeCreated.Any())
return null;
var unitWithTemplates = await templateService.Get().AsNoTracking().Where(t => t.JobId == jobId && unitIdsMustBeCreated.Any(x => x == t.UnitId)).Select(t => t.UnitId).ToListAsync();
return unitWithTemplates;
}
public async Task<IEnumerable<Guid>?> GetUnitsIdForNotExistTemplatesByJobFilterAsync(Guid jobId)
{
var unitIdsMustBeCreated = await GetUnitsIdByJobFilterAsync(jobId);
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;
}
}
}

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PARR.DAL.DomainServices
namespace PARR.DAL.DomainServices.Interfaces
{
public interface IShortcodesService
{

View File

@@ -6,7 +6,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PARR.DAL.DomainServices
namespace PARR.DAL.DomainServices.Interfaces
{
public interface ITemplateNameGeneratorService
{

View File

@@ -0,0 +1,27 @@
namespace PARR.DAL.DomainServices.Interfaces
{
public interface IUnitFilterService
{
/// <summary>
/// Получить все Unit.Id, для которых должны быть созданы Template
/// </summary>
/// <param name="jobId">Id работы</param>
/// <returns></returns>
Task<IEnumerable<Guid>?> GetUnitsIdByJobFilterAsync(Guid jobId);
/// <summary>
/// Получить все Unit.Id, для которых не были созданы Template
/// </summary>
/// <param name="jobId">Id работы</param>
/// <returns></returns>
Task<IEnumerable<Guid>?> GetUnitsIdForNotExistTemplatesByJobFilterAsync(Guid jobId);
/// <summary>
/// Получить все Unit.Id, для которых были созданы Template
/// </summary>
/// <param name="jobId">Id работы</param>
/// <returns></returns>
Task<IEnumerable<Guid>?> GetUnitsIdForExistTemplatesByJobFilterAsync(Guid jobId);
}
}

View File

@@ -5,7 +5,8 @@ using PARR.DAL.CacheServices;
using PARR.DAL.Configurations.DbSettings;
using PARR.DAL.Context;
using PARR.DAL.Contracts;
using PARR.DAL.DomainServices;
using PARR.DAL.DomainServices.Implementations;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.InfluxDbServices;
using PARR.DAL.Services.Implementation;
using PARR.DAL.Services.Implementations;
@@ -99,6 +100,7 @@ namespace PARR.DAL
services.AddTransient<IUnitService, UnitService>();
services.AddTransient<IUnitFieldValueService, UnitFieldValueService>();
services.AddTransient<IUnitFieldService, UnitFieldService>();
services.AddTransient<IUnitFilterService, UnitFilterService>();
#endregion

View File

@@ -2,7 +2,7 @@
using Microsoft.Extensions.Logging;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.DomainServices;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
using System.Reflection;

View File

@@ -1,15 +1,11 @@
using Elastic.CommonSchema;
using Microsoft.EntityFrameworkCore;
using PARR.BLL.Services.Interfaces;
using PARR.Constants;
using PARR.DAL.DomainServices;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.DAL.DomainServices.Interfaces;
using PARR.DAL.Services.Interfaces.Unit;
using PARR.EsppApi;
using PARR.EsppApi.Constants;
using PARR.EsppApi.Models.Query;
using System.Net.WebSockets;
namespace PARR.Test
{
@@ -39,85 +35,29 @@ namespace PARR.Test
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
#region test
using (var scope = serviceProvider.CreateScope())
{
var unitService = scope.ServiceProvider.GetService<IUnitService>();
//using (var scope = serviceProvider.CreateScope())
//{
// var unitFilterService = scope.ServiceProvider.GetService<IUnitFilterService>();
var unitsQuery = unitService!.Get()
.Include(t => t.UnitValues)
.ThenInclude(t => t.Field)
.Include(t => t.UnitValues)
.ThenInclude(t => t.Value)
.Where(t => /*EF.Functions.Like(t.Name, "%-ГВЦ") &&*/
t.UnitValues.Any(v =>
v.Field!.AihitName == ОДКАТЕГОРИЯ_ЭК" && v.Value!.Value == "система хранения данных (схд)")
&& t.UnitValues.Any(v =>
v.Field!.AihitName == "ТИП_ЭК" && v.Value!.Value == "коммутатор")
//&& t.UnitValues.Any(v =>
// v.Field!.AihitName == "АКТИВЕН" && v.Value!.Value == "1")
&& t.UnitValues.Any(v =>
v.Field!.AihitName == "НЕУНИКАЛЬНЫЙ_ЭК" && v.Value!.Value == "0")
&& !t.UnitValues.Any(v =>
v.Field!.AihitName == "СТАТУС" && v.Value!.Value == "6-Выведен из эксплуатации")
);
// if (unitFilterService == null)
// return;
var v1 = await unitsQuery
.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)
.ToListAsync();
var res = v1
.Where(t => (t.ParentUnits == null || t.ParentUnits.Count == 0) || !t.ParentUnits!.Any(a => a.ParentUnit != null && a.ParentUnit!.BaseFields!.NotUnique == "1"))
.OrderBy(t => t.Name).ToList();
var service = scope.ServiceProvider.GetService<ITemplateNameGeneratorService>();
foreach (var item in res)
{
var name = await service!.GetTemplateNameAsync(Guid.Parse("926793f7-c6d3-4f08-b5ce-517ce1a1ac37"), item.Id);
// var jobId = Guid.Parse("58b28517-8178-4683-a519-22f5989c9912");
// var unitsId = await unitFilterService.GetUnitsIdByJobFilterAsync(jobId);
// var unitService = scope.ServiceProvider.GetService<IUnitService>();
// if (unitService == null)
// return;
// var tForCreate = await unitFilterService.GetUnitsIdForExistTemplatesByJobFilterAsync(jobId);
// if (tForCreate == null)
// return;
// var units = await unitService
// .Get().AsNoTracking()
// .Where(t => tForCreate.Any(x => x == t.Id)).ToListAsync();
}
/*var service = scope.ServiceProvider.GetService<ITemplateNameGeneratorService>();
var ttt = await service.GetTemplateNameAsync(Guid.Parse("ba05948b-b040-48cc-ab77-0accc9c223a0"), Guid.Parse("d4a86f24-6975-4614-98ab-431f26e3eb69"));*/
//var service = scope.ServiceProvider.GetService<ITemplateService>();
//var templates = await service.Get()
// .Include(t => t.ApplicationsInWork)
// .ThenInclude(t=>t.Work)
// //.Select(s => new { s.Id, s.Host, s.HostId, s.JobId, s.UnitId })
// .Where(t => t.JobId == Guid.Parse("ba05948b-b040-48cc-ab77-0accc9c223a0")
// ).ToListAsync();
//var workNames = templates.Select(t=>t.ApplicationsInWork!.Work!.TemplateSuffix).Distinct();
//var jobService = scope.ServiceProvider.GetService<IJobService>();
//var jobs = await jobService!.Get().Where(t => workNames.Any(tt => tt == t.Name)).ToListAsync();
////var hostsName = templates.Select(t => t.Host!.Ek);
////var unitService = scope.ServiceProvider.GetService<IUnitService>();
////var units = await unitService.Get()
//// //.Select(s => new { s.Id, s.Name })
//// .Where(t => hostsName.Any(tt => tt == t.Name))
//// .ToListAsync();
//foreach (var t in templates) {
// var workName = t.ApplicationsInWork!.Work!.TemplateSuffix;
// //var unitId = units.FirstOrDefault(u => u.Name == hostName);
// var jobId = jobs.FirstOrDefault(t => t.Name == workName);
// if (jobId != null)
// t.JobId = jobId.Id;
//}
//await service.CommitAsync();
}
//var tName = "ДВС-ЭИТИ-ПТК-ПАРР__ВРТ-VCD-02-ДВС__ПРОЧЕЕ(РАБОТЫ)";
//var prefix = "ЭИТИ-ПТК-ПАРР";
////templateName.Contains(settingsFromDb.TemplatePrefixWithoutVariable, StringComparison.CurrentCultureIgnoreCase)
//var res = tName.Contains(prefix);
#endregion
#region unit