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

240 lines
10 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.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Controllers
{
#nullable enable
/// <summary>
/// Плановая траектория (загрузка и хранение)
/// </summary>
[Route("api/well/{idWell}/plannedTrajectory")]
[ApiController]
[Authorize]
public class PlannedTrajectoryController : ControllerBase
{
private readonly IWellService wellService;
private readonly IPlannedTrajectoryImportService plannedTrajectoryImportService;
private readonly IPlannedTrajectoryService plannedTrajectoryService;
public PlannedTrajectoryController(IWellService wellService, IPlannedTrajectoryImportService plannedTrajectoryImportService, IPlannedTrajectoryService plannedTrajectoryService)
{
this.plannedTrajectoryImportService = plannedTrajectoryImportService;
this.wellService = wellService;
this.plannedTrajectoryService = plannedTrajectoryService;
}
/// <summary>
/// Возвращает шаблон для заполнения строк плановой траектории
/// </summary>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("template")]
[AllowAnonymous]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
2022-12-25 23:16:36 +05:00
public IActionResult GetTemplate()
{
var stream = plannedTrajectoryImportService.GetTemplateFile();
var fileName = "ЕЦП_шаблон_файла_плановая_траектория.xlsx";
return File(stream, "application/octet-stream", fileName);
}
/// <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)
{
2022-12-27 00:02:49 +05:00
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
2022-12-27 00:02:49 +05:00
var stream = await plannedTrajectoryImportService.ExportAsync(idWell, token);
var fileName = plannedTrajectoryImportService.GetFileName(idWell, token);
return File(stream, "application/octet-stream", fileName);
}
/// <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]
2022-12-25 23:16:36 +05:00
[Permission]
[Route("import/{options}")]
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 (!idUser.HasValue)
return Forbid();
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];
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return BadRequest("Требуется xlsx файл.");
using Stream stream = file.OpenReadStream();
try
{
2022-12-27 00:02:49 +05:00
var result = plannedTrajectoryImportService.ImportAsync(idWell, idUser.Value, stream, token,(options & 1) > 0);
return Ok(result);
}
catch (FileFormatException ex)
{
return BadRequest(ex.Message);
2022-12-27 00:02:49 +05:00
}
}
/// <summary>
/// Получаем список всех строк координат плановой траектории (для клиента)
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet]
[Route("allRows")]
[Permission]
[ProducesResponseType(typeof(IEnumerable<PlannedTrajectoryDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetRows([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();
2022-12-27 21:45:03 +05:00
var result = plannedTrajectoryService.GetOrDefaultAsync(idWell,token);
return Ok(result);
}
/// <summary>
2022-12-27 21:45:03 +05:00
/// Добавить одну новую строчку координат для плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[Permission]
[ProducesResponseType(typeof(PlannedTrajectoryDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddRowAsync(int idWell, [FromBody] PlannedTrajectoryDto row,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
2022-12-27 21:45:03 +05:00
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
var result = await plannedTrajectoryService.AddAsync(idWell, idUser.Value, row, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Добавить массив строчек координат для плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="rows"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[Permission]
[ProducesResponseType(typeof(PlannedTrajectoryDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddRowAsync(int idWell, [FromBody] IEnumerable<PlannedTrajectoryDto> rows,
CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
var result = await plannedTrajectoryService.AddRangeAsync(idWell, idUser.Value, rows, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Изменить выбранную строку с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idRow"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPut("{idRow}")]
[Permission]
[ProducesResponseType(typeof(PlannedTrajectoryDto), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateRowAsync(int idWell, int idRow,
[FromBody] PlannedTrajectoryDto row, CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
var result = await plannedTrajectoryService.UpdateAsync(idWell, idUser.Value, idRow, row, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Удалить выбранную строку с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idRow"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpDelete("{idOperation}")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteRowAsync(int idWell, int idRow, CancellationToken token = default)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
2022-12-25 23:16:36 +05:00
var result = await plannedTrajectoryService.DeleteRangeAsync(new int[] { idRow }, token)
.ConfigureAwait(false);
return Ok(result);
}
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);
}
}
}