Files
parr_api/PARR.API/Controllers/V1/TnkController.cs

204 lines
7.9 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 AutoMapper;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces;
using PARR.Constants;
using PARR.DAL.DomainModels;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
namespace PARR.API.Controllers.V1
{
/// <summary>
/// Управление ТНК
/// </summary>
[Authorize(Roles = ParrRoles.Administrator.Role)]
public class TnkController : BaseApiController
{
private readonly ILogger<TnkController> logger;
private readonly IMapper mapper;
private readonly ITnkService tnkService;
private readonly IValidator<TnkRequest> validator;
private readonly IUriService uriService;
public TnkController(
ILogger<TnkController> logger,
IMapper mapper,
ITnkService tnkService,
IValidator<TnkRequest> validator,
IUriService uriService
)
{
this.logger = logger;
this.mapper = mapper;
this.tnkService = tnkService;
this.validator = validator;
this.uriService = uriService;
}
/// <summary>
/// Создать ТНК
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost(ApiRoutes.Tnk.Create)]
public async Task<IActionResult> Create([FromBody] TnkRequest request)
{
var resultValidate = await validator.ValidateAsync(request);
if (!resultValidate.IsValid)
return BadRequest(new Response(resultValidate.Errors));
var existName = await tnkService.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 tnk = new Tnk
{
Id = Guid.NewGuid(),
Name = request.Name,
EsppId = request.EsppId,
SubprocessId = request.SubprocessId,
};
if (!await tnkService.CreateAsync(tnk) || !await tnkService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при записи новой ТНК в базу данных" } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} добавил ТНК: {tnk.Name}, {tnk.EsppId}, {tnk.SubprocessId}");
var locationUri = uriService.GetUri(ApiRoutes.Tnk.Get, ApiRoutes.Tnk.getParam, tnk.Id);
return Created(locationUri, new Response<TnkResponse>(mapper.Map<TnkResponse>(tnk), true));
}
/// <summary>
/// Список ТНК постранично
/// </summary>
/// <param name="paginationQuery"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.Tnk.GetAll)]
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery)
{
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
IQueryable<Tnk> query = tnkService.Get()
.OrderBy(t => t.Name);
var tnks = await tnkService.GetPage(query, paginationFilter).ToListAsync();
if (!tnks.Any())
return NoContent();
var tnkResponse = mapper.Map<List<TnkResponse>>(tnks);
var paginationResponse = new PagedResponse<TnkResponse>(tnkResponse, true).GetPaginatedProps(paginationFilter, query);
return Ok(paginationResponse);
}
/// <summary>
/// Получить ТНК по id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.Tnk.Get)]
public async Task<IActionResult> GetById([FromRoute] Guid id)
{
var tnk = await tnkService.Get()
.FirstOrDefaultAsync(t => t.Id == id);
if (tnk == null)
return NotFound();
var response = mapper.Map<TnkResponse>(tnk);
return Ok(new Response<TnkResponse>(response, true));
}
/// <summary>
/// Получить связанные с ТНК работы
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet(ApiRoutes.Tnk.GetWorks)]
public async Task<IActionResult> Get([FromRoute] Guid id)
{
var tnk = await tnkService.Get()
.Include(w => w.Works)
.FirstOrDefaultAsync(t => t.Id == id);
if (tnk == null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найдена ТНК с id: {id}" } }));
var response = mapper.Map<List<WorkResponse>>(tnk.Works.OrderBy(t => t.Name).ToList());
return Ok(new Response<List<WorkResponse>>(response, true));
}
/// <summary>
/// Обновить ТНК
/// </summary>
/// <param name="id"></param>
/// <param name="request"></param>
/// <returns></returns>
[HttpPut(ApiRoutes.Tnk.Update)]
public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] TnkRequest request)
{
var resultValidate = await validator.ValidateAsync(request);
if (!resultValidate.IsValid)
return BadRequest(new Response(resultValidate.Errors));
var orig = await tnkService.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;
orig.SubprocessId = request.SubprocessId;
if (!await tnkService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка записи в базу данных изменений ТНК." } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} обновил ТНК: {orig.Id}, {orig.Name}, {orig.EsppId}, {orig.SubprocessId}");
return Ok(new Response<TnkResponse>(mapper.Map<TnkResponse>(orig), true));
}
/// <summary>
/// Удалить ТНК
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete(ApiRoutes.Tnk.Delete)]
public async Task<IActionResult> Delete([FromRoute] Guid id)
{
var tnk = await tnkService.GetAsync(id);
if (tnk == null)
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении ТНК. Не найдена ТНК Id: {id}" } }));
if (!tnkService.Delete(tnk) || !await tnkService.CommitAsync())
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении ТНК из базы данных" } }));
logger.LogInformation($"Пользователь {User.Identity?.Name} удалил ТНК: {tnk.Id}, {tnk.Name}, {tnk.EsppId}, {tnk.SubprocessId}");
return NoContent();
}
}
}