Merge pull request 'fix/add-sort-to-paginated-elements' (#24) from fix/add-sort-to-paginated-elements into dev

Reviewed-on: http://test.digitaldrilling.ru:8080/DDrilling/AsbCloudServer/pulls/24
This commit is contained in:
Никита Фролов 2023-02-03 11:52:07 +05:00
commit 952ce59e60
4 changed files with 134 additions and 65 deletions

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
namespace AsbCloudApp.Requests
{
#nullable enable
/// <summary>
/// параметры для запроса списка сообщений
/// </summary>
public class MessageRequestBase : RequestBase
{
/// <summary>
/// категория
/// </summary>
public IEnumerable<int>? Categoryids { get; set; }
/// <summary>
/// начальная дата
/// </summary>
public DateTime? Begin { get; set; }
/// <summary>
/// конечная дата
/// </summary>
public DateTime? End { get; set; }
/// <summary>
/// строка поиска
/// </summary>
public string? SearchString { get; set; }
}
/// <summary>
/// параметры для запроса списка сообщений (с id скважины)
/// </summary>
public class MessageRequest : MessageRequestBase
{
/// <summary>
/// id скважины
/// </summary>
public int IdWell { get; set; }
/// <summary>
/// параметры для запроса списка сообщений (с id скважины)
/// </summary>
/// <param name="request"></param>
/// <param name="idWell"></param>
public MessageRequest(MessageRequestBase request, int idWell)
{
this.IdWell = idWell;
this.Categoryids = request.Categoryids;
this.Begin = request.Begin;
this.End = request.End;
this.SearchString = request.SearchString;
this.Skip = request.Skip;
this.Take = request.Take;
this.SortFields = request.SortFields;
}
}
}

View File

@ -1,5 +1,6 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Requests;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
@ -15,20 +16,10 @@ namespace AsbCloudApp.Services
/// <summary> /// <summary>
/// Получить сообщения по параметрам /// Получить сообщения по параметрам
/// </summary> /// </summary>
/// <param name="idWell"></param> /// <param name="request"></param>
/// <param name="categoryids"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="searchString"></param>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<PaginationContainer<MessageDto>> GetMessagesAsync(int idWell, Task<PaginationContainer<MessageDto>> GetMessagesAsync(MessageRequest request, CancellationToken token);
IEnumerable<int> categoryids = default, DateTime begin = default,
DateTime end = default, string searchString = default,
int skip = 0, int take = 32,
CancellationToken token = default);
/// <summary> /// <summary>
/// Метод для сохранения сообщения от панели /// Метод для сохранения сообщения от панели

View File

