| | | 1 | | using Estud.Back.Domain.Identity; |
| | | 2 | | using Estud.Back.Domain.Students; |
| | | 3 | | using Estud.Back.Domain.Webhooks; |
| | | 4 | | |
| | | 5 | | namespace Estud.Back.Features.Students.CreateStudent; |
| | | 6 | | |
| | 36 | 7 | | public class CreateStudentService(EstudDbContext ctx, UserManager<EstudUser> userManager) : IEstudService |
| | | 8 | | { |
| | | 9 | | public async Task<OneOf<CreateStudentOut, EstudError>> Create(CreateStudentIn data) |
| | | 10 | | { |
| | 36 | 11 | | var email = data.Email.ToLowerInvariant(); |
| | 36 | 12 | | var emailUsed = await ctx.Users.AnyAsync(u => u.Email == email); |
| | 38 | 13 | | if (emailUsed) return EmailAlreadyUsed.I; |
| | | 14 | | |
| | 34 | 15 | | var studentRole = await ctx.GetStudentRole(); |
| | 34 | 16 | | var institutionId = ctx.RequestUser.InstitutionId; |
| | | 17 | | |
| | 34 | 18 | | var user = new EstudUser(institutionId, data.Name, email); |
| | 34 | 19 | | var student = new EstudStudent(user, institutionId, data.Name); |
| | 34 | 20 | | var userRole = new EstudUserRole(institutionId, user, studentRole.Id); |
| | 34 | 21 | | ctx.AddRange(student, userRole); |
| | | 22 | | |
| | | 23 | | // TODO: Refactor to use Domain Events Pattern |
| | 34 | 24 | | var webhookSubscriptions = await ctx.WebhookSubscriptions.Where(x => x.InstitutionId == institutionId && x.IsAct |
| | 34 | 25 | | .Select(x => new { x.Id, x.Events }).ToListAsync() ?? []; |
| | 122 | 26 | | foreach (var webhookSubscription in webhookSubscriptions.Where(x => x.Events.Contains(WebhookEventType.StudentCr |
| | | 27 | | { |
| | 18 | 28 | | var webhookCall = new WebhookCall(institutionId, webhookSubscription.Id, new { student.Name, user.Email }, W |
| | 18 | 29 | | ctx.Add(webhookCall); |
| | | 30 | | } |
| | | 31 | | |
| | 34 | 32 | | await userManager.CreateAsync(user, $"Estud@{Guid.NewGuid()}"); |
| | | 33 | | |
| | 34 | 34 | | return new CreateStudentOut { Id = student.Id }; |
| | 36 | 35 | | } |
| | | 36 | | } |