Compare commits

...

23 Commits

Author SHA1 Message Date
Mikhail Kuznetsov
9c27f81fe8 feat(templateMatcher): Приоритет автоконтроля JobGroup>Job при создании/переиспользовании шаблона 2026-07-03 11:59:46 +10:00
Mikhail Trubnikov
36e866f637 fix(test): Исправлен using 2026-07-03 11:36:12 +10:00
Mikhail Kuznetsov
1affa34b07 fix(core, api, templateMatcher, nextRun, templateDestributor, jobAutoControl): Исправление using после предыдущего рафакторинга 2026-07-03 11:25:39 +10:00
Mikhail Kuznetsov
3c9e03adbb refactor(dal,api,templateMatcher,templateGenerator,templateActivator): Немного порядка в namespaceах 2026-07-03 11:17:48 +10:00
Mikhail Trubnikov
143ae10190 feat(api): TemplateResponse - добавлены поля с примененными шорткодами 2026-07-03 11:16:31 +10:00
Mikhail Trubnikov
f8e16e9496 feat: Изменен NuGet.config, добавлен репозиторий dvgd 2026-07-01 16:32:38 +10:00
Mikhail Trubnikov
55ac424f1a Merge branch 'job-group-filters' into dev 2026-07-01 10:24:05 +10:00
Mikhail Trubnikov
cb3c98ed8c feat: Обвнолена версия Redis, c 7.2 до 8.8.0 2026-07-01 10:18:43 +10:00
Mikhail Trubnikov
16f97904eb feat(api,core,jobAutoControl): Валидация при получении запроса на синхронизацию групп, работ. JobAutoControlWorker - изменена логика, может обрабатывать группы и работы. 2026-06-30 16:12:52 +10:00
Mikhail Kuznetsov
52bd0d8ce1 fix(aihitLoader): Добавлены параметры понижения версии TLS 2026-06-26 12:23:07 +10:00
Mikhail Kuznetsov
65ef0dec92 fix(aihitRelationshipsSyncer): Перешли на Nexus SVRW 2026-06-26 11:59:26 +10:00
Mikhail Kuznetsov
7574cd31c2 fix(aihitRelationshipsSyncer): Финанльное исправление доверительных отношений с АИХ ИТ 2026-06-26 10:33:26 +10:00
Mikhail Kuznetsov
8a44f43a34 fix(aihitRelationshipsSyncer): Найдено решение проблемы с доверием сертификату при подключении к АИХ ИТ 2026-06-26 09:25:16 +10:00
Mikhail Kuznetsov
16ba4f21a2 fix(aihitRelationshipsSyncer): Ещё немного параметров для небезопасности с АИХ ИТ 2026-06-26 08:39:38 +10:00
Mikhail Kuznetsov
c1ff4d0258 fix(aihitRelationshipsSyncer): Дополнительные переменные параметров окружения 2026-06-25 17:27:14 +10:00
Mikhail Kuznetsov
5c2d1c31b5 fix(aihitRelationshipsSyncer): Encrypt=Optional вместо false/ 2026-06-25 17:10:23 +10:00
Mikhail Kuznetsov
806633aaf7 fix(aihitRelationshipsSyncer): Включение параметра UseUnsafeTls = treue через Program 2026-06-25 16:33:09 +10:00
Mikhail Kuznetsov
0d7969da44 fix(aihitRelationshipsSyncer): Включение старых версий TLS через Dockerfile 2026-06-25 14:51:42 +10:00
Mikhail Kuznetsov
4f2b2c204e fix(aihitMainLoader): В connectionString добавлен Encrypt=False; 2026-06-25 14:19:01 +10:00
Mikhail Kuznetsov
df6ed47bd9 fix(aihitMainLoader): В Dockerfile добавлено понижение уровня безопасности. 2026-06-25 14:01:59 +10:00
Mikhail Kuznetsov
8dfb2587b2 fix(aihitMainSyncer): Добавлен commit после синхронизации новых полей и новых значений полей: раньше вызывал null ошибку при получении Id новых значений. 2026-06-25 12:19:32 +10:00
Mikhail Trubnikov
4a8a67247d feat(api): Работы - управление автоконтролем и кол-вом связей 2026-06-19 11:19:43 +10:00
Mikhail Trubnikov
8151ea89b9 feat(api,core,dal): Группы работ - управление автокнотролем 2026-06-18 16:39:35 +10:00
117 changed files with 5154 additions and 800 deletions

View File

@@ -0,0 +1,21 @@
### 📋 Описание бага
Кратко и понятно опишите, что идет не так.
### 🔄 Шаги для воспроизведения
1. Перейти на страницу...
2. Нажать кнопку...
3. Ввести в поле поиска...
### ❌ Фактический результат
Что произошло на самом деле? (Например: Приложение завершилось с ошибкой 500).
### ✅ Ожидаемый результат
Что должно было произойти? (Например: Появился список найденных товаров).
### 🖥️ Окружение
* **ОС:** Windows 11 / macOS Sequoia
* **Браузер / Версия:** Chrome 124 / iOS App v2.1
* **Стенд:** Staging / Production
### 📎 Вложения
Скриншоты, гифки или логи, которые помогают понять проблему.

View File

@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="Nexus" value="http://10.99.253.167:8081/repository/nuget-group/" allowInsecureConnections="true"/>
<add key="Nexus-SVRW" value="http://nexus.svrw.oao.rzd/repository/nuget-group/" allowInsecureConnections="true"/>
<add key="Nexus-DVGD" value="http://10.99.253.167:8081/repository/nuget-group/index.json" protocolVersion="3" allowInsecureConnections="true"/>
<add key="Microsoft Visual Studio Offline Packages" value="C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\" />
</packageSources>
<disabledPackageSources>
<add key="Microsoft Visual Studio Offline Packages" value="true" />
<add key="nuget.org" value="true" />
<add key="Nexus-SVRW" value="true" />
</disabledPackageSources>
</configuration>

View File

@@ -27,7 +27,14 @@ FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# Fixes an old version TLS (AIH IT GVC)
RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
# 1. Принудительно настраиваем OpenSSL 3 на игнорирование непредвиденных EOF (UnsafeLegacyRenegotiation и IgnoreUnexpectedEOF)
RUN sed -i 's/providers = provider_sect/providers = provider_sect\nssl_conf = ssl_sect/' /etc/ssl/openssl.cnf \
&& printf "\n[ssl_sect]\nsystem_default = system_default_sect\n" >> /etc/ssl/openssl.cnf \
&& printf "\n[system_default_sect]\nOptions = UnsafeLegacyRenegotiation,IgnoreUnexpectedEOF\nMinProtocol = TLSv1\nCipherString = DEFAULT@SECLEVEL=0\n" >> /etc/ssl/openssl.cnf
# 2. Оставляем глобальные переменные совместимости для самого рантайма .NET 9
ENV DOTNET_AppContext_Switch_System_Net_Security_UseUnsafeOldTlsRuntimeBehavior=true
ENV DOTNET_AppContext_Switch_Microsoft_Data_SqlClient_UseOldTlsValue=true
ENV DOTNET_SYSTEM_NET_SECURITY_ALLOWUNSECUREDEFAULTS=true
ENTRYPOINT ["dotnet", "PARR.AIHITLoaderWorker.dll"]

View File

