using AsbCloudApp.Data.GTR; using AsbCloudApp.Repositories; using AsbCloudApp.Services; using AsbCloudWebApi.SignalR; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading; using System.Threading.Tasks; using AsbCloudApp.Exceptions; using AsbCloudApp.Requests; using Microsoft.AspNetCore.Http; using AsbCloudApp.Data; using System; using Org.BouncyCastle.Asn1.Ocsp; namespace AsbCloudWebApi.Controllers.SAUB; [Route("api/[controller]")] [ApiController] public class GtrWitsController : ControllerBase { protected readonly IWellService wellService; private readonly ITelemetryService telemetryService; private readonly IGtrRepository gtrRepository; private readonly IHubContext telemetryHubContext; public string SignalRMethodGetDataName { get; protected set; } = "ReceiveData"; public GtrWitsController( ITelemetryService telemetryService, IGtrRepository gtrRepository, IWellService wellService, IHubContext telemetryHubContext) { this.telemetryService = telemetryService; this.gtrRepository = gtrRepository; this.wellService = wellService; this.telemetryHubContext = telemetryHubContext; } /// /// Получить значение от ГТИ /// /// /// /// /// [HttpGet] [Permission] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] public async Task GetAllAsync([Required] int idWell, [FromQuery] GtrRequest request, CancellationToken token) { await AssertUserHasAccessToWellAsync(idWell, token); var dtos = await gtrRepository.GetAsync(idWell, request, token); return Ok(dtos); } /// /// Возвращает диапазон дат за которые есть телеметрия за период времени /// /// /// /// /// /// [HttpGet("{idWell}/dateRange")] [ProducesResponseType(typeof(DatesRangeDto), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType((int)System.Net.HttpStatusCode.NotFound)] [ProducesResponseType((int)System.Net.HttpStatusCode.NoContent)] public virtual async Task> GetRangeAsync( [FromRoute] int idWell, DateTimeOffset? geDate, DateTimeOffset? leDate, CancellationToken token) { await AssertUserHasAccessToWellAsync(idWell, token); var range = await gtrRepository.GetRangeAsync(idWell, geDate, leDate, token); return Ok(range); } /// /// Получить загруженные данные ГТИ по скважине /// /// Id скважины /// Параметры запроса /// Токен завершения задачи /// [HttpGet("{idWell}")] public async Task>> GetDataAsync([Required] int idWell, [FromQuery] GtrRequest request, CancellationToken token) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token).ConfigureAwait(false); if (!isCompanyOwnsWell) return Forbid(); var content = await gtrRepository.GetAsync(idWell, request.Begin?.DateTime, request.IntervalSec, request.ApproxPointsCount, token).ConfigureAwait(false); return Ok(content); } /// /// получение последних данных ГТИ по ключу record /// /// id скважины /// id record /// /// [HttpGet("{idWell}/{idRecord}")] public async Task>> GetLastDataByRecordIdAsync(int idWell, int idRecord, CancellationToken token) { int? idCompany = User.GetCompanyId(); if (idCompany is null) return Forbid(); bool isCompanyOwnsWell = await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token).ConfigureAwait(false); if (!isCompanyOwnsWell) return Forbid(); var content = gtrRepository.GetLastDataByRecordId(idWell, idRecord); return Ok(content); } /// /// Метод для получения WITS записи от панели оператора. /// Сохраняет в БД. /// /// уникальный идентификатор телеметрии /// WITS запись /// /// [HttpPost("{uid}")] public async Task PostDataAsync( string uid, [FromBody] IEnumerable dtos, CancellationToken token) { var telemetry = telemetryService.GetOrCreateTelemetryByUid(uid); await gtrRepository.SaveDataAsync(telemetry.Id, dtos, token).ConfigureAwait(false); var idWell = telemetryService.GetIdWellByTelemetryUid(uid); if (idWell is not null && dtos is not null) _ = Task.Run(() => telemetryHubContext.Clients.Group($"well_{idWell}_gtr") .SendAsync(SignalRMethodGetDataName, dtos), CancellationToken.None); return Ok(); } private async Task AssertUserHasAccessToWellAsync(int idWell, CancellationToken token) { var idUser = User.GetUserId(); var idCompany = User.GetCompanyId(); if (!idUser.HasValue) throw new ForbidException("Нет доступа к скважине"); if (!idCompany.HasValue) throw new ForbidException("Нет доступа к скважине"); if (!await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value, idWell, token)) throw new ForbidException("Нет доступа к скважине"); } }