DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/WellOperationController.cs

366 lines
16 KiB
C#
Raw Normal View History

using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers
{
/// <summary>
2022-06-16 17:37:10 +05:00
/// Буровые операции (вводимые вручную)
/// </summary>
2021-08-17 09:39:05 +05:00
[Route("api/well/{idWell}/wellOperations")]
[ApiController]
[Authorize]
public class WellOperationController : ControllerBase
{
private readonly IWellOperationService operationService;
private readonly IWellService wellService;
private readonly IWellOperationImportService wellOperationImportService;
public WellOperationController(IWellOperationService operationService, IWellService wellService, IWellOperationImportService wellOperationImportService)
{
this.operationService = operationService;
this.wellService = wellService;
this.wellOperationImportService = wellOperationImportService;
}
/// <summary>
/// Возвращает словарь типов секций
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("sectionTypes")]
[Permission]
[ProducesResponseType(typeof(IDictionary<int, string>), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetSectionTypes()
{
var result = operationService.GetSectionTypes();
return Ok(result);
}
2022-04-11 18:00:34 +05:00
/// <summary>
/// Возвращает список имен типов операций на скважине
/// </summary>
/// <returns></returns>
[HttpGet]
2021-08-17 09:39:05 +05:00
[Route("categories")]
[Permission]
[ProducesResponseType(typeof(IEnumerable<WellOperationCategoryDto>), (int)System.Net.HttpStatusCode.OK)]
2021-08-17 09:39:05 +05:00
public IActionResult GetCategories()
{
var result = operationService.GetCategories();
return Ok(result);
}
/// <summary>
/// Отфильтрованный список операций на скважине. Если не применять фильтр, то вернется весь список. Сортированный по глубине затем по дате
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="opertaionType">фильтр по план = 0, факт = 1</param>
/// <param name="sectionTypeIds">фильтр по списку id конструкций секции</param>
/// <param name="operationCategoryIds">фильтр по списку id категорий операции</param>
/// <param name="begin">фильтр по началу операции</param>
/// <param name="end">фильтр по окончанию операции</param>
/// <param name="minDepth">фильтр по минимальной глубине скважины</param>
/// <param name="maxDepth">фильтр по максимальной глубине скважины</param>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <param name="token"></param>
/// <returns>Список операций на скважине в контейнере для постраничного просмотра</returns>
[HttpGet]
[Permission]
[ProducesResponseType(typeof(PaginationContainer<WellOperationDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetOperationsAsync(
2021-08-28 22:34:57 +05:00
[FromRoute] int idWell,
[FromQuery] int? opertaionType = default,
[FromQuery] IEnumerable<int> sectionTypeIds = default,
[FromQuery] IEnumerable<int> operationCategoryIds = default,
2021-08-28 22:34:57 +05:00
[FromQuery] DateTime begin = default,
[FromQuery] DateTime end = default,
[FromQuery] double minDepth = double.MinValue,
[FromQuery] double maxDepth = double.MaxValue,
[FromQuery] int skip = 0,
[FromQuery] int take = 32,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await operationService.GetOperationsAsync(
idWell,
opertaionType,
sectionTypeIds,
operationCategoryIds,
begin,
end,
minDepth,
maxDepth,
skip,
take,
token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Статистика операций по скважине, группированая по категориям
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="opertaionType"></param>
/// <param name="sectionTypeIds"></param>
/// <param name="operationCategoryIds"></param>
/// <param name="begin"></param>
/// <param name="end"></param>
/// <param name="minDepth"></param>
/// <param name="maxDepth"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
[Route("groupStat")]
[Permission]
[ProducesResponseType(typeof(IEnumerable<WellGroupOpertionDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetGroupOperationsAsync(
[FromRoute] int idWell,
[FromQuery] int? opertaionType = default,
[FromQuery] IEnumerable<int> sectionTypeIds = default,
[FromQuery] IEnumerable<int> operationCategoryIds = default,
[FromQuery] DateTime begin = default,
[FromQuery] DateTime end = default,
[FromQuery] double minDepth = double.MinValue,
[FromQuery] double maxDepth = double.MaxValue,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await operationService.GetGroupOperationsStatAsync(
idWell,
opertaionType,
sectionTypeIds,
operationCategoryIds,
begin,
end,
minDepth,
maxDepth,
token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Возвращает нужную операцию на скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="idOperation">id нужной операции</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Нужную операцию на скважине</returns>
[HttpGet]
[Route("{idOperation}")]
[Permission]
[ProducesResponseType(typeof(WellOperationDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetAsync(int idWell, int idOperation,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
2022-12-07 09:02:04 +05:00
var result = await operationService.GetOrDefaultAsync(idOperation, token).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Добавляет новые операции на скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="values">Данные о добавляемых операциях</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Количество добавленных в БД строк</returns>
[HttpPost]
[Permission]
[ProducesResponseType(typeof(IEnumerable<WellOperationDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> InsertRangeAsync(int idWell, [FromBody] IEnumerable<WellOperationDto> values,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await operationService.InsertRangeAsync(idWell, values, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Обновляет выбранную операцию на скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="idOperation">id выбранной операции</param>
/// <param name="value">Новые данные для выбранной операции</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Количество обновленных в БД строк</returns>
[HttpPut("{idOperation}")]
[Permission]
[ProducesResponseType(typeof(WellOperationDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateAsync(int idWell, int idOperation,
[FromBody] WellOperationDto value, CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await operationService.UpdateAsync(idWell, idOperation, value, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Удаляет выбранную операцию на скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="idOperation">id выбранной операции</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Количество удаленных из БД строк</returns>
[HttpDelete("{idOperation}")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteAsync(int idWell, int idOperation, CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
var result = await operationService.DeleteAsync(new int[] { idOperation }, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Импортирует операции из excel (xlsx) файла
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="options">Удалить операции перед импортом = 1, если фал валидный</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns></returns>
[HttpPost]
[Permission]
[Route("import/{options}")]
2022-04-11 18:00:34 +05:00
public async Task<IActionResult> ImportAsync(int idWell,
[FromForm] IFormFileCollection files,
int options = 0,
CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
int? idUser = User.GetUserId();
if (idCompany is null || idUser is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
if (files.Count < 1)
return BadRequest("нет файла");
var file = files[0];
2022-04-11 18:00:34 +05:00
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return BadRequest("Требуется xlsx файл.");
using Stream stream = file.OpenReadStream();
try
{
wellOperationImportService.Import(idWell, stream, (options & 1) > 0);
}
2022-04-11 18:00:34 +05:00
catch (FileFormatException ex)
{
return BadRequest(ex.Message);
}
2022-04-11 18:00:34 +05:00
return Ok();
}
/// <summary>
/// Создает excel файл с операциями по скважине
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("export")]
[Permission]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> ExportAsync([FromRoute] int idWell, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var stream = wellOperationImportService.Export(idWell);
var fileName = await wellService.GetWellCaptionByIdAsync(idWell, token) + "_operations.xlsx";
return File(stream, "application/octet-stream", fileName);
2022-03-17 16:56:13 +05:00
}
/// <summary>
/// Создает excel файл с "сетевым графиком"
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="scheduleReportService"></param>
/// <param name="token"> Токен отмены задачи</param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("scheduleReport")]
[Permission]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
2022-04-11 18:00:34 +05:00
public async Task<IActionResult> ScheduleReportAsync([FromRoute] int idWell, [FromServices] IScheduleReportService scheduleReportService, CancellationToken token = default)
2022-03-17 16:56:13 +05:00
{
int? idCompany = User.GetCompanyId();
if (idCompany is null)
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
var stream = await scheduleReportService.MakeReportAsync(idWell, token);
var fileName = await wellService.GetWellCaptionByIdAsync(idWell, token) + "_ScheduleReport.xlsx";
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Возвращает шаблон файла импорта
/// </summary>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("template")]
[AllowAnonymous]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
public IActionResult GetTamplate()
{
var stream = wellOperationImportService.GetExcelTemplateStream();
var fileName = "ЕЦП_шаблон_файла_операций.xlsx";
return File(stream, "application/octet-stream", fileName);
}
private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token = default)
{
int? idCompany = User.GetCompanyId();
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false);
}
}
}