system-praktyk-api/src/InternshipSystem.Api/Controllers/DocumentsController.cs
2020-08-29 17:25:48 +02:00

86 lines
3.0 KiB
C#

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using InternshipSystem.Api.Queries;
using InternshipSystem.Api.Security;
using InternshipSystem.Core;
using InternshipSystem.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace InternshipSystem.Api.Controllers
{
[ApiController]
[Route("document")]
public class DocumentsController : ControllerBase
{
private InternshipDbContext Context { get; }
private IMapper Mapper { get; }
public DocumentsController(InternshipDbContext context, IMapper mapper)
{
Context = context;
Mapper = mapper;
}
/// <summary>
/// Fill out required document,
/// </summary>
/// <param name="documentRequest">Documents Scan and description, and Id of filled document</param>
/// <returns></returns>
/// <response code="200">If change was successfully registered</response>
/// <response code="400">If the provided query was malformed</response>
/// <response code="404">Id doesn't match any required document</response>
/// <response code="401">This action is only available for authorized student registered for current edition</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[Authorize(Policy = Policies.RegisteredOnly)]
public async Task<ActionResult> AddDocumentToInternship([FromBody] DocumentPublishRequest documentRequest, User user)
{
var validator = new DocumentPublishRequest.Validator();
var validationResult = await validator.ValidateAsync(documentRequest);
if (!validationResult.IsValid)
{
return BadRequest(validationResult.ToString());
}
var edition =
await Context.Editions
.FindAsync(user.EditionId.Value);
var internship = await Context.Entry(edition)
.Collection(e => e.Internships)
.Query()
.SingleAsync(i => i.Student.Id == user.PersonNumber);
var document = Mapper.Map<Document>(documentRequest);
if (documentRequest.Id.HasValue)
{
try
{
internship.UpdateDocument(document);
}
catch (InvalidOperationException)
{
return NotFound();
}
}
else
{
internship.AddNewDocument(document);
}
await Context.SaveChangesAsync();
return Ok();
}
}
}