| | | 1 | | using Estud.Back.Domain.Notifications; |
| | | 2 | | |
| | | 3 | | namespace Estud.Back.Features.Notifications.CreateNotification; |
| | | 4 | | |
| | 22 | 5 | | public class CreateNotificationService(EstudDbContext ctx) : IEstudService |
| | | 6 | | { |
| | | 7 | | private class Validator : AbstractValidator<CreateNotificationIn> |
| | | 8 | | { |
| | 2 | 9 | | public Validator() |
| | | 10 | | { |
| | 2 | 11 | | RuleFor(x => x.Title).NotEmpty().WithError(InvalidNotificationTitle.I); |
| | 2 | 12 | | RuleFor(x => x.Description).NotEmpty().WithError(InvalidNotificationDescription.I); |
| | 2 | 13 | | } |
| | | 14 | | } |
| | 2 | 15 | | private static readonly Validator V = new(); |
| | | 16 | | |
| | | 17 | | public async Task<OneOf<CreateNotificationOut, EstudError>> Create(CreateNotificationIn data) |
| | | 18 | | { |
| | 26 | 19 | | if (V.Run(data, out var error)) return error; |
| | | 20 | | |
| | 18 | 21 | | var institutionId = ctx.RequestUser.InstitutionId; |
| | | 22 | | |
| | 18 | 23 | | var notification = new Notification(institutionId, NotificationType.Custom, data.Title, data.Description); |
| | | 24 | | |
| | 18 | 25 | | if (data.TargetUsers is UsersGroup.All or UsersGroup.Teachers) |
| | | 26 | | { |
| | 16 | 27 | | await CreateNotificationFor(institutionId, notification, UserType.Teacher); |
| | | 28 | | } |
| | 18 | 29 | | if (data.TargetUsers is UsersGroup.All or UsersGroup.Students) |
| | | 30 | | { |
| | 4 | 31 | | await CreateNotificationFor(institutionId, notification, UserType.Student); |
| | | 32 | | } |
| | | 33 | | |
| | 18 | 34 | | await ctx.SaveChangesAsync(notification); |
| | | 35 | | |
| | 18 | 36 | | return new CreateNotificationOut { Id = notification.Id }; |
| | 22 | 37 | | } |
| | | 38 | | |
| | | 39 | | private async Task CreateNotificationFor(int institutionId, Notification notification, UserType userType) |
| | | 40 | | { |
| | 20 | 41 | | FormattableString sql = $@" |
| | 20 | 42 | | SELECT |
| | 20 | 43 | | u.id |
| | 20 | 44 | | FROM |
| | 20 | 45 | | estud.users u |
| | 20 | 46 | | INNER JOIN |
| | 20 | 47 | | estud.roles r ON r.base_type = {userType} |
| | 20 | 48 | | INNER JOIN |
| | 20 | 49 | | estud.user_roles ur ON ur.user_id = u.id AND ur.role_id = r.id |
| | 20 | 50 | | WHERE |
| | 20 | 51 | | u.institution_id = {institutionId} |
| | 20 | 52 | | "; |
| | | 53 | | |
| | 20 | 54 | | var usersIds = await ctx.Database.SqlQuery<int>(sql).ToListAsync(); |
| | | 55 | | |
| | 40 | 56 | | usersIds.ForEach(userId => ctx.UserNotifications.Add(new UserNotification(userId, notification))); |
| | 20 | 57 | | } |
| | | 58 | | } |