fix(ui): apply site scope and the history status filter in the server query, before paging (UI-7, UI-9, UI-10, WP1 task 1.7)

UI-7: Site Calls and the Notification report sent an unscoped query and
dropped other sites' rows client-side after paging - Site Calls pages
went short (Next disabled, own rows hidden), Notifications showed other
sites' counts and empty pages. New additive SourceSitesFilter on
SiteCallQueryRequest / NotificationOutboxQueryRequest (+ SourceSites /
SourceSiteIds on the repository filters; OPENJSON IN-list in the
SiteCalls keyset SQL, Contains in EF) carries the permitted identifiers;
an empty set matches nothing. Next is gated on the server page size.

UI-9: Secured Writes history paged over every status and filtered
terminal rows client-side. Additive ListSecuredWritesCommand.Statuses
reaches the repository query and count.

UI-10: Notification KPIs per-site table is narrowed to the caller's
sites (SiteScopeService.Resolve on the principal).

Tests: MSSQL mixed-site keyset/offset paging + count for both repos and
the secured-write status set; handler forwards Statuses; UI pages send
the permitted set (scoped) / none (system-wide); history requests the
terminal statuses; KPI per-site rows narrowed.
This commit is contained in:
Joseph Doherty
2026-12-03 10:21:01 -05:00
parent 2162fad8e9
commit 5a052c6327
29 changed files with 415 additions and 44 deletions
@@ -11,6 +11,7 @@
@inject ISiteRepository SiteRepository
@inject IKpiHistoryQueryService KpiHistory
@inject ILogger<NotificationKpis> Logger
@inject AuthenticationStateProvider AuthStateProvider
<div class="container-fluid mt-3">
<div class="page-head justify-content-between">
@@ -238,8 +239,18 @@
private bool _deliveredAvailable = true;
private string? _deliveredError;
// Code review 2026-12-02 UI-10: the per-site table is narrowed to the caller's permitted
// sites (by identifier). null = system-wide (no narrowing).
private HashSet<string>? _permittedSiteIdentifiers;
protected override async Task OnInitializedAsync()
{
// Resolve the caller's site scope once from the principal (no extra revalidation —
// SiteScopeService.Resolve is the pure rule PendingUpdatesHealthTiles uses). An
// unauthenticated principal is scoped to nothing.
var user = (await AuthStateProvider.GetAuthenticationStateAsync()).User;
var (isSystemWide, permittedIds) = SiteScopeService.Resolve(user);
try
{
_sites = (await SiteRepository.GetAllSitesAsync()).ToList();
@@ -250,6 +261,13 @@
Logger.LogWarning(ex, "Failed to load sites for the KPI per-site breakdown.");
}
// A scoped caller whose sites could not be loaded sees no per-site rows (fail closed).
_permittedSiteIdentifiers = isSystemWide
? null
: _sites.Where(s => permittedIds.Contains(s.Id))
.Select(s => s.SiteIdentifier)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
// First load rides whatever the shared KPI cache already holds fresh; the
// Refresh button forces a new query (see RefreshAll).
await LoadAllAsync(forceRefresh: false);
@@ -357,7 +375,9 @@
var response = await KpiSnapshots.GetPerSiteNotificationKpisAsync(forceRefresh);
if (response.Success)
{
_perSite = response.Sites;
_perSite = _permittedSiteIdentifiers is { } permitted
? response.Sites.Where(s => permitted.Contains(s.SourceSiteId)).ToList()
: response.Sites;
_perSiteError = null;
}
else
@@ -560,16 +560,17 @@
PageNumber: _pageNumber,
PageSize: _pageSize,
SourceNodeFilter: NullIfEmpty(_nodeFilter),
NotificationIdFilter: _notificationIdFilter);
NotificationIdFilter: _notificationIdFilter,
// Code review 2026-12-02 UI-7: push the caller's permitted sites into the
// query so the page and the total count cover only rows they may see.
SourceSitesFilter: ScopedSourceSites());
var response = await CommunicationService.QueryNotificationOutboxAsync(request);
if (response.Success)
{
// CentralUI-028: drop any row whose source site is outside the
// user's permitted set. The query API accepts only a single
// SourceSiteFilter, so a scoped user with an empty filter could
// otherwise see every site's rows; this is the row-level safety
// net behind the dropdown restriction.
// The permitted set is now applied server-side (SourceSitesFilter), so
// paging and _totalCount are over in-scope rows only (UI-7). This
// client-side pass stays as the row-level backstop (CentralUI-028).
_notifications = await FilterPermittedAsync(response.Notifications);
_totalCount = response.TotalCount;
}
@@ -815,6 +816,11 @@
/// A truly unknown <c>SourceSiteId</c> (stale row from a deleted site) is kept —
/// there is no Site.Id to gate it on.
/// </summary>
private IReadOnlyList<string>? ScopedSourceSites() =>
// System-wide: no constraint. Scoped: the permitted sites' identifiers (the
// dropdown's site list) — EMPTY if none resolved, which matches nothing.
_siteScopeSystemWide ? null : _sites.Select(s => s.SiteIdentifier).ToList();
private Task<List<NotificationSummary>> FilterPermittedAsync(
IEnumerable<NotificationSummary> notifications)
{
@@ -354,9 +354,13 @@
.Where(w => string.Equals(w.Status, "Pending", StringComparison.OrdinalIgnoreCase))
.ToList();
// History: terminal rows, offset-paged. TotalCount drives the pager bounds.
// History: terminal rows, offset-paged. TotalCount drives the pager bounds. The
// terminal-status filter runs server-side (code review 2026-12-02 UI-9) so Pending
// rows no longer take page slots or inflate the count; the client filter below
// stays only as a backstop.
var history = await SecuredWriteSvc.ListAsync(
status: null, siteId: null, skip: _historyPage * HistoryPageSize, take: HistoryPageSize);
status: null, siteId: null, skip: _historyPage * HistoryPageSize, take: HistoryPageSize,
statuses: TerminalStatuses);
_history = history.Items
.Where(w => TerminalStatuses.Contains(w.Status, StringComparer.OrdinalIgnoreCase))
.ToList();
@@ -286,7 +286,12 @@ public partial class SiteCallsReport
AfterId: cursor.AfterId,
PageSize: PageSize,
SourceNodeFilter: NullIfEmpty(_nodeFilter),
TrackedOperationIdFilter: _operationIdFilter);
TrackedOperationIdFilter: _operationIdFilter,
// Code review 2026-12-02 UI-7: push the caller's permitted sites into the
// query so keyset paging runs over rows they may see. The old client-side
// filter after paging left out-of-scope-heavy pages short, which disabled
// Next and hid the caller's own rows further down.
SourceSitesFilter: ScopedSourceSites());
var response = await CommunicationService.QuerySiteCallsAsync(request);
if (response.Success)
@@ -299,10 +304,11 @@ public partial class SiteCallsReport
// The response echoes the last row's cursor. A short page (fewer
// rows than requested) has no further page even if a cursor came
// back, so gate Next on a full page too.
// back, so gate Next on a full page too — the SERVER page, not the
// client-filtered one (the backstop filter must not end paging).
_nextCursor = response.NextAfterCreatedAtUtc is { } nextCreated
&& response.NextAfterId is { } nextId
&& _siteCalls.Count == PageSize
&& response.SiteCalls.Count == PageSize
? (nextCreated, nextId)
: null;
}
@@ -571,6 +577,14 @@ public partial class SiteCallsReport
/// Lookup uses <c>_allSites</c> (not <c>_sites</c>) so a row whose Site was
/// filtered OUT of the dropdown is correctly classified as out-of-scope.
/// </summary>
/// <summary>
/// The caller's permitted source sites for the server query: <c>null</c> for a
/// system-wide user, else the identifiers of the permitted sites (the dropdown list) —
/// EMPTY if none resolved, which matches nothing (code review 2026-12-02 UI-7).
/// </summary>
private IReadOnlyList<string>? ScopedSourceSites() =>
_siteScopeSystemWide ? null : _sites.Select(s => s.SiteIdentifier).ToList();
private Task<List<SiteCallSummary>> FilterPermittedAsync(
IEnumerable<SiteCallSummary> calls)
{
@@ -101,9 +101,12 @@ public interface ISecuredWriteService
/// <param name="siteId">Site id filter; <c>null</c> matches every site.</param>
/// <param name="skip">Rows to skip (offset paging); clamped to &gt;= 0 server-side.</param>
/// <param name="take">Maximum rows to return; clamped to 1..500 server-side.</param>
/// <param name="statuses">When non-null, only these statuses match — applied server-side
/// before paging and counting (code review 2026-12-02 UI-9).</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task resolving to the matching page + total match count, newest submission first.</returns>
Task<SecuredWriteListResult> ListAsync(
string? status, string? siteId, int skip = 0, int take = 200,
IReadOnlyList<string>? statuses = null,
CancellationToken cancellationToken = default);
}
@@ -82,10 +82,11 @@ public sealed class SecuredWriteService : ISecuredWriteService
/// <inheritdoc/>
public async Task<SecuredWriteListResult> ListAsync(
string? status, string? siteId, int skip = 0, int take = 200,
IReadOnlyList<string>? statuses = null,
CancellationToken cancellationToken = default)
{
var response = await SendAsync(
new ListSecuredWritesCommand(status, siteId, skip, take), cancellationToken);
new ListSecuredWritesCommand(status, siteId, skip, take, statuses), cancellationToken);
if (response is ManagementSuccess success)
{
var result = JsonSerializer.Deserialize<SecuredWriteListResult>(
@@ -51,6 +51,10 @@ public interface ISecuredWriteRepository
/// to <paramref name="siteId"/>. Used by the ManagementActor to constrain an unfiltered
/// list to a site-scoped caller's permitted sites at the query level (arch-review R2 N3),
/// so paging and totals stay correct.</param>
/// <param name="statuses">When non-null, only rows whose <c>Status</c> is in the set match
/// (code review 2026-12-02 UI-9: the Secured Writes history asks for the terminal statuses
/// so paging and the total count run over them in SQL). Applied IN ADDITION to
/// <paramref name="status"/>; an empty set matches nothing.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that resolves to a page of matching rows, newest submission first.</returns>
Task<IReadOnlyList<PendingSecuredWrite>> QueryAsync(
@@ -59,6 +63,7 @@ public interface ISecuredWriteRepository
int skip,
int take,
IReadOnlyCollection<string>? permittedSiteIds = null,
IReadOnlyCollection<string>? statuses = null,
CancellationToken ct = default);
/// <summary>
@@ -146,12 +151,17 @@ public interface ISecuredWriteRepository
/// to <paramref name="siteId"/>. Used by the ManagementActor to constrain an unfiltered
/// list to a site-scoped caller's permitted sites at the query level (arch-review R2 N3),
/// so paging and totals stay correct.</param>
/// <param name="statuses">When non-null, only rows whose <c>Status</c> is in the set match
/// (code review 2026-12-02 UI-9: the Secured Writes history asks for the terminal statuses
/// so paging and the total count run over them in SQL). Applied IN ADDITION to
/// <paramref name="status"/>; an empty set matches nothing.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that resolves to the count of matching rows.</returns>
Task<int> CountAsync(
string? status,
string? siteId,
IReadOnlyCollection<string>? permittedSiteIds = null,
IReadOnlyCollection<string>? statuses = null,
CancellationToken ct = default);
/// <summary>
@@ -27,6 +27,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Audit;
/// Flow Debugger / Audit Log); <c>null</c> = no filter. Additive, trailing
/// optional so existing positional callers are unaffected.
/// </param>
/// <param name="SourceSitesFilter">
/// Restrict to rows from ANY of these source sites (site identifiers) — the caller's
/// permitted set for a site-scoped user, so the scope is applied in the query BEFORE paging
/// (code review 2026-12-02 UI-7). <c>null</c> = no constraint; an EMPTY list matches nothing
/// (fail closed). Composes (AND) with <see cref="SourceSiteFilter"/>. Additive.
/// </param>
public sealed record SiteCallQueryRequest(
string CorrelationId,
string? StatusFilter,
@@ -40,7 +46,8 @@ public sealed record SiteCallQueryRequest(
Guid? AfterId,
int PageSize,
string? SourceNodeFilter = null,
Guid? TrackedOperationIdFilter = null);
Guid? TrackedOperationIdFilter = null,
IReadOnlyList<string>? SourceSitesFilter = null);
/// <summary>
/// A single <c>SiteCalls</c> row summarised for the Site Calls UI grid. Carries
@@ -60,7 +60,14 @@ public record RejectSecuredWriteCommand(long Id, string? Comment);
/// <param name="SiteId">Site id filter; <c>null</c> matches every site.</param>
/// <param name="Skip">Number of rows to skip (offset paging); clamped to &gt;= 0 server-side.</param>
/// <param name="Take">Maximum rows to return; clamped to 1..500 server-side. Default 200.</param>
public record ListSecuredWritesCommand(string? Status, string? SiteId, int Skip = 0, int Take = 200);
/// <param name="Statuses">
/// Additive (code review 2026-12-02 UI-9): when non-null, only rows whose status is in the set
/// match — the Central UI history asks for the terminal statuses so paging and the total
/// count run over them in SQL instead of filtering a mixed page client-side. Composes (AND)
/// with <paramref name="Status"/>. <c>null</c> = no constraint.
/// </param>
public record ListSecuredWritesCommand(string? Status, string? SiteId, int Skip = 0, int Take = 200,
IReadOnlyList<string>? Statuses = null);
/// <summary>
/// Result projection of a single pending secured write row, mirroring the
@@ -11,6 +11,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Notification;
/// Flow Debugger / Audit Log. Additive; <c>null</c> means "no filter" (legacy senders
/// compile unchanged).
/// </param>
/// <param name="SourceSitesFilter">
/// Restrict to rows from ANY of these source sites — the caller's permitted set for a
/// site-scoped user, so the scope applies in the query before paging AND counting (code
/// review 2026-12-02 UI-7). <c>null</c> = no constraint; an EMPTY list matches nothing.
/// Composes (AND) with <see cref="SourceSiteFilter"/>. Additive.
/// </param>
public record NotificationOutboxQueryRequest(
string CorrelationId,
string? StatusFilter,
@@ -24,7 +30,8 @@ public record NotificationOutboxQueryRequest(
int PageNumber,
int PageSize,
string? SourceNodeFilter = null,
string? NotificationIdFilter = null);
string? NotificationIdFilter = null,
IReadOnlyList<string>? SourceSitesFilter = null);
/// <summary>
/// A single notification row summarised for outbox UI display.
@@ -37,6 +37,10 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
/// <c>null</c> means "do not constrain". AND-combined with every other field,
/// so a mismatching <see cref="SourceSite"/> (etc.) still yields no rows.
/// </param>
/// <param name="SourceSites">
/// Restrict to rows from ANY of these source sites (the site-scoped caller's permitted set,
/// code review 2026-12-02 UI-7). <c>null</c> = no constraint; an EMPTY list matches nothing.
/// </param>
public sealed record SiteCallQueryFilter(
string? Channel = null,
string? SourceSite = null,
@@ -46,4 +50,5 @@ public sealed record SiteCallQueryFilter(
DateTime? ToUtc = null,
DateTime? StuckCutoffUtc = null,
string? SourceNode = null,
Guid? TrackedOperationId = null);
Guid? TrackedOperationId = null,
IReadOnlyList<string>? SourceSites = null);
@@ -27,6 +27,10 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Notifications;
/// Exact match on a single <c>NotificationId</c> — the <c>?correlationId=</c> deep link
/// from the Flow Debugger / Audit Log. <c>null</c> means "do not constrain".
/// </param>
/// <param name="SourceSiteIds">
/// Restrict to notifications from ANY of these sites (the site-scoped caller's permitted set,
/// code review 2026-12-02 UI-7). <c>null</c> = no constraint; an EMPTY list matches nothing.
/// </param>
public record NotificationOutboxFilter(
NotificationStatus? Status = null,
NotificationType? Type = null,
@@ -38,4 +42,5 @@ public record NotificationOutboxFilter(
DateTimeOffset? From = null,
DateTimeOffset? To = null,
string? SourceNode = null,
string? NotificationId = null);
string? NotificationId = null,
IReadOnlyList<string>? SourceSiteIds = null);
@@ -348,6 +348,15 @@ VALUES
query = query.Where(n => n.SourceSiteId == filter.SourceSiteId);
}
// Code review 2026-12-02 UI-7: a site-scoped caller's permitted set, applied in the
// query so the page AND the total count cover only rows the caller may see. An
// empty set matches nothing (fail closed).
if (filter.SourceSiteIds is { } sourceSiteIds)
{
var permitted = sourceSiteIds.ToList();
query = query.Where(n => permitted.Contains(n.SourceSiteId));
}
// SourceNode is exact-match like SourceSiteId. Rows with NULL
// SourceNode (legacy / unconfigured) are excluded when the filter is set.
if (!string.IsNullOrEmpty(filter.SourceNode))
@@ -58,6 +58,7 @@ public class SecuredWriteRepository : ISecuredWriteRepository
int skip,
int take,
IReadOnlyCollection<string>? permittedSiteIds = null,
IReadOnlyCollection<string>? statuses = null,
CancellationToken ct = default)
{
IQueryable<PendingSecuredWrite> query = _context.Set<PendingSecuredWrite>()
@@ -78,6 +79,11 @@ public class SecuredWriteRepository : ISecuredWriteRepository
query = query.Where(p => permittedSiteIds.Contains(p.SiteId));
}
if (statuses is not null)
{
query = query.Where(p => statuses.Contains(p.Status));
}
return await query
.OrderByDescending(p => p.SubmittedAtUtc)
.ThenByDescending(p => p.Id)
@@ -166,6 +172,7 @@ WHERE Id = {id}
string? status,
string? siteId,
IReadOnlyCollection<string>? permittedSiteIds = null,
IReadOnlyCollection<string>? statuses = null,
CancellationToken ct = default)
{
IQueryable<PendingSecuredWrite> query = _context.Set<PendingSecuredWrite>()
@@ -186,6 +193,11 @@ WHERE Id = {id}
query = query.Where(p => permittedSiteIds.Contains(p.SiteId));
}
if (statuses is not null)
{
query = query.Where(p => statuses.Contains(p.Status));
}
return await query.CountAsync(ct);
}
@@ -425,6 +425,9 @@ SELECT TOP (@PageSize)
FROM dbo.SiteCalls
WHERE (@Channel IS NULL OR Channel = @Channel)
AND (@SourceSite IS NULL OR SourceSite = @SourceSite)
-- Code review 2026-12-02 UI-7: a site-scoped caller's permitted set (JSON array), applied
-- here so keyset paging runs over rows the caller may see; '[]' matches nothing.
AND (@SourceSites IS NULL OR SourceSite IN (SELECT CAST([value] AS varchar(8000)) FROM OPENJSON(@SourceSites)))
AND (@SourceNode IS NULL OR SourceNode = @SourceNode)
AND (@Status IS NULL OR Status = @Status)
AND (@Target IS NULL OR Target = @Target)
@@ -449,6 +452,8 @@ OPTION (RECOMPILE);";
Param("@PageSize", SqlDbType.Int, paging.PageSize),
Param("@Channel", SqlDbType.VarChar, filter.Channel),
Param("@SourceSite", SqlDbType.VarChar, filter.SourceSite),
Param("@SourceSites", SqlDbType.NVarChar,
filter.SourceSites is null ? null : System.Text.Json.JsonSerializer.Serialize(filter.SourceSites)),
Param("@SourceNode", SqlDbType.VarChar, filter.SourceNode),
Param("@Status", SqlDbType.VarChar, filter.Status),
Param("@Target", SqlDbType.VarChar, filter.Target),
@@ -1949,8 +1949,8 @@ public class ManagementActor : ReceiveActor
// command can neither request a negative offset nor an unbounded page.
var take = Math.Clamp(cmd.Take, 1, 500);
var skip = Math.Max(0, cmd.Skip);
var rows = await repo.QueryAsync(cmd.Status, cmd.SiteId, skip, take, permittedIdentifiers);
var totalCount = await repo.CountAsync(cmd.Status, cmd.SiteId, permittedIdentifiers);
var rows = await repo.QueryAsync(cmd.Status, cmd.SiteId, skip, take, permittedIdentifiers, cmd.Statuses);
var totalCount = await repo.CountAsync(cmd.Status, cmd.SiteId, permittedIdentifiers, cmd.Statuses);
// Opportunistic expiry sweep (arch-review S2): every time the list is read, walk
// the page and expire any overdue Pending row. TryExpireIfStaleAsync self-filters
@@ -1047,7 +1047,8 @@ public class NotificationOutboxActor : ReceiveActor, IWithTimers
From: request.From,
To: request.To,
SourceNode: request.SourceNodeFilter,
NotificationId: request.NotificationIdFilter);
NotificationId: request.NotificationIdFilter,
SourceSiteIds: request.SourceSitesFilter);
using var scope = _serviceProvider.CreateScope();
var repository = scope.ServiceProvider.GetRequiredService<INotificationOutboxRepository>();
@@ -863,7 +863,8 @@ public class SiteCallAuditActor : ReceiveActor
// pages with a non-null next cursor).
StuckCutoffUtc: request.StuckOnly ? stuckCutoff : null,
SourceNode: NullIfBlank(request.SourceNodeFilter),
TrackedOperationId: request.TrackedOperationIdFilter);
TrackedOperationId: request.TrackedOperationIdFilter,
SourceSites: request.SourceSitesFilter);
var pageSize = Math.Clamp(request.PageSize, 1, MaxPageSize);
var paging = new SiteCallPaging(