| | 1 | | namespace Syki.Back.Features.Academic.CreateNotification; |
| | 2 | |
|
| 12 | 3 | | public class CreateNotificationService(SykiDbContext ctx) : IAcademicService |
| | 4 | | { |
| | 5 | | public async Task<NotificationOut> Create(Guid institutionId, CreateNotificationIn data) |
| | 6 | | { |
| 12 | 7 | | var notification = new Notification(institutionId, data.Title, data.Description, data.TargetUsers, data.Timeless |
| | 8 | |
|
| 12 | 9 | | if (data.TargetUsers is UsersGroup.All or UsersGroup.Teachers) |
| | 10 | | { |
| 7 | 11 | | await CreateNotificationFor(institutionId, notification.Id, UserRole.Teacher); |
| | 12 | | } |
| 12 | 13 | | if (data.TargetUsers is UsersGroup.All or UsersGroup.Students) |
| | 14 | | { |
| 8 | 15 | | await CreateNotificationFor(institutionId, notification.Id, UserRole.Student); |
| | 16 | | } |
| | 17 | |
|
| 12 | 18 | | ctx.Add(notification); |
| 12 | 19 | | await ctx.SaveChangesAsync(); |
| | 20 | |
|
| 12 | 21 | | return notification.ToOut(); |
| 12 | 22 | | } |
| | 23 | |
|
| | 24 | | private async Task CreateNotificationFor(Guid institutionId, Guid notificationId, UserRole userRole) |
| | 25 | | { |
| 15 | 26 | | FormattableString sql = $@" |
| 15 | 27 | | SELECT |
| 15 | 28 | | u.id |
| 15 | 29 | | FROM |
| 15 | 30 | | syki.users u |
| 15 | 31 | | INNER JOIN |
| 15 | 32 | | syki.roles r ON r.name = {userRole.ToString()} |
| 15 | 33 | | INNER JOIN |
| 15 | 34 | | syki.user_roles ur ON ur.user_id = u.id AND ur.role_id = r.id |
| 15 | 35 | | WHERE |
| 15 | 36 | | u.institution_id = {institutionId} |
| 15 | 37 | | "; |
| | 38 | |
|
| 15 | 39 | | var usersIds = await ctx.Database.SqlQuery<Guid>(sql).ToListAsync(); |
| | 40 | |
|
| 24 | 41 | | usersIds.ForEach(userId => ctx.UserNotifications.Add(new UserNotification(userId, notificationId))); |
| 15 | 42 | | } |
| | 43 | | } |