Add notification inbox and restrict email logging

This commit is contained in:
GonnaHetzMe committed 2026-11-18 18:40:53 +01:00
1 parent 33b6864d3b
commit 9ca23a2c15
5 files changed
+113 -2

No files matched your search

@@ -0,0 +1,39 @@
using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
[ApiController]
[Authorize]
[Route("api/notifications")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
{
[HttpGet]
public Task<PagedResult<NotificationDto>> List(
[FromQuery] bool unreadOnly = false, [FromQuery] int page = 1, [FromQuery] int pageSize = 20,
CancellationToken ct = default) => notifications.ListAsync(unreadOnly, page, pageSize, ct);
[HttpGet("unread-count")]
public Task<UnreadCountDto> CountUnread(CancellationToken ct) => notifications.CountUnreadAsync(ct);
[HttpPost("{id:int}/read")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<IActionResult> MarkRead(int id, CancellationToken ct)
{
await notifications.MarkReadAsync(id, ct);
return NoContent();
}
[HttpPost("read-all")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> MarkAllRead(CancellationToken ct)
{
await notifications.MarkAllReadAsync(ct);
return NoContent();
}
}
@@ -2,6 +2,7 @@ using FluentValidation;
using Helpdesk.Application.Auth; using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs; using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Issues; using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Users; using Helpdesk.Application.Users;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@@ -20,6 +21,7 @@ public static class DependencyInjection
services.AddScoped<UserService>(); services.AddScoped<UserService>();
services.AddScoped<CatalogService>(); services.AddScoped<CatalogService>();
services.AddScoped<IssueService>(); services.AddScoped<IssueService>();
services.AddScoped<NotificationService>();
return services; return services;
} }
} }
@@ -0,0 +1,61 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Issues;
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<IssueNotification> Inbox()
{
var userId = currentUser.Id;
return db.IssueNotifications.Where(n => n.UserId == userId);
}
private Task<int> MarkUnreadRowsAsync(IQueryable<IssueNotification> query, CancellationToken ct)
{
var now = clock.GetUtcNow().UtcDateTime;
return query.Where(n => n.ReadAt == null)
.ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct);
}
}
@@ -1,6 +1,6 @@
namespace Helpdesk.Domain.Issues; namespace Helpdesk.Domain.Issues;
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened } public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
public enum DeliveryChannel { Email, Push } public enum DeliveryChannel { Email, Push }
public enum DeliveryStatus { Pending, Skipped } public enum DeliveryStatus { Pending, Skipped }
@@ -11,12 +11,14 @@ public sealed class IssueNotification(
public int Id { get; private set; } public int Id { get; private set; }
public int? IssueId { get; private set; } public int? IssueId { get; private set; }
public int? ProposalId { get; private set; }
public Issue Issue { get; private set; } = issue; public Issue Issue { get; private set; } = issue;
public int UserId { get; private set; } = userId; public int UserId { get; private set; } = userId;
public NotificationType Type { get; private set; } = type; public NotificationType Type { get; private set; } = type;
public string Title { get; private set; } = title; public string Title { get; private set; } = title;
public string Message { get; private set; } = message; public string Message { get; private set; } = message;
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTime? ReadAt { get; private set; }
} }
public sealed class NotificationDelivery( public sealed class NotificationDelivery(
@@ -1,4 +1,5 @@
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Email; namespace Helpdesk.Infrastructure.Email;
@@ -7,14 +8,20 @@ namespace Helpdesk.Infrastructure.Email;
/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět /// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi. /// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
/// </summary> /// </summary>
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
{ {
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
{ {
if (environment.IsDevelopment())
LogEmail(to, subject, body); LogEmail(to, subject, body);
else
LogMissingTransport();
return Task.CompletedTask; return Task.CompletedTask;
} }
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")] [LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
private partial void LogEmail(string to, string subject, string body); private partial void LogEmail(string to, string subject, string body);
[LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")]
private partial void LogMissingTransport();
} }