@@ -1,6 +1,6 @@
{
"ConnectionStrings": {
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;TrustServerCertificate=true;"
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;Encrypt=Optional;TrustServerCertificate=true;MultiSubnetFailover=True;"
},
"Logging": {
"LogLevel": {

View File

@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.17" />
</ItemGroup>
<ItemGroup>

View File

@@ -288,6 +288,7 @@ private async Task SyncValuesAsync(List<string?> values)
if (hasNull && !existingValuesInDb.Contains(null))
newValuesToInsert.Add(null);
// Если нет новых значений, выходим БЕЗ вызова CommitAsync
if (newValuesToInsert.Count == 0)
{
logger.LogDebug("Нет новых значений для добавления в базу данных");
@@ -302,15 +303,19 @@ private async Task SyncValuesAsync(List<string?> values)
})
.ToList();
// Только добавляем в контекст, НЕ коммитим
if (!await unitFieldValueRepository.AddRangeAsync(newFieldValues))
{
logger.LogError("Не удалось добавить {Count} новых значений FieldValues в контекст", newValuesToInsert.Count);
return;
}
else
// Коммит выполняется ТОЛЬКО если были добавлены новые сущности
if (!await unitFieldValueRepository.CommitAsync())
{
logger.LogDebug("Подготовлено {Count} новых значений FieldValues для сохранения", newValuesToInsert.Count);
logger.LogError("Не удалось сохранить {Count} новых значений FieldValues в базу данных", newValuesToInsert.Count);
return;
}
logger.LogDebug("Успешно сохранено {Count} новых значений FieldValues", newValuesToInsert.Count);
}
@@ -318,6 +323,7 @@ private async Task SyncValuesAsync(List<string?> values)
{
var newFields = fieldsFromAihit.Where(t => !fieldsFromDB.Any(f => IsStringEqual(f.AihitName, t))).ToList();
// Если нет новых полей, выходим БЕЗ вызова CommitAsync
if (!newFields.Any())
{
logger.LogDebug("Нет новых полей для добавления в базу данных");
@@ -335,19 +341,24 @@ private async Task SyncValuesAsync(List<string?> values)
EsppName = null,
};
// Только добавляем в контекст, НЕ коммитим
if (!await unitFieldRepository.CreateAsync(field))
{
logger.LogError("Не удалось добавить поле в контекст: {FieldName}", item);
continue;
}
// Коммит выполняется ТОЛЬКО после успешного добавления конкретного поля
if (!await unitFieldRepository.CommitAsync())
{
logger.LogError("Не удалось сохранить поле в базу данных: {FieldName}", item);
}
else
{
logger.LogDebug("Подготовлено поле для сохранения: {FieldName}", item);
logger.LogDebug("Успешно сохранено поле: {FieldName}", item);
}
}
}
private bool IsStringEqual(string? value1, string? value2)
{
return string.Equals(

View File

@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.20" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.17" />
</ItemGroup>
<ItemGroup>

View File

@@ -4,7 +4,6 @@
FROM 10.99.253.167:8090/dotnet/runtime:9.0 AS base
WORKDIR /app
# This stage is used to build the service project
FROM 10.99.253.167:8090/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
@@ -33,7 +32,14 @@ FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# Fixes an old version TLS (AIH IT GVC)
RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /etc/ssl/openssl.cnf
# 1. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> OpenSSL 3 <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> EOF (UnsafeLegacyRenegotiation <20> IgnoreUnexpectedEOF)
RUN sed -i 's/providers = provider_sect/providers = provider_sect\nssl_conf = ssl_sect/' /etc/ssl/openssl.cnf \
&& printf "\n[ssl_sect]\nsystem_default = system_default_sect\n" >> /etc/ssl/openssl.cnf \
&& printf "\n[system_default_sect]\nOptions = UnsafeLegacyRenegotiation,IgnoreUnexpectedEOF\nMinProtocol = TLSv1\nCipherString = DEFAULT@SECLEVEL=0\n" >> /etc/ssl/openssl.cnf
# 2. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> .NET 9
ENV DOTNET_AppContext_Switch_System_Net_Security_UseUnsafeOldTlsRuntimeBehavior=true
ENV DOTNET_AppContext_Switch_Microsoft_Data_SqlClient_UseOldTlsValue=true
ENV DOTNET_SYSTEM_NET_SECURITY_ALLOWUNSECUREDEFAULTS=true
ENTRYPOINT ["dotnet", "PARR.AIHITRelationshipsSyncerWorker.dll"]

View File

@@ -1,6 +1,6 @@
{
"ConnectionStrings": {
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;TrustServerCertificate=true;",
"AihitConnection": "Data Source=10.248.19.97; Initial Catalog=mao2;User ID=awhit-ipp-parr;pwd=ET3h$9y1LH#D;Encrypt=Optional;TrustServerCertificate=true;MultiSubnetFailover=True;",
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
},
"Logging": {

View File

@@ -1,18 +1,14 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.EntityFrameworkCore": "Debug",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
"Microsoft.AspNetCore": "Warning"
}
"ConnectionStrings": {
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
//"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Debug",
"PARR.DAL": "Information"
}
},
"WriteTo": [

View File

@@ -1,6 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
},
"Logging": {
"LogLevel": {

View File

@@ -1,52 +1,14 @@
using PARR.Domain.Enums;
namespace PARR.API.Contracts.V1.Requests
{
public class JobAutoControlRequest
namespace PARR.API.Contracts.V1.Requests
{
/// <summary>
/// Создавать новые РР (из настроке РР)
/// Часть реквеста по управлению авто контролем для Job, JobGroup
/// </summary>
public bool CreateNew { get; set; }
public record JobAutoControlRequest
{
public bool IsEnable { get; init; }
/// <summary>
/// Деактивировать не актуальные согласно ЭК (обратные статусы ЭК)
/// </summary>
public bool Deactivate { get; set; }
public bool InitUsedTemplateState { get; init; }
/// <summary>
/// Активировать РР после смены ЭК (согласно настройкам статусов ЭК)
/// </summary>
public bool Activate { get; set; }
/// <summary>
/// Состояние для активированных РР, шаблоны
/// </summary>
public bool OnTemplateIsActive { get; set; }
/// <summary>
/// Состояние для активированных РР, расписания
/// </summary>
public bool OnScheduleIsActive { get; set; }
/// <summary>
/// Состояние для деактивированных РР, шаблоны
/// </summary>
public bool OffTemplateIsActive { get; set; }
/// <summary>
/// Состояние для деактивированных РР, расписания
/// </summary>
public bool OffScheduleIsActive { get; set; }
/// <summary>
/// Маски ЭК
/// </summary>
public required List<string> EkMasks { get; set; }
/// <summary>
/// Статусы ЭК для которых включена генерация РР и активация
/// </summary>
public required List<EkStatusEnum> EnabledEkStatuses { get; set; }
public bool InitUsedScheduleState { get; init; }
}
}

View File

@@ -1,47 +1,47 @@
namespace PARR.API.Contracts.V1.Requests
{
public class JobGroupRequest
public record JobGroupRequest
{
public required string Name { get; set; }
public required string Name { get; init; }
//public bool? IsUmbrella { get; set; }
public Guid GroupTypeId { get; set; }
public Guid GroupTypeId { get; init; }
/// <summary>
/// Поле по которому групиируем, если тип - ГРУППА
/// </summary>
public Guid? GroupingUnitFieldId { get; set; }
public Guid? GroupingUnitFieldId { get; init; }
public bool? IsGroupByResponsible { get; set; }
public bool? IsGroupByResponsible { get; init; }
public required string ShortDescription { get; set; }
public required string ShortDescription { get; init; }
public required string FullDescription { get; set; }
public required string FullDescription { get; init; }
public required string Solution { get; set; }
public required string Solution { get; init; }
public required string TemplateDuration { get; set; }
public required string TemplateDuration { get; init; }
public DateTimeOffset ReferenceDate { get; set; }
public DateTimeOffset ReferenceDate { get; init; }
public int? UserTimeZoneOffsetMinutes { get; set; }
public int? UserTimeZoneOffsetMinutes { get; init; }
/// <summary>
/// Использовать таймзону рабочей группы ответственного за ЭК шаблона
/// </summary>
public bool IsWorkGroupTimezone { get; set; }
public bool IsWorkGroupTimezone { get; init; }
public Guid ScheduleExcludeTypeId { get; set; }
public Guid ScheduleExcludeTypeId { get; init; }
public Guid? ScheduleExcludeTypeCalendarId { get; set; }
public Guid? ScheduleExcludeTypeCalendarId { get; init; }
public bool IsAutoDistributionEnabled { get; set; }
public bool IsAutoDistributionEnabled { get; init; }
/// <summary>
/// Настройки автораспределения
/// </summary>
public DistributionConfigRequest? DistributionConfig { get; set; }
public DistributionConfigRequest? DistributionConfig { get; init; }
//public bool IsAgent { get; set; }
@@ -51,28 +51,35 @@
//public string? AgentScript { get; set; }
public List<EsppSchValueRequest> Schedule { get; set; } = new List<EsppSchValueRequest>();
public List<EsppSchValueRequest> Schedule { get; init; } = new List<EsppSchValueRequest>();
/// <summary>
/// Настройки автоконтроля (возможны только в случае, если JobGroupType.IsJobGroupAutocontrol==true)
/// </summary>
public JobAutoControlRequest? AutoControl { get; init; }
}
public class EsppSchValueRequest
public record EsppSchValueRequest
{
public Guid TypeValueId { get; set; }
public Guid TypeValueId { get; init; }
public Guid TypeConfigId { get; set; }
public Guid TypeConfigId { get; init; }
}
public class DistributionConfigRequest
public record DistributionConfigRequest
{
public Guid DistributionPeriodId { get; set; }
public Guid DistributionPeriodId { get; init; }
/// <summary>
/// Исключать выходные и праздники
/// </summary>
public bool IsExcludeWeekends { get; set; }
public bool IsExcludeWeekends { get; init; }
/// <summary>
/// Группировать по рабочей группе
/// </summary>
public bool IsGroupingByWorkGroup { get; set; }
public bool IsGroupingByWorkGroup { get; init; }
}
}

View File

@@ -1,79 +1,91 @@
namespace PARR.API.Contracts.V1.Requests
{
public class JobRequest
public record JobRequest
{
public required Guid TnkId { get; set; }
public required Guid TnkId { get; init; }
public required Guid GroupId { get; set; }
public required Guid GroupId { get; init; }
public required string Name { get; set; }
public required string Name { get; init; }
public int? MinValueRelationships { get; set; }
//public int? MinValueRelationships { get; init; }
public int? MaxValueRelationships { get; set; }
//public int? MaxValueRelationships { get; init; }
public bool? IsParentRelationships { get; set; }
//public bool? IsParentRelationships { get; init; }
public required string TemplateNameMask { get; set; }
public JobRelationships? Relationships { get; init; }
public required string WorkGroupMask { get; set; }
public required string TemplateNameMask { get; init; }
public required string WorkName { get; set; }
public required string WorkGroupMask { get; init; }
public required string ResponseAreaMask { get; set; }
public required string WorkName { get; init; }
#region AutoControl
public required string ResponseAreaMask { get; init; }
public bool IsEnableAutoControl { get; set; }
//#region AutoControl
public bool InitUsedTemplateState { get; set; }
//public bool IsEnableAutoControl { get; set; }
public bool InitUsedScheduleState { get; set; }
//public bool InitUsedTemplateState { get; set; }
#endregion
//public bool InitUsedScheduleState { get; set; }
public required List<UnitFilterRequest> UnitFilters { get; set; }
//#endregion
public JobAutoControlRequest? AutoControl { get; init; }
public required List<UnitFilterRequest> UnitFilters { get; init; }
}
public record JobRelationships
{
public int MinValueRelationships { get; init; }
public class UnitFilterRequest
public int MaxValueRelationships { get; init; }
public bool IsParentRelationships { get; init; }
}
public record UnitFilterRequest
{
///// <summary>
///// Id = null в методе Create, в Update обязателен
///// </summary>
//public Guid? Id { get; set; }
public required string UnitFilterMask { get; set; }
public required string UnitFilterMask { get; init; }
public List<FieldFilterRequest>? FieldFilters { get; set; }
public List<FieldFilterRequest>? FieldFilters { get; init; }
public List<RelationshipFilterRequest>? RelationshipFilters { get; set; }
public List<RelationshipFilterRequest>? RelationshipFilters { get; init; }
}
public class FieldFilterRequest
public record FieldFilterRequest
{
public Guid FieldId { get; set; }
public Guid FieldId { get; init; }
public string? ValueMask { get; set; }
public string? ValueMask { get; init; }
public bool IsInverse { get; set; } = false;
public bool IsInverse { get; init; } = false;
}
public class RelationshipFilterRequest
public record RelationshipFilterRequest
{
public Guid FieldId { get; set; }
public Guid FieldId { get; init; }
public bool? IsParent { get; set; }
public bool? IsParent { get; init; }
public string? ValueMask { get; set; }
public string? ValueMask { get; init; }
public bool? IsFullMatch { get; set; }
public bool? IsFullMatch { get; init; }
public bool? IsInverse { get; set; }
public bool? IsInverse { get; init; }
}
}

View File

@@ -40,6 +40,8 @@
/// </summary>
public bool IsAutoDistributionEnabled { get; set; }
public JobGroupAutoControlResponse? AutoControl { get; set; }
// public bool IsAgent { get; set; }
// public string? AgentName { get; set; }
@@ -74,6 +76,15 @@
//public JobGroupDistributionConfigResponse? DistributionConfig { get; set; }
}
public class JobGroupAutoControlResponse
{
public bool IsEnable { get; set; }
public bool InitUsedTemplateState { get; set; }
public bool InitUsedScheduleState { get; set; }
}
public class JobGroupScheduleResponse
{
public string Timezone { get; set; } = string.Empty;

View File

@@ -2,14 +2,20 @@
namespace PARR.API.Contracts.V1.Responses
{
public class JobGroupTypeResponse
public record JobGroupTypeResponse
{
public Guid Id { get; set; }
public Guid Id { get; init; }
public required JobGroupTypesEnum Code { get; set; }
public required JobGroupTypesEnum Code { get; init; }
public required string Name { get; set; }
public required string Name { get; init; }
public required string Description { get; set; }
public required string Description { get; init; }
public bool IsAllowJobUnitFilter { get; init; }
public bool IsJobGroupAutoControl { get; init; }
public bool IsRelationshipsAllowed { get; init; }
}
}

View File

@@ -55,7 +55,6 @@
}
public class TemplateResponse : TemplateBaseResponse
{
public required string Category { get; set; }
@@ -72,6 +71,42 @@
public required string TemplateDuration { get; set; }
#region Поля с примененнымм шорткодами
/// <summary>
/// Работа в ЕСПП (с примененными шорткодами)
/// </summary>
public string? WorkNameRendered { get; set; }
/// <summary>
/// Рабочая группа (с примененными шорткодами)
/// </summary>
public string? WorkGroupRendered { get; set; }
/// <summary>
/// ЗО (с примененными шорткодами)
/// </summary>
public string? ResponseAreaRendered { get; set; }
/// <summary>
/// Краткое описание (с примененными шорткодами)
/// </summary>
public string? ShortDescriptionRendered { get; set; }
/// <summary>
/// Подробное описание (с примененными шорткодами)
/// </summary>
public string? FullDescriptionRendered { get; set; }
/// <summary>
/// Решение (с примененными шорткодами)
/// </summary>
public string? SolutionRendered { get; set; }
#endregion
public JobResponse? Job { get; set; }
public ProcessResponse? Process { get; set; }

View File

@@ -16,7 +16,8 @@ using PARR.Core.Common.Helpers;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Extensions;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.MatchingStatusService;
using PARR.Core.Services.UnitFilterService;
@@ -24,7 +25,7 @@ using PARR.Domain.Common.Pagination;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;
namespace PARR.API.Controllers.V1
@@ -35,46 +36,40 @@ namespace PARR.API.Controllers.V1
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class JobController : BaseApiController
{
private readonly ILogger<JobController> logger;
private readonly IMapper mapper;
private readonly IUriService uriService;
private readonly IJobRepository jobService;
private readonly ITemplateRepository templateService;
//private readonly IValidator<JobRequest> jobValidator;
private readonly IRabbitService mqService;
private readonly MqSettings mqSettings;
private readonly IClientService clientService;
private readonly IJobAutoControlRepository jobAutoControlService;
private readonly IMatchingStatusService matchingStatusService;
private readonly ILogger<JobController> _logger;
private readonly IMapper _mapper;
private readonly IUriService _uriService;
private readonly IJobRepository _jobRepository;
private readonly ITemplateRepository _templateRepository;
private readonly IRabbitService _mqService;
private readonly MqSettings _mqSettings;
private readonly IClientService _clientService;
private readonly IMatchingStatusService _matchingStatusService;
public JobController(
ILogger<JobController> logger,
IMapper mapper,
IUriService uriService,
IJobRepository jobService,
ITemplateRepository templateService,
IJobGroupRepository jobGroupService,
//IValidator<JobRequest> jobValidator,
IUnitFilterService unitFilterService,
IUnitRepository unitService,
IJobRepository jobRepository,
ITemplateRepository templateRepository,
IJobGroupRepository jobGroupRepository,
IUnitFilterService unitFilterRepository,
IUnitRepository unitRepository,
IRabbitService mqService,
MqSettings mqSettings,
IClientService clientService,
IJobAutoControlRepository jobAutoControlService,
IMatchingStatusService matchingStatusService
)
{
this.logger = logger;
this.mapper = mapper;
this.uriService = uriService;
this.jobService = jobService;
this.templateService = templateService;
//this.jobValidator = jobValidator;
this.mqService = mqService;
this.mqSettings = mqSettings;
this.clientService = clientService;
this.jobAutoControlService = jobAutoControlService;
this.matchingStatusService = matchingStatusService;
_logger = logger;
_mapper = mapper;
_uriService = uriService;
_jobRepository = jobRepository;
_templateRepository = templateRepository;
_mqService = mqService;
_mqSettings = mqSettings;
_clientService = clientService;
_matchingStatusService = matchingStatusService;
}
/// <summary>
@@ -84,9 +79,11 @@ namespace PARR.API.Controllers.V1
[HttpGet(ApiRoutes.Job.GetAll)]
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] JobQuery filter)
{
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
var paginationFilter = _mapper.Map<PaginationFilter>(paginationQuery);
IQueryable<Job> query = _jobRepository.Get()
.Include(t => t.AutoControl);
IQueryable<Job> query = jobService.Get().Include(t => t.AutoControl);
query = query.OrderBy(t => t.Name);
@@ -109,7 +106,8 @@ namespace PARR.API.Controllers.V1
query = query
.Include(t => t.Tnk)
.Include(t => t.Group).ThenInclude(t => t.GroupType)
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField);
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField)
.Include(t => t.Group).ThenInclude(t => t.AutoControl);
query = query
.Include(t => t.UnitFilters)
@@ -120,12 +118,12 @@ namespace PARR.API.Controllers.V1
.ThenInclude(t => t.UnitField);
}
var jobs = await jobService.GetPage(query, paginationFilter).ToListAsync();
var jobs = await _jobRepository.GetPage(query, paginationFilter).ToListAsync();
if (!jobs.Any())
return NoContent();
var response = mapper.Map<List<JobResponse>>(jobs);//TODO Migration to job
var response = _mapper.Map<List<JobResponse>>(jobs);//TODO Migration to job
foreach (var jobResponse in response)
{
@@ -152,9 +150,10 @@ namespace PARR.API.Controllers.V1
[HttpGet(ApiRoutes.Job.Get)]
public async Task<IActionResult> GetById([FromRoute] Guid id)
{
var job = await jobService.Get()
var job = await _jobRepository.Get()
.Include(t => t.Tnk)
.Include(t => t.Group).ThenInclude(t => t.GroupType)
.Include(t => t.Group).ThenInclude(t => t.AutoControl)
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField)
.Include(t => t.UnitFilters)
.ThenInclude(t => t.FieldFilters)
@@ -168,7 +167,7 @@ namespace PARR.API.Controllers.V1
if (job == null)
return NotFound();
var response = mapper.Map<JobResponse>(job);
var response = _mapper.Map<JobResponse>(job);
response.TemplatesCount = await GetCountTemplatesAsync(id); //await templateService.Get().CountAsync(t => t.JobId == id);
response.MatchingStatus = await GetMatchingStatusAsync(id);
@@ -188,51 +187,56 @@ namespace PARR.API.Controllers.V1
[HttpPost(ApiRoutes.Job.Create)]
public async Task<IActionResult> Create([FromBody] JobRequest request)
{
//#region Валидация
//var jobValidateResult = await jobValidator.ValidateAsync(request);//Валидация параметров самого задания
#region Проверка существования работы с такими же настройками связей параметрами
//if (!jobValidateResult.IsValid)
// return BadRequest(new Response(jobValidateResult.Errors));
//#endregion
//TODO: !!!!!!! проверить, если тип ЗОНТИК или ГРУППИРОВКА, то обязательно должны быть заполнены поля min max
#region Проверка существования работы с такими же параметрами
var isExistTheSameLinks = await jobService.Get()
.Include(t => t.Group).ThenInclude(t => t.GroupType)
if (request.Relationships != null)
{
//todo: не сильно правильный запрос, в нем проверяем полное совпадение, но не проверяем пересечения
var isExistTheSameLinks = await _jobRepository.Get()
//.Include(t => t.Group).ThenInclude(t => t.GroupType)
.AsNoTracking()
.CountAsync(t =>
//t.Group!.GroupType!.Code == JobGroupTypesEnum.Umbrella
(t.Group!.GroupType!.Code == JobGroupTypesEnum.Umbrella || t.Group!.GroupType!.Code == JobGroupTypesEnum.Group) &&
//(t.Group!.GroupType!.Code == JobGroupTypesEnum.Umbrella || t.Group!.GroupType!.Code == JobGroupTypesEnum.Group) &&
t.Group!.GroupType!.IsRelationshipsAllowed &&
t.GroupId == request.GroupId &&
(t.MinValueRelationships == request.MinValueRelationships ||
t.MaxValueRelationships == request.MaxValueRelationships)
(t.MinValueRelationships == request.Relationships.MinValueRelationships ||
t.MaxValueRelationships == request.Relationships.MaxValueRelationships)
);
if (isExistTheSameLinks > 0)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Name), Message = $"Работа с указанным диапазоном связей пересекается с уже имеющейся в базе данных({request.MinValueRelationships}-{request.MaxValueRelationships})" } }));
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
FieldName = nameof(request.Name),
Message = $"Работа с указанным диапазоном связей пересекается с уже имеющейся в базе данных({request.Relationships.MinValueRelationships}-{request.Relationships.MaxValueRelationships})"
} }));
}
#endregion
var job = mapper.Map<Job>(request);
var job = _mapper.Map<Job>(request);
if (request.AutoControl != null)
{
// разрешен автоконтроль или нет, проверил в валидаторе
job.AutoControl = new JobAutoControl
{
JobId = job.Id,
IsEnable = request.IsEnableAutoControl,
InitUsedScheduleState = request.InitUsedScheduleState,
InitUsedTemplateState = request.InitUsedTemplateState
IsEnable = request.AutoControl.IsEnable,
InitUsedScheduleState = request.AutoControl.InitUsedScheduleState,
InitUsedTemplateState = request.AutoControl.InitUsedTemplateState
};
}
if (!await jobService.CreateAsync(job) || !await jobService.CommitAsync())
if (!await _jobRepository.CreateAsync(job) || !await _jobRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при созании задания на выполнение работ" } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} добавил задание на выполнение работ: {job.Id}, {job.Name}, {job.WorkName}");
_logger.LogInformation($"Пользователь {User.Identity?.Name} добавил задание на выполнение работ: {job.Id}, {job.Name}, {job.WorkName}");
var createdJob = await jobService.Get()
var createdJob = await _jobRepository.Get()
.Include(t => t.Tnk)
.Include(t => t.Group).ThenInclude(t => t.GroupType)
.Include(t => t.Group).ThenInclude(t => t.AutoControl)
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField)
.Include(t => t.UnitFilters)
.ThenInclude(t => t.FieldFilters)
@@ -242,9 +246,9 @@ namespace PARR.API.Controllers.V1
.Include(t => t.AutoControl)
.FirstOrDefaultAsync(t => t.Id == job.Id);
var locationUri = uriService.GetUri(ApiRoutes.Job.Get, ApiRoutes.Job.getParam, createdJob!.Id);
var locationUri = _uriService.GetUri(ApiRoutes.Job.Get, ApiRoutes.Job.getParam, createdJob!.Id);
var response = mapper.Map<JobResponse>(createdJob);
var response = _mapper.Map<JobResponse>(createdJob);
// так как мы только что создали Job, то у него нет шаблонов, смело ставим = 0 (ускоряем запрос)
response.TemplatesCount = 0;
response.MatchingStatus = await GetMatchingStatusAsync(response.Id);
@@ -262,11 +266,7 @@ namespace PARR.API.Controllers.V1
[HttpPut(ApiRoutes.Job.Update)]
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] JobRequest request)
{
//var resultValidate = await jobValidator.ValidateAsync(request);
//if (!resultValidate.IsValid)
// return BadRequest(new Response(resultValidate.Errors));
var orig = await jobService.Get()
var orig = await _jobRepository.Get()
.Include(t => t.Tnk)
.Include(t => t.Group).ThenInclude(t => t.GroupType)
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField)
@@ -287,77 +287,77 @@ namespace PARR.API.Controllers.V1
//TODO: ВОТ ЭТО ВООБЩЕ МЫ БУДЕМ ПРОВЕРЯТЬ, АААА???? - Проверка существования работы с такими же параметрами
//TODO: !!!!!!! проверить, если тип ЗОНТИК или ГРУППИРОВКА, то обязательно должны быть заполнены поля min max
#region обновление полей задания на работу
orig.Name = request.Name.Trim();
orig.WorkName = request.WorkName.Trim();
orig.MinValueRelationships = request.MinValueRelationships;
orig.MaxValueRelationships = request.MaxValueRelationships;
orig.IsParentRelationships = request.IsParentRelationships;
orig.MinValueRelationships = request.Relationships?.MinValueRelationships;
orig.MaxValueRelationships = request.Relationships?.MaxValueRelationships;
orig.IsParentRelationships = request.Relationships?.IsParentRelationships;
orig.TemplateNameMask = request.TemplateNameMask.Trim();
orig.WorkGroupMask = request.WorkGroupMask.Trim();
orig.TnkId = request.TnkId;
orig.GroupId = request.GroupId;
orig.ResponseAreaMask = request.ResponseAreaMask.Trim();
#region Настройки автоконтроля
// валидатор проверяет корректность
if (request.AutoControl != null)
{
// Создаем новую запись или обновляем существующую
if (orig.AutoControl != null)
{
orig.AutoControl.IsEnable = request.IsEnableAutoControl;
orig.AutoControl.InitUsedScheduleState = request.InitUsedScheduleState;
orig.AutoControl.InitUsedTemplateState = request.InitUsedTemplateState;
orig.AutoControl.IsEnable = request.AutoControl.IsEnable;
orig.AutoControl.InitUsedScheduleState = request.AutoControl.InitUsedScheduleState;
orig.AutoControl.InitUsedTemplateState = request.AutoControl.InitUsedTemplateState;
}
else
{
// автоконтрол не загружен, проверяем есть ли он в бд, если нет, то создадим
var existAutoControl = await jobAutoControlService.Get().FirstOrDefaultAsync(t => t.JobId == id);
if (existAutoControl != null)
{
logger.LogError($"При обновлении job {id}, не загрузась связь с JobAutoControl, но она есть. Не стал обновлять Job, вернул ошибку.");
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении задания на выполнение работ." } }));
}
else
{
var autoControl = new JobAutoControl
orig.AutoControl = new JobAutoControl
{
JobId = id,
InitUsedScheduleState = request.InitUsedScheduleState,
InitUsedTemplateState = request.InitUsedTemplateState,
IsEnable = request.IsEnableAutoControl
InitUsedScheduleState = request.AutoControl.InitUsedScheduleState,
InitUsedTemplateState = request.AutoControl.InitUsedTemplateState,
IsEnable = request.AutoControl.IsEnable
};
orig.AutoControl = autoControl;
logger.LogWarning($"При обновлении job {id}, отсутствовала запись в таблице JobAutoControl, создал ее. {autoControl.ToJson()}");
}
}
else
{
// Удаляем настройки, скорей всего автоконтролем управляет группа работ
orig.AutoControl = null;
}
#endregion
orig.DateModified = DateTimeOffset.UtcNow;
#endregion
var job = mapper.Map<Job>(request);
var job = _mapper.Map<Job>(request);
job.Id = id;//На всякий. Пусть будет для чистоты
UpdateUnitFilters(orig, job);//Обновление вложенных дочерних элементов-фильтров
if (!await jobService.CommitAsync())
if (!await _jobRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении задания на выполнение работ." } }));
// если изменили маску, отправим задание на переименование связанных шаблонов
if (isChangedTemplateNameMask)
{
var mqResult = await SendRequestToUpdateTemplates(id);
var mqResult = await SendRequestToUpdateTemplates(orig);
//todo: если ошибка. пользователя не предупреждаем... возможно ему это и не нужно знать...ну не переименуются шаблоны, может они переименуются позже...
}
logger.LogInformation($"Пользователь {User.Identity?.Name} обновил задание на выполнение работ: {orig.Id}," +
_logger.LogInformation($"Пользователь {User.Identity?.Name} обновил задание на выполнение работ: {orig.Id}," +
$" {orig.Name}, {orig.WorkName}, {orig.MinValueRelationships}, {orig.MaxValueRelationships}," +
$" {orig.TemplateNameMask}, {orig.TnkId}, {nameof(orig.GroupId)}");
var updatedJob = await jobService.Get()
var updatedJob = await _jobRepository.Get()
.Include(t => t.Tnk)
.Include(t => t.Group).ThenInclude(t => t.GroupType)
.Include(t => t.Group).ThenInclude(t => t.AutoControl)
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField)
.Include(t => t.UnitFilters)
.ThenInclude(t => t.FieldFilters)
@@ -367,7 +367,7 @@ namespace PARR.API.Controllers.V1
.Include(t => t.AutoControl)
.FirstAsync(t => t.Id == orig.Id);
var response = mapper.Map<JobResponse>(updatedJob);
var response = _mapper.Map<JobResponse>(updatedJob);
response.TemplatesCount = await GetCountTemplatesAsync(id); //await templateService.Get().CountAsync(t => t.JobId == id);
response.MatchingStatus = await GetMatchingStatusAsync(id);
@@ -564,7 +564,7 @@ namespace PARR.API.Controllers.V1
[HttpDelete(ApiRoutes.Job.Delete)]
public async Task<IActionResult> Delete([FromRoute] Guid id)
{
var job = await jobService.Get().Include(t => t.Tnk)
var job = await _jobRepository.Get().Include(t => t.Tnk)
.FirstOrDefaultAsync(t => t.Id == id);
if (job == null)
@@ -572,19 +572,19 @@ namespace PARR.API.Controllers.V1
Message = $"Ошибка при удалении задания на выполнение работ. Не найдено задание на выполнение работ Id: {id}"
} }));
var templateCount = await templateService.Get().CountAsync(t => t.JobId == id);
var templateCount = await _templateRepository.Get().CountAsync(t => t.JobId == id);
if (templateCount > 0)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
Message = $"Ошибка при удалении задания на выполнение работ. С данным заданием связаны шаблоны: {templateCount} шт."
} }));
if (!jobService.Delete(job) || !await jobService.CommitAsync())
if (!_jobRepository.Delete(job) || !await _jobRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
Message = $"Ошибка при удалении задания на выполнение работ"
} }));
logger.LogInformation($"Пользователь {User.Identity?.Name} удалил задание на выполнение работ: {job.Id},{job.Name}," +
_logger.LogInformation($"Пользователь {User.Identity?.Name} удалил задание на выполнение работ: {job.Id},{job.Name}," +
$" {job.WorkName}, {job.MinValueRelationships}, {job.MaxValueRelationships}," +
$" {job.TemplateNameMask}, {job.TnkId}, {job.GroupId}");
@@ -599,7 +599,7 @@ namespace PARR.API.Controllers.V1
/// <returns></returns>
private async Task<JobStatModel> GetStatisticsAsync(Guid jobId)
{
var statResult = await jobService.Get()
var statResult = await _jobRepository.Get()
.Include(t => t.Templates)
.ThenInclude(t => t.RobotConfigurations)
.Where(x => x.Id == jobId)
@@ -629,35 +629,53 @@ namespace PARR.API.Controllers.V1
}
private async Task<bool> SendRequestToUpdateTemplates(Guid jobId)
private async Task<bool> SendRequestToUpdateTemplates(Job job)
{
if (job.Group?.GroupType == null)
throw new ArgumentException("Не хватает include для job.Group.GroupType", nameof(job.Group.GroupType));
Guid Id = default;
SyncTaskEntityTypeEnum EntityType = default;
// Смотрим кто управляет автоконтролем, и какой объект можно синхронизировать
if (job.Group.GroupType.IsJobGroupAutoControl)
{
// Управляет JobGroup
Id = job.GroupId;
EntityType = SyncTaskEntityTypeEnum.JobGroup;
}
else
{
// Управляет Job
Id = job.Id;
EntityType = SyncTaskEntityTypeEnum.Job;
}
var request = new TemplateMatcherMq
{
Id = jobId,
EntityType = SyncTaskEntityTypeEnum.Job,
Id = Id,
EntityType = EntityType,
Action = TemplateMatcherActionEnum.Update,
Initiator = new HistoryInitiator
{
InitiatorIp = clientService.GetClientIp()?.ToString(),
InitiatorIp = _clientService.GetClientIp()?.ToString(),
InitiatorParrComponentId = ParrComponentsEnum.Api,
InitiatorComment = $"В GUI изменено имя шаблона, при сохранении Job отправлен запрос на обновление связанных шаблонов"
}
};
//var msg = JsonSerializer.Serialize(request);
var result = await _mqService.SendAsync(_mqSettings.TemplatesMatcher, new List<object> { request });
//var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new[] { msg });
var result = await mqService.SendAsync(mqSettings.TemplatesMatcher, new List<object> { request });
logger.LogDebug("Получен код отпрвки: {IsSuccess}", result.IsSuccess);
_logger.LogDebug("Получен код отпрвки: {IsSuccess}", result.IsSuccess);
if (!result.IsSuccess)
{
logger.LogError($"Ошибка при отправке запроса в очередь на обновление связанных шаблонов, после обновления маски шаблона. {request.ToJson()}");
_logger.LogError($"Ошибка при отправке запроса в очередь на обновление связанных шаблонов, после обновления маски шаблона. {request.ToJson()}");
return false;
}
logger.LogInformation($"После изменения маски шаблона в jobId: {jobId}, отправлен запрос в очередь на переименование связанных шаблонов: {request.ToJson()}");
_logger.LogInformation($"После изменения маски шаблона в jobId: {job.Id}, отправлен запрос в очередь на переименование связанных шаблонов: {request.ToJson()}");
return true;
}
@@ -671,7 +689,7 @@ namespace PARR.API.Controllers.V1
private async Task<int> GetCountTemplatesAsync(Guid jobId)
{
// Получаем только шаблоны в статусе used
return await templateService.Get().CountAsync(t => t.JobId == jobId && t.StatusTypeId == TemplateStatusTypeEnum.Used);
return await _templateRepository.Get().CountAsync(t => t.JobId == jobId && t.StatusTypeId == TemplateStatusTypeEnum.Used);
}
/// <summary>
@@ -681,9 +699,9 @@ namespace PARR.API.Controllers.V1
/// <returns></returns>
private async Task<MatchingStatusResponse?> GetMatchingStatusAsync(Guid jobId)
{
var statusMatching = await matchingStatusService.GetStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
var statusMatching = await _matchingStatusService.GetStatusAsync(jobId, SyncTaskEntityTypeEnum.Job);
return mapper.Map<MatchingStatusResponse>(statusMatching);
return _mapper.Map<MatchingStatusResponse>(statusMatching);
}
}

