Merge pull request '#646 Репозиторий Хранения названий источников данных от систем' (#11) from DataSourceSystem into master
Reviewed-on: #11
This commit is contained in:
commit
e3319867dd
51
Persistence.API/Controllers/DataSourceSystemController.cs
Normal file
51
Persistence.API/Controllers/DataSourceSystemController.cs
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Persistence.Models;
|
||||||
|
using Persistence.Repositories;
|
||||||
|
|
||||||
|
namespace Persistence.API.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Работа с системами
|
||||||
|
/// </summary>
|
||||||
|
[ApiController]
|
||||||
|
[Authorize]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class DataSourceSystemController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IDataSourceSystemRepository dataSourceSystemRepository;
|
||||||
|
|
||||||
|
public DataSourceSystemController(IDataSourceSystemRepository dataSourceSystemRepository)
|
||||||
|
{
|
||||||
|
this.dataSourceSystemRepository = dataSourceSystemRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить системы
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult<DataSourceSystemDto>> Get(CancellationToken token)
|
||||||
|
{
|
||||||
|
var result = await dataSourceSystemRepository.Get(token);
|
||||||
|
|
||||||
|
return Ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить систему
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="dataSourceSystemDto"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost]
|
||||||
|
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
|
||||||
|
public async Task<IActionResult> Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
|
||||||
|
{
|
||||||
|
await dataSourceSystemRepository.Add(dataSourceSystemDto, token);
|
||||||
|
|
||||||
|
return CreatedAtAction(nameof(Add), true);
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Persistence.Models;
|
using Persistence.Models;
|
||||||
using Persistence.Models.Requests;
|
using Persistence.Models.Requests;
|
||||||
@ -44,17 +44,17 @@ public class TechMessagesController : ControllerBase
|
|||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить статистику по системам
|
/// Получить статистику по системам
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="autoDrillingSystem"></param>
|
/// <param name="autoDrillingSystem"></param>
|
||||||
/// <param name="categoryIds"></param>
|
/// <param name="categoryIds"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("statistics")]
|
[HttpGet("statistics")]
|
||||||
public async Task<ActionResult<IEnumerable<MessagesStatisticDto>>> GetStatistics([FromQuery] IEnumerable<string> autoDrillingSystem, [FromQuery] IEnumerable<int> categoryIds, CancellationToken token)
|
public async Task<ActionResult<IEnumerable<MessagesStatisticDto>>> GetStatistics([FromQuery] IEnumerable<Guid> autoDrillingSystem, [FromQuery] IEnumerable<int> categoryIds, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token);
|
var result = await techMessagesRepository.GetStatistics(autoDrillingSystem, categoryIds, token);
|
||||||
|
|
||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
@ -78,11 +78,11 @@ public class TechMessagesController : ControllerBase
|
|||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpGet("range")]
|
[HttpGet("range")]
|
||||||
public async Task<ActionResult<DatesRangeDto>> GetDatesRangeAsync(CancellationToken token)
|
public async Task<ActionResult<DatesRangeDto?>> GetDatesRangeAsync(CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await techMessagesRepository.GetDatesRangeAsync(token);
|
var result = await techMessagesRepository.GetDatesRangeAsync(token);
|
||||||
|
|
||||||
return Ok(result);
|
return result == null ? NoContent() : Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -100,19 +100,20 @@ public class TechMessagesController : ControllerBase
|
|||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Добавить новые технологические сообщения
|
/// Добавить новые технологические сообщения
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="dtos"></param>
|
/// <param name="systemId"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="dtos"></param>
|
||||||
/// <returns></returns>
|
/// <param name="token"></param>
|
||||||
[HttpPost]
|
/// <returns></returns>
|
||||||
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
|
[HttpPost("{systemId}")]
|
||||||
public async Task<IActionResult> AddRange([FromBody] IEnumerable<TechMessageDto> dtos, CancellationToken token)
|
[ProducesResponseType(typeof(int), (int)HttpStatusCode.Created)]
|
||||||
{
|
public async Task<IActionResult> AddRange([FromRoute] Guid systemId, [FromBody] IEnumerable<TechMessageDto> dtos, CancellationToken token)
|
||||||
var userId = User.GetUserId<Guid>();
|
{
|
||||||
|
var userId = User.GetUserId<Guid>();
|
||||||
|
|
||||||
var result = await techMessagesRepository.AddRange(dtos, userId, token);
|
var result = await techMessagesRepository.AddRange(systemId, dtos, userId, token);
|
||||||
|
|
||||||
return CreatedAtAction(nameof(AddRange), result);
|
return CreatedAtAction(nameof(AddRange), result);
|
||||||
}
|
}
|
||||||
|
@ -12,11 +12,11 @@ public abstract class BaseClient
|
|||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<T> ExecuteGetResponse<T>(Func<Task<IApiResponse<T>>> getMethod, CancellationToken token)
|
public async Task<T?> ExecuteGetResponse<T>(Func<Task<IApiResponse<T>>> getMethod, CancellationToken token)
|
||||||
{
|
{
|
||||||
var response = await getMethod.Invoke().WaitAsync(token);
|
var response = await getMethod.Invoke().WaitAsync(token);
|
||||||
|
|
||||||
if (response.IsSuccessful)
|
if (response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
return response.Content;
|
return response.Content;
|
||||||
}
|
}
|
||||||
@ -32,7 +32,7 @@ public abstract class BaseClient
|
|||||||
{
|
{
|
||||||
var response = await postMethod.Invoke().WaitAsync(token);
|
var response = await postMethod.Invoke().WaitAsync(token);
|
||||||
|
|
||||||
if (response.IsSuccessful)
|
if (response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -48,7 +48,7 @@ public abstract class BaseClient
|
|||||||
{
|
{
|
||||||
var response = await postMethod.Invoke().WaitAsync(token);
|
var response = await postMethod.Invoke().WaitAsync(token);
|
||||||
|
|
||||||
if (response.IsSuccessful)
|
if (response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
return response.Content;
|
return response.Content;
|
||||||
}
|
}
|
||||||
|
@ -16,7 +16,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
|
|||||||
|
|
||||||
public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
|
public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<int>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token);
|
async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -25,7 +25,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
|
|||||||
public async Task<PaginationContainer<DataWithWellDepthAndSectionDto>> GetByDate(Guid idDiscriminator, DateTimeOffset moment,
|
public async Task<PaginationContainer<DataWithWellDepthAndSectionDto>> GetByDate(Guid idDiscriminator, DateTimeOffset moment,
|
||||||
SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token)
|
SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<PaginationContainer<DataWithWellDepthAndSectionDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token);
|
async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -33,10 +33,10 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
|
|||||||
|
|
||||||
public async Task<IEnumerable<ChangeLogDto>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
|
public async Task<IEnumerable<ChangeLogDto>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<ChangeLogDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token);
|
async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<int> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token)
|
public async Task<int> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token)
|
||||||
@ -89,7 +89,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
|
|||||||
|
|
||||||
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
|
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<DatesRangeDto?>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token);
|
async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -98,5 +98,7 @@ public class ChangeLogClient : BaseClient, IChangeLogClient
|
|||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
refitChangeLogClient.Dispose();
|
refitChangeLogClient.Dispose();
|
||||||
}
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
37
Persistence.Client/Clients/DataSourceSystemClient.cs
Normal file
37
Persistence.Client/Clients/DataSourceSystemClient.cs
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Persistence.Client.Clients.Base;
|
||||||
|
using Persistence.Client.Clients.Interfaces;
|
||||||
|
using Persistence.Client.Clients.Interfaces.Refit;
|
||||||
|
using Persistence.Models;
|
||||||
|
|
||||||
|
namespace Persistence.Client.Clients;
|
||||||
|
public class DataSourceSystemClient : BaseClient, IDataSourceSystemClient
|
||||||
|
{
|
||||||
|
private readonly IRefitDataSourceSystemClient dataSourceSystemClient;
|
||||||
|
|
||||||
|
public DataSourceSystemClient(IRefitDataSourceSystemClient dataSourceSystemClient, ILogger<DataSourceSystemClient> logger) : base(logger)
|
||||||
|
{
|
||||||
|
this.dataSourceSystemClient = dataSourceSystemClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
|
||||||
|
{
|
||||||
|
await ExecutePostResponse(
|
||||||
|
async () => await dataSourceSystemClient.Add(dataSourceSystemDto, token), token);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
|
||||||
|
{
|
||||||
|
var result = await ExecuteGetResponse(
|
||||||
|
async () => await dataSourceSystemClient.Get(token), token);
|
||||||
|
|
||||||
|
return result!;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
dataSourceSystemClient.Dispose();
|
||||||
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
using Persistence.Models;
|
||||||
|
using Refit;
|
||||||
|
|
||||||
|
namespace Persistence.Client.Clients.Interfaces;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Клиент для работы с системами
|
||||||
|
/// </summary>
|
||||||
|
public interface IDataSourceSystemClient : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Получить системы
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить систему
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="dataSourceSystemDto"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
|
||||||
|
}
|
@ -14,14 +14,14 @@ public interface ITechMessagesClient : IDisposable
|
|||||||
/// <param name="dtos"></param>
|
/// <param name="dtos"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<int> AddRange(IEnumerable<TechMessageDto> dtos, CancellationToken token);
|
Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, CancellationToken token);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить диапазон дат, для которых есть данные в репозитории
|
/// Получить диапазон дат, для которых есть данные в репозитории
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token);
|
Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить список технологических сообщений в виде страницы
|
/// Получить список технологических сообщений в виде страницы
|
||||||
@ -43,16 +43,16 @@ public interface ITechMessagesClient : IDisposable
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить статистику по системам
|
/// Получить статистику по системам
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="autoDrillingSystem"></param>
|
/// <param name="systemIds"></param>
|
||||||
/// <param name="categoryId"></param>
|
/// <param name="categoryIds"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token);
|
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systemIds, IEnumerable<int> categoryIds, CancellationToken token);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить список всех систем
|
/// Получить список всех систем
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IEnumerable<string>> GetSystems(CancellationToken token);
|
Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token);
|
||||||
}
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
using Persistence.Models;
|
||||||
|
using Refit;
|
||||||
|
|
||||||
|
namespace Persistence.Client.Clients.Interfaces.Refit;
|
||||||
|
public interface IRefitDataSourceSystemClient : IDisposable
|
||||||
|
{
|
||||||
|
private const string BaseRoute = "/api/dataSourceSystem";
|
||||||
|
|
||||||
|
[Get($"{BaseRoute}")]
|
||||||
|
Task<IApiResponse<IEnumerable<DataSourceSystemDto>>> Get(CancellationToken token);
|
||||||
|
|
||||||
|
[Post($"{BaseRoute}")]
|
||||||
|
Task<IApiResponse> Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
|
||||||
|
}
|
@ -1,4 +1,5 @@
|
|||||||
using Persistence.Models;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Persistence.Models;
|
||||||
using Persistence.Models.Requests;
|
using Persistence.Models.Requests;
|
||||||
using Refit;
|
using Refit;
|
||||||
|
|
||||||
@ -11,19 +12,19 @@ namespace Persistence.Client.Clients.Interfaces.Refit
|
|||||||
[Get($"{BaseRoute}")]
|
[Get($"{BaseRoute}")]
|
||||||
Task<IApiResponse<PaginationContainer<TechMessageDto>>> GetPage([Query] PaginationRequest request, CancellationToken token);
|
Task<IApiResponse<PaginationContainer<TechMessageDto>>> GetPage([Query] PaginationRequest request, CancellationToken token);
|
||||||
|
|
||||||
[Post($"{BaseRoute}")]
|
[Post($"{BaseRoute}/{{systemId}}")]
|
||||||
Task<IApiResponse<int>> AddRange([Body] IEnumerable<TechMessageDto> dtos, CancellationToken token);
|
Task<IApiResponse<int>> AddRange(Guid systemId, [Body] IEnumerable<TechMessageDto> dtos, CancellationToken token);
|
||||||
|
|
||||||
[Get($"{BaseRoute}/systems")]
|
[Get($"{BaseRoute}/systems")]
|
||||||
Task<IApiResponse<IEnumerable<string>>> GetSystems(CancellationToken token);
|
Task<IApiResponse<IEnumerable<DataSourceSystemDto>>> GetSystems(CancellationToken token);
|
||||||
|
|
||||||
[Get($"{BaseRoute}/range")]
|
[Get($"{BaseRoute}/range")]
|
||||||
Task<IApiResponse<DatesRangeDto>> GetDatesRangeAsync(CancellationToken token);
|
Task<IApiResponse<DatesRangeDto?>> GetDatesRangeAsync(CancellationToken token);
|
||||||
|
|
||||||
[Get($"{BaseRoute}/part")]
|
[Get($"{BaseRoute}/part")]
|
||||||
Task<IApiResponse<IEnumerable<TechMessageDto>>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
|
Task<IApiResponse<IEnumerable<TechMessageDto>>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token);
|
||||||
|
|
||||||
[Get($"{BaseRoute}/statistics")]
|
[Get($"{BaseRoute}/statistics")]
|
||||||
Task<IApiResponse<IEnumerable<MessagesStatisticDto>>> GetStatistics([Query] string autoDrillingSystem, [Query] int categoryId, CancellationToken token);
|
Task<IApiResponse<IEnumerable<MessagesStatisticDto>>> GetStatistics([Query(CollectionFormat.Multi)] IEnumerable<Guid> systemIds, [Query(CollectionFormat.Multi)] IEnumerable<int> categoryIds, CancellationToken token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -17,42 +17,42 @@ public class SetpointClient : BaseClient, ISetpointClient
|
|||||||
|
|
||||||
public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token)
|
public async Task<IEnumerable<SetpointValueDto>> GetCurrent(IEnumerable<Guid> setpointKeys, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<SetpointValueDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token);
|
async () => await refitSetpointClient.GetCurrent(setpointKeys, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<SetpointValueDto>> GetHistory(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
|
public async Task<IEnumerable<SetpointValueDto>> GetHistory(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<SetpointValueDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token);
|
async () => await refitSetpointClient.GetHistory(setpointKeys, historyMoment, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLog(IEnumerable<Guid> setpointKeys, CancellationToken token)
|
public async Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLog(IEnumerable<Guid> setpointKeys, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<Dictionary<Guid, IEnumerable<SetpointLogDto>>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitSetpointClient.GetLog(setpointKeys, token), token);
|
async () => await refitSetpointClient.GetLog(setpointKeys, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
|
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<DatesRangeDto>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitSetpointClient.GetDatesRangeAsync(token), token);
|
async () => await refitSetpointClient.GetDatesRangeAsync(token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<SetpointLogDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
|
public async Task<IEnumerable<SetpointLogDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<SetpointLogDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitSetpointClient.GetPart(dateBegin, take, token), token);
|
async () => await refitSetpointClient.GetPart(dateBegin, take, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Add(Guid setpointKey, object newValue, CancellationToken token)
|
public async Task Add(Guid setpointKey, object newValue, CancellationToken token)
|
||||||
@ -64,5 +64,7 @@ public class SetpointClient : BaseClient, ISetpointClient
|
|||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
refitSetpointClient.Dispose();
|
refitSetpointClient.Dispose();
|
||||||
}
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,31 +18,31 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
|
|||||||
|
|
||||||
public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token)
|
public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<PaginationContainer<TechMessageDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTechMessagesClient.GetPage(request, token), token);
|
async () => await refitTechMessagesClient.GetPage(request, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<int> AddRange(IEnumerable<TechMessageDto> dtos, CancellationToken token)
|
public async Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecutePostResponse(
|
var result = await ExecutePostResponse(
|
||||||
async () => await refitTechMessagesClient.AddRange(dtos, token), token);
|
async () => await refitTechMessagesClient.AddRange(systemId, dtos, token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<string>> GetSystems(CancellationToken token)
|
public async Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<string>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTechMessagesClient.GetSystems(token), token);
|
async () => await refitTechMessagesClient.GetSystems(token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
|
public async Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<DatesRangeDto>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token);
|
async () => await refitTechMessagesClient.GetDatesRangeAsync(token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -50,22 +50,24 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
|
|||||||
|
|
||||||
public async Task<IEnumerable<TechMessageDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
|
public async Task<IEnumerable<TechMessageDto>> GetPart(DateTimeOffset dateBegin, int take, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<TechMessageDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token);
|
async () => await refitTechMessagesClient.GetPart(dateBegin, take, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(string autoDrillingSystem, int categoryId, CancellationToken token)
|
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systemIds, IEnumerable<int> categoryIds, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<MessagesStatisticDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTechMessagesClient.GetStatistics(autoDrillingSystem, categoryId, token), token);
|
async () => await refitTechMessagesClient.GetStatistics(systemIds, categoryIds, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
refitTechMessagesClient.Dispose();
|
refitTechMessagesClient.Dispose();
|
||||||
}
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,23 +24,23 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
|
|||||||
|
|
||||||
public async Task<IEnumerable<TDto>> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
|
public async Task<IEnumerable<TDto>> Get(DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<TDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token);
|
async () => await timeSeriesClient.Get(dateBegin, dateEnd, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<TDto>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default)
|
public async Task<IEnumerable<TDto>> GetResampledData(DateTimeOffset dateBegin, double intervalSec = 600d, int approxPointsCount = 1024, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<TDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token);
|
async () => await timeSeriesClient.GetResampledData(dateBegin, intervalSec, approxPointsCount, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<DatesRangeDto?> GetDatesRange(CancellationToken token)
|
public async Task<DatesRangeDto?> GetDatesRange(CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<DatesRangeDto?>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await timeSeriesClient.GetDatesRange(token), token);
|
async () => await timeSeriesClient.GetDatesRange(token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -49,5 +49,7 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
|
|||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
timeSeriesClient.Dispose();
|
timeSeriesClient.Dispose();
|
||||||
}
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,23 +24,23 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
|
|||||||
|
|
||||||
public async Task<IEnumerable<TimestampedSetDto>> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable<string>? columnNames, int skip, int take, CancellationToken token)
|
public async Task<IEnumerable<TimestampedSetDto>> Get(Guid idDiscriminator, DateTimeOffset? geTimestamp, IEnumerable<string>? columnNames, int skip, int take, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<TimestampedSetDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token);
|
async () => await refitTimestampedSetClient.Get(idDiscriminator, geTimestamp, columnNames, skip, take, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<TimestampedSetDto>> GetLast(Guid idDiscriminator, IEnumerable<string>? columnNames, int take, CancellationToken token)
|
public async Task<IEnumerable<TimestampedSetDto>> GetLast(Guid idDiscriminator, IEnumerable<string>? columnNames, int take, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<TimestampedSetDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token);
|
async () => await refitTimestampedSetClient.GetLast(idDiscriminator, columnNames, take, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<int> Count(Guid idDiscriminator, CancellationToken token)
|
public async Task<int> Count(Guid idDiscriminator, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<int>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTimestampedSetClient.Count(idDiscriminator, token), token);
|
async () => await refitTimestampedSetClient.Count(idDiscriminator, token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -48,7 +48,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
|
|||||||
|
|
||||||
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
|
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<DatesRangeDto?>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitTimestampedSetClient.GetDatesRange(idDiscriminator, token), token);
|
async () => await refitTimestampedSetClient.GetDatesRange(idDiscriminator, token), token);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -57,5 +57,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
|
|||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
refitTimestampedSetClient.Dispose();
|
refitTimestampedSetClient.Dispose();
|
||||||
}
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,30 +24,32 @@ public class WitsDataClient : BaseClient, IWitsDataClient
|
|||||||
|
|
||||||
public async Task<DatesRangeDto> GetDatesRangeAsync(Guid discriminatorId, CancellationToken token)
|
public async Task<DatesRangeDto> GetDatesRangeAsync(Guid discriminatorId, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<DatesRangeDto>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token);
|
async () => await refitWitsDataClient.GetDatesRangeAsync(discriminatorId, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<WitsDataDto>> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default)
|
public async Task<IEnumerable<WitsDataDto>> GetPart(Guid discriminatorId, DateTimeOffset dateBegin, int take = 86400, CancellationToken token = default)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token);
|
async () => await refitWitsDataClient.GetPart(discriminatorId, dateBegin, take, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<WitsDataDto>> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token)
|
public async Task<IEnumerable<WitsDataDto>> GetValuesForGraph(Guid discriminatorId, DateTimeOffset dateFrom, DateTimeOffset dateTo, int approxPointsCount, CancellationToken token)
|
||||||
{
|
{
|
||||||
var result = await ExecuteGetResponse<IEnumerable<WitsDataDto>>(
|
var result = await ExecuteGetResponse(
|
||||||
async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token);
|
async () => await refitWitsDataClient.GetValuesForGraph(discriminatorId, dateFrom, dateTo, approxPointsCount, token), token);
|
||||||
|
|
||||||
return result;
|
return result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
refitWitsDataClient.Dispose();
|
refitWitsDataClient.Dispose();
|
||||||
}
|
|
||||||
|
GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -128,5 +128,19 @@ namespace Persistence.Client
|
|||||||
|
|
||||||
return client;
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить клиент для работы c системами
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public IDataSourceSystemClient GetDataSourceSystemClient()
|
||||||
|
{
|
||||||
|
var logger = provider.GetRequiredService<ILogger<DataSourceSystemClient>>();
|
||||||
|
|
||||||
|
var restClient = RestService.For<IRefitDataSourceSystemClient>(httpClient, RefitSettings);
|
||||||
|
var client = new DataSourceSystemClient(restClient, logger);
|
||||||
|
|
||||||
|
return client;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -15,6 +15,7 @@ Persistence сервисом посредством обращения к кон
|
|||||||
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
|
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
|
||||||
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
|
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
|
||||||
- `IWitsDataClient` - Клиент для работы с параметрами Wits
|
- `IWitsDataClient` - Клиент для работы с параметрами Wits
|
||||||
|
- `IDataSourceSystemClient` - Клиент для работы с системами
|
||||||
|
|
||||||
## Использование
|
## Использование
|
||||||
Для получения того или иного Persistence - клиента нужно
|
Для получения того или иного Persistence - клиента нужно
|
||||||
|
@ -9,10 +9,10 @@ using Persistence.Database.Model;
|
|||||||
|
|
||||||
#nullable disable
|
#nullable disable
|
||||||
|
|
||||||
namespace Persistence.Database.Postgres.Migrations
|
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
|
||||||
{
|
{
|
||||||
[DbContext(typeof(PersistenceDbContext))]
|
[DbContext(typeof(PersistencePostgresContext))]
|
||||||
[Migration("20241202072250_TechMessageMigration")]
|
[Migration("20241212041758_TechMessageMigration")]
|
||||||
partial class TechMessageMigration
|
partial class TechMessageMigration
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@ -48,6 +48,30 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
b.ToTable("DrillingSystem");
|
b.ToTable("DrillingSystem");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("DiscriminatorId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Дискриминатор системы");
|
||||||
|
|
||||||
|
b.Property<int>("ParameterId")
|
||||||
|
.HasColumnType("integer")
|
||||||
|
.HasComment("Id параметра");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("Timestamp")
|
||||||
|
.HasColumnType("timestamp with time zone")
|
||||||
|
.HasComment("Временная отметка");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("varchar(256)")
|
||||||
|
.HasComment("Значение параметра в виде строки");
|
||||||
|
|
||||||
|
b.HasKey("DiscriminatorId", "ParameterId", "Timestamp");
|
||||||
|
|
||||||
|
b.ToTable("ParameterData");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
|
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("EventId")
|
b.Property<Guid>("EventId")
|
||||||
@ -59,27 +83,23 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
.HasColumnType("integer")
|
.HasColumnType("integer")
|
||||||
.HasComment("Id Категории важности");
|
.HasComment("Id Категории важности");
|
||||||
|
|
||||||
b.Property<double?>("Depth")
|
b.Property<int>("EventState")
|
||||||
.HasColumnType("double precision")
|
.HasColumnType("integer")
|
||||||
.HasComment("Глубина забоя");
|
.HasComment("Статус события");
|
||||||
|
|
||||||
b.Property<string>("MessageText")
|
b.Property<Guid>("SystemId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Id системы, к которой относится сообщение");
|
||||||
|
|
||||||
|
b.Property<string>("Text")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("varchar(512)")
|
.HasColumnType("varchar(512)")
|
||||||
.HasComment("Текст сообщения");
|
.HasComment("Текст сообщения");
|
||||||
|
|
||||||
b.Property<Guid>("SystemId")
|
|
||||||
.HasColumnType("uuid")
|
|
||||||
.HasComment("Id системы автобурения, к которой относится сообщение");
|
|
||||||
|
|
||||||
b.Property<DateTimeOffset>("Timestamp")
|
b.Property<DateTimeOffset>("Timestamp")
|
||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
.HasComment("Дата возникновения");
|
.HasComment("Дата возникновения");
|
||||||
|
|
||||||
b.Property<Guid>("UserId")
|
|
||||||
.HasColumnType("uuid")
|
|
||||||
.HasComment("Id пользователя за пультом бурильщика");
|
|
||||||
|
|
||||||
b.HasKey("EventId");
|
b.HasKey("EventId");
|
||||||
|
|
||||||
b.HasIndex("SystemId");
|
b.HasIndex("SystemId");
|
||||||
@ -110,6 +130,59 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Persistence.Database.Model.ChangeLog", b =>
|
||||||
|
{
|
||||||
|
b.Property<Guid>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Ключ записи");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset>("Creation")
|
||||||
|
.HasColumnType("timestamp with time zone")
|
||||||
|
.HasComment("Дата создания записи");
|
||||||
|
|
||||||
|
b.Property<double>("DepthEnd")
|
||||||
|
.HasColumnType("double precision")
|
||||||
|
.HasComment("Глубина забоя на дату окончания интервала");
|
||||||
|
|
||||||
|
b.Property<double>("DepthStart")
|
||||||
|
.HasColumnType("double precision")
|
||||||
|
.HasComment("Глубина забоя на дату начала интервала");
|
||||||
|
|
||||||
|
b.Property<Guid>("IdAuthor")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Автор изменения");
|
||||||
|
|
||||||
|
b.Property<Guid>("IdDiscriminator")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Дискриминатор таблицы");
|
||||||
|
|
||||||
|
b.Property<Guid?>("IdEditor")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Редактор");
|
||||||
|
|
||||||
|
b.Property<Guid?>("IdNext")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Id заменяющей записи");
|
||||||
|
|
||||||
|
b.Property<Guid>("IdSection")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Ключ секции");
|
||||||
|
|
||||||
|
b.Property<DateTimeOffset?>("Obsolete")
|
||||||
|
.HasColumnType("timestamp with time zone")
|
||||||
|
.HasComment("Дата устаревания (например при удалении)");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("jsonb")
|
||||||
|
.HasComment("Значение");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.ToTable("ChangeLog");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
|
modelBuilder.Entity("Persistence.Database.Model.DataSaub", b =>
|
||||||
{
|
{
|
||||||
b.Property<DateTimeOffset>("Date")
|
b.Property<DateTimeOffset>("Date")
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
#nullable disable
|
#nullable disable
|
||||||
|
|
||||||
namespace Persistence.Database.Postgres.Migrations
|
namespace Persistence.Database.Postgres.Migrations.PersistencePostgres
|
||||||
{
|
{
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public partial class TechMessageMigration : Migration
|
public partial class TechMessageMigration : Migration
|
||||||
@ -11,16 +11,16 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
protected override void Up(MigrationBuilder migrationBuilder)
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
{
|
{
|
||||||
migrationBuilder.CreateTable(
|
migrationBuilder.CreateTable(
|
||||||
name: "DrillingSystem",
|
name: "DataSourceSystem",
|
||||||
columns: table => new
|
columns: table => new
|
||||||
{
|
{
|
||||||
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы автобурения"),
|
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы - источника данных"),
|
||||||
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы автобурения"),
|
Name = table.Column<string>(type: "varchar(256)", nullable: false, comment: "Наименование системы - источника данных"),
|
||||||
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы автобурения")
|
Description = table.Column<string>(type: "text", nullable: true, comment: "Описание системы - источника данных")
|
||||||
},
|
},
|
||||||
constraints: table =>
|
constraints: table =>
|
||||||
{
|
{
|
||||||
table.PrimaryKey("PK_DrillingSystem", x => x.SystemId);
|
table.PrimaryKey("PK_DataSourceSystem", x => x.SystemId);
|
||||||
});
|
});
|
||||||
|
|
||||||
migrationBuilder.CreateTable(
|
migrationBuilder.CreateTable(
|
||||||
@ -30,18 +30,17 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
EventId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id события"),
|
EventId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id события"),
|
||||||
CategoryId = table.Column<int>(type: "integer", nullable: false, comment: "Id Категории важности"),
|
CategoryId = table.Column<int>(type: "integer", nullable: false, comment: "Id Категории важности"),
|
||||||
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"),
|
Timestamp = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, comment: "Дата возникновения"),
|
||||||
Depth = table.Column<double>(type: "double precision", nullable: true, comment: "Глубина забоя"),
|
Text = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
|
||||||
MessageText = table.Column<string>(type: "varchar(512)", nullable: false, comment: "Текст сообщения"),
|
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы, к которой относится сообщение"),
|
||||||
SystemId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id системы автобурения, к которой относится сообщение"),
|
EventState = table.Column<int>(type: "integer", nullable: false, comment: "Статус события")
|
||||||
UserId = table.Column<Guid>(type: "uuid", nullable: false, comment: "Id пользователя за пультом бурильщика")
|
|
||||||
},
|
},
|
||||||
constraints: table =>
|
constraints: table =>
|
||||||
{
|
{
|
||||||
table.PrimaryKey("PK_TechMessage", x => x.EventId);
|
table.PrimaryKey("PK_TechMessage", x => x.EventId);
|
||||||
table.ForeignKey(
|
table.ForeignKey(
|
||||||
name: "FK_TechMessage_DrillingSystem_SystemId",
|
name: "FK_TechMessage_DataSourceSystem_SystemId",
|
||||||
column: x => x.SystemId,
|
column: x => x.SystemId,
|
||||||
principalTable: "DrillingSystem",
|
principalTable: "DataSourceSystem",
|
||||||
principalColumn: "SystemId",
|
principalColumn: "SystemId",
|
||||||
onDelete: ReferentialAction.Cascade);
|
onDelete: ReferentialAction.Cascade);
|
||||||
});
|
});
|
||||||
@ -59,7 +58,7 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
name: "TechMessage");
|
name: "TechMessage");
|
||||||
|
|
||||||
migrationBuilder.DropTable(
|
migrationBuilder.DropTable(
|
||||||
name: "DrillingSystem");
|
name: "DataSourceSystem");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,5 @@
|
|||||||
// <auto-generated />
|
// <auto-generated />
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
@ -25,31 +24,31 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
|
NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "adminpack");
|
||||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||||
|
|
||||||
modelBuilder.Entity("Persistence.Database.Entity.DrillingSystem", b =>
|
modelBuilder.Entity("Persistence.Database.Entity.DataSourceSystem", b =>
|
||||||
{
|
{
|
||||||
b.Property<Guid>("SystemId")
|
b.Property<Guid>("SystemId")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasComment("Id системы автобурения");
|
.HasComment("Id системы - источника данных");
|
||||||
|
|
||||||
b.Property<string>("Description")
|
b.Property<string>("Description")
|
||||||
.HasColumnType("text")
|
.HasColumnType("text")
|
||||||
.HasComment("Описание системы автобурения");
|
.HasComment("Описание системы - источника данных");
|
||||||
|
|
||||||
b.Property<string>("Name")
|
b.Property<string>("Name")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("varchar(256)")
|
.HasColumnType("varchar(256)")
|
||||||
.HasComment("Наименование системы автобурения");
|
.HasComment("Наименование системы - источника данных");
|
||||||
|
|
||||||
b.HasKey("SystemId");
|
b.HasKey("SystemId");
|
||||||
|
|
||||||
b.ToTable("DrillingSystem");
|
b.ToTable("DataSourceSystem");
|
||||||
});
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
|
modelBuilder.Entity("Persistence.Database.Entity.ParameterData", b =>
|
||||||
{
|
{
|
||||||
b.Property<int>("DiscriminatorId")
|
b.Property<Guid>("DiscriminatorId")
|
||||||
.HasColumnType("integer")
|
.HasColumnType("uuid")
|
||||||
.HasComment("Дискриминатор системы");
|
.HasComment("Дискриминатор системы");
|
||||||
|
|
||||||
b.Property<int>("ParameterId")
|
b.Property<int>("ParameterId")
|
||||||
@ -81,27 +80,23 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
.HasColumnType("integer")
|
.HasColumnType("integer")
|
||||||
.HasComment("Id Категории важности");
|
.HasComment("Id Категории важности");
|
||||||
|
|
||||||
b.Property<double?>("Depth")
|
b.Property<int>("EventState")
|
||||||
.HasColumnType("double precision")
|
.HasColumnType("integer")
|
||||||
.HasComment("Глубина забоя");
|
.HasComment("Статус события");
|
||||||
|
|
||||||
b.Property<string>("MessageText")
|
b.Property<Guid>("SystemId")
|
||||||
|
.HasColumnType("uuid")
|
||||||
|
.HasComment("Id системы, к которой относится сообщение");
|
||||||
|
|
||||||
|
b.Property<string>("Text")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("varchar(512)")
|
.HasColumnType("varchar(512)")
|
||||||
.HasComment("Текст сообщения");
|
.HasComment("Текст сообщения");
|
||||||
|
|
||||||
b.Property<Guid>("SystemId")
|
|
||||||
.HasColumnType("uuid")
|
|
||||||
.HasComment("Id системы автобурения, к которой относится сообщение");
|
|
||||||
|
|
||||||
b.Property<DateTimeOffset>("Timestamp")
|
b.Property<DateTimeOffset>("Timestamp")
|
||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
.HasComment("Дата возникновения");
|
.HasComment("Дата возникновения");
|
||||||
|
|
||||||
b.Property<Guid>("UserId")
|
|
||||||
.HasColumnType("uuid")
|
|
||||||
.HasComment("Id пользователя за пультом бурильщика");
|
|
||||||
|
|
||||||
b.HasKey("EventId");
|
b.HasKey("EventId");
|
||||||
|
|
||||||
b.HasIndex("SystemId");
|
b.HasIndex("SystemId");
|
||||||
@ -137,48 +132,48 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
b.Property<Guid>("Id")
|
b.Property<Guid>("Id")
|
||||||
.ValueGeneratedOnAdd()
|
.ValueGeneratedOnAdd()
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("Id");
|
.HasComment("Ключ записи");
|
||||||
|
|
||||||
b.Property<DateTimeOffset>("Creation")
|
b.Property<DateTimeOffset>("Creation")
|
||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
.HasColumnName("Creation");
|
.HasComment("Дата создания записи");
|
||||||
|
|
||||||
b.Property<double>("DepthEnd")
|
b.Property<double>("DepthEnd")
|
||||||
.HasColumnType("double precision")
|
.HasColumnType("double precision")
|
||||||
.HasColumnName("DepthEnd");
|
.HasComment("Глубина забоя на дату окончания интервала");
|
||||||
|
|
||||||
b.Property<double>("DepthStart")
|
b.Property<double>("DepthStart")
|
||||||
.HasColumnType("double precision")
|
.HasColumnType("double precision")
|
||||||
.HasColumnName("DepthStart");
|
.HasComment("Глубина забоя на дату начала интервала");
|
||||||
|
|
||||||
b.Property<Guid>("IdAuthor")
|
b.Property<Guid>("IdAuthor")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("IdAuthor");
|
.HasComment("Автор изменения");
|
||||||
|
|
||||||
b.Property<Guid>("IdDiscriminator")
|
b.Property<Guid>("IdDiscriminator")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("IdDiscriminator");
|
.HasComment("Дискриминатор таблицы");
|
||||||
|
|
||||||
b.Property<Guid?>("IdEditor")
|
b.Property<Guid?>("IdEditor")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("IdEditor");
|
.HasComment("Редактор");
|
||||||
|
|
||||||
b.Property<Guid?>("IdNext")
|
b.Property<Guid?>("IdNext")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("IdNext");
|
.HasComment("Id заменяющей записи");
|
||||||
|
|
||||||
b.Property<Guid>("IdSection")
|
b.Property<Guid>("IdSection")
|
||||||
.HasColumnType("uuid")
|
.HasColumnType("uuid")
|
||||||
.HasColumnName("IdSection");
|
.HasComment("Ключ секции");
|
||||||
|
|
||||||
b.Property<DateTimeOffset?>("Obsolete")
|
b.Property<DateTimeOffset?>("Obsolete")
|
||||||
.HasColumnType("timestamp with time zone")
|
.HasColumnType("timestamp with time zone")
|
||||||
.HasColumnName("Obsolete");
|
.HasComment("Дата устаревания (например при удалении)");
|
||||||
|
|
||||||
b.Property<IDictionary<string, object>>("Value")
|
b.Property<string>("Value")
|
||||||
.IsRequired()
|
.IsRequired()
|
||||||
.HasColumnType("jsonb")
|
.HasColumnType("jsonb")
|
||||||
.HasColumnName("Value");
|
.HasComment("Значение");
|
||||||
|
|
||||||
b.HasKey("Id");
|
b.HasKey("Id");
|
||||||
|
|
||||||
@ -294,7 +289,7 @@ namespace Persistence.Database.Postgres.Migrations
|
|||||||
|
|
||||||
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
|
modelBuilder.Entity("Persistence.Database.Entity.TechMessage", b =>
|
||||||
{
|
{
|
||||||
b.HasOne("Persistence.Database.Entity.DrillingSystem", "System")
|
b.HasOne("Persistence.Database.Entity.DataSourceSystem", "System")
|
||||||
.WithMany()
|
.WithMany()
|
||||||
.HasForeignKey("SystemId")
|
.HasForeignKey("SystemId")
|
||||||
.OnDelete(DeleteBehavior.Cascade)
|
.OnDelete(DeleteBehavior.Cascade)
|
||||||
|
16
Persistence.Database/Entity/DataSourceSystem.cs
Normal file
16
Persistence.Database/Entity/DataSourceSystem.cs
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
|
||||||
|
namespace Persistence.Database.Entity;
|
||||||
|
public class DataSourceSystem
|
||||||
|
{
|
||||||
|
[Key, Comment("Id системы - источника данных")]
|
||||||
|
public Guid SystemId { get; set; }
|
||||||
|
|
||||||
|
[Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы - источника данных")]
|
||||||
|
public required string Name { get; set; }
|
||||||
|
|
||||||
|
[Comment("Описание системы - источника данных")]
|
||||||
|
public string? Description { get; set; }
|
||||||
|
}
|
@ -1,16 +0,0 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using System.ComponentModel.DataAnnotations;
|
|
||||||
using System.ComponentModel.DataAnnotations.Schema;
|
|
||||||
|
|
||||||
namespace Persistence.Database.Entity;
|
|
||||||
public class DrillingSystem
|
|
||||||
{
|
|
||||||
[Key, Comment("Id системы автобурения")]
|
|
||||||
public Guid SystemId { get; set; }
|
|
||||||
|
|
||||||
[Required, Column(TypeName = "varchar(256)"), Comment("Наименование системы автобурения")]
|
|
||||||
public required string Name { get; set; }
|
|
||||||
|
|
||||||
[Comment("Описание системы автобурения")]
|
|
||||||
public string? Description { get; set; }
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.ComponentModel.DataAnnotations.Schema;
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
|
||||||
@ -15,19 +15,16 @@ namespace Persistence.Database.Entity
|
|||||||
[Comment("Дата возникновения")]
|
[Comment("Дата возникновения")]
|
||||||
public DateTimeOffset Timestamp { get; set; }
|
public DateTimeOffset Timestamp { get; set; }
|
||||||
|
|
||||||
[Comment("Глубина забоя")]
|
[Column(TypeName = "varchar(512)"), Comment("Текст сообщения")]
|
||||||
public double? Depth { get; set; }
|
public required string Text { get; set; }
|
||||||
|
|
||||||
[Column(TypeName = "varchar(512)"), Comment("Текст сообщения")]
|
[Required, Comment("Id системы, к которой относится сообщение")]
|
||||||
public required string MessageText { get; set; }
|
public required Guid SystemId { get; set; }
|
||||||
|
|
||||||
[Required, Comment("Id системы автобурения, к которой относится сообщение")]
|
[Required, ForeignKey(nameof(SystemId)), Comment("Система, к которой относится сообщение")]
|
||||||
public required Guid SystemId { get; set; }
|
public virtual required DataSourceSystem System { get; set; }
|
||||||
|
|
||||||
[Required, ForeignKey(nameof(SystemId)), Comment("Система автобурения, к которой относится сообщение")]
|
[Comment("Статус события")]
|
||||||
public virtual required DrillingSystem System { get; set; }
|
public int EventState { get; set; }
|
||||||
|
}
|
||||||
[Comment("Id пользователя за пультом бурильщика")]
|
|
||||||
public Guid UserId { get; set; }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,9 @@ public class PersistenceDbContext : DbContext
|
|||||||
|
|
||||||
public DbSet<ParameterData> ParameterData => Set<ParameterData>();
|
public DbSet<ParameterData> ParameterData => Set<ParameterData>();
|
||||||
|
|
||||||
public PersistenceDbContext(DbContextOptions options)
|
public DbSet<DataSourceSystem> DataSourceSystem => Set<DataSourceSystem>();
|
||||||
|
|
||||||
|
public PersistenceDbContext(DbContextOptions options)
|
||||||
: base(options)
|
: base(options)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
@ -0,0 +1,82 @@
|
|||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Persistence.Client;
|
||||||
|
using Persistence.Client.Clients;
|
||||||
|
using Persistence.Client.Clients.Interfaces;
|
||||||
|
using Persistence.Database.Entity;
|
||||||
|
using Persistence.Models;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace Persistence.IntegrationTests.Controllers
|
||||||
|
{
|
||||||
|
public class DataSourceSystemControllerTest : BaseIntegrationTest
|
||||||
|
{
|
||||||
|
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
|
||||||
|
private readonly IDataSourceSystemClient dataSourceSystemClient;
|
||||||
|
private readonly IMemoryCache memoryCache;
|
||||||
|
public DataSourceSystemControllerTest(WebAppFactoryFixture factory) : base(factory)
|
||||||
|
{
|
||||||
|
var scope = factory.Services.CreateScope();
|
||||||
|
var persistenceClientFactory = scope.ServiceProvider
|
||||||
|
.GetRequiredService<PersistenceClientFactory>();
|
||||||
|
|
||||||
|
dataSourceSystemClient = persistenceClientFactory.GetDataSourceSystemClient();
|
||||||
|
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Get_returns_success()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
memoryCache.Remove(SystemCacheKey);
|
||||||
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
|
//act
|
||||||
|
var response = await dataSourceSystemClient.Get(CancellationToken.None);
|
||||||
|
|
||||||
|
//assert
|
||||||
|
Assert.NotNull(response);
|
||||||
|
Assert.Empty(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Get_AfterSave_returns_success()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
await Add();
|
||||||
|
|
||||||
|
//act
|
||||||
|
var response = await dataSourceSystemClient.Get(CancellationToken.None);
|
||||||
|
|
||||||
|
//assert
|
||||||
|
Assert.NotNull(response);
|
||||||
|
|
||||||
|
var expectedSystemCount = 1;
|
||||||
|
var actualSystemCount = response!.Count();
|
||||||
|
Assert.Equal(expectedSystemCount, actualSystemCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Add_returns_success()
|
||||||
|
{
|
||||||
|
await Add();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task Add()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
memoryCache.Remove(SystemCacheKey);
|
||||||
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
|
var dto = new DataSourceSystemDto()
|
||||||
|
{
|
||||||
|
SystemId = Guid.NewGuid(),
|
||||||
|
Name = "Test",
|
||||||
|
Description = "Test"
|
||||||
|
};
|
||||||
|
|
||||||
|
//act
|
||||||
|
await dataSourceSystemClient.Add(dto, CancellationToken.None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -4,34 +4,35 @@ using Persistence.Client;
|
|||||||
using Persistence.Client.Clients.Interfaces;
|
using Persistence.Client.Clients.Interfaces;
|
||||||
using Persistence.Database.Entity;
|
using Persistence.Database.Entity;
|
||||||
using Persistence.Models;
|
using Persistence.Models;
|
||||||
|
using Persistence.Models.Enumerations;
|
||||||
using Persistence.Models.Requests;
|
using Persistence.Models.Requests;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using Xunit;
|
using Xunit;
|
||||||
|
|
||||||
namespace Persistence.IntegrationTests.Controllers
|
namespace Persistence.IntegrationTests.Controllers
|
||||||
{
|
{
|
||||||
public class TechMessagesControllerTest : BaseIntegrationTest
|
public class TechMessagesControllerTest : BaseIntegrationTest
|
||||||
{
|
{
|
||||||
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey";
|
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
|
||||||
private readonly ITechMessagesClient techMessagesClient;
|
private readonly ITechMessagesClient techMessagesClient;
|
||||||
private readonly IMemoryCache memoryCache;
|
private readonly IMemoryCache memoryCache;
|
||||||
public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory)
|
public TechMessagesControllerTest(WebAppFactoryFixture factory) : base(factory)
|
||||||
{
|
{
|
||||||
var scope = factory.Services.CreateScope();
|
var scope = factory.Services.CreateScope();
|
||||||
var persistenceClientFactory = scope.ServiceProvider
|
var persistenceClientFactory = scope.ServiceProvider
|
||||||
.GetRequiredService<PersistenceClientFactory>();
|
.GetRequiredService<PersistenceClientFactory>();
|
||||||
|
|
||||||
techMessagesClient = persistenceClientFactory.GetTechMessagesClient();
|
techMessagesClient = persistenceClientFactory.GetTechMessagesClient();
|
||||||
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
|
memoryCache = scope.ServiceProvider.GetRequiredService<IMemoryCache>();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetPage_returns_success()
|
public async Task GetPage_returns_success()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
memoryCache.Remove(SystemCacheKey);
|
memoryCache.Remove(SystemCacheKey);
|
||||||
dbContext.CleanupDbSet<TechMessage>();
|
dbContext.CleanupDbSet<TechMessage>();
|
||||||
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
var requestDto = new PaginationRequest()
|
var requestDto = new PaginationRequest()
|
||||||
{
|
{
|
||||||
@ -50,18 +51,18 @@ namespace Persistence.IntegrationTests.Controllers
|
|||||||
Assert.Equal(requestDto.Take, response.Take);
|
Assert.Equal(requestDto.Take, response.Take);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetPage_AfterSave_returns_success()
|
public async Task GetPage_AfterSave_returns_success()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
var dtos = await InsertRange();
|
var dtos = await InsertRange(Guid.NewGuid());
|
||||||
var dtosCount = dtos.Count();
|
var dtosCount = dtos.Count();
|
||||||
var requestDto = new PaginationRequest()
|
var requestDto = new PaginationRequest()
|
||||||
{
|
{
|
||||||
Skip = 0,
|
Skip = 0,
|
||||||
Take = 2,
|
Take = 2,
|
||||||
SortSettings = nameof(TechMessage.CategoryId)
|
SortSettings = nameof(TechMessage.CategoryId)
|
||||||
};
|
};
|
||||||
|
|
||||||
//act
|
//act
|
||||||
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
|
var response = await techMessagesClient.GetPage(requestDto, CancellationToken.None);
|
||||||
@ -71,17 +72,18 @@ namespace Persistence.IntegrationTests.Controllers
|
|||||||
Assert.Equal(dtosCount, response.Count);
|
Assert.Equal(dtosCount, response.Count);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InsertRange_returns_success()
|
public async Task InsertRange_returns_success()
|
||||||
{
|
{
|
||||||
await InsertRange();
|
await InsertRange(Guid.NewGuid());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task InsertRange_returns_BadRequest()
|
public async Task InsertRange_returns_BadRequest()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
|
const string exceptionMessage = "Ошибка валидации, формата или маршрутизации запроса";
|
||||||
|
var systemId = Guid.NewGuid();
|
||||||
var dtos = new List<TechMessageDto>()
|
var dtos = new List<TechMessageDto>()
|
||||||
{
|
{
|
||||||
new TechMessageDto()
|
new TechMessageDto()
|
||||||
@ -89,17 +91,15 @@ namespace Persistence.IntegrationTests.Controllers
|
|||||||
EventId = Guid.NewGuid(),
|
EventId = Guid.NewGuid(),
|
||||||
CategoryId = -1, // < 0
|
CategoryId = -1, // < 0
|
||||||
Timestamp = DateTimeOffset.UtcNow,
|
Timestamp = DateTimeOffset.UtcNow,
|
||||||
Depth = -1, // < 0
|
Text = string.Empty, // length < 0
|
||||||
MessageText = string.Empty, // length < 0
|
EventState = EventState.Triggered
|
||||||
System = string.Concat(Enumerable.Repeat(nameof(TechMessageDto.System), 100)), // length > 256
|
}
|
||||||
UserId = Guid.NewGuid()
|
};
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
//act
|
//act
|
||||||
var response = await techMessagesClient.AddRange(dtos, new CancellationToken());
|
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@ -108,102 +108,97 @@ namespace Persistence.IntegrationTests.Controllers
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetSystems_returns_success()
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
memoryCache.Remove(SystemCacheKey);
|
|
||||||
dbContext.CleanupDbSet<TechMessage>();
|
|
||||||
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
|
|
||||||
|
|
||||||
//act
|
|
||||||
var response = await techMessagesClient.GetSystems(CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
|
||||||
Assert.NotNull(response);
|
|
||||||
Assert.Empty(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetSystems_AfterSave_returns_success()
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
var dtos = await InsertRange();
|
|
||||||
var systems = dtos
|
|
||||||
.Select(e => e.System)
|
|
||||||
.Distinct()
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
//act
|
|
||||||
var response = await techMessagesClient.GetSystems(CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
|
||||||
Assert.NotNull(response);
|
|
||||||
string?[]? content = response?.ToArray();
|
|
||||||
Assert.Equal(systems, content);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetStatistics_returns_success()
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
memoryCache.Remove(SystemCacheKey);
|
|
||||||
dbContext.CleanupDbSet<TechMessage>();
|
|
||||||
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
|
|
||||||
|
|
||||||
var importantId = 1;
|
|
||||||
var autoDrillingSystem = nameof(TechMessageDto.System);
|
|
||||||
|
|
||||||
//act
|
|
||||||
var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
|
||||||
Assert.NotNull(response);
|
|
||||||
Assert.Empty(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetStatistics_AfterSave_returns_success()
|
|
||||||
{
|
|
||||||
//arrange
|
|
||||||
var importantId = 0;
|
|
||||||
var autoDrillingSystem = nameof(TechMessageDto.System);
|
|
||||||
var dtos = await InsertRange();
|
|
||||||
var filteredDtos = dtos.Where(e => e.CategoryId == importantId && e.System == autoDrillingSystem);
|
|
||||||
|
|
||||||
//act
|
|
||||||
var response = await techMessagesClient.GetStatistics(autoDrillingSystem, importantId, CancellationToken.None);
|
|
||||||
|
|
||||||
//assert
|
|
||||||
Assert.NotNull(response);
|
|
||||||
var categories = response
|
|
||||||
.FirstOrDefault()?.Categories
|
|
||||||
.FirstOrDefault(e => e.Key == 0).Value;
|
|
||||||
Assert.Equal(filteredDtos.Count(), categories);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetDatesRange_returns_success()
|
public async Task GetSystems_returns_success()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
memoryCache.Remove(SystemCacheKey);
|
memoryCache.Remove(SystemCacheKey);
|
||||||
dbContext.CleanupDbSet<TechMessage>();
|
dbContext.CleanupDbSet<TechMessage>();
|
||||||
dbContext.CleanupDbSet<DrillingSystem>();
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
//act
|
//act
|
||||||
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
|
var response = await techMessagesClient.GetSystems(CancellationToken.None);
|
||||||
|
|
||||||
//assert
|
//assert
|
||||||
Assert.NotNull(response);
|
Assert.NotNull(response);
|
||||||
Assert.Equal(DateTimeOffset.MinValue, response?.From);
|
Assert.Empty(response);
|
||||||
Assert.Equal(DateTimeOffset.MaxValue, response?.To);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetDatesRange_AfterSave_returns_success()
|
public async Task GetSystems_AfterSave_returns_success()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
await InsertRange();
|
await InsertRange(Guid.NewGuid());
|
||||||
|
|
||||||
|
//act
|
||||||
|
var response = await techMessagesClient.GetSystems(CancellationToken.None);
|
||||||
|
|
||||||
|
//assert
|
||||||
|
Assert.NotNull(response);
|
||||||
|
var expectedSystemCount = 1;
|
||||||
|
Assert.Equal(expectedSystemCount, response!.Count());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetStatistics_returns_success()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
memoryCache.Remove(SystemCacheKey);
|
||||||
|
dbContext.CleanupDbSet<TechMessage>();
|
||||||
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
|
var categoryIds = new [] { 1, 2 };
|
||||||
|
var systemIds = new [] { Guid.NewGuid() };
|
||||||
|
|
||||||
|
//act
|
||||||
|
var response = await techMessagesClient.GetStatistics(systemIds, categoryIds, CancellationToken.None);
|
||||||
|
|
||||||
|
//assert
|
||||||
|
Assert.NotNull(response);
|
||||||
|
Assert.Empty(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetStatistics_AfterSave_returns_success()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
var categoryIds = new[] { 1 };
|
||||||
|
var systemId = Guid.NewGuid();
|
||||||
|
var dtos = await InsertRange(systemId);
|
||||||
|
var filteredDtos = dtos.Where(e => categoryIds.Contains(e.CategoryId));
|
||||||
|
|
||||||
|
//act
|
||||||
|
var response = await techMessagesClient.GetStatistics([systemId], categoryIds, CancellationToken.None);
|
||||||
|
|
||||||
|
//assert
|
||||||
|
Assert.NotNull(response);
|
||||||
|
Assert.NotEmpty(response);
|
||||||
|
var categories = response
|
||||||
|
.FirstOrDefault()!.Categories
|
||||||
|
.Count();
|
||||||
|
Assert.Equal(filteredDtos.Count(), categories);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetDatesRange_returns_NoContent()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
memoryCache.Remove(SystemCacheKey);
|
||||||
|
dbContext.CleanupDbSet<TechMessage>();
|
||||||
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
|
//act
|
||||||
|
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
|
||||||
|
|
||||||
|
//assert
|
||||||
|
Assert.Null(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task GetDatesRange_AfterSave_returns_success()
|
||||||
|
{
|
||||||
|
//arrange
|
||||||
|
await InsertRange(Guid.NewGuid());
|
||||||
|
|
||||||
//act
|
//act
|
||||||
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
|
var response = await techMessagesClient.GetDatesRangeAsync(CancellationToken.None);
|
||||||
@ -229,13 +224,13 @@ namespace Persistence.IntegrationTests.Controllers
|
|||||||
Assert.Empty(response);
|
Assert.Empty(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetPart_AfterSave_returns_success()
|
public async Task GetPart_AfterSave_returns_success()
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
var dateBegin = DateTimeOffset.UtcNow;
|
var dateBegin = DateTimeOffset.UtcNow;
|
||||||
var take = 1;
|
var take = 1;
|
||||||
await InsertRange();
|
await InsertRange(Guid.NewGuid());
|
||||||
|
|
||||||
//act
|
//act
|
||||||
var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
|
var response = await techMessagesClient.GetPart(dateBegin, take, CancellationToken.None);
|
||||||
@ -245,40 +240,36 @@ namespace Persistence.IntegrationTests.Controllers
|
|||||||
Assert.NotEmpty(response);
|
Assert.NotEmpty(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<IEnumerable<TechMessageDto>> InsertRange()
|
private async Task<IEnumerable<TechMessageDto>> InsertRange(Guid systemId)
|
||||||
{
|
{
|
||||||
//arrange
|
//arrange
|
||||||
memoryCache.Remove(SystemCacheKey);
|
memoryCache.Remove(SystemCacheKey);
|
||||||
dbContext.CleanupDbSet<TechMessage>();
|
dbContext.CleanupDbSet<TechMessage>();
|
||||||
dbContext.CleanupDbSet<DrillingSystem>();
|
dbContext.CleanupDbSet<DataSourceSystem>();
|
||||||
|
|
||||||
var dtos = new List<TechMessageDto>()
|
var dtos = new List<TechMessageDto>()
|
||||||
{
|
{
|
||||||
new()
|
new TechMessageDto()
|
||||||
{
|
{
|
||||||
EventId = Guid.NewGuid(),
|
EventId = Guid.NewGuid(),
|
||||||
CategoryId = 1,
|
CategoryId = 1,
|
||||||
Timestamp = DateTimeOffset.UtcNow,
|
Timestamp = DateTimeOffset.UtcNow,
|
||||||
Depth = 1.11,
|
Text = nameof(TechMessageDto.Text),
|
||||||
MessageText = nameof(TechMessageDto.MessageText),
|
EventState = Models.Enumerations.EventState.Triggered
|
||||||
System = nameof(TechMessageDto.System).ToLower(),
|
},
|
||||||
UserId = Guid.NewGuid()
|
new TechMessageDto()
|
||||||
},
|
{
|
||||||
new()
|
EventId = Guid.NewGuid(),
|
||||||
{
|
CategoryId = 2,
|
||||||
EventId = Guid.NewGuid(),
|
Timestamp = DateTimeOffset.UtcNow,
|
||||||
CategoryId = 2,
|
Text = nameof(TechMessageDto.Text),
|
||||||
Timestamp = DateTimeOffset.UtcNow,
|
EventState = Models.Enumerations.EventState.Triggered
|
||||||
Depth = 2.22,
|
}
|
||||||
MessageText = nameof(TechMessageDto.MessageText),
|
};
|
||||||
System = nameof(TechMessageDto.System).ToLower(),
|
|
||||||
UserId = Guid.NewGuid()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
//act
|
//act
|
||||||
var response = await techMessagesClient.AddRange(dtos, CancellationToken.None);
|
var response = await techMessagesClient.AddRange(systemId, dtos, CancellationToken.None);
|
||||||
|
|
||||||
//assert
|
//assert
|
||||||
Assert.Equal(dtos.Count, response);
|
Assert.Equal(dtos.Count, response);
|
||||||
|
@ -34,7 +34,8 @@ public static class DependencyInjection
|
|||||||
services.AddTransient<ITimestampedSetRepository, TimestampedSetRepository>();
|
services.AddTransient<ITimestampedSetRepository, TimestampedSetRepository>();
|
||||||
services.AddTransient<ITechMessagesRepository, TechMessagesRepository>();
|
services.AddTransient<ITechMessagesRepository, TechMessagesRepository>();
|
||||||
services.AddTransient<IParameterRepository, ParameterRepository>();
|
services.AddTransient<IParameterRepository, ParameterRepository>();
|
||||||
|
services.AddTransient<IDataSourceSystemRepository, DataSourceSystemCachedRepository>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,36 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Persistence.Models;
|
||||||
|
|
||||||
|
namespace Persistence.Repository.Repositories;
|
||||||
|
public class DataSourceSystemCachedRepository : DataSourceSystemRepository
|
||||||
|
{
|
||||||
|
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DataSourceSystem).FullName}CacheKey";
|
||||||
|
private readonly IMemoryCache memoryCache;
|
||||||
|
private const int CacheExpirationInMinutes = 60;
|
||||||
|
private readonly TimeSpan? AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);
|
||||||
|
|
||||||
|
public DataSourceSystemCachedRepository(DbContext db, IMemoryCache memoryCache) : base(db)
|
||||||
|
{
|
||||||
|
this.memoryCache = memoryCache;
|
||||||
|
}
|
||||||
|
public override async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
|
||||||
|
{
|
||||||
|
await base.Add(dataSourceSystemDto, token);
|
||||||
|
|
||||||
|
memoryCache.Remove(SystemCacheKey);
|
||||||
|
}
|
||||||
|
public override async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
|
||||||
|
{
|
||||||
|
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async (cacheEntry) =>
|
||||||
|
{
|
||||||
|
cacheEntry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;
|
||||||
|
|
||||||
|
var dtos = await base.Get(token);
|
||||||
|
|
||||||
|
return dtos;
|
||||||
|
});
|
||||||
|
|
||||||
|
return systems!;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Mapster;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using Persistence.Database.Entity;
|
||||||
|
using Persistence.Models;
|
||||||
|
using Persistence.Repositories;
|
||||||
|
|
||||||
|
namespace Persistence.Repository.Repositories;
|
||||||
|
public class DataSourceSystemRepository : IDataSourceSystemRepository
|
||||||
|
{
|
||||||
|
protected DbContext db;
|
||||||
|
public DataSourceSystemRepository(DbContext db)
|
||||||
|
{
|
||||||
|
this.db = db;
|
||||||
|
}
|
||||||
|
protected virtual IQueryable<DataSourceSystem> GetQueryReadOnly() => db.Set<DataSourceSystem>();
|
||||||
|
|
||||||
|
public virtual async Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token)
|
||||||
|
{
|
||||||
|
var entity = dataSourceSystemDto.Adapt<DataSourceSystem>();
|
||||||
|
|
||||||
|
await db.Set<DataSourceSystem>().AddAsync(entity, token);
|
||||||
|
await db.SaveChangesAsync(token);
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token)
|
||||||
|
{
|
||||||
|
var query = GetQueryReadOnly();
|
||||||
|
var entities = await query.ToArrayAsync(token);
|
||||||
|
var dtos = entities.Select(e => e.Adapt<DataSourceSystemDto>());
|
||||||
|
|
||||||
|
return dtos;
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,7 @@
|
|||||||
using Mapster;
|
using Mapster;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
using Persistence.Database.Entity;
|
using Persistence.Database.Entity;
|
||||||
using Persistence.Models;
|
using Persistence.Models;
|
||||||
using Persistence.Models.Requests;
|
using Persistence.Models.Requests;
|
||||||
@ -9,17 +10,15 @@ using UuidExtensions;
|
|||||||
|
|
||||||
namespace Persistence.Repository.Repositories
|
namespace Persistence.Repository.Repositories
|
||||||
{
|
{
|
||||||
public class TechMessagesRepository : ITechMessagesRepository
|
public class TechMessagesRepository : ITechMessagesRepository
|
||||||
{
|
{
|
||||||
private static readonly string SystemCacheKey = $"{typeof(Database.Entity.DrillingSystem).FullName}CacheKey";
|
private readonly IDataSourceSystemRepository sourceSystemRepository;
|
||||||
private const int CacheExpirationInMinutes = 60;
|
private DbContext db;
|
||||||
private readonly IMemoryCache memoryCache;
|
|
||||||
private readonly DbContext db;
|
|
||||||
|
|
||||||
public TechMessagesRepository(DbContext db, IMemoryCache memoryCache)
|
public TechMessagesRepository(DbContext db, IDataSourceSystemRepository sourceSystemRepository)
|
||||||
{
|
{
|
||||||
this.memoryCache = memoryCache;
|
|
||||||
this.db = db;
|
this.db = db;
|
||||||
|
this.sourceSystemRepository = sourceSystemRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected virtual IQueryable<TechMessage> GetQueryReadOnly() => db.Set<TechMessage>()
|
protected virtual IQueryable<TechMessage> GetQueryReadOnly() => db.Set<TechMessage>()
|
||||||
@ -50,19 +49,18 @@ namespace Persistence.Repository.Repositories
|
|||||||
return dto;
|
return dto;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<string> autoDrillingSystem, IEnumerable<int> categoryIds, CancellationToken token)
|
public async Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> systems, IEnumerable<int> categoryIds, CancellationToken token)
|
||||||
{
|
{
|
||||||
var query = GetQueryReadOnly();
|
var query = GetQueryReadOnly();
|
||||||
var systems = autoDrillingSystem.Select(s => s.ToLower().Trim());
|
var result = await query
|
||||||
var result = await query
|
.Where(e => !systems.Any() || systems.Contains(e.System.SystemId))
|
||||||
.Where(e => !systems.Any() || systems.Contains(e.System.Name.ToLower().Trim()))
|
.GroupBy(e => e.System.SystemId, (key, group) => new
|
||||||
.GroupBy(e => e.System.Name, (key, group) => new
|
{
|
||||||
{
|
System = group.FirstOrDefault()!.System.Name,
|
||||||
System = key,
|
Categories = group
|
||||||
Categories = group
|
.Where(g => !categoryIds.Any() || categoryIds.Contains(g.CategoryId))
|
||||||
.Where(g => !categoryIds.Any() || categoryIds.Contains(g.CategoryId))
|
})
|
||||||
})
|
.ToArrayAsync(token);
|
||||||
.ToArrayAsync(token);
|
|
||||||
|
|
||||||
var entities = new List<MessagesStatisticDto>();
|
var entities = new List<MessagesStatisticDto>();
|
||||||
foreach (var e in result)
|
foreach (var e in result)
|
||||||
@ -81,27 +79,18 @@ namespace Persistence.Repository.Repositories
|
|||||||
return entities;
|
return entities;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<string>> GetSystems(CancellationToken token)
|
public async Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token)
|
||||||
{
|
{
|
||||||
var entities = await GetDrillingSystems(token);
|
await CreateSystemIfNotExist(systemId, token);
|
||||||
var result = entities.Select(e => e.Name);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<int> AddRange(IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token)
|
|
||||||
{
|
|
||||||
|
|
||||||
var entities = new List<TechMessage>();
|
var entities = new List<TechMessage>();
|
||||||
foreach (var dto in dtos)
|
foreach (var dto in dtos)
|
||||||
{
|
{
|
||||||
var entity = dto.Adapt<TechMessage>();
|
var entity = dto.Adapt<TechMessage>();
|
||||||
var systems = await GetDrillingSystems(token);
|
|
||||||
var systemId = systems.FirstOrDefault(e => e.Name.ToLower().Trim() == dto.System.ToLower().Trim())?.SystemId
|
await CreateSystemIfNotExist(systemId, token);
|
||||||
?? await CreateDrillingSystem(dto.System, token);
|
|
||||||
|
|
||||||
entity.SystemId = systemId;
|
entity.SystemId = systemId;
|
||||||
entity.UserId = userId;
|
|
||||||
|
|
||||||
entities.Add(entity);
|
entities.Add(entity);
|
||||||
}
|
}
|
||||||
@ -125,54 +114,50 @@ namespace Persistence.Repository.Repositories
|
|||||||
return dtos;
|
return dtos;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token)
|
public async Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token)
|
||||||
{
|
{
|
||||||
var query = GetQueryReadOnly()
|
var systems = await sourceSystemRepository.Get(token);
|
||||||
.GroupBy(e => 1)
|
|
||||||
.Select(group => new
|
return systems!;
|
||||||
{
|
}
|
||||||
Min = group.Min(e => e.Timestamp),
|
|
||||||
Max = group.Max(e => e.Timestamp),
|
public async Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token)
|
||||||
});
|
{
|
||||||
var values = await query.FirstOrDefaultAsync(token);
|
var query = GetQueryReadOnly()
|
||||||
var result = new DatesRangeDto()
|
.GroupBy(e => 1)
|
||||||
{
|
.Select(group => new
|
||||||
From = values?.Min ?? DateTimeOffset.MinValue,
|
{
|
||||||
To = values?.Max ?? DateTimeOffset.MaxValue
|
Min = group.Min(e => e.Timestamp),
|
||||||
};
|
Max = group.Max(e => e.Timestamp),
|
||||||
|
});
|
||||||
|
|
||||||
|
var values = await query.FirstOrDefaultAsync(token);
|
||||||
|
if (values == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var result = new DatesRangeDto()
|
||||||
|
{
|
||||||
|
From = values?.Min ?? DateTimeOffset.MinValue,
|
||||||
|
To = values?.Max ?? DateTimeOffset.MaxValue
|
||||||
|
};
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<IEnumerable<Models.DrillingSystemDto>> GetDrillingSystems(CancellationToken token)
|
private async Task CreateSystemIfNotExist(Guid systemId, CancellationToken token)
|
||||||
{
|
{
|
||||||
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async f =>
|
var systems = await sourceSystemRepository.Get(token);
|
||||||
{
|
var system = systems?.FirstOrDefault(e => e.SystemId == systemId);
|
||||||
f.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CacheExpirationInMinutes);
|
|
||||||
|
|
||||||
var query = db.Set<Database.Entity.DrillingSystem>();
|
if (system == null)
|
||||||
var entities = await query.ToListAsync(token);
|
{
|
||||||
var dtos = entities.Select(e => e.Adapt<Models.DrillingSystemDto>());
|
system = new DataSourceSystemDto()
|
||||||
|
{
|
||||||
return dtos;
|
SystemId = systemId,
|
||||||
});
|
Name = string.Empty
|
||||||
|
};
|
||||||
return systems!;
|
await sourceSystemRepository.Add(system, token);
|
||||||
}
|
}
|
||||||
private async Task<Guid> CreateDrillingSystem(string name, CancellationToken token)
|
}
|
||||||
{
|
}
|
||||||
memoryCache.Remove(SystemCacheKey);
|
|
||||||
|
|
||||||
var entity = new DrillingSystem()
|
|
||||||
{
|
|
||||||
SystemId = Uuid7.Guid(),
|
|
||||||
Name = name.ToLower().Trim()
|
|
||||||
};
|
|
||||||
|
|
||||||
await db.Set<DrillingSystem>().AddAsync(entity, token);
|
|
||||||
await db.SaveChangesAsync(token);
|
|
||||||
|
|
||||||
return entity.SystemId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
namespace Persistence.Models;
|
namespace Persistence.Models;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Модель системы автобурения
|
/// Модель системы - источника данных
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class DrillingSystemDto
|
public class DataSourceSystemDto
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Ключ
|
/// Ключ
|
||||||
@ -13,7 +13,7 @@ public class DrillingSystemDto
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Наименование
|
/// Наименование
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required string Name { get; set; }
|
public required string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Описание
|
/// Описание
|
6
Persistence/Models/Enumerations/EventState.cs
Normal file
6
Persistence/Models/Enumerations/EventState.cs
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
namespace Persistence.Models.Enumerations;
|
||||||
|
public enum EventState
|
||||||
|
{
|
||||||
|
NotTriggered = 0,
|
||||||
|
Triggered = 1,
|
||||||
|
}
|
@ -1,4 +1,5 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Persistence.Models.Enumerations;
|
||||||
|
|
||||||
namespace Persistence.Models
|
namespace Persistence.Models
|
||||||
{
|
{
|
||||||
@ -24,29 +25,16 @@ namespace Persistence.Models
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public DateTimeOffset Timestamp { get; set; }
|
public DateTimeOffset Timestamp { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Глубина забоя
|
/// Текст сообщения
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Range(0, double.MaxValue, ErrorMessage = "Глубина забоя не может быть меньше 0")]
|
[Required]
|
||||||
public double? Depth { get; set; }
|
[StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")]
|
||||||
|
public required string Text { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Текст сообщения
|
/// Статус события
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Required]
|
public EventState EventState { get; set; }
|
||||||
[StringLength(512, MinimumLength = 1, ErrorMessage = "Допустимая длина текста сообщения от 1 до 512 символов")]
|
}
|
||||||
public required string MessageText { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Система автобурения, к которой относится сообщение
|
|
||||||
/// </summary>
|
|
||||||
[Required]
|
|
||||||
[StringLength(256, MinimumLength = 1, ErrorMessage = "Допустимая длина наименования системы АБ от 1 до 256 символов")]
|
|
||||||
public required string System { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Id пользователя за пультом бурильщика
|
|
||||||
/// </summary>
|
|
||||||
public Guid UserId { get; set; }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
22
Persistence/Repositories/IDataSourceSystemRepository.cs
Normal file
22
Persistence/Repositories/IDataSourceSystemRepository.cs
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
using Persistence.Models;
|
||||||
|
|
||||||
|
namespace Persistence.Repositories;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Интерфейс по работе с системами - источниками данных
|
||||||
|
/// </summary>
|
||||||
|
public interface IDataSourceSystemRepository
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Добавить систему
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="dataSourceSystemDto"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task Add(DataSourceSystemDto dataSourceSystemDto, CancellationToken token);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить список систем
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
public Task<IEnumerable<DataSourceSystemDto>> Get(CancellationToken token);
|
||||||
|
}
|
@ -22,14 +22,14 @@ namespace Persistence.Repositories
|
|||||||
/// <param name="dtos"></param>
|
/// <param name="dtos"></param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<int> AddRange(IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token);
|
Task<int> AddRange(Guid systemId, IEnumerable<TechMessageDto> dtos, Guid userId, CancellationToken token);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получение списка уникальных названий систем АБ
|
/// Получение списка систем
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IEnumerable<string>> GetSystems(CancellationToken token);
|
Task<IEnumerable<DataSourceSystemDto>> GetSystems(CancellationToken token);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получение количества сообщений по категориям и системам автобурения
|
/// Получение количества сообщений по категориям и системам автобурения
|
||||||
@ -38,7 +38,7 @@ namespace Persistence.Repositories
|
|||||||
/// <param name="autoDrillingSystem">Система автобурения</param>
|
/// <param name="autoDrillingSystem">Система автобурения</param>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<string> autoDrillingSystem, IEnumerable<int> categoryIds, CancellationToken token);
|
Task<IEnumerable<MessagesStatisticDto>> GetStatistics(IEnumerable<Guid> autoDrillingSystem, IEnumerable<int> categoryIds, CancellationToken token);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Получить порцию записей, начиная с заданной даты
|
/// Получить порцию записей, начиная с заданной даты
|
||||||
@ -54,6 +54,6 @@ namespace Persistence.Repositories
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="token"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
Task<DatesRangeDto> GetDatesRangeAsync(CancellationToken token);
|
Task<DatesRangeDto?> GetDatesRangeAsync(CancellationToken token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user