| | | 1 | | using Dapper; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | |
| | | 4 | | namespace Syki.Back.Features.Notifications.GetNotifications; |
| | | 5 | | |
| | 0 | 6 | | public class GetNotificationsService(SykiDbContext ctx) : ISykiService |
| | | 7 | | { |
| | | 8 | | public async Task<OneOf<GetNotificationsOut, SykiError>> Get(GetNotificationsIn data) |
| | | 9 | | { |
| | 0 | 10 | | var connection = await ctx.GetOpenConnectionAsync(); |
| | | 11 | | |
| | 0 | 12 | | var unreadFilter = data.UnreadOnly ? "AND un.viewed_at IS NULL" : ""; |
| | | 13 | | |
| | 0 | 14 | | var sql = $@" |
| | 0 | 15 | | SELECT |
| | 0 | 16 | | n.id, |
| | 0 | 17 | | n.notification_type, |
| | 0 | 18 | | n.title, |
| | 0 | 19 | | n.description, |
| | 0 | 20 | | n.created_at, |
| | 0 | 21 | | un.viewed_at, |
| | 0 | 22 | | n.metadata::text AS metadata, |
| | 0 | 23 | | COUNT(*) OVER() AS total_rows |
| | 0 | 24 | | FROM |
| | 0 | 25 | | syki.user_notifications un |
| | 0 | 26 | | JOIN |
| | 0 | 27 | | syki.notifications n ON n.id = un.notification_id |
| | 0 | 28 | | WHERE |
| | 0 | 29 | | un.user_id = @UserId |
| | 0 | 30 | | {unreadFilter} |
| | 0 | 31 | | ORDER BY n.created_at DESC |
| | 0 | 32 | | LIMIT @PageSize |
| | 0 | 33 | | OFFSET @Offset |
| | 0 | 34 | | "; |
| | | 35 | | |
| | 0 | 36 | | var offset = (data.Page - 1) * data.PageSize; |
| | 0 | 37 | | var parameters = new { UserId = ctx.RequestUser.Id, data.PageSize, Offset = offset }; |
| | | 38 | | |
| | 0 | 39 | | var rows = (await connection.QueryAsync<NotificationRow>(sql, parameters)).ToList(); |
| | | 40 | | |
| | 0 | 41 | | var items = rows.Select(r => new GetNotificationsItemOut |
| | 0 | 42 | | { |
| | 0 | 43 | | Id = r.Id, |
| | 0 | 44 | | NotificationType = (NotificationType)r.NotificationType, |
| | 0 | 45 | | Title = r.Title, |
| | 0 | 46 | | Description = r.Description, |
| | 0 | 47 | | CreatedAt = r.CreatedAt, |
| | 0 | 48 | | ViewedAt = r.ViewedAt, |
| | 0 | 49 | | Metadata = r.Metadata != null ? JsonDocument.Parse(r.Metadata) : null, |
| | 0 | 50 | | }).ToList(); |
| | | 51 | | |
| | 0 | 52 | | return new GetNotificationsOut |
| | 0 | 53 | | { |
| | 0 | 54 | | Total = rows.FirstOrDefault()?.TotalRows ?? 0, |
| | 0 | 55 | | Page = data.Page, |
| | 0 | 56 | | PageSize = data.PageSize, |
| | 0 | 57 | | Items = items, |
| | 0 | 58 | | }; |
| | 0 | 59 | | } |
| | | 60 | | } |