View File

@@ -14,7 +14,8 @@ using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using PARR.Core.Common.Helpers;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Core.Services.MatchingStatusService;
using PARR.Domain.Common.Pagination;
@@ -33,63 +34,64 @@ namespace PARR.API.Controllers.V1
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class JobGroupController : BaseApiController
{
private readonly ILogger<JobController> logger;
private readonly IMapper mapper;
private readonly IUriService uriService;
private readonly IJobGroupRepository groupService;
private readonly IJobRepository jobService;
private readonly IEsppSchTypeConfigRepository esppConfigService;
//private readonly IValidator<JobGroupRequest> validator;
private readonly IJobGroupTypeRepository jobGroupTypeService;
private readonly IMatchingStatusService matchingStatusService;
private readonly IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService;
private readonly IRabbitService mqService;
private readonly MqSettings mqSettings;
private readonly ILogger<JobController> _logger;
private readonly IMapper _mapper;
private readonly IUriService _uriService;
private readonly IJobGroupRepository _groupRepository;
private readonly IJobRepository _jobRepository;
private readonly IEsppSchTypeConfigRepository _esppConfigRepository;
private readonly IJobGroupTypeRepository _jobGroupTypeRepository;
private readonly IMatchingStatusService _matchingStatusRepository;
private readonly IScheduleResponseAreaTimeOffsetRepository _scheduleResponseAreaTimeOffsetRepository;
private readonly IJobAutoControlRepository _jobAutoControlRepository;
private readonly IRabbitService _mqService;
private readonly MqSettings _mqSettings;
public JobGroupController(
ILogger<JobController> logger,
IMapper mapper,
IUriService uriService,
IJobGroupRepository groupService,
IJobRepository jobService,
IEsppSchTypeConfigRepository esppConfigService,
//IValidator<JobGroupRequest> validator,
IJobGroupTypeRepository jobGroupTypeService,
IMatchingStatusService matchingStatusService,
IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService,
IJobGroupRepository groupRepository,
IJobRepository jobRepository,
IEsppSchTypeConfigRepository esppConfigRepository,
IJobGroupTypeRepository jobGroupTypeRepository,
IMatchingStatusService matchingStatusRepository,
IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetRepository,
IJobAutoControlRepository jobAutoControlRepository,
IRabbitService mqService,
MqSettings mqSettings
)
{
this.logger = logger;
this.mapper = mapper;
this.uriService = uriService;
this.groupService = groupService;
this.jobService = jobService;
this.esppConfigService = esppConfigService;
//this.validator = validator;
this.jobGroupTypeService = jobGroupTypeService;
this.matchingStatusService = matchingStatusService;
this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
this.mqService = mqService;
this.mqSettings = mqSettings;
this._logger = logger;
this._mapper = mapper;
this._uriService = uriService;
_groupRepository = groupRepository;
_jobRepository = jobRepository;
_esppConfigRepository = esppConfigRepository;
_jobGroupTypeRepository = jobGroupTypeRepository;
_matchingStatusRepository = matchingStatusRepository;
_scheduleResponseAreaTimeOffsetRepository = scheduleResponseAreaTimeOffsetRepository;
_jobAutoControlRepository = jobAutoControlRepository;
this._mqService = mqService;
this._mqSettings = mqSettings;
}
/// <summary>
/// Получить список групп заданий на выполнение работ постранично
/// Получить список групп работ постранично
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.JobGroup.GetAll)]
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] JobGroupQuery filter)
{
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
var paginationFilter = _mapper.Map<PaginationFilter>(paginationQuery);
IQueryable<JobGroup> query = groupService.Get()
IQueryable<JobGroup> query = _groupRepository.Get()
.Include(t => t.GroupType)
.Include(t => t.GroupingUnitField)
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar);
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.AutoControl);
query = query.OrderBy(t => t.GroupName);
@@ -104,12 +106,12 @@ namespace PARR.API.Controllers.V1
.Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod);
var jobGroups = await groupService.GetPage(query, paginationFilter).ToListAsync();
var jobGroups = await _groupRepository.GetPage(query, paginationFilter).ToListAsync();
if (!jobGroups.Any())
return NoContent();
var response = mapper.Map<List<JobGroupResponse>>(jobGroups);
var response = _mapper.Map<List<JobGroupResponse>>(jobGroups);
if (filter.IsFull)
foreach (var jobGroupResponse in response)
@@ -122,26 +124,27 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Получить группу заданий на выполнение работ по id
/// Получить группу работ по id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.JobGroup.Get)]
public async Task<IActionResult> GetById([FromRoute] Guid id)
{
var jobGroup = await groupService.Get()
var jobGroup = await _groupRepository.Get()
.Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.GroupType)
.Include(t => t.GroupingUnitField)
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.Include(t => t.AutoControl)
.FirstOrDefaultAsync(t => t.Id == id);
if (jobGroup == null)
return NotFound();
var response = mapper.Map<JobGroupResponse>(jobGroup);
var response = _mapper.Map<JobGroupResponse>(jobGroup);
await AppendMissingDataAsync(response);
return Ok(new Response<JobGroupResponse>(response, true));
@@ -149,18 +152,13 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Создать группу заданий на выполнение работ (JobGroup)
/// Создать группу работ (JobGroup)
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost(ApiRoutes.JobGroup.Create)]
public async Task<IActionResult> Create([FromBody] JobGroupRequest request)
{
//var resultValidate = await validator.ValidateAsync(request);
//if (!resultValidate.IsValid)
// return BadRequest(new Response(resultValidate.Errors));
var jobGroup = new JobGroup
{
Id = Guid.NewGuid(),
@@ -191,7 +189,7 @@ namespace PARR.API.Controllers.V1
// на всякий проверим, но вообще это проверяется в валидаторе
if (request.DistributionConfig == null)
{
logger.LogError("Ошибка при создании группы работ '{name}', отсутствуют настройки автораспределения", request.Name);
_logger.LogError("Ошибка при создании группы работ '{name}', отсутствуют настройки автораспределения", request.Name);
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создании группы заданий на выполнение работ" } }));
}
@@ -199,6 +197,22 @@ namespace PARR.API.Controllers.V1
}
#endregion
#region Настройки автоконтроля
// Корректность проверяется в валидаторе
if (request.AutoControl != null)
{
jobGroup.AutoControl = new JobGroupAutoControl
{
InitUsedScheduleState = request.AutoControl.InitUsedScheduleState,
InitUsedTemplateState = request.AutoControl.InitUsedTemplateState,
IsEnable = request.AutoControl.IsEnable,
JobGroupId = jobGroup.Id
};
}
#endregion
//Добавляем настройки планировщика
request.Schedule.ForEach(item =>
{
@@ -210,23 +224,24 @@ namespace PARR.API.Controllers.V1
});
});
if (!await groupService.CreateAsync(jobGroup) || !await groupService.CommitAsync())
if (!await _groupRepository.CreateAsync(jobGroup) || !await _groupRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создании группы заданий на выполнение работ" } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} добавил группу заданий на выполнение работ: {jobGroup.Id}, {jobGroup.GroupName}, {jobGroup.ShortDescription}");
_logger.LogInformation($"Пользователь {User.Identity?.Name} добавил группу заданий на выполнение работ: {jobGroup.Id}, {jobGroup.GroupName}, {jobGroup.ShortDescription}");
var createdJobGroup = await groupService.Get().Include(t => t.Jobs).ThenInclude(t => t.Tnk)
var createdJobGroup = await _groupRepository.Get().Include(t => t.Jobs).ThenInclude(t => t.Tnk)
.Include(t => t.GroupType)
.Include(t => t.GroupingUnitField)
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.Include(t => t.AutoControl)
.FirstAsync(t => t.Id == jobGroup.Id);
var locationUri = uriService.GetUri(ApiRoutes.JobGroup.Get, ApiRoutes.JobGroup.getParam, createdJobGroup.Id);
var locationUri = _uriService.GetUri(ApiRoutes.JobGroup.Get, ApiRoutes.JobGroup.getParam, createdJobGroup.Id);
var response = mapper.Map<JobGroupResponse>(createdJobGroup);
var response = _mapper.Map<JobGroupResponse>(createdJobGroup);
await AppendMissingDataAsync(response);
return Created(locationUri, new Response<JobGroupResponse>(response, true));
@@ -234,7 +249,7 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Обновить группу заданий на выполнение работ (JobGroup)
/// Обновить группу работ (JobGroup)
/// </summary>
/// <param name="id"></param>
/// <param name="request"></param>
@@ -242,15 +257,11 @@ namespace PARR.API.Controllers.V1
[HttpPut(ApiRoutes.JobGroup.Update)]
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] JobGroupRequest request)
{
//var resultValidate = await validator.ValidateAsync(request);
//if (!resultValidate.IsValid)
// return BadRequest(new Response(resultValidate.Errors));
var orig = await groupService.Get()
var orig = await _groupRepository.Get()
.Include(t => t.Jobs)
.ThenInclude(t => t.Tnk)
.Include(t => t.EsppSchValues)
.Include(t => t.AutoControl)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.FirstOrDefaultAsync(t => t.Id == id);
@@ -287,7 +298,7 @@ namespace PARR.API.Controllers.V1
{
if (request.DistributionConfig == null)
{
logger.LogError("Ошибка при изменении группы работ '{name}', отсутствуют настройки автораспределения", request.Name);
_logger.LogError("Ошибка при изменении группы работ '{name}', отсутствуют настройки автораспределения", request.Name);
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ" } }));
}
@@ -309,12 +320,50 @@ namespace PARR.API.Controllers.V1
// удаляем настройки распределения если они были
if (orig.DistributionConfig != null)
{
groupService.DeleteDistributionConfig(orig.DistributionConfig);
_groupRepository.DeleteDistributionConfig(orig.DistributionConfig);
}
}
#endregion
#region Настройки автоконтроля
// валидатор проверяет корректность
if (request.AutoControl != null)
{
// автоконтролем управляет JobGroup
if (orig.AutoControl != null)
{
// обновляем
orig.AutoControl.IsEnable = request.AutoControl.IsEnable;
orig.AutoControl.InitUsedScheduleState = request.AutoControl.InitUsedScheduleState;
orig.AutoControl.InitUsedTemplateState = request.AutoControl.InitUsedTemplateState;
// удалить настройки автоконтроля для job
await RemoveJobAutoControlSettingsAsync(orig.Id);
}
else
{
// создаем новую запись
orig.AutoControl = new JobGroupAutoControl
{
InitUsedScheduleState = request.AutoControl.InitUsedScheduleState,
InitUsedTemplateState = request.AutoControl.InitUsedTemplateState,
IsEnable = request.AutoControl.IsEnable,
JobGroupId = orig.Id
};
// удалить настройки автоконтроля для job
await RemoveJobAutoControlSettingsAsync(orig.Id);
}
}
else
{
// автоконтролем управляет каждый job отдельно
// удаляем настройки, если они были
orig.AutoControl = null;
}
#endregion
//обновляем планировщик
orig.EsppSchValues.Clear();
request.Schedule.ForEach(item =>
@@ -327,10 +376,10 @@ namespace PARR.API.Controllers.V1
});
});
if (!await groupService.CommitAsync())
if (!await _groupRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ." } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} обновил группу заданий на выполнение работ: {orig.Id}," +
_logger.LogInformation($"Пользователь {User.Identity?.Name} обновил группу заданий на выполнение работ: {orig.Id}," +
$" {orig.GroupName}, {orig.ShortDescription}, {orig.FullDescription}," +
$" {orig.Solution}, {orig.TemplateDuration}, {orig.ReferenceDate}, {orig.IsAutoDistributionEnabled}" +
$", {orig.IsAgent}, {orig.AgentName}, {orig.AgentTimeOutSec}, {orig.AgentScript}");
@@ -345,17 +394,17 @@ namespace PARR.API.Controllers.V1
JobGroupId = id,
Initiator = new HistoryInitiator { InitiatorComment = "Изменилось расписание группы работ в ГУИ, отправлен запрос на перерасчет nextRun", InitiatorParrComponentId = ParrComponentsEnum.Api }
};
var sendResult = await mqService.SendAsync(mqSettings.NextRun, new List<object> { requestToMq });
var sendResult = await _mqService.SendAsync(_mqSettings.NextRun, new List<object> { requestToMq });
if (sendResult.IsSuccess)
logger.LogInformation("Задание на перерасчет NextRun успешно отправлено в очередь MQ {queueName}", mqSettings.NextRun.QueueName);
_logger.LogInformation("Задание на перерасчет NextRun успешно отправлено в очередь MQ {queueName}", _mqSettings.NextRun.QueueName);
else
logger.LogError("Ошибка при отправке задания на перерасчет NextRun в очередь MQ {queueName}", mqSettings.NextRun.QueueName);
_logger.LogError("Ошибка при отправке задания на перерасчет NextRun в очередь MQ {queueName}", _mqSettings.NextRun.QueueName);
}
#endregion
var updatedJobGroup = await groupService.Get()
var updatedJobGroup = await _groupRepository.Get()
.Include(t => t.Jobs)
.ThenInclude(t => t.Tnk)
.Include(t => t.GroupType)
@@ -363,9 +412,10 @@ namespace PARR.API.Controllers.V1
.Include(t => t.ScheduleExcludeType)
.Include(t => t.ScheduleExcludeTypeCalendar)
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
.Include(t => t.AutoControl)
.FirstAsync(t => t.Id == orig.Id);
var response = mapper.Map<JobGroupResponse>(updatedJobGroup);
var response = _mapper.Map<JobGroupResponse>(updatedJobGroup);
await AppendMissingDataAsync(response);
return Ok(new Response<JobGroupResponse>(response, true));
@@ -373,14 +423,14 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Удалить группу заданий на выполнение работ (только если нет связанных заданий)
/// Удалить группу работ (только если нет связанных работ)
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete(ApiRoutes.JobGroup.Delete)]
public async Task<IActionResult> Delete([FromRoute] Guid id)
{
var jobGroup = await groupService.Get()
var jobGroup = await _groupRepository.Get()
.FirstOrDefaultAsync(t => t.Id == id);
if (jobGroup == null)
@@ -388,18 +438,18 @@ namespace PARR.API.Controllers.V1
Message = $"Ошибка при удалении группы заданий на выполнение работ. Не найдена группа заданий на выполнение работ Id: {id}"
} }));
var jobCount = await jobService.Get().CountAsync(t => t.GroupId == id);
var jobCount = await _jobRepository.Get().CountAsync(t => t.GroupId == id);
if (jobCount > 0)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
Message = $"Ошибка при удалении группы заданий на выполнение работ. С данным группой связаны задания: {jobCount} шт."
} }));
if (!groupService.Delete(jobGroup) || !await groupService.CommitAsync())
if (!_groupRepository.Delete(jobGroup) || !await _groupRepository.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel {
Message = $"Ошибка при удалении группы заданий на выполнение работ"
} }));
logger.LogInformation($"Пользователь {User.Identity?.Name} удалил группу заданий на выполнение работ: {jobGroup.Id},{jobGroup.GroupName}," +
_logger.LogInformation($"Пользователь {User.Identity?.Name} удалил группу заданий на выполнение работ: {jobGroup.Id},{jobGroup.GroupName}," +
$" {jobGroup.ShortDescription}, {jobGroup.FullDescription}," +
$" {jobGroup.Solution}, {jobGroup.TemplateDuration}, {jobGroup.ReferenceDate}," +
$" {jobGroup.IsAutoDistributionEnabled}, {jobGroup.IsAgent}, {jobGroup.AgentName}," +
@@ -408,6 +458,24 @@ namespace PARR.API.Controllers.V1
return NoContent();
}
/// <summary>
/// Удалить настройки автоконтроля для связанных Job
/// </summary>
/// <param name="jobGroupId"></param>
/// <returns></returns>
private async Task RemoveJobAutoControlSettingsAsync(Guid jobGroupId)
{
var jobAutoControlsToRemove = await _jobAutoControlRepository.Get()
.Where(t => t.Job!.GroupId == jobGroupId)
.ToListAsync();
if (!jobAutoControlsToRemove.Any())
return;
_logger.LogInformation("У группы работ {JobGroupId}, у связанных работ {JobsCount} шт. удалены настройки автоконтроля, так как автоконтролем управляем группа работ.", jobGroupId, jobAutoControlsToRemove.Count);
_jobAutoControlRepository.RemoveRange(jobAutoControlsToRemove);
}
/// <summary>
/// Проверка, были ли изменения в расписании
@@ -471,25 +539,25 @@ namespace PARR.API.Controllers.V1
/// <returns></returns>
private async Task AppendMissingDataAsync(JobGroupResponse jobGroupResponse)
{
var schedule = await esppConfigService.GetEsppScheduleDtoAsync(jobGroupResponse.Id);
var schedule = await _esppConfigRepository.GetEsppScheduleDtoAsync(jobGroupResponse.Id);
if (schedule == null)
{
logger.LogError($"Не смог замапить расписание, так как оно null. JobGroupId: {jobGroupResponse.Id}");
_logger.LogError($"Не смог замапить расписание, так как оно null. JobGroupId: {jobGroupResponse.Id}");
return;
}
var scheduleResponse = new JobGroupScheduleResponse
{
//Timezone = settingsFromDb.ScheduleTimezone,
Timezone = scheduleResponseAreaTimeOffsetService.GetDefault.EsppValue,
TypeSchedule = mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
Values = mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
Timezone = _scheduleResponseAreaTimeOffsetRepository.GetDefault.EsppValue,
TypeSchedule = _mapper.Map<EsppScheduleTypeScheduleResponse>(schedule.TypeSchedule),
Values = _mapper.Map<List<EsppScheduleValResponse>>(schedule.Values).OrderBy(t => t.Order).ToList()
};
jobGroupResponse.Schedule = scheduleResponse;
jobGroupResponse.JobsCount = await jobService.Get().CountAsync(t => t.GroupId == jobGroupResponse.Id);
jobGroupResponse.JobsCount = await _jobRepository.Get().CountAsync(t => t.GroupId == jobGroupResponse.Id);
jobGroupResponse.MatchingStatus = await GetMatchingStatusAsync(jobGroupResponse.Id);
}
@@ -506,7 +574,7 @@ namespace PARR.API.Controllers.V1
return null;
// Если есть значение, смотрим, групповой ли тип работ, и если нет, то вернем null
var groupingType = await jobGroupTypeService.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
var groupingType = await _jobGroupTypeRepository.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
if (request.GroupTypeId == groupingType.Id)
{
// это групповой тип работ, все ок
@@ -515,7 +583,7 @@ namespace PARR.API.Controllers.V1
else
{
// Это не сгруппированный тип, обнуляем IsGroupByResponsible
logger.LogInformation("При сохраненни JobGroup, был передан IsGroupByResponsible: {IsGroupByResponsible}, но при этом, тип группы не сгруппированный, а GroupTypeId: {GroupTypeId}, обнулил IsGroupByResponsible",
_logger.LogInformation("При сохраненни JobGroup, был передан IsGroupByResponsible: {IsGroupByResponsible}, но при этом, тип группы не сгруппированный, а GroupTypeId: {GroupTypeId}, обнулил IsGroupByResponsible",
request.IsGroupByResponsible, request.GroupTypeId);
return null;
}
@@ -534,7 +602,7 @@ namespace PARR.API.Controllers.V1
return request.GroupingUnitFieldId;
var groupingType = await jobGroupTypeService.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
var groupingType = await _jobGroupTypeRepository.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
if (request.GroupTypeId == groupingType.Id)
{
@@ -544,7 +612,7 @@ namespace PARR.API.Controllers.V1
else
{
// Это не сгруппированный тип, обнуляем GroupingUnitFieldId
logger.LogInformation("При сохраненни JobGroup, был передан GroupingUnitFieldId: {GroupingUnitFieldId}, но при этом, тип группы не сгруппированный, а GroupTypeId: {GroupTypeId}, обнулил GroupingUnitFieldId",
_logger.LogInformation("При сохраненни JobGroup, был передан GroupingUnitFieldId: {GroupingUnitFieldId}, но при этом, тип группы не сгруппированный, а GroupTypeId: {GroupTypeId}, обнулил GroupingUnitFieldId",
request.GroupingUnitFieldId, request.GroupTypeId);
return null;
}
@@ -558,9 +626,9 @@ namespace PARR.API.Controllers.V1
/// <returns></returns>
private async Task<MatchingStatusResponse?> GetMatchingStatusAsync(Guid jobGroupId)
{
var statusMatching = await matchingStatusService.GetStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
var statusMatching = await _matchingStatusRepository.GetStatusAsync(jobGroupId, SyncTaskEntityTypeEnum.JobGroup);
return mapper.Map<MatchingStatusResponse>(statusMatching);
return _mapper.Map<MatchingStatusResponse>(statusMatching);
}

View File

@@ -6,7 +6,7 @@ using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Domain.Common.Roles;
namespace PARR.API.Controllers.V1
@@ -17,23 +17,29 @@ namespace PARR.API.Controllers.V1
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class JobGroupTypeController : BaseApiController
{
private readonly IJobGroupTypeRepository jobGroupTypeService;
private readonly IJobGroupTypeRepository jobGroupTypeRepository;
private readonly IMapper mapper;
public JobGroupTypeController(
IJobGroupTypeRepository jobGroupTypeService,
IJobGroupTypeRepository jobGroupTypeRepository,
IMapper mapper
)
{
this.jobGroupTypeService = jobGroupTypeService;
this.jobGroupTypeRepository = jobGroupTypeRepository;
this.mapper = mapper;
}
/// <summary>
/// Получить список типов групп работ
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.JobGroupType.GetAll)]
public async Task<IActionResult> GetAll()
{
var query = jobGroupTypeService.Get().OrderBy(t => t.Description);
var query = jobGroupTypeRepository.Get()
.AsNoTracking()
.OrderBy(t => t.Description);
var types = await query.ToListAsync();

View File

@@ -6,7 +6,7 @@ using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Settings;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities.Base.History;

View File

@@ -8,11 +8,11 @@ using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService;
using PARR.Domain.Common.Roles;
using Job = PARR.Domain.Entities.Job.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.API.Controllers.V1
{

View File

@@ -32,7 +32,7 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Получить список всех переменных составляющих
/// Применить шорткод
/// </summary>
/// <returns></returns>
[HttpPost(ApiRoutes.ShortcodeApply.Apply)]

View File

@@ -33,7 +33,7 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Получить список всех переменных составляющих
/// Получить список всех переменных составляющих (список шорткодов)
/// </summary>
/// <returns></returns>
[HttpGet(ApiRoutes.Shortcode.GetAll)]

View File

@@ -9,7 +9,7 @@ using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Core.Services.NextRunServices;
using PARR.Core.Services.Shortcodes;

View File

@@ -48,9 +48,6 @@ namespace PARR.API.Controllers.V1
[HttpPost(ApiRoutes.SyncTask.MatchTemplates)]
public async Task<IActionResult> MatchTemplatesForJob([FromBody] MatchTemplatesRequest request)
{
//todo: Валидатор! Валидатор то забыли!!!
// проверяем, если уже идет синхронизация по этому объекту, то ахтунг, ошибка
var matchingStatus = await matchingStatusService.GetStatusAsync(request.ObjectId, request.EntityType);
if (matchingStatus.IsMatchingObject)

View File

@@ -1,5 +1,4 @@
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
@@ -8,7 +7,7 @@ using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.API.Settings;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities.Base.History;

View File

@@ -10,7 +10,6 @@ using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces;
using PARR.BLL.Helpers;
using PARR.Core.Common.Helpers;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Schedule;
@@ -30,37 +29,34 @@ namespace PARR.API.Controllers.V1
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class TemplateController : BaseApiController
{
private readonly IMapper mapper;
private readonly ITemplateRepository templateService;
private readonly IRobotConfigurationRepository robotConfigurationService;
private readonly IClientService clientService;
private readonly ILogger<TemplateController> logger;
private readonly IShortcodesService shortcodesService;
private readonly IOrderRepository orderService;
private readonly SettingsFromDb settingsFromDb;
private readonly IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService;
private readonly IMapper _mapper;
private readonly ITemplateRepository _templateRepository;
private readonly IRobotConfigurationRepository _robotConfigurationRepository;
private readonly IClientService _clientService;
private readonly ILogger<TemplateController> _logger;
private readonly IShortcodesService _shortcodesService;
private readonly IOrderRepository _orderRepository;
private readonly SettingsFromDb _settingsFromDb;
public TemplateController(
IMapper mapper,
ITemplateRepository templateService,
IRobotConfigurationRepository robotConfigurationService,
ITemplateRepository templateRepository,
IRobotConfigurationRepository robotConfigurationRepository,
IClientService clientService,
ILogger<TemplateController> logger,
IShortcodesService shortcodesService,
IOrderRepository orderService,
SettingsFromDb settingsFromDb,
IScheduleResponseAreaTimeOffsetRepository scheduleResponseAreaTimeOffsetService
IOrderRepository orderRepository,
SettingsFromDb settingsFromDb
)
{
this.mapper = mapper;
this.templateService = templateService;
this.robotConfigurationService = robotConfigurationService;
this.clientService = clientService;
this.logger = logger;
this.shortcodesService = shortcodesService;
this.orderService = orderService;
this.settingsFromDb = settingsFromDb;
this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
_mapper = mapper;
_templateRepository = templateRepository;
_robotConfigurationRepository = robotConfigurationRepository;
_clientService = clientService;
_logger = logger;
_shortcodesService = shortcodesService;
_orderRepository = orderRepository;
_settingsFromDb = settingsFromDb;
}
@@ -72,9 +68,10 @@ namespace PARR.API.Controllers.V1
[HttpGet(ApiRoutes.Template.GetAll)]
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] TemplateQuery filter)
{
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
var paginationFilter = _mapper.Map<PaginationFilter>(paginationQuery);
IQueryable<Template> query = templateService.Get()
IQueryable<Template> query = _templateRepository.Get()
.AsNoTracking()
.Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
.Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
.Include(t => t.StatusType)
@@ -82,8 +79,7 @@ namespace PARR.API.Controllers.V1
.Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
.Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
.OrderBy(t => t.Name)
.AsNoTracking();
.OrderBy(t => t.Name);
if (!string.IsNullOrEmpty(filter.Mask))
@@ -114,7 +110,7 @@ namespace PARR.API.Controllers.V1
#endregion
var templates = await templateService.GetPage(query, paginationFilter).ToListAsync();
var templates = await _templateRepository.GetPage(query, paginationFilter).ToListAsync();
//logger.LogDebug("Загрузка шаблонов из БД: {ElapsedMs} мс", sw.ElapsedMilliseconds);
@@ -122,7 +118,7 @@ namespace PARR.API.Controllers.V1
if (!templates.Any())
return NoContent();
var templateResponse = mapper.Map<List<TemplateListResponse>>(templates);
var templateResponse = _mapper.Map<List<TemplateListResponse>>(templates);
// словари для быстрого поиска
var templatesDict = templates.ToDictionary(t => t.Id);
@@ -135,7 +131,7 @@ namespace PARR.API.Controllers.V1
foreach (var responseItem in templateResponse)
{
//await ApplyTemplateShortcodesAsync(responseItem, templates.First(t => t.Id == responseItem.Id));
await ApplyTemplateShortcodesAsync(responseItem, templatesDict[responseItem.Id]);
await ApplyBaseTemplateShortcodesAsync(responseItem, templatesDict[responseItem.Id]);
//FillResponseAreaOffset(responseItem);
}
//logger.LogDebug("Получение шорткодов: {ElapsedMs} мс", sw.ElapsedMilliseconds);
@@ -165,7 +161,8 @@ namespace PARR.API.Controllers.V1
[HttpGet(ApiRoutes.Template.Get)]
public async Task<IActionResult> GetById([FromRoute] Guid id)
{
var template = await templateService.GetWithIncludes().AsNoTracking()
var template = await _templateRepository.GetWithIncludes()
.AsNoTracking()
.Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
.Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
@@ -179,9 +176,9 @@ namespace PARR.API.Controllers.V1
if (template == null)
return NotFound();
var response = mapper.Map<TemplateResponse>(template);
var response = _mapper.Map<TemplateResponse>(template);
await ApplyBaseTemplateShortcodesAsync(response, template);
await ApplyTemplateShortcodesAsync(response, template);
//FillResponseAreaOffset(response);
var ordersCountResult = await GetOrdersCountAsync(new List<Guid> { response.Id });
response.OrderCount = ordersCountResult.Count > 0 ? ordersCountResult.First().Value : 0;
@@ -215,7 +212,7 @@ namespace PARR.API.Controllers.V1
// .FirstOrDefaultAsync(t => t.Id == id);
#endregion
var template = await templateService.Get()
var template = await _templateRepository.Get()
.Include(t => t.RobotConfigurations)
.FirstOrDefaultAsync(t => t.Id == id);
@@ -226,21 +223,21 @@ namespace PARR.API.Controllers.V1
{
template.IsActiveTemplate = request.IsActiveTemplate;
//необходимо обновить шаблон
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, template);
var config = _robotConfigurationRepository.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, template);
//robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
_robotConfigurationRepository.SetUpdateTaskStatusIfAllow(config);
}
if (template.IsActiveSchedule != request.IsActiveSchedule)
{
template.IsActiveSchedule = request.IsActiveSchedule;
//необходимо обновить расписание
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
var config = _robotConfigurationRepository.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
//robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
_robotConfigurationRepository.SetUpdateTaskStatusIfAllow(config);
}
if (!await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Изменён статус шаблона/расписания", InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }))
if (!await _templateRepository.CommitAsync(new HistoryInitiator { InitiatorComment = "Изменён статус шаблона/расписания", InitiatorIp = _clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api }))
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении шаблона." } }));
#region old
@@ -263,7 +260,7 @@ namespace PARR.API.Controllers.V1
//return Ok(new Response<TemplateResponse>(response, true));
#endregion
var templateToResponse = await templateService.Get()
var templateToResponse = await _templateRepository.Get()
.AsNoTracking()
.Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
.Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
@@ -274,10 +271,9 @@ namespace PARR.API.Controllers.V1
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
.FirstAsync(t => t.Id == id);
var response = mapper.Map<TemplateListResponse>(templateToResponse);
var response = _mapper.Map<TemplateListResponse>(templateToResponse);
await ApplyTemplateShortcodesAsync(response, templateToResponse);
//FillResponseAreaOffset(response);
await ApplyBaseTemplateShortcodesAsync(response, templateToResponse);
var ordersCountResult = await GetOrdersCountAsync(new List<Guid> { response.Id });
response.OrderCount = ordersCountResult.Count > 0 ? ordersCountResult.First().Value : 0;
@@ -287,18 +283,34 @@ namespace PARR.API.Controllers.V1
/// <summary>
/// Применить шорткоды
/// Применить шорткоды. Для респонса TemplateBaseResponse
/// </summary>
/// <param name="response"></param>
/// <param name="template"></param>
/// <returns></returns>
private async Task ApplyTemplateShortcodesAsync(TemplateBaseResponse response, Template template)
private async Task ApplyBaseTemplateShortcodesAsync(TemplateBaseResponse response, Template template)
{
response.WorkGroup = await shortcodesService.ApplyShortcodesAsync(template.Job.WorkGroupMask, template);
response.ResponseArea = await shortcodesService.ApplyShortcodesAsync(template.Job.ResponseAreaMask, template);
response.WorkGroup = await _shortcodesService.ApplyShortcodesAsync(template.Job!.WorkGroupMask, template);
response.ResponseArea = await _shortcodesService.ApplyShortcodesAsync(template.Job!.ResponseAreaMask, template);
}
/// <summary>
/// Применить шорткоды. Для респонса TemplateResponse (добавлены дополнительные поля Rendered)
/// </summary>
/// <param name="response"></param>
/// <param name="template"></param>
/// <returns></returns>
private async Task ApplyTemplateShortcodesAsync(TemplateResponse response, Template template)
{
response.WorkNameRendered = await _shortcodesService.ApplyShortcodesAsync(template.Job!.WorkName, template);
response.WorkGroupRendered = await _shortcodesService.ApplyShortcodesAsync(template.Job!.WorkGroupMask, template);
response.ResponseAreaRendered = await _shortcodesService.ApplyShortcodesAsync(template.Job!.ResponseAreaMask, template);
response.ShortDescriptionRendered = await _shortcodesService.ApplyShortcodesAsync(template.Job.Group!.ShortDescription, template);
response.FullDescriptionRendered = await _shortcodesService.ApplyShortcodesAsync(template.Job.Group!.FullDescription, template);
response.SolutionRendered = await _shortcodesService.ApplyShortcodesAsync(template.Job.Group!.Solution, template);
}
/// <summary>
/// Получить кол-во нарядов для шаблонов
/// </summary>
@@ -309,7 +321,7 @@ namespace PARR.API.Controllers.V1
if (!templateIdList.Any())
return new Dictionary<Guid, int>();
var templateWithOrders = await orderService.Get()
var templateWithOrders = await _orderRepository.Get()
.Where(t => t.TemplateId.HasValue && templateIdList.Contains(t.TemplateId.Value))
.GroupBy(t => t.TemplateId)
.Select(t => new { TemplateId = t.Key, OrderCount = t.Count() })
@@ -323,36 +335,7 @@ namespace PARR.API.Controllers.V1
}
///// <summary>
///// Заполнить ResponseAreaOffset
///// </summary>
///// <param name="response"></param>
//private void FillResponseAreaOffset(TemplateBaseResponse response)
//{
// // если стоит галка IsResponseAreaTimezone и есть ЗО, то возвращаем оффсет
// if (response.IsResponseAreaTimezone && !string.IsNullOrEmpty(response.ResponseArea))
// {
// var responseArea = response.ResponseArea;
// response.ResponseAreaOffset = mapper.Map<ScheduleResponseAreaTimeOffsetResponse>(scheduleResponseAreaTimeOffsetService.GetByResponseAreaOrDefault(responseArea));
// }
// else
// {
// response.ResponseAreaOffset = null;
// }
// //var responseArea = response.IsResponseAreaTimezone && !string.IsNullOrEmpty(response.ResponseArea)
// // ? response.ResponseArea
// // : settingsFromDb.DefaultResponseAreaToTimeOffset;
// //response.NextRunResponseAreaInLocal = response.IsResponseAreaTimezone && !string.IsNullOrEmpty(response.ResponseArea)
// // ? nextRunService.GetNextRunWithResponseAreaOffset(response.NextRun, response.ResponseArea)
// // // возвращаем в дефолтной зоне
// // : nextRunService.GetNextRunWithResponseAreaOffset(response.NextRun, settingsFromDb.DefaultResponseAreaToTimeOffset);
// //response.NextRunResponseAreaInLocal = nextRunService.GetNextRunWithResponseAreaOffset(response.NextRun, responseArea);
// //response.ResponseAreaOffset = mapper.Map<ScheduleResponseAreaTimeOffsetResponse>(scheduleResponseAreaTimeOffsetService.GetByResponseAreaOrDefault(responseArea));
//}
}
}

View File

@@ -13,7 +13,7 @@ using PARR.Domain.DTOs.User;
using PARR.Domain.DTOs.Workload;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.Domain.Entities.Schedule;
using PARR.Domain.Entities.Unit;
@@ -368,7 +368,8 @@ namespace PARR.API.MappingProfiles
.Include<JobGroup, JobGroupWithDistributionConfigResponse>()
.ForMember(d => d.GroupType, o => o.MapFrom(s => s.GroupType))
.ForMember(d => d.GroupingUnitField, o => o.MapFrom(s => s.GroupingUnitField))
.ForMember(d => d.IsWorkGroupTimezone, o => o.MapFrom(s => s.IsResponseAreaTimezone));
.ForMember(d => d.IsWorkGroupTimezone, o => o.MapFrom(s => s.IsResponseAreaTimezone))
.ForMember(d => d.AutoControl, o => o.MapFrom(s => s.AutoControl));
CreateMap<JobGroup, JobGroupBaseResponse>()
.ForMember(d => d.Name, o => o.MapFrom(s => s.GroupName))
@@ -382,6 +383,7 @@ namespace PARR.API.MappingProfiles
.ForMember(d => d.ScheduleExcludeTypeCalendar, o => o.MapFrom(s => s.ScheduleExcludeTypeCalendar));
//.ForMember(d => d.DistributionConfig, o => o.MapFrom(s => s.DistributionConfig));
CreateMap<JobGroupAutoControl, JobGroupAutoControlResponse>();
#endregion

View File

@@ -3,7 +3,7 @@ using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.Domain.Common.Pagination;
using PARR.Domain.DTOs.RobotSnapshotDTO;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.API.MappingProfiles
{
@@ -17,7 +17,11 @@ namespace PARR.API.MappingProfiles
CreateMap<JobRequest, Job>()
.ForMember(d => d.Id, o => o.MapFrom(s => Guid.NewGuid()))
.ForMember(d => d.IsParentRelationships, o => o.MapFrom(s => s.Relationships != null ? s.Relationships.IsParentRelationships : (bool?)null))
.ForMember(d => d.MaxValueRelationships, o => o.MapFrom(s => s.Relationships != null ? s.Relationships.MaxValueRelationships : (int?)null))
.ForMember(d => d.MinValueRelationships, o => o.MapFrom(s => s.Relationships != null ? s.Relationships.MinValueRelationships : (int?)null))
.ForMember(d => d.DateCreated, o => o.MapFrom(s => DateTimeOffset.UtcNow))
.ForMember(d => d.AutoControl, o => o.Ignore())
.AfterMap((s, d) =>
{
if (d.UnitFilters != null)

View File

@@ -1,7 +1,7 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1.Requests;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
namespace PARR.API.Validators
{

View File

@@ -1,33 +0,0 @@
using FluentValidation;
using PARR.API.Contracts.V1.Requests;
using PARR.Domain.Enums;
namespace PARR.API.Validators
{
public class JobAutoControlRequestValidator : AbstractValidator<JobAutoControlRequest>
{
public JobAutoControlRequestValidator()
{
RuleFor(t => t.EkMasks).Must(items =>
items.Count(t => t.Trim().Length > 0) > 0
).WithMessage("Должна быть указана хотя бы одна маска ЭК");
RuleFor(t => t.EnabledEkStatuses).Must(
items => items.Distinct().Count() == items.Count()
).WithMessage("Статусы ЭК не должны повторяться");
RuleFor(t => t.EnabledEkStatuses).Must(items =>
{
return !items.Any(item => !Enum.IsDefined(typeof(EkStatusEnum), item)) && !items.Any(t => t == 0);
})
.WithMessage($"Допустимые значения: {(int)EkStatusEnum.New} ({EkStatusEnum.New}), " +
$"{(int)EkStatusEnum.Preapre} ({EkStatusEnum.Preapre}), " +
$"{(int)EkStatusEnum.Exploitation} ({EkStatusEnum.Exploitation}), " +
$"{(int)EkStatusEnum.Repair} ({EkStatusEnum.Repair}), " +
$"{(int)EkStatusEnum.Reserve} ({EkStatusEnum.Reserve}), " +
$"{(int)EkStatusEnum.OutOfService} ({EkStatusEnum.OutOfService}), " +
$"{(int)EkStatusEnum.Test} ({EkStatusEnum.Test}), " +
$"{(int)EkStatusEnum.Development} ({EkStatusEnum.Development})");
}
}
}

View File

@@ -2,7 +2,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1.Requests;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Domain.Enums;
@@ -12,11 +12,11 @@ namespace PARR.API.Validators
public class JobGroupValidator : AbstractValidator<JobGroupRequest>
{
public JobGroupValidator(
IJobGroupTypeRepository jobGroupTypeService,
IUnitFieldRepository unitFieldService,
IScheduleExcludeTypeRepository scheduleExcludeTypeService,
IScheduleExcludeTypeCalendarRepository scheduleExcludeTypeCalendarService,
IDistributionPeriodRepository distributionPeriodService
IJobGroupTypeRepository jobGroupTypeRepository,
IUnitFieldRepository unitFieldRepository,
IScheduleExcludeTypeRepository scheduleExcludeTypeRepository,
IScheduleExcludeTypeCalendarRepository scheduleExcludeTypeCalendarRepository,
IDistributionPeriodRepository distributionPeriodRepository
)
{
RuleFor(t => t.Name)
@@ -35,7 +35,7 @@ namespace PARR.API.Validators
.NotNull().NotEmpty();
RuleFor(t => t.GroupTypeId)
.MustAsync(async (entity, value, c) => await jobGroupTypeService.GetAsync(value) != null)
.MustAsync(async (entity, value, c) => await jobGroupTypeRepository.GetAsync(value) != null)
.WithMessage("Указан несуществующий Id типа");
//Проверяем существует ли такой GroupingUnitFieldId в unitField
@@ -47,7 +47,7 @@ namespace PARR.API.Validators
return true;
}
return await unitFieldService.GetAsync(value.Value) != null;
return await unitFieldRepository.GetAsync(value.Value) != null;
})
.WithMessage("Указано несуществующий Id поля");
@@ -55,7 +55,7 @@ namespace PARR.API.Validators
RuleFor(t => t.GroupingUnitFieldId)
.MustAsync(async (entity, value, c) =>
{
var groupingJobType = await jobGroupTypeService.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
var groupingJobType = await jobGroupTypeRepository.Get().FirstAsync(t => t.Code == JobGroupTypesEnum.Group);
// Если это сгруппированный тип, то у него обязательно должно быть заполнено поле GroupingUnitFieldId
if (entity.GroupTypeId == groupingJobType.Id)
@@ -68,14 +68,14 @@ namespace PARR.API.Validators
RuleFor(t => t.ScheduleExcludeTypeId)
.NotNull()
.NotEmpty()
.MustAsync(async (entity, value, c) => await scheduleExcludeTypeService.GetAsync(value) != null)
.MustAsync(async (entity, value, c) => await scheduleExcludeTypeRepository.GetAsync(value) != null)
.WithMessage("Некорректное значение");
RuleFor(t => t.ScheduleExcludeTypeCalendarId)
.MustAsync(async (entity, value, c) =>
{
// Если выбрано "Нет исключений", то это поле должно быть пустое, иначе, должно быть валидное значение
var type = await scheduleExcludeTypeService.GetAsync(entity.ScheduleExcludeTypeId);
var type = await scheduleExcludeTypeRepository.GetAsync(entity.ScheduleExcludeTypeId);
if (type == null)
return false;
@@ -89,7 +89,7 @@ namespace PARR.API.Validators
if (!value.HasValue)
return false;
return await scheduleExcludeTypeCalendarService.GetAsync(value.Value) != null;
return await scheduleExcludeTypeCalendarRepository.GetAsync(value.Value) != null;
})
.WithMessage("Некорректное значение");
@@ -115,7 +115,7 @@ namespace PARR.API.Validators
if (periodId.HasValue)
{
var exist = await distributionPeriodService.GetAsync(periodId.Value);
var exist = await distributionPeriodRepository.GetAsync(periodId.Value);
return exist != null;
}
@@ -129,7 +129,26 @@ namespace PARR.API.Validators
// если IsResponseAreaTimezone == true, то поле UserTimeZoneOffsetMinutes обязательно.
// если IsResponseAreaTimezone == false, то UserTimeZoneOffsetMinutes должно быть null
return (entity.IsWorkGroupTimezone && value != null) || (!entity.IsWorkGroupTimezone && value == null);
}).WithMessage("Некорректное значение."); ;
}).WithMessage("Некорректное значение.");
RuleFor(t => t.AutoControl)
.MustAsync(async (entity, value, c) =>
{
// Автоконтроль разрешен только типам работ у которых включен IsJobGroupAutoControl
var isAllowedAutocontrol = await jobGroupTypeRepository.Get()
.AnyAsync(t => t.Id == entity.GroupTypeId && t.IsJobGroupAutoControl == true);
// Разрешен автоконтроль и есть значение
if (isAllowedAutocontrol && value != null)
return true;
// Запрещен автоконтроль и нет значения
if (!isAllowedAutocontrol && value == null)
return true;
return false;
})
.WithMessage("Некорректные параметры автоконтроля");
}
}

View File

@@ -1,31 +1,28 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1.Requests;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Domain.Entities.JobGroupEntities;
namespace PARR.API.Validators
{
public class JobRequestValidator : AbstractValidator<JobRequest>
{
private readonly ITnkRepository tnkService;
private readonly IJobGroupRepository jobGroupService;
private readonly IJobRepository jobRepository;
private readonly IUnitFieldRepository unitFieldService;
private JobGroup? jobGroup;
private readonly ITnkRepository _tnkRepository;
private readonly IJobGroupRepository _jobGroupRepository;
private readonly IUnitFieldRepository _unitFieldRepository;
//private JobGroup? jobGroup;
public JobRequestValidator(
ITnkRepository tnkService,
IJobGroupRepository jobGroupService,
IJobRepository jobService,
IUnitFieldRepository unitFieldService
ITnkRepository tnkRepository,
IJobGroupRepository jobGroupRepository,
IUnitFieldRepository unitFieldRepository
)
{
this.tnkService = tnkService;
this.jobGroupService = jobGroupService;
this.jobRepository = jobService;
this.unitFieldService = unitFieldService;
_tnkRepository = tnkRepository;
_jobGroupRepository = jobGroupRepository;
_unitFieldRepository = unitFieldRepository;
RuleFor(t => t.Name)
.NotNull().NotEmpty();
@@ -48,14 +45,54 @@ namespace PARR.API.Validators
.MustAsync(async (entity, value, c) => await IsUnitFiltersCorrect(entity))
.WithMessage("Неверно заданы параметры фильтров. Внимательнее, пожалуйста!");
RuleFor(t => t.MinValueRelationships)
RuleFor(t => t.Relationships)
.MustAsync(async (entity, value, c) =>
{
// Relationships должны быть обязательно заполнены если в типе работ IsRelationshipsAllowed==true
var relationshipsIsRequired = await jobGroupRepository.Get()
.AnyAsync(t => t.Id == entity.GroupId && t.GroupType!.IsRelationshipsAllowed, c);
if (relationshipsIsRequired && value != null)
return true;
if (!relationshipsIsRequired && value == null)
return true;
return false;
})
.WithMessage("Некорректные настройки кол-ва связей");
When(t => t.Relationships != null, () =>
{
RuleFor(t => t.Relationships!.MinValueRelationships)
.GreaterThanOrEqualTo(0);
RuleFor(t => t.MaxValueRelationships)
.GreaterThanOrEqualTo(t => t.MinValueRelationships);
RuleFor(t => t.Relationships!.MaxValueRelationships)
.GreaterThanOrEqualTo(t => t.Relationships!.MinValueRelationships);
});
RuleFor(t => t.ResponseAreaMask)
.NotNull().NotEmpty();
RuleFor(t => t.AutoControl)
.MustAsync(async (entity, value, c) =>
{
// Автоконтроль разрешен только типам работ, у которых выключен IsJobGroupAutoControl
var isAllowedJobAutocontrol = await jobGroupRepository.Get()
.AnyAsync(t => t.Id == entity.GroupId && t.GroupType!.IsJobGroupAutoControl == false, c);
// Разрешен автоконтроль и есть значение
if (isAllowedJobAutocontrol && value != null)
return true;
// Запрещен автоконтроль и нет значения
if (!isAllowedJobAutocontrol && value == null)
return true;
return false;
})
.WithMessage("Некорректные параметры автоконтроля");
}
private async Task<bool> IsUnitFiltersCorrect(JobRequest entity)
@@ -72,7 +109,7 @@ namespace PARR.API.Validators
foreach (var fieldFilter in unitFilter.FieldFilters)
{
var fieldId = fieldFilter.FieldId;
if (await unitFieldService.GetAsync(fieldId) == null)
if (await _unitFieldRepository.GetAsync(fieldId) == null)
return false;
}
@@ -80,7 +117,7 @@ namespace PARR.API.Validators
foreach (var relationshipFilter in unitFilter.RelationshipFilters!)
{
var fieldId = relationshipFilter.FieldId;
if (await unitFieldService.GetAsync(fieldId) == null)
if (await _unitFieldRepository.GetAsync(fieldId) == null)
return false;
}
}
@@ -90,7 +127,7 @@ namespace PARR.API.Validators
private async Task<bool> IsGroupExist(JobRequest entity)
{
jobGroup = await jobGroupService.GetAsync(entity.GroupId);
var jobGroup = await _jobGroupRepository.GetAsync(entity.GroupId);
return jobGroup != null;
}
@@ -98,7 +135,7 @@ namespace PARR.API.Validators
private async Task<bool> IsTnkExist(JobRequest entity)
{
return await tnkService.GetAsync(entity.TnkId) != null;
return await _tnkRepository.GetAsync(entity.TnkId) != null;
}
}
}

View File

@@ -0,0 +1,51 @@
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1.Requests;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Enums;
namespace PARR.API.Validators
{
public class MatchTemplatesRequestValidator : AbstractValidator<MatchTemplatesRequest>
{
public MatchTemplatesRequestValidator(
IJobGroupRepository jobGroupRepository,
IJobRepository jobRepository,
ITemplateRepository templateRepository
)
{
RuleFor(t => t.ObjectId)
.NotNull()
.NotEmpty()
.WithMessage("Идентификатор объекта не может быть пустым.");
RuleFor(t => t)
.MustAsync(async (request, cancellation) =>
{
return request.EntityType switch
{
SyncTaskEntityTypeEnum.JobGroup =>
await jobGroupRepository.Get().AsNoTracking().AnyAsync(t => t.Id == request.ObjectId, cancellation),
SyncTaskEntityTypeEnum.Job =>
await jobRepository.Get().AsNoTracking().AnyAsync(t => t.Id == request.ObjectId && t.Group!.GroupType!.IsJobGroupAutoControl == false, cancellation),
SyncTaskEntityTypeEnum.Template =>
false, // TODO: Синхронизировать шаблоны нельзя
_ => false
};
})
.WithMessage(request => request.EntityType switch
{
SyncTaskEntityTypeEnum.Template => "Синхронизация шаблонов пока не поддерживается.",
SyncTaskEntityTypeEnum.Job => "Объект не найден или данные работы нельзя отправить на синхронизацию.",
_ => "Не найден объект с переданным ИД."
});
}
}
}

View File

@@ -1,7 +1,8 @@
using FluentValidation;
using PARR.API.Contracts.V1.Requests;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Enums;
namespace PARR.API.Validators

View File

@@ -1,8 +1,8 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.Domain.Entities.Schedule;
@@ -15,16 +15,13 @@ namespace PARR.Core.Common.Helpers;
public class JobGroupCloneHelper
{
private readonly IJobGroupRepository groupRepository;
private readonly IJobRepository jobRepository;
private readonly ILogger<JobGroupCloneHelper> logger;
public JobGroupCloneHelper(
IJobGroupRepository groupRepository,
IJobRepository jobRepository,
ILogger<JobGroupCloneHelper> logger)
{
this.groupRepository = groupRepository;
this.jobRepository = jobRepository;
this.logger = logger;
}

View File

@@ -1,13 +1,8 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Common.Helpers;

View File

@@ -24,6 +24,6 @@ namespace PARR.Core.Common.Interfaces.RabbitServices
/// <param name="mqSettings"></param>
/// <param name="msgObjectList"></param>
/// <returns></returns>
Task<RabbitSendResult> SendAsync(IMqSettings mqSettings, List<object> msgObjectList);
Task<RabbitSendResult> SendAsync(IMqSettings mqSettings, IEnumerable<object> msgObjectList);
}
}

View File

@@ -1,9 +0,0 @@
using PARR.Domain.Entities.Job;
namespace PARR.Core.Repositories.Interfaces.Job
{
public interface IJobAutoControlRepository
{
IQueryable<JobAutoControl> Get();
}
}

View File

@@ -1,8 +0,0 @@
using PARR.Core.Repositories.Base;
namespace PARR.Core.Repositories.Interfaces.Job
{
public interface IJobRepository : IBaseRepository<Domain.Entities.Job.Job>
{
}
}

View File

@@ -1,7 +1,7 @@
using PARR.Core.Repositories.Base;
using PARR.Domain.Entities.JobGroupEntities;
namespace PARR.Core.Repositories.Interfaces.Job
namespace PARR.Core.Repositories.Interfaces.JobGroupRepositories
{
public interface IJobGroupRepository : IBaseRepository<JobGroup>
{

View File

@@ -1,7 +1,7 @@
using PARR.Core.Repositories.Base;
using PARR.Domain.Entities.JobGroupEntities;
namespace PARR.Core.Repositories.Interfaces.Job
namespace PARR.Core.Repositories.Interfaces.JobGroupRepositories
{
public interface IJobGroupTypeRepository : IBaseRepository<JobGroupType>
{

View File

@@ -1,7 +1,7 @@
using PARR.Core.Repositories.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Repositories.Interfaces.Job
namespace PARR.Core.Repositories.Interfaces.JobRepositories
{
public interface IFieldFilterRepository : IBaseRepository<JobFieldFilter>
{

View File

@@ -0,0 +1,10 @@
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Repositories.Interfaces.JobRepositories
{
public interface IJobAutoControlRepository
{
IQueryable<JobAutoControl> Get();
void RemoveRange(List<JobAutoControl> autoControlList);
}
}

View File

@@ -0,0 +1,9 @@
using PARR.Core.Repositories.Base;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Repositories.Interfaces.JobRepositories
{
public interface IJobRepository : IBaseRepository<Job>
{
}
}

View File

@@ -1,7 +1,7 @@
using PARR.Core.Repositories.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Repositories.Interfaces.Job
namespace PARR.Core.Repositories.Interfaces.JobRepositories
{
public interface IJobUnitFilterRepository : IBaseRepository<JobUnitFilter>
{

View File

@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.Core.Common.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Cache.Models;
using PARR.Domain.DTOs.Matching;
using PARR.Domain.Enums;

View File

@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Core.Services.NextRunServices.Models;
using PARR.Core.Services.NextRunServices.Subservices;

View File

@@ -2,7 +2,7 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.Shortcodes.Enums;
using PARR.Core.Services.Shortcodes.Handlers;
@@ -10,7 +10,7 @@ using PARR.Core.Services.Shortcodes.Models;
using PARR.Domain.Cache.Models;
using PARR.Domain.DTOs.Shortcode;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;
using PARR.Domain.Settings;
using System.Runtime.CompilerServices;

View File

@@ -1,5 +1,5 @@
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Services.UnitFilterService
{

View File

@@ -1,7 +1,7 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;
namespace PARR.Core.Services.UnitFilterService.Matchers;

View File

@@ -2,7 +2,7 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Services.UnitFilterService.Matchers;

View File

@@ -3,7 +3,7 @@ using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Services.UnitFilterService.Matchers;

View File

@@ -1,5 +1,5 @@
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Services.UnitFilterService.Matchers.Interfaces
{

View File

@@ -1,4 +1,4 @@
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Services.UnitFilterService.Matchers.Interfaces
{

View File

@@ -1,5 +1,5 @@
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.Core.Services.UnitFilterService.Matchers.Interfaces
{

View File

@@ -1,12 +1,12 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Core.Services.UnitService.Interfaces;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.Unit;
using System.Diagnostics;

View File

@@ -2,7 +2,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.TaskRepositories;
using PARR.Core.Services.NextRunServices;
using PARR.Core.Services.TaskServices.Helpers;
@@ -10,7 +10,6 @@ using PARR.Core.Services.Workload.Interfaces;
using PARR.Core.Services.Workload.Models;
using PARR.Domain.Cache.Models;
using PARR.Domain.DTOs.Workload;
using PARR.Domain.Entities;
using PARR.Domain.Enums;
using PARR.Domain.Enums.Workload;

View File

@@ -3,15 +3,14 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using PARR.Core.Common.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.UnitFilterService;
using PARR.Core.Services.UnitFilterService.Matchers.Interfaces;
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Core.Services.UnitService.Interfaces;
using PARR.DAL.Context;
using PARR.Domain.Cache.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.Domain.Entities.Unit;
using PARR.Domain.Enums;

View File

@@ -3,7 +3,7 @@ using PARR.Core.Extensions;
using PARR.Domain.Common.Roles;
using PARR.Domain.Common.Template;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.Domain.Entities.RobotEntities;
using PARR.Domain.Entities.Schedule;
@@ -179,9 +179,9 @@ namespace PARR.DAL.Context
modelBuilder.Entity<JobGroupType>(f =>
{
f.HasData(
new() { Id = new Guid("4FA62E79-86BB-47C2-BE1A-72A716A170FA"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Simple.ToString(), Code = JobGroupTypesEnum.Simple, Description = "Обычный", IsAllowJobUnitFilter = true, IsJobGroupAutoControl = false },
new() { Id = new Guid("6EC58B1A-5C40-47B9-B036-4FA490E8D503"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Umbrella.ToString(), Code = JobGroupTypesEnum.Umbrella, Description = "Зонтик", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true },
new() { Id = new Guid("318625E5-F833-436A-99DF-2A382A1E71C7"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Group.ToString(), Code = JobGroupTypesEnum.Group, Description = "Сгруппированный", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true }
new() { Id = new Guid("4FA62E79-86BB-47C2-BE1A-72A716A170FA"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Simple.ToString(), Code = JobGroupTypesEnum.Simple, Description = "Обычный", IsAllowJobUnitFilter = true, IsJobGroupAutoControl = false, IsRelationshipsAllowed = false },
new() { Id = new Guid("6EC58B1A-5C40-47B9-B036-4FA490E8D503"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Umbrella.ToString(), Code = JobGroupTypesEnum.Umbrella, Description = "Зонтик", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true, IsRelationshipsAllowed = true },
new() { Id = new Guid("318625E5-F833-436A-99DF-2A382A1E71C7"), DateCreated = dateCreated, DateModified = null, Name = JobGroupTypesEnum.Group.ToString(), Code = JobGroupTypesEnum.Group, Description = "Сгруппированный", IsAllowJobUnitFilter = false, IsJobGroupAutoControl = true, IsRelationshipsAllowed = true }
);
});
#endregion

View File

@@ -3,8 +3,8 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.RobotRepositories;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Core.Repositories.Interfaces.TaskRepositories;
@@ -14,6 +14,7 @@ using PARR.DAL.Context;
using PARR.DAL.Repositories;
using PARR.DAL.Repositories.Job;
using PARR.DAL.Repositories.JobGroupRepositories;
using PARR.DAL.Repositories.JobRepositories;
using PARR.DAL.Repositories.RobotRepositories;
using PARR.DAL.Repositories.Schedule;
using PARR.DAL.Repositories.TaskRepositories;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PARR.DAL.Migrations
{
/// <inheritdoc />
public partial class tblGroupTypesAddRelationshipsSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsRelationshipsAllowed",
schema: "jobGroup",
table: "GroupTypes",
type: "boolean",
nullable: false,
defaultValue: false,
comment: "Разрешена настройка кол-ва связей");
migrationBuilder.UpdateData(
schema: "jobGroup",
table: "GroupTypes",
keyColumn: "Id",
keyValue: new Guid("318625e5-f833-436a-99df-2a382a1e71c7"),
column: "IsRelationshipsAllowed",
value: true);
migrationBuilder.UpdateData(
schema: "jobGroup",
table: "GroupTypes",
keyColumn: "Id",
keyValue: new Guid("4fa62e79-86bb-47c2-be1a-72a716a170fa"),
column: "IsRelationshipsAllowed",
value: false);
migrationBuilder.UpdateData(
schema: "jobGroup",
table: "GroupTypes",
keyColumn: "Id",
keyValue: new Guid("6ec58b1a-5c40-47b9-b036-4fa490e8d503"),
column: "IsRelationshipsAllowed",
value: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsRelationshipsAllowed",
schema: "jobGroup",
table: "GroupTypes");
}
}
}

View File

@@ -599,6 +599,10 @@ namespace PARR.DAL.Migrations
.HasColumnType("boolean")
.HasComment("Автоконтролем управляет JobGroup? true - да JobGroup, false - Job. Влияет на интерфейс и на логику работы автоконтроля.");
b.Property<bool>("IsRelationshipsAllowed")
.HasColumnType("boolean")
.HasComment("Разрешена настройка кол-ва связей");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
@@ -619,6 +623,7 @@ namespace PARR.DAL.Migrations
Description = "Обычный",
IsAllowJobUnitFilter = true,
IsJobGroupAutoControl = false,
IsRelationshipsAllowed = false,
Name = "Simple"
},
new
@@ -629,6 +634,7 @@ namespace PARR.DAL.Migrations
Description = "Зонтик",
IsAllowJobUnitFilter = false,
IsJobGroupAutoControl = true,
IsRelationshipsAllowed = true,
Name = "Umbrella"
},
new
@@ -639,6 +645,7 @@ namespace PARR.DAL.Migrations
Description = "Сгруппированный",
IsAllowJobUnitFilter = false,
IsJobGroupAutoControl = true,
IsRelationshipsAllowed = true,
Name = "Group"
});
});

View File

@@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;
using PARR.Domain.Entities.JobGroupEntities;
namespace PARR.DAL.Repositories.Job
namespace PARR.DAL.Repositories.JobGroupRepositories
{
internal class JobGroupRepository : BaseRepository<JobGroup>, IJobGroupRepository
{

View File

@@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;
using PARR.Domain.Entities.JobGroupEntities;
namespace PARR.DAL.Repositories.Job
namespace PARR.DAL.Repositories.JobGroupRepositories
{
internal class JobGroupTypeRepository : BaseRepository<JobGroupType>, IJobGroupTypeRepository
{

View File

@@ -1,8 +1,8 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.DAL.Repositories.Job
{

View File

@@ -1,6 +1,6 @@
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.DAL.Context;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.DAL.Repositories.Job
{
@@ -17,5 +17,10 @@ namespace PARR.DAL.Repositories.Job
{
return dataContext.JobAutoControls;
}
public void RemoveRange(List<JobAutoControl> autoControlList)
{
dataContext.JobAutoControls.RemoveRange(autoControlList);
}
}
}

View File

@@ -1,16 +1,16 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.DAL.Repositories.Job
namespace PARR.DAL.Repositories.JobRepositories
{
internal class JobRepository : BaseRepository<Domain.Entities.Job.Job>, IJobRepository
internal class JobRepository : BaseRepository<Domain.Entities.JobEntities.Job>, IJobRepository
{
public JobRepository(DataContext dataContext, ILogger<JobRepository> logger) : base(logger, dataContext) { }
public override Task<bool> CreateAsync(Domain.Entities.Job.Job obj)
public override Task<bool> CreateAsync(Domain.Entities.JobEntities.Job obj)
{
if (obj.AutoControl == null)
obj.AutoControl = new JobAutoControl
@@ -22,7 +22,7 @@ namespace PARR.DAL.Repositories.Job
}
public override Task<bool> AddRangeAsync(List<Domain.Entities.Job.Job> objs)
public override Task<bool> AddRangeAsync(List<Domain.Entities.JobEntities.Job> objs)
{
objs.ForEach(job =>
{

View File

@@ -1,8 +1,8 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.DAL.Repositories.Job
{

View File

@@ -5,7 +5,7 @@ using PARR.Domain.Entities.JobGroupEntities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.Domain.Entities.Job
namespace PARR.Domain.Entities.JobEntities
{
[Table("Jobs", Schema = DatabaseSchemas.Job)]
[Comment("Таблица видов работ")]

View File

@@ -3,7 +3,7 @@ using PARR.Domain.Constants;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.Domain.Entities.Job
namespace PARR.Domain.Entities.JobEntities
{
[Table("AutoControls", Schema = DatabaseSchemas.Job)]
[Comment("Таблица управления автоконтролем для работ")]

View File

@@ -5,7 +5,7 @@ using PARR.Domain.Entities.Unit;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.Domain.Entities.Job
namespace PARR.Domain.Entities.JobEntities
{
[Table("FieldFilters", Schema = DatabaseSchemas.Job)]
[Comment("Таблица описания критериев выборки аттрибутов ЭК")]

View File

@@ -3,7 +3,7 @@ using PARR.Domain.Constants;
using PARR.Domain.Entities.Unit;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.Domain.Entities.Job
namespace PARR.Domain.Entities.JobEntities
{
[Table("RelationshipFilters", Schema = DatabaseSchemas.Job)]
[Comment("Таблица фильтров связей ЭК")]

View File

@@ -4,7 +4,7 @@ using PARR.Domain.Entities.Base;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.Domain.Entities.Job
namespace PARR.Domain.Entities.JobEntities
{
[Table("UnitFilters", Schema = DatabaseSchemas.Job)]
[Comment("Таблица описания критериев выборки ЭК, описание полей в АСУ ЕСПП")]

View File

@@ -2,7 +2,7 @@
using PARR.Domain.Constants;
using System.ComponentModel.DataAnnotations.Schema;
namespace PARR.Domain.Entities.Job
namespace PARR.Domain.Entities.JobEntities
{
[Table("UnitsInTemplates", Schema = DatabaseSchemas.Job)]
[Comment("Таблица связи ЭК в шаблонах")]

View File

@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.Domain.Constants;
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.Schedule;
using PARR.Domain.Entities.Unit;
using PARR.Domain.Settings;
@@ -180,7 +181,7 @@ namespace PARR.Domain.Entities.JobGroupEntities
[ForeignKey(nameof(GroupTypeId))]
public JobGroupType? GroupType { get; set; }
public ICollection<Job.Job> Jobs { get; set; } = new HashSet<Job.Job>();
public ICollection<Job> Jobs { get; set; } = new HashSet<Job>();
public ICollection<EsppSchValue> EsppSchValues { get; set; } = new HashSet<EsppSchValue>();

View File

@@ -1,14 +1,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.Domain.Cache.Models;
using PARR.Domain.Constants;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.Unit;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PARR.Domain.Entities.JobGroupEntities
{

View File

@@ -35,10 +35,17 @@ namespace PARR.Domain.Entities.JobGroupEntities
/// <summary>
/// Автоконтролем управляет JobGroup? true - да JobGroup, false - Job.
/// Влияет на интерфейс и на логику работы автоконтроля.
/// Если true - то в GUI, кнопку синхронизировать можно нажать только в группах.
/// </summary>
[Comment("Автоконтролем управляет JobGroup? true - да JobGroup, false - Job. Влияет на интерфейс и на логику работы автоконтроля.")]
public bool IsJobGroupAutoControl { get; set; } = false;
/// <summary>
/// Разрешена настройка кол-ва связей
/// </summary>
[Comment("Разрешена настройка кол-ва связей")]
public bool IsRelationshipsAllowed { get; set; } = false;
public ICollection<JobGroup> JobGroups { get; set; } = new HashSet<JobGroup>();
}
}

View File

@@ -2,7 +2,7 @@
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Base.History.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@@ -77,7 +77,7 @@ namespace PARR.Domain.Entities
//public Host? Host { get; set; }
[ForeignKey(nameof(JobId))]
public Job.Job? Job { get; set; }
public JobEntities.Job? Job { get; set; }
[ForeignKey(nameof(UnitId))]
public Unit.Unit? Unit { get; set; }

View File

@@ -1,4 +1,5 @@
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.JobEntities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@@ -30,6 +31,6 @@ namespace PARR.Domain.Entities
public Subprocess? Subprocess { get; set; }
public ICollection<Job.Job> Jobs { get; set; } = new HashSet<Job.Job>();
public ICollection<Job> Jobs { get; set; } = new HashSet<Job>();
}
}

View File

@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.Domain.Constants;
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

View File

@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.Domain.Constants;
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

View File

@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using PARR.Domain.Constants;
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

View File

@@ -115,7 +115,7 @@ namespace PARR.Infrastructure.Rabbit
}
}
public async Task<RabbitSendResult> SendAsync(IMqSettings mqSettings, List<object> msgObjectList)
public async Task<RabbitSendResult> SendAsync(IMqSettings mqSettings, IEnumerable<object> msgObjectList)
{
var msgStringList = msgObjectList.Select(t => JsonSerializer.Serialize(t, jsonOptions)).ToArray();

View File

@@ -3,7 +3,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Enums;
@@ -13,11 +14,11 @@ namespace PARR.JobAutoControl
{
internal class JobAutoControlManager : IJobAutoControlManager
{
private readonly WorkerSettings workerSettings;
private readonly ILogger<JobAutoControlManager> logger;
private readonly IIntervalService intervalService;
private readonly IServiceProvider serviceProvider;
private readonly MqSettings mqSettings;
private readonly WorkerSettings _workerSettings;
private readonly ILogger<JobAutoControlManager> _logger;
private readonly IIntervalService _intervalService;
private readonly IServiceProvider _serviceProvider;
private readonly MqSettings _mqSettings;
public JobAutoControlManager(
WorkerSettings workerSettings,
@@ -27,68 +28,87 @@ namespace PARR.JobAutoControl
MqSettings mqSettings
)
{
this.workerSettings = workerSettings;
this.logger = logger;
this.intervalService = intervalService;
this.serviceProvider = serviceProvider;
this.mqSettings = mqSettings;
_workerSettings = workerSettings;
_logger = logger;
_intervalService = intervalService;
_serviceProvider = serviceProvider;
_mqSettings = mqSettings;
}
public async Task StartAsync()
{
logger.LogInformation("Запуск сервиса управления авто-контролем РР (JobAutoControl)");
_logger.LogInformation("Запуск сервиса управления авто-контролем РР (JobAutoControl)");
await intervalService.IntervalInitAsync(async () =>
await _intervalService.IntervalInitAsync(async () =>
{
await using (var scope = serviceProvider.CreateAsyncScope())
//using (var scope = serviceProvider.CreateScope())
await using (var scope = _serviceProvider.CreateAsyncScope())
{
var jobAutoControlService = scope.ServiceProvider.GetService<IJobAutoControlRepository>();
var mqService = scope.ServiceProvider.GetService<IRabbitService>();
var jobAutoControlRepository = scope.ServiceProvider.GetRequiredService<IJobAutoControlRepository>();
var jobGroupAutoControlRepository = scope.ServiceProvider.GetRequiredService<IJobGroupAutoControlRepository>();
var mqService = scope.ServiceProvider.GetRequiredService<IRabbitService>();
if (jobAutoControlService == null || mqService == null)
throw new Exception($"Не смог получить серивс {nameof(IJobAutoControlRepository)} или {nameof(IRabbitService)}");
await HandlerAsync(jobAutoControlService, mqService);
await HandlerAsync(jobAutoControlRepository, jobGroupAutoControlRepository, mqService);
}
}, workerSettings.RepeatEvery);
}, _workerSettings.RepeatEvery);
}
private async Task HandlerAsync(IJobAutoControlRepository jobAutoControlService, IRabbitService mqService)
private async Task HandlerAsync(IJobAutoControlRepository jobAutoControlRepository, IJobGroupAutoControlRepository jobGroupAutoControlRepository, IRabbitService mqService)
{
var jobsWithAutoControl = await jobAutoControlService.Get().Where(t => t.IsEnable).ToListAsync();
// Список JobGroup с включенным автоконтролем
var jobGroupsIds = await jobGroupAutoControlRepository.Get()
.AsNoTracking()
.Where(t => t.IsEnable)
.Select(t => t.JobGroupId)
.ToListAsync();
logger.LogInformation($"Работ с включенным авто-контролем: {jobsWithAutoControl.Count} шт.");
// Список Job с включенным автоконтролем, но у которых в JobGroupType.IsJobGroupAutocOntrol==false
var jobIds = await jobAutoControlRepository.Get()
.AsNoTracking()
.Where(t => t.IsEnable && t.Job!.Group!.GroupType!.IsJobGroupAutoControl == false)
.Select(t => t.JobId)
.ToListAsync();
if (jobsWithAutoControl.Count == 0)
_logger.LogInformation("Найдено объектов с включенным автоконтролем, групп: {JobGroupCount} шт., работ: {JobCount} шт.", jobGroupsIds.Count, jobIds.Count);
if (jobGroupsIds.Count == 0 && jobIds.Count == 0)
return;
// формируем сообщения
var msgList = jobsWithAutoControl.Select(t => new TemplateMatcherMq
var msgList = new List<TemplateMatcherMq>(jobGroupsIds.Count + jobIds.Count);
var initiator = new HistoryInitiator
{
InitiatorComment = $"Инициатор авто-контроль, периодичность: {_workerSettings.RepeatEvery}",
InitiatorIp = null,
InitiatorParrComponentId = ParrComponentsEnum.JobAutoControl
};
// группы
msgList.AddRange(jobGroupsIds.Select(id => new TemplateMatcherMq
{
Action = TemplateMatcherActionEnum.Sync,
EntityType = SyncTaskEntityTypeEnum.JobGroup,
Id = id,
Initiator = initiator
}));
// работы
msgList.AddRange(jobIds.Select(id => new TemplateMatcherMq
{
Action = TemplateMatcherActionEnum.Sync,
EntityType = SyncTaskEntityTypeEnum.Job,
Id = t.JobId,
Initiator = new HistoryInitiator
{
InitiatorComment = $"Инициатор авто-контроль, периодичность: {workerSettings.RepeatEvery}",
InitiatorIp = null,
InitiatorParrComponentId = ParrComponentsEnum.JobAutoControl
}
}).ToList();
//var msgStrList = msgList.Select(t => JsonSerializer.Serialize(t));
Id = id,
Initiator = initiator
}));
// отправляем задания в очередь template matcher`a
//var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgStrList.ToArray());
var sendResult = await mqService.SendAsync(mqSettings.TemplateMatcher, msgList.ToList<object>());
var sendResult = await mqService.SendAsync(_mqSettings.TemplateMatcher, msgList);
if (!sendResult.IsSuccess)
logger.LogError($"Ошибка при отправке сообщений ({msgList.Count()} шт.) в очередь.");
_logger.LogError("Ошибка при отправке сообщений ({Count} шт.) в очередь.", msgList.Count);
else
logger.LogInformation($"Выполнена отправка сообщений в очередь, {msgList.Count()} шт.");
_logger.LogInformation("Выполнена отправка сообщений в очередь, {Count} шт.", msgList.Count);
}
}

View File

@@ -3,7 +3,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Common.Interfaces;
using PARR.Core.Common.Interfaces.RabbitServices;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Domain.Common.Rabbit.Messages;
using PARR.NextRun.Services;
using PARR.NextRun.Settings;

View File

@@ -2,10 +2,11 @@
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Base;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Base;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.Domain.Enums;

View File

@@ -1,7 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.Domain.Entities.JobGroupEntities;
namespace PARR.TemplateDistributor.Services

View File

@@ -1,6 +1,6 @@
using Microsoft.EntityFrameworkCore;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Repositories.Interfaces.Unit;

View File

@@ -1,13 +1,13 @@
using Microsoft.EntityFrameworkCore;
using PARR.Core.Common.Interfaces;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.Core.Services.NextRunServices;
using PARR.Core.Services.Shortcodes;
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;
using PARR.TemplateGeneratorWorker.Services;

View File

@@ -1,6 +1,6 @@
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.Unit;
namespace PARR.TemplateMatcher.Models

View File

@@ -1,6 +1,6 @@
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.TemplateMatcher.Models;

View File

@@ -4,7 +4,7 @@ using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Core.Services.Shortcodes;
using PARR.Domain.Constants;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.TemplateMatcher.Models;

View File

@@ -6,9 +6,10 @@ using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Enums;
using PARR.TemplateMatcher.Models;
using PARR.TemplateMatcher.Services.Implementations;
using PARR.TemplateMatcher.Services.Interfaces;
using PARR.TemplateMatcher.Settings;
@@ -173,11 +174,9 @@ internal class GroupedTemplateProcessor : IGroupedTemplateProcessor
HistoryInitiator initiator,
CancellationToken ct)
{
// Вычисляем флаги активности
var isActiveTemplate = targetJob.AutoControl?.InitUsedTemplateState ?? false;
var isActiveSchedule = targetJob.AutoControl?.InitUsedScheduleState ?? false;
var (isActiveTemplate, isActiveSchedule) = AutoControlResolver.ResolveInitStates(
targetJob, targetJob.Group);
// Маппим кортежи в сообщения
var unitsInTemplateMsg = unitsInTemplateSubGroup
.Select(e => new UnitInTemplateMessage
{

View File

@@ -1,4 +1,4 @@
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.Domain.Entities.JobGroupEntities;
using PARR.TemplateMatcher.Models;

View File

@@ -1,5 +1,5 @@
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
using PARR.TemplateMatcher.Models;
namespace PARR.TemplateMatcher.Services.GroupedSync;

View File

@@ -1,5 +1,5 @@
using PARR.Core.Services.UnitFilterService.Models;
using PARR.Domain.Entities.Job;
using PARR.Domain.Entities.JobEntities;
namespace PARR.TemplateMatcher.Services.GroupedSync
{

View File

@@ -1,6 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Core.Repositories.Interfaces.JobGroupRepositories;
using PARR.TemplateMatcher.Services.GroupedSync;
namespace PARR.TemplateMatcher.Services.Implementations.GroupedSync;
@@ -24,6 +24,7 @@ internal class LoadJobGroupStage : IGroupedSyncStage
.AsNoTracking()
.AsSingleQuery()
.Include(jg => jg.GroupType)
.Include(jg => jg.AutoControl)
.Include(jg => jg.Jobs).ThenInclude(j => j.AutoControl)
.Include(jg => jg.Jobs).ThenInclude(j => j.UnitFilters)
.ThenInclude(uf => uf.RelationshipFilters).ThenInclude(rf => rf.UnitField)

Some files were not shown because too many files have changed in this diff Show More