system-praktyk-api/src/InternshipSystem.Api/Controllers/EditionController.cs
2020-10-02 21:11:01 +02:00

88 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using IdentityServer4.Extensions;
using InternshipSystem.Api.Result;
using InternshipSystem.Api.Security;
using InternshipSystem.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace InternshipSystem.Api.Controllers
{
[Route("editions")]
public class EditionController : ControllerBase
{
private InternshipDbContext Context { get; }
private IMapper Mapper { get; }
public EditionController(InternshipDbContext context, IMapper mapper)
{
Context = context;
Mapper = mapper;
}
/// <summary>
/// Get accessible editions
/// </summary>
/// <response code="200">Editions accessible by the current user</response>
/// <response code="401">This action is only available for authorized student</response>
/// <returns></returns>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[Authorize]
public async Task<ActionResult<IEnumerable<EditionResult>>> GetAvailableEditions([FromServices] User user, CancellationToken token)
{
var editions =
await Context.Editions
.Where(edition =>
edition.Internships
.Any(internship => internship.Student.Id == user.PersonNumber))
.ProjectTo<EditionResult>(Mapper.ConfigurationProvider)
.ToListAsync(token);
if (editions.IsNullOrEmpty())
{
return NotFound();
}
return Ok(editions);
}
/// <summary>
/// Get edition's configuration
/// </summary>
/// <response code="200">Parameters of edition registered for by student</response>
/// <response code="401">This action is only available for authorized student registered for this edition edition</response>
/// <response code="404">Specified edition doesn't exist</response>
/// <returns></returns>
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[Authorize]
public async Task<ActionResult<EditionConfigurationResult>> GetEditionsConfiguration(Guid id, CancellationToken token)
{
var edition =
await Context.Editions
.Include(e => e.AvailableSubjects)
.Include(e => e.Course)
.Where(e => e.Id.Equals(id))
.ProjectTo<EditionConfigurationResult>(Mapper.ConfigurationProvider)
.FirstOrDefaultAsync(token);
if (edition == null)
{
return NotFound();
}
return Ok(edition);
}
}
}