@ -1,6 +1,8 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Data.SAUB; using AsbCloudApp.Data.SAUB;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using AsbCloudDb;
using AsbCloudDb.Model; using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache; using AsbCloudInfrastructure.EfCache;
using Mapster; using Mapster;
@ -11,6 +13,7 @@ using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#nullable enable
namespace AsbCloudInfrastructure.Services.SAUB namespace AsbCloudInfrastructure.Services.SAUB
{ {
public class MessageService : IMessageService public class MessageService : IMessageService
@ -24,41 +27,39 @@ namespace AsbCloudInfrastructure.Services.SAUB
this.telemetryService = telemetryService; this.telemetryService = telemetryService;
} }
public async Task<PaginationContainer<MessageDto>> GetMessagesAsync( public async Task<PaginationContainer<MessageDto>> GetMessagesAsync(MessageRequest request, CancellationToken token)
int idWell,
IEnumerable<int> categoryids = default,
DateTime begin = default,
DateTime end = default,
string searchString = default,
int skip = 0,
int take = 32,
CancellationToken token = default)
{ {
var idTelemetry = telemetryService.GetOrDefaultIdTelemetryByIdWell(idWell); var result = new PaginationContainer<MessageDto>
{
Skip = request.Skip ?? 0,
Take = request.Take ?? 32,
};
var idTelemetry = telemetryService.GetOrDefaultIdTelemetryByIdWell(request.IdWell);
if (idTelemetry is null) if (idTelemetry is null)
return null; return result;
var allEvents = await db.TelemetryEvents.FromCacheAsync(token); var allEvents = await db.TelemetryEvents.FromCacheAsync(token);
var events = allEvents.Where(e => e.IdTelemetry == idTelemetry); var events = allEvents.Where(e => e.IdTelemetry == idTelemetry);
if (!events.Any()) if (!events.Any())
return null; return result;
var query = db.TelemetryMessages.Where(m => m.IdTelemetry == idTelemetry) var query = db.TelemetryMessages.Where(m => m.IdTelemetry == idTelemetry)
.OrderBy(m => m.DateTime).AsNoTracking(); .OrderBy(m => m.DateTime).AsNoTracking();
if (categoryids?.Any() == true || !string.IsNullOrEmpty(searchString)) if (request.Categoryids?.Any() == true || !string.IsNullOrEmpty(request.SearchString))
{ {
if (!string.IsNullOrEmpty(searchString)) if (!string.IsNullOrEmpty(request.SearchString))
events = events.Where(e => e.MessageTemplate.Contains(searchString, StringComparison.OrdinalIgnoreCase)); events = events.Where(e => e.MessageTemplate.Contains(request.SearchString, StringComparison.OrdinalIgnoreCase));
if (categoryids?.Any() == true) if (request.Categoryids?.Any() == true)
events = events.Where(e => categoryids.ToList().Contains(e.IdCategory)); events = events.Where(e => request.Categoryids.ToList().Contains(e.IdCategory));
var eventIds = events.Select(e => e.IdEvent); var eventIds = events.Select(e => e.IdEvent);
if (!eventIds.Any()) if (!eventIds.Any())
return null; return result;
query = query.Where(m => eventIds.Contains(m.IdEvent)); query = query.Where(m => eventIds.Contains(m.IdEvent));
} }
@ -67,30 +68,27 @@ namespace AsbCloudInfrastructure.Services.SAUB
var timezone = telemetryService.GetTimezone(idTelemetry ?? default); var timezone = telemetryService.GetTimezone(idTelemetry ?? default);
if (begin != default) if (request.Begin is not null)
{ {
var beginUtc = begin.ToUtcDateTimeOffset(timezone.Hours); var beginUtc = request.Begin.Value.ToUtcDateTimeOffset(timezone.Hours);
query = query.Where(m => m.DateTime >= beginUtc); query = query.Where(m => m.DateTime >= beginUtc);
} }
if (end != default) if (request.End is not null)
{ {
var endUtc = end.ToUtcDateTimeOffset(timezone.Hours); var endUtc = request.End.Value.ToUtcDateTimeOffset(timezone.Hours);
query = query.Where(m => m.DateTime <= endUtc); query = query.Where(m => m.DateTime <= endUtc);
} }
var result = new PaginationContainer<MessageDto> result.Count = query.Count();
if (request.SortFields?.Any() == true)
{ {
Skip = skip, query = query.SortBy(request.SortFields);
Take = take, }
Count = query.Count() var messagesList = await query.Skip(result.Skip)
}; .Take(result.Take).AsNoTracking()
.ToListAsync(token).ConfigureAwait(false);
if (skip > 0)
query = query.Skip(skip);
var messagesList = await query.Take(take).AsNoTracking()
.ToListAsync(token).ConfigureAwait(false);
if (messagesList.Count == 0) if (messagesList.Count == 0)
return result; return result;
@ -98,6 +96,9 @@ namespace AsbCloudInfrastructure.Services.SAUB
var allUsers = await db.TelemetryUsers.FromCacheAsync(token); var allUsers = await db.TelemetryUsers.FromCacheAsync(token);
var users = allUsers.Where(u => u.IdTelemetry == idTelemetry); var users = allUsers.Where(u => u.IdTelemetry == idTelemetry);
var eventsDict = events.ToDictionary(x=>x.IdEvent, x => x);
var usersDict = users.ToDictionary(x => x.IdUser, x => x);
foreach (var message in messagesList) foreach (var message in messagesList)
{ {
var messageDto = new MessageDto var messageDto = new MessageDto
@ -110,17 +111,15 @@ namespace AsbCloudInfrastructure.Services.SAUB
if (message.IdTelemetryUser is not null) if (message.IdTelemetryUser is not null)
{ {
if (users.Any()) if (usersDict.TryGetValue((int)message.IdTelemetryUser, out TelemetryUser? user))
{ {
var user = users.FirstOrDefault(u => u.IdUser == message.IdTelemetryUser);
messageDto.User = user.MakeDisplayName(); messageDto.User = user.MakeDisplayName();
} }
else else
messageDto.User = message.IdTelemetryUser.ToString(); messageDto.User = message.IdTelemetryUser.ToString();
} }
var e = events.FirstOrDefault(e => e.IdEvent == message.IdEvent); if (eventsDict.TryGetValue(message.IdEvent, out TelemetryEvent? e))
if (e != null)
{ {
messageDto.CategoryId = e.IdCategory; messageDto.CategoryId = e.IdCategory;
messageDto.Message = e.MakeMessageText(message); messageDto.Message = e.MakeMessageText(message);
@ -136,7 +135,7 @@ namespace AsbCloudInfrastructure.Services.SAUB
CancellationToken token = default) CancellationToken token = default)
{ {
if (!dtos.Any()) if (!dtos.Any())
return null; return Task.CompletedTask;
var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid); var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid);
var timezone = telemetryService.GetTimezone(telemetryId); var timezone = telemetryService.GetTimezone(telemetryId);
@ -154,3 +153,4 @@ namespace AsbCloudInfrastructure.Services.SAUB
} }
} }
} }
#nullable disable

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests;
using AsbCloudApp.Services; using AsbCloudApp.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System; using System;
@ -28,29 +29,30 @@ namespace AsbCloudWebApi.Controllers.SAUB
/// Выдает список сообщений по скважине /// Выдает список сообщений по скважине
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="categoryids">список категорий</param> /// <param name="request">Параметры запроса</param>
/// <param name="begin">дата начала</param>
/// <param name="end">окончание</param>
/// <param name="skip">для пагинации кол-во записей пропустить</param>
/// <param name="take">для пагинации кол-во записей </param>
/// <param name="searchString"> Строка поиска </param>
/// <param name="token">Токен для отмены задачи</param> /// <param name="token">Токен для отмены задачи</param>
/// <returns>список сообщений по скважине</returns> /// <returns>список сообщений по скважине</returns>
[HttpGet] [HttpGet]
[Permission] [Permission]
[ProducesResponseType(typeof(PaginationContainer<MessageDto>), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(PaginationContainer<MessageDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetMessagesAsync(int idWell, int skip = 0, int take = 32, public async Task<IActionResult> GetMessagesAsync(
[FromQuery] IEnumerable<int> categoryids = default, [FromRoute] int idWell,
DateTime begin = default, DateTime end = default, [FromQuery] MessageRequestBase request,
string searchString = default, CancellationToken token = default)
CancellationToken token = default)
{ {
if (take > 1024)
if (!await UserHasAccesToWellAsync(idWell, token))
return Forbid();
if (request.Take > 1024)
return BadRequest("limit mast be less then 1024"); return BadRequest("limit mast be less then 1024");
var result = await messageService.GetMessagesAsync(idWell, var requestToService = new MessageRequest(request, idWell);
categoryids, begin, end, searchString,
skip, take, token).ConfigureAwait(false); var result = await messageService.GetMessagesAsync(
requestToService,
token)
.ConfigureAwait(false);
if (result is null || result.Count == 0) if (result is null || result.Count == 0)
return NoContent(); return NoContent();
@ -85,5 +87,15 @@ namespace AsbCloudWebApi.Controllers.SAUB
return Ok(wellMessagesDatesRange); return Ok(wellMessagesDatesRange);
} }
protected async Task<bool> UserHasAccesToWellAsync(int idWell, CancellationToken token)
{
var idCompany = User.GetCompanyId();
if (idCompany is not null &&
await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)
.ConfigureAwait(false))
return true;
return false;
}
} }
} }