62 lines
2.5 KiB
C#
62 lines
2.5 KiB
C#
using Helpdesk.Application.Abstractions;
|
|
using Helpdesk.Application.Common;
|
|
using Helpdesk.Domain;
|
|
using Helpdesk.Domain.Notifications;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Helpdesk.Application.Notifications;
|
|
|
|
public sealed record NotificationDto(
|
|
int Id, string Type, string Title, string Message, int? IssueId, int? ProposalId, DateTime CreatedAt, DateTime? ReadAt);
|
|
|
|
public sealed record UnreadCountDto(int Count);
|
|
|
|
public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUser, TimeProvider clock)
|
|
{
|
|
public async Task<PagedResult<NotificationDto>> ListAsync(bool unreadOnly, int page, int pageSize, CancellationToken ct)
|
|
{
|
|
page = Math.Max(1, page);
|
|
pageSize = Math.Clamp(pageSize, 1, 100);
|
|
|
|
var query = Inbox().AsNoTracking();
|
|
if (unreadOnly)
|
|
query = query.Where(n => n.ReadAt == null);
|
|
|
|
var total = await query.CountAsync(ct);
|
|
var offset = (long)(page - 1) * pageSize;
|
|
if (offset >= total)
|
|
return new PagedResult<NotificationDto>([], total, page, pageSize);
|
|
|
|
var rows = await query.OrderByDescending(n => n.CreatedAt).ThenByDescending(n => n.Id)
|
|
.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
|
var items = rows.Select(n => new NotificationDto(
|
|
n.Id, n.Type.ToCode(), n.Title, n.Message, n.IssueId, n.ProposalId, n.CreatedAt, n.ReadAt)).ToArray();
|
|
return new PagedResult<NotificationDto>(items, total, page, pageSize);
|
|
}
|
|
|
|
public async Task<UnreadCountDto> CountUnreadAsync(CancellationToken ct) =>
|
|
new(await Inbox().CountAsync(n => n.ReadAt == null, ct));
|
|
|
|
public async Task MarkReadAsync(int id, CancellationToken ct)
|
|
{
|
|
var match = Inbox().Where(n => n.Id == id);
|
|
if (await MarkUnreadRowsAsync(match, ct) == 0 && !await match.AnyAsync(ct))
|
|
throw new NotFoundException("Notifikace neexistuje.");
|
|
}
|
|
|
|
public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct);
|
|
|
|
private IQueryable<Notification> Inbox()
|
|
{
|
|
var userId = currentUser.Id;
|
|
return NotificationVisibility.VisibleToRecipients(db).Where(n => n.UserId == userId);
|
|
}
|
|
|
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
|
{
|
|
var now = clock.GetUtcNow().UtcDateTime;
|
|
return query.Where(n => n.ReadAt == null)
|
|
.ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct);
|
|
}
|
|
}
|