Files
Arnaud Dartois 6b611e908a feat(notifications): abonnement par type d'événement + priorité ntfy (Fixes #61) (#154)
## Contexte

Issue #61 : Gestion des types d'alertes — abonnement par type d'événement + sévérité/priorité.

Les utilisateurs ne peuvent pas filtrer quelles notifications push/email ils reçoivent. Tous les événements (mouvement, personne, caméra hors ligne...) sont envoyés sans distinction.

## Changements

### Domaine
- **EventTypePriorityMap** (`src/Heimdall.Domain/Helpers/`) : mapping `EventType` → priorité ntfy (1-5)
  - CameraOffline/UnknownPerson = 5 (urgent), PersonDetected/FaceRecognized = 4 (high), MotionDetected/VehicleDetected/LicensePlateDetected = 3 (default), CameraOnline = 2 (low)
- **UserNotificationConfig** : ajout `SubscribedEventsJson` (JSON array), `GetSubscribedEvents()`, `IsEventTypeSubscribed()`, `SetSubscribedEvents()`
  - `null` ou `[]` = recevoir tous les événements (comportement par défaut)

### Infrastructure
- **NotificationService.DispatchToExternalChannelsAsync** : filtre par `IsEventTypeSubscribed()` avant envoi email/ntfy
- Priorité ntfy calculée via `EventTypePriorityMap.GetPriority()` et passée à `NtfyService`

### UI (Profile.razor)
- Checkboxes par type d'événement dans la section Notifications
- Texte explicatif : « Si aucun n'est sélectionné, tous les événements sont notifiés »
- Sauvegarde via `UpdateNotificationConfigRequest.SubscribedEvents`

### Tests
- 10 tests Domain : `UserNotificationConfig` (GetSubscribedEvents, IsEventTypeSubscribed, cas limites JSON invalide/vidé/unknown)
- 1 test Domain : `EventTypePriorityMap` (couvre les 8 EventTypes + null)
- 3 tests Infrastructure : filtrage par abonnement + priorité ntfy + filtre vide

## Vérification

- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 161 passed
- Infrastructure.Tests : 180 passed
- Application.Tests : 421 passed
- Web.Tests : 243 passed
- Agent.Tests : 206 passed
- Total : 1211 tests ✅

Closes #61

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/154
2026-08-20 15:10:37 +02:00

379 lines
14 KiB
C#

