diff --git a/backend/src/Helpdesk.Api/Controllers/NotificationsController.cs b/backend/src/Helpdesk.Api/Controllers/NotificationsController.cs new file mode 100644 index 0000000..5ed84af --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/NotificationsController.cs @@ -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(StatusCodes.Status401Unauthorized)] +public sealed class NotificationsController(NotificationService notifications) : ControllerBase +{ + [HttpGet] + public Task> 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 CountUnread(CancellationToken ct) => notifications.CountUnreadAsync(ct); + + [HttpPost("{id:int}/read")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task MarkRead(int id, CancellationToken ct) + { + await notifications.MarkReadAsync(id, ct); + return NoContent(); + } + + [HttpPost("read-all")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task MarkAllRead(CancellationToken ct) + { + await notifications.MarkAllReadAsync(ct); + return NoContent(); + } +} diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index d231b6b..e16c834 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -2,6 +2,7 @@ using FluentValidation; using Helpdesk.Application.Auth; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; +using Helpdesk.Application.Notifications; using Helpdesk.Application.Users; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -20,6 +21,7 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs new file mode 100644 index 0000000..50ac01f --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs @@ -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> 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([], 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(items, total, page, pageSize); + } + + public async Task 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 Inbox() + { + var userId = currentUser.Id; + return db.IssueNotifications.Where(n => n.UserId == userId); + } + + private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) + { + var now = clock.GetUtcNow().UtcDateTime; + return query.Where(n => n.ReadAt == null) + .ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct); + } +} diff --git a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs index 84f9aba..144c935 100644 --- a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs +++ b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs @@ -1,6 +1,6 @@ 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 DeliveryStatus { Pending, Skipped } @@ -11,12 +11,14 @@ public sealed class IssueNotification( public int Id { get; private set; } public int? IssueId { get; private set; } + public int? ProposalId { get; private set; } public Issue Issue { get; private set; } = issue; public int UserId { get; private set; } = userId; public NotificationType Type { get; private set; } = type; public string Title { get; private set; } = title; public string Message { get; private set; } = message; public DateTime CreatedAt { get; set; } + public DateTime? ReadAt { get; private set; } } public sealed class NotificationDelivery( diff --git a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs index 4fe3109..6b269b5 100644 --- a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs @@ -1,4 +1,5 @@ using Helpdesk.Application.Abstractions; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; 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 docker compose logs api). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi. /// -internal sealed partial class LoggingEmailSender(ILogger logger) : IEmailSender +internal sealed partial class LoggingEmailSender(ILogger logger, IHostEnvironment environment) : IEmailSender { public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) { - LogEmail(to, subject, body); + if (environment.IsDevelopment()) + LogEmail(to, subject, body); + else + LogMissingTransport(); return Task.CompletedTask; } [LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{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(); }