Compare commits
97 Commits
job-group-
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c7d041a8b | ||
|
|
236ddee5ef | ||
|
|
fdfd0f9363 | ||
|
|
393f043286 | ||
|
|
5c3b273346 | ||
|
|
0fcbe870b9 | ||
|
|
f9f234d119 | ||
|
|
394fc059ba | ||
|
|
1b02bf63bf | ||
|
|
09d8244b03 | ||
|
|
4e81ee72f4 | ||
|
|
04d9843cfb | ||
|
|
9f5bae3f32 | ||
|
|
a611a27c6e | ||
|
|
d6f4368917 | ||
|
|
e99ca22251 | ||
|
|
11eff75686 | ||
|
|
3818a470ce | ||
|
|
b475d1e10c | ||
|
|
f624b7f4a7 | ||
|
|
2a3afb9a5d | ||
|
|
f3a3a0cf8c | ||
|
|
2befb6b0c3 | ||
|
|
0629579cf0 | ||
|
|
83c6a5f605 | ||
|
|
e02a51f5ed | ||
|
|
fb20395e53 | ||
|
|
94bea5c46d | ||
|
|
349cf55862 | ||
|
|
4cd6134ad4 | ||
|
|
f10a50edae | ||
|
|
0ab5b49371 | ||
|
|
acdb6ec893 | ||
|
|
7d5fb23daf | ||
|
|
e36e08aa73 | ||
|
|
343468cf71 | ||
|
|
56cdca0502 | ||
|
|
8798529b4d | ||
|
|
556d895c7c | ||
|
|
58275d73f4 | ||
|
|
eacda75649 | ||
|
|
90e9f80505 | ||
|
|
b3879062a6 | ||
|
|
58b4d98b16 | ||
|
|
d1889460de | ||
|
|
5f384947a6 | ||
|
|
1cc2beb9ca | ||
|
|
0b0c0b04ad | ||
|
|
5094945c8e | ||
|
|
98245e73e6 | ||
|
|
cdcb4fd9bc | ||
|
|
bbb14ee4ea | ||
|
|
5edbcff35b | ||
|
|
6c93e1971f | ||
|
|
68696a2fdc | ||
|
|
751b693e72 | ||
|
|
6ca6bfbc2e | ||
|
|
178a991d8b | ||
|
|
a087958fd5 | ||
|
|
4ee2880a8f | ||
|
|
497d241caf | ||
|
|
4c80e247f5 | ||
|
|
83017c6bee | ||
|
|
323231f907 | ||
|
|
b1c3d90b40 | ||
|
|
511721b798 | ||
|
|
9f42a733e7 | ||
|
|
50556ef605 | ||
|
|
9194d127d2 | ||
|
|
33b0576ccc | ||
|
|
33cdc29e80 | ||
|
|
d7d4713953 | ||
|
|
4af552b29e | ||
|
|
9d3273191b | ||
|
|
246e8e69ae | ||
|
|
e9c9e9f03e | ||
|
|
fb9578fec0 | ||
|
|
9c27f81fe8 | ||
|
|
36e866f637 | ||
|
|
1affa34b07 | ||
|
|
3c9e03adbb | ||
|
|
143ae10190 | ||
|
|
f8e16e9496 | ||
|
|
55ac424f1a | ||
|
|
52bd0d8ce1 | ||
|
|
65ef0dec92 | ||
|
|
7574cd31c2 | ||
|
|
8a44f43a34 | ||
|
|
16ba4f21a2 | ||
|
|
c1ff4d0258 | ||
|
|
5c2d1c31b5 | ||
|
|
806633aaf7 | ||
|
|
0d7969da44 | ||
|
|
4f2b2c204e | ||
|
|
df6ed47bd9 | ||
|
|
8dfb2587b2 | ||
|
|
fe4461ee4e |
@@ -20,6 +20,7 @@ variables:
|
||||
PROD_TEMPLATE_UPDATER: "parr/parr-template-updater"
|
||||
PROD_WORKLOAD_BUILDER: "parr/parr-workload-builder"
|
||||
PROD_TASK_RECONCILIATION: "parr/parr-task-reconciliation"
|
||||
PROD_SNAPSHOTS: "parr/parr-snapshots"
|
||||
|
||||
|
||||
stages:
|
||||
@@ -1009,4 +1010,62 @@ prod_task_reconciliation_deploy:
|
||||
matrix:
|
||||
- RUNNER: shell-api-swarm-01
|
||||
tags:
|
||||
- ${RUNNER}
|
||||
- ${RUNNER}
|
||||
|
||||
|
||||
### SNAPSHOTS PROD ###
|
||||
prod_snapshots_build:
|
||||
stage: build
|
||||
only:
|
||||
- /^sn[0-9]+\.[0-9]+\.[0-9]+$/
|
||||
except:
|
||||
- branches
|
||||
services:
|
||||
- name: docker:20.10.21-dind
|
||||
command: [
|
||||
"--insecure-registry=10.99.253.167:8090",
|
||||
"--registry-mirror=http://10.99.253.167:8090",
|
||||
"--insecure-registry=harbor.dvgd.rzd",
|
||||
"--tls=false"
|
||||
]
|
||||
variables:
|
||||
DOCKER_HOST: tcp://docker:2375
|
||||
DOCKER_DRIVER: overlay2
|
||||
DOCKER_TLS_CERTDIR: ""
|
||||
script:
|
||||
- APP_VERSION=$(echo $CI_COMMIT_TAG | tr -d sn)
|
||||
- IMAGE_VERSION=$(echo $CI_COMMIT_TAG | sed 's/sn/v/g')
|
||||
- AUTHOR=$CI_COMMIT_AUTHOR
|
||||
- |
|
||||
docker build \
|
||||
-t $REPO/$PROD_SNAPSHOTS:$IMAGE_VERSION \
|
||||
-t $REPO/$PROD_SNAPSHOTS:latest \
|
||||
-t $PROD_SNAPSHOTS:$IMAGE_VERSION \
|
||||
-t $PROD_SNAPSHOTS:latest \
|
||||
--build-arg app_version=$APP_VERSION \
|
||||
--build-arg commit_author="$AUTHOR" \
|
||||
-f PARR.SnapshotWorker/Dockerfile .
|
||||
- docker login -u $HARBOR_PUSH_USER -p $HARBOR_PUSH_PASS $REPO
|
||||
- docker push --all-tags $REPO/$PROD_SNAPSHOTS
|
||||
tags:
|
||||
- docker
|
||||
|
||||
|
||||
prod_snapshots_deploy:
|
||||
stage: deploy
|
||||
environment:
|
||||
name: parr-snapshots
|
||||
only:
|
||||
- /^sn[0-9]+\.[0-9]+\.[0-9]+$/
|
||||
except:
|
||||
- branches
|
||||
script:
|
||||
- IMAGE_VERSION=$(echo $CI_COMMIT_TAG | sed 's/sn/v/g')
|
||||
- docker login -u $HARBOR_PULL_USER -p $HARBOR_PULL_PASS $REPO
|
||||
#- tag=$CI_COMMIT_TAG docker compose up -d
|
||||
- tag=$IMAGE_VERSION docker stack deploy -c docker-compose.snapshots.yml parr-snapshots --with-registry-auth
|
||||
parallel:
|
||||
matrix:
|
||||
- RUNNER: shell-api-swarm-01
|
||||
tags:
|
||||
- ${RUNNER}
|
||||
|
||||
23
NuGet.config
23
NuGet.config
@@ -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="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" />
|
||||
</disabledPackageSources>
|
||||
</configuration>
|
||||
<packageSources>
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||
<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>
|
||||
@@ -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"]
|
||||
@@ -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": {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -196,7 +196,6 @@ namespace PARR.AIHITMainSyncer.Services
|
||||
}
|
||||
|
||||
// Поиск конфигурации поля для тега
|
||||
// Рекомендация: если метод вызывается в цикле, передавайте найденное поле внешним слоем
|
||||
var tagUnitField = fieldsFromDB.FirstOrDefault(f => f.Code == "tag");
|
||||
bool isTagProperty = tagUnitField != null && multiValueProperty.Key == tagUnitField.AihitName;
|
||||
|
||||
@@ -258,7 +257,7 @@ namespace PARR.AIHITMainSyncer.Services
|
||||
}
|
||||
|
||||
|
||||
private async Task SyncValuesAsync(List<string?> values)
|
||||
private async Task SyncValuesAsync(List<string?> values)
|
||||
{
|
||||
bool hasNull = values.Any(v => v is null);
|
||||
var normalizedNoneNullValues = values
|
||||
@@ -288,6 +287,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 +302,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 +322,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 +340,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(
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,236 +1,261 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.AIHITRelationshipsSyncer.Models;
|
||||
using PARR.AIHITRelationshipsSyncer.Services.Interfaces;
|
||||
using PARR.AIHITRelationshipsSyncer.Settings;
|
||||
using PARR.Core.Repositories.Interfaces.Unit;
|
||||
using PARR.Domain.Entities.Unit;
|
||||
using PARR.Domain.Settings;
|
||||
|
||||
namespace PARR.AIHITRelationshipsSyncer.Services.Implementations
|
||||
namespace PARR.AIHITRelationshipsSyncer.Services.Implementations;
|
||||
|
||||
internal class RelationshipsSyncService : IRelationshipsSyncService
|
||||
{
|
||||
internal class RelationshipsSyncService : IRelationshipsSyncService
|
||||
private readonly ILogger<RelationshipsSyncService> _logger;
|
||||
private readonly IUnitRepository _unitRepository;
|
||||
private readonly SettingsFromDb _settingsFromDb;
|
||||
|
||||
public RelationshipsSyncService(
|
||||
ILogger<RelationshipsSyncService> logger,
|
||||
IUnitRepository unitRepository,
|
||||
SettingsFromDb settingsFromDb)
|
||||
{
|
||||
private readonly ILogger<RelationshipsSyncService> logger;
|
||||
private readonly IUnitRepository unitService;
|
||||
private readonly WorkerSettings workerSettings;
|
||||
|
||||
public RelationshipsSyncService(
|
||||
ILogger<RelationshipsSyncService> logger,
|
||||
IUnitRepository unitService,
|
||||
WorkerSettings workerSettings
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.unitService = unitService;
|
||||
this.workerSettings = workerSettings;
|
||||
}
|
||||
|
||||
|
||||
public async Task SyncAsync(List<AihitData> aihitdata)
|
||||
{
|
||||
var validPairs = ValidateInput(aihitdata);
|
||||
if (!validPairs.Any()) return;
|
||||
|
||||
var sourceUnitNames = ExtractUnitNames(validPairs);
|
||||
var existingUnits = await GetOrCreateUnitsAsync(sourceUnitNames);
|
||||
|
||||
var (toRemove, toAdd) = await GetDeltaAsync(validPairs);
|
||||
|
||||
await RemoveRelationshipsAsync(toRemove);
|
||||
await AddRelationshipsAsync(toAdd, existingUnits);
|
||||
|
||||
await FinalCommitAsync(toRemove.Count, toAdd.Count);
|
||||
}
|
||||
|
||||
private List<(string Parent, string Child)> ValidateInput(List<AihitData> data)
|
||||
{
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
logger.LogWarning("Получены пустые или null данные из АИХ ИТ. Пропускаю синхронизацию");
|
||||
return null!;
|
||||
}
|
||||
|
||||
var validPairs = data
|
||||
.Where(t => !string.IsNullOrWhiteSpace(t.ParentName) && !string.IsNullOrWhiteSpace(t.ChildName))
|
||||
.Where(t => t.ParentName != t.ChildName)
|
||||
.Select(t => (
|
||||
Parent: t.ParentName!.Trim().ToUpperInvariant(),
|
||||
Child: t.ChildName!.Trim().ToUpperInvariant()
|
||||
))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
if (validPairs.Count == 0)
|
||||
{
|
||||
logger.LogWarning("После нормализации не осталось валидных связей. Пропускаю синхронизацию");
|
||||
return new();
|
||||
}
|
||||
|
||||
logger.LogInformation("Получено {Count} валидных связей", validPairs.Count);
|
||||
return validPairs;
|
||||
}
|
||||
|
||||
|
||||
private static List<string> ExtractUnitNames(List<(string Parent, string Child)> pairs)
|
||||
{
|
||||
return pairs
|
||||
.SelectMany(x => new[] { x.Parent, x.Child })
|
||||
.Distinct()
|
||||
.ToList();
|
||||
}
|
||||
|
||||
|
||||
private async Task<Dictionary<string, Unit>> GetOrCreateUnitsAsync(List<string> names)
|
||||
{
|
||||
var existing = await unitService.Get()
|
||||
.AsNoTracking()
|
||||
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
|
||||
|
||||
var missing = names.Except(existing.Keys).ToList();
|
||||
if (!missing.Any()) return existing;
|
||||
|
||||
logger.LogInformation("Создание отсутствующих Unit:{Count}", missing.Count);
|
||||
foreach (var name in missing)
|
||||
{
|
||||
var unit = new Unit
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = name,
|
||||
DateCreated = DateTimeOffset.UtcNow
|
||||
};
|
||||
|
||||
if (await unitService.CreateAsync(unit))
|
||||
{
|
||||
logger.LogInformation("Создан Unit: {Name}", name);
|
||||
existing[name] = unit;
|
||||
}
|
||||
else
|
||||
logger.LogError("Не удалось создать Unit: {Name}", name);
|
||||
}
|
||||
|
||||
await unitService.CommitAsync();
|
||||
return existing;
|
||||
}
|
||||
|
||||
|
||||
private async Task<(List<ExistingRelationship> ToRemove, List<(string, string)> ToAdd)> GetDeltaAsync(List<(string Parent, string Child)> sourcePairs)
|
||||
{
|
||||
var allExistings = await unitService.Get()
|
||||
.AsNoTracking()
|
||||
.Include(u => u.ChildUnits).ThenInclude(r => r.ChildUnit)
|
||||
.Where(u => u.ChildUnits.Any())
|
||||
.SelectMany(u => u.ChildUnits, (parent, relationship) => new ExistingRelationship
|
||||
{
|
||||
ParentName = parent.Name,
|
||||
ChildName = relationship.ChildUnit!.Name,
|
||||
Relationship = relationship
|
||||
}
|
||||
)
|
||||
.ToListAsync();
|
||||
|
||||
var sourceSet = new HashSet<(string, string)>(sourcePairs);
|
||||
var existingSet = new HashSet<(string, string)>(allExistings.Select(x => (x.ParentName, x.ChildName)));
|
||||
|
||||
var toRemove = allExistings.Where(r => !sourceSet.Contains((r.ParentName, r.ChildName))).ToList();
|
||||
var toAdd = sourcePairs.Where(p => !existingSet.Contains(p)).ToList();
|
||||
|
||||
logger.LogInformation("Связей для удаления: {ToRemove}, для добавления: {ToAdd}", toRemove.Count, toAdd.Count);
|
||||
return (toRemove, toAdd);
|
||||
}
|
||||
|
||||
|
||||
private async Task RemoveRelationshipsAsync(List<ExistingRelationship> toRemove)
|
||||
{
|
||||
if (!toRemove.Any()) return;
|
||||
|
||||
var parentNames = toRemove.Select(r => r.ParentName).Distinct().ToList();
|
||||
|
||||
var parents = await unitService.Get()
|
||||
.Include(u => u.ChildUnits)
|
||||
.Where(u => parentNames.Contains(u.Name))
|
||||
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
|
||||
|
||||
foreach (var rel in toRemove)
|
||||
{
|
||||
if (!parents.TryGetValue(rel.ParentName, out var parent))
|
||||
{
|
||||
logger.LogWarning("Родитель '{Parent}' не найден при попытке удаления связи - '{Child}'", rel.ParentName, rel.ChildName);
|
||||
continue;
|
||||
}
|
||||
|
||||
var relationshipToRemove = parent.ChildUnits
|
||||
.FirstOrDefault(r => r.ChildUnitId == rel.Relationship.ChildUnitId);
|
||||
|
||||
if (relationshipToRemove != null)
|
||||
{
|
||||
logger.LogInformation("Удаление связи: '{Parent}' - '{Child}'", rel.ParentName, rel.ChildName);
|
||||
parent.ChildUnits.Remove(relationshipToRemove);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Связь '{Parent}'-'{Child}' не найдена в коллекции ChildUnits для удаления", rel.ParentName, rel.ChildName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AddRelationshipsAsync(List<(string Parent, string Child)> toAdd, Dictionary<string, Unit> allUnits)
|
||||
{
|
||||
if (!toAdd.Any()) return;
|
||||
|
||||
var parentNames = toAdd.Select(x => x.Parent).Distinct().ToList();
|
||||
var parents = await unitService.Get()
|
||||
.Include(u => u.ChildUnits)
|
||||
.Where(u => parentNames.Contains(u.Name))
|
||||
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
|
||||
|
||||
foreach (var (Parent, Child) in toAdd)
|
||||
{
|
||||
if (!parents.TryGetValue(Parent, out var parent) ||
|
||||
!allUnits.TryGetValue(Child, out var child))
|
||||
{
|
||||
logger.LogWarning("Пропущена связь '{Parent}' - '{Child}': Unit не найден", Parent, Child);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parent!.ChildUnits.Any(r => r.ChildUnitId == child.Id))
|
||||
{
|
||||
logger.LogWarning("Связь уже существует: '{Parent}' - '{Child}'", Parent, Child);
|
||||
continue;
|
||||
}
|
||||
|
||||
parent.ChildUnits.Add(new UnitInUnit
|
||||
{
|
||||
ParentUnitId = parent.Id,
|
||||
ChildUnitId = child.Id,
|
||||
DateCreated = DateTimeOffset.UtcNow
|
||||
});
|
||||
|
||||
logger.LogInformation("Добавлена связь: '{Parent}' - '{Child}'", Parent, Child);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async Task FinalCommitAsync(int removedCount, int addedCount)
|
||||
{
|
||||
if (removedCount > 0 || addedCount > 0)
|
||||
{
|
||||
if (await unitService.CommitAsync())
|
||||
{
|
||||
logger.LogInformation("Синхронизация завершена. Удалено: {Removed}, добавлено: {Added}", removedCount, addedCount);
|
||||
}
|
||||
else
|
||||
logger.LogError("Не удалось сохранить изменения в БД");
|
||||
}
|
||||
else
|
||||
logger.LogInformation("Изменений не обнаружено");
|
||||
}
|
||||
|
||||
private sealed class ExistingRelationship
|
||||
{
|
||||
public string ParentName { get; init; }
|
||||
public string ChildName { get; init; }
|
||||
public UnitInUnit Relationship { get; init; }
|
||||
}
|
||||
|
||||
_logger = logger;
|
||||
_unitRepository = unitRepository;
|
||||
_settingsFromDb = settingsFromDb;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SyncAsync(List<AihitData> aihitData)
|
||||
{
|
||||
var validPairs = ValidateInput(aihitData);
|
||||
|
||||
if (validPairs.Count == 0)
|
||||
return;
|
||||
|
||||
if (!await PassSafeguardCheckAsync(validPairs.Count))
|
||||
return;
|
||||
|
||||
var unitNames = ExtractUnitNames(validPairs);
|
||||
var unitsByName = await GetOrCreateUnitsAsync(unitNames);
|
||||
|
||||
var (toRemove, toAdd) = await GetDeltaAsync(validPairs);
|
||||
|
||||
// Удаление и добавление накапливаются в одном ChangeTracker.
|
||||
// CommitAsync сохраняет всё атомарно через SaveChangesAsync.
|
||||
await RemoveRelationshipsAsync(toRemove);
|
||||
await AddRelationshipsAsync(toAdd, unitsByName);
|
||||
await CommitChangesAsync(toRemove.Count, toAdd.Count);
|
||||
}
|
||||
|
||||
private List<(string ParentName, string ChildName)> ValidateInput(List<AihitData> data)
|
||||
{
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
_logger.LogWarning("Получены пустые данные из АИХ ИТ. Синхронизация пропущена");
|
||||
return new List<(string, string)>();
|
||||
}
|
||||
|
||||
var validPairs = data
|
||||
.Where(item => !string.IsNullOrWhiteSpace(item.ParentName) && !string.IsNullOrWhiteSpace(item.ChildName))
|
||||
.Where(item => item.ParentName != item.ChildName)
|
||||
.Select(item => (
|
||||
ParentName: item.ParentName!.Trim().ToUpperInvariant(),
|
||||
ChildName: item.ChildName!.Trim().ToUpperInvariant()
|
||||
))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
if (validPairs.Count == 0)
|
||||
{
|
||||
_logger.LogWarning("После нормализации не осталось валидных связей. Синхронизация пропущена");
|
||||
return new List<(string, string)>();
|
||||
}
|
||||
|
||||
_logger.LogInformation("Получено {Count} валидных связей", validPairs.Count);
|
||||
return validPairs;
|
||||
}
|
||||
|
||||
private async Task<bool> PassSafeguardCheckAsync(int incomingCount)
|
||||
{
|
||||
var previousCount = await _unitRepository.Get()
|
||||
.SelectMany(u => u.ChildUnits)
|
||||
.CountAsync();
|
||||
|
||||
if (previousCount == 0)
|
||||
return true;
|
||||
|
||||
var currentPercentage = Math.Round((decimal)incomingCount / previousCount * 100, 1, MidpointRounding.AwayFromZero);
|
||||
|
||||
if (currentPercentage < _settingsFromDb.MinRelationshipsThresholdPct)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Синхронизация отменена: количество полученных связей ниже порогового значения. " +
|
||||
"Получено: {CurrentCount} ({CurrentPercentage:F1}%), порог: {Threshold}% от прошлого объема ({PreviousCount})",
|
||||
incomingCount, currentPercentage, _settingsFromDb.MinRelationshipsThresholdPct, previousCount);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<string> ExtractUnitNames(List<(string ParentName, string ChildName)> pairs)
|
||||
{
|
||||
return pairs
|
||||
.SelectMany(pair => new[] { pair.ParentName, pair.ChildName })
|
||||
.Distinct()
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<Dictionary<string, Unit>> GetOrCreateUnitsAsync(List<string> names)
|
||||
{
|
||||
var existingUnits = await _unitRepository.Get()
|
||||
.AsNoTracking()
|
||||
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
|
||||
|
||||
var missingNames = names.Except(existingUnits.Keys).ToList();
|
||||
|
||||
if (missingNames.Count == 0)
|
||||
return existingUnits;
|
||||
|
||||
_logger.LogInformation("Создание отсутствующих юнитов: {Count}", missingNames.Count);
|
||||
|
||||
foreach (var name in missingNames)
|
||||
{
|
||||
var unit = new Unit
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = name,
|
||||
DateCreated = DateTimeOffset.UtcNow
|
||||
};
|
||||
|
||||
if (!await _unitRepository.CreateAsync(unit))
|
||||
{
|
||||
_logger.LogError("Не удалось создать юнит: {Name}", name);
|
||||
continue;
|
||||
}
|
||||
|
||||
existingUnits[name] = unit;
|
||||
_logger.LogDebug("Создан юнит: {Name}", name);
|
||||
}
|
||||
|
||||
await _unitRepository.CommitAsync();
|
||||
return existingUnits;
|
||||
}
|
||||
|
||||
private async Task<(List<ExistingRelationship> ToRemove, List<(string ParentName, string ChildName)> ToAdd)> GetDeltaAsync(
|
||||
List<(string ParentName, string ChildName)> sourcePairs)
|
||||
{
|
||||
var relevantParentNames = sourcePairs.Select(p => p.ParentName).Distinct().ToList();
|
||||
|
||||
var existingForParents = await _unitRepository.Get()
|
||||
.AsNoTracking()
|
||||
.Include(u => u.ChildUnits).ThenInclude(r => r.ChildUnit)
|
||||
.Where(u => relevantParentNames.Contains(u.Name))
|
||||
.SelectMany(u => u.ChildUnits, (parent, relationship) => new ExistingRelationship
|
||||
{
|
||||
ParentName = parent.Name,
|
||||
ChildName = relationship.ChildUnit!.Name,
|
||||
Relationship = relationship
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
var sourceSet = new HashSet<(string, string)>(sourcePairs);
|
||||
var existingSet = new HashSet<(string, string)>(
|
||||
existingForParents.Select(x => (x.ParentName, x.ChildName)));
|
||||
|
||||
var toRemove = existingForParents
|
||||
.Where(r => !sourceSet.Contains((r.ParentName, r.ChildName)))
|
||||
.ToList();
|
||||
|
||||
var toAdd = sourcePairs
|
||||
.Where(p => !existingSet.Contains(p))
|
||||
.ToList();
|
||||
|
||||
_logger.LogInformation("Дельта: удаление {ToRemove}, добавление {ToAdd}", toRemove.Count, toAdd.Count);
|
||||
return (toRemove, toAdd);
|
||||
}
|
||||
|
||||
private async Task RemoveRelationshipsAsync(List<ExistingRelationship> toRemove)
|
||||
{
|
||||
if (toRemove.Count == 0)
|
||||
return;
|
||||
|
||||
var parentNames = toRemove.Select(r => r.ParentName).Distinct().ToList();
|
||||
|
||||
var parents = await _unitRepository.Get()
|
||||
.Include(u => u.ChildUnits)
|
||||
.Where(u => parentNames.Contains(u.Name))
|
||||
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
|
||||
|
||||
foreach (var relationship in toRemove)
|
||||
{
|
||||
if (!parents.TryGetValue(relationship.ParentName, out var parent))
|
||||
{
|
||||
_logger.LogWarning("Родитель '{Parent}' не найден при удалении связи с '{Child}'",
|
||||
relationship.ParentName, relationship.ChildName);
|
||||
continue;
|
||||
}
|
||||
|
||||
var entityToRemove = parent.ChildUnits
|
||||
.FirstOrDefault(r => r.ChildUnitId == relationship.Relationship.ChildUnitId);
|
||||
|
||||
if (entityToRemove != null)
|
||||
parent.ChildUnits.Remove(entityToRemove);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AddRelationshipsAsync(
|
||||
List<(string ParentName, string ChildName)> toAdd,
|
||||
Dictionary<string, Unit> unitsByName)
|
||||
{
|
||||
if (toAdd.Count == 0)
|
||||
return;
|
||||
|
||||
var parentNames = toAdd.Select(x => x.ParentName).Distinct().ToList();
|
||||
|
||||
var parents = await _unitRepository.Get()
|
||||
.Include(u => u.ChildUnits)
|
||||
.Where(u => parentNames.Contains(u.Name))
|
||||
.ToDictionaryAsync(u => u.Name, StringComparer.Ordinal);
|
||||
|
||||
foreach (var (parentName, childName) in toAdd)
|
||||
{
|
||||
if (!parents.TryGetValue(parentName, out var parent) ||
|
||||
!unitsByName.TryGetValue(childName, out var child))
|
||||
{
|
||||
_logger.LogWarning("Пропущена связь '{Parent}' - '{Child}': юнит не найден", parentName, childName);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (parent.ChildUnits.Any(r => r.ChildUnitId == child.Id))
|
||||
continue;
|
||||
|
||||
parent.ChildUnits.Add(new UnitInUnit
|
||||
{
|
||||
ParentUnitId = parent.Id,
|
||||
ChildUnitId = child.Id,
|
||||
DateCreated = DateTimeOffset.UtcNow
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CommitChangesAsync(int removedCount, int addedCount)
|
||||
{
|
||||
if (removedCount == 0 && addedCount == 0)
|
||||
{
|
||||
_logger.LogInformation("Изменений не обнаружено");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!await _unitRepository.CommitAsync())
|
||||
throw new InvalidOperationException("Не удалось сохранить изменения связей в БД");
|
||||
|
||||
_logger.LogInformation("Синхронизация завершена. Удалено: {Removed}, добавлено: {Added}", removedCount, addedCount);
|
||||
}
|
||||
|
||||
private sealed class ExistingRelationship
|
||||
{
|
||||
public string ParentName { get; init; } = null!;
|
||||
public string ChildName { get; init; } = null!;
|
||||
public UnitInUnit Relationship { get; init; } = null!;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -32,8 +31,15 @@ RUN dotnet publish "./PARR.AIHITRelationshipsSyncerWorker.csproj" -c $BUILD_CONF
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
|
||||
# 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
|
||||
|
||||
# Fixes an old version TLS (AIH IT GVC)
|
||||
RUN sed -i 's/DEFAULT@SECLEVEL=2/DEFAULT@SECLEVEL=1/g' /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.AIHITRelationshipsSyncerWorker.dll"]
|
||||
@@ -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": {
|
||||
|
||||
@@ -1,31 +1,27 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"Microsoft.EntityFrameworkCore": "Debug",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
//"Microsoft": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
"ConnectionStrings": {
|
||||
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log/log-.txt",
|
||||
"rollingInterval": "Day"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"MqSettings": {
|
||||
"HostName": "10.99.253.216"
|
||||
}
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Debug",
|
||||
"PARR.DAL": "Information"
|
||||
}
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log/log-.txt",
|
||||
"rollingInterval": "Day"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"MqSettings": {
|
||||
"HostName": "10.99.253.216"
|
||||
}
|
||||
}
|
||||
@@ -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": {
|
||||
|
||||
@@ -99,6 +99,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.WorkloadBuilderWorker"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.TaskReconciliationWorker", "PARR.TaskReconciliationWorker\PARR.TaskReconciliationWorker.csproj", "{DB701295-1696-4E1A-9088-D3AECF823BA6}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.SnapshotWorker", "PARR.SnapshotWorker\PARR.SnapshotWorker.csproj", "{F5318808-942F-4EFB-9BC9-00B9F4704EB5}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -275,6 +277,10 @@ Global
|
||||
{DB701295-1696-4E1A-9088-D3AECF823BA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DB701295-1696-4E1A-9088-D3AECF823BA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DB701295-1696-4E1A-9088-D3AECF823BA6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace PARR.API.Contracts.V1
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Query.Expressions.Internal;
|
||||
|
||||
namespace PARR.API.Contracts.V1
|
||||
{
|
||||
// https://tproger.ru/translations/luchshie-praktiki-razrabotki-rest-api-20-sovetov/
|
||||
|
||||
@@ -210,11 +212,21 @@
|
||||
public const string GetPeriodStatistics = BaseStat + "/robot-tasks/{robot}/period/";
|
||||
}
|
||||
|
||||
public static class StatRobotTaskDetails
|
||||
{
|
||||
public const string Details = BaseStat + "/robot-tasks/details/{robot}/{task}";
|
||||
}
|
||||
|
||||
public static class StatRobotStatus
|
||||
{
|
||||
public const string Get = BaseStat + "/robot-statuses/";
|
||||
}
|
||||
|
||||
public static class StatRobotStatusDetails
|
||||
{
|
||||
public const string Details = BaseStat + "/robot-statuses/details/{robot}/{status}";
|
||||
}
|
||||
|
||||
public static class StatRobotHistory
|
||||
{
|
||||
public const string Get = BaseStat + "/robot-histories/";
|
||||
@@ -224,6 +236,7 @@
|
||||
{
|
||||
public const string Get = BaseStat + "/templates/";
|
||||
public const string GetForPeriod = BaseStat + "/templates/period";
|
||||
public const string GetTemplatesWithoutScheduleAndTaskCount = BaseStat + "/templates/without-schedule";
|
||||
}
|
||||
|
||||
public static class StatStatusTypeTemplates
|
||||
@@ -324,6 +337,16 @@
|
||||
public const string GetWorkloadTemplateReport = BaseStat + "/workload/templates/{reportType}/{filter}/{state}/{date}";
|
||||
}
|
||||
|
||||
public static class StatRobotMetrics
|
||||
{
|
||||
public const string GetRobotStatusMetrics = BaseStat + "/robot-metrics/robot-status/{robotCode}/{period}";
|
||||
|
||||
public const string GetTaskStatusMetrics = BaseStat + "/robot-metrics/task-status/{robotCode}/{period}";
|
||||
|
||||
public const string GetFilteredMetrics = BaseStat + "/robot-metrics/filtered";
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Наряды
|
||||
@@ -592,6 +615,17 @@
|
||||
|
||||
#endregion
|
||||
|
||||
#region HelpDocument
|
||||
|
||||
public static class HelpDocument
|
||||
{
|
||||
public const string GetDocument = Base + "/help-documents/get-document";
|
||||
|
||||
public const string GitLabWebhook = Base + "/help-documents/modified";
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace PARR.API.Contracts.V1.Requests
|
||||
{
|
||||
public record JobGroupRequest
|
||||
public record JobGroupRequest : UnitFiltersBaseRequest
|
||||
{
|
||||
public required string Name { get; init; }
|
||||
|
||||
@@ -36,6 +36,14 @@
|
||||
|
||||
public Guid? ScheduleExcludeTypeCalendarId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Маска ЭК
|
||||
/// </summary>
|
||||
public required string EkMask { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Автораспределение включено
|
||||
/// </summary>
|
||||
public bool IsAutoDistributionEnabled { get; init; }
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,20 +1,13 @@
|
||||
namespace PARR.API.Contracts.V1.Requests
|
||||
{
|
||||
public record JobRequest
|
||||
public record JobRequest : UnitFiltersBaseRequest
|
||||
{
|
||||
|
||||
public required Guid TnkId { get; init; }
|
||||
|
||||
public required Guid GroupId { get; init; }
|
||||
|
||||
public required string Name { get; init; }
|
||||
|
||||
//public int? MinValueRelationships { get; init; }
|
||||
|
||||
//public int? MaxValueRelationships { get; init; }
|
||||
|
||||
//public bool? IsParentRelationships { get; init; }
|
||||
|
||||
public JobRelationships? Relationships { get; init; }
|
||||
|
||||
public required string TemplateNameMask { get; init; }
|
||||
@@ -25,19 +18,9 @@
|
||||
|
||||
public required string ResponseAreaMask { get; init; }
|
||||
|
||||
//#region AutoControl
|
||||
|
||||
//public bool IsEnableAutoControl { get; set; }
|
||||
|
||||
//public bool InitUsedTemplateState { get; set; }
|
||||
|
||||
//public bool InitUsedScheduleState { get; set; }
|
||||
|
||||
//#endregion
|
||||
|
||||
public JobAutoControlRequest? AutoControl { get; init; }
|
||||
|
||||
public required List<UnitFilterRequest> UnitFilters { get; init; }
|
||||
//public required List<UnitFilterRequest> UnitFilters { get; init; }
|
||||
}
|
||||
|
||||
public record JobRelationships
|
||||
@@ -49,43 +32,38 @@
|
||||
public bool IsParentRelationships { get; init; }
|
||||
}
|
||||
|
||||
public record UnitFilterRequest
|
||||
{
|
||||
///// <summary>
|
||||
///// Id = null в методе Create, в Update обязателен
|
||||
///// </summary>
|
||||
//public Guid? Id { get; set; }
|
||||
//public record UnitFilterRequest
|
||||
//{
|
||||
// public required string UnitFilterMask { get; init; }
|
||||
|
||||
public required string UnitFilterMask { get; init; }
|
||||
// public List<FieldFilterRequest>? FieldFilters { get; init; }
|
||||
|
||||
public List<FieldFilterRequest>? FieldFilters { get; init; }
|
||||
|
||||
public List<RelationshipFilterRequest>? RelationshipFilters { get; init; }
|
||||
}
|
||||
// public List<RelationshipFilterRequest>? RelationshipFilters { get; init; }
|
||||
//}
|
||||
|
||||
|
||||
public record FieldFilterRequest
|
||||
{
|
||||
//public record FieldFilterRequest
|
||||
//{
|
||||
|
||||
public Guid FieldId { get; init; }
|
||||
// public Guid FieldId { get; init; }
|
||||
|
||||
public string? ValueMask { get; init; }
|
||||
// public string? ValueMask { get; init; }
|
||||
|
||||
public bool IsInverse { get; init; } = false;
|
||||
// public bool IsInverse { get; init; } = false;
|
||||
|
||||
}
|
||||
//}
|
||||
|
||||
|
||||
public record RelationshipFilterRequest
|
||||
{
|
||||
public Guid FieldId { get; init; }
|
||||
//public record RelationshipFilterRequest
|
||||
//{
|
||||
// public Guid FieldId { get; init; }
|
||||
|
||||
public bool? IsParent { get; init; }
|
||||
// public bool? IsParent { get; init; }
|
||||
|
||||
public string? ValueMask { get; init; }
|
||||
// public string? ValueMask { get; init; }
|
||||
|
||||
public bool? IsFullMatch { get; init; }
|
||||
// public bool? IsFullMatch { get; init; }
|
||||
|
||||
public bool? IsInverse { get; init; }
|
||||
}
|
||||
// public bool? IsInverse { get; init; }
|
||||
//}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Contracts.V1.Requests.Queries
|
||||
{
|
||||
public record RobotFilteredMetricsQuery
|
||||
{
|
||||
public RobotsEnum? RobotCode { get; init; }
|
||||
|
||||
public RobotStatusEnum? RobotStatusCode { get; init; }
|
||||
|
||||
public TaskStatusEnum? TaskStatusCode { get; init; }
|
||||
|
||||
public DateTimeOffset? DateFrom { get; init; }
|
||||
|
||||
public DateTimeOffset? DateTo { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Шаг группировки в минутах (например, 2, 30, 60, 1440)
|
||||
/// </summary>
|
||||
public int IntervalMinutes { get; set; } = 30;
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,31 @@
|
||||
|
||||
namespace PARR.API.Contracts.V1.Requests.Queries
|
||||
{
|
||||
public class RobotHistoryQuery
|
||||
public record RobotHistoryQuery
|
||||
{
|
||||
/// <summary>
|
||||
/// Фильтр по ИД шаблона
|
||||
/// </summary>
|
||||
public Guid? TemplateId { get; set; }
|
||||
public Guid? TemplateId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Фильтр по ИД робота
|
||||
/// </summary>
|
||||
public RobotsEnum? RobotCode { get; set; }
|
||||
public RobotsEnum? RobotCode { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Фильтр по уровню истории
|
||||
/// </summary>
|
||||
public RobotHistoryLevelEnum? HistoryLevel { get; set; }
|
||||
public RobotHistoryLevelEnum? HistoryLevel { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Дата начала
|
||||
/// </summary>
|
||||
public DateTimeOffset? DateFrom { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Дата окончания
|
||||
/// </summary>
|
||||
public DateTimeOffset? DateTo { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
namespace PARR.API.Contracts.V1.Requests
|
||||
{
|
||||
public class TnkRequest
|
||||
public record TnkRequest
|
||||
{
|
||||
public required string Name { get; set; }
|
||||
public string? ShortName { get; set; }
|
||||
public int? EsppId { get; set; }
|
||||
public Guid SubprocessId { get; set; }
|
||||
public required string Name { get; init; }
|
||||
public string? ShortName { get; init; }
|
||||
public int? EsppId { get; init; }
|
||||
public int? DurationMinutes { get; init; }
|
||||
public Guid SubprocessId { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
42
PARR.API/Contracts/V1/Requests/UnitFiltersBaseRequest.cs
Normal file
42
PARR.API/Contracts/V1/Requests/UnitFiltersBaseRequest.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
namespace PARR.API.Contracts.V1.Requests
|
||||
{
|
||||
/// <summary>
|
||||
/// Unit фильтры для Job и JobGroup
|
||||
/// </summary>
|
||||
public record UnitFiltersBaseRequest
|
||||
{
|
||||
public required List<UnitFilterRequest> UnitFilters { get; init; }
|
||||
}
|
||||
|
||||
public record UnitFilterRequest
|
||||
{
|
||||
public required string UnitFilterMask { get; init; }
|
||||
|
||||
public List<FieldFilterRequest>? FieldFilters { get; init; }
|
||||
|
||||
public List<RelationshipFilterRequest>? RelationshipFilters { get; init; }
|
||||
}
|
||||
|
||||
public record FieldFilterRequest
|
||||
{
|
||||
public Guid FieldId { get; init; }
|
||||
|
||||
public string? ValueMask { get; init; }
|
||||
|
||||
public bool IsInverse { get; init; } = false;
|
||||
|
||||
}
|
||||
|
||||
public record RelationshipFilterRequest
|
||||
{
|
||||
public Guid FieldId { get; init; }
|
||||
|
||||
public bool? IsParent { get; init; }
|
||||
|
||||
public string? ValueMask { get; init; }
|
||||
|
||||
public bool? IsFullMatch { get; init; }
|
||||
|
||||
public bool? IsInverse { get; init; }
|
||||
}
|
||||
}
|
||||
33
PARR.API/Contracts/V1/Responses/HelpDocumentResponse.cs
Normal file
33
PARR.API/Contracts/V1/Responses/HelpDocumentResponse.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
namespace PARR.API.Contracts.V1.Responses
|
||||
{
|
||||
public record HelpDocumentResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Уникальный ID (например: "ui/billing/invoice-create/vat-calc")
|
||||
/// </summary>
|
||||
public string HelpId { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Заголовок из метаданных файла (title)
|
||||
/// </summary>
|
||||
public string Title { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// // Чистый Markdown-текст (все, что идет после метаданных)
|
||||
/// </summary>
|
||||
public string Content { get; init; } = string.Empty;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// ИД для перехода назад
|
||||
/// </summary>
|
||||
public string? PrevId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// ИД для перехода вперед
|
||||
/// </summary>
|
||||
public string? NextId { get; init; }
|
||||
|
||||
public string? EditUrl { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
namespace PARR.API.Contracts.V1.Responses
|
||||
{
|
||||
public class JobGroupBaseResponse
|
||||
public class JobGroupShortResponse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
}
|
||||
|
||||
//public bool? IsUmbrella { get; set; }
|
||||
|
||||
public class JobGroupBaseResponse : JobGroupShortResponse
|
||||
{
|
||||
public required string ShortDescription { get; set; }
|
||||
|
||||
public required string FullDescription { get; set; }
|
||||
@@ -49,9 +50,19 @@
|
||||
// public int? AgentTimeOutSec { get; set; }
|
||||
|
||||
// public string? AgentScript { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Юнит фильтры
|
||||
/// </summary>
|
||||
public List<UnitFilterResponse>? UnitFilters { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Маска ЭК
|
||||
/// </summary>
|
||||
public required string EkMask { get; set; }
|
||||
}
|
||||
|
||||
public class JobGroupResponse : JobGroupWithDistributionConfigResponse //: JobGroupBaseResponse
|
||||
public class JobGroupResponse : JobGroupWithDistributionConfigResponse
|
||||
{
|
||||
//public List<JobResponse>? Jobs { get; set; }
|
||||
public int JobsCount { get; set; }
|
||||
@@ -71,9 +82,9 @@
|
||||
public ScheduleExcludeTypeCalendarResponse? ScheduleExcludeTypeCalendar { get; set; }
|
||||
|
||||
///// <summary>
|
||||
///// Настройки автораспределения
|
||||
///// Юнит фильтры
|
||||
///// </summary>
|
||||
//public JobGroupDistributionConfigResponse? DistributionConfig { get; set; }
|
||||
//public List<UnitFilterResponse>? UnitFilters { get; set; }
|
||||
}
|
||||
|
||||
public class JobGroupAutoControlResponse
|
||||
|
||||
@@ -30,6 +30,9 @@
|
||||
|
||||
public int? TemplatesCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Юнит фильтры Работы
|
||||
/// </summary>
|
||||
public List<UnitFilterResponse>? UnitFilters { get; set; }
|
||||
|
||||
public JobAutoControlResponse? AutoControl { get; set; }
|
||||
@@ -46,44 +49,6 @@
|
||||
}
|
||||
|
||||
|
||||
public class UnitFilterResponse
|
||||
{
|
||||
public required Guid Id { get; set; }
|
||||
|
||||
public required string UnitFilterMask { get; set; }
|
||||
|
||||
public List<FieldFilterResponse>? FieldFilters { get; set; }
|
||||
|
||||
public List<RelationshipFilterResponse>? RelationshipFilters { get; set; }
|
||||
|
||||
}
|
||||
|
||||
|
||||
public class FieldFilterResponse
|
||||
{
|
||||
public required Guid Id { get; set; }
|
||||
|
||||
public required FieldResponse Field { get; set; }
|
||||
|
||||
public string? ValueMask { get; set; }
|
||||
|
||||
public bool IsInverse { get; set; }
|
||||
|
||||
}
|
||||
|
||||
|
||||
public class RelationshipFilterResponse
|
||||
{
|
||||
public required FieldResponse Field { get; set; }
|
||||
|
||||
public bool? IsParent { get; set; }
|
||||
|
||||
public string? ValueMask { get; set; }
|
||||
|
||||
public bool? IsFullMatch { get; set; }
|
||||
|
||||
public bool? IsInverse { get; set; }
|
||||
}
|
||||
|
||||
|
||||
public class TemplateStats
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace PARR.API.Contracts.V1.Responses.Statistics
|
||||
{
|
||||
public record StatFilteredChartPoint
|
||||
{
|
||||
public DateTimeOffset Timestamp { get; init; }
|
||||
public int Count { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace PARR.API.Contracts.V1.Responses.Statistics
|
||||
{
|
||||
public record StatRobotStatusChartPoint
|
||||
{
|
||||
public DateTimeOffset Timestamp { get; init; }
|
||||
public int Wait { get; init; }
|
||||
public int InProgress { get; init; }
|
||||
public int Error { get; init; }
|
||||
public int Complete { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace PARR.API.Contracts.V1.Responses.Statistics
|
||||
{
|
||||
public record StatRobotTaskDetailsResponse
|
||||
{
|
||||
public RobotResponse Robot { get; init; } = null!;
|
||||
public TaskStatusResponse Task { get; init; } = null!;
|
||||
|
||||
public List<StatRobotTaskGroupDetailsResponse> Details { get; init; } = null!;
|
||||
}
|
||||
|
||||
public record StatRobotTaskGroupDetailsResponse
|
||||
{
|
||||
public JobGroupShortResponse JobGroup { get; init; } = null!;
|
||||
public int TemplatesCount { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace PARR.API.Contracts.V1.Responses.Statistics
|
||||
{
|
||||
public record StatTaskStatusChartPoint
|
||||
{
|
||||
public DateTimeOffset Timestamp { get; init; }
|
||||
public int Creating { get; init; }
|
||||
public int Updating { get; init; }
|
||||
public int Ok { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace PARR.API.Contracts.V1.Responses.Statistics
|
||||
{
|
||||
public record StatTemplatesWithoutScheduleResponse(int Count);
|
||||
|
||||
}
|
||||
@@ -33,6 +33,14 @@
|
||||
/// </summary>
|
||||
public string? ResponseArea { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// ЭК согласно настроек маски группы работ, подставляется в шаблон ЕСПП
|
||||
/// </summary>
|
||||
public required string EsppEk { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Юнит привязанный к шаблону
|
||||
/// </summary>
|
||||
public UnitWithAttributesResponse? Unit { get; set; }
|
||||
|
||||
public TemplateStatusTypeResponse? StatusType { get; set; }
|
||||
@@ -55,7 +63,6 @@
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class TemplateResponse : TemplateBaseResponse
|
||||
{
|
||||
public required string Category { get; set; }
|
||||
@@ -72,6 +79,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; }
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
|
||||
public int? EsppId { get; set; }
|
||||
|
||||
public int? DurationMinutes { get; set; }
|
||||
|
||||
public Guid SubprocessId { get; set; }
|
||||
}
|
||||
|
||||
|
||||
32
PARR.API/Contracts/V1/Responses/UnitFilterBaseResponse.cs
Normal file
32
PARR.API/Contracts/V1/Responses/UnitFilterBaseResponse.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace PARR.API.Contracts.V1.Responses
|
||||
{
|
||||
/// <summary>
|
||||
/// Базовый респонс для юнит фильтров
|
||||
/// </summary>
|
||||
public class UnitFilterResponse
|
||||
{
|
||||
public required Guid Id { get; set; }
|
||||
public required string UnitFilterMask { get; set; }
|
||||
public List<FieldFilterResponse>? FieldFilters { get; set; }
|
||||
public List<RelationshipFilterResponse>? RelationshipFilters { get; set; }
|
||||
}
|
||||
|
||||
|
||||
public class FieldFilterResponse
|
||||
{
|
||||
public required Guid Id { get; set; }
|
||||
public required FieldResponse Field { get; set; }
|
||||
public string? ValueMask { get; set; }
|
||||
public bool IsInverse { get; set; }
|
||||
}
|
||||
|
||||
|
||||
public class RelationshipFilterResponse
|
||||
{
|
||||
public required FieldResponse Field { get; set; }
|
||||
public bool? IsParent { get; set; }
|
||||
public string? ValueMask { get; set; }
|
||||
public bool? IsFullMatch { get; set; }
|
||||
public bool? IsInverse { get; set; }
|
||||
}
|
||||
}
|
||||
173
PARR.API/Controllers/V1/HelpDocumentController.cs
Normal file
173
PARR.API/Controllers/V1/HelpDocumentController.cs
Normal file
@@ -0,0 +1,173 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
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.Services.HelpDocument.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Exceptions;
|
||||
using PARR.Domain.Settings;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
/// <summary>
|
||||
/// Контроллер по работе со справочной документацией
|
||||
/// </summary>
|
||||
public class HelpDocumentController : BaseApiController
|
||||
{
|
||||
private readonly IHelpDocumentService _helpDocumentService;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly HelpDocumentSettings _helpDocumentSettings;
|
||||
private readonly ILogger<HelpDocumentController> _logger;
|
||||
|
||||
public HelpDocumentController(
|
||||
IHelpDocumentService helpDocumentService,
|
||||
IMapper mapper,
|
||||
HelpDocumentSettings helpDocumentSettings,
|
||||
ILogger<HelpDocumentController> logger
|
||||
)
|
||||
{
|
||||
_helpDocumentService = helpDocumentService;
|
||||
_mapper = mapper;
|
||||
_helpDocumentSettings = helpDocumentSettings;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить документ справки
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// <param name="helpId">Путь к справке (например: ui/billing/invoice-create/vat-calc)</param>
|
||||
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
||||
[HttpGet(ApiRoutes.HelpDocument.GetDocument)]
|
||||
public async Task<IActionResult> GetHelpDocument([FromQuery] string helpId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(helpId))
|
||||
throw new ArgumentNullException(nameof(helpId), "Значение не может быть пустым");
|
||||
|
||||
var documnet = await _helpDocumentService.GetHelpDocumentAsync(helpId);
|
||||
|
||||
if (documnet == null)
|
||||
return NotFound();
|
||||
|
||||
var response = _mapper.Map<HelpDocumentResponse>(documnet);
|
||||
|
||||
return Ok(new Response<HelpDocumentResponse>(response, true));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Вебхук от GitLab для автоматического сброса кэша при пуше изменений
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[AllowAnonymous]
|
||||
[HttpPost(ApiRoutes.HelpDocument.GitLabWebhook)]
|
||||
public async Task<IActionResult> GitLabWebhook([FromBody] JsonNode payload)
|
||||
{
|
||||
_logger.LogInformation("Получен Webhook запрос от GitLab.");
|
||||
|
||||
#region Проверка безопасности
|
||||
|
||||
// GitLab передает токен в заголовке X-Gitlab-Token
|
||||
if (!Request.Headers.TryGetValue("X-Gitlab-Token", out var receivedToken))
|
||||
{
|
||||
_logger.LogWarning("Запрос вебхука отклонен. Отсутствует заголовок X-Gitlab-Token.");
|
||||
throw new UnauthorizedException("Отсутствует авторизационный токен вебхука.");
|
||||
}
|
||||
|
||||
if (receivedToken.ToString() != _helpDocumentSettings.WebhookToken)
|
||||
{
|
||||
_logger.LogWarning("Запрос вебхука отклонен. Передан невалидный Secret Token.");
|
||||
throw new UnauthorizedException("Неверный токен вебхука.");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
_logger.LogDebug("Проверка Secret Token пройдена успешно. Начинается обработка изменений.");
|
||||
|
||||
try
|
||||
{
|
||||
// Проверяем, что это событие push
|
||||
var objectKind = payload["object_kind"]?.ToString();
|
||||
if (objectKind != "push")
|
||||
{
|
||||
_logger.LogDebug("Игнорируем вебхук: тип события '{ObjectKind}' не является 'push'.", objectKind);
|
||||
return Ok(new { message = "Ignored non-push event" });
|
||||
}
|
||||
|
||||
// Извлекаем массив коммитов
|
||||
var commits = payload["commits"]?.AsArray();
|
||||
if (commits == null || commits.Count == 0)
|
||||
{
|
||||
_logger.LogDebug("В вебхуке отсутствуют коммиты.");
|
||||
return Ok(new { message = "No commits found" });
|
||||
}
|
||||
|
||||
var filesToInvalidate = new HashSet<string>();
|
||||
|
||||
// Пробегаемся по коммитам и собираем измененные/добавленные файлы
|
||||
foreach (var commit in commits)
|
||||
{
|
||||
var modifiedFiles = commit?["modified"]?.AsArray();
|
||||
if (modifiedFiles != null)
|
||||
{
|
||||
foreach (var file in modifiedFiles)
|
||||
{
|
||||
var filePath = file?.ToString();
|
||||
if (filePath != null && filePath.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
filesToInvalidate.Add(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var addedFiles = commit?["added"]?.AsArray();
|
||||
if (addedFiles != null)
|
||||
{
|
||||
foreach (var file in addedFiles)
|
||||
{
|
||||
var filePath = file?.ToString();
|
||||
if (filePath != null && filePath.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
filesToInvalidate.Add(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filesToInvalidate.Count == 0)
|
||||
{
|
||||
_logger.LogDebug("Среди измененных файлов в коммитах нет документов .md. Кэш не изменен.");
|
||||
return Ok(new { message = "No .md files modified" });
|
||||
}
|
||||
|
||||
_logger.LogInformation("Вебхук зафиксировал изменения в {Count} файлах справок. Начинается сброс кэша...", filesToInvalidate.Count);
|
||||
|
||||
// Инвалидируем кэш для каждого измененного файла
|
||||
foreach (var file in filesToInvalidate)
|
||||
{
|
||||
// Превращаем путь "ui/billing/vat-calc.md" обратно в helpId "ui/billing/vat-calc"
|
||||
var helpId = file.Substring(0, file.Length - 3);
|
||||
|
||||
_logger.LogDebug("Сброс кэша по вебхуку для HelpId: {HelpId}", helpId);
|
||||
await _helpDocumentService.ClearCacheAsync(helpId);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Сброс кэша по вебхуку GitLab успешно завершен.");
|
||||
return Ok(new { clearedFilesCount = filesToInvalidate.Count });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при обработке Webhook от GitLab");
|
||||
// Возвращаем 200 или 500 в зависимости от политики.
|
||||
// Обычно возвращают BadRequest/InternalServerError, чтобы в GitLab в истории вебхуков была видна ошибка отладки.
|
||||
throw new ExternalServiceException("Внутренняя ошибка обработки вебхука");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -43,7 +44,6 @@ namespace PARR.API.Controllers.V1
|
||||
private readonly IRabbitService _mqService;
|
||||
private readonly MqSettings _mqSettings;
|
||||
private readonly IClientService _clientService;
|
||||
private readonly IJobAutoControlRepository _jobAutoControlRepository;
|
||||
private readonly IMatchingStatusService _matchingStatusService;
|
||||
|
||||
public JobController(
|
||||
@@ -58,7 +58,6 @@ namespace PARR.API.Controllers.V1
|
||||
IRabbitService mqService,
|
||||
MqSettings mqSettings,
|
||||
IClientService clientService,
|
||||
IJobAutoControlRepository jobAutoControlRepository,
|
||||
IMatchingStatusService matchingStatusService
|
||||
)
|
||||
{
|
||||
@@ -70,7 +69,6 @@ namespace PARR.API.Controllers.V1
|
||||
_mqService = mqService;
|
||||
_mqSettings = mqSettings;
|
||||
_clientService = clientService;
|
||||
_jobAutoControlRepository = jobAutoControlRepository;
|
||||
_matchingStatusService = matchingStatusService;
|
||||
}
|
||||
|
||||
@@ -84,6 +82,7 @@ namespace PARR.API.Controllers.V1
|
||||
var paginationFilter = _mapper.Map<PaginationFilter>(paginationQuery);
|
||||
|
||||
IQueryable<Job> query = _jobRepository.Get()
|
||||
.AsNoTracking()
|
||||
.Include(t => t.AutoControl);
|
||||
|
||||
|
||||
@@ -154,9 +153,22 @@ namespace PARR.API.Controllers.V1
|
||||
{
|
||||
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.Group)
|
||||
.ThenInclude(t => t.GroupType)
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.AutoControl)
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.GroupingUnitField)
|
||||
//--- Фильтры в группе
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t=>t.UnitField)
|
||||
//---
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
@@ -164,6 +176,7 @@ namespace PARR.API.Controllers.V1
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.AutoControl)
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
|
||||
if (job == null)
|
||||
@@ -171,12 +184,9 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
var response = _mapper.Map<JobResponse>(job);
|
||||
|
||||
response.TemplatesCount = await GetCountTemplatesAsync(id); //await templateService.Get().CountAsync(t => t.JobId == id);
|
||||
response.TemplatesCount = await GetCountTemplatesAsync(id);
|
||||
response.MatchingStatus = await GetMatchingStatusAsync(id);
|
||||
|
||||
//var statistics = await GetStatisticsAsync(response.Id);
|
||||
//BindStatistics(response, statistics);
|
||||
|
||||
return Ok(new Response<JobResponse>(response, true));
|
||||
}
|
||||
|
||||
@@ -245,7 +255,18 @@ namespace PARR.API.Controllers.V1
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.AutoControl)
|
||||
//--- Фильтры в группе
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
//---
|
||||
.FirstOrDefaultAsync(t => t.Id == job.Id);
|
||||
|
||||
var locationUri = _uriService.GetUri(ApiRoutes.Job.Get, ApiRoutes.Job.getParam, createdJob!.Id);
|
||||
@@ -363,10 +384,21 @@ namespace PARR.API.Controllers.V1
|
||||
.Include(t => t.Group).ThenInclude(t => t.GroupingUnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t=>t.UnitField)
|
||||
.Include(t => t.AutoControl)
|
||||
//--- Фильтры в группе
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.Group)
|
||||
.ThenInclude(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
//---
|
||||
.FirstAsync(t => t.Id == orig.Id);
|
||||
|
||||
var response = _mapper.Map<JobResponse>(updatedJob);
|
||||
@@ -413,124 +445,6 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
orig.UnitFilters.Add(newUnitFilter);
|
||||
}
|
||||
|
||||
#region old
|
||||
/* Писал полноценный апдейт, но Миша сказал что нахрен это - просто все удаляем, а потом создаём заново... Ох уж этот Миша...
|
||||
//Сразу удаляем UnitFilter которых нет
|
||||
var toDelete = orig.UnitFilters.Where(t => !mappedRequest.UnitFilters.Any(e => e.Id == t.Id));
|
||||
foreach (var item in toDelete)
|
||||
orig.UnitFilters.Remove(item);
|
||||
|
||||
foreach (var mappedUnitFilter in mappedRequest.UnitFilters)
|
||||
{
|
||||
var origUnitFilter = orig.UnitFilters.FirstOrDefault(t => t.Id == mappedUnitFilter.Id);
|
||||
|
||||
if (origUnitFilter == null)
|
||||
{
|
||||
var newUnitFilter = new JobUnitFilter
|
||||
{
|
||||
UnitFilter = mappedUnitFilter.UnitFilter,
|
||||
DateCreated = DateTimeOffset.UtcNow,
|
||||
JobId = orig.Id
|
||||
};
|
||||
|
||||
foreach (var newRequestFieldFilter in mappedUnitFilter.FieldFilters)
|
||||
{
|
||||
var newFieldFilter = CreateFieldFilter(newUnitFilter.Id, newRequestFieldFilter.FieldId, newRequestFieldFilter.ValueMask);
|
||||
|
||||
newUnitFilter.FieldFilters.Add(newFieldFilter);
|
||||
}
|
||||
|
||||
foreach (var newRequestRelationshipFilter in mappedUnitFilter.RelationshipFilters)
|
||||
{
|
||||
var newRelationshipFilter = CreateRelationshipFilter(newRequestRelationshipFilter.FieldId,
|
||||
newRequestRelationshipFilter.IsParent,
|
||||
newRequestRelationshipFilter.IsFullMatch,
|
||||
newRequestRelationshipFilter.IsInverse,
|
||||
newRequestRelationshipFilter.ValueMask);
|
||||
newUnitFilter.RelationshipFilters.Add(newRelationshipFilter);
|
||||
}
|
||||
|
||||
orig.UnitFilters.Add(newUnitFilter);
|
||||
}
|
||||
else
|
||||
{
|
||||
#region Непосредственно UnitFilter
|
||||
if (origUnitFilter.UnitFilter != mappedUnitFilter.UnitFilter)
|
||||
{
|
||||
origUnitFilter.UnitFilter = mappedUnitFilter.UnitFilter;
|
||||
origUnitFilter.DateModified = DateTimeOffset.UtcNow;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region FieldFilters
|
||||
//Сразу удаляем неактуальные
|
||||
var fieldFiltersToDelete = origUnitFilter.FieldFilters.Where(t => !mappedUnitFilter.FieldFilters.Any(m => m.FieldId == t.FieldId));
|
||||
foreach (var item in fieldFiltersToDelete)
|
||||
origUnitFilter.FieldFilters.Remove(item);
|
||||
|
||||
//Перебираем FieldFilter
|
||||
foreach (var mappedFieldFilter in mappedUnitFilter.FieldFilters)
|
||||
{
|
||||
var origFieldFilter = origUnitFilter.FieldFilters.FirstOrDefault(t => t.FieldId == mappedFieldFilter.FieldId);
|
||||
|
||||
if (origFieldFilter == null)//Нет в БД? не проблема - создадим
|
||||
{
|
||||
var newFieldFilter = CreateFieldFilter(origUnitFilter.Id, mappedFieldFilter.FieldId, mappedFieldFilter.ValueMask);
|
||||
origUnitFilter.FieldFilters.Add(newFieldFilter);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (origFieldFilter.ValueMask != mappedFieldFilter.ValueMask)
|
||||
{
|
||||
origFieldFilter.ValueMask = mappedFieldFilter.ValueMask;
|
||||
origFieldFilter.DateModified = DateTimeOffset.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region RelationshipFilters
|
||||
//Сразу удаляем неактуальные
|
||||
var relationshipFiltersToDelete = origUnitFilter.RelationshipFilters.Where(t => !mappedUnitFilter.RelationshipFilters.Any(m => m.FieldId == t.FieldId));
|
||||
foreach (var item in relationshipFiltersToDelete)
|
||||
origUnitFilter.RelationshipFilters.Remove(item);
|
||||
|
||||
//Перебираем RelationshipFilters
|
||||
foreach (var mappedRelationshipFilter in mappedUnitFilter.RelationshipFilters)
|
||||
{
|
||||
var origRelationshipFilter = origUnitFilter.RelationshipFilters.FirstOrDefault(t => t.FieldId == mappedRelationshipFilter.FieldId);
|
||||
|
||||
if (origRelationshipFilter == null)//Нет в БД? не проблема - создадим
|
||||
{
|
||||
var newRelationshipFilter = CreateRelationshipFilter(mappedRelationshipFilter.FieldId,
|
||||
mappedRelationshipFilter.IsParent,
|
||||
mappedRelationshipFilter.IsFullMatch,
|
||||
mappedRelationshipFilter.IsInverse,
|
||||
mappedRelationshipFilter.ValueMask);
|
||||
|
||||
origUnitFilter.RelationshipFilters.Add(newRelationshipFilter);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (origRelationshipFilter.IsParent != mappedRelationshipFilter.IsParent)
|
||||
origRelationshipFilter.IsParent = mappedRelationshipFilter.IsParent;
|
||||
|
||||
if (origRelationshipFilter.ValueMask != mappedRelationshipFilter.ValueMask)
|
||||
origRelationshipFilter.ValueMask = mappedRelationshipFilter.ValueMask;
|
||||
|
||||
if (origRelationshipFilter.IsFullMatch != mappedRelationshipFilter.IsFullMatch)
|
||||
origRelationshipFilter.IsFullMatch = mappedRelationshipFilter.IsFullMatch;
|
||||
|
||||
if (origRelationshipFilter.IsInverse != mappedRelationshipFilter.IsInverse)
|
||||
origRelationshipFilter.IsInverse = mappedRelationshipFilter.IsInverse;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}*/
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
private static JobRelationshipFilter CreateRelationshipFilter(Guid fieldId, bool isParent, bool isFullMatch, bool isInverse, string valueMask)
|
||||
|
||||
@@ -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;
|
||||
@@ -24,6 +25,7 @@ using PARR.Domain.Entities.Base.History;
|
||||
using PARR.Domain.Entities.JobGroupEntities;
|
||||
using PARR.Domain.Entities.Schedule;
|
||||
using PARR.Domain.Enums;
|
||||
using PARR.Domain.Exceptions;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
@@ -61,9 +63,9 @@ namespace PARR.API.Controllers.V1
|
||||
MqSettings mqSettings
|
||||
)
|
||||
{
|
||||
this._logger = logger;
|
||||
this._mapper = mapper;
|
||||
this._uriService = uriService;
|
||||
_logger = logger;
|
||||
_mapper = mapper;
|
||||
_uriService = uriService;
|
||||
_groupRepository = groupRepository;
|
||||
_jobRepository = jobRepository;
|
||||
_esppConfigRepository = esppConfigRepository;
|
||||
@@ -71,8 +73,8 @@ namespace PARR.API.Controllers.V1
|
||||
_matchingStatusRepository = matchingStatusRepository;
|
||||
_scheduleResponseAreaTimeOffsetRepository = scheduleResponseAreaTimeOffsetRepository;
|
||||
_jobAutoControlRepository = jobAutoControlRepository;
|
||||
this._mqService = mqService;
|
||||
this._mqSettings = mqSettings;
|
||||
_mqService = mqService;
|
||||
_mqSettings = mqSettings;
|
||||
}
|
||||
|
||||
|
||||
@@ -138,6 +140,12 @@ namespace PARR.API.Controllers.V1
|
||||
.Include(t => t.ScheduleExcludeTypeCalendar)
|
||||
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
|
||||
.Include(t => t.AutoControl)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
|
||||
if (jobGroup == null)
|
||||
@@ -175,7 +183,9 @@ namespace PARR.API.Controllers.V1
|
||||
ScheduleExcludeTypeCalendarId = request.ScheduleExcludeTypeCalendarId,
|
||||
IsAutoDistributionEnabled = request.IsAutoDistributionEnabled,
|
||||
IsResponseAreaTimezone = request.IsWorkGroupTimezone,
|
||||
IsGroupByResponsible = request.IsGroupByResponsible
|
||||
IsGroupByResponsible = request.IsGroupByResponsible,
|
||||
UnitFilters = new List<JobGroupUnitFilter>(),
|
||||
EkMask = request.EkMask,
|
||||
//IsAgent = request.IsAgent,
|
||||
//AgentName = request.AgentName,
|
||||
//AgentTimeOutSec = request.AgentTimeOutSec,
|
||||
@@ -212,6 +222,12 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
#endregion
|
||||
|
||||
#region Фильтры
|
||||
|
||||
jobGroup.UnitFilters = MapUnitFilters(request.UnitFilters, jobGroup.Id);
|
||||
|
||||
#endregion
|
||||
|
||||
//Добавляем настройки планировщика
|
||||
request.Schedule.ForEach(item =>
|
||||
{
|
||||
@@ -236,6 +252,12 @@ namespace PARR.API.Controllers.V1
|
||||
.Include(t => t.ScheduleExcludeTypeCalendar)
|
||||
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
|
||||
.Include(t => t.AutoControl)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.FirstAsync(t => t.Id == jobGroup.Id);
|
||||
|
||||
var locationUri = _uriService.GetUri(ApiRoutes.JobGroup.Get, ApiRoutes.JobGroup.getParam, createdJobGroup.Id);
|
||||
@@ -256,23 +278,35 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpPut(ApiRoutes.JobGroup.Update)]
|
||||
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] JobGroupRequest request)
|
||||
{
|
||||
// Специально не будем догружать инфу о фильтрах, чтоб не было слишком тяжелого запроса списка
|
||||
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)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
|
||||
if (orig == null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении группы заданий на выполнение работ. Не найдена группа с Id: {id}" } }));
|
||||
|
||||
// Тип группы работ изменять нельзя
|
||||
if (orig.GroupTypeId != request.GroupTypeId)
|
||||
throw new AppValidationException("Запрещено изменение поля 'Тип работ'");
|
||||
|
||||
|
||||
//Расписание было изменено, ниже добавим задание в очередь на обновление расписаний у связанных шаблонов
|
||||
var isScheduleChanged = IsScheduleChanged(orig, request);
|
||||
|
||||
orig.GroupName = request.Name.Trim();
|
||||
//orig.IsUmbrella = request.IsUmbrella;
|
||||
orig.GroupTypeId = request.GroupTypeId;
|
||||
// Тип группы работ изменять нельзя
|
||||
//orig.GroupTypeId = request.GroupTypeId;
|
||||
orig.GroupingUnitFieldId = await GetGroupingUnitFieldIdAsync(request);
|
||||
orig.ShortDescription = request.ShortDescription.Trim();
|
||||
orig.FullDescription = request.FullDescription.Trim();
|
||||
@@ -286,6 +320,7 @@ namespace PARR.API.Controllers.V1
|
||||
orig.IsResponseAreaTimezone = request.IsWorkGroupTimezone;
|
||||
// IsGroupByResponsible - может быть значение, только если тип ГРУППОВОЙ
|
||||
orig.IsGroupByResponsible = await GetIsGroupByResponsibleValue(request);
|
||||
orig.EkMask = request.EkMask;
|
||||
//orig.IsAgent = request.IsAgent;
|
||||
//orig.AgentName = request.AgentName;
|
||||
//orig.AgentTimeOutSec = request.AgentTimeOutSec;
|
||||
@@ -363,7 +398,19 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
#endregion
|
||||
|
||||
//обновляем планировщик
|
||||
#region Фильтры
|
||||
|
||||
orig.UnitFilters.Clear();
|
||||
|
||||
var newFilters = MapUnitFilters(request.UnitFilters, orig.Id);
|
||||
foreach (var filter in newFilters)
|
||||
{
|
||||
orig.UnitFilters.Add(filter);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region обновляем планировщик
|
||||
orig.EsppSchValues.Clear();
|
||||
request.Schedule.ForEach(item =>
|
||||
{
|
||||
@@ -374,6 +421,7 @@ namespace PARR.API.Controllers.V1
|
||||
TypeValueId = item.TypeValueId
|
||||
});
|
||||
});
|
||||
#endregion
|
||||
|
||||
if (!await _groupRepository.CommitAsync())
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении группы заданий на выполнение работ." } }));
|
||||
@@ -412,6 +460,12 @@ namespace PARR.API.Controllers.V1
|
||||
.Include(t => t.ScheduleExcludeTypeCalendar)
|
||||
.Include(t => t.DistributionConfig).ThenInclude(t => t.DistributionPeriod)
|
||||
.Include(t => t.AutoControl)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.FieldFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.Include(t => t.UnitFilters)
|
||||
.ThenInclude(t => t.RelationshipFilters)
|
||||
.ThenInclude(t => t.UnitField)
|
||||
.FirstAsync(t => t.Id == orig.Id);
|
||||
|
||||
var response = _mapper.Map<JobGroupResponse>(updatedJobGroup);
|
||||
@@ -457,6 +511,66 @@ namespace PARR.API.Controllers.V1
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Обновление юнит фильтров
|
||||
/// </summary>
|
||||
/// <param name="requestFilters"></param>
|
||||
/// <param name="jobGroupId"></param>
|
||||
/// <returns></returns>
|
||||
private List<JobGroupUnitFilter> MapUnitFilters(List<UnitFilterRequest> requestFilters, Guid jobGroupId)
|
||||
{
|
||||
return requestFilters.Select(requestFilter =>
|
||||
{
|
||||
var unitFilter = new JobGroupUnitFilter
|
||||
{
|
||||
DateCreated = DateTimeOffset.UtcNow,
|
||||
JobGroupId = jobGroupId,
|
||||
UnitFilter = requestFilter.UnitFilterMask
|
||||
};
|
||||
|
||||
// Добавляем FieldFilters
|
||||
if (requestFilter.FieldFilters != null)
|
||||
{
|
||||
foreach (var fieldFilterRequest in requestFilter.FieldFilters)
|
||||
{
|
||||
var fieldFilter = new JobGroupFieldFilter
|
||||
{
|
||||
DateCreated = DateTimeOffset.UtcNow,
|
||||
FieldId = fieldFilterRequest.FieldId,
|
||||
ValueMask = fieldFilterRequest.ValueMask ?? string.Empty,
|
||||
IsInverse = fieldFilterRequest.IsInverse,
|
||||
UnitFilter = unitFilter
|
||||
};
|
||||
unitFilter.FieldFilters.Add(fieldFilter);
|
||||
}
|
||||
}
|
||||
|
||||
// Добавляем RelationshipFilters
|
||||
if (requestFilter.RelationshipFilters != null)
|
||||
{
|
||||
foreach (var relFilterRequest in requestFilter.RelationshipFilters)
|
||||
{
|
||||
var relFilter = new JobGroupRelationshipFilter
|
||||
{
|
||||
FieldId = relFilterRequest.FieldId,
|
||||
IsParent = relFilterRequest.IsParent ?? false,
|
||||
ValueMask = relFilterRequest.ValueMask ?? string.Empty,
|
||||
IsFullMatch = relFilterRequest.IsFullMatch ?? false,
|
||||
IsInverse = relFilterRequest.IsInverse ?? false,
|
||||
UnitFilter = unitFilter
|
||||
};
|
||||
unitFilter.RelationshipFilters.Add(relFilter);
|
||||
}
|
||||
}
|
||||
|
||||
return unitFilter;
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Удалить настройки автоконтроля для связанных Job
|
||||
/// </summary>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
{
|
||||
@@ -65,6 +65,8 @@ namespace PARR.API.Controllers.V1
|
||||
|
||||
var jobGroup = await jobGroupService.Get().AsNoTracking()
|
||||
.Include(t => t.GroupType)
|
||||
.Include(g => g!.UnitFilters).ThenInclude(uf => uf.FieldFilters).ThenInclude(ff => ff.UnitField)
|
||||
.Include(g => g!.UnitFilters).ThenInclude(uf => uf.RelationshipFilters).ThenInclude(rf => rf.UnitField)
|
||||
.FirstAsync(t => t.Id == job.GroupId);
|
||||
job.Group = jobGroup;
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ using PARR.API.Services.Interfaces;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Domain.Common.Pagination;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
@@ -62,6 +62,7 @@ namespace PARR.API.Controllers.V1
|
||||
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
|
||||
|
||||
IQueryable<RobotHistory> query = robotHistoryService.Get()
|
||||
.AsNoTracking()
|
||||
.Include(t => t.RobotConfiguration)
|
||||
.ThenInclude(t => t!.Template)
|
||||
.Include(t => t.RobotConfiguration)
|
||||
@@ -79,19 +80,38 @@ namespace PARR.API.Controllers.V1
|
||||
if (request.HistoryLevel.HasValue)
|
||||
query = query.Where(t => t.HistoryLevel == (int)request.HistoryLevel);
|
||||
|
||||
if (request.DateFrom.HasValue)
|
||||
{
|
||||
var startDateUtc = request.DateFrom.Value.ToUniversalTime();
|
||||
query = query.Where(t => t.DateCreated >= startDateUtc);
|
||||
}
|
||||
|
||||
if (request.DateTo.HasValue)
|
||||
{
|
||||
var endDateUtc = request.DateTo.Value.ToUniversalTime();
|
||||
query = query.Where(t => t.DateCreated < endDateUtc);
|
||||
}
|
||||
|
||||
var history = await robotHistoryService.GetPage(query, paginationFilter).ToListAsync();
|
||||
|
||||
if (!history.Any())
|
||||
if (history.Count == 0)
|
||||
return NoContent();
|
||||
|
||||
var robotsIp = history.Where(t => !string.IsNullOrEmpty(t.RobotIp)).Select(t => t.RobotIp).Distinct().ToList();
|
||||
var users = await userService.Get().Where(t => robotsIp.Any(x => x == t.Ip)).Distinct().ToListAsync();
|
||||
var usersDictionary = await userService.Get()
|
||||
.AsNoTracking()
|
||||
.Where(t => robotsIp.Contains(t.Ip))
|
||||
.ToDictionaryAsync(t => t.Ip, t => t);
|
||||
|
||||
var response = mapper.Map<List<RobotHistoryResponse>>(history);
|
||||
response.ForEach(item =>
|
||||
foreach (var item in response)
|
||||
{
|
||||
item.User = mapper.Map<UserBaseResponse>(users.FirstOrDefault(t => t.Ip == item.RobotIp));
|
||||
});
|
||||
if (!string.IsNullOrWhiteSpace(item.RobotIp) && usersDictionary.TryGetValue(item.RobotIp, out var user))
|
||||
{
|
||||
item.User = mapper.Map<UserBaseResponse>(user);
|
||||
}
|
||||
}
|
||||
|
||||
var paginationResponse = new PagedResponse<RobotHistoryResponse>(response, true).GetPaginatedProps(paginationFilter, query);
|
||||
|
||||
return Ok(paginationResponse);
|
||||
|
||||
@@ -7,6 +7,7 @@ using PARR.API.Contracts.V1.Responses;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Services.Interfaces;
|
||||
using PARR.API.Settings;
|
||||
using PARR.Core.Services.RobotTask.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Entities.Base.History;
|
||||
@@ -18,38 +19,22 @@ namespace PARR.API.Controllers.V1
|
||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||
public class RobotTaskController : BaseApiController
|
||||
{
|
||||
private readonly IRobotTaskService robotTaskService;
|
||||
|
||||
private readonly IMapper mapper;
|
||||
//private readonly SettingsFromDb settingsFromDb;
|
||||
//private readonly IRobotConfigurationRepository robotConfigurationService;
|
||||
//private readonly ILogger<RobotTaskController> logger;
|
||||
private readonly IClientService clientService;
|
||||
//private readonly IRobotHistoryRepository robotHistoryService;
|
||||
//private readonly IShortcodesService shortcodesService;
|
||||
//private readonly INextRunService nextRunService;
|
||||
private readonly IRobotTaskService _robotTaskService;
|
||||
private readonly CommonSettings _commonSettings;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IClientService _clientService;
|
||||
|
||||
public RobotTaskController(
|
||||
IMapper mapper,
|
||||
//SettingsFromDb settingsFromDb,
|
||||
//IRobotConfigurationRepository robotConfigurationService,
|
||||
//ILogger<RobotTaskController> logger,
|
||||
IClientService clientService,
|
||||
//IRobotHistoryRepository robotHistoryService,
|
||||
//IShortcodesService shortcodesService,
|
||||
//INextRunService nextRunService
|
||||
IRobotTaskService robotTaskService
|
||||
IRobotTaskService robotTaskService,
|
||||
CommonSettings commonSettings
|
||||
)
|
||||
{
|
||||
this.robotTaskService = robotTaskService;
|
||||
this.mapper = mapper;
|
||||
//this.settingsFromDb = settingsFromDb;
|
||||
//this.robotConfigurationService = robotConfigurationService;
|
||||
//this.logger = logger;
|
||||
this.clientService = clientService;
|
||||
//this.robotHistoryService = robotHistoryService;
|
||||
//this.shortcodesService = shortcodesService;
|
||||
//this.nextRunService = nextRunService;
|
||||
_robotTaskService = robotTaskService;
|
||||
_commonSettings = commonSettings;
|
||||
_mapper = mapper;
|
||||
_clientService = clientService;
|
||||
}
|
||||
|
||||
|
||||
@@ -66,314 +51,37 @@ namespace PARR.API.Controllers.V1
|
||||
switch (robotCode)
|
||||
{
|
||||
case RobotsEnum.TemplateOrder:
|
||||
var templateTask = await robotTaskService.GetTemplateTaskAsync(
|
||||
var templateTask = await _robotTaskService.GetTemplateTaskAsync(
|
||||
taskStatusCode,
|
||||
requestQuery.SetInProgressStatus ?? false,
|
||||
clientService.GetClientIp()?.ToString(),
|
||||
_clientService.GetClientIp()?.ToString(),
|
||||
requestQuery.RobotId
|
||||
);
|
||||
var templateResponse = mapper.Map<RobotTaskTemplateResponse>(templateTask);
|
||||
var templateResponse = _mapper.Map<RobotTaskTemplateResponse>(templateTask);
|
||||
|
||||
return Ok(new Response<RobotTaskTemplateResponse>(templateResponse, true));
|
||||
case RobotsEnum.ScheduleOrder:
|
||||
var historyIniciator = new HistoryInitiator
|
||||
{
|
||||
InitiatorComment="Задание роботу, расписание.",
|
||||
InitiatorIp=clientService.GetClientIp()?.ToString(),
|
||||
InitiatorParrComponentId= ParrComponentsEnum.Api
|
||||
InitiatorComment = "Задание роботу, расписание.",
|
||||
InitiatorIp = _clientService.GetClientIp()?.ToString(),
|
||||
InitiatorParrComponentId = ParrComponentsEnum.Api
|
||||
};
|
||||
var scheduleTask = await robotTaskService.GetScheduleTaskAsync(
|
||||
var scheduleTask = await _robotTaskService.GetScheduleTaskAsync(
|
||||
taskStatusCode,
|
||||
requestQuery.SetInProgressStatus ?? false,
|
||||
historyIniciator.InitiatorIp,
|
||||
requestQuery.RobotId,
|
||||
historyIniciator
|
||||
historyIniciator,
|
||||
_commonSettings.ScheduleCooldownDuration
|
||||
);
|
||||
|
||||
var scheduleResponse = mapper.Map<RobotTaskScheduleResponse>(scheduleTask);
|
||||
var scheduleResponse = _mapper.Map<RobotTaskScheduleResponse>(scheduleTask);
|
||||
|
||||
return Ok(new Response<RobotTaskScheduleResponse>(scheduleResponse, true));
|
||||
default:
|
||||
throw new AppValidationException("Некорректное значение robotCode");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region Old
|
||||
|
||||
// /// <summary>
|
||||
// /// Получить задание для робота по коду робота и по статусу задания
|
||||
// /// </summary>
|
||||
// /// <param name="robotCode"></param>
|
||||
// /// <param name="taskStatusCode"></param>
|
||||
// /// <returns></returns>
|
||||
// [HttpGet(ApiRoutes.RobotTask.GetByRobotAndStatusTask)]
|
||||
// public async Task<IActionResult> GetByRobotAndStatusTask([FromRoute] RobotsEnum robotCode, [FromRoute] TaskStatusEnum taskStatusCode, [FromQuery] RobotTaskQuery requestQuery)
|
||||
// {
|
||||
// //Ищем все задания с превышенным кол-вом попыток и с просроченным временем и ставим им статус ошибки
|
||||
// await robotConfigurationService.MarkExpiredTasksAsFailedAsync(settingsFromDb.RobotAttemptsNumber, settingsFromDb.RobotWaitTime);
|
||||
|
||||
|
||||
// var query = robotConfigurationService.Get()
|
||||
// .AsSingleQuery()
|
||||
// .Where(t => t.RobotCode == (int)robotCode && t.TaskStatusCode == (int)taskStatusCode);
|
||||
|
||||
// switch (robotCode)
|
||||
// {
|
||||
// case RobotsEnum.TemplateOrder:
|
||||
// // шаблоны
|
||||
// query = query
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Field)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Value)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(a => a!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(g => g.GroupType)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(w => w!.Job)
|
||||
// .ThenInclude(t => t!.Tnk)
|
||||
// .ThenInclude(s => s!.Subprocess)
|
||||
// .ThenInclude(p => p!.Process);
|
||||
|
||||
// query = query
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.UnitsInTemplate);
|
||||
|
||||
// break;
|
||||
|
||||
// case RobotsEnum.ScheduleOrder:
|
||||
// //расписание
|
||||
// query = query
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Field)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Value)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(a => a!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(g => g.GroupType)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(a => a!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(t => t!.EsppSchValues)
|
||||
// .ThenInclude(t => t!.EsppSchTypeConfig)
|
||||
// .ThenInclude(t => t!.EsppSchTypeSchedule)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(t => t!.ScheduleExcludeType)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(t => t.ScheduleExcludeTypeCalendar)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Job)
|
||||
// .ThenInclude(t => t!.Tnk)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.UnitsInTemplate);
|
||||
|
||||
// //выбираем только записи с созданными шаблонами (у которых статус 20 или 30), а только потом у них ищем расписания
|
||||
// var createdTemplates = robotConfigurationService.Get()
|
||||
// .Where(t => t.RobotCode == (int)RobotsEnum.TemplateOrder && (t.TaskStatusCode == (int)TaskStatusEnum.Ok))
|
||||
// .Select(t => t.TemplateId);
|
||||
// query = query.Where(t => t.RobotCode == (int)RobotsEnum.ScheduleOrder && createdTemplates.Contains(t.TemplateId));
|
||||
// // query = query.Where(t => t.RobotCode == (int)RobotsEnum.ScheduleOrder && t.TemplateId==Guid.Parse("7cb7c3be-506d-40e0-a63f-4554edb52459"));
|
||||
// break;
|
||||
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
|
||||
|
||||
// // сортируем по NextRun, чтобы те у которых дата след срабатывания ближе к текущей, выполнились скорее
|
||||
// query = query.OrderBy(t => t.Template!.NextRun).ThenBy(t => t.Template!.IsActiveSchedule).ThenBy(t => t.Template.IsActiveTemplate);
|
||||
|
||||
// RobotConfiguration? task = null;
|
||||
|
||||
// //ищем задание в ожидании, если нашли, выбираем его
|
||||
// task = await query.FirstOrDefaultAsync(t => t.RobotStatusCode == (int)RobotStatusEnum.Wait);
|
||||
|
||||
// if (task == null)
|
||||
// {
|
||||
// //ищем задания в работе, которые можно перезапустить
|
||||
// //Поиск по `RobotStatusCode` = 22.
|
||||
// //Далее проверяется `LastStatusUpdated`, что время последнего смены статуса не превышает допустимого(берется из настроек, поле `RobotWaitTime`)
|
||||
// //и что текущая попытка не больше разрешенной(берется из настроек, поле `RobotAttemptsNumber`) - если это так, берется эта запись.
|
||||
|
||||
// var endDate = DateTimeOffset.UtcNow.Add(-settingsFromDb.RobotWaitTime);
|
||||
// task = await query
|
||||
// .FirstOrDefaultAsync(t =>
|
||||
// t.RobotStatusCode == (int)RobotStatusEnum.InProgress
|
||||
// && t.AttemptsNumber < settingsFromDb.RobotAttemptsNumber
|
||||
// && t.LastRobotStatusUpdated < endDate
|
||||
// );
|
||||
// }
|
||||
|
||||
// if (task == null)
|
||||
// return NotFound();
|
||||
|
||||
// if (requestQuery?.SetInProgressStatus == true)
|
||||
// {
|
||||
// var resultSetStatus = await SetInProgressStatusAsync(task.Id);
|
||||
// if (resultSetStatus == false)
|
||||
// {
|
||||
// logger.LogError($"Ошибка при установке статуса {RobotStatusEnum.InProgress.ToString()} для задания RobotConfigutationId {task.Id} (при выдаче задания роботу)");
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при выдаче задания." } }));
|
||||
// }
|
||||
// }
|
||||
|
||||
// switch (robotCode)
|
||||
// {
|
||||
// case RobotsEnum.TemplateOrder:
|
||||
// { //RobotTaskTemplateResponse
|
||||
// var robotTaskTemplateResponse = mapper.Map<RobotTaskTemplateResponse>(task);
|
||||
|
||||
// robotTaskTemplateResponse.FullDescription = NormalizeLineEndingsToCrlf(await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.FullDescription, task.Template!));
|
||||
// robotTaskTemplateResponse.ShortDescription = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.ShortDescription, task.Template!);
|
||||
// robotTaskTemplateResponse.Solution = NormalizeLineEndingsToCrlf(await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.Solution, task.Template!));
|
||||
// robotTaskTemplateResponse.TnkName = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.TnkName, task.Template!);
|
||||
// robotTaskTemplateResponse.WorkName = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.WorkName, task.Template!);
|
||||
// robotTaskTemplateResponse.WorkGroup = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.WorkGroup, task.Template!);
|
||||
// robotTaskTemplateResponse.ResponseArea = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.ResponseArea, task.Template!);
|
||||
|
||||
// return Ok(new Response<RobotTaskTemplateResponse>(robotTaskTemplateResponse, true));
|
||||
// }
|
||||
// case RobotsEnum.ScheduleOrder:
|
||||
// { // если был запрос на расписание, проверяем у него nextRun, lastRun, обновляем их
|
||||
// var resultUpdateNextRun = await UpdateNextRunAsync(task);
|
||||
// if (!resultUpdateNextRun)
|
||||
// {
|
||||
// logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}", task.TemplateId);
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при расчете NextRun" } }));
|
||||
// }
|
||||
|
||||
// //RobotTaskScheduleResponse
|
||||
// var robotTaskScheduleResponse = mapper.Map<RobotTaskScheduleResponse>(task);
|
||||
|
||||
// robotTaskScheduleResponse.Timezone = settingsFromDb.EsppScheduleTimezone;
|
||||
|
||||
// robotTaskScheduleResponse.WorkGroup = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.WorkGroup, task.Template!);
|
||||
// robotTaskScheduleResponse.ResponseArea = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.ResponseArea, task.Template!);
|
||||
|
||||
// //var nextRunWithRobotTz = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(task.Template!.NextRun, task.Template!.Job?.Group?.IsResponseAreaTimezone, robotTaskScheduleResponse.ResponseArea);
|
||||
// //nextRun в часовой зоне УЗ Робота ЕСПП
|
||||
// var nextRunWithRobotTz = task.Template!.NextRun.Add(nextRunService.GetEsppAccountOffset());
|
||||
|
||||
// //на всякий случай еще раз проверяем, что дата не устарела и отправляем задание
|
||||
// if (nextRunWithRobotTz < DateTimeOffset.UtcNow)
|
||||
// {
|
||||
// logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}, итоговое значение для робота, меньше чем сейчас {nextRunWithRobotTz}<{now}",
|
||||
// task.TemplateId, nextRunWithRobotTz, DateTimeOffset.UtcNow);
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при расчете NextRun" } }));
|
||||
// }
|
||||
|
||||
// robotTaskScheduleResponse.NextStart = EsppScheduleHelpers.GetNextRun(nextRunWithRobotTz);
|
||||
// robotTaskScheduleResponse.GenerationTime = EsppScheduleHelpers.GetGenerationTime(nextRunWithRobotTz);
|
||||
|
||||
// return Ok(new Response<RobotTaskScheduleResponse>(robotTaskScheduleResponse, true));
|
||||
// }
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
|
||||
// return BadRequest();
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// Обоновить NextRun если он устарел
|
||||
// /// </summary>
|
||||
// /// <param name="task"></param>
|
||||
// /// <returns></returns>
|
||||
// private async Task<bool> UpdateNextRunAsync(RobotConfiguration task)
|
||||
// {
|
||||
// var template = task.Template!;
|
||||
|
||||
// //var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
||||
// var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
// if (!nextRun.HasValue)
|
||||
// {
|
||||
// logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun=null, ошибка в расчетах.", template.Id);
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (nextRun.Value < DateTimeOffset.UtcNow)
|
||||
// {
|
||||
// logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun<Now [{nextRun}<{now}], ошибка в расчетах.", template.Id, nextRun.Value, DateTimeOffset.UtcNow);
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (nextRun != template.NextRun)
|
||||
// {
|
||||
// logger.LogDebug($"Для шаблона id {template.Id} обновляю nextRun, новое значение {nextRun}, старое значение {template.NextRun}");
|
||||
|
||||
// template.LastRun = template.NextRun;
|
||||
// template.NextRun = nextRun.Value;
|
||||
|
||||
// await robotConfigurationService.CommitAsync(new HistoryInitiator { InitiatorComment = "При получении задания роботом, обновил NextRun", InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api });
|
||||
// }
|
||||
|
||||
// return true;
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// Устанавливаем статус "Робот взял в работу", пишем в историю работы роботов инф о начале работ
|
||||
// /// </summary>
|
||||
// /// <param name="taskId"></param>
|
||||
// /// <returns></returns>
|
||||
// private async Task<bool> SetInProgressStatusAsync(Guid taskId)
|
||||
// {
|
||||
// var config = await robotConfigurationService.GetAsync(taskId);
|
||||
|
||||
// //изменение статуса робота
|
||||
// robotConfigurationService.ChangeRobotStatus(RobotStatusEnum.InProgress, config!);
|
||||
|
||||
// if (!await robotConfigurationService.CommitAsync())
|
||||
// return false;
|
||||
|
||||
// //записываем в лог робота
|
||||
// var history = new RobotHistory
|
||||
// {
|
||||
// Id = Guid.NewGuid(),
|
||||
// HistoryLevel = (int)RobotHistoryLevelEnum.Start,
|
||||
// TaskStatusCode = config.TaskStatusCode,
|
||||
// RobotConfigurationId = config.Id,
|
||||
// RobotIp = clientService.GetClientIp()?.ToString()
|
||||
// };
|
||||
|
||||
// if (!await robotHistoryService.CreateAsync(history) || !await robotHistoryService.CommitAsync())
|
||||
// return false;
|
||||
|
||||
// return true;
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// Приводит переносы строк в тексте к формату CRLF (\r\n)
|
||||
// /// </summary>
|
||||
// /// <param name="text">Исходный текст</param>
|
||||
// /// <returns>Текст с унифицированными переносами строк</returns>
|
||||
// private string NormalizeLineEndingsToCrlf(string? text)
|
||||
// {
|
||||
// if (string.IsNullOrEmpty(text))
|
||||
// return string.Empty;
|
||||
|
||||
// // Заменяем любые варианты переносов (\r\n, \r, \n) на единый \r\n
|
||||
// return System.Text.RegularExpressions.Regex.Replace(text, @"\r\n|\r|\n", "\r\n");
|
||||
// }
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,34 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PARR.API.Contracts.V1;
|
||||
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.API.Services.Interfaces;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Core.Services.RobotTaskRobotStatus.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Enums;
|
||||
using PARR.Domain.DTOs.RobotTaskRobotStatus;
|
||||
|
||||
namespace PARR.API.Controllers.V1
|
||||
{
|
||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||
public class RobotTaskRobotStatusController : BaseApiController
|
||||
{
|
||||
private readonly IRobotConfigurationRepository robotConfigurationService;
|
||||
private readonly IRobotHistoryRepository robotHistoryService;
|
||||
private readonly IMapper mapper;
|
||||
private readonly IClientService clientService;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IClientService _clientService;
|
||||
private readonly IRobotTaskRobotStatusService _robotTaskRobotStatusService;
|
||||
|
||||
public RobotTaskRobotStatusController(
|
||||
IRobotConfigurationRepository robotConfigurationService,
|
||||
IRobotHistoryRepository robotHistoryService,
|
||||
IMapper mapper,
|
||||
IClientService clientService
|
||||
IClientService clientService,
|
||||
IRobotTaskRobotStatusService robotTaskRobotStatusService
|
||||
)
|
||||
{
|
||||
this.robotConfigurationService = robotConfigurationService;
|
||||
this.robotHistoryService = robotHistoryService;
|
||||
this.mapper = mapper;
|
||||
this.clientService = clientService;
|
||||
_mapper = mapper;
|
||||
_clientService = clientService;
|
||||
_robotTaskRobotStatusService = robotTaskRobotStatusService;
|
||||
}
|
||||
|
||||
|
||||
@@ -45,47 +40,58 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpPut(ApiRoutes.RobotTaskRobotStatus.ChangeRobotStatus)]
|
||||
public async Task<IActionResult> ChangeStatus([FromRoute] Guid taskId, [FromBody] RobotTaskChangeRobotStatusRequest request)
|
||||
{
|
||||
var config = await robotConfigurationService.Get()
|
||||
.FirstOrDefaultAsync(t => t.Id == taskId);
|
||||
#region Old
|
||||
|
||||
if (config == null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найдено задание с id: {taskId}" } }));
|
||||
//var config = await _robotConfigurationRepository.Get()
|
||||
// .FirstOrDefaultAsync(t => t.Id == taskId);
|
||||
|
||||
//изменение статуса робота
|
||||
robotConfigurationService.ChangeRobotStatus(request.RobotStatusCode, config);
|
||||
//if (config == null)
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найдено задание с id: {taskId}" } }));
|
||||
|
||||
//если успех, изменяем статус задания на успех
|
||||
if (request.RobotStatusCode == RobotStatusEnum.Complete)
|
||||
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Ok, config);
|
||||
////изменение статуса робота
|
||||
//_robotConfigurationRepository.ChangeRobotStatus(request.RobotStatusCode, config);
|
||||
|
||||
if (!await robotConfigurationService.CommitAsync())
|
||||
return BadRequest("Ошибка при изменении статуса работы робота.");
|
||||
////если успех, изменяем статус задания на успех
|
||||
//if (request.RobotStatusCode == RobotStatusEnum.Complete)
|
||||
// _robotConfigurationRepository.ChangeTaskStatus(TaskStatusEnum.Ok, config);
|
||||
|
||||
//записываем в лог робота
|
||||
if (request.RobotStatusCode == RobotStatusEnum.InProgress || request.RobotStatusCode == RobotStatusEnum.Complete)
|
||||
{
|
||||
var historyLevel = request.RobotStatusCode == RobotStatusEnum.InProgress ? RobotHistoryLevelEnum.Start : RobotHistoryLevelEnum.Complete;
|
||||
//if (!await _robotConfigurationRepository.CommitAsync())
|
||||
// return BadRequest("Ошибка при изменении статуса работы робота.");
|
||||
|
||||
var history = new RobotHistory
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
HistoryLevel = (int)historyLevel,
|
||||
TaskStatusCode = config.TaskStatusCode,
|
||||
RobotConfigurationId = config.Id,
|
||||
RobotIp = clientService.GetClientIp()?.ToString(),
|
||||
RobotId = request.RobotId
|
||||
};
|
||||
await robotHistoryService.CreateAsync(history);
|
||||
await robotHistoryService.CommitAsync();
|
||||
}
|
||||
////записываем в лог робота
|
||||
//if (request.RobotStatusCode == RobotStatusEnum.InProgress || request.RobotStatusCode == RobotStatusEnum.Complete)
|
||||
//{
|
||||
// var historyLevel = request.RobotStatusCode == RobotStatusEnum.InProgress ? RobotHistoryLevelEnum.Start : RobotHistoryLevelEnum.Complete;
|
||||
|
||||
var configToResponse = await robotConfigurationService.Get()
|
||||
.Include(t => t.Robot)
|
||||
.Include(t => t.TaskStatus)
|
||||
.Include(t => t.RobotStatus)
|
||||
.FirstOrDefaultAsync(t => t.Id == taskId);
|
||||
// var history = new RobotHistory
|
||||
// {
|
||||
// Id = Guid.NewGuid(),
|
||||
// HistoryLevel = (int)historyLevel,
|
||||
// TaskStatusCode = config.TaskStatusCode,
|
||||
// RobotConfigurationId = config.Id,
|
||||
// RobotIp = _clientService.GetClientIp()?.ToString(),
|
||||
// RobotId = request.RobotId
|
||||
// };
|
||||
// await _robotHistoryRepository.CreateAsync(history);
|
||||
// await _robotHistoryRepository.CommitAsync();
|
||||
//}
|
||||
|
||||
var response = mapper.Map<RobotConfigurationResponse>(configToResponse);
|
||||
//var configToResponse = await _robotConfigurationRepository.Get()
|
||||
// .Include(t => t.Robot)
|
||||
// .Include(t => t.TaskStatus)
|
||||
// .Include(t => t.RobotStatus)
|
||||
// .FirstOrDefaultAsync(t => t.Id == taskId);
|
||||
|
||||
//var response = _mapper.Map<RobotConfigurationResponse>(configToResponse);
|
||||
|
||||
//return Ok(new Response<RobotConfigurationResponse>(response, true));
|
||||
|
||||
#endregion
|
||||
|
||||
var changeRequest = new ChangeRobotStatus(taskId, request.RobotStatusCode, request.RobotId, _clientService.GetClientIp()?.ToString());
|
||||
var result = await _robotTaskRobotStatusService.ChangeStatusAsync(changeRequest);
|
||||
|
||||
var response = _mapper.Map<RobotConfigurationResponse>(result);
|
||||
|
||||
return Ok(new Response<RobotConfigurationResponse>(response, true));
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Helpers;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PARR.API.Contracts.V1;
|
||||
using PARR.API.Contracts.V1.Requests.Queries;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Contracts.V1.Responses.Statistics;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.Core.Services.RobotMetrics;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.DTOs.RobotMetrics;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
/// <summary>
|
||||
/// Метрики заданий роботам
|
||||
/// </summary>
|
||||
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
||||
public class StatRobotMetricsController : BaseApiController
|
||||
{
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IRobotMetricsService _robotMetricsService;
|
||||
|
||||
public StatRobotMetricsController(
|
||||
IMapper mapper,
|
||||
IRobotMetricsService robotMetricsService
|
||||
)
|
||||
{
|
||||
_mapper = mapper;
|
||||
_robotMetricsService = robotMetricsService;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Статистика по Заданиям Роботу, график
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.StatRobotMetrics.GetRobotStatusMetrics)]
|
||||
public async Task<IActionResult> GetRobotStatusMetrics([FromRoute] RobotsEnum robotCode, [FromRoute] ChartPeriod period, CancellationToken cancellationToken)
|
||||
{
|
||||
var data = await _robotMetricsService.GetRobotStatusMetricsAsync(robotCode, period, cancellationToken);
|
||||
|
||||
var response = _mapper.Map<List<StatRobotStatusChartPoint>>(data);
|
||||
|
||||
return Ok(new Response<List<StatRobotStatusChartPoint>>(response, true));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Статистика по Статусам Заданий, график
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.StatRobotMetrics.GetTaskStatusMetrics)]
|
||||
public async Task<IActionResult> GetTaskStatusMetrics([FromRoute] RobotsEnum robotCode, [FromRoute] ChartPeriod period, CancellationToken cancellationToken)
|
||||
{
|
||||
var data = await _robotMetricsService.GetTaskStatusMetricsAsync(robotCode, period, cancellationToken);
|
||||
|
||||
var response = _mapper.Map<List<StatTaskStatusChartPoint>>(data);
|
||||
|
||||
return Ok(new Response<List<StatTaskStatusChartPoint>>(response, true));
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Статистика по статусам заданий, гибкий фильтр
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.StatRobotMetrics.GetFilteredMetrics)]
|
||||
public async Task<IActionResult> GetFilteredMetrics([FromQuery] RobotFilteredMetricsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// ------- Правильность расчетов этого метода доконца не проверена -------
|
||||
|
||||
var filter = _mapper.Map<MetricFilter>(request);
|
||||
|
||||
var data = await _robotMetricsService.GetFilteredMetricsAsync(filter, cancellationToken);
|
||||
|
||||
var response = _mapper.Map<List<StatFilteredChartPoint>>(data);
|
||||
|
||||
return Ok(new Response<List<StatFilteredChartPoint>>(response, true));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PARR.API.Contracts.V1;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.Core.Services.RobotStatusDetails.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
/// <summary>
|
||||
/// Детальная статистика по статусам заданий роботам
|
||||
/// </summary>
|
||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||
public class StatRobotStatusDetailsController : BaseApiController
|
||||
{
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IRobotStatusDetailsService _robotStatusDetailsService;
|
||||
|
||||
public StatRobotStatusDetailsController(
|
||||
IMapper mapper,
|
||||
IRobotStatusDetailsService robotStatusDetailsService
|
||||
)
|
||||
{
|
||||
_mapper = mapper;
|
||||
_robotStatusDetailsService = robotStatusDetailsService;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Список групп работ по статусам заданий роботам
|
||||
/// </summary>
|
||||
/// <param name="robot"></param>
|
||||
/// <param name="status"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.StatRobotStatusDetails.Details)]
|
||||
public async Task<IActionResult> Details([FromRoute] RobotsEnum robot, [FromRoute] RobotStatusEnum status)
|
||||
{
|
||||
var details = await _robotStatusDetailsService.GetDetailsAsync(robot, status);
|
||||
var response = _mapper.Map<StatRobotStatusDetailsResponse>(details);
|
||||
|
||||
return Ok(new Response<StatRobotStatusDetailsResponse>(response, true));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using PARR.API.Contracts.V1.Responses;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
public record StatRobotStatusDetailsResponse
|
||||
{
|
||||
public RobotResponse Robot { get; init; } = null!;
|
||||
public RobotStatusResponse Status { get; init; } = null!;
|
||||
|
||||
public List<StatRobotStatusGroupDetailsResponse> Details { get; init; } = null!;
|
||||
}
|
||||
|
||||
public record StatRobotStatusGroupDetailsResponse
|
||||
{
|
||||
public JobGroupShortResponse JobGroup { get; init; } = null!;
|
||||
public int TemplatesCount { get; init; }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PARR.API.Contracts.V1;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Contracts.V1.Responses.Statistics;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.Core.Services.RobotTaskDetailsServices.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
/// <summary>
|
||||
/// Детальная статистика по заданиям роботам
|
||||
/// </summary>
|
||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||
public class StatRobotTaskDetailsController : BaseApiController
|
||||
{
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IRobotTaskDetailsService _robotTaskDetailsService;
|
||||
|
||||
public StatRobotTaskDetailsController(
|
||||
IMapper mapper,
|
||||
IRobotTaskDetailsService robotTaskDetailsService
|
||||
)
|
||||
{
|
||||
_mapper = mapper;
|
||||
_robotTaskDetailsService = robotTaskDetailsService;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Список групп работ по заданиям роботам
|
||||
/// </summary>
|
||||
/// <param name="robot"></param>
|
||||
/// <param name="task"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.StatRobotTaskDetails.Details)]
|
||||
public async Task<IActionResult> Details([FromRoute] RobotsEnum robot, [FromRoute] TaskStatusEnum task)
|
||||
{
|
||||
var details = await _robotTaskDetailsService.GetDetailsAsync(robot, task);
|
||||
var response = _mapper.Map<StatRobotTaskDetailsResponse>(details);
|
||||
|
||||
return Ok(new Response<StatRobotTaskDetailsResponse>(response, true));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PARR.API.Contracts.V1;
|
||||
using PARR.API.Contracts.V1.Requests.BaseRequests;
|
||||
@@ -8,10 +9,12 @@ using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Helpers;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Core.Services.NextRunServices;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||
public class StatTemplateAutoControlController : BaseApiController
|
||||
{
|
||||
private readonly ITemplateRepository templateService;
|
||||
|
||||
@@ -10,6 +10,7 @@ using PARR.API.Helpers;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Core.Services.NextRunServices;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Controllers.V1.Statistics
|
||||
@@ -20,16 +21,16 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
||||
public class StatTemplateController : BaseApiController
|
||||
{
|
||||
private readonly ITemplateRepository templateService;
|
||||
private readonly INextRunService nextRunService;
|
||||
private readonly ITemplateRepository _templateRepository;
|
||||
private readonly INextRunService _nextRunService;
|
||||
|
||||
public StatTemplateController(
|
||||
ITemplateRepository templateService,
|
||||
ITemplateRepository templateRepository,
|
||||
INextRunService nextRunService
|
||||
)
|
||||
{
|
||||
this.templateService = templateService;
|
||||
this.nextRunService = nextRunService;
|
||||
_templateRepository = templateRepository;
|
||||
_nextRunService = nextRunService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -41,12 +42,12 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
{
|
||||
var response = new StatTemplateResponse
|
||||
{
|
||||
ActivateScheduleCount = await templateService.Get().AsNoTracking().CountAsync(t => t.IsActiveSchedule),
|
||||
ActivateTemplateCount = await templateService.Get().AsNoTracking().CountAsync(t => t.IsActiveTemplate),
|
||||
TemplateAgentCount = await templateService.Get().AsNoTracking().CountAsync(t => t.Job!.Group!.IsAgent),
|
||||
TemplateCount = await templateService.Get().AsNoTracking().CountAsync(),
|
||||
SyncEsppScheduleCount = await templateService.Get().AsNoTracking().CountAsync(t => t.RobotConfigurations.Any(c => c.RobotCode == (int)RobotsEnum.ScheduleOrder && c.TaskStatusCode == (int)TaskStatusEnum.Ok)),
|
||||
SyncEsppTemplatesCount = await templateService.Get().AsNoTracking().CountAsync(t => t.RobotConfigurations.Any(c => c.RobotCode == (int)RobotsEnum.TemplateOrder && c.TaskStatusCode == (int)TaskStatusEnum.Ok))
|
||||
ActivateScheduleCount = await _templateRepository.Get().AsNoTracking().CountAsync(t => t.IsActiveSchedule),
|
||||
ActivateTemplateCount = await _templateRepository.Get().AsNoTracking().CountAsync(t => t.IsActiveTemplate),
|
||||
TemplateAgentCount = await _templateRepository.Get().AsNoTracking().CountAsync(t => t.Job!.Group!.IsAgent),
|
||||
TemplateCount = await _templateRepository.Get().AsNoTracking().CountAsync(),
|
||||
SyncEsppScheduleCount = await _templateRepository.Get().AsNoTracking().CountAsync(t => t.RobotConfigurations.Any(c => c.RobotCode == (int)RobotsEnum.ScheduleOrder && c.TaskStatusCode == (int)TaskStatusEnum.Ok)),
|
||||
SyncEsppTemplatesCount = await _templateRepository.Get().AsNoTracking().CountAsync(t => t.RobotConfigurations.Any(c => c.RobotCode == (int)RobotsEnum.TemplateOrder && c.TaskStatusCode == (int)TaskStatusEnum.Ok))
|
||||
};
|
||||
|
||||
return Ok(new Response<StatTemplateResponse>(response, true));
|
||||
@@ -71,7 +72,7 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
userEnd.AddDays(1),
|
||||
timeZoneQuery.TimeZoneOffset);
|
||||
|
||||
var allRecords = await templateService.Get()
|
||||
var allRecords = await _templateRepository.Get()
|
||||
.AsNoTracking()
|
||||
.FilterByDateRangeUtc(t => t.DateCreated, utcStart, utcEnd)
|
||||
.Select(t => new { t.Id, t.DateCreated })
|
||||
@@ -80,7 +81,7 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
var resultDict = allRecords.GroupByUserDate(t => t.DateCreated, timeZoneQuery.TimeZoneOffset);
|
||||
|
||||
|
||||
var daysList = await nextRunService.GetWorkDaysAsync(userStart, userEnd, false);
|
||||
var daysList = await _nextRunService.GetWorkDaysAsync(userStart, userEnd, false);
|
||||
|
||||
var response = daysList.Select(date => new StatTemplatePeriodResponse
|
||||
{
|
||||
@@ -92,5 +93,27 @@ namespace PARR.API.Controllers.V1.Statistics
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить кол-во шаблонов у которых ИД расписания null и нет задания на создание расписания
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet(ApiRoutes.StatTemplate.GetTemplatesWithoutScheduleAndTaskCount)]
|
||||
public async Task<IActionResult> GetTemplatesWithoutScheduleAndTaskCount()
|
||||
{
|
||||
var count = await _templateRepository.Get()
|
||||
.CountAsync(t =>
|
||||
t.ScheduleEsppId == null
|
||||
&& !t.RobotConfigurations.Any(x =>
|
||||
x.RobotCode == (int)RobotsEnum.ScheduleOrder
|
||||
&& x.TaskStatusCode == (int)TaskStatusEnum.Creating
|
||||
)
|
||||
);
|
||||
|
||||
var resposne = new StatTemplatesWithoutScheduleResponse(count);
|
||||
|
||||
return Ok(new Response<StatTemplatesWithoutScheduleResponse>(resposne, true));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -10,10 +10,8 @@ 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;
|
||||
using PARR.Core.Services.Shortcodes;
|
||||
using PARR.Domain.Common.Pagination;
|
||||
using PARR.Domain.Common.Roles;
|
||||
@@ -30,37 +28,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 +67,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 +78,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 +109,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 +117,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 +130,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 +160,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 +175,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 +211,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 +222,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 +259,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 +270,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 +282,35 @@ 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);
|
||||
response.EsppEk = await _shortcodesService.ApplyShortcodesAsync(template.Job!.Group!.EkMask, 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));
|
||||
//}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,21 +27,18 @@ namespace PARR.API.Controllers.V1
|
||||
private readonly ILogger<TnkController> logger;
|
||||
private readonly IMapper mapper;
|
||||
private readonly ITnkRepository tnkService;
|
||||
//private readonly IValidator<TnkRequest> validator;
|
||||
private readonly IUriService uriService;
|
||||
|
||||
public TnkController(
|
||||
ILogger<TnkController> logger,
|
||||
IMapper mapper,
|
||||
ITnkRepository tnkService,
|
||||
//IValidator<TnkRequest> validator,
|
||||
IUriService uriService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.mapper = mapper;
|
||||
this.tnkService = tnkService;
|
||||
//this.validator = validator;
|
||||
this.uriService = uriService;
|
||||
}
|
||||
|
||||
@@ -127,23 +124,16 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpPost(ApiRoutes.Tnk.Create)]
|
||||
public async Task<IActionResult> Create([FromBody] TnkRequest request)
|
||||
{
|
||||
//var resultValidate = await validator.ValidateAsync(request);
|
||||
//if (!resultValidate.IsValid)
|
||||
// return BadRequest(new Response(resultValidate.Errors));
|
||||
|
||||
var existName = await tnkService.Get().FirstOrDefaultAsync(t => t.Name.ToLower() == request.Name.Trim().ToLower());
|
||||
if (existName != null)
|
||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Name), Message = $"Вид работы с именем \"{request.Name}\" уже существует." } }));
|
||||
|
||||
//var existEsppId = await tnkService.Get().FirstOrDefaultAsync(t => t.EsppId == request.EsppId);
|
||||
//if (existEsppId != null)
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.EsppId), Message = $"ТНК с EsppId: {request.EsppId} уже существует." } }));
|
||||
|
||||
var tnk = new Tnk
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = request.Name.Trim(),
|
||||
EsppId = request.EsppId,
|
||||
DurationMinutes = request.DurationMinutes,
|
||||
ShortName = request.ShortName?.Trim(),
|
||||
SubprocessId = request.SubprocessId
|
||||
};
|
||||
@@ -168,15 +158,6 @@ namespace PARR.API.Controllers.V1
|
||||
[HttpPut(ApiRoutes.Tnk.Update)]
|
||||
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] TnkRequest request)
|
||||
{
|
||||
//var resultValidate = await validator.ValidateAsync(request);
|
||||
//if (!resultValidate.IsValid)
|
||||
// return BadRequest(new Response(resultValidate.Errors));
|
||||
|
||||
////проверка на уникальность esppId
|
||||
//var existEsppId = await tnkService.Get().FirstOrDefaultAsync(t => t.Id != id && t.EsppId == request.EsppId);
|
||||
//if (existEsppId != null)
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.EsppId), Message = $"Уже есть ТНК с EsppId: {request.EsppId}" } }));
|
||||
|
||||
var orig = await tnkService.Get()
|
||||
.FirstOrDefaultAsync(t => t.Id == id);
|
||||
|
||||
@@ -186,6 +167,7 @@ namespace PARR.API.Controllers.V1
|
||||
orig.Name = request.Name.Trim();
|
||||
orig.EsppId = request.EsppId;
|
||||
orig.SubprocessId = request.SubprocessId;
|
||||
orig.DurationMinutes = request.DurationMinutes;
|
||||
orig.ShortName = request.ShortName?.Trim();
|
||||
orig.DateModified = DateTimeOffset.UtcNow;
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace PARR.API.Infrastructure.Middleware
|
||||
|
||||
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogError(exception, "Ошибка во время запроса {TraceId}: {Message}", httpContext.TraceIdentifier, exception.Message);
|
||||
logger.LogDebug(exception, "Ошибка во время запроса {TraceId}: {Message}", httpContext.TraceIdentifier, exception.Message);
|
||||
|
||||
// определяем статус код, в зависимости от типа исключения
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using PARR.API.Settings;
|
||||
using PARR.Domain.Settings;
|
||||
|
||||
namespace PARR.API.Installers
|
||||
{
|
||||
@@ -23,6 +24,14 @@ namespace PARR.API.Installers
|
||||
configuration.GetSection(nameof(MonitoringSettings)).Bind(monitoringSettings);
|
||||
services.AddSingleton(monitoringSettings);
|
||||
|
||||
var commonSettings = new CommonSettings();
|
||||
configuration.GetSection(nameof(CommonSettings)).Bind(commonSettings);
|
||||
services.AddSingleton(commonSettings);
|
||||
|
||||
var helpDocumentSettings = new HelpDocumentSettings();
|
||||
configuration.GetSection(nameof(HelpDocumentSettings)).Bind(helpDocumentSettings);
|
||||
services.AddSingleton(helpDocumentSettings);
|
||||
|
||||
//TODO: add other
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,27 @@
|
||||
using PARR.API.Authentication.Models;
|
||||
using PARR.API.Contracts.V1.Responses;
|
||||
using PARR.API.Contracts.V1.Responses.Statistics;
|
||||
using PARR.API.Controllers.V1.Statistics;
|
||||
using PARR.API.MappingProfiles.Resolvers;
|
||||
using PARR.Core.Repositories.Interfaces.Schedule;
|
||||
using PARR.Domain.DTOs.HelpDocument;
|
||||
using PARR.Domain.DTOs.Matching;
|
||||
using PARR.Domain.DTOs.RobotMetrics;
|
||||
using PARR.Domain.DTOs.RobotSnapshotDTO;
|
||||
using PARR.Domain.DTOs.RobotStatusDetails;
|
||||
using PARR.Domain.DTOs.RobotTask;
|
||||
using PARR.Domain.DTOs.RobotTaskDetails;
|
||||
using PARR.Domain.DTOs.RobotTaskRobotStatus;
|
||||
using PARR.Domain.DTOs.Shared;
|
||||
using PARR.Domain.DTOs.Shortcode;
|
||||
using PARR.Domain.DTOs.TaskDTO;
|
||||
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.RobotEntities;
|
||||
using PARR.Domain.Entities.Schedule;
|
||||
using PARR.Domain.Entities.Unit;
|
||||
|
||||
@@ -78,7 +86,7 @@ namespace PARR.API.MappingProfiles
|
||||
.ForMember(d => d.Script, o => o.MapFrom(s => s.AgentScript))
|
||||
.ForMember(d => d.TimeOutSec, o => o.MapFrom(s => s.AgentTimeOutSec));
|
||||
|
||||
CreateMap<PARR.Domain.Entities.TaskStatus, TaskStatusResponse>();
|
||||
CreateMap<PARR.Domain.Entities.RobotEntities.TaskStatus, TaskStatusResponse>();
|
||||
|
||||
#region ScheduleResponseAreaTimeOffsetResponse
|
||||
|
||||
@@ -254,12 +262,21 @@ namespace PARR.API.MappingProfiles
|
||||
|
||||
CreateMap<Robot, RobotResponse>();
|
||||
|
||||
CreateMap<PARR.Domain.Entities.TaskStatus, TaskStatusResponse>();
|
||||
CreateMap<PARR.Domain.Entities.RobotEntities.TaskStatus, TaskStatusResponse>();
|
||||
|
||||
//TODO: удалить этот маппинг, пока он нужен для шаблонов. TemplateController
|
||||
CreateMap<RobotConfiguration, RobotConfigurationResponse>()
|
||||
.ForMember(d => d.Robot, o => o.MapFrom(s => s.Robot))
|
||||
.ForMember(d => d.TaskStatus, o => o.MapFrom(s => s.TaskStatus))
|
||||
.ForMember(d => d.RobotStatus, o => o.MapFrom(s => s.RobotStatus));
|
||||
//---
|
||||
|
||||
CreateMap<RobotResult, RobotResponse>();
|
||||
CreateMap<RobotTaskStatusResult, TaskStatusResponse>();
|
||||
CreateMap<RobotStatusResult, RobotStatusResponse>();
|
||||
|
||||
CreateMap<RobotConfigurationResult, RobotConfigurationResponse>();
|
||||
|
||||
// === RobotConfiguration ===
|
||||
#endregion
|
||||
|
||||
@@ -342,7 +359,8 @@ namespace PARR.API.MappingProfiles
|
||||
.Include<Job, JobResponse>();
|
||||
|
||||
CreateMap<Job, JobResponse>()
|
||||
.ForMember(d => d.AutoControl, o => o.MapFrom(s => s.AutoControl));
|
||||
.ForMember(d => d.AutoControl, o => o.MapFrom(s => s.AutoControl))
|
||||
.ForMember(d => d.UnitFilters, o => o.MapFrom(s => s.UnitFilters.OrderBy(t => t.UnitFilter)));
|
||||
|
||||
CreateMap<JobUnitFilter, UnitFilterResponse>()
|
||||
.ForMember(d => d.UnitFilterMask, o => o.MapFrom(s => s.UnitFilter))
|
||||
@@ -363,13 +381,17 @@ namespace PARR.API.MappingProfiles
|
||||
|
||||
#region JobGroup
|
||||
|
||||
CreateMap<JobGroupShortResult, JobGroupShortResponse>()
|
||||
.ForMember(d => d.Name, o => o.MapFrom(s => s.GroupName));
|
||||
|
||||
CreateMap<JobGroup, JobGroupBaseResponse>()
|
||||
.Include<JobGroup, JobGroupResponse>()
|
||||
.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.AutoControl, o => o.MapFrom(s => s.AutoControl));
|
||||
.ForMember(d => d.AutoControl, o => o.MapFrom(s => s.AutoControl))
|
||||
.ForMember(d => d.UnitFilters, o => o.MapFrom(s => s.UnitFilters.OrderBy(t => t.UnitFilter)));
|
||||
|
||||
CreateMap<JobGroup, JobGroupBaseResponse>()
|
||||
.ForMember(d => d.Name, o => o.MapFrom(s => s.GroupName))
|
||||
@@ -383,6 +405,21 @@ namespace PARR.API.MappingProfiles
|
||||
.ForMember(d => d.ScheduleExcludeTypeCalendar, o => o.MapFrom(s => s.ScheduleExcludeTypeCalendar));
|
||||
//.ForMember(d => d.DistributionConfig, o => o.MapFrom(s => s.DistributionConfig));
|
||||
|
||||
//------- unit filters
|
||||
CreateMap<JobGroupUnitFilter, UnitFilterResponse>()
|
||||
.ForMember(d => d.UnitFilterMask, o => o.MapFrom(s => s.UnitFilter))
|
||||
.ForMember(d => d.FieldFilters, o => o.MapFrom(s => s.FieldFilters.OrderBy(o => o.UnitField!.AihitName)))
|
||||
.ForMember(d => d.RelationshipFilters, o => o.MapFrom(s => s.RelationshipFilters.OrderBy(o => o.UnitField!.AihitName)));
|
||||
|
||||
CreateMap<JobGroupFieldFilter, FieldResponse>();
|
||||
|
||||
CreateMap<JobGroupFieldFilter, FieldFilterResponse>()
|
||||
.ForMember(d => d.Field, o => o.MapFrom(s => s.UnitField));
|
||||
|
||||
CreateMap<JobGroupRelationshipFilter, RelationshipFilterResponse>()
|
||||
.ForMember(d => d.Field, o => o.MapFrom(s => s.UnitField));
|
||||
//---------
|
||||
|
||||
CreateMap<JobGroupAutoControl, JobGroupAutoControlResponse>();
|
||||
|
||||
#endregion
|
||||
@@ -500,6 +537,41 @@ namespace PARR.API.MappingProfiles
|
||||
|
||||
#endregion
|
||||
|
||||
#region StatRobotMetrics
|
||||
|
||||
CreateMap<TaskStatusChartPoint, StatTaskStatusChartPoint>();
|
||||
CreateMap<RobotStatusChartPoint, StatRobotStatusChartPoint>();
|
||||
CreateMap<FilteredChartPoint, StatFilteredChartPoint>();
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region StatRobotTaskDetailsResponse
|
||||
|
||||
CreateMap<RobotTaskGroupDetailsResult, StatRobotTaskGroupDetailsResponse>();
|
||||
//todo: ForMember не нужен?
|
||||
//.ForMember(d => d.JobGroup, o => o.MapFrom(s => s.JobGroup));
|
||||
|
||||
CreateMap<RobotTaskDetailsResult, StatRobotTaskDetailsResponse>();
|
||||
//todo: ForMember не нужен?
|
||||
//.ForMember(d => d.Details, o => o.MapFrom(s => s.Details));
|
||||
|
||||
#endregion
|
||||
|
||||
#region StatRobotStatusDetailsResponse
|
||||
|
||||
CreateMap<RobotStatusDetailsResult, StatRobotStatusDetailsResponse>();
|
||||
|
||||
CreateMap<RobotStatusGroupDetailsResult, StatRobotStatusGroupDetailsResponse>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region HelpDocumentResponse
|
||||
|
||||
CreateMap<HelpDocumentResult, HelpDocumentResponse>();
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.API.Contracts.V1.Requests.Queries;
|
||||
using PARR.Domain.Common.Pagination;
|
||||
using PARR.Domain.DTOs.RobotMetrics;
|
||||
using PARR.Domain.DTOs.RobotSnapshotDTO;
|
||||
using PARR.Domain.Entities.Job;
|
||||
using PARR.Domain.Entities.JobEntities;
|
||||
|
||||
namespace PARR.API.MappingProfiles
|
||||
{
|
||||
@@ -52,6 +53,9 @@ namespace PARR.API.MappingProfiles
|
||||
#endregion
|
||||
|
||||
CreateMap<StatRobotSnapshotQuery, RobotSnapshotQuery>();
|
||||
|
||||
|
||||
CreateMap<RobotFilteredMetricsQuery, MetricFilter>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
15
PARR.API/Settings/CommonSettings.cs
Normal file
15
PARR.API/Settings/CommonSettings.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace PARR.API.Settings
|
||||
{
|
||||
/// <summary>
|
||||
/// Общие настройки API
|
||||
/// </summary>
|
||||
public record CommonSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Период охлаждения (кулдаун) для расписаний.
|
||||
/// Запрещает повторно брать активные шаблоны в работу, если с момента их последнего запуска прошло меньше этого времени.
|
||||
/// Применяется только для инициаторов EsppScheduleSync и NextRun.
|
||||
/// </summary>
|
||||
public TimeSpan ScheduleCooldownDuration { get; init; } = TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
@@ -16,7 +16,8 @@ namespace PARR.API.Validators
|
||||
IUnitFieldRepository unitFieldRepository,
|
||||
IScheduleExcludeTypeRepository scheduleExcludeTypeRepository,
|
||||
IScheduleExcludeTypeCalendarRepository scheduleExcludeTypeCalendarRepository,
|
||||
IDistributionPeriodRepository distributionPeriodRepository
|
||||
IDistributionPeriodRepository distributionPeriodRepository,
|
||||
UnitFiltersBaseRequestValidator unitFilterValidator
|
||||
)
|
||||
{
|
||||
RuleFor(t => t.Name)
|
||||
@@ -38,6 +39,9 @@ namespace PARR.API.Validators
|
||||
.MustAsync(async (entity, value, c) => await jobGroupTypeRepository.GetAsync(value) != null)
|
||||
.WithMessage("Указан несуществующий Id типа");
|
||||
|
||||
// Валидация фильтров (они могут быть пустые, мы так договорились)
|
||||
Include(unitFilterValidator);
|
||||
|
||||
//Проверяем существует ли такой GroupingUnitFieldId в unitField
|
||||
RuleFor(t => t.GroupingUnitFieldId)
|
||||
.MustAsync(async (entity, value, c) =>
|
||||
@@ -150,6 +154,8 @@ namespace PARR.API.Validators
|
||||
})
|
||||
.WithMessage("Некорректные параметры автоконтроля");
|
||||
|
||||
RuleFor(t => t.EkMask)
|
||||
.NotNull().NotEmpty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json.Linq;
|
||||
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;
|
||||
|
||||
namespace PARR.API.Validators
|
||||
@@ -12,20 +11,17 @@ namespace PARR.API.Validators
|
||||
{
|
||||
private readonly ITnkRepository _tnkRepository;
|
||||
private readonly IJobGroupRepository _jobGroupRepository;
|
||||
private readonly IJobRepository _jobRepository;
|
||||
private readonly IUnitFieldRepository _unitFieldRepository;
|
||||
//private JobGroup? jobGroup;
|
||||
|
||||
public JobRequestValidator(
|
||||
ITnkRepository tnkRepository,
|
||||
IJobGroupRepository jobGroupRepository,
|
||||
IJobRepository jobRepository,
|
||||
IUnitFieldRepository unitFieldRepository
|
||||
IUnitFieldRepository unitFieldRepository,
|
||||
UnitFiltersBaseRequestValidator unitFilterValidator
|
||||
)
|
||||
{
|
||||
_tnkRepository = tnkRepository;
|
||||
_jobGroupRepository = jobGroupRepository;
|
||||
_jobRepository = jobRepository;
|
||||
_unitFieldRepository = unitFieldRepository;
|
||||
|
||||
RuleFor(t => t.Name)
|
||||
@@ -42,12 +38,28 @@ namespace PARR.API.Validators
|
||||
.MustAsync(async (entity, value, c) => await IsGroupExist(entity))
|
||||
.WithMessage("Указан несуществующий Id группы работ({PropertyValue})");
|
||||
|
||||
RuleForEach(t => t.UnitFilters)
|
||||
.NotNull().NotEmpty();
|
||||
#region UnitFiters
|
||||
|
||||
When(t => t.UnitFilters != null && t.UnitFilters.Any(), () =>
|
||||
{
|
||||
RuleFor(t => t.UnitFilters)
|
||||
.MustAsync(async (entity, value, c) =>
|
||||
{
|
||||
// Проверяем флаг в БД: разрешены ли фильтры для этой группы
|
||||
return await jobGroupRepository.Get()
|
||||
.AnyAsync(t => t.Id == entity.GroupId && t.GroupType!.IsAllowJobUnitFilter == true, c);
|
||||
})
|
||||
.WithMessage("Дополнительные фильтры запрещены")
|
||||
// Stop делает так, что если флаг равен false, FluentValidation остановится
|
||||
// и НЕ пойдет выполнять Include базового валидатора (сэкономим запрос к БД)
|
||||
.DependentRules(() =>
|
||||
{
|
||||
// Этот валидатор сработает ПОСЛЕ успешной проверки флага IsAllowJobUnitFilter
|
||||
Include(unitFilterValidator);
|
||||
});
|
||||
});
|
||||
|
||||
RuleForEach(t => t.UnitFilters)
|
||||
.MustAsync(async (entity, value, c) => await IsUnitFiltersCorrect(entity))
|
||||
.WithMessage("Неверно заданы параметры фильтров. Внимательнее, пожалуйста!");
|
||||
#endregion
|
||||
|
||||
RuleFor(t => t.Relationships)
|
||||
.MustAsync(async (entity, value, c) =>
|
||||
@@ -99,35 +111,6 @@ namespace PARR.API.Validators
|
||||
.WithMessage("Некорректные параметры автоконтроля");
|
||||
}
|
||||
|
||||
private async Task<bool> IsUnitFiltersCorrect(JobRequest entity)
|
||||
{
|
||||
foreach (var unitFilter in entity.UnitFilters)
|
||||
{
|
||||
if (string.IsNullOrEmpty(unitFilter.UnitFilterMask))
|
||||
return false;
|
||||
|
||||
//if (unitFilter.FieldFilters == null || !unitFilter.FieldFilters.Any())
|
||||
// return false;
|
||||
|
||||
if (unitFilter.FieldFilters != null && unitFilter.FieldFilters.Any())
|
||||
foreach (var fieldFilter in unitFilter.FieldFilters)
|
||||
{
|
||||
var fieldId = fieldFilter.FieldId;
|
||||
if (await _unitFieldRepository.GetAsync(fieldId) == null)
|
||||
return false;
|
||||
}
|
||||
|
||||
if (unitFilter.RelationshipFilters != null && unitFilter.RelationshipFilters.Any())
|
||||
foreach (var relationshipFilter in unitFilter.RelationshipFilters!)
|
||||
{
|
||||
var fieldId = relationshipFilter.FieldId;
|
||||
if (await _unitFieldRepository.GetAsync(fieldId) == null)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> IsGroupExist(JobRequest entity)
|
||||
{
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
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.JobRepositories;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.API.Validators
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -19,6 +19,11 @@ namespace PARR.API.Validators
|
||||
|
||||
//RuleFor(t => t.EsppId).NotEmpty().NotNull().WithMessage("EsppId не может быть пустым");
|
||||
|
||||
RuleFor(t => t.DurationMinutes)
|
||||
.GreaterThanOrEqualTo(0)
|
||||
.When(t => t.DurationMinutes.HasValue)
|
||||
.WithMessage("Значение не может быть отрицательным");
|
||||
|
||||
RuleFor(t => t.SubprocessId).NotEmpty().NotNull();
|
||||
|
||||
RuleFor(t => t.SubprocessId)
|
||||
|
||||
85
PARR.API/Validators/UnitFiltersBaseRequestValidator.cs
Normal file
85
PARR.API/Validators/UnitFiltersBaseRequestValidator.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PARR.API.Contracts.V1.Requests;
|
||||
using PARR.Core.Repositories.Interfaces.Unit;
|
||||
|
||||
namespace PARR.API.Validators
|
||||
{
|
||||
/// <summary>
|
||||
/// Валидация фильтроп вдя JobGroup, Job
|
||||
/// </summary>
|
||||
public class UnitFiltersBaseRequestValidator: AbstractValidator<UnitFiltersBaseRequest>
|
||||
{
|
||||
private readonly IUnitFieldRepository _unitFieldRepository;
|
||||
|
||||
public UnitFiltersBaseRequestValidator(IUnitFieldRepository unitFieldRepository)
|
||||
{
|
||||
_unitFieldRepository = unitFieldRepository;
|
||||
|
||||
// Это правило будет применяться ко ВСЕМ, кто наследует UnitFiltersBaseRequest
|
||||
RuleForEach(t => t.UnitFilters)
|
||||
.MustAsync(async (entity, value, c) => await IsUnitFiltersCorrect(entity))
|
||||
.WithMessage("Неверно заданы параметры фильтров.");
|
||||
}
|
||||
|
||||
private async Task<bool> IsUnitFiltersCorrect(UnitFiltersBaseRequest entity)
|
||||
{
|
||||
// 1. Проверим маски, они не должны быть пустыми
|
||||
foreach (var unitFilter in entity.UnitFilters)
|
||||
{
|
||||
if (string.IsNullOrEmpty(unitFilter.UnitFilterMask))
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. Собираем все уникальные FieldId из всех фильтров в памяти
|
||||
var requestedFieldIds = entity.UnitFilters
|
||||
.SelectMany(uf =>
|
||||
(uf.FieldFilters ?? Enumerable.Empty<FieldFilterRequest>()).Select(ff => ff.FieldId)
|
||||
.Concat((uf.RelationshipFilters ?? Enumerable.Empty<RelationshipFilterRequest>()).Select(rf => rf.FieldId)))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
// Если фильтров с ID нет, то и проверять в БД нечего
|
||||
if (!requestedFieldIds.Any())
|
||||
return true;
|
||||
|
||||
// 3. Выполняем ОДИН запрос к БД.
|
||||
var existingFieldIds = await _unitFieldRepository.Get()
|
||||
.Where(field => requestedFieldIds.Contains(field.Id))
|
||||
.Select(field => field.Id)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
// 4. Если количество найденных ID в БД меньше, чем мы запрашивали,
|
||||
// значит какого-то fieldId не существует
|
||||
return requestedFieldIds.Count == existingFieldIds.Count;
|
||||
|
||||
#region Old
|
||||
//foreach (var unitFilter in entity.UnitFilters)
|
||||
//{
|
||||
// if (string.IsNullOrEmpty(unitFilter.UnitFilterMask))
|
||||
// return false;
|
||||
|
||||
// if (unitFilter.FieldFilters != null && unitFilter.FieldFilters.Any())
|
||||
// foreach (var fieldFilter in unitFilter.FieldFilters)
|
||||
// {
|
||||
// var fieldId = fieldFilter.FieldId;
|
||||
// if (await _unitFieldRepository.GetAsync(fieldId) == null)
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (unitFilter.RelationshipFilters != null && unitFilter.RelationshipFilters.Any())
|
||||
// foreach (var relationshipFilter in unitFilter.RelationshipFilters!)
|
||||
// {
|
||||
// var fieldId = relationshipFilter.FieldId;
|
||||
// if (await _unitFieldRepository.GetAsync(fieldId) == null)
|
||||
// return false;
|
||||
// }
|
||||
//}
|
||||
|
||||
//return true;
|
||||
#endregion
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,8 @@
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware": "None"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
@@ -14,7 +15,8 @@
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
"Microsoft.Hosting.Lifetime": "Information",
|
||||
"Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware": "Fatal"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -111,7 +113,22 @@
|
||||
}
|
||||
],
|
||||
"RabbitMq": {
|
||||
"ThresholdConnections": 29
|
||||
"ThresholdConnections": 32
|
||||
}
|
||||
},
|
||||
"CommonSettings": {
|
||||
"ScheduleCooldownDuration": "03:00:00"
|
||||
},
|
||||
"HelpDocumentSettings": {
|
||||
"GitLabSettings": {
|
||||
"BaseUrl": "http://gitlab.dvgd.oao.rzd/api/v4/",
|
||||
"ProjectId": "1343",
|
||||
"Token": "glpat-2PBp1c9hryQHUJnoZn3S",
|
||||
"DefaultBranch": "main",
|
||||
"RepositoryPath": "http://gitlab.dvgd.oao.rzd/devptk/parr/parr_help_docs"
|
||||
},
|
||||
"CacheTTL": "23:59:00",
|
||||
"ShortTTL": "00:10:00",
|
||||
"WebhookToken": "ParrSecret2026"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -120,7 +117,8 @@ public class JobGroupCloneHelper
|
||||
ScheduleExcludeTypeCalendarId = source.ScheduleExcludeTypeCalendarId,
|
||||
DateCreated = DateTimeOffset.UtcNow,
|
||||
Jobs = new HashSet<Job>(),
|
||||
EsppSchValues = new HashSet<EsppSchValue>()
|
||||
EsppSchValues = new HashSet<EsppSchValue>(),
|
||||
EkMask = source.EkMask
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -1,17 +1,29 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using PARR.Core.Common.Helpers;
|
||||
using PARR.Core.Common.Implementations;
|
||||
using PARR.Core.Common.Interfaces;
|
||||
using PARR.Core.Services.HelpDocument.Implementations;
|
||||
using PARR.Core.Services.HelpDocument.Interfaces;
|
||||
using PARR.Core.Services.MatchingStatusService;
|
||||
using PARR.Core.Services.NextRunServices;
|
||||
using PARR.Core.Services.NextRunServices.Subservices;
|
||||
using PARR.Core.Services.RobotMetrics;
|
||||
using PARR.Core.Services.RobotSnapshotServices;
|
||||
using PARR.Core.Services.RobotStatusDetails.Implementations;
|
||||
using PARR.Core.Services.RobotStatusDetails.Interfaces;
|
||||
using PARR.Core.Services.RobotTask.Implementations;
|
||||
using PARR.Core.Services.RobotTask.Interfaces;
|
||||
using PARR.Core.Services.RobotTaskDetailsServices.Implementations;
|
||||
using PARR.Core.Services.RobotTaskDetailsServices.Interfaces;
|
||||
using PARR.Core.Services.RobotTaskRobotStatus.Implemetations;
|
||||
using PARR.Core.Services.RobotTaskRobotStatus.Interfaces;
|
||||
using PARR.Core.Services.Shortcodes;
|
||||
using PARR.Core.Services.Shortcodes.Handlers;
|
||||
using PARR.Core.Services.Snapshots.Implementations;
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
using PARR.Core.Services.TaskServices.Handlers;
|
||||
using PARR.Core.Services.TaskServices.Handlers.Factory;
|
||||
using PARR.Core.Services.TaskServices.Implementations;
|
||||
@@ -97,6 +109,8 @@ namespace PARR.Core
|
||||
services.AddScoped<IShortcodeHandler, FieldShortcodeHandler>();
|
||||
services.AddScoped<IShortcodeHandler, TagShortcodeHandler>();
|
||||
services.AddScoped<IShortcodeHandler, RelatedUnitTagShortcodeHandler>();
|
||||
services.AddScoped<IShortcodeHandler, ParentUnitByNameShortcodeHandler>();
|
||||
services.AddScoped<IShortcodeHandler, ParentUnitByFieldValueShortcodeHandler>();
|
||||
|
||||
services.AddScoped<IShortcodesService, ShortcodesService>();
|
||||
#endregion
|
||||
@@ -107,14 +121,29 @@ namespace PARR.Core
|
||||
|
||||
services.AddScoped<IRobotTaskService, RobotTaskService>();
|
||||
services.AddScoped<IRobotSnapshotService, RobotSnapshotService>();
|
||||
services.AddScoped<IRobotTaskRobotStatusService, RobotTaskRobotStatusService>();
|
||||
services.AddScoped<IRobotTaskDetailsService, RobotTaskDetailsService>();
|
||||
services.AddScoped<IRobotStatusDetailsService, RobotStatusDetailsService>();
|
||||
|
||||
services.AddScoped<IUnitService, UnitService>();
|
||||
services.AddScoped<UnitCacheService>();
|
||||
|
||||
services.AddScoped<IRobotMetricsService, RobotMetricsService>();
|
||||
|
||||
//services.AddScoped<IUserService, UserService>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Сервисы сбора снапшотов
|
||||
|
||||
services.TryAddSingleton<ISnapshotSettings, DefaultSnapshotSettings>();
|
||||
|
||||
services.AddScoped<ISnapshotProvider, RobotConfigurationSnapshotService>();
|
||||
services.AddScoped<ISnapshotProvider, RobotSnapshotService>();
|
||||
// тут другие сервисы, реализующие ISnapshotProvider
|
||||
|
||||
#endregion
|
||||
|
||||
#region Workload
|
||||
|
||||
services.AddScoped<WorkloadCacheService>();
|
||||
@@ -149,6 +178,16 @@ namespace PARR.Core
|
||||
|
||||
#endregion
|
||||
|
||||
#region
|
||||
|
||||
// Добавляем дефолтные настройки, при необходимости переопределить в воркерах (API)
|
||||
services.TryAddSingleton<HelpDocumentSettings>();
|
||||
|
||||
services.AddHttpClient<IHelpDocumentProvider, GitLabHelpProvider>();
|
||||
services.AddScoped<IHelpDocumentService, HelpDocumentService>();
|
||||
|
||||
#endregion
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
|
||||
10
PARR.Core/Extensions/EnumerableExtensions.cs
Normal file
10
PARR.Core/Extensions/EnumerableExtensions.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace PARR.Core.Extensions
|
||||
{
|
||||
public static class EnumerableExtensions
|
||||
{
|
||||
public static int MaxOrDefault(this IEnumerable<int> source)
|
||||
{
|
||||
return source.Any() ? source.Max() : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,9 @@ namespace PARR.Core.Infrastructure.Mapping.RobotTask
|
||||
//.ForMember(d => d.Initiator, o => o.MapFrom<RobotTaskTemplateInitiatorResolver>())
|
||||
//.ForMember(d => d.Category, o => o.MapFrom<RobotTaskTemplateCategoryResolver>())
|
||||
.ForMember(d => d.WorkGroup, o => o.MapFrom(s => s.Template!.Job!.WorkGroupMask))
|
||||
.ForMember(d => d.Ek, o => o.MapFrom(s => s.Template!.Unit!.Name))
|
||||
//.ForMember(d => d.Ek, o => o.MapFrom(s => s.Template!.Unit!.Name))
|
||||
// Берем ЭК на у юнита, а в группе работ, маску ЭК (шорткод)
|
||||
.ForMember(d => d.Ek, o => o.MapFrom(s => s.Template!.Job!.Group!.EkMask))
|
||||
.ForMember(d => d.Name, o => o.MapFrom(s => s.Template!.Name))
|
||||
.ForMember(d => d.ProcessName, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Subprocess!.Process!.Name))
|
||||
.ForMember(d => d.ProcessEsppId, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Subprocess!.Process!.EsppId))
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using AutoMapper;
|
||||
using PARR.Domain.DTOs.RobotTaskRobotStatus;
|
||||
using PARR.Domain.Entities;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.RobotTaskRobotStatus
|
||||
{
|
||||
internal class RobotConfigurationResultMappingProfile : Profile
|
||||
{
|
||||
public RobotConfigurationResultMappingProfile()
|
||||
{
|
||||
CreateMap<RobotConfiguration, RobotConfigurationResult>()
|
||||
.ForMember(d => d.Robot, o => o.MapFrom(s => s.Robot))
|
||||
.ForMember(d => d.TaskStatus, o => o.MapFrom(s => s.TaskStatus))
|
||||
.ForMember(d => d.RobotStatus, o => o.MapFrom(s => s.RobotStatus));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using AutoMapper;
|
||||
using PARR.Domain.DTOs.Shared;
|
||||
using PARR.Domain.Entities.JobGroupEntities;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.Shared
|
||||
{
|
||||
public class JobGroupResultMappingProfile: Profile
|
||||
{
|
||||
public JobGroupResultMappingProfile()
|
||||
{
|
||||
CreateMap<JobGroup, JobGroupShortResult>()
|
||||
.Include<JobGroup, JobGroupResult>();
|
||||
|
||||
CreateMap<JobGroup, JobGroupResult>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using AutoMapper;
|
||||
using PARR.Domain.DTOs.Shared;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.Shared
|
||||
{
|
||||
public class RobotResultMappingProfile : Profile
|
||||
{
|
||||
public RobotResultMappingProfile()
|
||||
{
|
||||
CreateMap<Robot, RobotResult>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using AutoMapper;
|
||||
using PARR.Domain.DTOs.Shared;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.Shared
|
||||
{
|
||||
public class RobotStatusResultMappingProfile : Profile
|
||||
{
|
||||
public RobotStatusResultMappingProfile()
|
||||
{
|
||||
CreateMap<RobotStatus, RobotStatusResult>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using AutoMapper;
|
||||
using PARR.Domain.DTOs.Shared;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.Shared
|
||||
{
|
||||
public class RobotTaskStatusResultMappingProfile : Profile
|
||||
{
|
||||
public RobotTaskStatusResultMappingProfile()
|
||||
{
|
||||
CreateMap<PARR.Domain.Entities.RobotEntities.TaskStatus, RobotTaskStatusResult>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.16" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.16" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.16" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="9.0.16" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -49,5 +49,11 @@ namespace PARR.Core.Repositories.Interfaces
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> SetInProgressStatusAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Установить статус робота - Ошибка, и поставить максимальное значение попыток
|
||||
/// </summary>
|
||||
/// <param name="configuration"></param>
|
||||
void SetErrorRobotStatusAndMaxAttempts(RobotConfiguration configuration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using PARR.Core.Repositories.Base;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces
|
||||
{
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
{
|
||||
public interface IStatusTemplateRepository
|
||||
{
|
||||
IQueryable<Domain.Entities.TaskStatus> Get();
|
||||
IQueryable<Domain.Entities.RobotEntities.TaskStatus> Get();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
{
|
||||
public interface ITaskStatusRepository
|
||||
{
|
||||
IQueryable<Domain.Entities.TaskStatus> Get();
|
||||
IQueryable<Domain.Entities.RobotEntities.TaskStatus> Get();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
using PARR.Core.Repositories.Base;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces.Job
|
||||
{
|
||||
public interface IJobRepository : IBaseRepository<Domain.Entities.Job.Job>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
{
|
||||
@@ -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>
|
||||
{
|
||||
@@ -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>
|
||||
{
|
||||
@@ -1,6 +1,6 @@
|
||||
using PARR.Domain.Entities.Job;
|
||||
using PARR.Domain.Entities.JobEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces.Job
|
||||
namespace PARR.Core.Repositories.Interfaces.JobRepositories
|
||||
{
|
||||
public interface IJobAutoControlRepository
|
||||
{
|
||||
@@ -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>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
{
|
||||
@@ -0,0 +1,9 @@
|
||||
using PARR.Core.Repositories.Base;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces.RobotRepositories
|
||||
{
|
||||
public interface IRobotConfigurationSnapshotRepository : IBaseRepository<RobotConfigurationSnapshot>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using PARR.Domain.Entities.TemplateEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces.TemplateRepositories
|
||||
{
|
||||
public interface ITemplateRenamePendingRepository
|
||||
{
|
||||
Task<bool> CreateAsync(TemplateRenamePending obj);
|
||||
IQueryable<TemplateRenamePending> Get();
|
||||
void Remove(TemplateRenamePending obj);
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ using PARR.Domain.Entities.Unit;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces.Unit
|
||||
{
|
||||
public interface IUnitFieldValueRepository: IBaseRepository<UnitFieldValue>
|
||||
public interface IUnitFieldValueRepository : IBaseRepository<UnitFieldValue>
|
||||
{
|
||||
Task<UnitFieldValue?> GetByValueNameAsync(string? value);
|
||||
Task<List<Guid>> FindValueIdsByMaskAsync(string mask, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,19 +4,11 @@ namespace PARR.Core.Repositories.Interfaces.Unit
|
||||
{
|
||||
public interface IUnitInUnitRepository
|
||||
{
|
||||
Task<List<UnitInUnit>> GetByParentIdAsync(Guid parentId);
|
||||
Task<List<UnitInUnit>> GetByChildIdAsync(Guid childId);
|
||||
|
||||
/// <summary>
|
||||
/// Получает связи, где ChildUnitId unitIds (для IsParent=True).
|
||||
/// Возвращает все связанные UnitId для заданного юнита в обоих направлениях.
|
||||
/// Единая точка загрузки связей.
|
||||
/// </summary>
|
||||
Task<List<UnitInUnit>> GetParentLinksByChildIdsAsync(IEnumerable<Guid> childUnitIds);
|
||||
|
||||
/// <summary>
|
||||
/// Получает связи, где ParentUnitId unitIds (для IsParent=False).
|
||||
/// </summary>
|
||||
Task<List<UnitInUnit>> GetChildLinksByParentIdsAsync(IEnumerable<Guid> parentUnitIds);
|
||||
|
||||
Task<List<Guid>> GetRelatedUnitIdsAsync(Guid unitId, CancellationToken ct = default);
|
||||
|
||||
IQueryable<UnitInUnit> Get();
|
||||
}
|
||||
|
||||
@@ -4,18 +4,18 @@ namespace PARR.Core.Repositories.Interfaces.Unit
|
||||
{
|
||||
public interface IUnitRepository : IBaseRepository<Domain.Entities.Unit.Unit>
|
||||
{
|
||||
/// <summary>
|
||||
/// Поиск юнитов по списку ID значений.
|
||||
/// Используется для эффективной фильтрации после предварительного поиска ValueId.
|
||||
/// </summary>
|
||||
Task<List<Guid>> FindUnitIdsByValueIdsAsync(
|
||||
IReadOnlyList<Guid> unitIds,
|
||||
Guid fieldId,
|
||||
IReadOnlyList<Guid> valueIds,
|
||||
CancellationToken ct = default);
|
||||
|
||||
IQueryable<Guid> GetInitialUnitIds(string dbValueMask);
|
||||
|
||||
/// <summary>
|
||||
/// Получить юниты по Id атрибута и маски значения
|
||||
/// </summary>
|
||||
/// <param name="query"></param>
|
||||
/// <param name="fieldId"></param>
|
||||
/// <param name="valueMask"></param>
|
||||
/// <param name="isInverse">true - не содержит, false - содержит</param>
|
||||
/// <returns></returns>
|
||||
IQueryable<Domain.Entities.Unit.Unit> GetUnitByFieldAndValue(IQueryable<Domain.Entities.Unit.Unit> query, Guid fieldId, string valueMask, bool isInverse = false);
|
||||
|
||||
IQueryable<Domain.Entities.Unit.Unit> GetWithIncludes();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Core.Services.HelpDocument.Interfaces;
|
||||
using PARR.Domain.DTOs.HelpDocument;
|
||||
using PARR.Domain.Settings;
|
||||
using System.Web;
|
||||
|
||||
namespace PARR.Core.Services.HelpDocument.Implementations
|
||||
{
|
||||
/// <summary>
|
||||
/// Получение справочной документации из GitLab
|
||||
/// </summary>
|
||||
internal class GitLabHelpProvider : IHelpDocumentProvider
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly HelpDocumentSettings _helpDocumentSettings;
|
||||
private readonly ILogger<GitLabHelpProvider> _logger;
|
||||
|
||||
public GitLabHelpProvider(HttpClient httpClient, HelpDocumentSettings helpDocumentSettings, ILogger<GitLabHelpProvider> logger)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_helpDocumentSettings = helpDocumentSettings;
|
||||
_logger = logger;
|
||||
|
||||
// Базовая настройка http
|
||||
_httpClient = httpClient;
|
||||
|
||||
if (_helpDocumentSettings.GitLabSettings == null)
|
||||
{
|
||||
_logger.LogCritical("Инициализация провайдера справки провалена: не задана секция GitLabSettings");
|
||||
throw new ArgumentNullException(nameof(_helpDocumentSettings.GitLabSettings), "Не заданы настройки подключения к GitLab");
|
||||
}
|
||||
|
||||
_httpClient.BaseAddress = new Uri(_helpDocumentSettings.GitLabSettings.BaseUrl);
|
||||
_httpClient.DefaultRequestHeaders.Add("PRIVATE-TOKEN", _helpDocumentSettings.GitLabSettings.Token);
|
||||
}
|
||||
|
||||
|
||||
public async Task<HelpDocumentResult?> GetDocumentAsync(string helpId)
|
||||
{
|
||||
//1. Формируем путь к файлу
|
||||
var filePath = $"{helpId}.md";
|
||||
|
||||
// 2. GitLab API требует, чтобы относительный путь к файлу в URL был закодирован (экранирован)
|
||||
var urlEncodedPath = HttpUtility.UrlEncode(filePath);
|
||||
|
||||
// 3. Собираем эндпоинт для получения RAW контента файла
|
||||
string relativeRequestUrl = $"projects/{_helpDocumentSettings.GitLabSettings!.ProjectId}/repository/files/{urlEncodedPath}/raw?ref={_helpDocumentSettings.GitLabSettings.DefaultBranch}";
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
// Создаем URI строго с флагом UriKind.Relative. Это заставит HttpClient отправить %2F в сыром виде!
|
||||
var relativeUri = new Uri(relativeRequestUrl, UriKind.Relative);
|
||||
|
||||
_logger.LogDebug("Отправка HTTP GET запроса к GitLab API. Относительный URI: {RelativeUri}", relativeRequestUrl);
|
||||
|
||||
var response = await _httpClient.GetAsync(relativeUri);
|
||||
|
||||
// Если файла нет (404) или токен не подошел (401/403)
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("Документ справки не найден или недоступен в GitLab. HelpId: {HelpId}, StatusCode: {StatusCode}",
|
||||
helpId, response.StatusCode);
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Файл справки успешно получен из GitLab. Размер ответа: {ContentLength} байт",
|
||||
response.Content.Headers.ContentLength);
|
||||
|
||||
// Получаем весь текст файла (и шапку, и контент)
|
||||
string rawFileContent = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// 4. Парсим файл
|
||||
var result = ParseMarkdownFile(helpId, rawFileContent);
|
||||
|
||||
_logger.LogDebug("Документ справки успешно загружен и распарсен. HelpId: {HelpId}, Title: '{Title}'",
|
||||
helpId, result.Title);
|
||||
|
||||
var editUrl = GenerateEditUrl(helpId);
|
||||
|
||||
return result with
|
||||
{
|
||||
EditUrl = editUrl
|
||||
};
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при запросе справки {HelpId} из GitLab", helpId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private string? GenerateEditUrl(string helpId)
|
||||
{
|
||||
if (_helpDocumentSettings.GitLabSettings == null)
|
||||
return null;
|
||||
|
||||
var repoPath = _helpDocumentSettings.GitLabSettings.RepositoryPath;
|
||||
var branch = _helpDocumentSettings.GitLabSettings.DefaultBranch ?? "main";
|
||||
|
||||
return $"{repoPath}/-/edit/{branch}/{helpId}.md";
|
||||
}
|
||||
|
||||
private HelpDocumentResult ParseMarkdownFile(string helpId, string rawContent)
|
||||
{
|
||||
_logger.LogDebug("Начало парсинга структуры Markdown для HelpId: {HelpId}", helpId);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(rawContent))
|
||||
{
|
||||
_logger.LogWarning("Получен пустой контент для HelpId: {HelpId}", helpId);
|
||||
return new HelpDocumentResult { HelpId = helpId };
|
||||
}
|
||||
|
||||
// Стандартное разделение строк с поддержкой разных типов окончаний (Windows/Linux)
|
||||
var lines = rawContent.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
|
||||
|
||||
var title = string.Empty;
|
||||
string? prevId = null;
|
||||
string? nextId = null;
|
||||
|
||||
var contentStartIndex = 0;
|
||||
var isInsideFrontMatter = false;
|
||||
var frontMatterClosed = false;
|
||||
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i].Trim();
|
||||
|
||||
// Ищем маркеры начала и конца метаданных "---"
|
||||
if (line == "---")
|
||||
{
|
||||
if (!isInsideFrontMatter && !frontMatterClosed)
|
||||
{
|
||||
isInsideFrontMatter = true;
|
||||
_logger.LogDebug("Обнаружено начало блока метаданных (Front Matter) на строке {LineIndex}", i);
|
||||
continue;
|
||||
}
|
||||
else if (isInsideFrontMatter)
|
||||
{
|
||||
isInsideFrontMatter = false;
|
||||
frontMatterClosed = true;
|
||||
contentStartIndex = i + 1; // Контент начинается строго со следующей строки
|
||||
_logger.LogDebug("Обнаружен конец блока метаданных на строке {LineIndex}", i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Читаем свойства внутри блока метаданных
|
||||
if (isInsideFrontMatter)
|
||||
{
|
||||
if (line.StartsWith("title:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
title = line.Substring("title:".Length).Trim();
|
||||
_logger.LogDebug("В метаданных найден Title: '{Title}'", title);
|
||||
}
|
||||
// Парсим Предыдущий шаг
|
||||
else if (line.StartsWith("prev_id:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
prevId = line.Substring("prev_id:".Length).Trim();
|
||||
_logger.LogDebug("В метаданных найден PrevId: '{PrevId}'", prevId);
|
||||
}
|
||||
// Парсим Следующий шаг
|
||||
else if (line.StartsWith("next_id:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
nextId = line.Substring("next_id:".Length).Trim();
|
||||
_logger.LogDebug("В метаданных найден NextId: '{NextId}'", nextId);
|
||||
}
|
||||
|
||||
// Тут в будущем можно парсить другие поля, например: icon, min_role и т.д.
|
||||
}
|
||||
}
|
||||
|
||||
string cleanContent;
|
||||
|
||||
if (frontMatterClosed)
|
||||
{
|
||||
// Собираем обратно чистый контент, исключая строки с шапкой
|
||||
cleanContent = string.Join(Environment.NewLine, lines.Skip(contentStartIndex));
|
||||
}
|
||||
else
|
||||
{
|
||||
// Если шапки "---" вообще не было в файле, берем весь текст как есть
|
||||
_logger.LogDebug("Блок метаданных '---' не найден в файле. Весь текст перенесен в Content.");
|
||||
cleanContent = rawContent;
|
||||
title = Path.GetFileNameWithoutExtension(helpId); // Дефолтный заголовок из имени файла
|
||||
}
|
||||
|
||||
return new HelpDocumentResult
|
||||
{
|
||||
HelpId = helpId,
|
||||
Title = title,
|
||||
Content = cleanContent,
|
||||
PrevId = prevId,
|
||||
NextId = nextId
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Core.Common.Interfaces;
|
||||
using PARR.Core.Services.HelpDocument.Interfaces;
|
||||
using PARR.Domain.Cache;
|
||||
using PARR.Domain.DTOs.HelpDocument;
|
||||
using PARR.Domain.Settings;
|
||||
|
||||
namespace PARR.Core.Services.HelpDocument.Implementations
|
||||
{
|
||||
internal class HelpDocumentService : IHelpDocumentService
|
||||
{
|
||||
private readonly IHelpDocumentProvider _helpProvider;
|
||||
private readonly IRedisCacheService _redisCacheService;
|
||||
private readonly HelpDocumentSettings _helpDocumentSettings;
|
||||
private readonly ILogger<HelpDocumentService> _logger;
|
||||
|
||||
public HelpDocumentService(
|
||||
IHelpDocumentProvider helpProvider,
|
||||
IRedisCacheService redisCacheService,
|
||||
HelpDocumentSettings helpDocumentSettings,
|
||||
ILogger<HelpDocumentService> logger
|
||||
)
|
||||
{
|
||||
_helpProvider = helpProvider;
|
||||
_redisCacheService = redisCacheService;
|
||||
_helpDocumentSettings = helpDocumentSettings;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
|
||||
public async Task<HelpDocumentResult?> GetHelpDocumentAsync(string helpId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(helpId))
|
||||
{
|
||||
_logger.LogWarning("Значение helpId: '{helpId}' пустое.", helpId);
|
||||
return null;
|
||||
}
|
||||
|
||||
var cacheKey = _redisCacheService.GetKey(CacheKeys.HelpDocument.HelpDocumentItem(helpId));
|
||||
|
||||
_logger.LogDebug("Запрос справки. Проверка наличия в Redis по ключу: {CacheKey}", cacheKey);
|
||||
|
||||
// 1. Попытка получить данные из Redis
|
||||
var cachedData = await _redisCacheService.GetCachedDataAsync<HelpDocumentResult?>(cacheKey, useCompression: true);
|
||||
|
||||
if (cachedData != null)
|
||||
{
|
||||
_logger.LogInformation("Документ справки успешно извлечен из кэша Redis. HelpId: {HelpId}", helpId);
|
||||
return cachedData;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Кэш пуст или недоступен. Запрос документа напрямую через провайдер для HelpId: {HelpId}", helpId);
|
||||
|
||||
// 2. Если в Redis пусто, идем в GitLab через наш провайдер
|
||||
var remoteDocument = await _helpProvider.GetDocumentAsync(helpId);
|
||||
|
||||
if (remoteDocument == null)
|
||||
{
|
||||
_logger.LogWarning("Документ не найден ни в Redis, ни в GitLab. HelpId: {HelpId}", helpId);
|
||||
|
||||
|
||||
// Создаем понятный для пользователя текст-заглушку если нет документации
|
||||
remoteDocument = new HelpDocumentResult
|
||||
{
|
||||
HelpId = helpId,
|
||||
Title = "Раздел в разработке",
|
||||
Content = "### 📚 Отсутствует документация по данному разделу.\n\n" +
|
||||
"Если у вас возникли срочные вопросы, свяжитесь с теми, кто знает на них ответы :)."
|
||||
};
|
||||
|
||||
// Кэшируем заглушку на короткий срок (например, на 5-10 минут), а не на 24 часа.
|
||||
// Это нужно, чтобы как только аналитик создаст файл и прилетит хук, кэш обновился,
|
||||
// но при этом частые клики пользователей по сломанному вопросику не спамили GitLab запросами 404.
|
||||
await _redisCacheService.SetCachedDataAsync(cacheKey, remoteDocument, _helpDocumentSettings.ShortTTL, useCompression: true);
|
||||
|
||||
return remoteDocument;
|
||||
}
|
||||
|
||||
// 3. Сохраняем полученный документ в Redis для последующих запросов
|
||||
await _redisCacheService.SetCachedDataAsync(cacheKey, remoteDocument, _helpDocumentSettings.CacheTTL, useCompression: true);
|
||||
|
||||
_logger.LogDebug("Вернул документацию из провайдера для HelpId: {HelpId}", helpId);
|
||||
|
||||
return remoteDocument;
|
||||
}
|
||||
|
||||
|
||||
public async Task ClearCacheAsync(string helpId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(helpId))
|
||||
{
|
||||
_logger.LogWarning("Попытка очистки кэша: передан пустой helpId.");
|
||||
return;
|
||||
}
|
||||
|
||||
var cacheKey = _redisCacheService.GetKey(CacheKeys.HelpDocument.HelpDocumentItem(helpId));
|
||||
|
||||
_logger.LogInformation("Удаление документа справки из кэша Redis по вебхуку. Ключ: {CacheKey}", cacheKey);
|
||||
|
||||
await _redisCacheService.DeleteCachedDataAsync(cacheKey);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using PARR.Domain.DTOs.HelpDocument;
|
||||
|
||||
namespace PARR.Core.Services.HelpDocument.Interfaces
|
||||
{
|
||||
internal interface IHelpDocumentProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Запрашивает сырой файл .md из источника (например gitlab)
|
||||
/// </summary>
|
||||
/// <param name="helpId"></param>
|
||||
/// <returns></returns>
|
||||
Task<HelpDocumentResult?> GetDocumentAsync(string helpId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using PARR.Domain.DTOs.HelpDocument;
|
||||
|
||||
namespace PARR.Core.Services.HelpDocument.Interfaces
|
||||
{
|
||||
/// <summary>
|
||||
/// Сервис загрузки справочной документации
|
||||
/// </summary>
|
||||
public interface IHelpDocumentService
|
||||
{
|
||||
/// <summary>
|
||||
/// Получить документ справки по его уникальному идентификатору (с учетом кэширования в Redis)
|
||||
/// </summary>
|
||||
/// <param name="helpId">Уникальный путь справке</param>
|
||||
/// <returns></returns>
|
||||
Task<HelpDocumentResult?> GetHelpDocumentAsync(string helpId);
|
||||
|
||||
/// <summary>
|
||||
/// Сбрасывает кэш в Redis для конкретного документа справки (вызывается вебхуком)
|
||||
/// </summary>
|
||||
/// <param name="helpId"></param>
|
||||
/// <returns></returns>
|
||||
Task ClearCacheAsync(string helpId);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user