DD.WellWorkover.Cloud/AsbCloudWebApi/Controllers/Trajectory/TrajectoryEditableController.cs
Степанов Дмитрий 4874a9288b Рефакторинг контроллеров
1. Добавлен метод расширения для парсинга Excel файлов
2. Рефакторинг контроллеров траекторий
2024-01-29 15:39:39 +05:00

192 lines
7.4 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 AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudInfrastructure.Services.Trajectory.Export;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Data;
using AsbCloudApp.Requests.Import;
using AsbCloudInfrastructure.Services;
namespace AsbCloudWebApi.Controllers.Trajectory
{
/// <summary>
/// Плановые и фактические траектории (загрузка и хранение)
/// </summary>
[ApiController]
[Authorize]
public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>
where TDto : TrajectoryGeoDto
{
private readonly ParserServiceFactory parserServiceFactory;
private readonly TrajectoryExportService<TDto> trajectoryExportService;
private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;
protected TrajectoryEditableController(IWellService wellService,
ParserServiceFactory parserServiceFactory,
TrajectoryExportService<TDto> trajectoryExportService,
ITrajectoryEditableRepository<TDto> trajectoryRepository)
: base(
wellService,
trajectoryExportService,
trajectoryRepository)
{
this.trajectoryExportService = trajectoryExportService;
this.trajectoryRepository = trajectoryRepository;
this.parserServiceFactory = parserServiceFactory;
}
protected abstract TrajectoryParserRequest ParserOptions { get; }
/// <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 = trajectoryExportService.GetTemplateFile();
return File(stream, "application/octet-stream", fileName);
}
/// <summary>
/// Импортирует координаты из excel (xlsx) файла
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="token"> Токен отмены задачи </param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost("parse")]
[ProducesResponseType((int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType(typeof(ValidationProblemDetails), (int)System.Net.HttpStatusCode.BadRequest)]
public async Task<ActionResult<ParserResultDto<TDto>>> Parse(int idWell,
[FromForm] IFormFileCollection files,
CancellationToken token)
{
var idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid();
var parserService = parserServiceFactory.Create<TDto, TrajectoryParserRequest>(ParserOptions.IdParserService);
return this.ParseExcelFile(files, ParserOptions, parserService);
}
/// <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] TDto 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 trajectoryRepository.AddAsync(row, token);
return Ok(result);
}
/// <summary>
/// Добавить массив строчек координат для плановой траектории
/// </summary>
/// <param name="idWell"></param>
/// <param name="dtos"></param>
/// <param name="deleteBeforeInsert"></param>
/// <param name="token"></param>
/// <returns>количество успешно записанных строк в БД</returns>
[HttpPost("range/{deleteBeforeInsert:bool}")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddRangeAsync(int idWell,
[FromBody] IEnumerable<TDto> dtos,
bool deleteBeforeInsert,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid();
var idUser = User.GetUserId();
if (!idUser.HasValue)
return Forbid();
foreach (var dto in dtos)
{
dto.IdUser = idUser.Value;
dto.IdWell = idWell;
}
if (deleteBeforeInsert)
await trajectoryRepository.DeleteByIdWellAsync(idWell, token);
var result = await trajectoryRepository.AddRangeAsync(dtos, 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] TDto 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 trajectoryRepository.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 trajectoryRepository.DeleteRangeAsync(new int[] { idRow }, token);
return Ok(result);
}
}
}