Рефакторинг контроллеров

This commit is contained in:
Степанов Дмитрий 2024-02-01 16:37:03 +05:00
parent e361ccf4c1
commit dc19829948
7 changed files with 76 additions and 86 deletions

View File

@ -0,0 +1,13 @@
using System.IO;
using AsbCloudApp.Data;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers.Interfaces;
public interface IControllerWithParser<TDto, in TOptions>
where TDto : class, IId
{
ActionResult<ParserResultDto<TDto>> Parse(Stream file, TOptions options);
IActionResult GetTemplate();
}

View File

@ -1,11 +0,0 @@
using System.IO;
using AsbCloudApp.Data;
using Microsoft.AspNetCore.Mvc;
namespace AsbCloudWebApi.Controllers.Interfaces;
public interface IHasExcelParser<TDto>
where TDto : class, IId
{
ActionResult<ParserResultDto<TDto>> Parse(Stream file);
}

View File

@ -1,10 +0,0 @@
using System.IO;
using AsbCloudApp.Data;
namespace AsbCloudWebApi.Controllers.Interfaces;
public interface IHasExcelParserWithOptions<TDto, in TOptions>
where TDto : class, IId
{
ParserResultDto<TDto> Parse(Stream file, TOptions options);
}

View File

@ -10,6 +10,7 @@ using System.IO;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsbCloudApp.Data; using AsbCloudApp.Data;
using AsbCloudApp.Requests.ParserOptions;
using AsbCloudInfrastructure.Services; using AsbCloudInfrastructure.Services;
using AsbCloudWebApi.Controllers.Interfaces; using AsbCloudWebApi.Controllers.Interfaces;
@ -22,35 +23,33 @@ namespace AsbCloudWebApi.Controllers.Trajectory
[ApiController] [ApiController]
[Authorize] [Authorize]
public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>, public abstract class TrajectoryEditableController<TDto> : TrajectoryController<TDto>,
IHasExcelParser<TDto> IControllerWithParser<TDto, IParserOptionsRequest>
where TDto : TrajectoryGeoDto where TDto : TrajectoryGeoDto
{ {
private readonly ParserServiceFactory parserServiceFactory; private readonly IParserService<TDto, IParserOptionsRequest> parserService;
private readonly TrajectoryExportService<TDto> trajectoryExportService;
private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository; private readonly ITrajectoryEditableRepository<TDto> trajectoryRepository;
protected TrajectoryEditableController(IWellService wellService, protected TrajectoryEditableController(IWellService wellService,
ParserServiceFactory parserServiceFactory, ParserServiceFactory parserServiceFactory,
TrajectoryExportService<TDto> trajectoryExportService, TrajectoryExportService<TDto> trajectoryExportService,
ITrajectoryEditableRepository<TDto> trajectoryRepository) ITrajectoryEditableRepository<TDto> trajectoryRepository,
int idParserService)
: base( : base(
wellService, wellService,
trajectoryExportService, trajectoryExportService,
trajectoryRepository) trajectoryRepository)
{ {
this.trajectoryExportService = trajectoryExportService; parserService = parserServiceFactory.Create<TDto, IParserOptionsRequest>(idParserService);
this.trajectoryRepository = trajectoryRepository; this.trajectoryRepository = trajectoryRepository;
this.parserServiceFactory = parserServiceFactory;
} }
protected abstract int IdParserService { get; } ActionResult<ParserResultDto<TDto>> IControllerWithParser<TDto, IParserOptionsRequest>.Parse(Stream file,
IParserOptionsRequest options)
ActionResult<ParserResultDto<TDto>> IHasExcelParser<TDto>.Parse(Stream file)
{ {
try try
{ {
var parserService = parserServiceFactory.GetParser<TDto>(IdParserService); var parserResult = parserService.Parse(file, options);
return Ok(parserService.Parse(file)); return Ok(parserResult);
} }
catch (FileFormatException ex) catch (FileFormatException ex)
{ {
@ -68,7 +67,7 @@ namespace AsbCloudWebApi.Controllers.Trajectory
[ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status204NoContent)]
public IActionResult GetTemplate() public IActionResult GetTemplate()
{ {
var stream = trajectoryExportService.GetTemplateFile(); var stream = parserService.GetTemplateFile();
return File(stream, "application/octet-stream", fileName); return File(stream, "application/octet-stream", fileName);
} }
@ -94,46 +93,19 @@ namespace AsbCloudWebApi.Controllers.Trajectory
if (!await CanUserAccessToWellAsync(idWell, token)) if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
return this.ParseExcelFile(files); return this.ParseExcelFile(files, IParserOptionsRequest.Empty());
} }
/// <summary> /// <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> /// </summary>
/// <param name="idWell"></param> /// <param name="idWell"></param>
/// <param name="dtos"></param> /// <param name="dtos"></param>
/// <param name="deleteBeforeInsert"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns>количество успешно записанных строк в БД</returns> /// <returns></returns>
[HttpPost("range/{deleteBeforeInsert:bool}")] [HttpPost]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)] [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> AddRangeAsync(int idWell, public async Task<IActionResult> InsertRangeAsync(int idWell, [FromBody] IEnumerable<TDto> dtos, CancellationToken token)
[FromBody] IEnumerable<TDto> dtos,
bool deleteBeforeInsert,
CancellationToken token)
{ {
if (!await CanUserAccessToWellAsync(idWell, token)) if (!await CanUserAccessToWellAsync(idWell, token))
return Forbid(); return Forbid();
@ -149,9 +121,39 @@ namespace AsbCloudWebApi.Controllers.Trajectory
dto.IdWell = idWell; dto.IdWell = idWell;
} }
if (deleteBeforeInsert) var result = await trajectoryRepository.AddRangeAsync(dtos, token);
await trajectoryRepository.DeleteByIdWellAsync(idWell, token); return Ok(result);
}
/// <summary>
/// Удалить все по скважине и добавить новые
/// </summary>
/// <param name="idWell"></param>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost("replace")]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> ClearAndInsertRangeAsync(int idWell, [FromBody] IEnumerable<TDto> dtos, CancellationToken token)
{
//TODO: это вся радость требует рефакторинга.
//Удаление с добавлением новых записей должно происходить в рамках одной транзакции, да и вообще должно быть реализовано на уровне репозиторий.
//Рефакторинг будет когда доберёмся до журнала изменений для траекторий.
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;
}
await trajectoryRepository.DeleteByIdWellAsync(idWell, token);
var result = await trajectoryRepository.AddRangeAsync(dtos, token); var result = await trajectoryRepository.AddRangeAsync(dtos, token);
return Ok(result); return Ok(result);
} }

