| | 1 | | namespace Syki.Back.Features.Academic.CreateClass; |
| | 2 | |
|
| | 3 | | /// <summary> |
| | 4 | | /// Cria uma nova Turma. |
| | 5 | | /// </summary> |
| 468 | 6 | | public class CreateClassService(SykiDbContext ctx) : IAcademicService |
| | 7 | | { |
| | 8 | | public async Task<OneOf<ClassOut, SykiError>> Create(Guid institutionId, CreateClassIn data) |
| | 9 | | { |
| 202 | 10 | | await using var transaction = await ctx.Database.BeginTransactionAsync(); |
| | 11 | |
|
| 202 | 12 | | var disciplineOk = await ctx.Disciplines.AnyAsync(x => x.InstitutionId == institutionId && x.Id == data.Discipli |
| 203 | 13 | | if (!disciplineOk) return new DisciplineNotFound(); |
| | 14 | |
|
| 201 | 15 | | var teacherOk = await ctx.Teachers.AnyAsync(p => p.InstitutionId == institutionId && p.Id == data.TeacherId); |
| 202 | 16 | | if (!teacherOk) return new TeacherNotFound(); |
| | 17 | |
|
| 200 | 18 | | var periodExists = await ctx.AcademicPeriodExists(institutionId, data.Period); |
| 201 | 19 | | if (!periodExists) return new AcademicPeriodNotFound(); |
| | 20 | |
|
| 402 | 21 | | var schedules = data.Schedules.ConvertAll(h => Schedule.New(h.Day, h.Start, h.End)); |
| 800 | 22 | | foreach (var schedule in schedules) |
| | 23 | | { |
| 204 | 24 | | if (schedule.IsError()) return schedule.GetError(); |
| | 25 | | } |
| | 26 | |
|
| 197 | 27 | | var result = Class.New( |
| 197 | 28 | | institutionId, |
| 197 | 29 | | data.DisciplineId, |
| 197 | 30 | | data.TeacherId, |
| 197 | 31 | | data.Period, |
| 197 | 32 | | data.Vacancies, |
| 199 | 33 | | schedules.ConvertAll(x => x.GetSuccess()) |
| 197 | 34 | | ); |
| | 35 | |
|
| 198 | 36 | | if (result.IsError()) return result.GetError(); |
| | 37 | |
|
| 196 | 38 | | var @class = result.GetSuccess(); |
| | 39 | |
|
| 196 | 40 | | ctx.Classes.Add(@class); |
| 196 | 41 | | await ctx.SaveChangesAsync(); |
| | 42 | |
|
| 196 | 43 | | @class = await ctx.Classes |
| 196 | 44 | | .Include(c => c.Period) |
| 196 | 45 | | .Include(t => t.Lessons) |
| 196 | 46 | | .Include(t => t.Schedules) |
| 196 | 47 | | .FirstAsync(x => x.Id == @class.Id); |
| | 48 | |
|
| 196 | 49 | | @class.CreateLessons(); |
| 196 | 50 | | await ctx.SaveChangesAsync(); |
| | 51 | |
|
| 196 | 52 | | await transaction.CommitAsync(); |
| | 53 | |
|
| 196 | 54 | | @class = await ctx.Classes.AsNoTracking() |
| 196 | 55 | | .Include(t => t.Discipline) |
| 196 | 56 | | .Include(t => t.Teacher) |
| 196 | 57 | | .Include(t => t.Schedules) |
| 196 | 58 | | .Include(t => t.Lessons) |
| 196 | 59 | | .ThenInclude(l => l.Attendances) |
| 196 | 60 | | .FirstAsync(x => x.Id == @class.Id); |
| | 61 | |
|
| 196 | 62 | | return @class.ToOut(); |
| 202 | 63 | | } |
| | 64 | | } |