From 8929f0e61cfb211334057d28de159f740a323b9c Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 10:51:34 +0100 Subject: [PATCH 1/2] docs: distinguish shipped notification channels (#375) --- docs/notifications.md | 66 +++++++++++++++++++++++------ skills/notification-center/SKILL.md | 2 + 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/docs/notifications.md b/docs/notifications.md index 17c4978..bb7c296 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -1,22 +1,62 @@ -# Heimdall — Notifications (Email + Gotify + Templates) +# Heimdall — Notifications -**Stack :** `FluentEmail.Smtp`, `Gotify.NET`, `RazorTemplating` / `Scriban` (Markdown → HTML) +## État livré vérifié dans le dépôt + +Les canaux externes déclarés par `NotificationChannel` sont `Email` et `Ntfy`; +les notifications in-app sont consultables séparément dans le centre +`/notifications`. L’interface utilise les endpoints authentifiés +`/api/notifications` et le hub `/hubs/notifications` pour le compteur non lu. +Voir [`signalr-usage.md`](signalr-usage.md) pour le contrat du hub. + +Les réglages administrateur se trouvent dans `/settings` (policy +`Admin.Manage`) : configuration et test SMTP, configuration et test ntfy. Les +préférences de l’utilisateur, dont l’adresse email, l’activation ntfy, le topic, +les événements abonnés et les options de résumé, sont éditées dans `/profile`. +La livraison email utilise `EmailService`; les notifications push utilisent +`NtfyService` et Hangfire. `DailyDigestJob` envoie le résumé quotidien à 8 h; +`WeeklyDigestJob` envoie le résumé hebdomadaire le lundi à 8 h, selon les +expressions cron enregistrées dans `JobSetup`. + +Ces constats sont une vérification statique des sources, pas une validation de +serveur SMTP, de serveur ntfy ni d’un déploiement. La configuration de ces +services dépend de l’opérateur. + +Sources principales : + +- [`NotificationChannel`](../src/Heimdall.Domain/Enums/NotificationChannel.cs) +- [`NotificationSettingsSection`](../src/Heimdall.Web/Components/Settings/NotificationSettingsSection.razor) +- [`NotificationsPage`](../src/Heimdall.Web/Components/Pages/NotificationsPage.razor) +- [`NotificationsController`](../src/Heimdall.Web/Controllers/NotificationsController.cs) +- [`NtfyService`](../src/Heimdall.Infrastructure/Services/NtfyService.cs) +- [`EmailService`](../src/Heimdall.Infrastructure/Services/EmailService.cs) +- [`DailyDigestJob`](../src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs) +- [`WeeklyDigestJob`](../src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs) +- [Planifications Hangfire](../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs) + +## Conception historique — ne décrit pas l’état livré + +Les sections qui suivent conservent des exemples de conception antérieurs à +l’implémentation actuelle. Gotify, l’éditeur de templates, les bibliothèques +proposées, les tableaux d’événements et les écrans maquetés ci-dessous ne sont +pas une description contractuelle des fonctions livrées. Se référer à la +section d’état livré ci-dessus avant d’appliquer un exemple. --- -## 1. Canaux de notification +## 1. Canaux de notification — conception historique -| Canal | Usage | Priorité | Bibliothèque | -|---|---|---|---| -| **Email** (SMTP) | Notifications importantes, résumés | 🔴 Requis | `FluentEmail.Smtp` + `FluentEmail.Razor` | -| **Gotify** (push) | Alertes temps réel, notifications rapides | 🟠 Recommandé | `Gotify.NET` | -| **In-app** (SignalR) | Notifications silencieuses dans l'UI | 🟢 Requis | SignalR (intégré) | +| Canal proposé | Usage prévu | +|---|---| +| Email (SMTP) | Notifications et résumés | +| Gotify | Push | +| In-app (SignalR) | Notifications dans l’UI | --- -## 2. SMTP — Configuration +## 2. SMTP — exemple de conception historique -Configurable depuis l'UI Admin : +La configuration ci-dessous est un modèle de conception, pas le schéma actuel +de l’interface : ```csharp public class SmtpConfig @@ -46,7 +86,7 @@ dotnet add package Scriban // templates Markdown alternatif --- -## 3. Gotify — Configuration +## 3. Gotify — conception historique, non livrée Gotify est un serveur de notification push self-hosted (Docker). @@ -100,7 +140,7 @@ public class GotifyConfig --- -## 4. Templates de notification (Markdown) +## 4. Templates de notification — conception historique ### Architecture @@ -461,4 +501,4 @@ Daily digest is generated at configured hour User language changes template language Admin can test SMTP connection from UI Admin can test Gotify connection from UI -``` \ No newline at end of file +``` diff --git a/skills/notification-center/SKILL.md b/skills/notification-center/SKILL.md index 39b7ab0..8d06e24 100644 --- a/skills/notification-center/SKILL.md +++ b/skills/notification-center/SKILL.md @@ -7,6 +7,8 @@ description: Implement and accept the authenticated Heimdall in-app notification The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser. +When documenting delivery channels, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. In `docs/notifications.md`, keep old Gotify/template UI sketches explicitly labeled as historical design when they are retained. + ## Acceptance 1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests. -- 2.54.1 From b042652965c0173c3662dbccf26e18f2ab71df0a Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Fri, 13 Nov 2026 10:54:13 +0100 Subject: [PATCH 2/2] docs: remove obsolete notification proposals (#375) --- docs/notifications.md | 470 ---------------------------- skills/notification-center/SKILL.md | 2 +- 2 files changed, 1 insertion(+), 471 deletions(-) diff --git a/docs/notifications.md b/docs/notifications.md index bb7c296..f698d66 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -32,473 +32,3 @@ Sources principales : - [`DailyDigestJob`](../src/Heimdall.Infrastructure/Jobs/DailyDigestJob.cs) - [`WeeklyDigestJob`](../src/Heimdall.Infrastructure/Jobs/WeeklyDigestJob.cs) - [Planifications Hangfire](../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs) - -## Conception historique — ne décrit pas l’état livré - -Les sections qui suivent conservent des exemples de conception antérieurs à -l’implémentation actuelle. Gotify, l’éditeur de templates, les bibliothèques -proposées, les tableaux d’événements et les écrans maquetés ci-dessous ne sont -pas une description contractuelle des fonctions livrées. Se référer à la -section d’état livré ci-dessus avant d’appliquer un exemple. - ---- - -## 1. Canaux de notification — conception historique - -| Canal proposé | Usage prévu | -|---|---| -| Email (SMTP) | Notifications et résumés | -| Gotify | Push | -| In-app (SignalR) | Notifications dans l’UI | - ---- - -## 2. SMTP — exemple de conception historique - -La configuration ci-dessous est un modèle de conception, pas le schéma actuel -de l’interface : - -```csharp -public class SmtpConfig -{ - public string Host { get; set; } = "smtp.example.com"; - public int Port { get; set; } = 587; - public string Username { get; set; } = string.Empty; - public string Password { get; set; } = string.Empty; // chiffré - public bool UseSsl { get; set; } = true; - public string FromAddress { get; set; } = "heimdall@example.com"; - public string FromName { get; set; } = "Heimdall"; -} -``` - -Stockée en base (table `AppConfig`), champ `Password` chiffré avec `IDataProtector`. - -Test depuis l'UI : "Envoyer un email de test". - -### Librairies NuGet - -``` -dotnet add package FluentEmail.Smtp -dotnet add package FluentEmail.Razor // templates Razor → HTML -// ou -dotnet add package Scriban // templates Markdown alternatif -``` - ---- - -## 3. Gotify — conception historique, non livrée - -Gotify est un serveur de notification push self-hosted (Docker). - -### Dépendances - -``` -dotnet add package Gotify.NET -``` - -### Configuration - -```csharp -public class GotifyConfig -{ - public string ServerUrl { get; set; } = "http://gotify:8080"; - public string AppToken { get; set; } = string.Empty; // chiffré - public int Priority { get; set; } = 5; // 0-10 -} -``` - -### UI Admin - -```text -┌──────────────────────────────────────────────┐ -│ Notifications │ -│ │ -│ ┌──── Email (SMTP) ───────────────────────┐ │ -│ │ Serveur: [smtp.example.com ] │ │ -│ │ Port: [587 ] │ │ -│ │ SSL: [x] │ │ -│ │ Utilisateur: [notifications@... ] │ │ -│ │ Mot de passe: [******** ] │ │ -│ │ De: [heimdall@example.com ] │ │ -│ │ │ │ -│ │ [Tester la connexion] │ │ -│ └───────────────────────────────────────────┘ │ -│ │ -│ ┌──── Gotify ──────────────────────────────┐ │ -│ │ Serveur: [http://gotify:8080 ] │ │ -│ │ Token: [******** ] │ │ -│ │ Priorité: [5 ▼] │ │ -│ │ │ │ -│ │ [Tester la connexion] │ │ -│ └───────────────────────────────────────────┘ │ -│ │ -│ ┌──── Templates ───────────────────────────┐ │ -│ │ [Modifier les templates ▼] │ │ -│ └───────────────────────────────────────────┘ │ -└──────────────────────────────────────────────┘ -``` - ---- - -## 4. Templates de notification — conception historique - -### Architecture - -```text -Base de données -└── NotificationTemplate - ├── EventType (enum) - ├── Language ("fr", "en", "de"...) - ├── Channel ("email", "gotify", "inapp") - ├── Subject (string, avec variables) - └── Body (string, Markdown avec variables) -``` - -### Template Entity - -```csharp -public class NotificationTemplate -{ - public Guid Id { get; set; } - public EventType EventType { get; set; } // PersonDetected, etc. - public string Language { get; set; } = "fr"; // "fr", "en", "de" - public string Channel { get; set; } = "email"; // "email", "gotify", "inapp" - public string Subject { get; set; } = string.Empty; - public string BodyMarkdown { get; set; } = string.Empty; - public bool IsDefault { get; set; } // template par défaut -} -``` - -### Variables disponibles dans les templates - -| Variable | Description | Exemple | -|---|---|---| -| `{{SiteName}}` | Nom du site | "Entrepôt A" | -| `{{CameraName}}` | Nom de la caméra | "Entrée principale" | -| `{{EventType}}` | Type d'événement | "PersonDetected" | -| `{{EventTime}}` | Horodatage | "14/07/2026 14:23:05" | -| `{{EventTimeAgo}}` | Relatif | "il y a 2 minutes" | -| `{{PersonName}}` | Nom de la personne | "Jean Dupont" | -| `{{PersonPhotoUrl}}` | Lien photo | `https://heimdall/...` | -| `{{VehiclePlate}}` | Plaque | "AA-123-XX" | -| `{{VehicleModel}}` | Modèle | "Renault Clio" | -| `{{SnapshotUrl}}` | Lien snapshot | `https://heimdall/...` | -| `{{EventUrl}}` | Lien vers l'événement | `https://heimdall/events/...` | -| `{{SiteUrl}}` | URL du Central | `https://heimdall.example.com` | -| `{{AlertCount}}` | Nombre d'alertes (résumé) | "12" | - -### Templates par défaut (fr) - -```markdown -=== PersonDetected — email — fr === -Subject: [Heimdall] Personne détectée — {{CameraName}} -Body: -**🔴 Alerte — Personne détectée** - -| | | -|---|---| -| **Site** | {{SiteName}} | -| **Caméra** | {{CameraName}} | -| **Date** | {{EventTime}} | -| **Personne** | {{PersonName}} | - -Voir l'événement : [{{EventUrl}}]({{EventUrl}}) - ---- - -=== PersonDetected — email — en === -Subject: [Heimdall] Person detected — {{CameraName}} -Body: -**🔴 Alert — Person detected** - -| | | -|---|---| -| **Site** | {{SiteName}} | -| **Camera** | {{CameraName}} | -| **Time** | {{EventTime}} | -| **Person** | {{PersonName}} | - -View event: [{{EventUrl}}]({{EventUrl}}) - ---- - -=== UnknownPerson — gotify — fr === -Subject: Visage inconnu — {{CameraName}} -Body: -Visage inconnu détecté sur {{CameraName}} ({{SiteName}}) -à {{EventTime}}. - ---- - -=== DailySummary — email — fr === -Subject: [Heimdall] Résumé quotidien — {{SiteName}} — {{EventTime}} -Body: -**📊 Résumé quotidien — {{SiteName}}** - -Période: {{DateStart}} → {{DateEnd}} - -| Type | Nombre | -|---|---| -| Personnes détectées | {{PersonCount}} | -| Dont connues | {{KnownPersonCount}} | -| Dont inconnues | {{UnknownPersonCount}} | -| Véhicules détectés | {{VehicleCount}} | -| Événements total | {{TotalEventCount}} | - -[Voir le tableau de bord]({{SiteUrl}}) -``` - -### Rendu du template - -```csharp -public class NotificationService : INotificationService -{ - private readonly ScribanTemplateEngine _scriban; - private readonly IRepository _templates; - - public async Task RenderAsync( - EventType eventType, - string language, - string channel, - Dictionary variables) - { - // 1. Chercher template spécifique (eventType + language + channel) - var template = await _templates.FirstOrDefaultAsync(t => - t.EventType == eventType && - t.Language == language && - t.Channel == channel); - - // 2. Fallback : template par défaut de cette langue - template ??= await _templates.FirstOrDefaultAsync(t => - t.EventType == eventType && - t.Language == language && - t.IsDefault); - - // 3. Fallback : template anglais - template ??= await _templates.FirstOrDefaultAsync(t => - t.EventType == eventType && - t.Language == "en" && - t.IsDefault); - - if (template == null) return string.Empty; - - // 4. Rendre avec Scriban - var parsed = Template.Parse(template.BodyMarkdown); - var result = await parsed.RenderAsync(variables); - return result; - } -} -``` - -### UI d'édition des templates - -```text -┌──────────────────────────────────────────────────────┐ -│ Templates de notification [Langue: français ▼] -│ │ -│ Événement: [Personne détectée ▼] Canal: [Email ▼] │ -│ │ -│ Sujet: │ -│ ┌──────────────────────────────────────────────────┐ │ -│ │ [Heimdall] Personne détectée — {{CameraName}} │ │ -│ └──────────────────────────────────────────────────┘ │ -│ │ -│ Corps (Markdown): │ -│ ┌──────────────────────────────────────────────────┐ │ -│ │ **🔴 Alerte — Personne détectée** │ │ -│ │ │ │ -│ │ | | | │ │ -│ │ |---|---| │ │ -│ │ | **Site** | {{SiteName}} | │ │ -│ │ | **Caméra** | {{CameraName}} | │ │ -│ │ │ │ -│ │ Voir : [{{EventUrl}}]({{EventUrl}}) │ │ -│ └──────────────────────────────────────────────────┘ │ -│ │ -│ [Aperçu] [Réinitialiser] [Enregistrer] │ -│ │ -│ ── Aperçu ────────────────────────────────────────── │ -│ De: heimdall@example.com │ -│ À: test@example.com │ -│ Sujet: [Heimdall] Personne détectée — Entrée │ -│ ──────────────────────────────────────────────────── │ -│ 🔴 Alerte — Personne détectée │ -│ Site: Entrepôt A | Caméra: Entrée | Date: 14/07... │ -└──────────────────────────────────────────────────────┘ -``` - -### Librairies - -``` -dotnet add package Scriban # Moteur de templates Markdown -dotnet add package Scriban.Signed # (si besoin strong name) -// ou -dotnet add package FluentEmail.Razor # Alternative Razor → HTML -dotnet add package FluentEmail.Smtp # Envoi SMTP -dotnet add package Gotify.NET # Gotify push -``` - ---- - -## 5. Types d'événements notifiables - -| EventType | Email | Gotify | In-App (SignalR) | Template dispo | -|---|---|---|---|---| -| `PersonDetected` | ✅ | ✅ | ✅ | Oui | -| `UnknownPerson` | ✅ (haut) | ✅ | ✅ | Oui | -| `FaceRecognized` | 🟡 (option) | 🟡 | ✅ | Oui | -| `VehicleDetected` | ✅ | ✅ | ✅ | Oui | -| `LicensePlateDetected` | 🟡 | ✅ | ✅ | Oui | -| `MotionDetected` | ❌ (trop) | ❌ | ✅ (silencieux) | Non | -| `CameraOffline` | ✅ | ✅ | ✅ | Oui | -| `CameraOnline` | 🟡 | 🟡 | ✅ | Oui | -| `DailySummary` | ✅ | ❌ | ❌ | Oui | -| `WeeklySummary` | ✅ | ❌ | ❌ | Oui | - ---- - -## 6. File d'attente des notifications (Hangfire) - -Toutes les notifications passent par Hangfire pour : - -1. Fiabilité (retry si échec SMTP) -2. File d'attente (ne pas bloquer le thread de détection) -3. Rate limiting (max N emails/min) - -```csharp -public class SendNotificationJob -{ - [AutomaticRetry(Attempts = 3, DelaysInSeconds = [60, 300, 900])] - public async Task ExecuteAsync( - Guid eventId, - string channel, // "email", "gotify", "inapp" - string language, - CancellationToken ct) - { - var event = await _db.Events.FindAsync(new object[] { eventId }, ct); - var variables = await BuildVariablesAsync(event, ct); - - var rendered = await _notificationService.RenderAsync( - event.Type, language, channel, variables); - - await channel switch - { - "email" => await SendEmailAsync(event, rendered, ct), - "gotify" => await SendGotifyAsync(event, rendered, ct), - "inapp" => await SendInAppAsync(event, rendered, ct), - _ => Task.CompletedTask - }; - } -} -``` - -### Déclenchement depuis le pipeline IA - -```csharp -// Dans le handler de détection -if (shouldNotify) -{ - BackgroundJob.Enqueue(j => - j.ExecuteAsync(event.Id, "email", user.Language, CancellationToken.None)); - BackgroundJob.Enqueue(j => - j.ExecuteAsync(event.Id, "gotify", user.Language, CancellationToken.None)); -} - -// Notification in-app = temps réel via SignalR (pas Hangfire) -await _signalrHub.SendEventAsync(event); -``` - ---- - -## 7. Configuration par User - -Chaque utilisateur peut configurer ses notifications : - -```csharp -public class UserNotificationConfig -{ - public Guid UserId { get; set; } - public bool EmailEnabled { get; set; } = true; - public bool GotifyEnabled { get; set; } = false; - public string EmailAddress { get; set; } = string.Empty; - public List SubscribedEvents { get; set; } = new(); - public string Language { get; set; } = "fr"; - public bool DailyDigest { get; set; } = true; - public bool WeeklyDigest { get; set; } = false; -} -``` - -UI User : - -```text -┌──────────────────────────────────────────────┐ -│ Mes notifications │ -│ │ -│ Recevoir les notifications par : │ -│ [✅] Email : jean@example.com │ -│ [ ] Gotify │ -│ │ -│ M'alerter pour : │ -│ [✅] Personnes détectées │ -│ [✅] Visages inconnus │ -│ [ ] Véhicules │ -│ [✅] Caméra hors ligne │ -│ [ ] Mouvement seul │ -│ │ -│ Résumés : │ -│ [✅] Résumé quotidien │ -│ [ ] Résumé hebdomadaire │ -│ │ -│ Langue des notifications : [Français ▼] │ -└──────────────────────────────────────────────┘ -``` - ---- - -## 8. Résumés quotidiens/hebdomadaires (Hangfire) - -```csharp -// Planifié dans Hangfire -RecurringJob.AddOrUpdate( - "daily-digest", - j => j.ExecuteAsync(CancellationToken.None), - Cron.Daily(8)); // 8h00 - -public class DailyDigestJob -{ - public async Task ExecuteAsync(CancellationToken ct) - { - var users = await _db.Users - .Where(u => u.NotificationConfig.DailyDigest) - .ToListAsync(ct); - - foreach (var user in users) - { - var stats = await BuildDailyStatsAsync(user.Id, ct); - BackgroundJob.Enqueue(j => - j.ExecuteAsync(stats, "email", user.NotificationConfig.Language, ct)); - } - } -} -``` - ---- - -## 9. Tests - -``` -Notification is sent when person detected -SMTP failure retries 3 times via Hangfire -Gotify notification is sent correctly -User can disable email notifications -Template rendering replaces all variables -Missing variable does not crash (Scriban safe) -Template editing in UI saves correctly -Template preview shows correct rendering -Fallback to default template works -Fallback to English template works -Daily digest is generated at configured hour -User language changes template language -Admin can test SMTP connection from UI -Admin can test Gotify connection from UI -``` diff --git a/skills/notification-center/SKILL.md b/skills/notification-center/SKILL.md index 8d06e24..f5efe78 100644 --- a/skills/notification-center/SKILL.md +++ b/skills/notification-center/SKILL.md @@ -7,7 +7,7 @@ description: Implement and accept the authenticated Heimdall in-app notification The header bell is rendered by `Components/Shared/NotificationBadge.razor`; it displays the unread count delivered by `NotificationsHubClient` and must navigate to `/notifications`. The page reads the signed-in user's list through `HeimdallApiClient` and the existing `GET /api/notifications` endpoint. Read actions use the existing per-user `POST /api/notifications/{id}/read` and `POST /api/notifications/mark-all-read` endpoints, then refresh the hub count. Keep authorization on the page and user scoping in the API/application handlers; never accept a user id from the browser. -When documenting delivery channels, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. In `docs/notifications.md`, keep old Gotify/template UI sketches explicitly labeled as historical design when they are retained. +When documenting delivery channels, verify `NotificationChannel`, `SendNotificationJob`, `NotificationSettingsSection.razor`, `Profile.razor`, the delivery services, and `BackgroundJobs/JobSetup.cs`. The shipped external channels are SMTP email and ntfy; do not describe Gotify as integrated. `/settings` owns global SMTP/ntfy settings and test actions, while `/profile` owns user preferences. Check both digest job implementations and their schedules before documenting cadence. Distinguish source inspection from validation against a real SMTP/ntfy deployment. Remove obsolete channel integrations, editor flows, and test claims from `docs/notifications.md`; if a historical example must remain, label that exact heading/table/snippet locally rather than relying on a broad notice elsewhere in the guide. ## Acceptance -- 2.54.1