using AutoMapper;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Notifications.Mapping;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Domain.Enums;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Services;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Heimdall.Infrastructure.Tests.Services;
/// <summary>
/// Unit tests for <see cref="NotificationService"/>.
/// Uses SQLite in-memory for real EF Core behavior with mocked external channels.
/// </summary>
public class NotificationServiceTests : IDisposable
{
private readonly SqliteConnection _connection;
private readonly AppDbContext _context;
private readonly IMapper _mapper;
private readonly INotificationBroadcastService _broadcast;
private readonly IEmailService _emailService;
private readonly INtfyService _ntfyService;
private readonly INotificationRateLimiter _rateLimiter;
private readonly ILogger<NotificationService> _logger;
private readonly NotificationService _service;
public NotificationServiceTests()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var opts = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlite(_connection)
.Options;
_context = new AppDbContext(opts, new AuditInterceptor());
_context.Database.EnsureCreated();
// Real AutoMapper with the actual notification mapping profile
// (v16 : constructeur 2 args — ILoggerFactory requis)
var mapperConfig = new MapperConfiguration(cfg =>
cfg.AddProfile<NotificationMappingProfile>(), NullLoggerFactory.Instance);
_mapper = mapperConfig.CreateMapper();
_broadcast = Substitute.For<INotificationBroadcastService>();
_emailService = Substitute.For<IEmailService>();
_ntfyService = Substitute.For<INtfyService>();
_rateLimiter = Substitute.For<INotificationRateLimiter>();
_logger = Substitute.For<ILogger<NotificationService>>();
_service = new NotificationService(
_context, _mapper, _broadcast, _emailService, _ntfyService,
_rateLimiter, _logger);
}
public void Dispose()
{
_context.Dispose();
_connection.Close();
_connection?.Dispose();
GC.SuppressFinalize(this);
}
[Fact]
public async Task CreateNotificationAsync_ShouldAddAndBroadcast()
{
// Arrange
var userId = Guid.NewGuid();
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(true);
// Act
var result = await _service.CreateNotificationAsync(
userId, "Test Title", "Test message", NotificationType.Info,
EventType.PersonDetected, Guid.NewGuid());
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Title.ShouldBe("Test Title");
result.Data.UserId.ShouldBe(userId);
// Verify broadcast was called
await _broadcast.Received(1).NotifyNewNotification(
Arg.Is<NotificationDto>(d => d!.Title == "Test Title"),
Arg.Any<CancellationToken>());
// Verify it was persisted
var count = await _context.Notifications.CountAsync();
count.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_RateLimited_ShouldSkipSilently()
{
// Arrange
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(false);
// Act
var result = await _service.CreateNotificationAsync(
Guid.NewGuid(), "Test", "Message", NotificationType.Info,
EventType.PersonDetected, Guid.NewGuid());
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldBeNull(); // Silently skipped
// Nothing should be persisted
var count = await _context.Notifications.CountAsync();
count.ShouldBe(0);
// No broadcast should happen
await _broadcast.DidNotReceiveWithAnyArgs().NotifyNewNotification(default!, default);
}
[Fact]
public async Task GetUnreadCountAsync_ShouldReturnCount()
{
// Arrange
var userId = Guid.NewGuid();
// Seed notifications directly in the database
_context.Notifications.Add(new Notification(userId, "Unread1", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(userId, "Unread2", "Msg", NotificationType.Info));
var readNotification = new Notification(userId, "Read", "Msg", NotificationType.Info);
readNotification.MarkAsRead();
_context.Notifications.Add(readNotification);
await _context.SaveChangesAsync();
// Act
var count = await _service.GetUnreadCountAsync(userId);
// Assert
count.ShouldBe(2);
}
[Fact]
public async Task GetUnreadCountAsync_OtherUsers_NotCounted()
{
// Arrange
var userId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
_context.Notifications.Add(new Notification(userId, "Mine", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(otherUserId, "Theirs", "Msg", NotificationType.Info));
await _context.SaveChangesAsync();
// Act
var count = await _service.GetUnreadCountAsync(userId);
// Assert
count.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_WithoutRateLimiter_ShouldWork()
{
// Arrange
var userId = Guid.NewGuid();
// cameraId is null, so rate limiter is skipped entirely
// Act
var result = await _service.CreateNotificationAsync(
userId, "No Cam", "Message", NotificationType.Alert,
eventType: null, cameraId: null);
// Assert
result.IsSuccess.ShouldBeTrue();
result.Data.ShouldNotBeNull();
result.Data.Type.ShouldBe(NotificationType.Alert.ToString());
// Broadcast should still be called
await _broadcast.Received(1).NotifyNewNotification(
Arg.Any<NotificationDto>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task MarkAsReadAsync_ExistingNotification_MarksItRead()
{
// Arrange
var userId = Guid.NewGuid();
var notification = new Notification(userId, "Read Test", "Msg", NotificationType.Info);
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
notification.IsRead.ShouldBeFalse();
// Act
await _service.MarkAsReadAsync(notification.Id, userId);
// Assert
var updated = await _context.Notifications.FindAsync(notification.Id);
updated.ShouldNotBeNull();
updated.IsRead.ShouldBeTrue();
updated.ReadAt.ShouldNotBeNull();
}
[Fact]
public async Task MarkAsReadAsync_OtherUsersNotification_DoesNothing()
{
// Arrange
var ownerId = Guid.NewGuid();
var otherUserId = Guid.NewGuid();
var notification = new Notification(ownerId, "Not Mine", "Msg", NotificationType.Info);
_context.Notifications.Add(notification);
await _context.SaveChangesAsync();
// Act
await _service.MarkAsReadAsync(notification.Id, otherUserId);
// Assert — should NOT mark as read since it belongs to another user
var updated = await _context.Notifications.FindAsync(notification.Id);
updated.ShouldNotBeNull();
updated.IsRead.ShouldBeFalse();
}
[Fact]
public async Task MarkAllAsReadAsync_MarksAllUserNotifications()
{
// Arrange
var userId = Guid.NewGuid();
_context.Notifications.Add(new Notification(userId, "A", "Msg", NotificationType.Info));
_context.Notifications.Add(new Notification(userId, "B", "Msg", NotificationType.Warning));
_context.Notifications.Add(new Notification(Guid.NewGuid(), "Other", "Msg", NotificationType.Info));
await _context.SaveChangesAsync();
// Act
await _service.MarkAllAsReadAsync(userId);
// Assert
var userUnread = await _context.Notifications
.CountAsync(n => n.UserId == userId && !n.IsRead);
userUnread.ShouldBe(0);
// Other user's notification should remain unread
var otherUnread = await _context.Notifications
.CountAsync(n => n.UserId != userId && !n.IsRead);
otherUnread.ShouldBe(1);
}
[Fact]
public async Task GetNotificationsAsync_ShouldReturnPagedResults()
{
// Arrange
var userId = Guid.NewGuid();
for (int i = 0; i < 5; i++)
{
_context.Notifications.Add(new Notification(userId, $"Title {i}", $"Msg {i}", NotificationType.Info));
}
await _context.SaveChangesAsync();
// Act
var result = await _service.GetNotificationsAsync(userId, null, page: 1, pageSize: 3);
// Assert
result.Items.Count.ShouldBe(3);
result.TotalCount.ShouldBe(5);
result.Page.ShouldBe(1);
result.TotalPages.ShouldBe(2);
result.HasNextPage.ShouldBeTrue();
result.HasPreviousPage.ShouldBeFalse();
}
[Fact]
public async Task GetNotificationsAsync_FilterByRead_ReturnsFiltered()
{
// Arrange
var userId = Guid.NewGuid();
var n1 = new Notification(userId, "Unread", "Msg", NotificationType.Info);
var n2 = new Notification(userId, "Read", "Msg", NotificationType.Info);
n2.MarkAsRead();
_context.Notifications.Add(n1);
_context.Notifications.Add(n2);
await _context.SaveChangesAsync();
// Act
var unread = await _service.GetNotificationsAsync(userId, isRead: false, page: 1, pageSize: 20);
var read = await _service.GetNotificationsAsync(userId, isRead: true, page: 1, pageSize: 20);
// Assert
unread.Items.Count.ShouldBe(1);
unread.TotalCount.ShouldBe(1);
read.Items.Count.ShouldBe(1);
read.TotalCount.ShouldBe(1);
}
[Fact]
public async Task CreateNotificationAsync_WithSubscribedEvents_FilteredOut_ShouldSkipExternalDispatch()
{
// Arrange — user only subscribed to CameraOffline
var userId = Guid.NewGuid();
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(true);
var config = new UserNotificationConfig(userId);
config.UpdateNtfy("http://ntfy:80", true);
config.SetSubscribedEvents("[\"CameraOffline\"]");
_context.UserNotificationConfigs.Add(config);
await _context.SaveChangesAsync();
// Act — send a PersonDetected notification (not subscribed)
await _service.CreateNotificationAsync(
userId, "Personne", "Détectée", NotificationType.Warning,
EventType.PersonDetected, Guid.NewGuid());
// Assert — ntfy should NOT be called (event not subscribed)
await _ntfyService.DidNotReceive().SendNotificationAsync(
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<int>(), Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task CreateNotificationAsync_WithSubscribedEvents_Matching_ShouldDispatchWithPriority()
{
// Arrange — user subscribed to PersonDetected
var userId = Guid.NewGuid();
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(true);
var config = new UserNotificationConfig(userId);
config.UpdateNtfy("http://ntfy:80", true);
config.SetSubscribedEvents("[\"PersonDetected\"]");
_context.UserNotificationConfigs.Add(config);
await _context.SaveChangesAsync();
// Act — send a PersonDetected notification (subscribed)
await _service.CreateNotificationAsync(
userId, "Personne", "Détectée", NotificationType.Warning,
EventType.PersonDetected, Guid.NewGuid());
// Assert — ntfy should be called with priority 4 (PersonDetected = high)
await _ntfyService.Received(1).SendNotificationAsync(
Arg.Any<string>(),
Arg.Is("Personne"),
Arg.Is("Détectée"),
Arg.Is(4), // PersonDetected priority
Arg.Any<string?>(),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task CreateNotificationAsync_WithNoFilter_ShouldDispatchAll()
{
// Arrange — no subscribed events (null) → all events pass
var userId = Guid.NewGuid();
_rateLimiter.ShouldSend(Arg.Any<Guid>(), Arg.Any<EventType>(), Arg.Any<Guid?>())
.Returns(true);
var config = new UserNotificationConfig(userId);
config.UpdateNtfy("http://ntfy:80", true);
// No SetSubscribedEvents call → null
_context.UserNotificationConfigs.Add(config);
await _context.SaveChangesAsync();
// Act
await _service.CreateNotificationAsync(
userId, "Motion", "Detected", NotificationType.Info,
EventType.MotionDetected, Guid.NewGuid());
// Assert — ntfy should be called with default priority 3
await _ntfyService.Received(1).SendNotificationAsync(
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Any<string>(),
Arg.Is(3), // MotionDetected = default priority
Arg.Any<string?>(),
Arg.Any<CancellationToken>());
}
}