View File

@ -20,9 +20,11 @@ public class TrajectoryFactManualController : TrajectoryEditableController<Traje
TrajectoryFactManualExportService trajectoryExportService, TrajectoryFactManualExportService trajectoryExportService,
ParserServiceFactory parserServiceFactory, ParserServiceFactory parserServiceFactory,
ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryRepository) ITrajectoryEditableRepository<TrajectoryGeoFactDto> trajectoryRepository)
: base(wellService, parserServiceFactory, trajectoryExportService, trajectoryRepository) : base(wellService,
parserServiceFactory,
trajectoryExportService,
trajectoryRepository,
ParserServiceFactory.IdTrajectoryFactManualParserService)
{ {
} }
protected override int IdParserService => ParserServiceFactory.IdTrajectoryFactManualParserService;
} }

View File

@ -27,13 +27,15 @@ namespace AsbCloudWebApi.Controllers.Trajectory
ParserServiceFactory parserServiceFactory, ParserServiceFactory parserServiceFactory,
ITrajectoryEditableRepository<TrajectoryGeoPlanDto> trajectoryRepository, ITrajectoryEditableRepository<TrajectoryGeoPlanDto> trajectoryRepository,
TrajectoryService trajectoryVisualizationService) TrajectoryService trajectoryVisualizationService)
: base(wellService, parserServiceFactory, trajectoryExportService, trajectoryRepository) : base(wellService,
parserServiceFactory,
trajectoryExportService,
trajectoryRepository,
ParserServiceFactory.IdTrajectoryPlanParserService)
{ {
this.trajectoryVisualizationService = trajectoryVisualizationService; this.trajectoryVisualizationService = trajectoryVisualizationService;
} }
protected override int IdParserService => ParserServiceFactory.IdTrajectoryPlanParserService;
/// <summary> /// <summary>
/// Получение координат для визуализации траектории (плановой и фактической) /// Получение координат для визуализации траектории (плановой и фактической)
/// </summary> /// </summary>

View File

@ -88,16 +88,8 @@ namespace Microsoft.AspNetCore.Mvc
return options; return options;
} }
public static ActionResult<ParserResultDto<TDto>> ParseExcelFile<TDto>(this IHasExcelParser<TDto> controller, public static ActionResult<ParserResultDto<TDto>> ParseExcelFile<TDto, TOptions>(
IFormFileCollection files) this IControllerWithParser<TDto, TOptions> controller,
where TDto : class, IId
{
using var file = GetExcelFile(files);
return controller.Parse(file);
}
public static ActionResult<ParserResultDto<TDto>> ParseExcelFileWithOptions<TDto, TOptions>(
this IHasExcelParserWithOptions<TDto, TOptions> controller,
IFormFileCollection files, IFormFileCollection files,
TOptions options) TOptions options)
where TDto : class, IId where TDto : class, IId