feat(api): создан ProcessController+валидация входных данных
This commit is contained in:
8
PARR.API/Contracts/V1/Requests/ProcessRequest.cs
Normal file
8
PARR.API/Contracts/V1/Requests/ProcessRequest.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
namespace PARR.API.Contracts.V1.Requests
|
||||||
|
{
|
||||||
|
public class ProcessRequest
|
||||||
|
{
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public int EsppId { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
201
PARR.API/Controllers/V1/ProcessController.cs
Normal file
201
PARR.API/Controllers/V1/ProcessController.cs
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
using AutoMapper;
|
||||||
|
using FluentValidation;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using PARR.API.Contracts.V1;
|
||||||
|
using PARR.API.Contracts.V1.Requests;
|
||||||
|
using PARR.API.Contracts.V1.Responses.Base;
|
||||||
|
using PARR.API.Contracts.V1.Responses;
|
||||||
|
using PARR.API.Controllers.V1.Base;
|
||||||
|
using PARR.API.Services.Interfaces;
|
||||||
|
using PARR.Constants;
|
||||||
|
using PARR.DAL.Services.Interfaces;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using PARR.DAL.Models;
|
||||||
|
using PARR.API.Contracts.V1.Requests.Queries;
|
||||||
|
using PARR.API.Extensions;
|
||||||
|
using PARR.DAL.DomainModels;
|
||||||
|
|
||||||
|
namespace PARR.API.Controllers.V1
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Управление процессами
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
||||||
|
public class ProcessController : BaseApiController
|
||||||
|
{
|
||||||
|
private readonly ILogger<ProcessController> logger;
|
||||||
|
private readonly IMapper mapper;
|
||||||
|
private readonly IProcessService processService;
|
||||||
|
private readonly IValidator<ProcessRequest> validator;
|
||||||
|
private readonly IUriService uriService;
|
||||||
|
|
||||||
|
public ProcessController(
|
||||||
|
ILogger<ProcessController> logger,
|
||||||
|
IMapper mapper,
|
||||||
|
IProcessService processService,
|
||||||
|
IValidator<ProcessRequest> validator,
|
||||||
|
IUriService uriService
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.logger = logger;
|
||||||
|
this.mapper = mapper;
|
||||||
|
this.processService = processService;
|
||||||
|
this.validator = validator;
|
||||||
|
this.uriService = uriService;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Создать процесс
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost(ApiRoutes.Process.Create)]
|
||||||
|
public async Task<IActionResult> Create([FromBody] ProcessRequest request)
|
||||||
|
{
|
||||||
|
var resultValidate = await validator.ValidateAsync(request);
|
||||||
|
if (!resultValidate.IsValid)
|
||||||
|
return BadRequest(new Response(resultValidate.Errors));
|
||||||
|
|
||||||
|
var existName = await processService.Get().FirstOrDefaultAsync(t => t.Name == request.Name);
|
||||||
|
if (existName != null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Name), Message = $"Процесс с именем \"{request.Name}\" уже существует." } }));
|
||||||
|
|
||||||
|
var process = new Process
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
Name = request.Name,
|
||||||
|
EsppId = request.EsppId
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!await processService.CreateAsync(process) || !await processService.CommitAsync())
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при записи нового процесса в базу данных" } }));
|
||||||
|
|
||||||
|
logger.LogInformation($"Пользователь {User.Identity?.Name} добавил процесс: {process.Name}, {process.EsppId}");
|
||||||
|
|
||||||
|
var locationUri = uriService.GetUri(ApiRoutes.Process.Get, ApiRoutes.Process.getParam, process.Id);
|
||||||
|
|
||||||
|
return Created(locationUri, new Response<ProcessResponse>(mapper.Map<ProcessResponse>(process), true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Список процессов постранично
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="paginationQuery"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet(ApiRoutes.Process.GetAll)]
|
||||||
|
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery)
|
||||||
|
{
|
||||||
|
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
|
||||||
|
|
||||||
|
IQueryable<Process> query = processService.Get()
|
||||||
|
.OrderBy(t => t.Name);
|
||||||
|
|
||||||
|
var processes = await processService.GetPage(query, paginationFilter).ToListAsync();
|
||||||
|
|
||||||
|
if (!processes.Any())
|
||||||
|
return NoContent();
|
||||||
|
|
||||||
|
var processesResponse = mapper.Map<List<ProcessResponse>>(processes);
|
||||||
|
var paginationResponse = new PagedResponse<ProcessResponse>(processesResponse, true).GetPaginatedProps(paginationFilter, query);
|
||||||
|
|
||||||
|
return Ok(paginationResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить процесс по id
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet(ApiRoutes.Process.Get)]
|
||||||
|
public async Task<IActionResult> GetById([FromRoute] Guid id)
|
||||||
|
{
|
||||||
|
var process = await processService.Get()
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == id);
|
||||||
|
|
||||||
|
if (process == null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
|
var response = mapper.Map<ProcessResponse>(process);
|
||||||
|
|
||||||
|
return Ok(new Response<ProcessResponse>(response, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить связанные с процессом подпроцессы
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet(ApiRoutes.Process.GetSubprcesses)]
|
||||||
|
public async Task<IActionResult> Get([FromRoute] Guid id)
|
||||||
|
{
|
||||||
|
var process = await processService.Get()
|
||||||
|
.Include(t => t.Subprocesses)
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == id);
|
||||||
|
|
||||||
|
if (process == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден процесс с id: {id}" } }));
|
||||||
|
|
||||||
|
var response = mapper.Map<List<SubprocessResponse>>(process.Subprocesses.OrderBy(t => t.Name).ToList());
|
||||||
|
|
||||||
|
return Ok(new Response<List<SubprocessResponse>>(response, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Обновить процесс
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPut(ApiRoutes.Process.Update)]
|
||||||
|
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] ProcessRequest request)
|
||||||
|
{
|
||||||
|
var resultValidate = await validator.ValidateAsync(request);
|
||||||
|
if (!resultValidate.IsValid)
|
||||||
|
return BadRequest(new Response(resultValidate.Errors));
|
||||||
|
|
||||||
|
var orig = await processService.Get()
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == id);
|
||||||
|
|
||||||
|
if (orig == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении процесса. Не найден процесс Id: {id}" } }));
|
||||||
|
|
||||||
|
orig.Name = request.Name;
|
||||||
|
orig.EsppId = request.EsppId;
|
||||||
|
|
||||||
|
if (!await processService.CommitAsync())
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка записи в базу данных изменений процесса." } }));
|
||||||
|
|
||||||
|
logger.LogInformation($"Пользователь {User.Identity?.Name} обновил процесс: {orig.Id}, {orig.Name}, {orig.EsppId}");
|
||||||
|
|
||||||
|
return Ok(new Response<ProcessResponse>(mapper.Map<ProcessResponse>(orig), true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Удалить подпроцесс
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="id"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpDelete(ApiRoutes.Process.Delete)]
|
||||||
|
public async Task<IActionResult> Delete([FromRoute] Guid id)
|
||||||
|
{
|
||||||
|
var process = await processService.GetAsync(id);
|
||||||
|
|
||||||
|
if (process == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении процесса. Не найден процесс Id: {id}" } }));
|
||||||
|
|
||||||
|
if (!processService.Delete(process) || !await processService.CommitAsync())
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении процесса из базы данных" } }));
|
||||||
|
|
||||||
|
logger.LogInformation($"Пользователь {User.Identity?.Name} удалил процесс: {process.Id}, {process.Name}, {process.EsppId}");
|
||||||
|
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,7 @@ using PARR.DAL.Services.Interfaces;
|
|||||||
namespace PARR.API.Controllers.V1
|
namespace PARR.API.Controllers.V1
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Управление Подпроцессами
|
/// Управление подпроцессами
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
[Authorize(Roles = ParrRoles.Administrator.Role)]
|
||||||
public class SubprocessController : BaseApiController
|
public class SubprocessController : BaseApiController
|
||||||
@@ -141,9 +141,9 @@ namespace PARR.API.Controllers.V1
|
|||||||
if (subprocess == null)
|
if (subprocess == null)
|
||||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден подпроцесс с id: {id}" } }));
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден подпроцесс с id: {id}" } }));
|
||||||
|
|
||||||
var response = mapper.Map<List<SubprocessResponse>>(subprocess.Tnks.OrderBy(t => t.Name).ToList());
|
var response = mapper.Map<List<TnkResponse>>(subprocess.Tnks.OrderBy(t => t.Name).ToList());
|
||||||
|
|
||||||
return Ok(new Response<List<SubprocessResponse>>(response, true));
|
return Ok(new Response<List<TnkResponse>>(response, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -164,7 +164,7 @@ namespace PARR.API.Controllers.V1
|
|||||||
.FirstOrDefaultAsync(t => t.Id == id);
|
.FirstOrDefaultAsync(t => t.Id == id);
|
||||||
|
|
||||||
if (orig == null)
|
if (orig == null)
|
||||||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении подпроцесса. Не найдена подпроцесс Id: {id}" } }));
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении подпроцесса. Не найден подпроцесс Id: {id}" } }));
|
||||||
|
|
||||||
orig.Name = request.Name;
|
orig.Name = request.Name;
|
||||||
orig.EsppId = request.EsppId;
|
orig.EsppId = request.EsppId;
|
||||||
|
|||||||
17
PARR.API/Validators/ProcessValidator.cs
Normal file
17
PARR.API/Validators/ProcessValidator.cs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
using FluentValidation;
|
||||||
|
using PARR.API.Contracts.V1.Requests;
|
||||||
|
|
||||||
|
namespace PARR.API.Validators
|
||||||
|
{
|
||||||
|
public class ProcessValidator : AbstractValidator<ProcessRequest>
|
||||||
|
{
|
||||||
|
private bool? isValid = null;
|
||||||
|
|
||||||
|
public ProcessValidator()
|
||||||
|
{
|
||||||
|
RuleFor(t => t.Name).NotEmpty().NotNull().WithMessage("Имя процесса не может быть пустым");
|
||||||
|
|
||||||
|
RuleFor(t => t.EsppId).NotEmpty().NotNull().WithMessage("EsppId не может быть пустым");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user