presence/Presence.API/Controllers/GroupController.cs
2024-12-05 10:31:49 +03:00

99 lines
3.3 KiB
C#

using domain.Request;
using domain.UseCase;
using Microsoft.AspNetCore.Mvc;
using Presence.API.Response;
namespace Presence.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class GroupController : ControllerBase
{
private readonly IGroupUseCase _groupService;
public GroupController(IGroupUseCase groupService)
{
_groupService = groupService;
}
[HttpGet("/group")]
public ActionResult<GroupResponse> GetAllGroups()
{
var result = _groupService
.GetGroupsWithStudents()
.Select(group => new GroupResponse
{
Id = group.Id,
Name = group.Name,
Users = group.Users?.Select(
user => new UserResponse
{
Id = user.Id,
LastName = user.LastName,
FirstName = user.FirstName,
Patronymic = user.Patronymic
}).ToList()
}).ToList();
return Ok(result);
}
[HttpDelete("/group/{id}")]
public IActionResult DeleteGroup(int id)
{
RemoveGroupRequest removeGroupRequest = new() { GroupId = id };
bool isDeleted = _groupService.RemoveGroup(removeGroupRequest);
if (!isDeleted) return NotFound();
else return NoContent();
}
[HttpPost("/group")]
public ActionResult<GroupResponse> PostGroup(AddGroupRequest addGroupRequest)
{
if (addGroupRequest is null)
return BadRequest(new ArgumentNullException());
var groupWithStudentsRequest = new AddGroupWithStudentRequest
{
AddGroupRequest = new AddGroupRequest { Name = addGroupRequest.Name },
AddStudentRequests = addGroupRequest.Students
};
_groupService.AddGroupWithStudents(groupWithStudentsRequest);
var createdGroup = _groupService.GetGroupsWithStudents()
.FirstOrDefault(g => g.Name == addGroupRequest.Name);
return CreatedAtAction(nameof(GetGroupById), new { id = createdGroup.Id }, createdGroup);
}
[HttpGet("/group/{id:int}")]
public ActionResult<GroupResponse> GetGroupById(int id)
{
var group = _groupService.GetGroupsWithStudents().FirstOrDefault(g => g.Id == id);
if (group == null)
return NotFound();
var response = new GroupResponse
{
Id = group.Id,
Name = group.Name,
Users = group.Users?.Select(
user => new UserResponse
{
Id = user.Id,
LastName = user.LastName,
FirstName = user.FirstName,
Patronymic = user.Patronymic
}).ToList()
};
return Ok(response);
}
[HttpGet("/group/{id}/subjects")]
public ActionResult<GroupSubjectResponse> GetGroupSubject(int id)
{
return Ok(_groupService.GetGroupSubject(id));
}
}
}