fix(web): open a notification center from the header #307

Merged
arnaud.dartois merged 4 commits from fix/302-notification-center into main 2026-11-08 18:57:33 +01:00
7 changed files with 169 additions and 1 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
---
name: notification-center
description: Implement and accept the authenticated Heimdall in-app notification center.
---
# Notification center
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.
## Acceptance
1. Build `Heimdall.Web` with the SDK from `global.json` and run focused Web tests.
2. In disposable Central + PostgreSQL Compose, create only synthetic notifications for the disposable admin, open `/notifications` from the header bell, confirm notification content appears and `/events` is not loaded.
3. Mark one item read and all items read; verify displayed state and unread badge refresh. Confirm empty and API failure states render.
4. Use unique Compose project, generated credentials, loopback port, and project-owned image tag. Follow `compose-disposable-recipe` exactly: remove only that project and exact local tag, verify project containers/volumes/networks and image tag are absent, and retain shared images.
The empty and failed API states have focused bUnit coverage in `NotificationsPageTests`. Simulate the API error with an HTTP 500 response for `GET /api/notifications`; taking PostgreSQL offline also breaks server-side session validation before the page can handle the notification request.
@@ -0,0 +1,88 @@
@page "/notifications"
@using Heimdall.Application.DTOs
@attribute [Authorize]
@layout MainLayout
@inject HeimdallApiClient Api
@inject NotificationsHubClient Hub
@inject UiText Text
@inject ISnackbar Snackbar
<MudText Typo="Typo.h1" Class="mb-4">@Text["NotificationsPage_Title"]</MudText>
@if (_loading)
{
<MudProgressLinear Indeterminate="true" />
}
else if (_failed)
{
<MudAlert Severity="Severity.Error">@Text["NotificationsPage_Failed"]</MudAlert>
}
else if (_items.Count == 0)
{
<MudAlert Severity="Severity.Info">@Text["NotificationsPage_Empty"]</MudAlert>
}
else
{
<div class="d-flex justify-end mb-3">
<MudButton Variant="Variant.Outlined" Disabled="@(!_items.Any(x => !x.IsRead))" OnClick="MarkAllReadAsync">
@Text["NotificationsPage_MarkAllRead"]
</MudButton>
</div>
@foreach (var item in _items)
{
<MudPaper Class="pa-4 mb-2" Elevation="1">
<div class="d-flex justify-space-between align-start">
<div>
<MudText Typo="Typo.h6">@item.Title</MudText>
<MudText>@item.Message</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">@item.CreatedAt.ToLocalTime().ToString("g")</MudText>
</div>
@if (!item.IsRead)
{
<MudButton Variant="Variant.Text" OnClick="@(() => MarkReadAsync(item.Id))">@Text["NotificationsPage_MarkRead"]</MudButton>
}
</div>
</MudPaper>
}
}
@code {
private List<NotificationDto> _items = [];
private bool _loading = true;
private bool _failed;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
_loading = true;
_failed = false;
try
{
var result = await Api.GetNotificationsAsync();
_items = result?.Items.ToList() ?? [];
_failed = result is null;
}
catch (HttpRequestException) { _failed = true; }
finally { _loading = false; }
}
private async Task MarkReadAsync(Guid id)
{
if (await Api.MarkNotificationAsReadAsync(id))
{
await LoadAsync();
await Hub.RefreshUnreadCountAsync();
}
else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error);
}
private async Task MarkAllReadAsync()
{
if (await Api.MarkAllNotificationsAsReadAsync())
{
await LoadAsync();
await Hub.RefreshUnreadCountAsync();
}
else Snackbar.Add(Text["NotificationsPage_UpdateFailed"], Severity.Error);
}
}
@@ -10,7 +10,7 @@
Visible="@(Hub.UnreadCount > 0)">
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit"
aria-label="@Text["SharedNotificationBadge_Title"]"
OnClick="@(() => Navigation.NavigateTo("/events"))" />
OnClick="@(() => Navigation.NavigateTo("/notifications"))" />
</MudBadge>
</MudTooltip>
@@ -4133,4 +4133,10 @@
<data name="CameraDetail_PlateOcrConfirm" xml:space="preserve"><value>Confirmer le lien</value></data>
<data name="CameraDetail_PlateOcrLinked" xml:space="preserve"><value>L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné.</value></data>
<data name="CameraDetail_PlateOcrNoVehicle" xml:space="preserve"><value>Aucun véhicule correspondant trouvé. L’observation reste sans lien.</value></data>
<data name="NotificationsPage_Title"><value>Notifications</value></data>
<data name="NotificationsPage_Failed"><value>Impossible de charger les notifications. Réessayez.</value></data>
<data name="NotificationsPage_Empty"><value>Vous n’avez aucune notification.</value></data>
<data name="NotificationsPage_MarkAllRead"><value>Tout marquer comme lu</value></data>
<data name="NotificationsPage_MarkRead"><value>Marquer comme lu</value></data>
<data name="NotificationsPage_UpdateFailed"><value>Impossible de mettre à jour la notification.</value></data>
</root>
@@ -4133,4 +4133,10 @@
<data name="CameraDetail_PlateOcrConfirm" xml:space="preserve"><value>Confirmer le lien</value></data>
<data name="CameraDetail_PlateOcrLinked" xml:space="preserve"><value>L’observation de plaque et son événement sont maintenant liés au véhicule sélectionné.</value></data>
<data name="CameraDetail_PlateOcrNoVehicle" xml:space="preserve"><value>Aucun véhicule correspondant trouvé. L’observation reste sans lien.</value></data>
<data name="NotificationsPage_Title"><value>Notifications</value></data>
<data name="NotificationsPage_Failed"><value>Notifications could not be loaded. Try again.</value></data>
<data name="NotificationsPage_Empty"><value>You have no notifications.</value></data>
<data name="NotificationsPage_MarkAllRead"><value>Mark all as read</value></data>
<data name="NotificationsPage_MarkRead"><value>Mark as read</value></data>
<data name="NotificationsPage_UpdateFailed"><value>The notification could not be updated.</value></data>
</root>
@@ -1037,6 +1037,25 @@ public class HeimdallApiClient : IDisposable
// ─── Notification Config ─────────────────────────────────────────
public async Task<PagedResult<NotificationDto>?> GetNotificationsAsync(int page = 1, int pageSize = 20)
{
var client = CreateClient();
return await client.GetFromJsonAsync<PagedResult<NotificationDto>>(
$"api/notifications?page={page}&pageSize={pageSize}", Json);
}
public async Task<bool> MarkNotificationAsReadAsync(Guid id)
{
using var response = await CreateClient().PostAsync($"api/notifications/{id}/read", content: null);
return response.IsSuccessStatusCode;
}
public async Task<bool> MarkAllNotificationsAsReadAsync()
{
using var response = await CreateClient().PostAsync("api/notifications/mark-all-read", content: null);
return response.IsSuccessStatusCode;
}
public async Task<NotificationConfigItem?> GetNotificationConfigAsync()
{
var client = CreateClient();
@@ -0,0 +1,32 @@
using Bunit;
using Bunit.TestDoubles;
using Heimdall.Application.DTOs;
using Heimdall.Web.Components.Pages;
using Shouldly;
namespace Heimdall.Web.Tests.Components.Pages;
public sealed class NotificationsPageTests : PageTestBase
{
[Fact]
public void NotificationsPage_EmptyList_ShowsEmptyState()
{
Handler.OnGet("api/notifications", new PagedResult<NotificationDto>([], 0, 1, 20));
LoginAs();
var cut = RenderPage<NotificationsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Vous n’avez aucune notification."));
}
[Fact]
public void NotificationsPage_ApiFailure_ShowsErrorState()
{
Handler.OnGet("api/notifications", System.Net.HttpStatusCode.InternalServerError);
LoginAs();
var cut = RenderPage<NotificationsPage>();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Impossible de charger les notifications. Réessayez."));
}
}