forked from ddrilling/AsbCloudServer
Olga Nemt
c7a6e38315
2. Добавлен CancellationToken token 3. Рефактор запроса на получение списка плановых операций 4. Проверка на доступность скважины пользователю 5. Сортировка данных по дате в методе MergeArrays
353 lines
15 KiB
C#
353 lines
15 KiB
C#
using AsbCloudApp.Data;
|
||
using AsbCloudApp.Repositories;
|
||
using AsbCloudApp.Requests;
|
||
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}/wellOperations")]
|
||
[ApiController]
|
||
[Authorize]
|
||
public class WellOperationController : ControllerBase
|
||
{
|
||
private readonly IWellOperationRepository operationRepository;
|
||
private readonly IWellService wellService;
|
||
private readonly IWellOperationImportService wellOperationImportService;
|
||
|
||
public WellOperationController(IWellOperationRepository operationService, IWellService wellService, IWellOperationImportService wellOperationImportService)
|
||
{
|
||
this.operationRepository = 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 = operationRepository.GetSectionTypes();
|
||
return Ok(result);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Возвращает список имен типов операций на скважине
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
[HttpGet]
|
||
[Route("categories")]
|
||
[Permission]
|
||
[ProducesResponseType(typeof(IEnumerable<WellOperationCategoryDto>), (int)System.Net.HttpStatusCode.OK)]
|
||
public IActionResult GetCategories()
|
||
{
|
||
var result = operationRepository.GetCategories();
|
||
return Ok(result);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Возвращает список плановых операций для сопоставления
|
||
/// </summary>
|
||
/// <param name="idWell">id скважины</param>
|
||
/// <param name="token"></param>
|
||
/// <returns></returns>
|
||
[HttpGet]
|
||
[Route("operationsPlan")]
|
||
[ProducesResponseType(typeof(IEnumerable<WellOperationDto>), (int)System.Net.HttpStatusCode.OK)]
|
||
public async Task<IActionResult> GetOperationsPlanAsync([FromRoute] int idWell, CancellationToken token)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
var result = await operationRepository
|
||
.GetOperationsPlanAsync(idWell, token)
|
||
.ConfigureAwait(false);
|
||
return Ok(result);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Отфильтрованный список операций на скважине. Если не применять фильтр, то вернется весь список. Сортированный по глубине затем по дате
|
||
/// </summary>
|
||
/// <param name="idWell">id скважины</param>
|
||
/// <param name="request"></param>
|
||
/// <param name="token"></param>
|
||
/// <returns>Список операций на скважине в контейнере для постраничного просмотра</returns>
|
||
[HttpGet]
|
||
[Permission]
|
||
[ProducesResponseType(typeof(PaginationContainer<WellOperationDto>), (int)System.Net.HttpStatusCode.OK)]
|
||
public async Task<IActionResult> GetOperationsAsync(
|
||
[FromRoute] int idWell,
|
||
[FromQuery] WellOperationRequestBase request,
|
||
CancellationToken token)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
var requestToService = new WellOperationRequest(request, idWell);
|
||
var result = await operationRepository.GetPageAsync(
|
||
requestToService,
|
||
token)
|
||
.ConfigureAwait(false);
|
||
return Ok(result);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Статистика операций по скважине, группированая по категориям
|
||
/// </summary>
|
||
/// <param name="idWell">id скважины</param>
|
||
/// <param name="request"></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] WellOperationRequestBase request,
|
||
CancellationToken token)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
var requestToService = new WellOperationRequest(request, idWell);
|
||
var result = await operationRepository.GetGroupOperationsStatAsync(
|
||
requestToService,
|
||
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> GetOrDefaultAsync(int idWell, int idOperation,
|
||
CancellationToken token)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
var result = await operationRepository.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)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
foreach (var value in values)
|
||
value.IdWell = idWell;
|
||
|
||
var result = await operationRepository.InsertRangeAsync(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)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
value.IdWell = idWell;
|
||
value.Id = idOperation;
|
||
|
||
var result = await operationRepository.UpdateAsync(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)
|
||
{
|
||
if (!await CanUserAccessToWellAsync(idWell,
|
||
token).ConfigureAwait(false))
|
||
return Forbid();
|
||
|
||
var result = await operationRepository.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}")]
|
||
public async Task<IActionResult> ImportAsync(int idWell,
|
||
[FromForm] IFormFileCollection files,
|
||
int options,
|
||
CancellationToken token)
|
||
{
|
||
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];
|
||
if (Path.GetExtension(file.FileName).ToLower() != ".xlsx")
|
||
return BadRequest("Требуется xlsx файл.");
|
||
using Stream stream = file.OpenReadStream();
|
||
|
||
try
|
||
{
|
||
wellOperationImportService.Import(idWell, stream, (options & 1) > 0);
|
||
}
|
||
catch (FileFormatException ex)
|
||
{
|
||
return BadRequest(ex.Message);
|
||
}
|
||
|
||
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)
|
||
{
|
||
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);
|
||
}
|
||
|
||
/// <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)]
|
||
public async Task<IActionResult> ScheduleReportAsync([FromRoute] int idWell, [FromServices] IScheduleReportService scheduleReportService, CancellationToken token)
|
||
{
|
||
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)
|
||
{
|
||
int? idCompany = User.GetCompanyId();
|
||
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
|
||
idWell, token).ConfigureAwait(false);
|
||
}
|
||
}
|
||
#nullable disable
|
||
}
|