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:
@@ -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 <age> ago (<UTC timestamp>)`) 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.
|
||||
|
||||
+21
-1
@@ -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
|
||||
|
||||
+12
-6
@@ -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();
|
||||
|
||||
+17
-3
@@ -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 >= 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 >= 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
|
||||
|
||||
+8
-1
@@ -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);
|
||||
|
||||
+9
@@ -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))
|
||||
|
||||
+12
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -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(
|
||||
|
||||
@@ -57,14 +57,14 @@ public class SecuredWritesTests : BunitContext
|
||||
|
||||
// Empty list by default; individual tests seed the queue/history.
|
||||
_service.ListAsync(
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<IReadOnlyList<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult(new SecuredWriteListResult(Array.Empty<SecuredWriteDto>(), 0)));
|
||||
}
|
||||
|
||||
/// <summary>Stubs <c>ListAsync</c> (any filter/paging args) to return <paramref name="rows"/>.</summary>
|
||||
private void SeedList(IReadOnlyList<SecuredWriteDto> rows, int? totalCount = null)
|
||||
=> _service.ListAsync(
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<IReadOnlyList<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult(new SecuredWriteListResult(rows, totalCount ?? rows.Count)));
|
||||
|
||||
/// <summary>
|
||||
@@ -295,7 +295,25 @@ public class SecuredWritesTests : BunitContext
|
||||
|
||||
// The history second-page fetch offsets by one page (skip: 50).
|
||||
_service.Received().ListAsync(
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), 50, Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), 50, Arg.Any<int>(), Arg.Any<IReadOnlyList<string>?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void History_RequestsTerminalStatuses_ServerSide()
|
||||
{
|
||||
AddAuth("op", "Operator");
|
||||
var cut = RenderPage();
|
||||
|
||||
cut.WaitForAssertion(() => _service.Received().ListAsync(
|
||||
Arg.Is<string?>(x => x == null), Arg.Is<string?>(x => x == null), Arg.Is(0), Arg.Any<int>(),
|
||||
Arg.Is<IReadOnlyList<string>?>(s => s != null
|
||||
&& s.OrderBy(x => x).SequenceEqual(new[] { "Executed", "Expired", "Failed", "Rejected" })),
|
||||
Arg.Any<CancellationToken>()));
|
||||
}
|
||||
|
||||
// ── (e) Approve dialog surfaces submission age (stale-setpoint scenario) ──
|
||||
|
||||
@@ -168,6 +168,44 @@ public class NotificationKpisPageTests : BunitContext
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="scoped">Whether the caller carries a SiteId claim for Plant A.</param>
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void PerSiteRows_AreNarrowedToTheCallersSites(bool scoped)
|
||||
{
|
||||
_perSiteReply = new PerSiteNotificationKpiResponse("p", true, null, new List<SiteNotificationKpiSnapshot>
|
||||
{
|
||||
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<AuthenticationStateProvider>(new TestAuthStateProvider(scopedUser));
|
||||
}
|
||||
|
||||
var cut = Render<NotificationKpisPage>();
|
||||
|
||||
cut.WaitForAssertion(() => Assert.Contains("Plant A", cut.Markup));
|
||||
if (scoped)
|
||||
Assert.DoesNotContain("Plant B", cut.Markup);
|
||||
else
|
||||
Assert.Contains("Plant B", cut.Markup);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the page shows the per-site empty state when there are no sites.</summary>
|
||||
/// <returns>The result.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -338,6 +338,38 @@ public class NotificationReportPageTests : BunitContext
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-7: a scoped user's permitted sites ride the query itself
|
||||
/// (<c>SourceSitesFilter</c>), so the page and the total count cover only in-scope rows;
|
||||
/// a system-wide user sends no such constraint.
|
||||
/// </summary>
|
||||
[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<AuthenticationStateProvider>(new TestAuthStateProvider(scopedUser));
|
||||
|
||||
var cut = Render<NotificationReportPage>();
|
||||
|
||||
cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests));
|
||||
Assert.Equal(new[] { "plant-a" }, _queryRequests[0].SourceSitesFilter);
|
||||
}
|
||||
|
||||
/// <summary>A system-wide user's query carries no permitted-sites constraint.</summary>
|
||||
[Fact]
|
||||
public void SiteScoping_SystemWideUser_SendsNoSitesConstraint()
|
||||
{
|
||||
var cut = Render<NotificationReportPage>();
|
||||
|
||||
cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests));
|
||||
Assert.Null(_queryRequests[0].SourceSitesFilter);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that clearing the notification filter pill drops the filter and re-queries.</summary>
|
||||
[Fact]
|
||||
public void NotificationFilterPill_Clear_DropsTheFilterAndRequeries()
|
||||
|
||||
@@ -663,6 +663,38 @@ public class SiteCallsReportPageTests : BunitContext
|
||||
Assert.DoesNotContain(FailedId.ToString("N")[..12], cut.Markup);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-7: a scoped user's permitted sites ride the query itself
|
||||
/// (<c>SourceSitesFilter</c>), so keyset paging runs over in-scope rows; a system-wide
|
||||
/// user sends no such constraint.
|
||||
/// </summary>
|
||||
[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<AuthenticationStateProvider>(new TestAuthStateProvider(scopedUser));
|
||||
|
||||
var cut = Render<SiteCallsReportPage>();
|
||||
|
||||
cut.WaitForAssertion(() => Assert.NotEmpty(_queryRequests));
|
||||
Assert.Equal(new[] { "plant-a" }, _queryRequests[0].SourceSitesFilter);
|
||||
}
|
||||
|
||||
/// <summary>A system-wide user's query carries no permitted-sites constraint.</summary>
|
||||
[Fact]
|
||||
public void SiteScoping_SystemWideUser_SendsNoSitesConstraint()
|
||||
{
|
||||
var cut = Render<SiteCallsReportPage>();
|
||||
|
||||
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
|
||||
|
||||
+46
-3
@@ -139,6 +139,47 @@ public class NotificationOutboxRepositoryIntegrationTests : IClassFixture<MsSqlM
|
||||
Assert.Equal("Wanted", row.Subject);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<string>()), pageNumber: 1, pageSize: 50);
|
||||
Assert.Empty(none);
|
||||
Assert.Equal(0, noneCount);
|
||||
}
|
||||
|
||||
// --- helpers ------------------------------------------------------------
|
||||
|
||||
private ScadaBridgeDbContext CreateContext()
|
||||
@@ -152,7 +193,9 @@ public class NotificationOutboxRepositoryIntegrationTests : IClassFixture<MsSqlM
|
||||
private static Notification MakeNotification(
|
||||
string id,
|
||||
NotificationStatus status = NotificationStatus.Pending,
|
||||
string subject = "Subject")
|
||||
string subject = "Subject",
|
||||
string sourceSiteId = "site-cd015",
|
||||
int minutes = 0)
|
||||
{
|
||||
return new Notification(
|
||||
id,
|
||||
@@ -160,10 +203,10 @@ public class NotificationOutboxRepositoryIntegrationTests : IClassFixture<MsSqlM
|
||||
"Ops List",
|
||||
subject,
|
||||
"Body",
|
||||
"site-cd015")
|
||||
sourceSiteId)
|
||||
{
|
||||
Status = status,
|
||||
CreatedAt = new DateTimeOffset(2026, 5, 20, 10, 0, 0, TimeSpan.Zero),
|
||||
CreatedAt = new DateTimeOffset(2026, 5, 20, 10, 0, 0, TimeSpan.Zero).AddMinutes(minutes),
|
||||
SiteEnqueuedAt = new DateTimeOffset(2026, 5, 20, 9, 59, 0, TimeSpan.Zero),
|
||||
};
|
||||
}
|
||||
|
||||
+40
@@ -489,6 +489,46 @@ public class SiteCallAuditRepositoryTests : IClassFixture<MsSqlMigrationFixture>
|
||||
Assert.All(rows, r => Assert.Equal(siteA, r.SourceSite));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<string>()), new SiteCallPaging(PageSize: 50)));
|
||||
Assert.Empty(await repo.QueryAsync(new SiteCallQueryFilter(SourceSite: other, SourceSites: new[] { mine }), new SiteCallPaging(PageSize: 50)));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that filtering by tracked operation id returns exactly that row.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
|
||||
+27
@@ -286,6 +286,33 @@ public class SecuredWriteRepositoryTests : IClassFixture<MsSqlMigrationFixture>
|
||||
Assert.Equal(0, await repo.CountAsync(status: "Executed", siteId: siteId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a query with permitted site ids returns only rows for those sites.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[SkippableFact]
|
||||
|
||||
@@ -185,7 +185,7 @@ public class ManagementActorTests : TestKit, IDisposable
|
||||
var securedWriteRepo = Substitute.For<ISecuredWriteRepository>();
|
||||
securedWriteRepo.QueryAsync(
|
||||
Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(),
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<PendingSecuredWrite>>(
|
||||
Array.Empty<PendingSecuredWrite>()));
|
||||
_services.AddScoped(_ => securedWriteRepo);
|
||||
|
||||
@@ -469,7 +469,7 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable
|
||||
[Fact]
|
||||
public void List_FiltersByStatusAndSite()
|
||||
{
|
||||
_securedWriteRepo.QueryAsync("Pending", "SITE1", 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
_securedWriteRepo.QueryAsync("Pending", "SITE1", 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite>
|
||||
{
|
||||
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<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
_securedWriteRepo.Received(1).QueryAsync("Pending", "SITE1", 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that listing with no filters passes nulls to the repository.</summary>
|
||||
[Fact]
|
||||
public void List_NoFilters_PassesNullsToRepository()
|
||||
{
|
||||
_securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
_securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite>());
|
||||
|
||||
var actor = CreateActor();
|
||||
@@ -509,7 +509,7 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable
|
||||
actor.Tell(envelope);
|
||||
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a site-scoped reader requesting an out-of-scope site is unauthorized.</summary>
|
||||
@@ -532,14 +532,14 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable
|
||||
new("Site3", "SITE3") { Id = 3 },
|
||||
});
|
||||
_securedWriteRepo.QueryAsync(null, null, 0, 200,
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite>());
|
||||
var actor = CreateActor();
|
||||
actor.Tell(ScopedEnvelope(new ListSecuredWritesCommand(null, null), "bob", ["3"], "Verifier"));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200,
|
||||
Arg.Is<IReadOnlyCollection<string>?>(s => s != null && s.Single() == "SITE3"),
|
||||
Arg.Any<CancellationToken>());
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a system-wide reader passes a null permitted-sites filter.</summary>
|
||||
@@ -547,14 +547,14 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable
|
||||
public void List_SystemWideReader_PassesNullPermittedFilter()
|
||||
{
|
||||
_securedWriteRepo.QueryAsync(null, null, 0, 200,
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite>());
|
||||
var actor = CreateActor();
|
||||
actor.Tell(Envelope(new ListSecuredWritesCommand(null, null), "carol", "Operator"));
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 0, 200,
|
||||
Arg.Is<IReadOnlyCollection<string>?>(s => s == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
@@ -802,19 +802,41 @@ public class SecuredWriteHandlerTests : TestKit, IDisposable
|
||||
[Fact]
|
||||
public void List_WithSkipTake_ForwardsPagingAndReturnsTotalCount()
|
||||
{
|
||||
_securedWriteRepo.QueryAsync(null, null, 10, 25, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
_securedWriteRepo.QueryAsync(null, null, 10, 25, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite>());
|
||||
_securedWriteRepo.CountAsync(null, null, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>()).Returns(87);
|
||||
_securedWriteRepo.CountAsync(null, null, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>()).Returns(87);
|
||||
|
||||
var actor = CreateActor();
|
||||
actor.Tell(Envelope(new ListSecuredWritesCommand(null, null, Skip: 10, Take: 25), "carol", "Operator"));
|
||||
|
||||
var resp = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 10, 25, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
_securedWriteRepo.Received(1).CountAsync(null, null, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 10, 25, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
_securedWriteRepo.Received(1).CountAsync(null, null, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>());
|
||||
Assert.Contains("\"totalCount\":87", resp.JsonData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-9: a <c>Statuses</c> set on the command reaches both the
|
||||
/// page query and the count, so the history's terminal filter runs in SQL.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void List_WithStatuses_ForwardsTheSetToQueryAndCount()
|
||||
{
|
||||
string[] terminal = ["Executed", "Failed", "Rejected", "Expired"];
|
||||
_securedWriteRepo.QueryAsync(null, null, 0, 50, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite>());
|
||||
_securedWriteRepo.CountAsync(null, null, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>()).Returns(3);
|
||||
|
||||
var actor = CreateActor();
|
||||
actor.Tell(Envelope(new ListSecuredWritesCommand(null, null, Skip: 0, Take: 50, Statuses: terminal), "carol", "Operator"));
|
||||
|
||||
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||
_securedWriteRepo.Received(1).QueryAsync(null, null, 0, 50, Arg.Any<IReadOnlyCollection<string>?>(),
|
||||
Arg.Is<IReadOnlyCollection<string>?>(s => s != null && s.SequenceEqual(terminal)), Arg.Any<CancellationToken>());
|
||||
_securedWriteRepo.Received(1).CountAsync(null, null, Arg.Any<IReadOnlyCollection<string>?>(),
|
||||
Arg.Is<IReadOnlyCollection<string>?>(s => s != null && s.SequenceEqual(terminal)), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// 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<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
_securedWriteRepo.QueryAsync(null, null, 0, 200, Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new List<PendingSecuredWrite> { fresh, stale });
|
||||
_securedWriteRepo.TryMarkExpiredAsync(2, Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ public class SecuredWriteTerminalPurgeTests : TestKit
|
||||
{
|
||||
_services.AddScoped(_ => _repo);
|
||||
_repo.QueryAsync(Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<int>(), Arg.Any<int>(),
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<IReadOnlyCollection<string>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Array.Empty<PendingSecuredWrite>());
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user