diff --git a/AsbCloudApp/Requests/MessageRequest.cs b/AsbCloudApp/Requests/MessageRequest.cs new file mode 100644 index 00000000..8f7f06f6 --- /dev/null +++ b/AsbCloudApp/Requests/MessageRequest.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; + +namespace AsbCloudApp.Requests +{ +#nullable enable + /// + /// параметры для запроса списка сообщений + /// + public class MessageRequestBase : RequestBase + { + /// + /// категория + /// + public IEnumerable? Categoryids { get; set; } + + + /// + /// начальная дата + /// + public DateTime? Begin { get; set; } + + /// + /// конечная дата + /// + public DateTime? End { get; set; } + + /// + /// строка поиска + /// + public string? SearchString { get; set; } + + } + + /// + /// параметры для запроса списка сообщений (с id скважины) + /// + public class MessageRequest : MessageRequestBase + { + + /// + /// id скважины + /// + public int IdWell { get; set; } + + /// + /// параметры для запроса списка сообщений (с id скважины) + /// + /// + /// + 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; + } + + } +} diff --git a/AsbCloudApp/Services/IMessageService.cs b/AsbCloudApp/Services/IMessageService.cs index 0b2261a4..b3abd842 100644 --- a/AsbCloudApp/Services/IMessageService.cs +++ b/AsbCloudApp/Services/IMessageService.cs @@ -1,5 +1,6 @@ using AsbCloudApp.Data; using AsbCloudApp.Data.SAUB; +using AsbCloudApp.Requests; using System; using System.Collections.Generic; using System.Threading; @@ -15,20 +16,10 @@ namespace AsbCloudApp.Services /// /// Получить сообщения по параметрам /// - /// - /// - /// - /// - /// - /// - /// + /// /// /// - Task> GetMessagesAsync(int idWell, - IEnumerable categoryids = default, DateTime begin = default, - DateTime end = default, string searchString = default, - int skip = 0, int take = 32, - CancellationToken token = default); + Task> GetMessagesAsync(MessageRequest request, CancellationToken token); /// /// Метод для сохранения сообщения от панели diff --git a/AsbCloudInfrastructure/Services/SAUB/MessageService.cs b/AsbCloudInfrastructure/Services/SAUB/MessageService.cs index 1911029a..cd4a1749 100644 --- a/AsbCloudInfrastructure/Services/SAUB/MessageService.cs +++ b/AsbCloudInfrastructure/Services/SAUB/MessageService.cs @@ -1,6 +1,8 @@ using AsbCloudApp.Data; using AsbCloudApp.Data.SAUB; +using AsbCloudApp.Requests; using AsbCloudApp.Services; +using AsbCloudDb; using AsbCloudDb.Model; using AsbCloudInfrastructure.EfCache; using Mapster; @@ -11,6 +13,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +#nullable enable namespace AsbCloudInfrastructure.Services.SAUB { public class MessageService : IMessageService @@ -24,41 +27,39 @@ namespace AsbCloudInfrastructure.Services.SAUB this.telemetryService = telemetryService; } - public async Task> GetMessagesAsync( - int idWell, - IEnumerable categoryids = default, - DateTime begin = default, - DateTime end = default, - string searchString = default, - int skip = 0, - int take = 32, - CancellationToken token = default) + public async Task> GetMessagesAsync(MessageRequest request, CancellationToken token) { - var idTelemetry = telemetryService.GetOrDefaultIdTelemetryByIdWell(idWell); + var result = new PaginationContainer + { + Skip = request.Skip ?? 0, + Take = request.Take ?? 32, + }; + + var idTelemetry = telemetryService.GetOrDefaultIdTelemetryByIdWell(request.IdWell); if (idTelemetry is null) - return null; + return result; var allEvents = await db.TelemetryEvents.FromCacheAsync(token); var events = allEvents.Where(e => e.IdTelemetry == idTelemetry); if (!events.Any()) - return null; + return result; var query = db.TelemetryMessages.Where(m => m.IdTelemetry == idTelemetry) .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)) - events = events.Where(e => e.MessageTemplate.Contains(searchString, StringComparison.OrdinalIgnoreCase)); + if (!string.IsNullOrEmpty(request.SearchString)) + events = events.Where(e => e.MessageTemplate.Contains(request.SearchString, StringComparison.OrdinalIgnoreCase)); - if (categoryids?.Any() == true) - events = events.Where(e => categoryids.ToList().Contains(e.IdCategory)); + if (request.Categoryids?.Any() == true) + events = events.Where(e => request.Categoryids.ToList().Contains(e.IdCategory)); var eventIds = events.Select(e => e.IdEvent); if (!eventIds.Any()) - return null; + return result; query = query.Where(m => eventIds.Contains(m.IdEvent)); } @@ -67,30 +68,27 @@ namespace AsbCloudInfrastructure.Services.SAUB 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); } - 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); } - var result = new PaginationContainer + result.Count = query.Count(); + + if (request.SortFields?.Any() == true) { - Skip = skip, - Take = take, - Count = query.Count() - }; - - if (skip > 0) - query = query.Skip(skip); - - var messagesList = await query.Take(take).AsNoTracking() - .ToListAsync(token).ConfigureAwait(false); + query = query.SortBy(request.SortFields); + } + var messagesList = await query.Skip(result.Skip) + .Take(result.Take).AsNoTracking() + .ToListAsync(token).ConfigureAwait(false); if (messagesList.Count == 0) return result; @@ -98,6 +96,9 @@ namespace AsbCloudInfrastructure.Services.SAUB var allUsers = await db.TelemetryUsers.FromCacheAsync(token); 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) { var messageDto = new MessageDto @@ -110,17 +111,15 @@ namespace AsbCloudInfrastructure.Services.SAUB 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(); } else messageDto.User = message.IdTelemetryUser.ToString(); } - var e = events.FirstOrDefault(e => e.IdEvent == message.IdEvent); - if (e != null) + if (eventsDict.TryGetValue(message.IdEvent, out TelemetryEvent? e)) { messageDto.CategoryId = e.IdCategory; messageDto.Message = e.MakeMessageText(message); @@ -136,7 +135,7 @@ namespace AsbCloudInfrastructure.Services.SAUB CancellationToken token = default) { if (!dtos.Any()) - return null; + return Task.CompletedTask; var telemetryId = telemetryService.GetOrCreateTelemetryIdByUid(uid); var timezone = telemetryService.GetTimezone(telemetryId); @@ -154,3 +153,4 @@ namespace AsbCloudInfrastructure.Services.SAUB } } } +#nullable disable diff --git a/AsbCloudWebApi/Controllers/SAUB/MessageController.cs b/AsbCloudWebApi/Controllers/SAUB/MessageController.cs index 00f6fd6e..89c40692 100644 --- a/AsbCloudWebApi/Controllers/SAUB/MessageController.cs +++ b/AsbCloudWebApi/Controllers/SAUB/MessageController.cs @@ -1,4 +1,5 @@ using AsbCloudApp.Data; +using AsbCloudApp.Requests; using AsbCloudApp.Services; using Microsoft.AspNetCore.Mvc; using System; @@ -28,29 +29,30 @@ namespace AsbCloudWebApi.Controllers.SAUB /// Выдает список сообщений по скважине /// /// id скважины - /// список категорий - /// дата начала - /// окончание - /// для пагинации кол-во записей пропустить - /// для пагинации кол-во записей - /// Строка поиска + /// Параметры запроса /// Токен для отмены задачи /// список сообщений по скважине [HttpGet] [Permission] [ProducesResponseType(typeof(PaginationContainer), (int)System.Net.HttpStatusCode.OK)] - public async Task GetMessagesAsync(int idWell, int skip = 0, int take = 32, - [FromQuery] IEnumerable categoryids = default, - DateTime begin = default, DateTime end = default, - string searchString = default, - CancellationToken token = default) + public async Task GetMessagesAsync( + [FromRoute] int idWell, + [FromQuery] MessageRequestBase request, + 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"); - var result = await messageService.GetMessagesAsync(idWell, - categoryids, begin, end, searchString, - skip, take, token).ConfigureAwait(false); + var requestToService = new MessageRequest(request, idWell); + + var result = await messageService.GetMessagesAsync( + requestToService, + token) + .ConfigureAwait(false); if (result is null || result.Count == 0) return NoContent(); @@ -85,5 +87,15 @@ namespace AsbCloudWebApi.Controllers.SAUB return Ok(wellMessagesDatesRange); } + + protected async Task 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; + } } }