feat(ui): Audit KPI tiles on Health dashboard (#23 M7)

Adds three KPI tiles to the central Health dashboard for the Audit channel:
volume (rows in the last hour), error rate (Failed/Parked/Discarded over
total), and backlog (sum of SiteAuditBacklog.PendingCount across all sites).

Repo + service:
- IAuditLogRepository.GetKpiSnapshotAsync(window, nowUtc) — single aggregate
  SELECT over the trailing window returning total + error counts; nowUtc is
  optional for production callers and pinned by integration tests against the
  shared MSSQL fixture so the global counts are deterministic.
- AuditLogQueryService.GetKpiSnapshotAsync() — composes the repo aggregate
  with a sum of SiteAuditBacklog.PendingCount read from ICentralHealthAggregator.
- AuditLogKpiSnapshot record in Commons/Types/.

UI:
- New AuditKpiTiles Blazor component (Components/Health/) — three Bootstrap
  card-tiles, click navigates to /audit/log with the matching pre-filter.
- Health.razor wires the tiles in alongside the existing Notification Outbox
  KPIs; LoadAuditKpis() runs on every 10s refresh tick and degrades to em
  dashes + inline error if the query fails.
- AuditLogPage extended to parse ?status= so the error-rate tile drill-in
  (?status=Failed) auto-loads the grid.

Tests:
- AuditLogRepositoryTests: GetKpiSnapshotAsync mixed-status + empty-window
  cases against the MSSQL migration fixture.
- AuditLogQueryServiceTests: forwarding + backlog composition; sites with
  null SiteAuditBacklog contribute zero.
- AuditKpiTilesTests: 9 bUnit tests covering tile render, error-rate maths
  with safe zero-events handling, em-dash unavailable path, click-through
  navigation, and warning/danger border thresholds.
- HealthPageTests: new Renders_AuditKpiTiles_WithValues plus IAuditLogQueryService
  stub registration in the constructor so existing outbox tests still pass.
- AuditLogPageScaffoldTests: ?status=Failed auto-load + unknown status drop.
This commit is contained in:
Joseph Doherty
2026-05-20 20:43:57 -04:00
parent 38fc9b4102
commit 943c2ced39
18 changed files with 969 additions and 7 deletions

View File

@@ -2,8 +2,11 @@ using NSubstitute;
using ScadaLink.CentralUI.Services;
using ScadaLink.Commons.Entities.Audit;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Messages.Health;
using ScadaLink.Commons.Types;
using ScadaLink.Commons.Types.Audit;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.HealthMonitoring;
namespace ScadaLink.CentralUI.Tests.Services;
@@ -15,6 +18,13 @@ namespace ScadaLink.CentralUI.Tests.Services;
/// </summary>
public class AuditLogQueryServiceTests
{
private static ICentralHealthAggregator EmptyAggregator()
{
var agg = Substitute.For<ICentralHealthAggregator>();
agg.GetAllSiteStates().Returns(new Dictionary<string, SiteHealthState>());
return agg;
}
[Fact]
public async Task QueryAsync_ForwardsFilterAndPaging_ToRepository()
{
@@ -28,7 +38,7 @@ public class AuditLogQueryServiceTests
repo.QueryAsync(filter, paging, Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(expected));
var sut = new AuditLogQueryService(repo);
var sut = new AuditLogQueryService(repo, EmptyAggregator());
var result = await sut.QueryAsync(filter, paging);
@@ -44,7 +54,7 @@ public class AuditLogQueryServiceTests
repo.QueryAsync(Arg.Any<AuditLogQueryFilter>(), Arg.Do<AuditLogPaging>(p => observed = p), Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
var sut = new AuditLogQueryService(repo);
var sut = new AuditLogQueryService(repo, EmptyAggregator());
await sut.QueryAsync(new AuditLogQueryFilter(), paging: null);
@@ -54,4 +64,103 @@ public class AuditLogQueryServiceTests
Assert.Null(observed.AfterOccurredAtUtc);
Assert.Null(observed.AfterEventId);
}
// ─────────────────────────────────────────────────────────────────────────
// M7-T13 Bundle E: GetKpiSnapshotAsync — composes repo + health-aggregator
// ─────────────────────────────────────────────────────────────────────────
[Fact]
public async Task GetKpiSnapshotAsync_ForwardsToRepo_AddsBacklogFromHealthAggregator()
{
var repo = Substitute.For<IAuditLogRepository>();
var anchor = new DateTime(2026, 5, 20, 10, 0, 0, DateTimeKind.Utc);
var repoSnapshot = new AuditLogKpiSnapshot(
TotalEventsLastHour: 42,
ErrorEventsLastHour: 7,
BacklogTotal: 0, // repo leaves this at zero
AsOfUtc: anchor);
repo.GetKpiSnapshotAsync(Arg.Any<TimeSpan>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(repoSnapshot));
// Two sites: plant-a with PendingCount=5, plant-b with PendingCount=11.
// Sum = 16 → backlog tile shows 16.
var sites = new Dictionary<string, SiteHealthState>
{
["plant-a"] = StateWithBacklog("plant-a", pending: 5),
["plant-b"] = StateWithBacklog("plant-b", pending: 11),
};
var agg = Substitute.For<ICentralHealthAggregator>();
agg.GetAllSiteStates().Returns(sites);
var sut = new AuditLogQueryService(repo, agg);
var snapshot = await sut.GetKpiSnapshotAsync();
Assert.Equal(42, snapshot.TotalEventsLastHour);
Assert.Equal(7, snapshot.ErrorEventsLastHour);
Assert.Equal(16, snapshot.BacklogTotal);
Assert.Equal(anchor, snapshot.AsOfUtc);
// The service requests a 1-hour trailing window and lets the repo
// anchor nowUtc to its own clock — we leave the second parameter null.
await repo.Received(1).GetKpiSnapshotAsync(
TimeSpan.FromHours(1),
Arg.Is<DateTime?>(v => v == null),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetKpiSnapshotAsync_SiteWithoutBacklogSnapshot_ContributesZero()
{
var repo = Substitute.For<IAuditLogRepository>();
repo.GetKpiSnapshotAsync(Arg.Any<TimeSpan>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new AuditLogKpiSnapshot(0, 0, 0, DateTime.UtcNow)));
// plant-a has no LatestReport at all; plant-b has a report but null SiteAuditBacklog.
var sites = new Dictionary<string, SiteHealthState>
{
["plant-a"] = new() { SiteId = "plant-a", LatestReport = null, IsOnline = true },
["plant-b"] = StateWithBacklog("plant-b", pending: null),
["plant-c"] = StateWithBacklog("plant-c", pending: 4),
};
var agg = Substitute.For<ICentralHealthAggregator>();
agg.GetAllSiteStates().Returns(sites);
var sut = new AuditLogQueryService(repo, agg);
var snapshot = await sut.GetKpiSnapshotAsync();
// Only plant-c contributes; plant-a (no report) and plant-b (null backlog) yield zero.
Assert.Equal(4, snapshot.BacklogTotal);
}
private static SiteHealthState StateWithBacklog(string siteId, int? pending)
{
SiteAuditBacklogSnapshot? backlog = pending.HasValue
? new SiteAuditBacklogSnapshot(pending.Value, OldestPendingUtc: null, OnDiskBytes: 0)
: null;
var report = new SiteHealthReport(
SiteId: siteId,
SequenceNumber: 1,
ReportTimestamp: DateTimeOffset.UtcNow,
DataConnectionStatuses: new Dictionary<string, ConnectionHealth>(),
TagResolutionCounts: new Dictionary<string, TagResolutionStatus>(),
ScriptErrorCount: 0,
AlarmEvaluationErrorCount: 0,
StoreAndForwardBufferDepths: new Dictionary<string, int>(),
DeadLetterCount: 0,
DeployedInstanceCount: 0,
EnabledInstanceCount: 0,
DisabledInstanceCount: 0,
SiteAuditBacklog: backlog);
return new SiteHealthState
{
SiteId = siteId,
LatestReport = report,
LastReportReceivedAt = DateTimeOffset.UtcNow,
LastHeartbeatAt = DateTimeOffset.UtcNow,
LastSequenceNumber = 1,
IsOnline = true,
};
}
}