From 5a052c632705d9c79b77b39342d5ff0a85ca8ca8 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:21:01 -0500 Subject: [PATCH] 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. --- docs/requirements/Component-CentralUI.md | 4 +- .../Notifications/NotificationKpis.razor | 22 ++++++++- .../Notifications/NotificationReport.razor | 18 ++++--- .../Pages/Operations/SecuredWrites.razor | 8 ++- .../Pages/SiteCalls/SiteCallsReport.razor.cs | 20 ++++++-- .../Services/ISecuredWriteService.cs | 3 ++ .../Services/SecuredWriteService.cs | 3 +- .../Repositories/ISecuredWriteRepository.cs | 10 ++++ .../Messages/Audit/SiteCallQueries.cs | 9 +++- .../Management/SecuredWriteCommands.cs | 9 +++- .../Notification/NotificationOutboxQueries.cs | 9 +++- .../Types/Audit/SiteCallQueryFilter.cs | 7 ++- .../Notifications/NotificationOutboxFilter.cs | 7 ++- .../NotificationOutboxRepository.cs | 9 ++++ .../Repositories/SecuredWriteRepository.cs | 12 +++++ .../Repositories/SiteCallAuditRepository.cs | 5 ++ .../ManagementActor.cs | 4 +- .../NotificationOutboxActor.cs | 3 +- .../SiteCallAuditActor.cs | 3 +- .../Components/SecuredWritesTests.cs | 24 +++++++-- .../Pages/NotificationKpisPageTests.cs | 38 ++++++++++++++ .../Pages/NotificationReportPageTests.cs | 32 ++++++++++++ .../Pages/SiteCallsReportPageTests.cs | 32 ++++++++++++ ...icationOutboxRepositoryIntegrationTests.cs | 49 +++++++++++++++++-- .../SiteCallAuditRepositoryTests.cs | 40 +++++++++++++++ .../SecuredWriteRepositoryTests.cs | 27 ++++++++++ .../ManagementActorTests.cs | 2 +- .../SecuredWriteHandlerTests.cs | 48 +++++++++++++----- .../SecuredWriteTerminalPurgeTests.cs | 2 +- 29 files changed, 415 insertions(+), 44 deletions(-) diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index a1d98b6f..3335b2f5 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -279,13 +279,14 @@ Per-leaf alarm rendering (leaf nodes are individual conditions for native alarms - Each row exposes a **"View audit history"** action that opens the Audit Log page pre-filtered to `CorrelationId = NotificationId`, surfacing every operational audit event recorded for that notification. - **Stuck rows are visually badged** — a notification is stuck if it is `Pending` or `Retrying` and older than the configurable stuck-age threshold. Stuck detection is display-only; there is no automated escalation or alerting. - All queries are served from the central `Notifications` table — no remote per-site queries are needed, unlike the Parked Message Management page. +- **Site scope is applied in the query (code review 2026-12-02 UI-7).** For a site-scoped user the permitted sites' identifiers ride `NotificationOutboxQueryRequest.SourceSitesFilter`, so the page and the total count cover only rows they may see; the client-side row filter remains only as a backstop. (Before, the query was unscoped and the rows were filtered after paging — pages came back partly or wholly empty and the pager counted other sites' rows.) The **Notification KPIs** page (`/notifications/kpis`) likewise narrows its per-site breakdown to the caller's sites (UI-10); the global tiles and trends are unchanged. ### Secured Writes (Operator / Verifier / Administrator Roles) - A **Secured Writes** page (`/operations/secured-writes`) drives the **two-person** authorization workflow for writes through the MxAccess Gateway: an **Operator** initiates the write, a separate **Verifier** approves it, and only an approved write reaches the site. - The **page itself is gated by `RequireSecuredWriteAccess`** — satisfied by any of `Operator` / `Verifier` / `Administrator`. Although the pending/history lists are read-only, they expose process-sensitive tag values, so the page is not open to every authenticated user; this aligns with the ManagementActor `ListSecuredWritesCommand` any-of gate (arch-review UA1). The submit and approve/reject sub-actions are further gated by `RequireOperator` / `RequireVerifier` respectively (below). - **Operator (submit)** — a submit form gated by `RequireOperator`: pick the site → an **MxGateway** connection on that site → the tag path → a typed value → an optional comment. Submission inserts a `Pending` `PendingSecuredWrite` row centrally; it does **not** write anything yet. - **Verifier (approve / reject)** — a pending queue gated by `RequireVerifier` with **Approve** / **Reject** (+comment) actions. Approve shows a confirmation of the exact site / connection / tag / value before firing, and surfaces the **submission age** (`Submitted ago ()`) so a verifier can catch a stale setpoint before it reaches the device. The two confirmations are deliberately styled apart: **Approve is amber (`DialogSeverity.Caution`) and Reject stays red** — see the confirm-severity contract under Technology for why (register row 75). The verifier's **own submissions are disabled in the UI and rejected server-side** (no self-approval). On approve, central marks the row `Approved` and relays the write to the site MxGateway (records `Executed` / `Failed`); reject moves it to `Rejected` with a reason. The pending queue is **unpaged** — it is bounded by the submission **TTL**: a `Pending` row that is neither approved nor rejected before the TTL elapses expires to the terminal **`Expired`** status and drops out of the queue into History. -- **History** — terminal rows (Executed / Failed / Rejected / **Expired**, where `Expired` is a real TTL-driven terminal status) with the full who/when/outcome trail (operator, verifier, comments, timestamps, any execution error). Terminal rows accumulate without bound, so the History table is **offset-paged** (page-size 50, Prev/Next) driven by the server's unpaged `TotalCount` (`ListSecuredWritesCommand` `Skip`/`Take`); the pager buttons disable at the real bounds. +- **History** — terminal rows (Executed / Failed / Rejected / **Expired**, where `Expired` is a real TTL-driven terminal status) with the full who/when/outcome trail (operator, verifier, comments, timestamps, any execution error). Terminal rows accumulate without bound, so the History table is **offset-paged** (page-size 50, Prev/Next) driven by the server's unpaged `TotalCount` (`ListSecuredWritesCommand` `Skip`/`Take`); the pager buttons disable at the real bounds. The terminal-status filter runs **server-side** (`ListSecuredWritesCommand.Statuses`, code review 2026-12-02 UI-9), so `Pending` rows no longer occupy history page slots or inflate `TotalCount`. - Every lifecycle event (submit / approve / reject / execute) is written to the central Audit Log; the rows share the `PendingSecuredWrite.Id` as `CorrelationId` so they join into one operation (see Component-ManagementService.md, Component-AuditLog.md). - **Dev caveat**: with `DisableLogin` on, the auto-login identity holds all roles, so the two-person flow cannot be exercised end-to-end by a single user via the dev UI — no-self-approval is covered by handler tests; real two-person use requires two real identities. @@ -295,6 +296,7 @@ Per-leaf alarm rendering (leaf nodes are individual conditions for native alarms - **Retry** and **Discard** actions are available on `Parked` rows only — `Failed` rows are not actionable, since a permanent failure would simply fail again and its error was already returned synchronously to the calling script. The actions issue central→site commands to the owning site; if the site is offline the UI surfaces a "site unreachable" message. - Each row exposes a **"View audit history"** action that opens the Audit Log page pre-filtered to `CorrelationId = TrackedOperationId`, showing every operational audit event recorded for that cached call. - Data is served from the central Site Call Audit component's `SiteCalls` table. The page is **read-mostly** — an eventually-consistent mirror of site state; the site remains the source of truth. +- **Site scope is applied in the query (code review 2026-12-02 UI-7):** a site-scoped user's permitted site identifiers ride `SiteCallQueryRequest.SourceSitesFilter`, so keyset paging runs over in-scope rows and Next is gated on the server page size. Before, the query was unscoped and the client dropped other sites' rows after paging, so any page with an out-of-scope row was "short" and disabled Next. ### Health Monitoring Dashboard (All Roles) - Overview of all sites with online/offline status. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationKpis.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationKpis.razor index fce17006..475c4fbc 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationKpis.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationKpis.razor @@ -11,6 +11,7 @@ @inject ISiteRepository SiteRepository @inject IKpiHistoryQueryService KpiHistory @inject ILogger Logger +@inject AuthenticationStateProvider AuthStateProvider
@@ -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? _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 diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationReport.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationReport.razor index 74966258..81032992 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationReport.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationReport.razor @@ -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 SourceSiteId (stale row from a deleted site) is kept — /// there is no Site.Id to gate it on. /// + private IReadOnlyList? 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> FilterPermittedAsync( IEnumerable notifications) { diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor index dc40eed0..f33b4a88 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor @@ -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(); diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/SiteCalls/SiteCallsReport.razor.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/SiteCalls/SiteCallsReport.razor.cs index e49323a9..6f463427 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/SiteCalls/SiteCallsReport.razor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/SiteCalls/SiteCallsReport.razor.cs @@ -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 _allSites (not _sites) so a row whose Site was /// filtered OUT of the dropdown is correctly classified as out-of-scope. /// + /// + /// The caller's permitted source sites for the server query: null 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). + /// + private IReadOnlyList? ScopedSourceSites() => + _siteScopeSystemWide ? null : _sites.Select(s => s.SiteIdentifier).ToList(); + private Task> FilterPermittedAsync( IEnumerable calls) { diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/ISecuredWriteService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/ISecuredWriteService.cs index 4aa87f6f..ff69a48d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/ISecuredWriteService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/ISecuredWriteService.cs @@ -101,9 +101,12 @@ public interface ISecuredWriteService /// Site id filter; null matches every site. /// Rows to skip (offset paging); clamped to >= 0 server-side. /// Maximum rows to return; clamped to 1..500 server-side. + /// When non-null, only these statuses match — applied server-side + /// before paging and counting (code review 2026-12-02 UI-9). /// Cancellation token. /// A task resolving to the matching page + total match count, newest submission first. Task ListAsync( string? status, string? siteId, int skip = 0, int take = 200, + IReadOnlyList? statuses = null, CancellationToken cancellationToken = default); } diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/SecuredWriteService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/SecuredWriteService.cs index e7d8004b..311cd0c4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/SecuredWriteService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/SecuredWriteService.cs @@ -82,10 +82,11 @@ public sealed class SecuredWriteService : ISecuredWriteService /// public async Task ListAsync( string? status, string? siteId, int skip = 0, int take = 200, + IReadOnlyList? 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( diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ISecuredWriteRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ISecuredWriteRepository.cs index 7d611ad1..6a0b98b9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ISecuredWriteRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ISecuredWriteRepository.cs @@ -51,6 +51,10 @@ public interface ISecuredWriteRepository /// to . 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. + /// When non-null, only rows whose Status 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 + /// ; an empty set matches nothing. /// Cancellation token. /// A task that resolves to a page of matching rows, newest submission first. Task> QueryAsync( @@ -59,6 +63,7 @@ public interface ISecuredWriteRepository int skip, int take, IReadOnlyCollection? permittedSiteIds = null, + IReadOnlyCollection? statuses = null, CancellationToken ct = default); /// @@ -146,12 +151,17 @@ public interface ISecuredWriteRepository /// to . 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. + /// When non-null, only rows whose Status 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 + /// ; an empty set matches nothing. /// Cancellation token. /// A task that resolves to the count of matching rows. Task CountAsync( string? status, string? siteId, IReadOnlyCollection? permittedSiteIds = null, + IReadOnlyCollection? statuses = null, CancellationToken ct = default); /// diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Audit/SiteCallQueries.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Audit/SiteCallQueries.cs index e424c60e..884a94f6 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Audit/SiteCallQueries.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Audit/SiteCallQueries.cs @@ -27,6 +27,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Audit; /// Flow Debugger / Audit Log); null = no filter. Additive, trailing /// optional so existing positional callers are unaffected. /// +/// +/// 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). null = no constraint; an EMPTY list matches nothing +/// (fail closed). Composes (AND) with . Additive. +/// 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? SourceSitesFilter = null); /// /// A single SiteCalls row summarised for the Site Calls UI grid. Carries diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SecuredWriteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SecuredWriteCommands.cs index 721ea231..e87bbcbf 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SecuredWriteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SecuredWriteCommands.cs @@ -60,7 +60,14 @@ public record RejectSecuredWriteCommand(long Id, string? Comment); /// Site id filter; null matches every site. /// Number of rows to skip (offset paging); clamped to >= 0 server-side. /// Maximum rows to return; clamped to 1..500 server-side. Default 200. -public record ListSecuredWritesCommand(string? Status, string? SiteId, int Skip = 0, int Take = 200); +/// +/// 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 . null = no constraint. +/// +public record ListSecuredWritesCommand(string? Status, string? SiteId, int Skip = 0, int Take = 200, + IReadOnlyList? Statuses = null); /// /// Result projection of a single pending secured write row, mirroring the diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Notification/NotificationOutboxQueries.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Notification/NotificationOutboxQueries.cs index 7c25b2f0..f0b4ff18 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Notification/NotificationOutboxQueries.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Notification/NotificationOutboxQueries.cs @@ -11,6 +11,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Notification; /// Flow Debugger / Audit Log. Additive; null means "no filter" (legacy senders /// compile unchanged). /// +/// +/// 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). null = no constraint; an EMPTY list matches nothing. +/// Composes (AND) with . Additive. +/// 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? SourceSitesFilter = null); /// /// A single notification row summarised for outbox UI display. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/SiteCallQueryFilter.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/SiteCallQueryFilter.cs index 3258b929..93e8fc9f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/SiteCallQueryFilter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/SiteCallQueryFilter.cs @@ -37,6 +37,10 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; /// null means "do not constrain". AND-combined with every other field, /// so a mismatching (etc.) still yields no rows. /// +/// +/// Restrict to rows from ANY of these source sites (the site-scoped caller's permitted set, +/// code review 2026-12-02 UI-7). null = no constraint; an EMPTY list matches nothing. +/// 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? SourceSites = null); diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Notifications/NotificationOutboxFilter.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Notifications/NotificationOutboxFilter.cs index 307bd732..bc50696d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Notifications/NotificationOutboxFilter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Notifications/NotificationOutboxFilter.cs @@ -27,6 +27,10 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Notifications; /// Exact match on a single NotificationId — the ?correlationId= deep link /// from the Flow Debugger / Audit Log. null means "do not constrain". /// +/// +/// Restrict to notifications from ANY of these sites (the site-scoped caller's permitted set, +/// code review 2026-12-02 UI-7). null = no constraint; an EMPTY list matches nothing. +/// 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? SourceSiteIds = null); diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationOutboxRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationOutboxRepository.cs index 5e921617..0feee788 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationOutboxRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationOutboxRepository.cs @@ -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)) diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SecuredWriteRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SecuredWriteRepository.cs index d258745c..555425c2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SecuredWriteRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SecuredWriteRepository.cs @@ -58,6 +58,7 @@ public class SecuredWriteRepository : ISecuredWriteRepository int skip, int take, IReadOnlyCollection? permittedSiteIds = null, + IReadOnlyCollection? statuses = null, CancellationToken ct = default) { IQueryable query = _context.Set() @@ -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? permittedSiteIds = null, + IReadOnlyCollection? statuses = null, CancellationToken ct = default) { IQueryable query = _context.Set() @@ -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); } diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs index 4e829286..d4065b3b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/SiteCallAuditRepository.cs @@ -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), diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index c3f31632..00fabf04 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -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 diff --git a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs index 5d37cdcc..e41a3a60 100644 --- a/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs @@ -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(); diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs index 47786f52..dcb130ec 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs @@ -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( diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Components/SecuredWritesTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Components/SecuredWritesTests.cs index a960fe7b..6d25dd8f 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Components/SecuredWritesTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Components/SecuredWritesTests.cs @@ -57,14 +57,14 @@ public class SecuredWritesTests : BunitContext // Empty list by default; individual tests seed the queue/history. _service.ListAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any()) .Returns(Task.FromResult(new SecuredWriteListResult(Array.Empty(), 0))); } /// Stubs ListAsync (any filter/paging args) to return . private void SeedList(IReadOnlyList rows, int? totalCount = null) => _service.ListAsync( - Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any?>(), Arg.Any()) .Returns(Task.FromResult(new SecuredWriteListResult(rows, totalCount ?? rows.Count))); /// @@ -295,7 +295,25 @@ public class SecuredWritesTests : BunitContext // The history second-page fetch offsets by one page (skip: 50). _service.Received().ListAsync( - Arg.Any(), Arg.Any(), 50, Arg.Any(), Arg.Any()); + Arg.Any(), Arg.Any(), 50, Arg.Any(), Arg.Any?>(), Arg.Any()); + } + + /// + /// Code review 2026-12-02 UI-9: the history list asks the server for the terminal + /// statuses (filter + count in SQL) instead of paging over every status and dropping + /// Pending rows client-side. + /// + [Fact] + public void History_RequestsTerminalStatuses_ServerSide() + { + AddAuth("op", "Operator"); + var cut = RenderPage(); + + cut.WaitForAssertion(() => _service.Received().ListAsync( + Arg.Is(x => x == null), Arg.Is(x => x == null), Arg.Is(0), Arg.Any(), + Arg.Is?>(s => s != null + && s.OrderBy(x => x).SequenceEqual(new[] { "Executed", "Expired", "Failed", "Rejected" })), + Arg.Any())); } // ── (e) Approve dialog surfaces submission age (stale-setpoint scenario) ── diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationKpisPageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationKpisPageTests.cs index b7be9539..b498a3e7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationKpisPageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationKpisPageTests.cs @@ -168,6 +168,44 @@ public class NotificationKpisPageTests : BunitContext }); } + /// + /// Code review 2026-12-02 UI-10: a Deployer scoped to Plant A sees only Plant A's per-site + /// row, not every site's names, queue depths and parked/stuck counts. A system-wide user + /// still sees both. + /// + /// Whether the caller carries a SiteId claim for Plant A. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void PerSiteRows_AreNarrowedToTheCallersSites(bool scoped) + { + _perSiteReply = new PerSiteNotificationKpiResponse("p", true, null, new List + { + new("plant-a", QueueDepth: 4, StuckCount: 1, ParkedCount: 0, + DeliveredLastInterval: 9, OldestPendingAge: TimeSpan.FromMinutes(7)), + new("plant-b", QueueDepth: 13, StuckCount: 0, ParkedCount: 3, + DeliveredLastInterval: 2, OldestPendingAge: TimeSpan.FromMinutes(1)), + }); + if (scoped) + { + var scopedUser = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtTokenService.UsernameClaimType, "scoped"), + new Claim(JwtTokenService.RoleClaimType, "Deployer"), + new Claim(JwtTokenService.SiteIdClaimType, "1"), // Plant A only + }, "TestAuth")); + Services.AddSingleton(new TestAuthStateProvider(scopedUser)); + } + + var cut = Render(); + + cut.WaitForAssertion(() => Assert.Contains("Plant A", cut.Markup)); + if (scoped) + Assert.DoesNotContain("Plant B", cut.Markup); + else + Assert.Contains("Plant B", cut.Markup); + } + /// Verifies that the page shows the per-site empty state when there are no sites. /// The result. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationReportPageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationReportPageTests.cs index c7f5ca0e..1f48da6e 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationReportPageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationReportPageTests.cs @@ -338,6 +338,38 @@ public class NotificationReportPageTests : BunitContext }); } + /// + /// Code review 2026-12-02 UI-7: a scoped user's permitted sites ride the query itself + /// (SourceSitesFilter), so the page and the total count cover only in-scope rows; + /// a system-wide user sends no such constraint. + /// + [Fact] + public void SiteScoping_ScopedUser_PushesPermittedSitesIntoTheQuery() + { + var scopedUser = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtTokenService.UsernameClaimType, "scoped"), + new Claim(JwtTokenService.RoleClaimType, "Deployer"), + new Claim(JwtTokenService.SiteIdClaimType, "1"), // Plant A only + }, "TestAuth")); + Services.AddSingleton(new TestAuthStateProvider(scopedUser)); + + var cut = Render(); + + cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests)); + Assert.Equal(new[] { "plant-a" }, _queryRequests[0].SourceSitesFilter); + } + + /// A system-wide user's query carries no permitted-sites constraint. + [Fact] + public void SiteScoping_SystemWideUser_SendsNoSitesConstraint() + { + var cut = Render(); + + cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests)); + Assert.Null(_queryRequests[0].SourceSitesFilter); + } + /// Verifies that clearing the notification filter pill drops the filter and re-queries. [Fact] public void NotificationFilterPill_Clear_DropsTheFilterAndRequeries() diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SiteCallsReportPageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SiteCallsReportPageTests.cs index f90b1266..e9c973dc 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SiteCallsReportPageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SiteCallsReportPageTests.cs @@ -663,6 +663,38 @@ public class SiteCallsReportPageTests : BunitContext Assert.DoesNotContain(FailedId.ToString("N")[..12], cut.Markup); } + /// + /// Code review 2026-12-02 UI-7: a scoped user's permitted sites ride the query itself + /// (SourceSitesFilter), so keyset paging runs over in-scope rows; a system-wide + /// user sends no such constraint. + /// + [Fact] + public void SiteScoping_ScopedUser_PushesPermittedSitesIntoTheQuery() + { + var scopedUser = new ClaimsPrincipal(new ClaimsIdentity(new[] + { + new Claim(JwtTokenService.UsernameClaimType, "scoped"), + new Claim(JwtTokenService.RoleClaimType, "Deployer"), + new Claim(JwtTokenService.SiteIdClaimType, "1"), // Plant A only + }, "TestAuth")); + Services.AddSingleton(new TestAuthStateProvider(scopedUser)); + + var cut = Render(); + + cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests)); + Assert.Equal(new[] { "plant-a" }, _queryRequests[0].SourceSitesFilter); + } + + /// A system-wide user's query carries no permitted-sites constraint. + [Fact] + public void SiteScoping_SystemWideUser_SendsNoSitesConstraint() + { + var cut = Render(); + + cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests)); + Assert.Null(_queryRequests[0].SourceSitesFilter); + } + // ───────────────────────────────────────────────────────────────────────── // Trends (K14) — a collapsible section with one KpiTrendChart per metric // (buffered / parked / failedLastInterval) for SiteCallAudit / Global. The diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/NotificationOutboxRepositoryIntegrationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/NotificationOutboxRepositoryIntegrationTests.cs index 4acba710..7b518dda 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/NotificationOutboxRepositoryIntegrationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/NotificationOutboxRepositoryIntegrationTests.cs @@ -139,6 +139,47 @@ public class NotificationOutboxRepositoryIntegrationTests : IClassFixture + /// Code review 2026-12-02 UI-7: the permitted-sites filter is applied in the query, so the + /// page AND the total count cover only rows the scoped caller may see (pre-fix the count + /// included every site and pages came back partly or wholly empty after client filtering). + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task QueryAsync_SourceSiteIdsFilter_PagesAndCountsInScopeRowsOnly() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var mine = "site-ui7-" + Guid.NewGuid().ToString("N")[..8]; + var other = "site-ui7-" + Guid.NewGuid().ToString("N")[..8]; + await using (var context = CreateContext()) + { + var repo = new NotificationOutboxRepository(context); + for (var i = 0; i < 3; i++) + await repo.InsertIfNotExistsAsync(MakeNotification(Guid.NewGuid().ToString(), sourceSiteId: mine, minutes: i)); + for (var i = 0; i < 7; i++) + await repo.InsertIfNotExistsAsync(MakeNotification(Guid.NewGuid().ToString(), sourceSiteId: other, minutes: 10 + i)); + } + + await using var queryContext = CreateContext(); + var queryRepo = new NotificationOutboxRepository(queryContext); + var (rows, totalCount) = await queryRepo.QueryAsync( + new NotificationOutboxFilter(SourceSiteIds: new[] { mine }), pageNumber: 1, pageSize: 2); + + Assert.Equal(3, totalCount); + Assert.Equal(2, rows.Count); + Assert.All(rows, r => Assert.Equal(mine, r.SourceSiteId)); + + var (page2, _) = await queryRepo.QueryAsync( + new NotificationOutboxFilter(SourceSiteIds: new[] { mine }), pageNumber: 2, pageSize: 2); + Assert.Equal(mine, Assert.Single(page2).SourceSiteId); + + var (none, noneCount) = await queryRepo.QueryAsync( + new NotificationOutboxFilter(SourceSiteIds: Array.Empty()), pageNumber: 1, pageSize: 50); + Assert.Empty(none); + Assert.Equal(0, noneCount); + } + // --- helpers ------------------------------------------------------------ private ScadaBridgeDbContext CreateContext() @@ -152,7 +193,9 @@ public class NotificationOutboxRepositoryIntegrationTests : IClassFixture Assert.All(rows, r => Assert.Equal(siteA, r.SourceSite)); } + /// + /// Code review 2026-12-02 UI-7: a site-scoped caller's permitted set is applied in the + /// query, so keyset paging runs over in-scope rows only. Mixed data where the OTHER site + /// produces most of the traffic must still yield full in-scope pages and a cursor that + /// reaches every in-scope row. + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task QueryAsync_SourceSitesFilter_PagesOverInScopeRowsOnly() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var mine = NewSiteId(); + var other = NewSiteId(); + await using var context = CreateContext(); + var repo = new SiteCallAuditRepository(context); + + // Newest-first order: 6 rows of the other site sit ON TOP of 5 of mine, interleaved. + var t0 = new DateTime(2026, 6, 1, 10, 0, 0, DateTimeKind.Utc); + for (var i = 0; i < 5; i++) + await repo.UpsertAsync(NewRow(TrackedOperationId.New(), sourceSite: mine, createdAtUtc: t0.AddMinutes(i))); + for (var i = 0; i < 6; i++) + await repo.UpsertAsync(NewRow(TrackedOperationId.New(), sourceSite: other, createdAtUtc: t0.AddMinutes(10 + i))); + + var scope = new SiteCallQueryFilter(SourceSites: new[] { mine }); + var page1 = await repo.QueryAsync(scope, new SiteCallPaging(PageSize: 3)); + Assert.Equal(3, page1.Count); // full page, not 0 (pre-fix: other site's rows) + Assert.All(page1, r => Assert.Equal(mine, r.SourceSite)); + + var last = page1[^1]; + var page2 = await repo.QueryAsync(scope, new SiteCallPaging( + PageSize: 3, AfterCreatedAtUtc: last.CreatedAtUtc, AfterId: last.TrackedOperationId)); + Assert.Equal(2, page2.Count); + Assert.All(page2, r => Assert.Equal(mine, r.SourceSite)); + + // Empty permitted set matches nothing (fail closed), and composes with SourceSite. + Assert.Empty(await repo.QueryAsync(new SiteCallQueryFilter(SourceSites: Array.Empty()), new SiteCallPaging(PageSize: 50))); + Assert.Empty(await repo.QueryAsync(new SiteCallQueryFilter(SourceSite: other, SourceSites: new[] { mine }), new SiteCallPaging(PageSize: 50))); + } + /// Verifies that filtering by tracked operation id returns exactly that row. /// A task that represents the asynchronous operation. [SkippableFact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/SecuredWriteRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/SecuredWriteRepositoryTests.cs index 9c504eac..68b2a3d7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/SecuredWriteRepositoryTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/SecuredWriteRepositoryTests.cs @@ -286,6 +286,33 @@ public class SecuredWriteRepositoryTests : IClassFixture Assert.Equal(0, await repo.CountAsync(status: "Executed", siteId: siteId)); } + /// + /// Code review 2026-12-02 UI-9: the history asks for the terminal statuses, applied in SQL + /// before paging and counting, so Pending rows neither take page slots nor inflate the + /// total that drives the pager. + /// + /// A task that represents the asynchronous operation. + [SkippableFact] + public async Task QueryAndCount_StatusesFilter_PageAndCountOnlyThoseStatuses() + { + Skip.IfNot(_fixture.Available, _fixture.SkipReason); + + var siteId = NewSiteId(); + await using var context = CreateContext(); + var repo = new SecuredWriteRepository(context); + for (var i = 0; i < 4; i++) await repo.AddAsync(NewRow(siteId, status: "Pending")); + await repo.AddAsync(NewRow(siteId, status: "Executed")); + await repo.AddAsync(NewRow(siteId, status: "Rejected")); + await repo.AddAsync(NewRow(siteId, status: "Expired")); + + string[] terminal = ["Executed", "Failed", "Rejected", "Expired"]; + var page = await repo.QueryAsync(null, siteId, skip: 0, take: 2, statuses: terminal); + Assert.Equal(2, page.Count); + Assert.All(page, r => Assert.Contains(r.Status, terminal)); + Assert.Equal(3, await repo.CountAsync(null, siteId, statuses: terminal)); + Assert.Equal(7, await repo.CountAsync(null, siteId)); + } + /// Verifies that a query with permitted site ids returns only rows for those sites. /// A task that represents the asynchronous operation. [SkippableFact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs index 1df96e95..62ef9bcf 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs @@ -185,7 +185,7 @@ public class ManagementActorTests : TestKit, IDisposable var securedWriteRepo = Substitute.For(); securedWriteRepo.QueryAsync( Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any?>(), Arg.Any()) + Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(Task.FromResult>( Array.Empty())); _services.AddScoped(_ => securedWriteRepo); diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteHandlerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteHandlerTests.cs index e08484e2..99e3272a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteHandlerTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteHandlerTests.cs @@ -469,7 +469,7 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable [Fact] public void List_FiltersByStatusAndSite() { - _securedWriteRepo.QueryAsync("Pending", "SITE1", 0, 200, Arg.Any?>(), Arg.Any()) + _securedWriteRepo.QueryAsync("Pending", "SITE1", 0, 200, Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(new List { new() @@ -492,14 +492,14 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable Assert.Equal(envelope.CorrelationId, response.CorrelationId); Assert.Contains("\"id\":3", response.JsonData); Assert.Contains("alice", response.JsonData); - _securedWriteRepo.Received(1).QueryAsync("Pending", "SITE1", 0, 200, Arg.Any?>(), Arg.Any()); + _securedWriteRepo.Received(1).QueryAsync("Pending", "SITE1", 0, 200, Arg.Any?>(), Arg.Any?>(), Arg.Any()); } /// Verifies that listing with no filters passes nulls to the repository. [Fact] public void List_NoFilters_PassesNullsToRepository() { - _securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any?>(), Arg.Any()) + _securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(new List()); var actor = CreateActor(); @@ -509,7 +509,7 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable actor.Tell(envelope); ExpectMsg(TimeSpan.FromSeconds(5)); - _securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200, Arg.Any?>(), Arg.Any()); + _securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200, Arg.Any?>(), Arg.Any?>(), Arg.Any()); } /// Verifies that a site-scoped reader requesting an out-of-scope site is unauthorized. @@ -532,14 +532,14 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable new("Site3", "SITE3") { Id = 3 }, }); _securedWriteRepo.QueryAsync(null, null, 0, 200, - Arg.Any?>(), Arg.Any()) + Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(new List()); var actor = CreateActor(); actor.Tell(ScopedEnvelope(new ListSecuredWritesCommand(null, null), "bob", ["3"], "Verifier")); ExpectMsg(TimeSpan.FromSeconds(5)); _securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200, Arg.Is?>(s => s != null && s.Single() == "SITE3"), - Arg.Any()); + Arg.Any?>(), Arg.Any()); } /// Verifies that a system-wide reader passes a null permitted-sites filter. @@ -547,14 +547,14 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable public void List_SystemWideReader_PassesNullPermittedFilter() { _securedWriteRepo.QueryAsync(null, null, 0, 200, - Arg.Any?>(), Arg.Any()) + Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(new List()); var actor = CreateActor(); actor.Tell(Envelope(new ListSecuredWritesCommand(null, null), "carol", "Operator")); ExpectMsg(TimeSpan.FromSeconds(5)); _securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200, Arg.Is?>(s => s == null), - Arg.Any()); + Arg.Any?>(), Arg.Any()); } // ------------------------------------------------------------------------ @@ -802,19 +802,41 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable [Fact] public void List_WithSkipTake_ForwardsPagingAndReturnsTotalCount() { - _securedWriteRepo.QueryAsync(null, null, 10, 25, Arg.Any?>(), Arg.Any()) + _securedWriteRepo.QueryAsync(null, null, 10, 25, Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(new List()); - _securedWriteRepo.CountAsync(null, null, Arg.Any?>(), Arg.Any()).Returns(87); + _securedWriteRepo.CountAsync(null, null, Arg.Any?>(), Arg.Any?>(), Arg.Any()).Returns(87); var actor = CreateActor(); actor.Tell(Envelope(new ListSecuredWritesCommand(null, null, Skip: 10, Take: 25), "carol", "Operator")); var resp = ExpectMsg(TimeSpan.FromSeconds(5)); - _securedWriteRepo.Received(1).QueryAsync(null, null, 10, 25, Arg.Any?>(), Arg.Any()); - _securedWriteRepo.Received(1).CountAsync(null, null, Arg.Any?>(), Arg.Any()); + _securedWriteRepo.Received(1).QueryAsync(null, null, 10, 25, Arg.Any?>(), Arg.Any?>(), Arg.Any()); + _securedWriteRepo.Received(1).CountAsync(null, null, Arg.Any?>(), Arg.Any?>(), Arg.Any()); Assert.Contains("\"totalCount\":87", resp.JsonData); } + /// + /// Code review 2026-12-02 UI-9: a Statuses set on the command reaches both the + /// page query and the count, so the history's terminal filter runs in SQL. + /// + [Fact] + public void List_WithStatuses_ForwardsTheSetToQueryAndCount() + { + string[] terminal = ["Executed", "Failed", "Rejected", "Expired"]; + _securedWriteRepo.QueryAsync(null, null, 0, 50, Arg.Any?>(), Arg.Any?>(), Arg.Any()) + .Returns(new List()); + _securedWriteRepo.CountAsync(null, null, Arg.Any?>(), Arg.Any?>(), Arg.Any()).Returns(3); + + var actor = CreateActor(); + actor.Tell(Envelope(new ListSecuredWritesCommand(null, null, Skip: 0, Take: 50, Statuses: terminal), "carol", "Operator")); + + ExpectMsg(TimeSpan.FromSeconds(5)); + _securedWriteRepo.Received(1).QueryAsync(null, null, 0, 50, Arg.Any?>(), + Arg.Is?>(s => s != null && s.SequenceEqual(terminal)), Arg.Any()); + _securedWriteRepo.Received(1).CountAsync(null, null, Arg.Any?>(), + Arg.Is?>(s => s != null && s.SequenceEqual(terminal)), Arg.Any()); + } + // ------------------------------------------------------------------------ // Opportunistic expiry sweep on list // ------------------------------------------------------------------------ @@ -835,7 +857,7 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable ValueJson = "false", ValueType = "Boolean", Status = "Pending", OperatorUser = "alice", SubmittedAtUtc = DateTime.UtcNow.AddHours(-25) // TTL default 24h }; - _securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any?>(), Arg.Any()) + _securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(new List { fresh, stale }); _securedWriteRepo.TryMarkExpiredAsync(2, Arg.Any(), Arg.Any()) .Returns(true); diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteTerminalPurgeTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteTerminalPurgeTests.cs index 93c82038..8fd43862 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteTerminalPurgeTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/SecuredWriteTerminalPurgeTests.cs @@ -26,7 +26,7 @@ public class SecuredWriteTerminalPurgeTests : TestKit { _services.AddScoped(_ => _repo); _repo.QueryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), - Arg.Any?>(), Arg.Any()) + Arg.Any?>(), Arg.Any?>(), Arg.Any()) .Returns(Array.Empty()); }