DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/Trajectory/FactTrajectoryController.cs

209 lines
8.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services;
using AsbCloudInfrastructure.Services.Trajectory;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers.Trajectory;
/// <summary>
/// Фактическая траектория
/// </summary>
[Authorize]
[ApiController]
[Route("api/well/{idWell}/[controller]")]
public class FactTrajectoryController : ControllerBase
{
private readonly ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryFactRepository;
private readonly IWellService wellService;
private readonly FactTrajectoryImportService factTrajectoryImportService;
public FactTrajectoryController(
ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryFactRepository,
IWellService wellService,
FactTrajectoryImportService factTrajectoryImportService)
{
this.trajectoryFactRepository = trajectoryFactRepository;
this.wellService = wellService;
this.factTrajectoryImportService = factTrajectoryImportService;
}
/// <summary>
/// Метод получения всех строк фактических траекторий по id скважины
/// </summary>
/// <param name="idWell">Id скважины</param>
/// <param name="cancellationToken">Токен отмены операции</param>
/// <returns></returns>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<TrajectoryGeoFactDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetRowsAsync([FromRoute] int idWell,
CancellationToken cancellationToken)
{
var importedFactTrajectories = await trajectoryFactRepository.GetAsync(idWell,
cancellationToken);
return Ok(importedFactTrajectories);
}
/// <summary>
/// Добавить одну новую строчку координат для фактической траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="row"></param>
/// <param name="token"></param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddAsync(int idWell, [FromBody] TrajectoryGeoFactDto row,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
row.IdUser = idUser.Value;
row.IdWell = idWell;
var result = await trajectoryFactRepository.AddAsync(row, token);
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}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateAsync(int idWell, int idRow,
[FromBody] TrajectoryGeoFactDto row, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
row.Id = idRow;
row.IdUser = idUser.Value;
row.IdWell = idWell;
var result = await trajectoryFactRepository.UpdateAsync(row, token);
return Ok(result);
}
/// <summary>
/// Удалить выбранную строку с координатами
/// </summary>
/// <param name="idWell"></param>
/// <param name="idRow"></param>
/// <param name="token"></param>
/// <returns>количество успешно удаленных строк из БД</returns>
[HttpDelete("{idRow}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> DeleteAsync(int idWell, int idRow, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
var result = await trajectoryFactRepository.DeleteRangeAsync(new int[] { idRow }, token);
return Ok(result);
}
/// <summary>
/// Формируем excel файл с текущими строками фактической траектории
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>Запрашиваемый файл</returns>
[HttpGet("export")]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK, "application/octet-stream")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> ExportAsync([FromRoute] int idWell, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
var stream = await factTrajectoryImportService.ExportAsync(idWell, token);
var fileName = await factTrajectoryImportService.GetFileNameAsync(idWell, token);
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Возвращает excel шаблон для заполнения строк фактической траектории
/// </summary>
/// <returns>Запрашиваемый файл</returns>
[HttpGet("template")]
[AllowAnonymous]
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK, "application/octet-stream")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult GetTemplate()
{
var stream = factTrajectoryImportService.GetTemplateFile();
var fileName = "ЕЦП_шаблон_файлаактическая_импортируемая_траектория.xlsx";
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Импортирует координаты из excel (xlsx) файла
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="deleteBeforeImport">Удалить операции перед импортом, если фал валидный</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost("import/{deleteBeforeImport}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
public async Task<IActionResult> ImportAsync(int idWell,
[FromForm] IFormFileCollection files,
bool deleteBeforeImport,
CancellationToken token)
{
int? idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
if (!await CanUserAccessToWellAsync(idWell,
token).ConfigureAwait(false))
return Forbid();
if (files.Count < 1)
return this.ValidationBadRequest(nameof(files), "нет файла");
var file = files[0];
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
return this.ValidationBadRequest(nameof(files), "Требуется xlsx файл.");
using Stream stream = file.OpenReadStream();
try
{
var trajectoryRows = await factTrajectoryImportService.ImportAsync(idWell, idUser.Value, stream, token);
if (deleteBeforeImport)
await trajectoryFactRepository.DeleteByIdWellAsync(idWell, token);
var rowsCount = await trajectoryFactRepository.AddRangeAsync(trajectoryRows, token);
return Ok(rowsCount);
}
catch (FileFormatException ex)
{
return this.ValidationBadRequest(nameof(files), ex.Message);
}
}
private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token)
{
int? idCompany = User.GetCompanyId();
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false);
}
}