Разделил метод контроллера

This commit is contained in:
parent 5d865457ec
commit 5c904951b8

View File

@ -11,8 +11,9 @@ using System.ComponentModel.DataAnnotations;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Data.WellOperationImport;
using AsbCloudApp.Services.WellOperationImport; using AsbCloudApp.Services.WellOperationImport;
using AsbCloudApp.Data.WellOperationImport.Options;
using AsbCloudApp.Exceptions;
namespace AsbCloudWebApi.Controllers namespace AsbCloudWebApi.Controllers
{ {
@ -30,6 +31,8 @@ namespace AsbCloudWebApi.Controllers
private readonly IWellOperationExportService wellOperationExportService; private readonly IWellOperationExportService wellOperationExportService;
private readonly IWellOperationImportTemplateService wellOperationImportTemplateService; private readonly IWellOperationImportTemplateService wellOperationImportTemplateService;
private readonly IWellOperationImportService wellOperationImportService; private readonly IWellOperationImportService wellOperationImportService;
private readonly IWellOperationExcelParser<WellOperationImportDefaultOptionsDto> wellOperationDefaultExcelParser;
private readonly IWellOperationExcelParser<WellOperationImportGazpromKhantosOptionsDto> wellOperationGazpromKhantosExcelParser;
private readonly IUserRepository userRepository; private readonly IUserRepository userRepository;
public WellOperationController(IWellOperationRepository operationRepository, public WellOperationController(IWellOperationRepository operationRepository,
@ -37,6 +40,8 @@ namespace AsbCloudWebApi.Controllers
IWellOperationImportTemplateService wellOperationImportTemplateService, IWellOperationImportTemplateService wellOperationImportTemplateService,
IWellOperationExportService wellOperationExportService, IWellOperationExportService wellOperationExportService,
IWellOperationImportService wellOperationImportService, IWellOperationImportService wellOperationImportService,
IWellOperationExcelParser<WellOperationImportDefaultOptionsDto> wellOperationDefaultExcelParser,
IWellOperationExcelParser<WellOperationImportGazpromKhantosOptionsDto> wellOperationGazpromKhantosExcelParser,
IUserRepository userRepository) IUserRepository userRepository)
{ {
this.operationRepository = operationRepository; this.operationRepository = operationRepository;
@ -44,6 +49,8 @@ namespace AsbCloudWebApi.Controllers
this.wellOperationImportTemplateService = wellOperationImportTemplateService; this.wellOperationImportTemplateService = wellOperationImportTemplateService;
this.wellOperationExportService = wellOperationExportService; this.wellOperationExportService = wellOperationExportService;
this.wellOperationImportService = wellOperationImportService; this.wellOperationImportService = wellOperationImportService;
this.wellOperationDefaultExcelParser = wellOperationDefaultExcelParser;
this.wellOperationGazpromKhantosExcelParser = wellOperationGazpromKhantosExcelParser;
this.userRepository = userRepository; this.userRepository = userRepository;
} }
@ -287,7 +294,7 @@ namespace AsbCloudWebApi.Controllers
/// <summary> /// <summary>
/// Импорт плановых операций из excel (xlsx) файла /// Импорт операций из excel (xlsx) файла. Стандартный заполненный шаблон
/// </summary> /// </summary>
/// <param name="idWell">id скважины</param> /// <param name="idWell">id скважины</param>
/// <param name="options">Параметры для парсинга файла</param> /// <param name="options">Параметры для парсинга файла</param>
@ -295,29 +302,20 @@ namespace AsbCloudWebApi.Controllers
/// <param name="deleteBeforeImport">Удалить операции перед импортом = 1, если файл валидный</param> /// <param name="deleteBeforeImport">Удалить операции перед импортом = 1, если файл валидный</param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
[HttpPost("import/{deleteBeforeImport}")] [HttpPost("import/default/{deleteBeforeImport}")]
[Permission] [Permission]
public async Task<IActionResult> ImportAsync(int idWell, public async Task<IActionResult> ImportDefaultExcelFileAsync(int idWell,
[FromQuery] WellOperationParserOptionsDto options, [FromQuery] WellOperationImportDefaultOptionsDto options,
[FromForm] IFormFileCollection files, [FromForm] IFormFileCollection files,
[Range(0, 1, ErrorMessage = "Недопустимое значение. Допустимые: 0, 1")] int deleteBeforeImport, [Range(0, 1, ErrorMessage = "Недопустимое значение. Допустимые: 0, 1")] int deleteBeforeImport,
CancellationToken token) CancellationToken token)
{ {
var idCompany = User.GetCompanyId();
var idUser = User.GetUserId(); var idUser = User.GetUserId();
if (idCompany is null || idUser is null) if (!idUser.HasValue)
return Forbid(); throw new ForbidException("Неизвестный пользователь");
if (!await CanUserAccessToWellAsync(idWell, token)) await AssertUserHasAccessToImportWellOperationsAsync(idWell, token);
return Forbid();
if (!await CanUserEditWellOperationsAsync(idWell, token))
return Forbid();
if (!await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false))
return Forbid();
if (files.Count < 1) if (files.Count < 1)
return this.ValidationBadRequest(nameof(files), "Нет файла"); return this.ValidationBadRequest(nameof(files), "Нет файла");
@ -330,7 +328,56 @@ namespace AsbCloudWebApi.Controllers
try try
{ {
await wellOperationImportService.ImportAsync(idWell, idUser.Value, stream, options, (deleteBeforeImport & 1) > 0, token); var sheet = wellOperationDefaultExcelParser.Parse(stream, options);
await wellOperationImportService.ImportAsync(idWell, idUser.Value, options.IdType, sheet, (deleteBeforeImport & 1) > 0, token);
}
catch (FileFormatException ex)
{
return this.ValidationBadRequest(nameof(files), ex.Message);
}
return Ok();
}
/// <summary>
/// Импорт операций из excel (xlsx) файла. ГПНХ (Хантос)
/// </summary>
/// <param name="idWell">id скважины</param>
/// <param name="options">Параметры для парсинга файла</param>
/// <param name="files">Коллекция из одного файла xlsx</param>
/// <param name="deleteBeforeImport">Удалить операции перед импортом = 1, если файл валидный</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost("import/gazpromKhantos/{deleteBeforeImport}")]
[Permission]
public async Task<IActionResult> ImportGazpromKhantosExcelFileAsync(int idWell,
[FromQuery] WellOperationImportGazpromKhantosOptionsDto options,
[FromForm] IFormFileCollection files,
[Range(0, 1, ErrorMessage = "Недопустимое значение. Допустимые: 0, 1")] int deleteBeforeImport,
CancellationToken token)
{
var idUser = User.GetUserId();
if (!idUser.HasValue)
throw new ForbidException("Неизвестный пользователь");
await AssertUserHasAccessToImportWellOperationsAsync(idWell, token);
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 sheet = wellOperationGazpromKhantosExcelParser.Parse(stream, options);
await wellOperationImportService.ImportAsync(idWell, idUser.Value, options.IdType, sheet, (deleteBeforeImport & 1) > 0, token);
} }
catch (FileFormatException ex) catch (FileFormatException ex)
{ {
@ -406,6 +453,24 @@ namespace AsbCloudWebApi.Controllers
return File(stream, "application/octet-stream", fileName); return File(stream, "application/octet-stream", fileName);
} }
private async Task AssertUserHasAccessToImportWellOperationsAsync(int idWell, CancellationToken token)
{
var idCompany = User.GetCompanyId();
var idUser = User.GetUserId();
if (!idCompany.HasValue || !idUser.HasValue)
throw new ForbidException("Неизвестный пользователь");
if (!await CanUserAccessToWellAsync(idWell, token))
throw new ForbidException("Нет доступа к скважине");
if (!await CanUserEditWellOperationsAsync(idWell, token))
throw new ForbidException("Недостаточно прав для редактирования ГГД на завершенной скважине");
if (!await wellService.IsCompanyInvolvedInWellAsync(idCompany.Value, idWell, token))
throw new ForbidException("Скважина недоступна для компании");
}
private async Task<bool> CanUserEditWellOperationsAsync(int idWell, CancellationToken token) private async Task<bool> CanUserEditWellOperationsAsync(int idWell, CancellationToken token)
{ {
var idUser = User.GetUserId(); var idUser = User.GetUserId();