Files
CourseWork_GradeBook_Backend/GradeBookServer.Application/Services/GroupService.cs

122 lines
3.7 KiB
C#

using GradeBookServer.Application.Common.Specifications;
using GradeBookServer.Application.DTOs.Group;
using GradeBookServer.Application.DTOs.Student;
using GradeBookServer.Application.Interfaces;
using GradeBookServer.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeBookServer.Application.Services
{
public class GroupService
{
private readonly IBaseRepository<Group> _baseRepository;
public GroupService(IBaseRepository<Group> baseRepository)
{
_baseRepository = baseRepository;
}
public async Task<GroupReadDto?> GetGroupByIdAsync(int id)
{
var group = await _baseRepository.GetByIdWithIncludeAsync(
g => g.ID == id,
new IncludeSpecification<Group>(g => g.Students!, g => g.Direction!)
);
if (group == null)
return null;
return new GroupReadDto
{
ID = group.ID,
Name = group.Name,
DirectionName = group.Direction?.Name ?? "—",
Students = group.Students.Select(s => new StudentReadDto
{
ID = s.ID,
FullName = s.FullName,
Age = s.Age,
GroupName = null
}).ToList()
};
}
public async Task<IEnumerable<GroupReadDto>> GetGroupsByDirectionIdAsync(int directionId)
{
var groups = await _baseRepository
.WhereAsync(
g => g.DirectionID == directionId,
new IncludeSpecification<Group>(g => g.Students!, g => g.Direction!)
);
return groups.Select(group => new GroupReadDto
{
ID = group.ID,
Name = group.Name,
DirectionName = group.Direction?.Name ?? "—",
Students = group.Students.Select(s => new StudentReadDto
{
ID = s.ID,
FullName = s.FullName,
Age = s.Age,
GroupName = null
}).ToList()
});
}
public async Task<IEnumerable<GroupNameDto>?> GetAllGroupsAsync()
{
var groups = await _baseRepository.GetAllAsync();
if (groups == null)
return null;
return groups.Select(g => new GroupNameDto
{
ID = g.ID,
Name = g.Name
});
}
public async Task AddGroupAsync(GroupCreateDto dto)
{
var students = await _baseRepository.GetManyByIdsAsync<Student>(dto.StudentIds);
var group = new Group
{
Name = dto.Name,
DirectionID = dto.DirectionID,
Students = students.ToList()
};
await _baseRepository.AddAsync(group);
}
public async Task UpdateGroupAsync(int id, GroupCreateDto dto)
{
var group = await _baseRepository.GetByIdAsync(id);
if (group == null) return;
group.Name = dto.Name;
group.DirectionID = dto.DirectionID;
var students = await _baseRepository.GetManyByIdsAsync<Student>(dto.StudentIds);
group.Students.Clear();
foreach (var s in students)
group.Students.Add(s);
await _baseRepository.UpdateAsync(group);
}
public async Task DeleteGroupAsync(int id)
{
await _baseRepository.DeleteAsync(id);
}
}
}