Compare commits
92 Commits
ba335519f4
...
4307c38117
| Author | SHA1 | Date | |
|---|---|---|---|
| 4307c38117 | |||
| 33e1802e6d | |||
| a9393c8913 | |||
| cd8e4872f6 | |||
| d6ead8ae62 | |||
| f8e2d7a934 | |||
| c5c8511379 | |||
| 9558d98343 | |||
| c3501ecd72 | |||
| 78fadb82d2 | |||
| 4860aeff62 | |||
| 538117d114 | |||
| 58ac06a358 | |||
| 73df322a66 | |||
| cdfd0ffbd2 | |||
| f0c69aad83 | |||
| 4555a3f333 | |||
| a1d484a5ff | |||
| 609bdb37ef | |||
| bffbb0c2da | |||
| 3827b98484 | |||
| b46691747c | |||
| 095361b73f | |||
| c5378f8723 | |||
| 07dae35533 | |||
| 28cab6e881 | |||
| c72d7b7902 | |||
| 84cb8c2abb | |||
| ab40534986 | |||
| f08a4d609f | |||
| c68b9cccd2 | |||
| 529921f2de | |||
| 7bd081ba50 | |||
| 4b8986036e | |||
| e814bf5efb | |||
| 282bc8b53c | |||
| 8f85cce298 | |||
| e3b83f8561 | |||
| 597d664a53 | |||
| ae25b5a8d6 | |||
| 5185486a3c | |||
| 79fe098886 | |||
| 69e0d546b5 | |||
| fb18253f32 | |||
| 454e47ea38 | |||
| d844405cec | |||
| e51104af5f | |||
| 47f5ca687c | |||
| 2935c41bf7 | |||
| 2843781db4 | |||
| 3d4521f250 | |||
| f4e03ce8f7 | |||
| a1eed1c2ab | |||
| 5585d7ba51 | |||
| 7c1d61647e | |||
| b432c788c3 | |||
| 72e084f588 | |||
| 78360eb6a7 | |||
| 6a4c9a85b8 | |||
| 649e45b5c0 | |||
| 48dfb875bd | |||
| 2b2c1b264a | |||
| 7674b37a24 | |||
| ddafc5c811 | |||
| 7aeb7a43b0 | |||
| 4369da61c1 | |||
| 8270a603d3 | |||
| 023c4f7cde | |||
| 042776abb6 | |||
| 828acd3266 | |||
| fef4d4cf83 | |||
| 0449c473c1 | |||
| 4d3cef18cb | |||
| 07b651d933 | |||
| 1d82e6bc8c | |||
| a3ac77dd41 | |||
| e773915e26 | |||
| ef2791ffd8 | |||
| 64cc96253f | |||
| e0d085481f | |||
| c8915e8638 | |||
| 67ff494bf5 | |||
| acbb52b459 | |||
| 9ee21205d6 | |||
| 7b41c2c202 | |||
| b7f7fe935c | |||
| 2e4ca5a35f | |||
| 6a34ed9ed6 | |||
| 4755ceee81 | |||
| c0aaba17ea | |||
| d8ba99d19d | |||
| 1a23b902b2 |
@@ -124,8 +124,9 @@ Related repos cloned as sibling directories under `~/Desktop/` — referenced fo
|
||||
- Error classification: HTTP 5xx/408/429/connection errors = transient; other 4xx = permanent (returned to script).
|
||||
- Notification Service: SMTP with OAuth2 Client Credentials (Microsoft 365) or Basic Auth. BCC delivery, plain text.
|
||||
- Notification delivery is central-only: sites store-and-forward notifications to the central cluster (target = central, not SMTP); sites never talk to SMTP. Notification lists and SMTP config are no longer deployed to sites; recipient resolution happens at central, at delivery time.
|
||||
- Notification lists carry a `Type` discriminator (`Email` now; `Teams` and others later). `Notify.To("list")` is type-agnostic; delivery is via per-type `INotificationDeliveryAdapter` (success/transient/permanent classification, same pattern as External System Gateway).
|
||||
- Notification lists carry a `Type` discriminator (`Email` and `Sms`). `Notify.To("list")` is type-agnostic; delivery is via per-type `INotificationDeliveryAdapter` (Email via SMTP; Sms via Twilio REST — `SmsNotificationDeliveryAdapter`, no SDK, one POST per recipient, per-recipient rollup). List Type is fixed after creation.
|
||||
- `Notify.Send` is async — returns a `NotificationId` (GUID, idempotency key) status handle immediately. `Notify.Status(notificationId)` returns a status record (status, retry count, last error, key timestamps); answered site-locally as `Forwarding` while still in the site S&F buffer, otherwise round-trips to central.
|
||||
- SMS delivery adapter (T9/T10, 2026-06-19): `SmsNotificationDeliveryAdapter` — Twilio REST, no SDK, HTTP Basic auth (`AccountSid:AuthToken`), one `POST .../Messages.json` per recipient. `SmsConfiguration` entity (`AccountSid`, `AuthToken` encrypted via Data Protection, `FromNumber`/`MessagingServiceSid`, `ApiBaseUrl`, timeout/retry) stored centrally; managed Admin-only via CLI `notification sms list|update` + Central UI `/notifications/sms`. Central-only (never deployed to sites). Per-recipient rollup: all-accepted → Delivered; any-transient → retry/park; mix → delivered-to-good + note; all-permanent → Park. `SmsConfiguration` (Auth Token in SecretsBlock) travels in Transport bundles via `--sms-configs`.
|
||||
- Inbound API: `POST /api/{methodName}`, `X-API-Key` header, flat JSON, extended type system (Object, List).
|
||||
|
||||
### Templates & Deployment
|
||||
@@ -203,7 +204,7 @@ Related repos cloned as sibling directories under `~/Desktop/` — referenced fo
|
||||
- Stuck = `Pending`/`Retrying` older than a configurable age threshold (default 10 min) — display-only (KPI count + row badge), no escalation/alerting.
|
||||
- Headline KPI tiles surface on the Health dashboard; a new Central UI Notification Outbox page offers a queryable list with Retry/Discard actions on parked notifications.
|
||||
- Site Call Audit KPIs are central-computed point-in-time from the `SiteCalls` table (global + per-site), mirroring the Notification Outbox KPI shape; tiles surface on the Health dashboard alongside a queryable Central UI Site Calls page with Retry/Discard on parked rows.
|
||||
- KPI History & Trends (#26, M6): a reusable central KPI-history backbone — supersedes the prior "point-in-time only, no time-series store" stance — backed by a tall/EAV `KpiSample` table in central MS SQL (no new infra). A `KpiHistoryRecorderActor` cluster singleton (`kpi-history-recorder`, **not readiness-gated**, best-effort with per-source isolation) samples every minute by enumerating DI-registered `IKpiSampleSource`s (each lives with its owner, registered via `TryAddEnumerable`, reusing existing KPI/aggregator reads); daily purge after `RetentionDays` (default 90). Querying is `IKpiHistoryRepository.GetRawSeriesAsync` → `KpiSeriesBucketer` (last-value-per-bucket) → scoped dual-ctor `KpiHistoryQueryService` → a reusable **custom-SVG** `KpiTrendChart` (no third-party charting lib). Trends ship on four surfaces: Notification Outbox, Site Calls, Audit Log pages + a per-site Health-dashboard panel. `KpiHistoryOptions` (`ScadaBridge:KpiHistory`): SampleInterval 60s, RetentionDays 90, PurgeInterval 1d, DefaultMaxSeriesPoints 200; validated. M6's T9 (Teams + other non-Email delivery adapters) and T10 (`NotificationType` enum values + Central UI list "Type" selector) are deferred to the next major version.
|
||||
- KPI History & Trends (#26, M6): a reusable central KPI-history backbone — supersedes the prior "point-in-time only, no time-series store" stance — backed by a tall/EAV `KpiSample` table in central MS SQL (no new infra). A `KpiHistoryRecorderActor` cluster singleton (`kpi-history-recorder`, **not readiness-gated**, best-effort with per-source isolation) samples every minute by enumerating DI-registered `IKpiSampleSource`s (each lives with its owner, registered via `TryAddEnumerable`, reusing existing KPI/aggregator reads); daily purge after `RetentionDays` (default 90). Querying is `IKpiHistoryRepository.GetRawSeriesAsync` → `KpiSeriesBucketer` (last-value-per-bucket) → scoped dual-ctor `KpiHistoryQueryService` → a reusable **custom-SVG** `KpiTrendChart` (no third-party charting lib). Trends ship on four surfaces: Notification Outbox, Site Calls, Audit Log pages + a per-site Health-dashboard panel. `KpiHistoryOptions` (`ScadaBridge:KpiHistory`): SampleInterval 60s, RetentionDays 90, PurgeInterval 1d, DefaultMaxSeriesPoints 200; validated. M6's T9 and T10 were originally deferred. **T9/T10 delivered 2026-06-19** as an SMS (Twilio) adapter — Teams was evaluated and dropped (outbound-only backends cannot send 1:1 chat bodies via Graph without a Bot Framework inbound endpoint; SMS is inherently per-person and outbound-only). `NotificationType.Sms` added; `SmsNotificationDeliveryAdapter` (Twilio REST, no SDK) registered alongside Email; Central UI Type selector (adapter-gated) + SMS recipient input; CLI `--type sms --phones` on list create/update; `notification sms list|update` commands.
|
||||
|
||||
### Code Organization
|
||||
- Entity classes are persistence-ignorant POCOs in Commons; EF mappings in Configuration Database.
|
||||
|
||||
@@ -88,4 +88,27 @@
|
||||
<PackageVersion Include="ZB.MOM.WW.Theme" Version="0.3.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
Targeted NuGet audit suppression (NOT a blanket NuGetAudit=false).
|
||||
|
||||
GHSA-2m69-gcr7-jv3q (NU1903, high) is on the NATIVE library SQLitePCLRaw.lib.e_sqlite3
|
||||
2.1.11, pulled in TRANSITIVELY by Microsoft.Data.Sqlite / EntityFrameworkCore.Sqlite.
|
||||
The current MS-supported package line still references it: Microsoft.Data.Sqlite.Core
|
||||
10.0.9 (latest 10.0.x as of 2026-06) declares `SQLitePCLRaw.core 2.1.11`, so a version
|
||||
bump within the supported line does NOT clear it. The only patched native lib is the
|
||||
SQLitePCLRaw 3.x line — force-overriding the whole SQLitePCLRaw family to 3.x under a
|
||||
Microsoft.Data.Sqlite built and pinned for 2.1.x is unsupported and runtime-risky for the
|
||||
entire site-local SQLite layer (S&F buffer, operation tracking, native-alarm state).
|
||||
|
||||
Risk assessment: SQLite here is internal, local-only storage on site nodes (+ tests); it is
|
||||
not an externally-reachable SQL surface for untrusted input, so practical exposure is low.
|
||||
Suppressing ONLY this advisory (auditing stays ON for everything else) lets the full
|
||||
solution AND the docker in-container restore build cleanly without the blanket
|
||||
`/p:NuGetAudit=false` workaround. REVISIT and remove this suppression once Microsoft.Data.Sqlite
|
||||
ships a 10.0.x that references a patched (3.x) SQLitePCLRaw bundle.
|
||||
-->
|
||||
<ItemGroup>
|
||||
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-2m69-gcr7-jv3q" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -16,7 +16,7 @@ This repository is the full **implementation** project for ScadaBridge — the C
|
||||
| Central Database | MS SQL Server, Entity Framework Core |
|
||||
| Site Storage | SQLite (deployed configs, S&F buffer, event logs) |
|
||||
| Authentication | Direct LDAP/AD bind (LDAPS/StartTLS), JWT sessions |
|
||||
| Notifications | Delivered from the central cluster (SMTP, OAuth2/Microsoft 365); store-and-forwarded from sites |
|
||||
| Notifications | Delivered from the central cluster (Email via SMTP/OAuth2-M365; SMS via Twilio REST); store-and-forwarded from sites |
|
||||
| Hosting | Windows Server, Windows Service |
|
||||
| Cluster | Akka.NET Cluster (active/standby, keep-oldest SBR) |
|
||||
| Logging | Serilog (structured) |
|
||||
@@ -83,8 +83,8 @@ Both stacks share the infrastructure services in [`infra/`](infra/) (MS SQL, LDA
|
||||
| 5 | Central–Site Communication | [docs/requirements/Component-Communication.md](docs/requirements/Component-Communication.md) | Dual transport: Akka.NET ClusterClient (command/control) + gRPC server-streaming (real-time data). 9 message patterns with per-pattern timeouts, SiteStreamGrpcServer/Client, application-level correlation IDs, transport heartbeat config, gRPC keepalive, message ordering, connection failure behavior. The gRPC stream additively carries the read-only native alarm mirror (computed + native OPC UA / MxAccess) via the enriched `AlarmStateUpdate`. |
|
||||
| 6 | Store-and-Forward Engine | [docs/requirements/Component-StoreAndForward.md](docs/requirements/Component-StoreAndForward.md) | Buffering (transient failures only), fixed-interval retry, parking, async best-effort replication, SQLite persistence at sites. |
|
||||
| 7 | External System Gateway | [docs/requirements/Component-ExternalSystemGateway.md](docs/requirements/Component-ExternalSystemGateway.md) | HTTP/REST + JSON, API key/Basic Auth, per-system timeout, dual call modes (Call/CachedCall), transient/permanent error classification, dedicated blocking I/O dispatcher, ADO.NET connection pooling. |
|
||||
| 8 | Notification Service | [docs/requirements/Component-NotificationService.md](docs/requirements/Component-NotificationService.md) | Central-only — manages typed notification-list and SMTP definitions, supplies per-type delivery adapters (SMTP with OAuth2 (M365) or Basic Auth, BCC, plain text); delivery performed by the Notification Outbox. |
|
||||
| 9 | Central UI | [docs/requirements/Component-CentralUI.md](docs/requirements/Component-CentralUI.md) | Blazor Server with SignalR real-time push, load balancer failover with JWT, all management workflows. |
|
||||
| 8 | Notification Service | [docs/requirements/Component-NotificationService.md](docs/requirements/Component-NotificationService.md) | Central-only — manages typed notification-list, SMTP, and SMS definitions; supplies per-type delivery adapters (Email via SMTP with OAuth2 (M365) or Basic Auth, BCC, plain text; SMS via Twilio REST, per-recipient, outbound-only); delivery performed by the Notification Outbox. |
|
||||
| 9 | Central UI | [docs/requirements/Component-CentralUI.md](docs/requirements/Component-CentralUI.md) | Blazor Server with SignalR real-time push, load balancer failover with JWT, all management workflows. Custom-content modal host (`DialogService.ShowAsync<T>`) with focus-trap/restore; dark-mode CSS-variable token layer (`[data-bs-theme="dark"]` overriding `ZB.MOM.WW.Theme` tokens in `site.css`, `localStorage`-persisted, SSR no-flash); reusable presentational components `OffsetPager`, `KeysetPager`, and `DateTimeRangeFilter` adopted across report/audit pages. |
|
||||
| 10 | Security & Auth | [docs/requirements/Component-Security.md](docs/requirements/Component-Security.md) | Direct LDAP bind (LDAPS/StartTLS), JWT sessions (HMAC-SHA256, 15-min refresh, 30-min idle), role-based authorization (incl. the `Operator`/`Verifier` two-person secured-write roles + policies), site-scoped permissions. |
|
||||
| 11 | Health Monitoring | [docs/requirements/Component-HealthMonitoring.md](docs/requirements/Component-HealthMonitoring.md) | 30s report interval, 60s offline threshold, monotonic sequence numbers, raw error counts, tag resolution counts, dead letter monitoring. |
|
||||
| 12 | Site Event Logging | [docs/requirements/Component-SiteEventLogging.md](docs/requirements/Component-SiteEventLogging.md) | SQLite storage, 30-day retention + 1GB cap, daily purge, paginated remote queries with keyword search. |
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.CLI` |
|
||||
| Design doc | `docs/requirements/Component-CLI.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 1 |
|
||||
|
||||
## Summary
|
||||
@@ -1082,3 +1082,36 @@ authoritative source.
|
||||
**Resolution**
|
||||
|
||||
_Unresolved._
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the CLI SMS surface: `--type email|sms` / `--phones` on `notification list`,
|
||||
the `notification sms list|update` subcommands, and `bundle export --sms-configs`. Channel-aware
|
||||
validation and the AuthToken-never-printed projection are correct and tested. One Low test-coverage
|
||||
finding; Resolved.
|
||||
|
||||
### CLI-024 — No contract test pinning `notification sms update` required fields
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Status | Resolved |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs` |
|
||||
|
||||
**Description**
|
||||
|
||||
`UpdateCommandContractTests` pins the `Required`/optional contract for every other update command's
|
||||
core flags, but had no entry for `notification sms update` — a future regression making `--id` or
|
||||
`--account-sid` optional (silently sending null) would go uncaught.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add a contract test asserting the required/optional flags for `notification sms update`.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `a9393c89`): added `SmsUpdate_CoreFieldsRequired`. (Updated in commit
|
||||
`33e1802e` when `--from-number` became conditionally validated rather than `Required` — see
|
||||
CentralUI-035 — so the test now pins `--id`/`--account-sid` Required and `--from-number`/`--auth-token`
|
||||
optional, with the either-or validation covered in `NotificationSmsCommandTests`.)
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.CentralUI` |
|
||||
| Design doc | `docs/requirements/Component-CentralUI.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 0 |
|
||||
|
||||
## Summary
|
||||
@@ -1595,3 +1595,93 @@ advances to Step 2 without opening a session; a wrong passphrase increments the
|
||||
counter and writes the `BundleImportUnlockFailed` audit row; the lockout resets
|
||||
the wizard to Step 1 once `MaxUnlockAttemptsPerSession` is reached; a successful
|
||||
unlock resets the counter and advances to Step 3.
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the CentralUI SMS surface: the `/notifications/sms` Admin-only config page, the
|
||||
adapter-gated Type selector + per-type recipient input on the list form, the Type column, and the
|
||||
Transport-export SMS-config selection. Security is solid — the page is `RequireAdmin`, the AuthToken is
|
||||
never rendered (presence-only) and never pre-filled, preserve-if-blank is correct. Two Medium
|
||||
correctness findings and one Low test gap; all Resolved.
|
||||
|
||||
### CentralUI-034 — Notification Lists recipient badge renders "Name <>" for SMS recipients
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Medium |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationLists.razor:70` |
|
||||
|
||||
**Description**
|
||||
|
||||
The recipient badge rendered `@r.Name <@r.EmailAddress>` unconditionally. An SMS recipient carries a
|
||||
PhoneNumber and a null EmailAddress, so an SMS list rendered "Jane <>" — an empty contact field. The
|
||||
same commit added the Type column to this page but did not make the badge type-aware (the list form's
|
||||
recipients table WAS made type-aware; only this summary page was missed).
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Make the badge type-aware: show PhoneNumber for SMS lists, EmailAddress otherwise.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): the badge now selects the contact field by `list.Type` (phone
|
||||
for SMS, email otherwise). Locked by `SmsListRecipientBadge_ShowsPhoneNumber_NotEmptyAngleBrackets`
|
||||
(commit `a9393c89`).
|
||||
|
||||
### CentralUI-035 — SMS config Save hard-required a From Number, contradicting the either-or contract
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Medium |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/SmsConfiguration.razor:219` |
|
||||
|
||||
**Description**
|
||||
|
||||
`Save()` required a From Number unconditionally, but the design doc and the Twilio delivery adapter
|
||||
treat FromNumber and MessagingServiceSid as either-or (the adapter only errors when BOTH are blank, and
|
||||
uses the Messaging Service SID instead of From when set). An admin could not create a Twilio
|
||||
Messaging-Service-only configuration through the UI, despite the entity and adapter supporting it.
|
||||
Investigation found the drift ran deeper than the UI: the entity ctor and the EF `FromNumber` column
|
||||
were also non-null, so a pure UI fix was insufficient.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Reconcile the implementation with the spec — make FromNumber optional end-to-end (entity, schema, UI,
|
||||
CLI) so a Messaging-Service-only config is valid, with at-least-one-of (FromNumber, MessagingServiceSid)
|
||||
validated at the boundaries.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `33e1802e`): made FromNumber optional end-to-end — `SmsConfiguration.FromNumber`
|
||||
→ nullable (ctor param optional), EF `IsRequired(false)` + migration `SmsFromNumberOptional` (ALTER
|
||||
COLUMN nullable), `SmsConfigDto.FromNumber` → nullable, `UpdateSmsConfigCommand.FromNumber` → nullable,
|
||||
UI validation now requires AccountSid + at-least-one-of(FromNumber, MessagingServiceSid), and CLI
|
||||
`--from-number` is conditionally validated. Direction chosen by the design owner.
|
||||
|
||||
### CentralUI-036 — No test for the From-Number/Messaging-Service-SID either-or rule
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Status | Resolved |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SmsConfigurationPageTests.cs` |
|
||||
|
||||
**Description**
|
||||
|
||||
No test pinned the sender-identity validation, so the divergence in CentralUI-035 (UI stricter than the
|
||||
adapter contract) was not caught.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add a test that saving succeeds with a Messaging Service SID and no From Number.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `33e1802e`): added `SavingNewConfig_MessagingServiceSidOnly_NoFromNumber_Saves`,
|
||||
which asserts the config persists with a null FromNumber. Complemented by ManagementActor + CLI
|
||||
either-or tests in the same commit.
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.Commons` |
|
||||
| Design doc | `docs/requirements/Component-Commons.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 2 |
|
||||
|
||||
## Summary
|
||||
@@ -1155,3 +1155,87 @@ fields on positional records MUST be added at the end of the parameter list AND
|
||||
carry a `= null` (or other safe) default value, so existing positional construction
|
||||
sites keep compiling. Apply that rule retroactively to `TrackingStatusSnapshot` and any
|
||||
other recent record that did not adopt it. No behavioral change required.
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the SMS (Twilio) notifications feature (#21 Notification Outbox / #8
|
||||
Notification Service slice). Three Low-severity findings in Commons; all closed. The new
|
||||
`SmsConfiguration` POCO, `NotificationType.Sms`, the `NotificationRecipient` `ForEmail`/`ForSms`
|
||||
factories, and the additive message-contract changes all follow the established conventions.
|
||||
|
||||
### Commons-024 — `NotificationRecipient` public constructor name-guard weaker than the factories
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Notifications/NotificationRecipient.cs:21-25` |
|
||||
|
||||
**Description**
|
||||
|
||||
The public `NotificationRecipient(string name, string emailAddress)` constructor validated `name`
|
||||
with a null-only check (`name ?? throw`), while the `ForEmail`/`ForSms` factories reject
|
||||
null-or-whitespace names. A caller using the public ctor directly could produce a recipient with a
|
||||
whitespace name, an invariant the factories forbid. (EF materializes via the private parameterless
|
||||
ctor + property injection, so this ctor is reached only by intentional email-path callers.)
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Tighten the public ctor's name guard to `IsNullOrWhiteSpace` to match the factories.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): the public ctor now throws `ArgumentException` on a
|
||||
null-or-whitespace name, matching `ForEmail`. Locked by `NotificationRecipientTests` (commit `a9393c89`).
|
||||
|
||||
### Commons-025 — No unit tests for `NotificationRecipient.ForEmail`/`ForSms` factory invariants
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Status | Resolved |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Entities/NotificationRecipientTests.cs` |
|
||||
|
||||
**Description**
|
||||
|
||||
The recipient construction invariants (email-only for `ForEmail`, phone-only for `ForSms`,
|
||||
non-blank name on every path) were exercised only transitively via ManagementActor tests, with no
|
||||
focused Commons-layer unit tests.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add a `NotificationRecipientTests` covering both factories' happy paths, the null/whitespace guards,
|
||||
and the contact-field exclusivity.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `a9393c89`): added `NotificationRecipientTests` (14 cases) covering
|
||||
`ForEmail`/`ForSms` happy paths, contact-field exclusivity, null/whitespace name guards, and the
|
||||
public-ctor guards.
|
||||
|
||||
### Commons-026 — `Create/UpdateNotificationListCommand.RecipientEmails` non-nullable even for SMS lists
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Code organization & conventions |
|
||||
| Status | Won't Fix |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/NotificationCommands.cs:7-8` |
|
||||
|
||||
**Description**
|
||||
|
||||
`CreateNotificationListCommand`/`UpdateNotificationListCommand` carry `RecipientEmails` as a
|
||||
required positional parameter even when `Type = Sms`, where it is semantically irrelevant (the
|
||||
handler ignores it and reads `RecipientPhones`). This is an ergonomics wart, not a correctness bug.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Optionally default `RecipientEmails` to an empty list, or normalize null→empty in the handler.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Won't Fix (2026-06-19): not a correctness defect — the handler already ignores `RecipientEmails`
|
||||
for SMS lists. Changing a required positional parameter to defaulted/nullable is a breaking
|
||||
contract change for existing callers for a pure-ergonomics gain; deferred indefinitely.
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase` |
|
||||
| Design doc | `docs/requirements/Component-ConfigurationDatabase.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 0 |
|
||||
|
||||
## Summary
|
||||
@@ -1373,3 +1373,91 @@ later months. This pins down the resolution of CD-019. (2) Add a
|
||||
`DeploymentRecord`, clear the change tracker, call `DeleteDeploymentRecordAsync`,
|
||||
and assert the row is gone — pinning the resolution of CD-018. Both tests should be
|
||||
`[SkippableFact]` so the suite still passes when no MS SQL Server is available.
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the SMS (Twilio) notifications data layer: the `SmsConfiguration` EF mapping +
|
||||
encrypted `AuthToken`, the `AddSmsNotifications` migration, and the `NotificationRecipient` nullable
|
||||
contact change. The encryption wiring (`EncryptedStringConverter` on `AuthToken` via
|
||||
`ApplySecretColumnEncryption` + `GuardSecretWritesHaveAKeyRing`) mirrors `SmtpConfiguration.Credentials`
|
||||
and is correct. Two Medium findings (one data-safety, one test gap) and one Low test gap; the two
|
||||
Mediums are Resolved.
|
||||
|
||||
### ConfigurationDatabase-025 — `AddSmsNotifications.Down()` silently corrupts SMS-only recipients
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Medium |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20260619135543_AddSmsNotifications.cs:52-66` |
|
||||
|
||||
**Description**
|
||||
|
||||
The `Down()` migration drops the `PhoneNumber` column and backfills every NULL `EmailAddress` to `''`
|
||||
so the column can revert to NOT NULL. An SMS-only recipient (PhoneNumber set, EmailAddress
|
||||
legitimately NULL) is therefore corrupted on rollback: its phone is dropped and its email becomes an
|
||||
invalid empty string. In a database where SMS lists have been created, the rollback destroys contact data.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Before dropping `PhoneNumber`, guard the rollback: throw if any SMS-only recipient (PhoneNumber set,
|
||||
EmailAddress NULL) exists, so the operator must reassign/remove them first instead of losing data silently.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): `Down()` now runs a `THROW`-on-`IF EXISTS` guard for
|
||||
SMS-only recipients as its first statement (while `PhoneNumber` is still queryable), refusing the
|
||||
rollback instead of corrupting data. Comments document the invariant.
|
||||
|
||||
### ConfigurationDatabase-026 — No encryption-at-rest regression test for `SmsConfiguration.AuthToken`
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Medium |
|
||||
| Category | Testing coverage |
|
||||
| Status | Resolved |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/SecretEncryptionTests.cs` |
|
||||
|
||||
**Description**
|
||||
|
||||
`SecretEncryptionTests` covered the database-connection, SMTP-credentials, and external-system secrets
|
||||
with "stored-encrypted / raw != plaintext / round-trips" tests, but had no parallel test for the
|
||||
Twilio `AuthToken`. A refactor dropping `SmsConfiguration` from `ApplySecretColumnEncryption` would go
|
||||
uncaught.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add `SmsConfiguration_AuthToken_StoredEncrypted_RoundTrips` and a null-round-trip test mirroring the
|
||||
SMTP shape.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `a9393c89`): added both tests; the encrypted test also asserts the raw
|
||||
column is ciphertext and that `AccountSid` stays plaintext.
|
||||
|
||||
### ConfigurationDatabase-027 — No MS SQL migration integration test for `AddSmsNotifications`
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Status | Deferred |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Migrations/` |
|
||||
|
||||
**Description**
|
||||
|
||||
Prior structural migrations have MS SQL integration tests asserting the resulting columns/types/nullability.
|
||||
`AddSmsNotifications` (and the follow-up `SmsFromNumberOptional`) have none, so the column shapes and the
|
||||
idempotency of the `ALTER COLUMN` statements are unverified against a real SQL Server.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add an `AddSmsNotificationsMigrationTests` using the `MsSqlMigrationFixture` pattern.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Deferred (2026-06-19): the migrations are standard idempotent `ALTER`/guarded-`CREATE` statements
|
||||
verified by the model snapshot and the build, and `AddSmsNotifications` was applied to the real
|
||||
docker MS SQL during the feature's integration pass. A live-SQL migration test is tracked for a
|
||||
future ConfigurationDatabase test-stability pass.
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.ManagementService` |
|
||||
| Design doc | `docs/requirements/Component-ManagementService.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 0 (1 Deferred — see ManagementService-012) |
|
||||
|
||||
## Summary
|
||||
@@ -1131,3 +1131,88 @@ entirely.
|
||||
|
||||
Defer until a noticeable hot path emerges, but track it: this is the only N+1 in
|
||||
`ManagementActor` once 002 / 014 are folded in.
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the `ManagementActor` SMS surface: the SMS/SMTP provider-config command gating,
|
||||
`HandleUpdateSmsConfig`, and the `SmsConfigPublicShape` secret projection. The secret-redaction chain
|
||||
(`SmsConfigPublicShape` exposes `HasAuthToken` only; the AuthToken never reaches the response or audit
|
||||
afterState) is correct and tested. One High authorization finding, one Medium secret-clear footgun, one
|
||||
Low stale comment; all Resolved.
|
||||
|
||||
### ManagementService-024 — SMS/SMTP provider-config updates were Designer-gated despite Admin-only UI
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | High |
|
||||
| Category | Security |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs:189-190` |
|
||||
|
||||
**Description**
|
||||
|
||||
`UpdateSmsConfigCommand` (and the pre-existing `UpdateSmtpConfigCommand`) were placed in the Designer
|
||||
arm of `GetRequiredRole`, but both the `/notifications/sms` and `/notifications/smtp` Central UI pages
|
||||
enforce `RequireAdmin`. This split-brain let a Designer who is blocked in the UI still rotate a
|
||||
production credential (the Twilio Auth Token / SMTP password) via the CLI / Management API. The design
|
||||
(D8) specifies SMS config management as Admin-only.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Move `UpdateSmsConfigCommand` (and `UpdateSmtpConfigCommand`, whose UI page is also RequireAdmin) to the
|
||||
Administrator arm so the actor gate matches the UI.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): both update commands moved to the Administrator arm. Locked by
|
||||
`UpdateSmsConfig_WithDesignerRole_ReturnsUnauthorized` and updated success-case tests (commit `a9393c89`).
|
||||
|
||||
### ManagementService-025 — Empty-string `--auth-token` silently clears the stored Twilio token
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Medium |
|
||||
| Category | Security |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs:1859` |
|
||||
|
||||
**Description**
|
||||
|
||||
`HandleUpdateSmsConfig` used `if (cmd.AuthToken is not null)` for preserve-if-omitted. An explicit empty
|
||||
/ whitespace `--auth-token ""` passes the null check and overwrites the stored token with empty, silently
|
||||
clearing the credential and 401-ing every subsequent send. A Twilio Auth Token is always required, so an
|
||||
empty value is never a valid rotation.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Guard on `IsNullOrWhiteSpace` so an empty token is treated as omitted (preserve). (SMTP `Credentials`
|
||||
keeps its null-only guard, since empty may be valid for anonymous SMTP.)
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): the guard is now `!string.IsNullOrWhiteSpace(cmd.AuthToken)`.
|
||||
Locked by `UpdateSmsConfig_WithEmptyAuthToken_PreservesExistingToken` (commit `a9393c89`).
|
||||
|
||||
### ManagementService-026 — Stale "Admin-only" comment on `HandleListSmtpConfigs`
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Documentation & comments |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs:1788-1790` |
|
||||
|
||||
**Description**
|
||||
|
||||
The comment on `HandleListSmtpConfigs` called the `UpdateSmtpConfig` path "Admin-only", which did not
|
||||
match its (then) Designer gating; the SMS counterpart comment said "Designer-gated". The two were
|
||||
inconsistent.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Make the comments accurate after fixing the gating.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): with both update commands moved to Administrator (MS-024), the
|
||||
SMTP "Admin-only" comment is now accurate and the SMS list comment was updated to "Admin-only".
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox` |
|
||||
| Design doc | `docs/requirements/Component-NotificationOutbox.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 7 |
|
||||
|
||||
## Summary
|
||||
@@ -486,3 +486,89 @@ task-construction throw and is otherwise unreachable."
|
||||
**Resolution**
|
||||
|
||||
_Unresolved._
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the Twilio `SmsNotificationDeliveryAdapter`, `SmsErrorClassifier`, `SmsOptions`,
|
||||
the DI registration, and the `NotificationOutboxActor` ingest type-stamping. This is the risk centre of
|
||||
the feature; it is well-built. The Twilio request shape, the transient/permanent error classification,
|
||||
the per-recipient rollup, and — critically — the AuthToken redaction on every error path
|
||||
(`CredentialRedactor.Scrub`) are all correct and well-tested. Three Low findings; all closed.
|
||||
|
||||
### NotificationOutbox-011 — `SmsConfiguration.MaxRetries`/`RetryDelay` are operator-settable but never honored
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Design-document adherence |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs:370-404` |
|
||||
|
||||
**Description**
|
||||
|
||||
The dispatcher's `ResolveRetryPolicyAsync` derives the retry policy (max-retries + interval) from the
|
||||
central SMTP configuration for all notification types. `SmsConfiguration.MaxRetries`/`RetryDelay` are
|
||||
operator-editable (management, UI, Transport) but never read at dispatch time — they are dead config,
|
||||
which misleads an operator who sets them. (`ConnectionTimeoutSeconds`, by contrast, IS honored by the
|
||||
adapter.)
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Either honor the per-SMS values type-aware in `ResolveRetryPolicyAsync`, or document the fields as
|
||||
reserved so operators are not misled.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): the fields are now documented as RESERVED on the entity
|
||||
(XML doc) and in `Component-NotificationService.md` — the dispatcher reuses the shared SMTP-derived
|
||||
retry policy per the documented "retry reuses central SMTP" decision. Honoring them per-type would
|
||||
supersede that decision and is recorded as a deferred enhancement (not changed unilaterally for a Low finding).
|
||||
|
||||
### NotificationOutbox-012 — SMS body truncation can split a surrogate pair at the cap boundary
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Resolved |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/SmsNotificationDeliveryAdapter.cs:359-367` |
|
||||
|
||||
**Description**
|
||||
|
||||
`ComposeBody` truncates by UTF-16 code-unit index. If `MaxMessageLength` falls on a surrogate-pair
|
||||
boundary (e.g. an emoji in the alarm subject/body), the cut emits a lone surrogate — one malformed
|
||||
character at the boundary. Cosmetic and only at the exact cap.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Back off one code unit if the cut would split a surrogate pair.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `cd8e4872`): the truncation now backs off by one code unit when the cut
|
||||
index lands immediately after a high surrogate, keeping the body well-formed and within the cap.
|
||||
|
||||
### NotificationOutbox-013 — No actor-level dispatch test for SMS-typed routing
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Status | Resolved |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/NotificationOutboxActorDispatchTests.cs` |
|
||||
|
||||
**Description**
|
||||
|
||||
The adapter, ingest type-stamping, and DI registration were independently tested, but no actor-level
|
||||
test exercised the Type-keyed adapter selection landing an SMS-typed notification on the SMS adapter
|
||||
(vs the Email adapter).
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add a dispatch test that routes an SMS-typed notification through an SMS stub adapter and asserts the
|
||||
outcome.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `a9393c89`): made the dispatch-test stub adapter Type-configurable and
|
||||
added `Dispatch_SmsTypedNotification_RoutesToSmsAdapter_NotEmailAdapter`.
|
||||
|
||||
@@ -50,20 +50,20 @@ module file and counted in **Total**.
|
||||
| Module | Last reviewed | Commit | Open (C/H/M/L) | Open | Total |
|
||||
|--------|---------------|--------|----------------|------|-------|
|
||||
| [AuditLog](AuditLog/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 11 |
|
||||
| [CLI](CLI/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 23 |
|
||||
| [CentralUI](CentralUI/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 33 |
|
||||
| [CLI](CLI/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 24 |
|
||||
| [CentralUI](CentralUI/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 36 |
|
||||
| [ClusterInfrastructure](ClusterInfrastructure/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 14 |
|
||||
| [Commons](Commons/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 23 |
|
||||
| [Commons](Commons/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 26 |
|
||||
| [Communication](Communication/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 22 |
|
||||
| [ConfigurationDatabase](ConfigurationDatabase/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 24 |
|
||||
| [ConfigurationDatabase](ConfigurationDatabase/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 27 |
|
||||
| [DataConnectionLayer](DataConnectionLayer/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 22 |
|
||||
| [DeploymentManager](DeploymentManager/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 24 |
|
||||
| [ExternalSystemGateway](ExternalSystemGateway/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 23 |
|
||||
| [HealthMonitoring](HealthMonitoring/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 23 |
|
||||
| [Host](Host/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 22 |
|
||||
| [InboundAPI](InboundAPI/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 25 |
|
||||
| [ManagementService](ManagementService/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 23 |
|
||||
| [NotificationOutbox](NotificationOutbox/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 10 |
|
||||
| [ManagementService](ManagementService/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 26 |
|
||||
| [NotificationOutbox](NotificationOutbox/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 13 |
|
||||
| [NotificationService](NotificationService/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 25 |
|
||||
| [Security](Security/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 21 |
|
||||
| [SiteCallAudit](SiteCallAudit/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 6 |
|
||||
@@ -71,7 +71,7 @@ module file and counted in **Total**.
|
||||
| [SiteRuntime](SiteRuntime/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 26 |
|
||||
| [StoreAndForward](StoreAndForward/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 24 |
|
||||
| [TemplateEngine](TemplateEngine/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 22 |
|
||||
| [Transport](Transport/findings.md) | 2026-05-28 | `1eb6e97` | 0/0/0/0 | 0 | 12 |
|
||||
| [Transport](Transport/findings.md) | 2026-06-19 | `d6ead8ae` | 0/0/0/0 | 0 | 15 |
|
||||
|
||||
## Pending Findings
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
| Module | `src/ZB.MOM.WW.ScadaBridge.Transport` |
|
||||
| Design doc | `docs/requirements/Component-Transport.md` |
|
||||
| Status | Reviewed |
|
||||
| Last reviewed | 2026-05-28 |
|
||||
| Last reviewed | 2026-06-19 |
|
||||
| Reviewer | claude-agent |
|
||||
| Commit reviewed | `1eb6e97` |
|
||||
| Open findings | 7 |
|
||||
| Commit reviewed | `d6ead8ae` |
|
||||
| Open findings | 0 |
|
||||
|
||||
## Summary
|
||||
|
||||
@@ -527,3 +527,90 @@ but the Audit-Log-Viewer UI surface — the dropdown + `BundleImported` hyperlin
|
||||
is a deferred UI follow-up. Operators have a workaround via the existing
|
||||
`audit query --bundle-import-id` CLI flag. The UI work belongs in the CentralUI
|
||||
backlog; implementing it here would expand scope beyond a doc fix.
|
||||
|
||||
#### Re-review 2026-06-19 (commit `d6ead8ae`) — SMS notifications feature
|
||||
|
||||
Per-module review of the Transport SMS surface: `SmsConfigDto`, the entity serializer round-trip,
|
||||
`ApplySmsConfigsAsync` (AccountSid-keyed upsert), and `CompareSmsConfiguration`. The secret isolation is
|
||||
correct — the AuthToken rides only the encrypted `SecretsBlock`, never the plaintext DTO/diff, and the
|
||||
diff is presence-only. Backward-compat with pre-SMS bundles holds (`SmsConfigs` defaults to empty). Two
|
||||
findings carried over as Won't Fix (shared/inherited patterns), one Low test gap Resolved.
|
||||
|
||||
### Transport-015 — `ApplySmsConfigsAsync` Rename branch falls back to the original key when `RenameTo` is null
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Medium |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Won't Fix |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs:2573` |
|
||||
|
||||
**Description**
|
||||
|
||||
The Rename branch uses `resolution.RenameTo ?? dto.AccountSid`; a null `RenameTo` on a Rename action
|
||||
would add a config under the original key, risking a duplicate. Flagged Medium by the reviewer.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Guard the Rename branch against a null `RenameTo`.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Won't Fix (2026-06-19): on investigation this is the established repo-wide import pattern — every entity
|
||||
type's apply method uses the identical `resolution.RenameTo ?? <originalKey>` fallback (templates,
|
||||
folders, sites, data connections, instances, SMTP at line 2497, SMS at line 2573, ...). It is not
|
||||
SMS-specific, the import-wizard / CLI map step supplies `RenameTo` for a Rename action (the `??` is
|
||||
belt-and-suspenders), and the reviewer's proposed guard would merely relabel the duplicate as an Add. If
|
||||
the null-`RenameTo` edge is a real concern it is a Transport-wide question outside the SMS review scope;
|
||||
changing only the SMS branch would break the cross-entity consistency.
|
||||
|
||||
### Transport-016 — New `SmsConfiguration` audit rows log entity id "0"
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Correctness & logic bugs |
|
||||
| Status | Won't Fix |
|
||||
| Location | `src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs:2576,2594` |
|
||||
|
||||
**Description**
|
||||
|
||||
Audit rows for newly created `SmsConfiguration` entities log `"0"` as the entity id (the surrogate key
|
||||
is unknown before EF assigns it), mirroring the SMTP path. Correlation is still possible by name
|
||||
(AccountSid), so the id is misleading but not lost.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Read back the assigned id after save and use it in the audit `LogAsync` call.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Won't Fix (2026-06-19): this is the established inherited pattern (SMTP at lines 2500/2518 does the same)
|
||||
and is not a regression introduced by the SMS work. The audit row carries the AccountSid as
|
||||
`entityName`, so the row is correlatable. A cross-entity cleanup to log real ids is out of the SMS
|
||||
review scope.
|
||||
|
||||
### Transport-017 — No unit tests for `CompareSmsConfiguration`
|
||||
|
||||
| | |
|
||||
|--|--|
|
||||
| Severity | Low |
|
||||
| Category | Testing coverage |
|
||||
| Status | Resolved |
|
||||
| Location | `tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/Import/ArtifactDiffTests.cs` |
|
||||
|
||||
**Description**
|
||||
|
||||
`CompareSmsConfiguration` (the new diff method) had no dedicated unit tests; in particular the
|
||||
secret presence-only invariant (the AuthToken value must never be echoed) relied on parallelism with the
|
||||
SMTP/DataConnection patterns rather than a direct assertion.
|
||||
|
||||
**Recommendation**
|
||||
|
||||
Add unit tests for New/Identical/Modified plus the AuthToken presence-only invariant.
|
||||
|
||||
**Resolution**
|
||||
|
||||
Resolved 2026-06-19 (commit `a9393c89`): added five `CompareSmsConfiguration` tests — existing-null→New,
|
||||
all-match→Identical, FromNumber-differs→Modified, and the two secret cases (value-changes-but-presence-
|
||||
preserved → no echo; presence-flip → `<present>` marker only, token never echoed).
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
"DataConnection": {
|
||||
"ReconnectInterval": "00:00:05",
|
||||
"TagResolutionRetryInterval": "00:00:10",
|
||||
"WriteTimeout": "00:00:30"
|
||||
"WriteTimeout": "00:00:30",
|
||||
"SeedReadTimeout": "00:00:30"
|
||||
},
|
||||
"StoreAndForward": {
|
||||
"SqliteDbPath": "/app/data/store-and-forward.db",
|
||||
|
||||
@@ -119,8 +119,15 @@ Deferrals (NOT shipped in M9):
|
||||
- Folder drag-drop — permanently deferred (`[PERM]`). Menu-based reorder (T23) ships instead.
|
||||
- Unified notifications+site-calls outbox page — deferred; Notification Outbox and Site Calls pages remain separate.
|
||||
|
||||
#### M10 — UI/UX platform (T33–T36, T41)
|
||||
`IDialogService` modal abstraction; design-tokens/CSS-vars + dark-mode/theming; shared pagination+filter component; accessibility pass; Playwright alarm-override UI coverage.
|
||||
#### M10 — UI/UX platform (T33–T36, T41) — **DELIVERED**
|
||||
Delivered per `docs/plans/2026-06-18-m10-uiux-platform.md` (full scope):
|
||||
- **T33** — custom-content modal host: `DialogService.ShowAsync<TResult>` generic overload + `DialogContext<TResult>` + focus-trap + focus-restore + tokenized `.sb-modal-backdrop`; 5 simple dialogs (MoveFolder, MoveTemplate, RenameFolder, ComposeInto, MoveDataConnection) migrated from inline `rgba` backdrops onto the host.
|
||||
- **T34** — dark-mode toggle: CSS-variable token layer (`[data-bs-theme="dark"]` block in `site.css` overriding the `ZB.MOM.WW.Theme` light `:root` tokens, `localStorage`-persisted, SSR no-flash inline hydration script) + `DarkModeToggle` component in the rail footer; all standalone `rgba` backdrops tokenized to `.sb-modal-backdrop` (incl. InstanceConfigure, NodeBrowserDialog, TestBindingsDialog, MoveInstance/Area/CreateArea, TemplateEdit).
|
||||
- **T35** — 3 reusable presentational components: `OffsetPager` (prev/next + "Page X of Y · N total"), `KeysetPager` (cursor-stack nav + "Page X · Y rows"), `DateTimeRangeFilter` (input-only from/to pair, UTC conversion stays page-side); adopted into NotificationReport, ConfigurationAuditLog, SiteCallsReport, AuditResultsGrid+AuditFilterBar, EventLogs.
|
||||
- **T36** — bounded a11y pass: TreeView chevron gains `role="button"` + `tabindex="0"` + `aria-label`/`aria-expanded` + Enter/Space keyboard activation; Toast/LoadingSpinner/AlarmStateBadges confirmed already compliant; regression bUnit tests locked.
|
||||
- **T41** — Playwright alarm-override trigger-config coverage: HiLo setpoint merge, non-HiLo whole-replace, validation error stays open, Cancel, Clear-from-modal — all asserted via UI + CLI read-back.
|
||||
|
||||
This is the **final milestone** of the system-completion roadmap. All in-scope M1–M10 features are now delivered. Follow-up items logged in `docs/plans/2026-06-18-m10-uiux-platform.md`.
|
||||
|
||||
## Dependencies & sequencing
|
||||
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
# T34 Spike: Theme Dark-Mode Feasibility Findings
|
||||
|
||||
**Date:** 2026-06-18
|
||||
**Task:** Verify whether the external `ZB.MOM.WW.Theme` shell can go dark via `data-bs-theme` CSS override.
|
||||
|
||||
---
|
||||
|
||||
## 1. CSS Load Order
|
||||
|
||||
Confirmed from `src/ZB.MOM.WW.ScadaBridge.Host/Components/App.razor`:
|
||||
|
||||
```
|
||||
bootstrap.min.css (line 8)
|
||||
bootstrap-icons.css (line 9)
|
||||
<ThemeHead /> (line 10) → injects theme.css then layout.css
|
||||
Host.styles.css (line 11)
|
||||
site.css (line 12) ← our override point
|
||||
```
|
||||
|
||||
`site.css` loads **after** theme.css and layout.css. A `[data-bs-theme="dark"]` block in site.css has sufficient specificity to shadow every `:root` token defined in theme.css, because `[attr]` selector specificity (0,1,0) beats `:root` (0,0,1) at equal cascade layer.
|
||||
|
||||
---
|
||||
|
||||
## 2. Token Inventory (theme.css `:root`)
|
||||
|
||||
All tokens defined in the `:root` block of `~/.nuget/packages/zb.mom.ww.theme/0.3.1/staticwebassets/css/theme.css`:
|
||||
|
||||
### Surfaces & ink
|
||||
| Token | Light value | Role |
|
||||
|---|---|---|
|
||||
| `--paper` | `#f4f4f1` | page background |
|
||||
| `--card` | `#ffffff` | raised surfaces, bars, table heads |
|
||||
| `--ink` | `#1b1d21` | primary text |
|
||||
| `--ink-soft` | `#5a6066` | secondary text, labels |
|
||||
| `--ink-faint` | `#8b9097` | tertiary text, captions |
|
||||
| `--rule` | `#e4e4df` | hairline borders, row dividers |
|
||||
| `--rule-strong` | `#d2d2cb` | emphasised hairlines, bar underline, pills |
|
||||
|
||||
### Accent
|
||||
| Token | Light value | Role |
|
||||
|---|---|---|
|
||||
| `--accent` | `#2f5fd0` | links, sort arrows, primary actions |
|
||||
| `--accent-deep` | `#1e3f99` | hover/pressed accent |
|
||||
|
||||
### Status — foreground
|
||||
| Token | Light value |
|
||||
|---|---|
|
||||
| `--ok` | `#2f9e44` |
|
||||
| `--warn` | `#e8920c` |
|
||||
| `--bad` | `#e03131` |
|
||||
| `--idle` | `#868e96` |
|
||||
|
||||
### Status — tinted backgrounds
|
||||
| Token | Light value |
|
||||
|---|---|
|
||||
| `--ok-bg` | `#e9f6ec` |
|
||||
| `--warn-bg` | `#fdf1dd` |
|
||||
| `--bad-bg` | `#fceaea` |
|
||||
| `--idle-bg` | `#eef0f2` |
|
||||
|
||||
### Status — borders
|
||||
| Token | Light value |
|
||||
|---|---|
|
||||
| `--ok-border` | `#c6e6cd` |
|
||||
| `--warn-border` | `#efd6a6` |
|
||||
| `--bad-border` | `#eec3c3` |
|
||||
| `--ok-border-soft` | `#bfe3c6` |
|
||||
| `--warn-border-soft` | `#f0d9ab` |
|
||||
| `--bad-border-soft` | `#f0c0c0` |
|
||||
|
||||
### Warning ink
|
||||
| Token | Light value |
|
||||
|---|---|
|
||||
| `--warn-ink` | `#b56a00` |
|
||||
| `--warn-ink-deep` | `#8a5a00` |
|
||||
|
||||
### Info tint
|
||||
| Token | Light value |
|
||||
|---|---|
|
||||
| `--info-bg` | `#e7ecfb` |
|
||||
| `--info-border` | `#cdd9f7` |
|
||||
|
||||
### Neutral surface washes
|
||||
| Token | Light value | Role |
|
||||
|---|---|---|
|
||||
| `--zebra-bg` | `#fbfbf9` | even-row / sticky-head fill |
|
||||
| `--hover-bg` | `#f3f6fd` | row / rail-link hover |
|
||||
| `--active-bg` | `#eef2fc` | active rail-link fill |
|
||||
|
||||
### Bootstrap overrides (derive from above)
|
||||
| Token | Value |
|
||||
|---|---|
|
||||
| `--bs-body-bg` | `var(--paper)` |
|
||||
| `--bs-body-color` | `var(--ink)` |
|
||||
| `--bs-body-font-family` | `var(--sans)` |
|
||||
| `--bs-body-font-size` | `0.9rem` |
|
||||
| `--bs-primary` | `var(--accent)` |
|
||||
| `--bs-border-color` | `var(--rule)` |
|
||||
| `--bs-emphasis-color` | `var(--ink)` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Rail Tokenization Audit (layout.css)
|
||||
|
||||
Every colour-bearing rule in the side-rail uses CSS custom properties. No hard-coded hex or rgb values appear anywhere in layout.css. Key rules:
|
||||
|
||||
**Rail background and border:**
|
||||
```css
|
||||
.side-rail {
|
||||
background: var(--card);
|
||||
border-right: 1px solid var(--rule-strong);
|
||||
}
|
||||
```
|
||||
|
||||
**Brand block:**
|
||||
```css
|
||||
.side-rail .brand {
|
||||
color: var(--ink);
|
||||
border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.side-rail .brand .mark { color: var(--accent); }
|
||||
```
|
||||
|
||||
**Section eyebrow / toggle:**
|
||||
```css
|
||||
.rail-eyebrow-toggle { color: var(--ink-faint); }
|
||||
.rail-eyebrow-toggle:hover { color: var(--ink); }
|
||||
.rail-section > summary::before { color: var(--ink-faint); }
|
||||
```
|
||||
|
||||
**Nav links (default / hover / active):**
|
||||
```css
|
||||
.rail-link { color: var(--ink-soft); }
|
||||
.rail-link:hover { background: var(--hover-bg); color: var(--ink); }
|
||||
.rail-link.active { background: var(--active-bg); border-left-color: var(--accent); color: var(--accent-deep); }
|
||||
```
|
||||
|
||||
**Rail foot / session block:**
|
||||
```css
|
||||
.rail-foot { border-top: 1px solid var(--rule); }
|
||||
.rail-btn { color: var(--ink-soft); background: var(--card); border: 1px solid var(--rule-strong); }
|
||||
.rail-btn:hover { border-color: var(--accent); color: var(--accent); }
|
||||
.rail-roles { color: var(--ink-faint); }
|
||||
.rail-ico { color: var(--ink-faint); }
|
||||
```
|
||||
|
||||
**Login title:**
|
||||
```css
|
||||
.login-title { color: var(--ink); }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. VERDICT
|
||||
|
||||
**RAIL TOKENIZES → dark feasible by token override.**
|
||||
|
||||
Every rail background, text, and border colour in layout.css resolves through a CSS custom property from the token set. Overriding the token values under `[data-bs-theme="dark"]` in site.css (which loads after theme.css/layout.css) will fully recolour the side-rail, app chrome, panels, data tables, chips, and status elements — no Theme-package coordination required.
|
||||
|
||||
---
|
||||
|
||||
## 5. Concrete Dark Token Override List
|
||||
|
||||
Paste this entire block under `[data-bs-theme="dark"]` in site.css. Accent colour (`--accent`) is kept at `#4d7fe8` — a lighter shade of the brand blue that reads well on dark backgrounds while preserving brand identity.
|
||||
|
||||
```css
|
||||
[data-bs-theme="dark"] {
|
||||
/* Surfaces & ink */
|
||||
--paper: #1b1d21;
|
||||
--card: #25282d;
|
||||
--ink: #e6e8ec;
|
||||
--ink-soft: #9aa0aa;
|
||||
--ink-faint: #6b727c;
|
||||
--rule: #33373e;
|
||||
--rule-strong: #3a3f46;
|
||||
|
||||
/* Accent — lightened for contrast on dark */
|
||||
--accent: #4d7fe8;
|
||||
--accent-deep: #7aa0ef;
|
||||
|
||||
/* Status — foregrounds unchanged (inherently visible on dark) */
|
||||
--ok: #40b856;
|
||||
--warn: #f0a030;
|
||||
--bad: #f05050;
|
||||
--idle: #7a8290;
|
||||
|
||||
/* Status — tinted backgrounds (dark surface tints) */
|
||||
--ok-bg: #1a2e1e;
|
||||
--warn-bg: #2e2210;
|
||||
--bad-bg: #2e1616;
|
||||
--idle-bg: #25282d;
|
||||
|
||||
/* Status — borders on dark tints */
|
||||
--ok-border: #2a5030;
|
||||
--warn-border: #4a3510;
|
||||
--bad-border: #4a2020;
|
||||
--ok-border-soft: #264a2c;
|
||||
--warn-border-soft: #44300e;
|
||||
--bad-border-soft: #44201e;
|
||||
|
||||
/* Warning ink — brightened amber for dark contrast */
|
||||
--warn-ink: #d4891a;
|
||||
--warn-ink-deep: #b8741a;
|
||||
|
||||
/* Info tint */
|
||||
--info-bg: #1a2240;
|
||||
--info-border: #2a3660;
|
||||
|
||||
/* Neutral surface washes */
|
||||
--zebra-bg: #202328;
|
||||
--hover-bg: #2a2e38;
|
||||
--active-bg: #1e2640;
|
||||
|
||||
/* Bootstrap bridge tokens */
|
||||
--bs-body-bg: var(--paper);
|
||||
--bs-body-color: var(--ink);
|
||||
--bs-border-color: var(--rule);
|
||||
--bs-emphasis-color: var(--ink);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Caveats
|
||||
|
||||
1. **Bootstrap intrinsic dark utilities**: Bootstrap 5.3 has its own `[data-bs-theme="dark"]` rules for components (alerts, badges, modals, etc.). Our token block sits in site.css at cascade level 0; Bootstrap's own dark-mode block in bootstrap.min.css (loaded earlier) will also fire. The Bootstrap rules and our token rules are additive and complementary — they should not conflict, but any Bootstrap component that ignores our tokens and uses Bootstrap's built-in dark-mode palette may have a slightly different feel. Inspect on first run.
|
||||
|
||||
2. **`body` gradient in theme.css**: The `body` rule in theme.css is:
|
||||
```css
|
||||
body {
|
||||
background: radial-gradient(1200px 480px at 88% -8%, var(--card) 0%, rgba(255,255,255,0) 70%),
|
||||
var(--paper);
|
||||
}
|
||||
```
|
||||
On dark mode, `rgba(255,255,255,0)` in the gradient is transparent white and will remain unchanged. The gradient will still render; `var(--card)` will resolve to the dark card value and the effect will be a subtle lighter sheen in the top-right corner — acceptable, but the gradient can be suppressed in site.css for a flatter dark background if preferred.
|
||||
|
||||
3. **Status tints on dark**: The status background tokens (`--ok-bg`, `--warn-bg`, `--bad-bg`) are deliberately dark-surface equivalents (very low-saturation tints). Verify contrast ratios of status chip text against these backgrounds before shipping.
|
||||
|
||||
4. **`data-bs-theme` placement**: The attribute must be set on `<html>` (or `<body>`) so the CSS selector matches all descendants. The toggle implementation (next task) should write `document.documentElement.setAttribute('data-bs-theme', 'dark')`.
|
||||
@@ -0,0 +1,100 @@
|
||||
# M10 — UI/UX Platform Design (T33–T36, T41)
|
||||
|
||||
> Final milestone of the system-completion roadmap (`docs/plans/2026-06-15-stillpending-completion-design.md`).
|
||||
> Branch: `worktree-m10-uiux-platform` off `origin/main` @ `ba335519`.
|
||||
|
||||
## Goal
|
||||
|
||||
Consolidate the Central UI's cross-cutting presentation concerns into a small set of reusable primitives — a custom-content modal host, a CSS-variable token layer with a dark-mode toggle, extracted pagination/filter components — plus a bounded accessibility pass and Playwright coverage for the alarm-override trigger-config UI. No new functional surfaces; this is platform hardening of what already ships.
|
||||
|
||||
## Scope (locked)
|
||||
|
||||
| Task | What ships |
|
||||
|---|---|
|
||||
| **T33** | Custom-content modal host: extend the existing `DialogHost`/`DialogService` with `ShowAsync<TResult>(title, RenderFragment, …)`, **focus trap + focus restoration + a tokenized backdrop built in**. Migrate the simple reusable dialogs (`MoveFolder`, `MoveDataConnection`, `MoveTemplate`, `RenameFolder`, `ComposeInto`) onto it. Leave the 4 complex `TemplateEdit` page-embedded modals as-is. |
|
||||
| **T34** | Full dark-mode toggle (sun/moon control) binding `data-bs-theme` on `<html>` + `localStorage` persistence + SSR hydration; an app-level CSS-variable **token layer**; tokenize the ~17 hard-coded `rgba(0,0,0,…)` backdrops (now centralized in the modal host) + audit `bg-light/white/dark` utility usage. **Gated by a verification spike** on the external `ZB.MOM.WW.Theme` shell. |
|
||||
| **T35** | Extract three targeted components — `OffsetPager`, `KeysetPager`, `DateTimeRangeFilter` — and adopt them into the pages that already share each pattern. **Not** a unified offset+keyset framework. |
|
||||
| **T36** | Bounded accessibility pass: aria-label audit/fix for icon buttons, status badges, and spinners; modal focus trap + restoration (delivered **inside** the T33 host); toast `aria-live` verification. No TreeView arrow-key navigation (R7 stays deferred). |
|
||||
| **T41** | Extend the existing `AlarmOverride_SetPriority_ThenClear_RoundTrips` Playwright test with trigger-config scenarios: HiLo setpoint edit (merge), non-HiLo whole-replace, a validation error, modal cancel, clear-from-modal. |
|
||||
|
||||
### Explicitly out of scope (deferred / logged)
|
||||
- A unified offset+keyset pagination framework — blocked by the offset-vs-keyset total-count mismatch; the three extracted components stay separate.
|
||||
- TreeView arrow-key navigation (R7).
|
||||
- Migrating the complex `TemplateEdit` page-embedded modals to the host.
|
||||
- Theming the external `ZB.MOM.WW.Theme` side-rail shell if the spike shows it does not honor `data-bs-theme` (becomes a coordination follow-up, not M10 work).
|
||||
|
||||
## Architecture
|
||||
|
||||
### T33 — Custom-content modal host
|
||||
The existing `DialogHost.razor` / `DialogService` / `IDialogService` already provide `ConfirmAsync` / `PromptAsync` and are DI-registered (`ServiceCollectionExtensions.cs:37`) and rendered once in `MainLayout`. M10 **extends, not replaces**: add a generic `ShowAsync<TResult>(string title, RenderFragment body, …)` overload that renders arbitrary child content inside the same host chrome and resolves a typed result when the dialog closes. The host owns:
|
||||
- the backdrop (a single tokenized element — replaces ~17 per-dialog `rgba(0,0,0,…)` backdrops),
|
||||
- **focus trap** (Tab/Shift-Tab cycle within the modal) + **focus restoration** (return focus to the trigger element on close),
|
||||
- Escape-to-cancel and click-outside-to-cancel (consistent with current behavior).
|
||||
|
||||
Migrated dialogs (`MoveFolder`, `MoveDataConnection`, `MoveTemplate`, `RenameFolder`, `ComposeInto`) drop their own backdrop/markup and become `RenderFragment` bodies passed to `ShowAsync<T>`. Each migration must preserve the dialog's existing observable behavior and keep its current bUnit fixture (or the page's) green.
|
||||
|
||||
### T34 — Token layer + dark mode (spike-gated)
|
||||
Bootstrap 5.3.3 (bundled at `Host/wwwroot/lib/bootstrap`) natively supports `data-bs-theme="dark"`. The plan:
|
||||
1. **Spike first** (`T34-spike`, small): verify whether the external `ZB.MOM.WW.Theme` shell (`<ThemeShell Product="ScadaBridge" Accent="#2f5fd0">` at `MainLayout.razor:6`) honors `data-bs-theme` — does the side-rail go dark? Decide wiring before committing toggle work.
|
||||
2. **Token layer** (`T34a`): introduce an app-level CSS-variable layer in `CentralUI/wwwroot/css/site.css` (semantic tokens — surface, border, backdrop, etc. — mapped onto Bootstrap dark vars), tokenize the modal-host backdrop, and audit `bg-light/white/dark` utility usage so content respects the theme.
|
||||
3. **Dark toggle** (`T34b`, high-risk): a sun/moon control that sets `data-bs-theme` on `<html>`, persists the choice in `localStorage`, and hydrates the correct theme on first paint (SSR — avoid a light-flash). Blazor Server: the toggle is a small JS-interop + a persisted preference.
|
||||
|
||||
**Risk gate:** `T34a`/`T34b` do not start until `T34-spike` reports whether the shell can go dark. If it cannot, we ship tokens-only and log the shell-theming coordination as a follow-up — surfaced to the user before proceeding.
|
||||
|
||||
### T35 — Targeted pager/filter extractions
|
||||
Three independent extractions, each adopted only by pages that already use that exact pattern:
|
||||
- **`OffsetPager`** — page-number/offset paging → `NotificationReport.razor`, `ConfigurationAuditLog.razor` (and the `Deployments.razor` offset via `PagerWindow.cs` if it folds in cleanly).
|
||||
- **`KeysetPager`** — cursor/keyset paging with a cursor stack → `SiteCallsReport.razor`, `Components/Audit/AuditResultsGrid.razor`.
|
||||
- **`DateTimeRangeFilter`** — the existing date-range filter pattern (CentralUI-027, ~8 pages) extracted into one component with UTC conversion centralized.
|
||||
|
||||
No shared base abstraction across offset and keyset — they have genuinely different contracts (offset knows total count; keyset does not). Pages touched by **both** a pager and the date-range filter (NotificationReport, SiteCalls, ConfigAudit) get serialized edits in the plan.
|
||||
|
||||
### T36 — Bounded accessibility pass
|
||||
- **aria-label audit/fix**: icon-only buttons (edit/clear/move/reorder), status badges, and spinners get accessible names. Bounded to high-traffic operator + config pages.
|
||||
- **focus trap + restoration**: delivered *in* the T33 host (one implementation, not per-dialog).
|
||||
- **toast `aria-live`**: verify/confirm `ToastNotification.razor` announces (`aria-live="polite"` already at line 14) and that dynamically-added toasts are announced.
|
||||
|
||||
### T41 — Alarm-override Playwright extension
|
||||
Extend the existing test (`Deployment/InstanceConfigureTests.cs:192`) and/or add sibling specs against the docker cluster. The `InstanceConfigureFixture` already provisions a HiLo alarm (`AlarmName="HiHi"`, hi:80, hiHi:95); all data-test hooks exist (`alarm-override-row-{name}`, `alarm-edit-btn`, `alarm-priority-input`, `alarm-save-override`, `alarm-override-badge`, `alarm-clear-btn`). Scenarios: HiLo setpoint edit (merge semantics), non-HiLo whole-replace, a validation error, modal cancel (no change), clear-from-modal.
|
||||
|
||||
## Build order & waves
|
||||
|
||||
The modal host is foundational — it's the single home for T34's tokenized backdrop and T36's focus trap — so it goes first; everything else is independent and fans out.
|
||||
|
||||
1. **Wave 1 (foundation + independent kickoff):** `T33a` (modal host) ∥ `T34-spike` ∥ `T41`.
|
||||
2. **Wave 2 (build on host / spike):** `T33b` (migrate dialogs) ∥ `T34a` (token layer + backdrop tokenization) ∥ `T35a` (OffsetPager) ∥ `T35b` (KeysetPager) ∥ `T35c` (DateTimeRangeFilter).
|
||||
3. **Wave 3 (theme + a11y):** `T34b` (dark toggle, gated by spike) ∥ `T36a` (aria audit + toast verify).
|
||||
4. **Wave 4:** `INT` — full-solution build, docker rebuild, full Playwright run (incl. T41), a11y smoke, docs sync, whole-branch integration review.
|
||||
|
||||
### Classifications
|
||||
| Task | Class |
|
||||
|---|---|
|
||||
| T33a (modal host — shared UI infra, focus trap) | **high-risk** |
|
||||
| T33b (migrate dialogs) | standard |
|
||||
| T34-spike (Theme dark verification) | small |
|
||||
| T34a (token layer + backdrop tokenize + bg-* audit) | standard |
|
||||
| T34b (dark toggle + persistence + SSR hydration) | **high-risk** |
|
||||
| T35a (OffsetPager) | standard |
|
||||
| T35b (KeysetPager) | standard |
|
||||
| T35c (DateTimeRangeFilter) | standard |
|
||||
| T36a (aria audit + toast verify) | standard |
|
||||
| T41 (alarm-override Playwright extension) | standard |
|
||||
| INT | **high-risk** |
|
||||
|
||||
## Testing
|
||||
- **bUnit**: modal host (`ShowAsync` round-trip, focus trap, backdrop token, Escape/click-outside cancel); each pager (offset paging math, keyset cursor stack push/pop, date-range UTC conversion); each migrated dialog keeps its existing fixture green.
|
||||
- **Component a11y**: aria-name assertions in the relevant component tests; toast `aria-live` assertion.
|
||||
- **Dark toggle**: persistence + hydration unit/interop test.
|
||||
- **T41**: live Playwright against the docker cluster (`localhost:9000` / `ws://localhost:3000`).
|
||||
- **INT**: full solution build (`dotnet build ZB.MOM.WW.ScadaBridge.slnx`, `TreatWarningsAsErrors`), EF model-drift check, every touched test project unfiltered, docker rebuild (`bash docker/deploy.sh`) + `/health/ready` smoke, full Playwright run.
|
||||
|
||||
## Key risks
|
||||
1. **External `ZB.MOM.WW.Theme` dark support (biggest unknown).** The package owns the side-rail shell. If it ignores `data-bs-theme`, the toggle darkens Bootstrap content but leaves the rail light — a broken half-dark UI. **Mitigation:** `T34-spike` runs first and gates T34a/T34b; if the shell can't go dark, surface it and decide (tokens-only ship, or coordinate a Theme-package change) before building the toggle.
|
||||
2. **Shared report-page files** (NotificationReport / SiteCalls / ConfigAudit are each touched by both a pager extraction and the date-range filter) → serialize those edits in the plan to avoid concurrent-edit collisions.
|
||||
3. **Modal host is shared infra.** Migrating dialogs onto it must preserve each dialog's behavior and keep its existing tests green — a regression here hits multiple pages. The whole-branch integration reviewer must re-run every migrated dialog's fixture.
|
||||
4. **No new NuGet packages** (central package management) and **no third-party Blazor component frameworks** — the dark toggle, token layer, and pagers are all custom (consistent with the existing custom-component rule). The `KpiTrendChart` custom-SVG precedent confirms this is the house style.
|
||||
|
||||
## Constraints (project standing rules)
|
||||
- Work in this dedicated worktree, never the primary checkout; pathspec commits only (`git commit -m "msg" -- <paths>`); ≤2–3 concurrent committers + post-wave HEAD-presence checks.
|
||||
- Targeted tests/builds per task; full-solution build + docker rebuild + Playwright only at INT.
|
||||
- `.razor`/`.cs` edits follow the surrounding Blazor + Bootstrap idiom; no third-party component frameworks; no new NuGet packages.
|
||||
@@ -0,0 +1,473 @@
|
||||
# M10 — UI/UX Platform Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development to implement this plan task-by-task.
|
||||
|
||||
**Status: DELIVERED — 2026-06-18.** All five tasks shipped: `DialogService.ShowAsync<T>` custom-content modal host with focus-trap/restore (T33); dark-mode CSS-variable token layer + localStorage toggle + SSR no-flash (T34); `OffsetPager`/`KeysetPager`/`DateTimeRangeFilter` presentational components adopted across five pages (T35); TreeView chevron a11y + regression tests (T36); Playwright alarm-override trigger-config scenarios (T41). This is the final milestone of the system-completion roadmap.
|
||||
|
||||
**Goal:** Consolidate Central UI cross-cutting presentation into reusable primitives — a custom-content modal host, a dark-mode token layer, extracted pager/filter components — plus a bounded a11y pass and Playwright coverage for the alarm-override trigger-config UI. No new functional surfaces.
|
||||
|
||||
**Architecture:** Extend the existing `DialogHost`/`DialogService` with a generic `ShowAsync<TResult>` overload that owns focus-trap + focus-restoration + a single tokenized backdrop, then migrate the 5 simple ad-hoc dialogs onto it. Add a CSS-variable dark token layer in `site.css` (loads after the compiled `ZB.MOM.WW.Theme` `theme.css`, overriding its light-only `:root` tokens under `[data-bs-theme="dark"]`) plus a `localStorage`-backed toggle. Extract three **purely presentational** components (`OffsetPager`, `KeysetPager`, `DateTimeRangeFilter`) — navigation/cursor/UTC logic stays page-side — and adopt them per-page so each shared file is owned by exactly one task.
|
||||
|
||||
**Tech Stack:** Blazor Server (.NET 10, `TreatWarningsAsErrors`), Bootstrap 5.3.3 (`data-bs-theme` aware), external `ZB.MOM.WW.Theme` 0.3.1 (compiled NuGet — no source), bUnit + xUnit, Microsoft.Playwright C#. No new NuGet packages; no third-party Blazor component frameworks.
|
||||
|
||||
**Base:** branch `worktree-m10-uiux-platform` off `origin/main` @ `ba335519`. Design: `docs/plans/2026-06-18-m10-uiux-platform-design.md` (committed `1a23b902`).
|
||||
|
||||
---
|
||||
|
||||
## Execution rules (every task)
|
||||
|
||||
- **Worktree:** you are already in `.claude/worktrees/m10-uiux-platform`. Implementers do **NOT** create worktrees.
|
||||
- **Commits:** pathspec form only — `git commit -m "msg" -- <paths>` (`-m` BEFORE `--`). Never `git add -A`/`-a`/`.`. For new files, `git add <explicit path>` then pathspec commit. Retry on `index.lock`.
|
||||
- **Concurrency:** ≤2–3 concurrent committers per wave; post-wave HEAD-presence check (`git log --oneline` shows every wave commit; recover orphans via cherry-pick).
|
||||
- **Builds/tests:** targeted per task (build only the touched project; run the named filtered test). Full-solution build + docker rebuild + Playwright + live smoke happen **only in the INT task**.
|
||||
- **File ownership:** the `Files:` block is the contract. Each shared file is owned by exactly one task per wave. If you need a file not listed, STOP — it's a plan defect; surface it.
|
||||
|
||||
## Wave / dependency map
|
||||
|
||||
| Wave | Tasks (native IDs assigned at creation) |
|
||||
|---|---|
|
||||
| 1 | T33a (modal host) ∥ T34-spike ∥ T41 |
|
||||
| 2 | T33b (migrate dialogs, ⟵T33a) ∥ T34a (token layer, ⟵spike) ∥ T35a (OffsetPager) ∥ T35b (KeysetPager) ∥ T35c (DateTimeRangeFilter) |
|
||||
| 3 | T35d (NotificationReport ⟵T35a,T35c,T34a) ∥ T35e (ConfigAudit ⟵T35a,T35c) ∥ T35f (SiteCalls ⟵T35b,T35c,T34a) ∥ T35g (AuditGrid+FilterBar ⟵T35b,T35c) ∥ T35h (EventLogs ⟵T35c) ∥ T34c (standalone backdrops ⟵T34a) |
|
||||
| 4 | T34b (dark toggle ⟵spike,T34a) ∥ T36a (aria pass) |
|
||||
| 5 | INT |
|
||||
|
||||
---
|
||||
|
||||
## Wave 1
|
||||
|
||||
### Task T33a: Modal host — `ShowAsync<TResult>` + focus trap + focus restoration + tokenized backdrop
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T34-spike, T41
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/IDialogService.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/DialogService.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/DialogHost.razor`
|
||||
- Create: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Shared/DialogHostShowAsyncTests.cs`
|
||||
|
||||
**Context:** The host today (read it) renders Confirm/Prompt only, with a Bootstrap `.modal-backdrop`, once-per-dialog focus, and Escape-to-cancel. We add a third dialog kind — **custom content** — that renders an arbitrary `RenderFragment` and resolves a typed result the body sets via a callback. This becomes the single home for the migrated dialogs (T33b), the tokenized backdrop (T34a), and the focus trap (T36/this task).
|
||||
|
||||
**Design contract:**
|
||||
- `IDialogService` gains:
|
||||
```csharp
|
||||
// Shows arbitrary content. The body fragment receives a controller it can call to
|
||||
// close the dialog with a typed result (or null = cancel). Resolves when closed.
|
||||
Task<TResult?> ShowAsync<TResult>(string title, RenderFragment<DialogContext<TResult>> body, string? size = null);
|
||||
```
|
||||
where `DialogContext<TResult>` exposes `void Close(TResult result)` and `void Cancel()`.
|
||||
- `DialogService`: add `DialogKind.Custom`; store the `RenderFragment` and the typed-close delegate on `DialogState` (widen the record additively — keep existing positional params, add optional `Content` + `Size` + a non-generic `Func<object?,bool>`/boxed TCS already present). Reuse the existing single-dialog `EnsureNoActiveDialog` guard and the boxed `_tcs`/`Resolve` plumbing (custom resolves with the boxed `TResult?`).
|
||||
- `DialogHost.razor`:
|
||||
- render branch for `DialogKind.Custom` → `@state.Content(ctx)` inside `.modal-body`, with the footer suppressed (the custom body supplies its own buttons), and `modal-dialog` size class from `state.Size` (e.g. `modal-lg`).
|
||||
- **Focus trap:** add an `@onkeydown` handler that, on `Tab`/`Shift+Tab`, keeps focus within `_modalRef` (query focusable elements via a tiny JS interop helper `sbDialog.focusTrap(modalEl, shiftKey)` OR a pure-Blazor first/last sentinel approach — prefer the JS helper added to a new `wwwroot/js/dialog.js`, registered in `App.razor` head as `<script src="_content/ZB.MOM.WW.ScadaBridge.CentralUI/js/dialog.js"></script>`). Keep Escape-cancel.
|
||||
- **Focus restoration:** before opening, capture `document.activeElement` (JS `sbDialog.captureFocus()` returns an opaque handle or stashes it); on close, `sbDialog.restoreFocus()`. Implement in `dialog.js`; call from `OnAfterRenderAsync` open/close branches.
|
||||
- **Tokenized backdrop:** change the backdrop `<div class="modal-backdrop fade show">` to also carry a class `sb-modal-backdrop` (the token rule is added in T34a; here just add the hook class — no inline rgba).
|
||||
|
||||
**Steps:**
|
||||
1. Write `DialogHostShowAsyncTests.cs` (bUnit): render `DialogHost` with a `DialogService`; call `ShowAsync<string>("T", ctx => builder => { ... button calls ctx.Close("ok") ... })`; assert the custom body renders, the footer is absent, clicking the body's close button resolves the awaited task to `"ok"`, and Escape resolves to `null`. Add an assertion that the backdrop element carries class `sb-modal-backdrop`. Run → FAIL (API absent).
|
||||
2. Add `DialogContext<TResult>`, the `ShowAsync<TResult>` interface method + `DialogService` implementation (new `DialogKind.Custom`, additive `DialogState` fields).
|
||||
3. Add the `DialogKind.Custom` render branch + size class + `sb-modal-backdrop` class in `DialogHost.razor`.
|
||||
4. Create `wwwroot/js/dialog.js` (`focusTrap`, `captureFocus`, `restoreFocus`); wire the keydown trap + capture/restore in `DialogHost`; add the `<script>` include to `Host/Components/App.razor` head.
|
||||
5. Run the new test + the full CentralUI.Tests dialog suite → PASS.
|
||||
6. Commit: `git add` the new test + js, then `git commit -m "feat(centralui): DialogHost ShowAsync<T> custom-content + focus trap/restore + backdrop hook (T33a)" -- <files>`.
|
||||
|
||||
**Acceptance:** existing `ConfirmAsync`/`PromptAsync` behavior unchanged (their tests still green); `ShowAsync<T>` resolves typed result / null-on-cancel; focus is trapped within the modal and restored to the trigger on close; backdrop has no inline rgba.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~Dialog"`
|
||||
|
||||
---
|
||||
|
||||
### Task T34-spike: Verify `ZB.MOM.WW.Theme` dark-mode feasibility
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** T33a, T41
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/plans/2026-06-18-m10-t34-spike-findings.md`
|
||||
- Read-only: `~/.nuget/packages/zb.mom.ww.theme/0.3.1/staticwebassets/css/theme.css` and `layout.css`
|
||||
|
||||
**Context:** The dark toggle (T34b) is gated on this. The package is a compiled NuGet — we cannot edit it. Known: `theme.css` defines `--paper/--card/--ink/--accent` + `--bs-body-bg`/`--bs-body-color`/`--bs-primary` in a light-only `:root`. The viable path is overriding those tokens under `[data-bs-theme="dark"]` in our `site.css` (which loads *after* `theme.css` in `App.razor`, so equal-specificity selectors win by source order).
|
||||
|
||||
**Steps:**
|
||||
1. Read `theme.css` and `layout.css` from the nuget cache. Determine: (a) the **exact list of CSS custom properties** the side-rail / shell rules consume (`var(--paper)`, `var(--card)`, `var(--ink)`, `var(--bs-*)`, etc.) — i.e. are the rail backgrounds/text driven by tokens or hard-coded hex?; (b) whether `theme.css` already loads before `site.css` (it does, via `<ThemeHead/>` at `App.razor:10` vs `site.css` at `:12`).
|
||||
2. Write `2026-06-18-m10-t34-spike-findings.md`: VERDICT (rail tokenizes → dark feasible by token override / rail hard-codes → rail stays light, ship tokens-only + log coordination follow-up), the **concrete dark token override list** (each `--token: <dark value>` to put under `[data-bs-theme="dark"]`), and any caveats (e.g. `--accent` should stay or shift).
|
||||
3. Commit: `git add docs/plans/2026-06-18-m10-t34-spike-findings.md && git commit -m "docs(m10): T34 theme dark-mode feasibility spike findings" -- docs/plans/2026-06-18-m10-t34-spike-findings.md`.
|
||||
|
||||
**Acceptance:** findings doc states a clear VERDICT + the dark token list. **The controller surfaces the verdict to the user before dispatching T34b if it is "rail stays light".**
|
||||
|
||||
---
|
||||
|
||||
### Task T41: Alarm-override Playwright — trigger-config scenarios
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T33a, T34-spike
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/AlarmTriggerEditor.razor` (add `data-test` hooks only)
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor` (add `data-test` hooks only — do NOT touch the backdrop; T34c owns that)
|
||||
- Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests/Deployment/InstanceConfigureFixture.cs` (provision a second, non-HiLo alarm)
|
||||
- Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests/Deployment/InstanceConfigureTests.cs`
|
||||
|
||||
**Context:** The override modal (`InstanceConfigure.razor:367-428`) edits trigger config via `<AlarmTriggerEditor>` (HiLo merges setpoints; other types whole-replace) plus a priority input, an `_editingError` alert, a `Cancel` and a `Clear Override` button. `AlarmTriggerEditor.razor` has **no** `data-test` hooks; the cancel/clear/error elements in `InstanceConfigure.razor` have none either. The existing test `AlarmOverride_SetPriority_ThenClear_RoundTrips` only exercises priority. Fixture provisions one HiLo alarm (`AlarmName="HiHi"`, hi:80, hiHi:95, attr `Value`).
|
||||
|
||||
**Steps:**
|
||||
1. Add `data-test` hooks: in `AlarmTriggerEditor.razor` HiLo setpoint inputs (`alarm-hilo-hi`, `alarm-hilo-hihi`, `alarm-hilo-lo`, `alarm-hilo-lolo`) and the ValueMatch/Threshold inputs used by the non-HiLo case (e.g. `alarm-threshold-input`/`alarm-operator-select` — name per the rendered fields); in `InstanceConfigure.razor` the modal Cancel (`alarm-cancel-override`), modal Clear (`alarm-clear-from-modal`), and the `_editingError` alert (`alarm-override-error`).
|
||||
2. In `InstanceConfigureFixture.cs`, provision a second alarm of a non-HiLo type via `CliRunner.AddAlarmAsync(TemplateId, "<Name>", "<NonHiLoType>", priority:…, attribute: AttributeName, …)`; expose its name/type as fixture fields.
|
||||
3. Add Playwright scenarios in `InstanceConfigureTests.cs` (new `[SkippableFact]` methods, reuse the existing structure + `CliRunner.GetInstanceDocumentAsync` read-back + `finally`-teardown via `DeleteInstanceAlarmOverrideAsync`):
|
||||
- **HiLo setpoint edit merges:** open the HiLo row's edit modal, change a setpoint (e.g. `hi`→70) without touching `hiHi`, Save, assert toast + override badge, read-back asserts the override's effective HiLo config merged (changed `hi`, retained inherited `hiHi`).
|
||||
- **Non-HiLo whole-replace:** open the non-HiLo row, set its config, Save, read-back asserts the whole trigger config replaced.
|
||||
- **Validation error:** enter an invalid value (e.g. priority `2000` or a non-numeric setpoint), Save, assert `alarm-override-error` visible and dialog stays open (no toast, no badge).
|
||||
- **Cancel:** open edit, change a field, click `alarm-cancel-override`, assert modal closed and read-back shows no override.
|
||||
- **Clear-from-modal:** with an override present, open edit, click `alarm-clear-from-modal`, assert badge gone + read-back shows no override.
|
||||
4. Run the Playwright test class (needs the docker cluster up — if unavailable the `Skip.IfNot` short-circuits; in that case the controller runs it in INT). Commit pathspec.
|
||||
|
||||
**Acceptance:** new scenarios assert via UI **and** CLI read-back; hooks added are stable (kebab-case `data-test`); fixture teardown leaves the instance override-free. **Note:** the `InstanceConfigure.razor` backdrop tokenization is explicitly out of scope here (T34c, wave 3) — only add hooks.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests --filter "FullyQualifiedName~InstanceConfigure"` (or run in INT if no cluster).
|
||||
|
||||
---
|
||||
|
||||
## Wave 2
|
||||
|
||||
### Task T33b: Migrate the 5 simple dialogs to `ShowAsync<T>`
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T34a, T35a, T35b, T35c
|
||||
**Blocked by:** T33a
|
||||
|
||||
**Files:**
|
||||
- Delete/replace: `Components/Shared/MoveFolderDialog.razor`, `MoveTemplateDialog.razor`, `RenameFolderDialog.razor`, `ComposeIntoDialog.razor`, `MoveDataConnectionDialog.razor`
|
||||
- Modify: `Components/Pages/Design/Templates.razor` (invokes 4 of them)
|
||||
- Modify: `Components/Pages/Design/DataConnections.razor` (invokes MoveDataConnection)
|
||||
- Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Shared/MoveDataConnectionDialogTests.cs` (rework to drive via the host)
|
||||
|
||||
**Context (verbatim recon):** each of the 5 dialogs is an `@if(IsVisible)` component rendering its OWN backdrop `<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">` with `@bind-IsVisible` + an `OnSubmit`/`OnMoved` callback. Parents: `Templates.razor` shows MoveFolder (`_showMoveFolderDialog`, `OpenMoveFolderDialog`/`SubmitMoveFolder`), MoveTemplate (`_showMoveTemplateDialog`/`SubmitMoveTemplate`), RenameFolder (`_showRenameFolderDialog`/`SubmitRenameFolder`), ComposeInto (`_showComposeDialog`/`SubmitCompose`). `DataConnections.razor` shows MoveDataConnection (`_showMoveDialog`, `OpenMoveDialog`/`OnConnectionMoved`); that dialog injects `IDataConnectionMoveService` and does its async move + inline error itself.
|
||||
|
||||
**Approach:** Convert each dialog from an `@if`-rendered component into a small **content component** that exposes a `RenderFragment`-returning helper (or keep it as a component rendered as the `ShowAsync` body). Simplest, lowest-risk pattern: turn each into a reusable body component invoked from the parent via `DialogService.ShowAsync<TResult>(...)`, e.g. in `Templates.razor`:
|
||||
```csharp
|
||||
var result = await Dialog.ShowAsync<int?>("Move folder", ctx =>
|
||||
@<MoveFolderBody Options="@_folderOptions" FolderName="@name"
|
||||
OnPick="@(id => ctx.Close(id))" OnCancel="@(() => ctx.Cancel())" />);
|
||||
if (result is { } newParentId) { /* existing SubmitMoveFolder logic */ }
|
||||
```
|
||||
- The 4 simple Templates dialogs return their picked value (`int?` parent/folder, `string` new name, or a `(parentId, slot)` tuple) — keep the parent's existing validation/service-call/toast/reload logic; the dialog body only collects input.
|
||||
- MoveDataConnection keeps its async-move-with-inline-error semantics: the body component still injects `IDataConnectionMoveService` and calls `ctx.Close(true)` on success / shows inline error + stays open on guard failure. Rework `MoveDataConnectionDialogTests.cs` to render the host + drive the body (the 5 assertions: picker renders, dispatch with ids, guard error stays open, success closes+signals).
|
||||
- **Result:** the 5 inline `rgba(0,0,0,0.4)` backdrops are deleted (host owns the single backdrop). Remaining standalone backdrops are handled by T34c.
|
||||
|
||||
**Steps:** (1) rework `MoveDataConnectionDialogTests.cs` to the host-driven flow → FAIL; (2) migrate MoveDataConnection first (it has the test); make it green; (3) migrate the 4 Templates dialogs + update `Templates.razor` call sites; (4) build CentralUI + run the dialog + Templates + DataConnections test suites; (5) pathspec commit.
|
||||
|
||||
**Acceptance:** all 5 dialogs open via `ShowAsync`, no inline rgba backdrops remain in these 5 files, each dialog's observable behavior (validation, async move, error-stays-open, success-closes) is preserved, `MoveDataConnectionDialogTests` green, build clean.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~Dialog|FullyQualifiedName~Templates|FullyQualifiedName~DataConnections"`
|
||||
|
||||
---
|
||||
|
||||
### Task T34a: Dark token layer in `site.css` + `.sb-modal-backdrop`
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** T33b, T35a, T35b, T35c
|
||||
**Blocked by:** T34-spike
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/wwwroot/css/site.css`
|
||||
|
||||
**Context:** `site.css` already loads after the Theme `theme.css` (App.razor:12 vs :10), so a `[data-bs-theme="dark"]` block here overrides the package's light `:root` tokens by source order. The spike findings doc lists the exact tokens. No App.razor change (keep dark tokens in the already-linked `site.css` — do NOT add a new stylesheet/link; that avoids colliding with T34b's App.razor edits).
|
||||
|
||||
**Steps:**
|
||||
1. Add a `.sb-modal-backdrop { background: var(--sb-backdrop, rgba(0,0,0,0.4)); }` rule + a semantic token block: in `:root` define `--sb-backdrop: rgba(0,0,0,0.4);` (light); in `[data-bs-theme="dark"]` define the dark token overrides from the spike (`--paper`, `--card`, `--ink`, `--bs-body-bg`, `--bs-body-color`, `--bs-border-color`, `--sb-backdrop: rgba(0,0,0,0.6)`, etc.).
|
||||
2. Verify the existing `.modal-content` / `#reconnect-modal` rules still read sensibly in dark (they use `var(--bs-white)` — confirm or token-ize).
|
||||
3. (No test — pure CSS; visual verification deferred to INT docker smoke.) `dotnet build` the CentralUI project to confirm the static asset still bundles.
|
||||
4. Pathspec commit.
|
||||
|
||||
**Acceptance:** `site.css` defines `--sb-backdrop` (light + dark) + `.sb-modal-backdrop` + a `[data-bs-theme="dark"]` token block matching the spike list; CentralUI builds. No toggle yet (T34b applies the attribute).
|
||||
|
||||
**Test:** `dotnet build src/ZB.MOM.WW.ScadaBridge.CentralUI`
|
||||
|
||||
---
|
||||
|
||||
### Task T35a: `OffsetPager` component
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** T33b, T34a, T35b, T35c
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/OffsetPager.razor`
|
||||
- Create: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Shared/OffsetPagerTests.cs`
|
||||
|
||||
**Context:** NotificationReport + ConfigurationAuditLog share a prev/next + "Page X of Y · N total" pattern with page-side "next enabled" logic. Deployments uses windowed numbered buttons (PagerWindow) and is **out of scope**. Component is purely presentational — the page owns the page number field, the query, and the next-enabled decision.
|
||||
|
||||
**Contract:**
|
||||
```razor
|
||||
@* OffsetPager: prev/next + page summary. Page owns navigation + data fetch. *@
|
||||
@if (TotalCount is { } || ShowWhenEmpty) { ... }
|
||||
@code {
|
||||
[Parameter] public int Page { get; set; } = 1;
|
||||
[Parameter] public EventCallback<int> PageChanged { get; set; } // emits Page±1
|
||||
[Parameter] public bool HasNextPage { get; set; } // page decides
|
||||
[Parameter] public int? TotalCount { get; set; } // for "· N total"
|
||||
[Parameter] public int PageSize { get; set; } // for "of Y"
|
||||
[Parameter] public bool Disabled { get; set; }
|
||||
private bool HasPrev => Page > 1;
|
||||
private int? PageCount => (TotalCount is { } t && PageSize > 0) ? (int)Math.Ceiling(t / (double)PageSize) : null;
|
||||
}
|
||||
```
|
||||
Markup: Prev button (`disabled` when `!HasPrev || Disabled`, click → `PageChanged.InvokeAsync(Page-1)`); a label `Page @Page@(PageCount is {} pc ? $" of {pc}" : "")@(TotalCount is {} t ? $" · {t} total" : "")`; Next button (`disabled` when `!HasNextPage || Disabled`, click → `PageChanged.InvokeAsync(Page+1)`). Add `data-test="pager-prev"`/`pager-next`/`pager-summary`.
|
||||
|
||||
**Steps:** TDD — bUnit test: prev disabled at Page=1; next disabled when `HasNextPage=false`; clicking next emits `PageChanged(Page+1)`; summary text renders "Page 2 of 5 · 230 total" for Page=2,PageSize=50,TotalCount=230. Implement. Green. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~OffsetPager"`
|
||||
|
||||
---
|
||||
|
||||
### Task T35b: `KeysetPager` component
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** T33b, T34a, T35a, T35c
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/KeysetPager.razor`
|
||||
- Create: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Shared/KeysetPagerTests.cs`
|
||||
|
||||
**Context:** SiteCallsReport + AuditResultsGrid share a "Page X · Y rows" + prev/next bar where the **cursor stack lives in the page** (different cursor types: a tuple vs `AuditLogPaging`). The component is just the button bar; navigation stays page-side via callbacks.
|
||||
|
||||
**Contract:**
|
||||
```csharp
|
||||
[Parameter] public int PageNumber { get; set; } = 1;
|
||||
[Parameter] public int RowCount { get; set; }
|
||||
[Parameter] public bool CanGoBack { get; set; } // page: _cursorStack.Count > 0
|
||||
[Parameter] public bool HasNextPage { get; set; } // page: from query response
|
||||
[Parameter] public bool Disabled { get; set; } // loading
|
||||
[Parameter] public EventCallback OnPrevious { get; set; }
|
||||
[Parameter] public EventCallback OnNext { get; set; }
|
||||
```
|
||||
Markup: label `Page @PageNumber · @RowCount rows`; Prev (`disabled` when `!CanGoBack || Disabled`, click → `OnPrevious`); Next (`disabled` when `!HasNextPage || Disabled`, click → `OnNext`). `data-test="keyset-prev"`/`keyset-next`/`keyset-summary`.
|
||||
|
||||
**Steps:** TDD bUnit (prev disabled when `CanGoBack=false`; next disabled when `HasNextPage=false`; clicks fire callbacks; summary text). Implement. Green. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~KeysetPager"`
|
||||
|
||||
---
|
||||
|
||||
### Task T35c: `DateTimeRangeFilter` component
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** T33b, T34a, T35a, T35b
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/DateTimeRangeFilter.razor`
|
||||
- Create: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Shared/DateTimeRangeFilterTests.cs`
|
||||
|
||||
**Context:** ~5 pages duplicate a from/to `type="datetime-local"` pair bound to `DateTime?` (NotificationReport `_fromFilter/_toFilter`; ConfigurationAuditLog `_filterFrom/_filterTo`; SiteCallsReport `_fromFilter/_toFilter`; AuditFilterBar `audit-from/audit-to`; EventLogs `_filterFrom/_filterTo`). Pages convert to UTC **differently** (some `SpecifyKind(Local).ToUniversalTime()`, ConfigurationAuditLog via `BrowserTime.LocalInputToUtc` JS). **Therefore the component is input-only** — it emits the raw `DateTime?` (Unspecified) values; each page keeps its own UTC conversion. This is the key design decision that lets one component serve all pages without forcing a UTC strategy.
|
||||
|
||||
**Contract:**
|
||||
```csharp
|
||||
[Parameter] public DateTime? From { get; set; }
|
||||
[Parameter] public EventCallback<DateTime?> FromChanged { get; set; }
|
||||
[Parameter] public DateTime? To { get; set; }
|
||||
[Parameter] public EventCallback<DateTime?> ToChanged { get; set; }
|
||||
[Parameter] public string IdPrefix { get; set; } = "dtr"; // distinct ids per page: "no", "sc", "audit-filter", ...
|
||||
[Parameter] public string FromLabel { get; set; } = "From";
|
||||
[Parameter] public string ToLabel { get; set; } = "To";
|
||||
```
|
||||
Markup: two `<input type="datetime-local">` with `id="@(IdPrefix)-from"`/`-to`, `@bind`/`@bind:after` two-way wired to FromChanged/ToChanged, `data-test="@(IdPrefix)-from"`/`-to`. No Apply button (pages own that).
|
||||
|
||||
**Steps:** TDD bUnit (renders two datetime-local inputs with the prefixed ids; setting the from input invokes `FromChanged` with the parsed `DateTime?`). Implement. Green. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~DateTimeRangeFilter"`
|
||||
|
||||
---
|
||||
|
||||
## Wave 3
|
||||
|
||||
> Each wave-3 task owns exactly ONE page/cluster file set → all mutually parallelizable. Adoption tasks replace the page's hand-rolled pager/filter markup with the new component, **preserving the page's existing fields, query, cursor stack, and UTC conversion** (wire them to the component's params/callbacks). Keep each page's bUnit test green; update selectors only where the test asserts old pager markup.
|
||||
|
||||
### Task T35d: Adopt OffsetPager + DateTimeRangeFilter into NotificationReport (+ backdrop token)
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T35e, T35f, T35g, T35h, T34c
|
||||
**Blocked by:** T35a, T35c, T34a
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationReport.razor`
|
||||
- Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationReportPageTests.cs` (only if it asserts old pager/filter markup)
|
||||
|
||||
**Wiring:** replace the pager markup (lines ~208-221) with `<OffsetPager Page="_pageNumber" PageChanged="OnPageChanged" HasNextPage="@(_notifications.Count >= _pageSize)" TotalCount="_totalCount" PageSize="_pageSize" />` (add `OnPageChanged(int p){ _pageNumber=p; await FetchPage(); }`). Replace the from/to inputs (lines ~76-84) with `<DateTimeRangeFilter From="_fromFilter" FromChanged="v => _fromFilter=v" To="_toFilter" ToChanged="v => _toFilter=v" IdPrefix="no" />` — keep the existing `ToUtc` (lines ~677-682) on query. Replace the inline detail-modal backdrop (line 229 `rgba(0,0,0,0.4)`) with the `sb-modal-backdrop` class. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~NotificationReport"`
|
||||
|
||||
### Task T35e: Adopt OffsetPager + DateTimeRangeFilter into ConfigurationAuditLog
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T35d, T35f, T35g, T35h, T34c
|
||||
**Blocked by:** T35a, T35c
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Audit/ConfigurationAuditLog.razor`
|
||||
- Modify: its bUnit test if present (find under tests/)
|
||||
|
||||
**Wiring:** pager (lines ~177-183) → `<OffsetPager Page="_page" PageChanged="..." HasNextPage="HasMore" TotalCount="_totalCount" PageSize="_pageSize" />`; from/to (lines ~62-75) → `<DateTimeRangeFilter ... IdPrefix="audit-filter" />`, **keeping the existing `BrowserTime.LocalInputToUtc` conversion** (lines ~326-327) on query. No inline backdrop here. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~ConfigurationAuditLog"`
|
||||
|
||||
### Task T35f: Adopt KeysetPager + DateTimeRangeFilter into SiteCallsReport (+ backdrop token)
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T35d, T35e, T35g, T35h, T34c
|
||||
**Blocked by:** T35b, T35c, T34a
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/SiteCalls/SiteCallsReport.razor`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/SiteCalls/SiteCallsReport.razor.cs`
|
||||
- Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SiteCallsReportPageTests.cs` (if it asserts old pager markup)
|
||||
|
||||
**Wiring:** pager (lines ~216-234) → `<KeysetPager PageNumber="_pageNumber" RowCount="_rows.Count" CanGoBack="@(_cursorStack.Count > 0)" HasNextPage="@(_nextCursor is not null)" Disabled="_loading" OnPrevious="PrevPage" OnNext="NextPage" />` — keep the `.razor.cs` cursor-stack `PrevPage`/`NextPage`/`FetchPage` intact. From/to (lines ~76-84) → `<DateTimeRangeFilter ... IdPrefix="sc" />`, keep the `.razor.cs` `ToUtc` (lines ~482-485). Inline relay-modal backdrop (line 295 `rgba(0,0,0,0.4)`) → `sb-modal-backdrop`. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~SiteCallsReport"`
|
||||
|
||||
### Task T35g: Adopt KeysetPager into AuditResultsGrid + DateTimeRangeFilter into AuditFilterBar
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T35d, T35e, T35f, T35h, T34c
|
||||
**Blocked by:** T35b, T35c
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Audit/AuditResultsGrid.razor` + `.razor.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Audit/AuditFilterBar.razor`
|
||||
- Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Components/Audit/AuditResultsGridTests.cs` (keyset cursor test `Click_NextPage_CallsService_WithCursor_OfLastRow` must stay green — it drives next-page; ensure the new button carries the click)
|
||||
|
||||
**Wiring:** AuditResultsGrid pager (lines ~75-76) → `<KeysetPager PageNumber="_pageNumber" RowCount="_rows.Count" CanGoBack="CanGoBack" HasNextPage="@(_loading ? false : _rows.Count >= _pageSize)" Disabled="_loading" OnPrevious="PrevPage" OnNext="NextPage" />` — keep `.razor.cs` cursor logic + the error-safe prev-pop. AuditFilterBar custom-range inputs (lines ~96-105, only shown when `TimeRange == Custom`) → `<DateTimeRangeFilter ... IdPrefix="audit" />`, keep its existing binding/conversion. Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~AuditResultsGrid|FullyQualifiedName~AuditFilterBar"`
|
||||
|
||||
### Task T35h: Adopt DateTimeRangeFilter into EventLogs
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** T35d, T35e, T35f, T35g, T34c
|
||||
**Blocked by:** T35c
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/EventLogs.razor`
|
||||
- Modify: its bUnit test if present
|
||||
|
||||
**Wiring:** from/to inputs (lines ~60-73) → `<DateTimeRangeFilter From="_filterFrom" FromChanged="v=>_filterFrom=v" To="_filterTo" ToChanged="v=>_filterTo=v" IdPrefix="filter" />`, keep its existing query/conversion + continuation paging untouched (EventLogs uses continuation paging — **do not** introduce a pager component here). Commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~EventLog"`
|
||||
|
||||
### Task T34c: Tokenize remaining standalone backdrops + `bg-*` audit
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** T35d, T35e, T35f, T35g, T35h
|
||||
**Blocked by:** T34a
|
||||
|
||||
**Files:**
|
||||
- Modify: `Components/Dialogs/NodeBrowserDialog.razor` (line 9 `rgba(0,0,0,0.5)`)
|
||||
- Modify: `Components/Dialogs/TestBindingsDialog.razor` (line 7 `rgba(0,0,0,0.5)`)
|
||||
- Modify: `Components/Pages/Deployment/MoveInstanceDialog.razor`, `MoveAreaDialog.razor`, `CreateAreaDialog.razor` (line 3 each)
|
||||
- Modify: `Components/Pages/Deployment/InstanceConfigure.razor` (line 369)
|
||||
- Modify: `Components/Pages/Design/TemplateEdit.razor` (lines 697, 957, 1080, 1302)
|
||||
|
||||
**Context:** these are the standalone modal backdrops NOT migrated to the host (T33b removed the 5 simple ones; T35d/T35f tokenized NotificationReport/SiteCalls inline backdrops). Replace each inline `style="background: rgba(0,0,0,0.x);"` with `class="... sb-modal-backdrop"` (append to existing classes; drop the inline style). Spot-audit `bg-light`/`bg-white`/`bg-dark` literals in these files for obvious dark-mode contrast breaks and convert the worst offenders to Bootstrap theme-aware classes (`bg-body`, `bg-body-secondary`, `text-bg-*`) — bounded, don't chase every instance.
|
||||
|
||||
**Steps:** replace the 9 backdrops; build CentralUI; pathspec commit. **Note ordering:** InstanceConfigure.razor is also touched by T41 (wave 1, hooks) — T41 completes before this wave, so no concurrent edit.
|
||||
|
||||
**Test:** `dotnet build src/ZB.MOM.WW.ScadaBridge.CentralUI`
|
||||
|
||||
---
|
||||
|
||||
## Wave 4
|
||||
|
||||
### Task T34b: Dark-mode toggle + persistence + SSR hydration
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** T36a
|
||||
**Blocked by:** T34-spike, T34a
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/DarkModeToggle.razor`
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.CentralUI/wwwroot/js/theme.js`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Layout/MainLayout.razor` (add the toggle into `<RailFooter>`)
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Host/Components/App.razor` (pre-hydration inline script + `theme.js` include)
|
||||
|
||||
**Context (gated by spike):** if the spike verdict is "rail stays light", the controller surfaces it to the user BEFORE this task and the toggle ships content-only (or the task is deferred). Assuming feasible:
|
||||
- `theme.js`: `sbTheme.get()` (localStorage key `sb-theme`, default `light`), `sbTheme.set(mode)` (writes localStorage + `document.documentElement.setAttribute("data-bs-theme", mode)`), `sbTheme.toggle()`.
|
||||
- `App.razor` head: an **inline** `<script>` that reads `localStorage['sb-theme']` and sets `data-bs-theme` on `<html>` **before** body render (prevents the light-flash on load) — place before the CSS links is fine since it only sets the attribute. Plus a `<script src="_content/.../js/theme.js"></script>` include.
|
||||
- `DarkModeToggle.razor`: a sun/moon `<button>` (`aria-label="Toggle dark mode"`, `aria-pressed`), `@onclick` → JS `sbTheme.toggle()` then read back current mode to swap the icon. Render in the rail footer next to the sign-out form.
|
||||
|
||||
**Steps:** (1) create `theme.js` + `DarkModeToggle.razor`; (2) wire the inline hydration script + include into `App.razor`; (3) add the toggle to `MainLayout` `<RailFooter>`; (4) bUnit test the toggle renders with `aria-label`/`aria-pressed` and calls the JS module on click (mock IJSRuntime); (5) build CentralUI + Host; (6) pathspec commit. Live dark/light verification happens in INT docker smoke.
|
||||
|
||||
**Acceptance:** toggle flips `data-bs-theme` on `<html>`, persists across reload via localStorage, no light-flash on first paint (hydration script), toggle is keyboard-reachable + labeled. Confirmed visually in INT.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~DarkModeToggle"`
|
||||
|
||||
### Task T36a: Accessibility pass — TreeView chevron + icon-button audit + toast aria-live verify
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** T34b
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Shared/TreeView.razor` (chevron pseudo-button line ~54 — add `role="button"` + `aria-label`/`aria-expanded` + keyboard `@onkeydown` Enter/Space to toggle)
|
||||
- Modify: any other icon-only buttons surfaced lacking an accessible name (bounded — recon found most already labeled; do not touch wave-3-owned report pages)
|
||||
- Create/Modify: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Shared/` a11y assertion test (TreeView chevron has aria-label + role=button; assert `ToastNotification` container has `aria-live="polite"` + `aria-atomic`)
|
||||
|
||||
**Context:** recon confirmed Toast (`aria-live="polite"` + `role="alert"`), LoadingSpinner (`role="status"` + visually-hidden), and AlarmStateBadges (text + `aria-label`) are already compliant — so this task mainly adds the TreeView chevron accessible name + keyboard activation and locks the compliant state with a regression test. Keep it bounded; do NOT edit report pages owned by wave-3 tasks.
|
||||
|
||||
**Steps:** add `role="button"`, `tabindex="0"`, `aria-label` (e.g. `@(expanded ? "Collapse" : "Expand") @label`), `aria-expanded`, and Enter/Space `@onkeydown` to the TreeView toggle; add the bUnit a11y test; build + run; pathspec commit.
|
||||
|
||||
**Test:** `dotnet test tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests --filter "FullyQualifiedName~TreeView|FullyQualifiedName~Toast"`
|
||||
|
||||
---
|
||||
|
||||
## Wave 5
|
||||
|
||||
### Task INT: Integration — build, docker, Playwright, a11y smoke, docs, whole-branch review
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~10 min (controller-driven, not a single subagent)
|
||||
|
||||
**Steps:**
|
||||
1. **Full-solution build:** `dotnet build ZB.MOM.WW.ScadaBridge.slnx` — must be 0 warnings / 0 errors (`TreatWarningsAsErrors`).
|
||||
2. **EF model-drift check:** `dotnet ef migrations has-pending-model-changes` (M10 adds no entities/migrations — confirm none introduced).
|
||||
3. **Touched test projects, unfiltered:** run `ZB.MOM.WW.ScadaBridge.CentralUI.Tests` in full. Prove any red is pre-existing per [[integration-catches-cross-cutting-gaps]] (`git diff --stat ba335519..HEAD -- <failing test's target files>` empty ⇒ pre-existing; known pre-existing reds: #163 InstanceConfigureListOverrideTests, #207 QueryStringDrillInTests).
|
||||
4. **Docker rebuild + smoke:** `bash docker/deploy.sh`; verify `/health/ready` 200 on central-a/b + traefik (`localhost:9001/9002/9000`).
|
||||
5. **Playwright (incl. T41):** run `ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests` against the live cluster — alarm-override scenarios + a smoke of the migrated dialogs + the dark toggle.
|
||||
6. **a11y + dark smoke (Chrome):** load the UI, toggle dark mode, confirm the side-rail + content + a migrated dialog all go dark with no light-flash and readable contrast; tab into a dialog and confirm focus is trapped + restored.
|
||||
7. **Whole-branch integration review:** dispatch a code-reviewer over `git diff ba335519..HEAD` focused on: every migrated dialog's behavior preserved (re-run their fixtures), the modal host shared-infra change not regressing any page, the dark token override actually winning over the Theme package, and no inline rgba backdrops left except intentional ones.
|
||||
8. **Docs sync:** update `README.md` (component table / Central UI notes if needed), the M10 design doc status, and `docs/plans/2026-06-15-stillpending-completion-design.md` (mark M10 / T33-T36,T41 delivered). Log any deferrals as FOLLOWUP tasks (e.g. Deployments-PagerWindow not unified; complex TemplateEdit modals not migrated; TreeView arrow-key R7 still deferred; Theme-package shell-theming coordination if spike said rail stays light).
|
||||
9. Pathspec commit the docs.
|
||||
|
||||
**Acceptance:** full build 0/0; CentralUI.Tests green modulo proven-pre-existing reds; docker healthy; Playwright green; dark mode + focus trap verified live; integration review INTEGRATION-CLEAN; docs synced.
|
||||
|
||||
---
|
||||
|
||||
## Deferred / out of scope (log as FOLLOWUPs at INT)
|
||||
- Unified offset+keyset pagination framework (blocked by total-count mismatch).
|
||||
- `Deployments.razor` PagerWindow → OffsetPager (different windowed UX; intentionally left).
|
||||
- Complex `TemplateEdit` page-embedded modals → host migration.
|
||||
- TreeView arrow-key navigation (R7).
|
||||
- Theme-package side-rail dark theming, IF the spike verdict is "rail stays light" (coordination follow-up).
|
||||
|
||||
## Follow-ups logged at delivery (INT findings)
|
||||
- **#207 (pre-existing, open since M6/K14):** `QueryStringDrillInTests` fixture does not register `IKpiHistoryQueryService` — 3 `SiteCallsReport` drill-in tests red on this gap; unrelated to M10.
|
||||
- **#163 (pre-existing):** `InstanceConfigureListOverrideTests` codec roundtrip red; pre-dates M10.
|
||||
- **NotificationReport `OffsetPager` always-visible:** pager is now always visible when results exist (previously hidden on sub-page-size sets); buttons are correctly disabled on a single page — product decision whether to re-add an `@if (_totalCount > _pageSize)` guard.
|
||||
- **`Deployments.razor` PagerWindow intentionally kept:** windowed numbered-button UX is deliberate; NOT migrated to `OffsetPager`.
|
||||
- **`TemplateEdit` inline modals NOT migrated:** the page-embedded modals (wave-3 T34c already tokenized their backdrops); full migration to the host is deferred.
|
||||
- **TreeView full arrow-key navigation (R7) still deferred.**
|
||||
- **Full-app `bg-light`/`bg-white` → theme-aware utility sweep deferred:** only the bounded modal-surface offenders were addressed in T34c; INT dark-mode smoke may surface additional instances.
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"planPath": "docs/plans/2026-06-18-m10-uiux-platform.md",
|
||||
"tasks": [
|
||||
{"id": 269, "subject": "M10-T33a: Modal host ShowAsync<T> + focus trap/restore + backdrop hook", "status": "pending"},
|
||||
{"id": 270, "subject": "M10-T34-spike: Verify ZB.MOM.WW.Theme dark-mode feasibility", "status": "pending"},
|
||||
{"id": 271, "subject": "M10-T41: Alarm-override Playwright trigger-config scenarios", "status": "pending"},
|
||||
{"id": 272, "subject": "M10-T33b: Migrate 5 simple dialogs to ShowAsync<T>", "status": "pending", "blockedBy": [269]},
|
||||
{"id": 273, "subject": "M10-T34a: Dark token layer in site.css + .sb-modal-backdrop", "status": "pending", "blockedBy": [270]},
|
||||
{"id": 274, "subject": "M10-T35a: OffsetPager component", "status": "pending"},
|
||||
{"id": 275, "subject": "M10-T35b: KeysetPager component", "status": "pending"},
|
||||
{"id": 276, "subject": "M10-T35c: DateTimeRangeFilter component", "status": "pending"},
|
||||
{"id": 277, "subject": "M10-T35d: Adopt OffsetPager+DateTimeRangeFilter into NotificationReport (+backdrop token)", "status": "pending", "blockedBy": [274, 276, 273]},
|
||||
{"id": 278, "subject": "M10-T35e: Adopt OffsetPager+DateTimeRangeFilter into ConfigurationAuditLog", "status": "pending", "blockedBy": [274, 276]},
|
||||
{"id": 279, "subject": "M10-T35f: Adopt KeysetPager+DateTimeRangeFilter into SiteCallsReport (+backdrop token)", "status": "pending", "blockedBy": [275, 276, 273]},
|
||||
{"id": 280, "subject": "M10-T35g: Adopt KeysetPager into AuditResultsGrid + DateTimeRangeFilter into AuditFilterBar", "status": "pending", "blockedBy": [275, 276]},
|
||||
{"id": 281, "subject": "M10-T35h: Adopt DateTimeRangeFilter into EventLogs", "status": "pending", "blockedBy": [276]},
|
||||
{"id": 282, "subject": "M10-T34c: Tokenize remaining standalone backdrops + bg-* audit", "status": "pending", "blockedBy": [273]},
|
||||
{"id": 283, "subject": "M10-T34b: Dark-mode toggle + persistence + SSR hydration", "status": "pending", "blockedBy": [270, 273]},
|
||||
{"id": 284, "subject": "M10-T36a: Accessibility pass — TreeView chevron + icon audit + toast verify", "status": "pending"},
|
||||
{"id": 285, "subject": "M10-INT: Integration — build, docker, Playwright, a11y+dark smoke, docs, review", "status": "pending", "blockedBy": [271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284]}
|
||||
],
|
||||
"lastUpdated": "2026-06-18"
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
# SMS Notifications (T9 pivot + T10) — Design
|
||||
|
||||
**Date:** 2026-06-19
|
||||
**Status:** Approved (full scope) — proceed to implementation plan.
|
||||
**Supersedes:** the T9 "Teams delivery adapter" direction. T9/T10 were deferred to "next major version" in M6 (`docs/plans/2026-06-17-m6-kpi-history-design.md`). This design pulls them forward and **pivots the second delivery channel from Microsoft Teams to SMS (Twilio)**.
|
||||
|
||||
---
|
||||
|
||||
## Goal
|
||||
|
||||
Add `NotificationType.Sms` and a Twilio-REST `SmsNotificationDeliveryAdapter` behind the existing `INotificationDeliveryAdapter` seam, plus the T10 enum/UI/CLI plumbing, so notification lists can deliver to ZB team members by text message. Email delivery is unchanged.
|
||||
|
||||
## Why the pivot (Teams → SMS)
|
||||
|
||||
The user's requirement is "notify ZB team members individually." Investigation of the current Microsoft Graph / Teams platform (2025–2026) established a hard architectural constraint:
|
||||
|
||||
- An **outbound-only** backend (our on-prem central cluster, which already does OAuth2 client-credentials to `login.microsoftonline.com` for SMTP) **cannot** send a full 1:1 chat-message body to a person via Graph. App-only chat sending is migration-only; real-time chat sending is delegated-user-only.
|
||||
- A full-body per-person Teams DM requires a **Bot Framework bot with a publicly-reachable *inbound* HTTPS endpoint** that Azure Bot Service calls into the datacenter — a significant security/deployment change for an on-prem SCADA system.
|
||||
- The only purely-outbound per-person Teams mechanism (`sendActivityNotification`) delivers a ~150-char headline + deep link, not a message body, and requires a published Teams app installed per recipient.
|
||||
|
||||
SMS sidesteps all of that: it is inherently per-person (recipient = phone number), carries a full message body, and is **outbound-only** (a single HTTPS POST to the provider). It is the natural "second delivery type" that makes the T10 Type selector meaningful.
|
||||
|
||||
**Provider decision:** Twilio, called directly over its REST API (no SDK), honoring the project's no-new-NuGet-package rule (central package management). `Microsoft.Extensions.Http` is already in central package management (used by NotificationService/ExternalSystemGateway); the NotificationOutbox project gains a `<PackageReference>` to it — no new package version is introduced.
|
||||
|
||||
## Architecture
|
||||
|
||||
Mirror the existing Email/SMTP stack:
|
||||
|
||||
- A notification list's existing `NotificationList.Type` field decides the channel.
|
||||
- `Notify.To("list")` / `Notify.Send` stay type-agnostic at the site.
|
||||
- Central resolves the **list's Type at ingest** and stamps it on the `Notification` row; the outbox actor already dispatches via `Dictionary<NotificationType, INotificationDeliveryAdapter>` and parks on a missing adapter, so routing is automatic.
|
||||
|
||||
## Tech stack
|
||||
|
||||
C#/.NET 10, Akka.NET, EF Core (MS SQL central), Blazor Server (Central UI), System.CommandLine (CLI), `IHttpClientFactory`, ASP.NET Data Protection (`EncryptedStringConverter`) for secret-at-rest. No new NuGet packages.
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
### D1 — Delivery adapter (Twilio REST)
|
||||
- New `SmsNotificationDeliveryAdapter : INotificationDeliveryAdapter` (`Type => NotificationType.Sms`) in `NotificationOutbox/Delivery`, registered alongside the Email adapter in `ServiceCollectionExtensions`.
|
||||
- Request: `POST {ApiBaseUrl}/2010-04-01/Accounts/{AccountSid}/Messages.json`, HTTP Basic auth (`AccountSid:AuthToken`), `application/x-www-form-urlencoded` body `To` / `From` (or `MessagingServiceSid`) / `Body`. Named `HttpClient` `"Twilio"` via `IHttpClientFactory`.
|
||||
- Success = Twilio 2xx (message accepted/queued). Note: true *delivery* confirmation needs a status-callback webhook (inbound) — out of scope; "accepted by Twilio" is treated as Delivered, exactly as the Email adapter treats "accepted by the SMTP server."
|
||||
|
||||
### D2 — Secret-at-rest (`SmsConfiguration` entity)
|
||||
- New `SmsConfiguration` entity, provider-neutral name, mirroring `SmtpConfiguration`:
|
||||
- `Id`, `AccountSid` (plaintext — also appears in the URL path), `AuthToken` (**encrypted** via `EncryptedStringConverter`), `FromNumber` (E.164) and/or optional `MessagingServiceSid`, optional `ApiBaseUrl` (default `https://api.twilio.com`; lets tests point at a fake handler / supports regional), `ConnectionTimeoutSeconds`, `MaxRetries`, `RetryDelay`.
|
||||
- EF: add `AuthToken` to `ScadaBridgeDbContext.ApplySecretColumnEncryption`. Idempotent migration adds the table.
|
||||
- `CredentialRedactor.Scrub(message, authToken)` removes the AuthToken from any logged error.
|
||||
|
||||
### D3 — Recipient model (per-list typing)
|
||||
- A list is entirely Email **or** entirely SMS (single `NotificationList.Type`).
|
||||
- `NotificationRecipient` gains a nullable `PhoneNumber` (E.164, e.g. nvarchar(32)); `EmailAddress` is relaxed to **nullable** (currently NOT NULL). Email-list recipients carry `EmailAddress`; SMS-list recipients carry `PhoneNumber`.
|
||||
- Type-aware validation: SMS recipients require a valid E.164 `PhoneNumber`; Email recipients require a valid `EmailAddress`.
|
||||
- Constructor/factory: keep `NotificationRecipient(name, email)`; add an SMS construction path (factory `NotificationRecipient.ForSms(name, phone)` / `ForEmail(name, email)` or object-initializer support).
|
||||
- Migration: additive nullable `PhoneNumber` column + one NOT-NULL→NULL relaxation on `EmailAddress`. Idempotent.
|
||||
|
||||
### D4 — Message format
|
||||
- SMS has no subject. Body = `Subject` + newline + `Body` (whichever present), plain text, truncated to a configurable cap (`SmsOptions.MaxMessageLength`, default 1600 = Twilio max) with an ellipsis when over.
|
||||
- Doc caveat: Twilio segments at 160 GSM-7 chars and bills per segment.
|
||||
|
||||
### D5 — Error classification
|
||||
- Small local `SmsErrorClassifier` in `NotificationOutbox/Delivery`, mirroring the pattern of `SmtpErrorClassifier` (no cross-project reference to ExternalSystemGateway):
|
||||
- **Transient:** HTTP 5xx, 408, 429; `HttpRequestException`, `TaskCanceledException`/timeout (non-caller-cancel).
|
||||
- **Permanent:** other 4xx (incl. 401/403 bad creds, 400 invalid/unsubscribed number).
|
||||
|
||||
### D6 — Per-recipient rollup (no SMS BCC → one POST per number)
|
||||
- Send one Twilio request per recipient; classify each.
|
||||
- **All accepted →** `Success` (`ResolvedTargets` = the numbers).
|
||||
- **Any transient →** `Transient` (the whole notification retries at the fixed interval, then Parks after max-retries). *Accepted caveat:* numbers already accepted on a prior attempt get re-texted on retry — the same "re-send to all" characteristic the Email adapter already has with BCC. (v1 does NOT track per-recipient state; that is a documented future enhancement.)
|
||||
- **No transient, mix of accepted + permanent-bad →** `Success` to the good numbers; permanently-bad numbers recorded in `LastError`. Do not park if anything got through.
|
||||
- **All permanent / no recipients / no SMS config / list-not-found →** `Permanent` (Park).
|
||||
|
||||
### D7 — Ingest type-stamping
|
||||
- At `NotificationOutboxActor` ingest (currently hard-codes `NotificationType.Email`, ~line 1147), resolve the target list by `ListName` and stamp the Notification's `Type` from the **list's** Type (default Email if the list is not found — delivery parks on "list not found" regardless). Keeps `Notify.To` type-agnostic.
|
||||
|
||||
### D8 — T10 UI/CLI plumbing
|
||||
- `NotificationType.Sms` added to the enum.
|
||||
- `Create/UpdateNotificationListCommand` gain `NotificationType Type` (additive, default Email); handlers persist it.
|
||||
- CLI: `notification list create/update --type email|sms`, with `--emails` (email lists) / `--phones` (sms lists).
|
||||
- Central UI `NotificationListForm`: an **adapter-gated** Type selector — it offers only `NotificationType` values that have a registered `INotificationDeliveryAdapter` (Email + SMS today; auto-extends if more are added). The recipient input switches email↔phone by the selected type with appropriate validation.
|
||||
- Type is chosen at **create** and is **fixed on edit** (prevents email/phone recipient mismatch within a list).
|
||||
- `NotificationLists` list page gains a **Type** column.
|
||||
- New SMS-config management mirroring SMTP: `ListSmsConfigsCommand` / `UpdateSmsConfigCommand` (+ `HandleListSmsConfigs` / `HandleUpdateSmsConfig`, role-gated like SMTP, audited via a credential-free public shape), CLI `notification sms list|update`, Admin-only Central UI page `/notifications/sms`.
|
||||
|
||||
### D9 — Transport
|
||||
- `NotificationRecipientDto` gains a nullable `PhoneNumber` (backward-compatible: omitted = null).
|
||||
- New `SmsConfigDto` (secret rides the existing `SecretsBlock`), mirroring `SmtpConfigDto`, carried in `BundleContentDto` / `EntityAggregate` and round-tripped by `EntitySerializer`.
|
||||
|
||||
---
|
||||
|
||||
## Blast radius (file-level)
|
||||
|
||||
**Commons**
|
||||
- `Types/Enums/NotificationType.cs` — add `Sms`.
|
||||
- `Entities/Notifications/NotificationRecipient.cs` — add `PhoneNumber`; SMS construction path.
|
||||
- `Entities/Notifications/SmsConfiguration.cs` — **new**.
|
||||
- `Messages/Management/NotificationCommands.cs` — add `Type` to Create/Update list commands; add `ListSmsConfigsCommand` / `UpdateSmsConfigCommand`.
|
||||
- `Interfaces/Repositories/INotificationRepository.cs` — add SMS-config read/write methods (mirror SMTP).
|
||||
|
||||
**Configuration Database**
|
||||
- `Configurations/NotificationConfiguration.cs` — `EmailAddress` nullable, `PhoneNumber` mapping; `SmsConfiguration` mapping.
|
||||
- `ScadaBridgeDbContext.cs` — `ApplySecretColumnEncryption` adds `SmsConfiguration.AuthToken`; `DbSet<SmsConfiguration>`.
|
||||
- Repository impl — SMS-config methods.
|
||||
- New idempotent EF migration (PhoneNumber + EmailAddress-nullable + SmsConfiguration table).
|
||||
|
||||
**NotificationOutbox**
|
||||
- `Delivery/SmsNotificationDeliveryAdapter.cs` — **new**.
|
||||
- `Delivery/SmsErrorClassifier.cs` — **new**.
|
||||
- `ServiceCollectionExtensions.cs` — register SMS adapter + named `"Twilio"` HttpClient.
|
||||
- `NotificationOutboxActor.cs` — ingest type-stamping (D7).
|
||||
- `*.csproj` — add `Microsoft.Extensions.Http` PackageReference (already centrally managed).
|
||||
- `SmsOptions` (`ScadaBridge:Sms`) — timeout / max-length (retry reuses outbox settings where possible).
|
||||
|
||||
**Management Service**
|
||||
- `ManagementActor.cs` — `HandleListSmsConfigs` / `HandleUpdateSmsConfig` (+ role gating + audit public shape); list-command handlers persist `Type`.
|
||||
|
||||
**CLI**
|
||||
- `Commands/NotificationCommands.cs` — `--type` + `--phones` on list create/update; `notification sms list|update` group.
|
||||
- CLI `README.md`.
|
||||
|
||||
**Central UI**
|
||||
- `Components/Pages/Notifications/NotificationListForm.razor` — Type selector (adapter-gated) + per-type recipient input.
|
||||
- `Components/Pages/Notifications/NotificationLists.razor` — Type column.
|
||||
- `Components/Pages/Notifications/SmsConfiguration.razor` — **new** (`/notifications/sms`, mirror SMTP page).
|
||||
- Nav entry for the SMS config page.
|
||||
|
||||
**Transport**
|
||||
- `Serialization/EntityDtos.cs` — `PhoneNumber` on recipient DTO; `SmsConfigDto`.
|
||||
- `Serialization/EntitySerializer.cs` — map SMS config + recipient phone both directions.
|
||||
- `BundleContentDto` / `EntityAggregate` — include SMS configs.
|
||||
|
||||
**Tests** (break / add)
|
||||
- **Update** `NotificationOutbox.Tests/ServiceRegistrationTests.cs` — `Assert.Single(adapters)` → assert Email **and** SMS registered.
|
||||
- New `SmsNotificationDeliveryAdapter` unit tests (fake `HttpMessageHandler`: 201 / 5xx / 429 / timeout / 400 / 401 / rollup / redaction).
|
||||
- Ingest type-stamping test.
|
||||
- CLI tests (`--type`, `--phones`, `sms` group).
|
||||
- bUnit: Type selector (adapter-gated), per-type recipient editor, Type column.
|
||||
- EF/migration config tests.
|
||||
- Playwright: SMS-list create flow (INT).
|
||||
|
||||
**Docs / deploy**
|
||||
- `docs/requirements/Component-NotificationService.md`, `Component-NotificationOutbox.md`.
|
||||
- `CLAUDE.md` decision notes (NotificationType = Email+Sms; **T9/T10 delivered as SMS, not deferred**; flip the M6 deferral note).
|
||||
- `README.md` component table / CLI README as needed.
|
||||
- Docker: no new secret (SMS config lives in DB like SMTP); minimal `ScadaBridge:Sms` options.
|
||||
|
||||
---
|
||||
|
||||
## Out of scope / deferred (logged, not built)
|
||||
- Per-recipient delivery-state tracking to avoid duplicate texts on retry (v1 uses unit-retry, matching Email-BCC; see D6).
|
||||
- Twilio status-callback (inbound) webhook for true delivery confirmation.
|
||||
- Microsoft Teams delivery (dropped).
|
||||
- Mixed email+phone single list (per-list typing only).
|
||||
- Editable list Type after creation.
|
||||
|
||||
## Execution
|
||||
- Dedicated worktree `feat/sms-notifications` off `main` (`c72d7b79`); pathspec commits (`-m` before `--`, never `git add -A`); targeted builds/tests per task; full-solution build + docker rebuild + Playwright + live smoke at INT; then `finishing-a-development-branch` (merge-to-local-main per established pattern — push only on explicit confirmation).
|
||||
- Plan + `.tasks.json` co-located in `docs/plans/`. Subagent-driven execution (classification-driven review chains).
|
||||
@@ -0,0 +1,280 @@
|
||||
# SMS Notifications (T9 pivot + T10) Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Add `NotificationType.Sms` + a Twilio-REST `SmsNotificationDeliveryAdapter` behind the existing `INotificationDeliveryAdapter` seam, plus the T10 enum/UI/CLI Type-selector plumbing, so notification lists can deliver to ZB team members by SMS. Email is unchanged.
|
||||
|
||||
**Architecture:** Mirror the Email/SMTP stack. A list's existing `NotificationList.Type` decides the channel; `Notify.To` stays type-agnostic; central stamps the Notification's Type from the list at ingest; the outbox actor already routes `Dictionary<NotificationType, adapter>` and parks on a missing adapter. Twilio called directly over REST (no SDK). Secrets encrypted via the existing Data-Protection `EncryptedStringConverter`.
|
||||
|
||||
**Tech Stack:** C#/.NET 10, Akka.NET, EF Core (MS SQL), Blazor Server, System.CommandLine, `IHttpClientFactory`, ASP.NET Data Protection. **No new NuGet packages** (`Microsoft.Extensions.Http` is already centrally managed).
|
||||
|
||||
**Design doc:** `docs/plans/2026-06-19-sms-notifications-design.md` (committed 28cab6e8).
|
||||
|
||||
**Execution rules:** dedicated worktree `feat/sms-notifications` off `main` `c72d7b79`. Implementers do NOT create worktrees. Pathspec commits only (`git commit -m "msg" -- <paths>`, `-m` before `--`, never `git add -A`; `git add <explicit path>` for new files; retry on index.lock). ≤2-3 concurrent committers per wave + post-wave HEAD-presence check (`git merge-base --is-ancestor <sha> HEAD`). Targeted builds/tests per task; full-solution build + docker rebuild + Playwright + live smoke only at INT (S11). TreatWarningsAsErrors=true.
|
||||
|
||||
---
|
||||
|
||||
## Wave / dependency map
|
||||
|
||||
- **Wave 1:** S1 (Commons foundation) — blocks all.
|
||||
- **Wave 2:** S2 (Config-DB migration) ∥ S5 (Management commands+handlers). Both ⟵ S1.
|
||||
- **Wave 3:** S3 (adapter) ⟵ S1,S2 ∥ S4 (ingest stamping) ⟵ S1 ∥ S6 (CLI) ⟵ S5.
|
||||
- **Wave 4:** S7 (list form) ∥ S8 (list page Type column) ∥ S9 (SMS config page) ∥ S10 (Transport). All ⟵ S1/S5 (S9,S10 also ⟵ S2). Cap at 3 concurrent; queue the 4th.
|
||||
- **Wave 5:** S11 (INT) ⟵ all.
|
||||
|
||||
---
|
||||
|
||||
### Task S1: Commons foundation — NotificationType.Sms, recipient phone, SmsConfiguration entity, repo interface
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** none (foundational)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Commons/Types/Enums/NotificationType.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Notifications/NotificationRecipient.cs`
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.Commons/Entities/Notifications/SmsConfiguration.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/INotificationRepository.cs`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/` (add a recipient-factory + SmsConfiguration shape test if a suitable test class exists; else a small new test file)
|
||||
|
||||
**Steps:**
|
||||
1. Add `Sms` to `NotificationType` (after `Email`). Update the enum's XML doc to "Email and SMS supported." NOTE: `Commons.Tests` may have an enum-count assertion — if so, update it (this is the known enum-count-drift pattern).
|
||||
2. `NotificationRecipient`: add `public string? PhoneNumber { get; set; }`; relax `EmailAddress` to `string?`. Keep the existing `NotificationRecipient(string name, string emailAddress)` ctor (email path). Add static factories `ForEmail(string name, string email)` and `ForSms(string name, string phoneNumber)` (set the appropriate field, leave the other null; validate name non-empty). Keep a parameterless-friendly path for EF.
|
||||
3. Create `SmsConfiguration` POCO (persistence-ignorant): `int Id`, `string AccountSid`, `string? AuthToken`, `string FromNumber`, `string? MessagingServiceSid`, `string? ApiBaseUrl`, `int ConnectionTimeoutSeconds`, `int MaxRetries`, `TimeSpan RetryDelay`. Mirror `SmtpConfiguration` constructor/validation style.
|
||||
4. `INotificationRepository`: add `Task<SmsConfiguration?> GetSmsConfigurationAsync(CancellationToken=default)`, `Task<IReadOnlyList<SmsConfiguration>> GetAllSmsConfigurationsAsync(CancellationToken=default)`, `Task AddSmsConfigurationAsync(SmsConfiguration, CancellationToken=default)`, `Task UpdateSmsConfigurationAsync(SmsConfiguration, CancellationToken=default)` (match the SMTP method shapes already present).
|
||||
5. Build `dotnet build src/ZB.MOM.WW.ScadaBridge.Commons/...`; run any touched Commons tests.
|
||||
6. Commit (pathspec; `git add` the new SmsConfiguration.cs).
|
||||
|
||||
**Acceptance:** Commons builds 0/0; `NotificationType.Sms` exists; recipient carries nullable phone + factories; `SmsConfiguration` + repo methods defined.
|
||||
|
||||
---
|
||||
|
||||
### Task S2: Configuration Database — EF mappings, encryption, idempotent migration
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S5
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/NotificationConfiguration.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/ScadaBridgeDbContext.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/NotificationRepository.cs` (or wherever `INotificationRepository` is implemented — locate it)
|
||||
- Create: new EF migration under `src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/` (mapping/round-trip + encryption test)
|
||||
|
||||
**Steps:**
|
||||
1. `NotificationRecipientConfiguration`: `EmailAddress` → `.IsRequired(false)`; add `PhoneNumber` `.HasMaxLength(32)` (nullable).
|
||||
2. Add `SmsConfigurationConfiguration : IEntityTypeConfiguration<SmsConfiguration>` (key, `AccountSid` required maxlen, `FromNumber` required, `AuthToken`/`MessagingServiceSid`/`ApiBaseUrl` nullable, sensible maxlens). Add `DbSet<SmsConfiguration>` + apply config.
|
||||
3. `ScadaBridgeDbContext.ApplySecretColumnEncryption`: add `modelBuilder.Entity<SmsConfiguration>().Property(s => s.AuthToken).HasConversion(converter);`.
|
||||
4. Implement the four `INotificationRepository` SMS-config methods (mirror SMTP impls exactly).
|
||||
5. Generate the migration (`dotnet ef migrations add AddSmsNotifications ...`). Then make it **idempotent** per repo convention (guard column add / table create / column-alter the way prior migrations in this repo do — match an existing idempotent migration as reference). Migration must: add `NotificationRecipients.PhoneNumber` (nullable), alter `NotificationRecipients.EmailAddress` to nullable, create `SmsConfigurations` table.
|
||||
6. Verify NO `PendingModelChangesWarning`: `dotnet build` + a model-drift check (the repo has a pattern/test for this — run it).
|
||||
7. Build Config-DB + run touched Config-DB tests. Commit (pathspec).
|
||||
|
||||
**Acceptance:** Config-DB builds; migration idempotent + no model drift; encryption applied to `AuthToken`; recipient phone + nullable email mapped; round-trip test green.
|
||||
|
||||
---
|
||||
|
||||
### Task S3: SmsNotificationDeliveryAdapter (Twilio REST) + classifier + options + DI + adapter tests
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S4, S6
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/SmsNotificationDeliveryAdapter.cs`
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/Delivery/SmsErrorClassifier.cs`
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/SmsOptions.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/ServiceCollectionExtensions.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/ZB.MOM.WW.ScadaBridge.NotificationOutbox.csproj`
|
||||
- Modify (test): `tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/ServiceRegistrationTests.cs`
|
||||
- Create (test): `tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/Delivery/SmsNotificationDeliveryAdapterTests.cs`
|
||||
|
||||
**Steps:**
|
||||
1. `SmsErrorClassifier`: static `IsTransient(HttpStatusCode)` (5xx/408/429) + `IsTransient(Exception, CancellationToken)` (HttpRequestException/Timeout/TaskCanceled when not caller-cancelled). Mirror `SmtpErrorClassifier`'s enum+static-method shape.
|
||||
2. `SmsOptions` (bind `ScadaBridge:Sms`): `int MaxMessageLength = 1600`, `int ConnectionTimeoutSeconds = 30` (config-row value overrides). Validate.
|
||||
3. `SmsNotificationDeliveryAdapter : INotificationDeliveryAdapter`, `Type => NotificationType.Sms`. Ctor: `INotificationRepository`, `IHttpClientFactory`, `ILogger`, `IOptions<SmsOptions>`. `DeliverAsync`:
|
||||
- Load list by `notification.ListName` → `Permanent` if missing.
|
||||
- Load recipients; filter to non-empty `PhoneNumber` → `Permanent` if none.
|
||||
- Load `GetSmsConfigurationAsync()` → `Permanent` if null/incomplete.
|
||||
- Compose body = `Subject` + "\n" + `Body`, truncate to `MaxMessageLength`.
|
||||
- For each phone: `POST {ApiBaseUrl}/2010-04-01/Accounts/{AccountSid}/Messages.json`, Basic auth header `AccountSid:AuthToken`, form `To`/`From`(or MessagingServiceSid)/`Body`. Classify per response.
|
||||
- Roll up per D6 (all-accepted→Success; any-transient→Transient; mix accepted+permanent→Success + LastError note; all-permanent→Permanent). `ResolvedTargets` = accepted numbers.
|
||||
- Scrub AuthToken from any logged error via `CredentialRedactor.Scrub`.
|
||||
4. `ServiceCollectionExtensions.AddNotificationOutbox`: register `SmsNotificationDeliveryAdapter` as scoped `INotificationDeliveryAdapter` (alongside Email); `services.AddHttpClient("Twilio")`; bind `SmsOptions`.
|
||||
5. `.csproj`: add `<PackageReference Include="Microsoft.Extensions.Http" />` (version comes from Directory.Packages.props — do NOT add a version attribute).
|
||||
6. **Update `ServiceRegistrationTests`**: the `Assert.Single(adapters)` test must now assert both Email and SMS adapters are registered (e.g. `Assert.Equal(2, adapters.Count)` + both types present); keep/add a `SmsNotificationDeliveryAdapter.Type == Sms` assertion.
|
||||
7. Adapter unit tests with a fake `HttpMessageHandler`: 201 success (single + multi recipient), 500/429/timeout → Transient, 400/401 → Permanent, mix accepted+400 → Success with LastError note, no-config/no-recipients/list-missing → Permanent, AuthToken never appears in returned error string.
|
||||
8. Build NotificationOutbox + run NotificationOutbox.Tests. Commit (pathspec; `git add` new files).
|
||||
|
||||
**Acceptance:** adapter builds; both adapters registered; all adapter unit tests + the updated ServiceRegistration test green; no AuthToken leakage.
|
||||
|
||||
---
|
||||
|
||||
### Task S4: Ingest type-stamping in NotificationOutboxActor
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** S3, S6
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.NotificationOutbox/NotificationOutboxActor.cs` (the ingest path that currently hard-codes `NotificationType.Email`, ~line 1147)
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.NotificationOutbox.Tests/` (ingest type-stamping test)
|
||||
|
||||
**Steps:**
|
||||
1. At ingest, resolve the target list (`GetListByNameAsync(msg.ListName)`); stamp `Type = list?.Type ?? NotificationType.Email` onto the new `Notification`. Keep the at-least-once insert-if-not-exists semantics intact (do NOT change idempotency). Add a brief comment replacing the old "all notifications are email" comment.
|
||||
2. Test: ingest for an Email list stamps Email; ingest for an Sms list stamps Sms; ingest for a missing list defaults Email (and later parks at delivery — assert default only).
|
||||
3. Build + run NotificationOutbox.Tests (filtered). Commit (pathspec).
|
||||
|
||||
**Acceptance:** notifications inherit the list's Type at ingest; idempotency unchanged; tests green.
|
||||
|
||||
---
|
||||
|
||||
### Task S5: Management — list-command Type + SMS-config commands/handlers
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S2
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/NotificationCommands.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/` (handler tests)
|
||||
|
||||
**Steps:**
|
||||
1. `NotificationCommands.cs`: add `NotificationType Type = NotificationType.Email` to `CreateNotificationListCommand` and `UpdateNotificationListCommand` (additive trailing param). Add `record ListSmsConfigsCommand;` and `record UpdateSmsConfigCommand(int SmsConfigId, string AccountSid, string FromNumber, string? MessagingServiceSid = null, string? ApiBaseUrl = null, string? AuthToken = null);` (mirror `UpdateSmtpConfigCommand`, preserve-if-null for AuthToken).
|
||||
2. `ManagementActor`: in Create/Update list handlers, persist `cmd.Type` on the `NotificationList`. Add `HandleListSmsConfigs` + `HandleUpdateSmsConfig` (preserve-if-null AuthToken/ApiBaseUrl), role-gate (Designer/Admin per SMTP), and audit via a credential-free `SmsConfigPublicShape` (mirror `SmtpConfigPublicShape` — never log/return AuthToken). Wire the command routing entries.
|
||||
3. Handler tests: create list with Type=Sms persists Sms; update SMS config preserves AuthToken when null, never surfaces AuthToken in audit/response.
|
||||
4. Build Commons + ManagementService + run ManagementService.Tests (filtered). Commit (pathspec).
|
||||
|
||||
**Acceptance:** list commands carry Type; SMS-config commands/handlers exist, role-gated, secret-safe; tests green.
|
||||
|
||||
---
|
||||
|
||||
### Task S6: CLI — list --type/--phones + notification sms group
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S3, S4
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CLI/README.md`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/`
|
||||
|
||||
**Steps:**
|
||||
1. List `create`/`update`: add `--type email|sms` (default email) and `--phones` (comma-separated E.164). Validate: email type requires `--emails`; sms type requires `--phones`; reject mismatch. Build `Create/UpdateNotificationListCommand` with `Type` + the right recipient set. (Recipients for SMS map to phone numbers — coordinate with how recipients are submitted; if recipients are added via a separate command, set Type on the list and feed phones through the recipient path.)
|
||||
2. Add `notification sms list` (→ `ListSmsConfigsCommand`) and `notification sms update --id --account-sid --from-number [--messaging-service-sid] [--api-base-url] [--auth-token]` (→ `UpdateSmsConfigCommand`), mirroring the `notification smtp` group. Render JSON/table; never print AuthToken.
|
||||
3. Update CLI README (notification section: `--type`/`--phones`, `sms` group).
|
||||
4. Build CLI + run CLI.Tests (filtered). Commit (pathspec).
|
||||
|
||||
**Acceptance:** CLI creates SMS lists + manages SMS config; validation enforced; secret never printed; tests + README updated.
|
||||
|
||||
---
|
||||
|
||||
### Task S7: Central UI — NotificationListForm Type selector + per-type recipient input
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S8, S9, S10
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationListForm.razor`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/` (NotificationListForm tests)
|
||||
|
||||
**Steps:**
|
||||
1. Add an **adapter-gated** Type selector: source the options from the registered `INotificationDeliveryAdapter` Types (inject the adapter set or a small accessor; if injecting the adapters into the UI is awkward, expose a server-side accessor that returns the registered `NotificationType` set). Today renders Email + SMS. Selector enabled on create; **read-only on edit** (Id.HasValue) to prevent recipient-kind mismatch.
|
||||
2. Recipient editor: when Type=Email show the Email input + validate email; when Type=Sms show a Phone input + validate E.164. Build the recipient via `NotificationRecipient.ForEmail/ForSms`. Update the recipients table to show Email or Phone per type.
|
||||
3. On save, pass `Type` to the create command / new list.
|
||||
4. bUnit tests: selector renders Email+SMS; choosing SMS shows phone input + validation; create persists Type; edit shows Type read-only. **Razor hygiene:** any `@* *@` comment must sit OUTSIDE element start tags (the recurring circuit-crash landmine).
|
||||
5. Build CentralUI + run the NotificationListForm tests (filtered). Commit (pathspec).
|
||||
|
||||
**Acceptance:** Type selector adapter-gated + create-only; per-type recipient input + validation; tests green; no Razor start-tag comments.
|
||||
|
||||
---
|
||||
|
||||
### Task S8: Central UI — NotificationLists Type column
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** S7, S9, S10
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/NotificationLists.razor`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/NotificationListsPageTests.cs`
|
||||
|
||||
**Steps:**
|
||||
1. Add a **Type** column to the lists table (render `NotificationType`). Keep markup tokenized/consistent with the M10 table conventions.
|
||||
2. Update/extend `NotificationListsPageTests` to assert the Type column renders (e.g. an SMS list shows "Sms").
|
||||
3. Build CentralUI + run NotificationListsPageTests. Commit (pathspec).
|
||||
|
||||
**Acceptance:** Type column renders; test green.
|
||||
|
||||
---
|
||||
|
||||
### Task S9: Central UI — SMS configuration page
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S7, S8, S10
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/SmsConfiguration.razor`
|
||||
- Modify: the nav/menu component that lists `/notifications/smtp` (add `/notifications/sms`)
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/` (SmsConfiguration page test)
|
||||
|
||||
**Steps:**
|
||||
1. New page `/notifications/sms` (Admin-only, mirror `SmtpConfiguration.razor`): list SMS configs, create/edit form (AccountSid, FromNumber, MessagingServiceSid, ApiBaseUrl, AuthToken — AuthToken write-only/masked, preserve-if-blank on edit), save via repository/management. Never render the stored AuthToken back.
|
||||
2. Add the nav entry next to the SMTP settings entry.
|
||||
3. bUnit: page renders config rows; AuthToken input is masked/not pre-filled; save calls the repository. Razor start-tag comment hygiene.
|
||||
4. Build CentralUI + run the page test. Commit (pathspec; `git add` new file).
|
||||
|
||||
**Acceptance:** SMS config page works + Admin-gated + secret-safe; nav entry added; test green.
|
||||
|
||||
---
|
||||
|
||||
### Task S10: Transport — recipient PhoneNumber DTO + SmsConfigDto round-trip
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** S7, S8, S9
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Transport/Serialization/EntityDtos.cs`
|
||||
- Modify: `src/ZB.MOM.WW.ScadaBridge.Transport/Serialization/EntitySerializer.cs`
|
||||
- Test: `tests/ZB.MOM.WW.ScadaBridge.Transport.*Tests/`
|
||||
|
||||
**Steps:**
|
||||
1. `NotificationRecipientDto`: add `string? PhoneNumber` (trailing, nullable → backward-compatible). `SmsConfigDto` mirroring `SmtpConfigDto` (secret in `SecretsBlock`). Add `IReadOnlyList<SmsConfigDto> SmsConfigs` to `BundleContentDto` and `IReadOnlyList<SmsConfiguration> SmsConfigurations` to `EntityAggregate`.
|
||||
2. `EntitySerializer`: map recipient PhoneNumber both directions; map SMS configs export/import (mirror SMTP, including SecretsBlock handling). Keep `schemaVersion` evolution additive per repo convention.
|
||||
3. Tests: recipient phone round-trips; SMS config round-trips with secret in SecretsBlock; old bundle without PhoneNumber deserializes to null.
|
||||
4. Build Transport + run Transport tests (filtered). Commit (pathspec).
|
||||
|
||||
**Acceptance:** SMS recipient phone + SMS config travel in bundles; backward-compatible; tests green.
|
||||
|
||||
---
|
||||
|
||||
### Task S11: Integration — build, migration drift, docker, Playwright, live smoke, docs, review
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~10 min (+ docker rebuild wall-time)
|
||||
**Parallelizable with:** none
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/requirements/Component-NotificationService.md`, `docs/requirements/Component-NotificationOutbox.md`
|
||||
- Modify: `CLAUDE.md` (NotificationType = Email+Sms; T9/T10 delivered as SMS — flip the M6 deferral note; add the SMS-adapter decision bullet)
|
||||
- Modify: `README.md` (component table / notes if needed)
|
||||
- Create (test): `tests/ZB.MOM.WW.ScadaBridge.CentralUI.PlaywrightTests/Notifications/SmsNotificationListTests.cs` (or extend existing notification Playwright)
|
||||
|
||||
**Steps:**
|
||||
1. Full-solution build: `dotnet build ZB.MOM.WW.ScadaBridge.slnx` — 0 warnings/errors.
|
||||
2. EF model-drift check (no `PendingModelChangesWarning`).
|
||||
3. Full unfiltered managed test run `dotnet test ZB.MOM.WW.ScadaBridge.slnx` (run 2–3× for load-flake surfacing per the integration memory). Triage any red: prove pre-existing via `git diff --stat c72d7b79..HEAD -- <target files>` before attributing.
|
||||
4. Docker rebuild: `bash docker/deploy.sh`; `/health/ready` 200 on the active node.
|
||||
5. Live smoke via CLI against the cluster: set an SMS config (fake AccountSid + `--api-base-url` pointed at a mock, OR document Twilio sandbox), create an `--type sms` list with a phone recipient, submit a notification, verify it routes to the SMS adapter and parks-with-reason when the fake returns an error (proves routing + classification end-to-end). Also verify an Email list still delivers (no regression).
|
||||
6. Playwright: SMS-list create flow (Type selector → SMS → phone recipient → save) against the freshly-rebuilt cluster; broad notification-page smoke. Razor circuit-crash check: load `/notifications/lists/create` + `/notifications/sms` in a real browser (the bUnit-invisible render-crash gate).
|
||||
7. Docs reconciliation: Component docs + CLAUDE.md + README + CLI README synced; confirm the M6 deferral note is flipped to "delivered (SMS pivot)."
|
||||
8. Whole-branch integration review over `git diff c72d7b79..HEAD` (Bash-capable reviewer): end-to-end trace of the new `NotificationType.Sms` path (submit → ingest stamp → adapter dispatch → Twilio POST → park/retry), shared-component injection regressions (any new ctor/`[Inject]` dep → grep every fixture across ALL test projects), and secret-leak audit (AuthToken never logged/returned/rendered).
|
||||
9. Commit docs (pathspec). Then hand to finishing-a-development-branch.
|
||||
|
||||
**Acceptance:** full build + full managed tests green; docker healthy; live smoke proves SMS routing + Email no-regression; Playwright + render-crash gate green; docs synced; whole-branch review INTEGRATION-CLEAN.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"planPath": "docs/plans/2026-06-19-sms-notifications.md",
|
||||
"tasks": [
|
||||
{"id": 299, "subject": "S1: Commons foundation — NotificationType.Sms + recipient phone + SmsConfiguration + repo iface", "status": "pending"},
|
||||
{"id": 300, "subject": "S2: Config-DB — EF mappings + AuthToken encryption + idempotent migration", "status": "pending", "blockedBy": [299]},
|
||||
{"id": 303, "subject": "S5: Management — list-command Type + SMS-config commands/handlers", "status": "pending", "blockedBy": [299]},
|
||||
{"id": 301, "subject": "S3: SmsNotificationDeliveryAdapter (Twilio REST) + classifier + options + DI + tests", "status": "pending", "blockedBy": [299, 300]},
|
||||
{"id": 302, "subject": "S4: NotificationOutboxActor ingest type-stamping from list", "status": "pending", "blockedBy": [299]},
|
||||
{"id": 304, "subject": "S6: CLI — list --type/--phones + notification sms group", "status": "pending", "blockedBy": [303]},
|
||||
{"id": 305, "subject": "S7: Central UI — NotificationListForm adapter-gated Type selector + per-type recipient input", "status": "pending", "blockedBy": [299, 303]},
|
||||
{"id": 306, "subject": "S8: Central UI — NotificationLists Type column", "status": "pending", "blockedBy": [299]},
|
||||
{"id": 307, "subject": "S9: Central UI — SMS configuration page (/notifications/sms)", "status": "pending", "blockedBy": [300, 303]},
|
||||
{"id": 308, "subject": "S10: Transport — recipient PhoneNumber DTO + SmsConfigDto round-trip", "status": "pending", "blockedBy": [299]},
|
||||
{"id": 309, "subject": "S11: INT — build, drift, docker, Playwright, live smoke, docs, whole-branch review", "status": "pending", "blockedBy": [300, 301, 302, 303, 304, 305, 306, 307, 308]}
|
||||
],
|
||||
"lastUpdated": "2026-06-19"
|
||||
}
|
||||
@@ -174,6 +174,7 @@ These are configured via `DataConnectionOptions` in `appsettings.json`, not per-
|
||||
| `ReconnectInterval` | 5s | Fixed interval between reconnection attempts |
|
||||
| `TagResolutionRetryInterval` | 10s | Retry interval for unresolved tag paths |
|
||||
| `WriteTimeout` | 30s | Timeout for write operations |
|
||||
| `SeedReadTimeout` | 30s | Per-tag timeout for seed reads on the initial-subscribe (and reconnect re-seed) path. A hung device read is treated as a failed seed: retried up to `SeedReadMaxAttempts`, then the tag stays Uncertain until a change notification arrives. |
|
||||
|
||||
## Subscription Management
|
||||
|
||||
|
||||
@@ -65,12 +65,12 @@ The site forwards only `(listName, subject, body)` plus provenance — recipient
|
||||
|
||||
## The `Notifications` Table
|
||||
|
||||
The table is type-agnostic so it can record any notification type the system supports — email today, Microsoft Teams and others later. One row per notification.
|
||||
The table is type-agnostic so it can record any notification type the system supports — `Email` and `Sms` today; others can be added by registering a new `INotificationDeliveryAdapter`. One row per notification.
|
||||
|
||||
| Field | Notes |
|
||||
|---|---|
|
||||
| `NotificationId` | GUID, primary key. Generated at the **site**; used as the idempotency key. |
|
||||
| `Type` | `Email` / `Teams` / … discriminator. |
|
||||
| `Type` | `Email` / `Sms` / … discriminator. Stamped at ingest from the target list's `Type` (default `Email` if the list is not found — delivery parks on "list not found" regardless). |
|
||||
| `ListName` | Target notification list. |
|
||||
| `Subject`, `Body` | Plain-text content. |
|
||||
| `TypeData` | JSON — extensibility hook for future per-type fields. |
|
||||
@@ -99,7 +99,7 @@ The Notification Outbox and the central [`Site Call Audit`](Component-SiteCallAu
|
||||
|
||||
### Retry Policy
|
||||
|
||||
Delivery retry reuses the central SMTP configuration's max-retry-count and fixed retry interval. The interval is fixed (no exponential backoff), consistent with the existing fixed-interval store-and-forward convention.
|
||||
Delivery retry reuses the central SMTP configuration's max-retry-count and fixed retry interval for Email notifications. SMS notifications reuse the `SmsConfiguration`'s retry settings. The interval is fixed (no exponential backoff), consistent with the existing fixed-interval store-and-forward convention.
|
||||
|
||||
### Retention
|
||||
|
||||
@@ -133,10 +133,12 @@ The operational `Notifications` table remains the **source of truth** for the di
|
||||
|
||||
A delivery adapter implementing `INotificationDeliveryAdapter` is registered per `Type`. Each `Deliver(...)` call returns one of `success | transient failure | permanent failure`, mirroring the External System Gateway error-classification pattern.
|
||||
|
||||
- **Email adapter — implemented now.** The existing SMTP composition/send logic, relocated to the central cluster.
|
||||
- **Teams and other adapters — future.** The `Type` discriminator and the adapter interface are the seam; no Teams code exists in this design. Teams auth and targeting (Incoming Webhooks vs Graph API) is a separate design conversation.
|
||||
- **Email adapter.** The existing SMTP composition/send logic, relocated to the central cluster. Sends a single BCC email to all list recipients.
|
||||
- **SMS adapter (Twilio REST).** Added in T9/T10 (2026-06-19). Sends one Twilio REST request per recipient phone number. Per-recipient results are rolled up: all-accepted → `Success`; any-transient → retry/park; mix of accepted + permanent-bad → `Success` with bad numbers noted in `LastError`; all-permanent → `Permanent` (Park). See [Component-NotificationService.md](Component-NotificationService.md), SMS Delivery Adapter.
|
||||
|
||||
Delivery adapters are provided by the Notification Service, which manages notification-list and SMTP definitions and supplies the stateless per-type "deliver one notification" implementations.
|
||||
The outbox dispatches by looking up the adapter registered for the notification's `Type`. If no adapter is registered for a given `Type`, the notification is parked with a "no adapter" error — the seam is open for future delivery channels.
|
||||
|
||||
Delivery adapters are provided by the Notification Service, which manages notification-list, SMTP, and SMS definitions and supplies the stateless per-type "deliver one notification" implementations. The SMS `SmsConfiguration` (including encrypted Auth Token) travels in Transport bundles alongside SMTP config.
|
||||
|
||||
## Active/Standby Behavior
|
||||
|
||||
@@ -177,7 +179,7 @@ Delivery max-retry-count and retry interval are not part of `NotificationOutboxO
|
||||
|
||||
## Dependencies
|
||||
|
||||
- **Notification Service**: Provides notification-list and SMTP definitions, and the per-type delivery adapters the outbox invokes.
|
||||
- **Notification Service**: Provides notification-list, SMTP, and SMS definitions, and the per-type delivery adapters the outbox invokes (Email + Twilio SMS).
|
||||
- **Configuration Database**: Hosts the `Notifications` table; provides the entity POCO, repository, and EF migration for outbox persistence.
|
||||
- **Central–Site Communication**: Carries inbound notification submissions and acks between sites and central.
|
||||
- **Audit Log (#23)**: The dispatcher direct-writes `Notification.Attempt` and `Notification.Terminal` rows to the central `AuditLog` via `ICentralAuditWriter` (insert-if-not-exists on `EventId`); the site-emitted `Notification.Enqueued` row arrives via the standard audit telemetry channel. See [Component-AuditLog.md](Component-AuditLog.md), Central direct-write (central-originated events).
|
||||
@@ -187,7 +189,7 @@ Delivery max-retry-count and retry interval are not part of `NotificationOutboxO
|
||||
## Interactions
|
||||
|
||||
- **Site Store-and-Forward Engine**: Forwards notifications to central via Central–Site Communication; the outbox ingests them and acks once persisted.
|
||||
- **Notification Service**: Supplies delivery adapters and resolves notification lists at delivery time.
|
||||
- **Notification Service**: Supplies delivery adapters (Email + SMS) and resolves notification lists at delivery time.
|
||||
- **Central UI**: Queries the `Notifications` table for the Notification Outbox page and issues operator Retry/Discard actions on parked notifications.
|
||||
- **Health Monitoring**: Polls the outbox for KPI tiles on the health dashboard.
|
||||
- **KPI History (#26)**: Emits `IKpiSampleSource` (`NotificationOutboxKpiSampleSource`, Global + per-Site + per-Node) consumed by the KpiHistory recorder (#26), reusing the existing `Compute…KpisAsync` reads; the resulting `queueDepth` / `stuckCount` / `parkedCount` / `deliveredLastInterval` / `oldestPendingAgeSeconds` series render as trends on the Notification Outbox page via `KpiTrendChart`. See [Component-KpiHistory.md](Component-KpiHistory.md).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Purpose
|
||||
|
||||
The Notification Service is the central component that manages notification-list and SMTP definitions and provides the per-type delivery adapters used to send notifications. It manages notification-list and SMTP definitions, and supplies the stateless "deliver one notification" adapter implementations that the Notification Outbox invokes at delivery time.
|
||||
The Notification Service is the central component that manages notification-list, SMTP, and SMS definitions and provides the per-type delivery adapters used to send notifications. It manages notification-list and delivery-channel definitions, and supplies the stateless "deliver one notification" adapter implementations that the Notification Outbox invokes at delivery time.
|
||||
|
||||
The Notification Service no longer delivers notifications from sites. Notification delivery has been inverted: a site script's notification is store-and-forwarded to the central cluster, and the central **Notification Outbox** owns dispatch and delivery, calling an `INotificationDeliveryAdapter` supplied by this component. See [`Component-NotificationOutbox.md`](Component-NotificationOutbox.md).
|
||||
|
||||
@@ -13,25 +13,27 @@ Central cluster only. The Notification Service manages definitions in the centra
|
||||
## Responsibilities
|
||||
|
||||
### Definitions (Central)
|
||||
- Store notification lists in the configuration database: list name, list **type**, and type-specific targets (e.g. recipients for an `Email` list).
|
||||
- Store notification lists in the configuration database: list name, list **type**, and type-specific targets (e.g. recipients for an `Email` list, phone numbers for an `Sms` list).
|
||||
- Store email server configuration (SMTP settings).
|
||||
- Managed by users with the Designer role.
|
||||
- Notification lists and SMTP configuration are **not deployed to sites** — they exist centrally only. There is no deploy-to-sites artifact and no local SQLite copy.
|
||||
- Store SMS provider configuration (`SmsConfiguration`: Twilio credentials and endpoint settings).
|
||||
- Managed by users with the Designer role (notification lists) and Admin role (SMTP and SMS configuration).
|
||||
- Notification lists, SMTP configuration, and SMS configuration are **not deployed to sites** — they exist centrally only. There is no deploy-to-sites artifact and no local SQLite copy.
|
||||
|
||||
### Delivery Adapters (Central)
|
||||
- Provide a delivery adapter implementing `INotificationDeliveryAdapter` for each notification `Type`.
|
||||
- Each adapter is a stateless "deliver one notification" implementation: it composes and sends a single notification and classifies the outcome.
|
||||
- The **Email adapter** is the relocated SMTP composition and send logic — formerly run at sites, it now runs on the central cluster.
|
||||
- Resolve a notification list name to its concrete targets (e.g. recipient addresses) at delivery time, on behalf of the Notification Outbox.
|
||||
- The **SMS adapter** delivers notifications via Twilio REST to a list's phone-number recipients — see SMS Delivery Adapter below.
|
||||
- Resolve a notification list name to its concrete targets (e.g. recipient addresses or phone numbers) at delivery time, on behalf of the Notification Outbox.
|
||||
|
||||
## Notification List Definition
|
||||
|
||||
Each notification list includes:
|
||||
- **Name**: Unique identifier (e.g., "Maintenance-Team", "Shift-Supervisors").
|
||||
- **Type**: The notification type — `Email` (implemented now); `Teams` and other types are planned for the future. `Notify.To("list")` works transparently for any type — the calling script does not care about the type.
|
||||
- **Type-specific targets**: The targets appropriate to the list type. For an `Email` list, one or more recipient entries, each with:
|
||||
- Recipient name.
|
||||
- Email address.
|
||||
- **Type**: The notification channel — `Email` or `Sms`. `Notify.To("list")` works transparently for any type — the calling script does not care about the type. The type is chosen at list creation and is **fixed** — it cannot be changed on update (prevents email/phone recipient mismatch within a list).
|
||||
- **Type-specific targets**: The targets appropriate to the list type:
|
||||
- **Email list** — one or more recipient entries, each with a recipient name and email address.
|
||||
- **SMS list** — one or more recipient entries, each with a recipient name and E.164 phone number.
|
||||
|
||||
Lists are defined and stored centrally only. **Recipient resolution happens at central, at delivery time** — a site forwards only `(listName, subject, body)` plus provenance; the Notification Outbox asks the Notification Service to resolve the list when it dispatches the notification.
|
||||
|
||||
@@ -50,6 +52,20 @@ The SMTP configuration is defined centrally and used by the central Email delive
|
||||
- **Max concurrent connections**: Maximum simultaneous SMTP connections from the central cluster (default: 5).
|
||||
- **Retry settings**: Max retry count, fixed time between retries. The Notification Outbox reuses these for delivery retry of transient failures.
|
||||
|
||||
## SMS Configuration
|
||||
|
||||
The `SmsConfiguration` entity is defined centrally and used by the central SMS delivery adapter. It mirrors `SmtpConfiguration` in structure and is not deployed to sites. It is managed by Admin-role users via the CLI (`notification sms list|update`) and the Central UI `/notifications/sms` page. It includes:
|
||||
|
||||
- **Account SID**: Twilio Account SID (plaintext; also appears in the API URL path).
|
||||
- **Auth Token**: Twilio Auth Token, **encrypted at rest** via ASP.NET Data Protection (`EncryptedStringConverter`). The Auth Token is never returned from the list command — the listing reports it only as a `hasAuthToken` presence flag.
|
||||
- **From number** (optional): Sender phone number in E.164 format (e.g., `+15551234567`). Used unless a Messaging Service SID is specified. A valid configuration carries a From number **and/or** a Messaging Service SID — at least one is required (validated in the Central UI, the CLI, and again by the delivery adapter).
|
||||
- **Messaging Service SID** (optional): Twilio Messaging Service SID. When present, Twilio uses it for sender selection; used instead of the From number (so a Messaging-Service-only config needs no From number).
|
||||
- **API base URL** (optional): Override for the Twilio REST API base URL (default: `https://api.twilio.com`). Allows pointing at a test/stub handler or a regional endpoint.
|
||||
- **Connection timeout**: Maximum time to wait for a Twilio API response (honored per-send by the delivery adapter).
|
||||
- **Max retries** / **Retry delay**: Reserved. The Notification Outbox dispatcher currently derives the retry policy (max-retries + interval) from the central SMTP configuration for all notification types; these per-SMS values are persisted and transported for forward-compatibility but are not yet read at dispatch time. Honoring them per-type is a deferred enhancement.
|
||||
|
||||
The `SmsConfiguration` entity travels in Transport bundles — the Auth Token rides the encrypted `SecretsBlock` (keyed by Account SID), consistent with how SMTP credentials are bundled.
|
||||
|
||||
## Script API
|
||||
|
||||
```csharp
|
||||
@@ -65,14 +81,34 @@ NotificationStatus status = Notify.Status(id);
|
||||
|
||||
## Notification Delivery Behavior
|
||||
|
||||
Delivery is performed centrally by the Notification Outbox, which calls the `INotificationDeliveryAdapter` registered for the notification's `Type`. The behavior below describes the Email adapter.
|
||||
Delivery is performed centrally by the Notification Outbox, which calls the `INotificationDeliveryAdapter` registered for the notification's `Type`.
|
||||
|
||||
### Recipient Handling (Email)
|
||||
- A single email is sent per notification, with all list recipients in **BCC**. The from address is placed in the To field.
|
||||
- Recipients do not see each other's email addresses.
|
||||
- No per-recipient deduplication — if the same email address appears in multiple lists and a script sends to both, they receive multiple emails.
|
||||
|
||||
### Error Classification
|
||||
## SMS Delivery Adapter
|
||||
|
||||
The `SmsNotificationDeliveryAdapter` delivers notifications to an SMS list via the Twilio REST API (no Twilio SDK — uses `IHttpClientFactory` with a named `"Twilio"` `HttpClient` and HTTP Basic auth with `AccountSid:AuthToken`). It is outbound-only; true per-recipient delivery confirmation requires a status-callback webhook (out of scope for v1). "Accepted by Twilio" is treated as delivered, consistent with how the Email adapter treats "accepted by SMTP."
|
||||
|
||||
### Message Format
|
||||
- SMS has no subject line. The message body is composed as `Subject` + newline + `Body` (whichever are present), plain text, truncated to a configurable cap (`SmsOptions.MaxMessageLength`, default 1600 — the Twilio maximum) with an ellipsis when over. Twilio segments at 160 GSM-7 characters and bills per segment.
|
||||
|
||||
### Per-Recipient Delivery (no BCC equivalent)
|
||||
SMS has no BCC mechanism. The adapter sends one Twilio request per recipient and classifies each:
|
||||
|
||||
- **All accepted** → `Success`; `ResolvedTargets` is snapshotted with the accepted numbers.
|
||||
- **Any transient failure** → `Transient` (the whole notification retries at the fixed interval, then Parks after max-retries). Numbers already accepted on a prior attempt are re-texted on retry — the same "re-send to all" characteristic the Email adapter already has with BCC. (v1 does not track per-recipient state; that is a documented future enhancement.)
|
||||
- **No transient failures, mix of accepted + permanent-bad** → `Success` to the good numbers; permanently-bad numbers are recorded in `LastError`. The notification is not parked if anything got through.
|
||||
- **All permanent / no recipients / no SMS config / list-not-found** → `Permanent` (Park).
|
||||
|
||||
### Error Classification (SMS)
|
||||
A small `SmsErrorClassifier` mirrors the External System Gateway pattern:
|
||||
- **Transient**: HTTP 5xx, 408, 429; `HttpRequestException`, timeout (non-caller-cancel).
|
||||
- **Permanent**: other 4xx (including 401/403 bad credentials, 400 invalid/unsubscribed number).
|
||||
|
||||
### Error Classification (Email)
|
||||
Each `Deliver(...)` call returns one of `success | transient failure | permanent failure`, consistent with the External System Gateway pattern. There is **no synchronous permanent-failure return to the script** — `Send()` returns immediately, before any delivery is attempted.
|
||||
|
||||
- **Transient failures** (connection refused, timeout, SMTP 4xx temporary errors): The Notification Outbox moves the row to `Retrying` and schedules another attempt per the SMTP configuration's retry settings.
|
||||
@@ -81,11 +117,11 @@ Each `Deliver(...)` call returns one of `success | transient failure | permanent
|
||||
- A script observes failures only by calling `Notify.Status(id)` and seeing a `Parked` status — not as a synchronous exception.
|
||||
|
||||
### No Rate Limiting
|
||||
- No application-level rate limiting. If the SMTP server enforces sending limits (e.g., Microsoft 365 throttling), those manifest as transient failures and are retried naturally by the Notification Outbox.
|
||||
- No application-level rate limiting. If the delivery endpoint enforces sending limits (e.g., Microsoft 365 throttling or Twilio rate limits), those manifest as transient failures and are retried naturally by the Notification Outbox.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- **Configuration Database (MS SQL)**: Stores notification list definitions (name, type, type-specific targets) and SMTP config.
|
||||
- **Configuration Database (MS SQL)**: Stores notification list definitions (name, type, type-specific targets), SMTP configuration, and `SmsConfiguration`.
|
||||
- **Notification Outbox**: Invokes the delivery adapters supplied by this component and asks it to resolve notification lists at delivery time.
|
||||
- **Security & Auth**: Designer role manages notification lists.
|
||||
- **Configuration Database (via IAuditService)**: Notification list changes are audit logged.
|
||||
|
||||
@@ -36,11 +36,12 @@ public sealed class AuditLogKpiSampleSource : IKpiSampleSource
|
||||
/// </summary>
|
||||
private static readonly TimeSpan Window = TimeSpan.FromHours(1);
|
||||
|
||||
// Metric catalog — the exact strings persisted in KpiSample.Metric. Stable
|
||||
// identifiers the recorder + UI trend charts key on; do not rename.
|
||||
private const string TotalEventsLastHourMetric = "totalEventsLastHour";
|
||||
private const string ErrorEventsLastHourMetric = "errorEventsLastHour";
|
||||
private const string BacklogTotalMetric = "backlogTotal";
|
||||
// Metric catalog — the exact strings persisted in KpiSample.Metric. All three are
|
||||
// charted, so they share the public Commons catalog: source + UI trend page key off
|
||||
// one symbol (#178). Stable identifiers; do not rename (values are persisted).
|
||||
private const string TotalEventsLastHourMetric = KpiMetrics.AuditLog.TotalEventsLastHour;
|
||||
private const string ErrorEventsLastHourMetric = KpiMetrics.AuditLog.ErrorEventsLastHour;
|
||||
private const string BacklogTotalMetric = KpiMetrics.AuditLog.BacklogTotal;
|
||||
|
||||
private readonly IAuditLogRepository _repository;
|
||||
|
||||
|
||||
@@ -61,6 +61,9 @@ public static class BundleCommands
|
||||
var dbConnectionsOption = NameListOption("--db-connections", "Comma-separated database-connection names");
|
||||
var notificationListsOption = NameListOption("--notification-lists", "Comma-separated notification-list names");
|
||||
var smtpConfigsOption = NameListOption("--smtp-configs", "Comma-separated SMTP host names");
|
||||
// SMS (S10b): SmsConfiguration is keyed by AccountSid (no Name column), so
|
||||
// tokens are AccountSid values — mirrors --smtp-configs using Host.
|
||||
var smsConfigsOption = NameListOption("--sms-configs", "Comma-separated SMS provider account SIDs");
|
||||
// Inbound API keys are not transported between environments (re-arch C4) — no
|
||||
// --api-keys option. Re-create keys and re-grant their method scopes on the
|
||||
// destination via the admin UI/CLI.
|
||||
@@ -91,6 +94,7 @@ public static class BundleCommands
|
||||
cmd.Add(dbConnectionsOption);
|
||||
cmd.Add(notificationListsOption);
|
||||
cmd.Add(smtpConfigsOption);
|
||||
cmd.Add(smsConfigsOption);
|
||||
cmd.Add(apiMethodsOption);
|
||||
cmd.Add(sitesOption);
|
||||
cmd.Add(instancesOption);
|
||||
@@ -118,7 +122,8 @@ public static class BundleCommands
|
||||
Passphrase: passphrase,
|
||||
SourceEnvironment: sourceEnv,
|
||||
SiteNames: result.GetValue(sitesOption),
|
||||
InstanceNames: result.GetValue(instancesOption));
|
||||
InstanceNames: result.GetValue(instancesOption),
|
||||
SmsConfigurationNames: result.GetValue(smsConfigsOption));
|
||||
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.CommandLine;
|
||||
using System.CommandLine.Parsing;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
||||
|
||||
@@ -24,10 +25,43 @@ public static class NotificationCommands
|
||||
command.Add(BuildUpdate(urlOption, formatOption, usernameOption, passwordOption));
|
||||
command.Add(BuildDelete(urlOption, formatOption, usernameOption, passwordOption));
|
||||
command.Add(BuildSmtp(urlOption, formatOption, usernameOption, passwordOption));
|
||||
command.Add(BuildSms(urlOption, formatOption, usernameOption, passwordOption));
|
||||
|
||||
return command;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Notification list create/update options (static so the parsed values can
|
||||
// be read back both from the SetAction and from the testable Build* helpers).
|
||||
// ------------------------------------------------------------------------
|
||||
private static readonly Option<string> ListCreateNameOption =
|
||||
new("--name") { Description = "Notification list name", Required = true };
|
||||
private static readonly Option<string?> ListCreateEmailsOption =
|
||||
new("--emails") { Description = "Comma-separated recipient emails (required for --type email; rejected for --type sms)" };
|
||||
private static readonly Option<string?> ListCreatePhonesOption =
|
||||
new("--phones") { Description = "Comma-separated recipient phone numbers in E.164 (required for --type sms; rejected for --type email)" };
|
||||
private static readonly Option<string> ListCreateTypeOption = CreateListTypeOption();
|
||||
|
||||
private static readonly Option<int> ListUpdateIdOption =
|
||||
new("--id") { Description = "Notification list ID", Required = true };
|
||||
private static readonly Option<string> ListUpdateNameOption =
|
||||
new("--name") { Description = "List name", Required = true };
|
||||
private static readonly Option<string?> ListUpdateEmailsOption =
|
||||
new("--emails") { Description = "Comma-separated recipient emails (required for --type email; rejected for --type sms)" };
|
||||
private static readonly Option<string?> ListUpdatePhonesOption =
|
||||
new("--phones") { Description = "Comma-separated recipient phone numbers in E.164 (required for --type sms; rejected for --type email)" };
|
||||
private static readonly Option<string> ListUpdateTypeOption = CreateListTypeOption();
|
||||
|
||||
private static Option<string> CreateListTypeOption()
|
||||
{
|
||||
var option = new Option<string>("--type")
|
||||
{
|
||||
Description = "Delivery channel: email or sms (case-insensitive; default email)",
|
||||
DefaultValueFactory = _ => "email",
|
||||
};
|
||||
return option;
|
||||
}
|
||||
|
||||
private static Command BuildGet(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var idOption = new Option<int>("--id") { Description = "Notification list ID", Required = true };
|
||||
@@ -44,27 +78,50 @@ public static class NotificationCommands
|
||||
|
||||
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var idOption = new Option<int>("--id") { Description = "Notification list ID", Required = true };
|
||||
var nameOption = new Option<string>("--name") { Description = "List name", Required = true };
|
||||
var emailsOption = new Option<string>("--emails") { Description = "Comma-separated recipient emails", Required = true };
|
||||
|
||||
var cmd = new Command("update") { Description = "Update a notification list" };
|
||||
cmd.Add(idOption);
|
||||
cmd.Add(nameOption);
|
||||
cmd.Add(emailsOption);
|
||||
cmd.Add(ListUpdateIdOption);
|
||||
cmd.Add(ListUpdateNameOption);
|
||||
cmd.Add(ListUpdateTypeOption);
|
||||
cmd.Add(ListUpdateEmailsOption);
|
||||
cmd.Add(ListUpdatePhonesOption);
|
||||
cmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
var id = result.GetValue(idOption);
|
||||
var name = result.GetValue(nameOption)!;
|
||||
var emailsRaw = result.GetValue(emailsOption)!;
|
||||
var emails = emailsRaw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
|
||||
UpdateNotificationListCommand command;
|
||||
try
|
||||
{
|
||||
command = BuildUpdateNotificationListCommand(result);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
OutputFormatter.WriteError(ex.Message, "INVALID_ARGUMENT");
|
||||
return 1;
|
||||
}
|
||||
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
new UpdateNotificationListCommand(id, name, emails));
|
||||
result, urlOption, formatOption, usernameOption, passwordOption, command);
|
||||
});
|
||||
return cmd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the <see cref="UpdateNotificationListCommand"/> from a parsed
|
||||
/// <c>notification list update</c> invocation, applying the channel-aware
|
||||
/// recipient validation. Throws <see cref="ArgumentException"/> when the
|
||||
/// channel and the supplied recipient flags are inconsistent.
|
||||
/// </summary>
|
||||
/// <param name="result">The parsed command-line result.</param>
|
||||
/// <returns>A validated <see cref="UpdateNotificationListCommand"/>.</returns>
|
||||
internal static UpdateNotificationListCommand BuildUpdateNotificationListCommand(ParseResult result)
|
||||
{
|
||||
var id = result.GetValue(ListUpdateIdOption);
|
||||
var name = result.GetValue(ListUpdateNameOption)!;
|
||||
var (type, emails, phones) = ResolveListChannel(
|
||||
result.GetValue(ListUpdateTypeOption)!,
|
||||
result.GetValue(ListUpdateEmailsOption),
|
||||
result.GetValue(ListUpdatePhonesOption));
|
||||
return new UpdateNotificationListCommand(id, name, emails, type, phones);
|
||||
}
|
||||
|
||||
private static Command BuildSmtp(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var group = new Command("smtp") { Description = "Manage SMTP configuration" };
|
||||
@@ -145,6 +202,91 @@ public static class NotificationCommands
|
||||
return new UpdateSmtpConfigCommand(id, server, port, authMode, from, tlsMode, credentials);
|
||||
}
|
||||
|
||||
private static Command BuildSms(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var group = new Command("sms") { Description = "Manage SMS (Twilio) configuration" };
|
||||
|
||||
var listCmd = new Command("list") { Description = "List SMS configurations (Auth Token shown as a presence flag only)" };
|
||||
listCmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption, new ListSmsConfigsCommand());
|
||||
});
|
||||
group.Add(listCmd);
|
||||
|
||||
var updateCmd = new Command("update") { Description = "Update SMS configuration" };
|
||||
updateCmd.Add(SmsIdOption);
|
||||
updateCmd.Add(SmsAccountSidOption);
|
||||
updateCmd.Add(SmsFromNumberOption);
|
||||
updateCmd.Add(SmsMessagingServiceSidOption);
|
||||
updateCmd.Add(SmsApiBaseUrlOption);
|
||||
updateCmd.Add(SmsAuthTokenOption);
|
||||
updateCmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
BuildUpdateSmsConfigCommand(result));
|
||||
});
|
||||
group.Add(updateCmd);
|
||||
|
||||
return group;
|
||||
}
|
||||
|
||||
// SMS update options are static so the parsed values can be read back both
|
||||
// from the SetAction and from BuildUpdateSmsConfigCommand (used by tests).
|
||||
private static readonly Option<int> SmsIdOption =
|
||||
new("--id") { Description = "SMS config ID", Required = true };
|
||||
private static readonly Option<string> SmsAccountSidOption =
|
||||
new("--account-sid") { Description = "Twilio Account SID", Required = true };
|
||||
private static readonly Option<string?> SmsFromNumberOption =
|
||||
new("--from-number")
|
||||
{
|
||||
Description = "Sender phone number (E.164). Provide this and/or --messaging-service-sid.",
|
||||
};
|
||||
private static readonly Option<string?> SmsMessagingServiceSidOption =
|
||||
new("--messaging-service-sid")
|
||||
{
|
||||
Description = "Twilio Messaging Service SID (optional; OMITTING IT CLEARS the stored value)",
|
||||
};
|
||||
private static readonly Option<string?> SmsApiBaseUrlOption =
|
||||
new("--api-base-url")
|
||||
{
|
||||
Description = "API base URL override (optional; preserves existing if omitted)",
|
||||
};
|
||||
private static readonly Option<string?> SmsAuthTokenOption =
|
||||
new("--auth-token")
|
||||
{
|
||||
Description = "Twilio Auth Token (optional; PRESERVES the stored token if omitted; never printed back)",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Builds the <see cref="UpdateSmsConfigCommand"/> from a parsed <c>sms update</c>
|
||||
/// invocation. Note the asymmetric preserve-vs-clear semantics enforced server-side:
|
||||
/// omitting <c>--auth-token</c> / <c>--api-base-url</c> maps to null so the handler
|
||||
/// PRESERVES the existing values, whereas omitting <c>--messaging-service-sid</c> also
|
||||
/// maps to null but the handler OVERWRITES (clears) the stored value.
|
||||
/// </summary>
|
||||
/// <param name="result">The parsed command-line result from the <c>sms update</c> invocation.</param>
|
||||
/// <returns>An <see cref="UpdateSmsConfigCommand"/> populated from the parsed result.</returns>
|
||||
internal static UpdateSmsConfigCommand BuildUpdateSmsConfigCommand(ParseResult result)
|
||||
{
|
||||
var id = result.GetValue(SmsIdOption);
|
||||
var accountSid = result.GetValue(SmsAccountSidOption)!;
|
||||
var fromNumber = result.GetValue(SmsFromNumberOption);
|
||||
var messagingServiceSid = result.GetValue(SmsMessagingServiceSidOption);
|
||||
var apiBaseUrl = result.GetValue(SmsApiBaseUrlOption);
|
||||
var authToken = result.GetValue(SmsAuthTokenOption);
|
||||
// Whole-replace update: the sender identity must be re-supplied. A Twilio config
|
||||
// needs a From number and/or a Messaging Service SID, so reject the case where the
|
||||
// update would leave neither (mirrors the UI + delivery-adapter validation).
|
||||
if (string.IsNullOrWhiteSpace(fromNumber) && string.IsNullOrWhiteSpace(messagingServiceSid))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"Provide --from-number and/or --messaging-service-sid (at least one sender identity is required).");
|
||||
}
|
||||
return new UpdateSmsConfigCommand(id, accountSid, fromNumber, messagingServiceSid, apiBaseUrl, authToken);
|
||||
}
|
||||
|
||||
private static Command BuildList(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var cmd = new Command("list") { Description = "List all notification lists" };
|
||||
@@ -158,24 +300,103 @@ public static class NotificationCommands
|
||||
|
||||
private static Command BuildCreate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var nameOption = new Option<string>("--name") { Description = "Notification list name", Required = true };
|
||||
var emailsOption = new Option<string>("--emails") { Description = "Comma-separated recipient emails", Required = true };
|
||||
|
||||
var cmd = new Command("create") { Description = "Create a notification list" };
|
||||
cmd.Add(nameOption);
|
||||
cmd.Add(emailsOption);
|
||||
cmd.Add(ListCreateNameOption);
|
||||
cmd.Add(ListCreateTypeOption);
|
||||
cmd.Add(ListCreateEmailsOption);
|
||||
cmd.Add(ListCreatePhonesOption);
|
||||
cmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
var name = result.GetValue(nameOption)!;
|
||||
var emailsRaw = result.GetValue(emailsOption)!;
|
||||
var emails = emailsRaw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
|
||||
CreateNotificationListCommand command;
|
||||
try
|
||||
{
|
||||
command = BuildCreateNotificationListCommand(result);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
OutputFormatter.WriteError(ex.Message, "INVALID_ARGUMENT");
|
||||
return 1;
|
||||
}
|
||||
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
new CreateNotificationListCommand(name, emails));
|
||||
result, urlOption, formatOption, usernameOption, passwordOption, command);
|
||||
});
|
||||
return cmd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the <see cref="CreateNotificationListCommand"/> from a parsed
|
||||
/// <c>notification list create</c> invocation, applying the channel-aware
|
||||
/// recipient validation. Throws <see cref="ArgumentException"/> when the
|
||||
/// channel and the supplied recipient flags are inconsistent.
|
||||
/// </summary>
|
||||
/// <param name="result">The parsed command-line result.</param>
|
||||
/// <returns>A validated <see cref="CreateNotificationListCommand"/>.</returns>
|
||||
internal static CreateNotificationListCommand BuildCreateNotificationListCommand(ParseResult result)
|
||||
{
|
||||
var name = result.GetValue(ListCreateNameOption)!;
|
||||
var (type, emails, phones) = ResolveListChannel(
|
||||
result.GetValue(ListCreateTypeOption)!,
|
||||
result.GetValue(ListCreateEmailsOption),
|
||||
result.GetValue(ListCreatePhonesOption));
|
||||
return new CreateNotificationListCommand(name, emails, type, phones);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the <c>--type</c> value (case-insensitive) and validates that the supplied
|
||||
/// recipient flags match the channel: <c>email</c> requires <c>--emails</c> and rejects
|
||||
/// <c>--phones</c>; <c>sms</c> requires <c>--phones</c> and rejects <c>--emails</c>.
|
||||
/// </summary>
|
||||
/// <param name="typeRaw">The raw <c>--type</c> value.</param>
|
||||
/// <param name="emailsRaw">The raw <c>--emails</c> value, or null when omitted.</param>
|
||||
/// <param name="phonesRaw">The raw <c>--phones</c> value, or null when omitted.</param>
|
||||
/// <returns>The resolved channel and recipient lists (the off-channel list is empty).</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when the type is unknown or the recipient flags are inconsistent with the channel.</exception>
|
||||
private static (NotificationType Type, IReadOnlyList<string> Emails, IReadOnlyList<string>? Phones) ResolveListChannel(
|
||||
string typeRaw, string? emailsRaw, string? phonesRaw)
|
||||
{
|
||||
if (!Enum.TryParse<NotificationType>(typeRaw, ignoreCase: true, out var type))
|
||||
{
|
||||
throw new ArgumentException($"Invalid --type '{typeRaw}'. Expected 'email' or 'sms'.");
|
||||
}
|
||||
|
||||
var emails = SplitRecipients(emailsRaw);
|
||||
var phones = SplitRecipients(phonesRaw);
|
||||
|
||||
if (type == NotificationType.Email)
|
||||
{
|
||||
if (phones.Count > 0)
|
||||
{
|
||||
throw new ArgumentException("--phones is not valid for --type email; use --emails.");
|
||||
}
|
||||
|
||||
if (emails.Count == 0)
|
||||
{
|
||||
throw new ArgumentException("--emails is required for --type email.");
|
||||
}
|
||||
|
||||
return (type, emails, null);
|
||||
}
|
||||
|
||||
// Sms
|
||||
if (emails.Count > 0)
|
||||
{
|
||||
throw new ArgumentException("--emails is not valid for --type sms; use --phones.");
|
||||
}
|
||||
|
||||
if (phones.Count == 0)
|
||||
{
|
||||
throw new ArgumentException("--phones is required for --type sms.");
|
||||
}
|
||||
|
||||
return (type, Array.Empty<string>(), phones);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> SplitRecipients(string? raw) =>
|
||||
string.IsNullOrWhiteSpace(raw)
|
||||
? Array.Empty<string>()
|
||||
: raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
|
||||
|
||||
private static Command BuildDelete(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var idOption = new Option<int>("--id") { Description = "Notification list ID", Required = true };
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System.CommandLine;
|
||||
using System.CommandLine.Parsing;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;
|
||||
|
||||
@@ -138,7 +140,7 @@ public static class TemplateCommands
|
||||
var templateIdOption = new Option<int>("--template-id") { Description = "Template ID", Required = true };
|
||||
var nameOption = new Option<string>("--name") { Description = "Attribute name", Required = true };
|
||||
var dataTypeOption = new Option<string>("--data-type") { Description = "Data type", Required = true };
|
||||
var valueOption = new Option<string?>("--value") { Description = "Default value. For a List attribute, supply a JSON array (e.g. '[\"WO-1\",\"WO-2\"]')." };
|
||||
var valueOption = new Option<string?>("--value") { Description = "Default value. For a List attribute, supply a JSON array in native form: numeric/boolean elements unquoted (e.g. an Int32 list '[10,20,30]'), string elements quoted (e.g. '[\"WO-1\",\"WO-2\"]')." };
|
||||
var descOption = new Option<string?>("--description") { Description = "Description" };
|
||||
var sourceOption = new Option<string?>("--data-source") { Description = "Data source reference" };
|
||||
var elementTypeOption = new Option<string?>("--element-type") { Description = ElementTypeOptionDescription };
|
||||
@@ -181,7 +183,7 @@ public static class TemplateCommands
|
||||
var updateIdOption = new Option<int>("--id") { Description = "Attribute ID", Required = true };
|
||||
var updateNameOption = new Option<string>("--name") { Description = "Attribute name", Required = true };
|
||||
var updateDataTypeOption = new Option<string>("--data-type") { Description = "Data type", Required = true };
|
||||
var updateValueOption = new Option<string?>("--value") { Description = "Default value. For a List attribute, supply a JSON array (e.g. '[\"WO-1\",\"WO-2\"]')." };
|
||||
var updateValueOption = new Option<string?>("--value") { Description = "Default value. For a List attribute, supply a JSON array in native form: numeric/boolean elements unquoted (e.g. an Int32 list '[10,20,30]'), string elements quoted (e.g. '[\"WO-1\",\"WO-2\"]')." };
|
||||
var updateDescOption = new Option<string?>("--description") { Description = "Description" };
|
||||
var updateSourceOption = new Option<string?>("--data-source") { Description = "Data source reference" };
|
||||
var updateElementTypeOption = new Option<string?>("--element-type") { Description = ElementTypeOptionDescription };
|
||||
@@ -239,9 +241,38 @@ public static class TemplateCommands
|
||||
internal const string ElementTypeOptionDescription =
|
||||
"Element scalar type for a List attribute (String, Int32, Float, Double, Boolean, DateTime). Required when --data-type is List.";
|
||||
|
||||
/// <summary>The element scalar types permitted for a List attribute (matches the Management API).</summary>
|
||||
/// <summary>Shared description for the <c>--min-time-between-runs</c> option on script add/update.</summary>
|
||||
internal const string MinTimeBetweenRunsOptionDescription =
|
||||
"Minimum time between script runs (a throttle for triggered scripts; the re-fire interval for a WhileTrue trigger). "
|
||||
+ "Accepts a value with a unit suffix: ms, s/sec, or m/min (e.g. 500ms, 5s, 2min); a bare number is seconds. "
|
||||
+ "Omit, or pass 0 / a blank value, to leave it unset (no throttle).";
|
||||
|
||||
/// <summary>Shared description for the <c>--execution-timeout-seconds</c> option on script add/update.</summary>
|
||||
internal const string ExecutionTimeoutOptionDescription =
|
||||
"Per-script execution timeout in seconds. Omit (or pass a non-positive value) to use the site's global "
|
||||
+ "default (SiteRuntimeOptions.ScriptExecutionTimeoutSeconds).";
|
||||
|
||||
/// <summary>Shared description for the script <c>--trigger-kind</c> option on script add/update.</summary>
|
||||
internal const string ScriptTriggerKindOptionDescription =
|
||||
"Expression trigger analysis kind: advisory (default) or strict. "
|
||||
+ "Strict escalates a blank expression from a warning to a deploy-blocking error. "
|
||||
+ "Requires --trigger-config: with no config the kind is ignored (a warning is printed to stderr).";
|
||||
|
||||
/// <summary>Shared description for the alarm <c>--trigger-kind</c> option on alarm update.</summary>
|
||||
internal const string AlarmTriggerKindOptionDescription =
|
||||
"Expression trigger analysis kind: advisory (default) or strict. "
|
||||
+ "Requires --trigger-config: with no config the kind is ignored (a warning is printed to stderr).";
|
||||
|
||||
/// <summary>
|
||||
/// The element scalar types permitted for a List attribute — derived from the
|
||||
/// single source of truth, <see cref="AttributeValueCodec.IsValidElementType"/>,
|
||||
/// so the CLI never drifts from the codec/Management API.
|
||||
/// </summary>
|
||||
private static readonly string[] ValidElementScalars =
|
||||
{ "String", "Int32", "Float", "Double", "Boolean", "DateTime" };
|
||||
Enum.GetValues<DataType>()
|
||||
.Where(AttributeValueCodec.IsValidElementType)
|
||||
.Select(t => t.ToString())
|
||||
.ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// Validates the <c>--data-type</c> / <c>--element-type</c> combination client-side so
|
||||
@@ -268,7 +299,8 @@ public static class TemplateCommands
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!ValidElementScalars.Contains(elementType!.Trim(), StringComparer.OrdinalIgnoreCase))
|
||||
if (!Enum.TryParse<DataType>(elementType!.Trim(), ignoreCase: true, out var parsed)
|
||||
|| !AttributeValueCodec.IsValidElementType(parsed))
|
||||
{
|
||||
error = $"Invalid --element-type '{elementType}'. Valid List element scalars are: "
|
||||
+ string.Join(", ", ValidElementScalars) + ".";
|
||||
@@ -311,6 +343,102 @@ public static class TemplateCommands
|
||||
private static string? NormalizeElementType(string? elementType)
|
||||
=> string.IsNullOrWhiteSpace(elementType) ? null : elementType.Trim();
|
||||
|
||||
/// <summary>
|
||||
/// Parses the raw <c>--min-time-between-runs</c> value into a <see cref="TimeSpan"/>.
|
||||
/// A blank/absent value means "unset" (<paramref name="value"/> null → <c>null</c>, no error).
|
||||
/// Otherwise the value must be a positive integer with an optional unit suffix:
|
||||
/// <c>ms</c>, <c>s</c>/<c>sec</c>, or <c>m</c>/<c>min</c>; a bare number is interpreted as
|
||||
/// seconds (matching the UI duration input's default unit). A value of <c>0</c> resolves to
|
||||
/// <c>null</c> (unset), mirroring <c>DurationInput.Compose</c>. The unit set and "bare = seconds"
|
||||
/// default deliberately mirror the Central UI duration input so the two authoring surfaces agree.
|
||||
/// </summary>
|
||||
/// <param name="value">The raw flag value, or null when the flag was omitted.</param>
|
||||
/// <param name="duration">The parsed duration, or <c>null</c> for an absent/unset value.</param>
|
||||
/// <param name="error">A descriptive error message when parsing fails; otherwise null.</param>
|
||||
/// <returns><c>true</c> when the value is absent or parses cleanly; <c>false</c> on a malformed value.</returns>
|
||||
internal static bool TryParseMinTimeBetweenRuns(string? value, out TimeSpan? duration, out string? error)
|
||||
{
|
||||
duration = null;
|
||||
error = null;
|
||||
|
||||
var trimmed = value?.Trim();
|
||||
if (string.IsNullOrEmpty(trimmed))
|
||||
return true; // omitted → unset
|
||||
|
||||
// Split a trailing alphabetic unit suffix from the leading numeric part.
|
||||
var splitIndex = trimmed.Length;
|
||||
while (splitIndex > 0 && char.IsLetter(trimmed[splitIndex - 1]))
|
||||
splitIndex--;
|
||||
|
||||
var numberPart = trimmed[..splitIndex];
|
||||
var unitPart = trimmed[splitIndex..].ToLowerInvariant();
|
||||
|
||||
if (!long.TryParse(numberPart, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var amount)
|
||||
|| amount < 0)
|
||||
{
|
||||
error = $"Invalid --min-time-between-runs '{value}'. Expected a non-negative number with an optional "
|
||||
+ "unit suffix (ms, s/sec, m/min); a bare number is seconds (e.g. 500ms, 5s, 2min).";
|
||||
return false;
|
||||
}
|
||||
|
||||
var factorMs = unitPart switch
|
||||
{
|
||||
"ms" => 1L,
|
||||
"" or "s" or "sec" => 1000L,
|
||||
"m" or "min" => 60000L,
|
||||
_ => -1L,
|
||||
};
|
||||
|
||||
if (factorMs < 0)
|
||||
{
|
||||
error = $"Invalid --min-time-between-runs unit in '{value}'. Valid units are: ms, s/sec, m/min.";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Guard against overflow: reject if amount * factorMs would exceed TimeSpan.MaxValue (in ms).
|
||||
// The divide is safe because factorMs is always >= 1.
|
||||
if (amount > TimeSpan.MaxValue.TotalMilliseconds / factorMs)
|
||||
{
|
||||
error = $"Invalid --min-time-between-runs '{value}': value is too large.";
|
||||
return false;
|
||||
}
|
||||
|
||||
// 0 (with or without a unit) → unset, mirroring DurationInput.Compose's non-positive handling.
|
||||
duration = amount == 0 ? null : TimeSpan.FromMilliseconds(amount * factorMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether <c>--trigger-kind</c> was supplied without a <c>--trigger-config</c>.
|
||||
/// In that case <see cref="TriggerConfigJson.InjectAnalysisKind"/> has no JSON object to inject
|
||||
/// into and silently drops the kind (#257) — the caller should warn the user.
|
||||
/// </summary>
|
||||
/// <param name="triggerConfig">The raw <c>--trigger-config</c> JSON value, or null when absent.</param>
|
||||
/// <param name="triggerKind">The raw <c>--trigger-kind</c> value, or null when absent.</param>
|
||||
/// <returns><c>true</c> when a kind was given but no config — i.e. the kind will be ignored.</returns>
|
||||
internal static bool TriggerKindWillBeIgnored(string? triggerConfig, string? triggerKind)
|
||||
=> !string.IsNullOrWhiteSpace(triggerKind) && string.IsNullOrWhiteSpace(triggerConfig);
|
||||
|
||||
/// <summary>
|
||||
/// Warns (to stderr) when <c>--trigger-kind</c> is supplied without a <c>--trigger-config</c>
|
||||
/// (see <see cref="TriggerKindWillBeIgnored"/>). The command still proceeds — the kind is
|
||||
/// advisory metadata, not a required field — but the user is told it had no effect so they are
|
||||
/// not surprised that a <c>strict</c> request did not take. Warn-and-continue (rather than a hard
|
||||
/// error) keeps the flag combination non-fatal: a script/alarm is still created, just without the
|
||||
/// requested analysis kind.
|
||||
/// </summary>
|
||||
/// <param name="triggerConfig">The raw <c>--trigger-config</c> JSON value, or null when absent.</param>
|
||||
/// <param name="triggerKind">The raw <c>--trigger-kind</c> value, or null when absent.</param>
|
||||
private static void WarnIfTriggerKindIgnored(string? triggerConfig, string? triggerKind)
|
||||
{
|
||||
if (TriggerKindWillBeIgnored(triggerConfig, triggerKind))
|
||||
{
|
||||
Console.Error.WriteLine(
|
||||
$"warning: --trigger-kind '{triggerKind!.Trim()}' was ignored because no --trigger-config was supplied. "
|
||||
+ "The analysis kind is written into the trigger-config JSON, so it has no effect without one.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Command BuildAlarm(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
{
|
||||
var group = new Command("alarm") { Description = "Manage template alarms" };
|
||||
@@ -407,7 +535,7 @@ public static class TemplateCommands
|
||||
// M9-T28b: --trigger-kind for update (same semantics as add)
|
||||
var updateTriggerKindOption = new Option<string?>("--trigger-kind")
|
||||
{
|
||||
Description = "Expression trigger analysis kind: advisory (default) or strict."
|
||||
Description = AlarmTriggerKindOptionDescription
|
||||
};
|
||||
|
||||
var updateCmd = new Command("update") { Description = "Update a template alarm" };
|
||||
@@ -421,8 +549,10 @@ public static class TemplateCommands
|
||||
updateCmd.Add(updateTriggerKindOption);
|
||||
updateCmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
var rawConfig = result.GetValue(updateTriggerConfigOption);
|
||||
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateTriggerKindOption));
|
||||
var triggerConfig = TriggerConfigJson.InjectAnalysisKind(
|
||||
result.GetValue(updateTriggerConfigOption),
|
||||
rawConfig,
|
||||
result.GetValue(updateTriggerKindOption));
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
@@ -532,12 +662,12 @@ public static class TemplateCommands
|
||||
|
||||
var paramsOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON" };
|
||||
var returnOption = new Option<string?>("--return-def") { Description = "Return definition JSON" };
|
||||
var minTimeOption = new Option<string?>("--min-time-between-runs") { Description = MinTimeBetweenRunsOptionDescription };
|
||||
var execTimeoutOption = new Option<int?>("--execution-timeout-seconds") { Description = ExecutionTimeoutOptionDescription };
|
||||
// M9-T28b: analysis kind for Expression triggers (advisory|strict; default advisory).
|
||||
var scriptTriggerKindOption = new Option<string?>("--trigger-kind")
|
||||
{
|
||||
Description = "Expression trigger analysis kind: advisory (default) or strict. " +
|
||||
"Strict escalates a blank expression from a warning to a deploy-blocking error. " +
|
||||
"Used with --trigger-config or appended to a built config when --trigger-type is Expression."
|
||||
Description = ScriptTriggerKindOptionDescription
|
||||
};
|
||||
|
||||
var addCmd = new Command("add") { Description = "Add a script to a template" };
|
||||
@@ -549,11 +679,21 @@ public static class TemplateCommands
|
||||
addCmd.Add(lockedOption);
|
||||
addCmd.Add(paramsOption);
|
||||
addCmd.Add(returnOption);
|
||||
addCmd.Add(minTimeOption);
|
||||
addCmd.Add(execTimeoutOption);
|
||||
addCmd.Add(scriptTriggerKindOption);
|
||||
addCmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
if (!TryParseMinTimeBetweenRuns(result.GetValue(minTimeOption), out var minTime, out var minTimeError))
|
||||
{
|
||||
OutputFormatter.WriteError(minTimeError!, "INVALID_ARGUMENT");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var rawConfig = result.GetValue(triggerConfigOption);
|
||||
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(scriptTriggerKindOption));
|
||||
var triggerConfig = TriggerConfigJson.InjectAnalysisKind(
|
||||
result.GetValue(triggerConfigOption),
|
||||
rawConfig,
|
||||
result.GetValue(scriptTriggerKindOption));
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
@@ -565,7 +705,9 @@ public static class TemplateCommands
|
||||
triggerConfig,
|
||||
result.GetValue(lockedOption),
|
||||
result.GetValue(paramsOption),
|
||||
result.GetValue(returnOption)));
|
||||
result.GetValue(returnOption),
|
||||
minTime,
|
||||
result.GetValue(execTimeoutOption)));
|
||||
});
|
||||
group.Add(addCmd);
|
||||
|
||||
@@ -579,10 +721,12 @@ public static class TemplateCommands
|
||||
|
||||
var updateParamsOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON" };
|
||||
var updateReturnOption = new Option<string?>("--return-def") { Description = "Return definition JSON" };
|
||||
var updateMinTimeOption = new Option<string?>("--min-time-between-runs") { Description = MinTimeBetweenRunsOptionDescription };
|
||||
var updateExecTimeoutOption = new Option<int?>("--execution-timeout-seconds") { Description = ExecutionTimeoutOptionDescription };
|
||||
// M9-T28b: --trigger-kind for update (same semantics as add)
|
||||
var updateScriptTriggerKindOption = new Option<string?>("--trigger-kind")
|
||||
{
|
||||
Description = "Expression trigger analysis kind: advisory (default) or strict."
|
||||
Description = ScriptTriggerKindOptionDescription
|
||||
};
|
||||
|
||||
var updateCmd = new Command("update") { Description = "Update a template script" };
|
||||
@@ -594,11 +738,21 @@ public static class TemplateCommands
|
||||
updateCmd.Add(updateLockedOption);
|
||||
updateCmd.Add(updateParamsOption);
|
||||
updateCmd.Add(updateReturnOption);
|
||||
updateCmd.Add(updateMinTimeOption);
|
||||
updateCmd.Add(updateExecTimeoutOption);
|
||||
updateCmd.Add(updateScriptTriggerKindOption);
|
||||
updateCmd.SetAction(async (ParseResult result) =>
|
||||
{
|
||||
if (!TryParseMinTimeBetweenRuns(result.GetValue(updateMinTimeOption), out var minTime, out var minTimeError))
|
||||
{
|
||||
OutputFormatter.WriteError(minTimeError!, "INVALID_ARGUMENT");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var rawConfig = result.GetValue(updateTriggerConfigOption);
|
||||
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateScriptTriggerKindOption));
|
||||
var triggerConfig = TriggerConfigJson.InjectAnalysisKind(
|
||||
result.GetValue(updateTriggerConfigOption),
|
||||
rawConfig,
|
||||
result.GetValue(updateScriptTriggerKindOption));
|
||||
return await CommandHelpers.ExecuteCommandAsync(
|
||||
result, urlOption, formatOption, usernameOption, passwordOption,
|
||||
@@ -610,7 +764,9 @@ public static class TemplateCommands
|
||||
triggerConfig,
|
||||
result.GetValue(updateLockedOption),
|
||||
result.GetValue(updateParamsOption),
|
||||
result.GetValue(updateReturnOption)));
|
||||
result.GetValue(updateReturnOption),
|
||||
minTime,
|
||||
result.GetValue(updateExecTimeoutOption)));
|
||||
});
|
||||
group.Add(updateCmd);
|
||||
|
||||
|
||||
@@ -271,7 +271,7 @@ scadabridge --url <url> template alarm update --id <int> --name <string> --trigg
|
||||
| `--description` | no | Description |
|
||||
| `--trigger-config` | no | Trigger configuration JSON |
|
||||
| `--locked` | no | Lock the alarm in derived templates |
|
||||
| `--trigger-kind` | no | Expression-trigger analysis kind: `advisory` (default) or `strict`. Ignored for non-`Expression` trigger types. |
|
||||
| `--trigger-kind` | no | Expression-trigger analysis kind: `advisory` (default) or `strict`. Ignored for non-`Expression` trigger types. **Requires `--trigger-config`** — the kind is written into the trigger-config JSON, so on `update` it has no effect without one (the CLI prints a warning to stderr and continues). |
|
||||
|
||||
#### `template alarm delete`
|
||||
|
||||
@@ -325,7 +325,7 @@ scadabridge --url <url> template native-alarm-source remove --id <int>
|
||||
Add a script to a template.
|
||||
|
||||
```sh
|
||||
scadabridge --url <url> template script add --template-id <int> --name <string> --trigger-type <string> --code <string> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>] [--trigger-kind <kind>]
|
||||
scadabridge --url <url> template script add --template-id <int> --name <string> --trigger-type <string> --code <string> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>] [--min-time-between-runs <duration>] [--execution-timeout-seconds <int>] [--trigger-kind <kind>]
|
||||
```
|
||||
|
||||
| Option | Required | Description |
|
||||
@@ -338,7 +338,9 @@ scadabridge --url <url> template script add --template-id <int> --name <string>
|
||||
| `--locked` | no | Lock the script in derived templates |
|
||||
| `--parameters` | no | Parameter definitions JSON |
|
||||
| `--return-def` | no | Return definition JSON |
|
||||
| `--trigger-kind` | no | Expression-trigger analysis kind: `advisory` (default) or `strict`. Only meaningful when `--trigger-type` is `Expression`. |
|
||||
| `--min-time-between-runs` | no | Minimum time between runs — a throttle for triggered scripts, or the re-fire interval for a `WhileTrue` trigger. Accepts a unit suffix `ms`, `s`/`sec`, or `m`/`min` (e.g. `500ms`, `5s`, `2min`); a bare number is seconds. Omit, or pass `0`, to leave it unset (no throttle). |
|
||||
| `--execution-timeout-seconds` | no | Per-script execution timeout in seconds. Omit (or pass a non-positive value) to use the site's global default (`SiteRuntimeOptions.ScriptExecutionTimeoutSeconds`). |
|
||||
| `--trigger-kind` | no | Expression-trigger analysis kind: `advisory` (default) or `strict`. Only meaningful when `--trigger-type` is `Expression`. **Requires `--trigger-config`** — the kind is written into the trigger-config JSON, so passing `--trigger-kind` without `--trigger-config` has no effect (the CLI prints a warning to stderr and continues). |
|
||||
|
||||
#### `template script update`
|
||||
|
||||
@@ -346,7 +348,7 @@ Update a script on a template. An update **replaces** the whole entity — every
|
||||
field below must be supplied with its post-update value, even if unchanged.
|
||||
|
||||
```sh
|
||||
scadabridge --url <url> template script update --id <int> --name <string> --trigger-type <string> --code <string> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>] [--trigger-kind <kind>]
|
||||
scadabridge --url <url> template script update --id <int> --name <string> --trigger-type <string> --code <string> [--trigger-config <json>] [--locked] [--parameters <json>] [--return-def <json>] [--min-time-between-runs <duration>] [--execution-timeout-seconds <int>] [--trigger-kind <kind>]
|
||||
```
|
||||
|
||||
| Option | Required | Description |
|
||||
@@ -359,7 +361,9 @@ scadabridge --url <url> template script update --id <int> --name <string> --trig
|
||||
| `--locked` | no | Lock the script in derived templates |
|
||||
| `--parameters` | no | Parameter definitions JSON |
|
||||
| `--return-def` | no | Return definition JSON |
|
||||
| `--trigger-kind` | no | Expression-trigger analysis kind: `advisory` (default) or `strict`. Only meaningful when `--trigger-type` is `Expression`. |
|
||||
| `--min-time-between-runs` | no | Minimum time between runs (throttle / `WhileTrue` re-fire interval). Unit suffix `ms`, `s`/`sec`, or `m`/`min` (e.g. `500ms`, `5s`, `2min`); a bare number is seconds. Omit or `0` leaves it unset. As an update replaces the whole entity, omitting this **clears** any existing value. |
|
||||
| `--execution-timeout-seconds` | no | Per-script execution timeout in seconds; omit (or non-positive) uses the site default. As an update replaces the whole entity, omitting this **clears** any existing override. |
|
||||
| `--trigger-kind` | no | Expression-trigger analysis kind: `advisory` (default) or `strict`. Only meaningful when `--trigger-type` is `Expression`. **Requires `--trigger-config`** — without it the kind is ignored (the CLI warns to stderr and continues). |
|
||||
|
||||
#### `template script delete`
|
||||
|
||||
@@ -981,31 +985,47 @@ scadabridge --url <url> notification list
|
||||
|
||||
#### `notification create`
|
||||
|
||||
Create a notification list with one or more recipients.
|
||||
Create a notification list with one or more recipients. The `--type` flag selects the
|
||||
delivery channel and decides which recipient flag is required: `email` (the default)
|
||||
uses `--emails`; `sms` uses `--phones`. Supplying the wrong recipient flag for the
|
||||
channel is rejected before the command is sent.
|
||||
|
||||
```sh
|
||||
# Email list (default channel)
|
||||
scadabridge --url <url> notification create --name <string> --emails <email1,email2,...>
|
||||
|
||||
# SMS list
|
||||
scadabridge --url <url> notification create --name <string> --type sms --phones <e164a,e164b,...>
|
||||
```
|
||||
|
||||
| Option | Required | Description |
|
||||
|--------|----------|-------------|
|
||||
| `--name` | yes | Notification list name |
|
||||
| `--emails` | yes | Comma-separated list of recipient email addresses |
|
||||
| `--type` | no | Delivery channel: `email` or `sms` (case-insensitive; default `email`) |
|
||||
| `--emails` | conditional | Comma-separated recipient email addresses. **Required for `--type email`; rejected for `--type sms`.** |
|
||||
| `--phones` | conditional | Comma-separated recipient phone numbers in E.164. **Required for `--type sms`; rejected for `--type email`.** |
|
||||
|
||||
#### `notification update`
|
||||
|
||||
Update a notification list. An update **replaces** the whole entity — every required
|
||||
field below must be supplied, even if unchanged.
|
||||
field below must be supplied, even if unchanged. As with `create`, `--type` selects the
|
||||
channel and decides whether `--emails` or `--phones` is required.
|
||||
|
||||
```sh
|
||||
# Email list
|
||||
scadabridge --url <url> notification update --id <int> --name <string> --emails <email1,email2,...>
|
||||
|
||||
# SMS list
|
||||
scadabridge --url <url> notification update --id <int> --name <string> --type sms --phones <e164a,e164b,...>
|
||||
```
|
||||
|
||||
| Option | Required | Description |
|
||||
|--------|----------|-------------|
|
||||
| `--id` | yes | Notification list ID |
|
||||
| `--name` | yes | List name |
|
||||
| `--emails` | yes | Comma-separated list of recipient email addresses |
|
||||
| `--type` | no | Delivery channel: `email` or `sms` (case-insensitive; default `email`) |
|
||||
| `--emails` | conditional | Comma-separated recipient email addresses. **Required for `--type email`; rejected for `--type sms`.** |
|
||||
| `--phones` | conditional | Comma-separated recipient phone numbers in E.164. **Required for `--type sms`; rejected for `--type email`.** |
|
||||
|
||||
#### `notification delete`
|
||||
|
||||
@@ -1045,6 +1065,32 @@ scadabridge --url <url> notification smtp update --id <int> --server <string> --
|
||||
| `--tls-mode` | no | TLS mode: `None`, `StartTLS`, or `SSL` (preserves existing if omitted) |
|
||||
| `--credentials` | no | SMTP credentials — `username:password` for Basic, or client secret for OAuth2 (preserves existing if omitted) |
|
||||
|
||||
#### `notification sms list`
|
||||
|
||||
Show the current SMS (Twilio) configuration. The Twilio **Auth Token is never returned**
|
||||
— the listing reports it only as a `hasAuthToken` presence flag.
|
||||
|
||||
```sh
|
||||
scadabridge --url <url> notification sms list
|
||||
```
|
||||
|
||||
#### `notification sms update`
|
||||
|
||||
Update the SMS (Twilio) configuration.
|
||||
|
||||
```sh
|
||||
scadabridge --url <url> notification sms update --id <int> --account-sid <string> --from-number <string> [--messaging-service-sid <string>] [--api-base-url <string>] [--auth-token <string>]
|
||||
```
|
||||
|
||||
| Option | Required | Description |
|
||||
|--------|----------|-------------|
|
||||
| `--id` | yes | SMS config ID |
|
||||
| `--account-sid` | yes | Twilio Account SID |
|
||||
| `--from-number` | yes | Sender phone number (E.164) |
|
||||
| `--messaging-service-sid` | no | Twilio Messaging Service SID. **Omitting it CLEARS the stored value** (the update overwrites it). |
|
||||
| `--api-base-url` | no | API base URL override (preserves existing if omitted) |
|
||||
| `--auth-token` | no | Twilio Auth Token. **Omitting it PRESERVES the stored token.** Never printed back. |
|
||||
|
||||
---
|
||||
|
||||
### `security` — Security settings
|
||||
@@ -1698,6 +1744,7 @@ scadabridge --url <url> bundle export --output <path> [--passphrase <string>] [-
|
||||
| `--db-connections` | no | Comma-separated database-connection names to include |
|
||||
| `--notification-lists` | no | Comma-separated notification-list names to include |
|
||||
| `--smtp-configs` | no | Comma-separated SMTP host names to include |
|
||||
| `--sms-configs` | no | Comma-separated SMS provider account SIDs to include |
|
||||
| `--api-methods` | no | Comma-separated API-method names to include |
|
||||
| `--sites` | no | Comma-separated site identifiers (preferred) or friendly names to include |
|
||||
| `--instances` | no | Comma-separated instance unique-names to include (also pulls their site + bound data connections) |
|
||||
|
||||
@@ -91,18 +91,17 @@
|
||||
<div class="col-auto" data-test="filter-custom-range">
|
||||
@if (_model.TimeRange == AuditTimeRangePreset.Custom)
|
||||
{
|
||||
<div class="d-flex gap-1 align-items-end">
|
||||
<div>
|
||||
<label class="form-label small mb-1" for="audit-from">From (UTC)</label>
|
||||
<input id="audit-from" type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_model.CustomFromUtc" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="form-label small mb-1" for="audit-to">To (UTC)</label>
|
||||
<input id="audit-to" type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_model.CustomToUtc" />
|
||||
</div>
|
||||
</div>
|
||||
@* DateTimeRangeFilter is INPUT-ONLY: it surfaces the raw datetime-local
|
||||
picks (DateTimeKind.Unspecified) straight into the model's range fields.
|
||||
The local→UTC conversion still happens later in Apply()/LocalInputToUtc,
|
||||
exactly as before. IdPrefix="audit" keeps the audit-from/audit-to ids. *@
|
||||
<DateTimeRangeFilter From="_model.CustomFromUtc"
|
||||
FromChanged="@(v => _model.CustomFromUtc = v)"
|
||||
To="_model.CustomToUtc"
|
||||
ToChanged="@(v => _model.CustomToUtc = v)"
|
||||
IdPrefix="audit"
|
||||
FromLabel="From (UTC)"
|
||||
ToLabel="To (UTC)" />
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -72,24 +72,20 @@
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted small">Page @_pageNumber · @_rows.Count rows</span>
|
||||
@* CentralUI-032: keyset paging is naturally forward-only, but the
|
||||
in-component _cursorStack lets the user step back through previous
|
||||
pages by replaying the prior cursor. The Previous button is gated
|
||||
on the stack having at least one prior cursor — i.e. we are not on
|
||||
the first page. *@
|
||||
<div class="btn-group">
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
data-test="grid-prev-page"
|
||||
disabled="@(_loading || !CanGoBack)"
|
||||
@onclick="PrevPage">Previous page</button>
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
data-test="grid-next-page"
|
||||
disabled="@(_loading || _rows.Count < _pageSize)"
|
||||
@onclick="NextPage">Next page</button>
|
||||
</div>
|
||||
</div>
|
||||
@* CentralUI-032: keyset paging is naturally forward-only, but the
|
||||
in-component _cursorStack lets the user step back through previous
|
||||
pages by replaying the prior cursor. The Previous button is gated
|
||||
on CanGoBack (the stack having at least one prior cursor — i.e. we
|
||||
are not on the first page); HasNextPage mirrors the prior "short
|
||||
page = end" signal (a full page suggests more rows may follow). All
|
||||
cursor logic stays page-side; KeysetPager is purely presentational. *@
|
||||
<KeysetPager PageNumber="_pageNumber"
|
||||
RowCount="_rows.Count"
|
||||
CanGoBack="CanGoBack"
|
||||
HasNextPage="@(!_loading && _rows.Count >= _pageSize)"
|
||||
Disabled="_loading"
|
||||
OnPrevious="PrevPage"
|
||||
OnNext="NextPage" />
|
||||
</div>
|
||||
|
||||
@code {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
@if (_isVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" role="dialog" style="background-color: rgba(0,0,0,0.5);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1" role="dialog">
|
||||
<div class="modal-dialog modal-xl" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
@if (_isVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" role="dialog" style="background-color: rgba(0,0,0,0.5);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1" role="dialog">
|
||||
<div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
<NavMenu />
|
||||
</Nav>
|
||||
<RailFooter>
|
||||
@* T34b: dark-mode toggle sits in the rail footer alongside the session
|
||||
block. It is auth-agnostic (pure client-side theme) so it renders even
|
||||
on the login page. *@
|
||||
<DarkModeToggle />
|
||||
<AuthorizeView>
|
||||
<Authorized>
|
||||
@* CentralUI-024: claim type resolved via JwtTokenService. *@
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
<AuthorizeView Policy="@AuthorizationPolicies.RequireAdmin">
|
||||
<Authorized Context="notifAdminContext">
|
||||
<NavRailItem Href="/notifications/smtp" Text="SMTP Configuration" />
|
||||
<NavRailItem Href="/notifications/sms" Text="SMS Configuration" />
|
||||
</Authorized>
|
||||
</AuthorizeView>
|
||||
<AuthorizeView Policy="@AuthorizationPolicies.RequireDesign">
|
||||
|
||||
@@ -293,9 +293,9 @@ public partial class AuditLogPage : IDisposable
|
||||
/// <summary>The metrics rendered in the panel, in display order.</summary>
|
||||
private static readonly (string Metric, string Title, string? Unit)[] TrendMetrics =
|
||||
{
|
||||
("totalEventsLastHour", "Events / hour", null),
|
||||
("errorEventsLastHour", "Error events / hour", null),
|
||||
("backlogTotal", "Backlog", null),
|
||||
(KpiMetrics.AuditLog.TotalEventsLastHour, "Events / hour", null),
|
||||
(KpiMetrics.AuditLog.ErrorEventsLastHour, "Error events / hour", null),
|
||||
(KpiMetrics.AuditLog.BacklogTotal, "Backlog", null),
|
||||
};
|
||||
|
||||
/// <summary>Per-metric series state, keyed by the metric name.</summary>
|
||||
|
||||
+6
-25
@@ -58,21 +58,10 @@
|
||||
@bind="_filterAction"
|
||||
placeholder="e.g. Create" />
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label small" for="audit-filter-from">From</label>
|
||||
<input id="audit-filter-from"
|
||||
type="datetime-local"
|
||||
class="form-control form-control-sm"
|
||||
aria-label="From timestamp"
|
||||
@bind="_filterFrom" />
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label small" for="audit-filter-to">To</label>
|
||||
<input id="audit-filter-to"
|
||||
type="datetime-local"
|
||||
class="form-control form-control-sm"
|
||||
aria-label="To timestamp"
|
||||
@bind="_filterTo" />
|
||||
<div class="col-md-4">
|
||||
<DateTimeRangeFilter From="_filterFrom" FromChanged="(v => _filterFrom = v)"
|
||||
To="_filterTo" ToChanged="(v => _filterTo = v)"
|
||||
IdPrefix="audit-filter" />
|
||||
</div>
|
||||
<div class="col-md-2 d-flex gap-1">
|
||||
<button class="btn btn-primary btn-sm" @onclick="Search" disabled="@_searching">
|
||||
@@ -174,13 +163,7 @@
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted small">Page @_page of @TotalPages (@_totalCount total)</span>
|
||||
<div>
|
||||
<button class="btn btn-outline-secondary btn-sm me-1" @onclick="PrevPage" disabled="@(_page <= 1)">Previous</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="NextPage" disabled="@(!HasMore)">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
<OffsetPager Page="_page" PageChanged="OnPageChanged" HasNextPage="HasMore" TotalCount="_totalCount" PageSize="_pageSize" />
|
||||
}
|
||||
|
||||
@if (_modalEntry != null)
|
||||
@@ -238,7 +221,6 @@
|
||||
|
||||
private ToastNotification _toast = default!;
|
||||
|
||||
private int TotalPages => _pageSize > 0 ? Math.Max(1, (_totalCount + _pageSize - 1) / _pageSize) : 1;
|
||||
private bool HasMore => _page * _pageSize < _totalCount;
|
||||
|
||||
// Tracks the BundleImportId we last fetched against so a re-render with the
|
||||
@@ -310,8 +292,7 @@
|
||||
await FetchPage();
|
||||
}
|
||||
|
||||
private async Task PrevPage() { _page--; await FetchPage(); }
|
||||
private async Task NextPage() { _page++; await FetchPage(); }
|
||||
private async Task OnPageChanged(int page) { _page = page; await FetchPage(); }
|
||||
|
||||
private async Task FetchPage()
|
||||
{
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
|
||||
+6
-5
@@ -3,6 +3,7 @@
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types
|
||||
@@ -366,7 +367,7 @@
|
||||
@* Override edit modal *@
|
||||
@if (_editingAlarm != null)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-scrollable modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -405,7 +406,7 @@
|
||||
|
||||
@if (_editingError != null)
|
||||
{
|
||||
<div class="alert alert-danger small mt-2 mb-0">@_editingError</div>
|
||||
<div class="alert alert-danger small mt-2 mb-0" data-test="alarm-override-error">@_editingError</div>
|
||||
}
|
||||
</div>
|
||||
<div class="modal-footer justify-content-between">
|
||||
@@ -413,12 +414,13 @@
|
||||
@if (HasOverride(_editingAlarm.Name))
|
||||
{
|
||||
<button class="btn btn-outline-danger btn-sm"
|
||||
data-test="alarm-clear-from-modal"
|
||||
@onclick="() => ClearFromModal()"
|
||||
disabled="@_saving">Clear Override</button>
|
||||
}
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="CancelEditOverride">Cancel</button>
|
||||
<button class="btn btn-outline-secondary btn-sm" data-test="alarm-cancel-override" @onclick="CancelEditOverride">Cancel</button>
|
||||
<button class="btn btn-success btn-sm" data-test="alarm-save-override" @onclick="SaveOverrideFromModal" disabled="@_saving">Save Override</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1347,8 +1349,7 @@
|
||||
private bool HasNativeOverride(string sourceName) => _existingNativeOverrides.ContainsKey(sourceName);
|
||||
|
||||
private IEnumerable<DataConnection> AlarmCapableConnections() =>
|
||||
_siteConnections.Where(c => string.Equals(c.Protocol, "OpcUa", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(c.Protocol, "MxGateway", StringComparison.OrdinalIgnoreCase));
|
||||
_siteConnections.Where(c => AlarmCapableProtocols.IsAlarmCapable(c.Protocol));
|
||||
|
||||
private async Task SaveNativeOverride(string sourceName)
|
||||
{
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
|
||||
@@ -42,12 +42,6 @@
|
||||
|
||||
<ToastNotification @ref="_toast" />
|
||||
|
||||
<MoveDataConnectionDialog @bind-IsVisible="_showMoveDialog"
|
||||
ConnectionId="_moveConnectionId"
|
||||
ConnectionName="@_moveConnectionName"
|
||||
SiteOptions="MoveTargetSiteOptions()"
|
||||
OnMoved="OnConnectionMoved" />
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<LoadingSpinner IsLoading="true" />
|
||||
@@ -425,37 +419,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ── M9-T24b: Move connection to another site ──
|
||||
// The dialog dispatches MoveDataConnectionCommand through the guard-running
|
||||
// ManagementActor path (IDataConnectionMoveService) — NOT a direct repository
|
||||
// write — so the server enforces the Designer gate and every move guard. The
|
||||
// page only opens the dialog, supplies the candidate target sites (the current
|
||||
// site excluded), and reloads the tree once the move succeeds.
|
||||
private bool _showMoveDialog;
|
||||
private int _moveConnectionId;
|
||||
private int _moveConnectionSiteId;
|
||||
private string _moveConnectionName = string.Empty;
|
||||
|
||||
private void OpenMoveDialog(DataConnection conn)
|
||||
// ── M9-T24b / T33b: Move connection to another site ──
|
||||
// Opened via IDialogService.ShowAsync. The body dispatches MoveDataConnectionCommand
|
||||
// through the guard-running ManagementActor path (IDataConnectionMoveService) — NOT
|
||||
// a direct repository write — so the server enforces the Designer gate and every
|
||||
// move guard, showing any guard error inline and staying open. On success the body
|
||||
// closes with true; the page then toasts and reloads the tree.
|
||||
private async Task OpenMoveDialog(DataConnection conn)
|
||||
{
|
||||
_moveConnectionId = conn.Id;
|
||||
_moveConnectionSiteId = conn.SiteId;
|
||||
_moveConnectionName = conn.Name;
|
||||
_showMoveDialog = true;
|
||||
var connId = conn.Id;
|
||||
var connName = conn.Name;
|
||||
var options = MoveTargetSiteOptions(conn.SiteId);
|
||||
var moved = await Dialog.ShowAsync<bool>(
|
||||
$"Move '{connName}' to site…",
|
||||
ctx => @<MoveDataConnectionDialog Context="ctx"
|
||||
ConnectionId="connId"
|
||||
ConnectionName="@connName"
|
||||
SiteOptions="options" />);
|
||||
if (moved)
|
||||
{
|
||||
_toast.ShowSuccess($"Connection '{connName}' moved.");
|
||||
await LoadDataAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// Candidate target sites for the move: every site EXCEPT the connection's
|
||||
// current one. Sourced from the already-loaded tree roots (each root is a site).
|
||||
private IEnumerable<(int Id, string Label)> MoveTargetSiteOptions() =>
|
||||
private IEnumerable<(int Id, string Label)> MoveTargetSiteOptions(int currentSiteId) =>
|
||||
_treeRoots
|
||||
.Where(r => r.SiteId is int sid && sid != _moveConnectionSiteId)
|
||||
.Select(r => (r.SiteId!.Value, r.Label));
|
||||
|
||||
private async Task OnConnectionMoved()
|
||||
{
|
||||
_toast.ShowSuccess($"Connection '{_moveConnectionName}' moved.");
|
||||
await LoadDataAsync();
|
||||
}
|
||||
.Where(r => r.SiteId is int sid && sid != currentSiteId)
|
||||
.Select(r => (r.SiteId!.Value, r.Label))
|
||||
.ToList();
|
||||
|
||||
// M9-T25: enum → Bootstrap badge class. Mirrors the Health dashboard's
|
||||
// GetConnectionHealthBadge (Components/Pages/Monitoring/Health.razor) so the
|
||||
|
||||
@@ -93,10 +93,13 @@
|
||||
<td>@(string.IsNullOrWhiteSpace(s.Scope) ? "—" : s.Scope)</td>
|
||||
<td><code>lib:@s.Name</code></td>
|
||||
<td class="text-end">
|
||||
@* Row actions are disabled while the editor is open so the
|
||||
row under edit (and its siblings) can't be deleted out from
|
||||
under the form, and while a delete is in flight (_busy). *@
|
||||
<button class="btn btn-outline-primary btn-sm me-1"
|
||||
@onclick="() => BeginEdit(s)">Edit</button>
|
||||
@onclick="() => BeginEdit(s)" disabled="@(_editing || _busy)">Edit</button>
|
||||
<button class="btn btn-outline-danger btn-sm"
|
||||
@onclick="() => DeleteSchema(s)">Delete</button>
|
||||
@onclick="() => DeleteSchema(s)" disabled="@(_editing || _busy)">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
@@ -208,21 +211,34 @@
|
||||
|
||||
private async Task DeleteSchema(SharedSchema schema)
|
||||
{
|
||||
// In-flight guard: an editor-open row action is already disabled in the markup,
|
||||
// but the _busy gate is the authoritative guard against a double-invoked delete
|
||||
// (and mirrors the Save path's guard).
|
||||
if (_busy) return;
|
||||
|
||||
var confirmed = await Dialog.ConfirmAsync(
|
||||
"Delete Schema",
|
||||
$"Delete library schema '{schema.Name}'? References to lib:{schema.Name} will no longer resolve.",
|
||||
danger: true);
|
||||
if (!confirmed) return;
|
||||
|
||||
var result = await SchemaLibraryService.DeleteAsync(schema.Id);
|
||||
if (result.Success)
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
_toast.ShowSuccess($"Schema '{schema.Name}' deleted.");
|
||||
await LoadAsync();
|
||||
var result = await SchemaLibraryService.DeleteAsync(schema.Id);
|
||||
if (result.Success)
|
||||
{
|
||||
_toast.ShowSuccess($"Schema '{schema.Name}' deleted.");
|
||||
await LoadAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_toast.ShowError(result.Error ?? "Delete failed.");
|
||||
}
|
||||
}
|
||||
else
|
||||
finally
|
||||
{
|
||||
_toast.ShowError(result.Error ?? "Delete failed.");
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
|
||||
@@ -129,8 +130,8 @@
|
||||
private string? _scriptParameters;
|
||||
private string? _scriptReturn;
|
||||
private bool _scriptIsLocked;
|
||||
// Round-tripped from the loaded script so UI edits preserve a timeout set
|
||||
// via Transport import (no authoring control in the UI — scoped out).
|
||||
// Per-script execution-timeout override (seconds). Bound to the "Execution timeout"
|
||||
// input on the trigger tab; null/0 means "use the site's global default" (#54).
|
||||
private int? _scriptExecutionTimeoutSeconds;
|
||||
private string? _scriptFormError;
|
||||
private string _scriptModalTab = "trigger"; // "trigger" | "code" | "parameters" | "return"
|
||||
@@ -187,7 +188,7 @@
|
||||
_alarms = (await TemplateEngineRepository.GetAlarmsByTemplateIdAsync(Id)).ToList();
|
||||
_nativeSources = (await TemplateEngineRepository.GetNativeAlarmSourcesByTemplateIdAsync(Id)).ToList();
|
||||
_alarmCapableConnections = (await CentralUiRepository.GetAllDataConnectionsAsync())
|
||||
.Where(c => IsAlarmCapable(c.Protocol))
|
||||
.Where(c => AlarmCapableProtocols.IsAlarmCapable(c.Protocol))
|
||||
.GroupBy(c => c.Name, StringComparer.OrdinalIgnoreCase)
|
||||
.Select(g => g.First())
|
||||
.OrderBy(c => c.Name, StringComparer.OrdinalIgnoreCase)
|
||||
@@ -694,7 +695,7 @@
|
||||
@if (_showAttrForm)
|
||||
{
|
||||
var editing = _editAttrId.HasValue;
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-scrollable">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -954,7 +955,7 @@
|
||||
@if (_showAlarmForm)
|
||||
{
|
||||
var editing = _editAlarmId.HasValue;
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-scrollable">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -1077,7 +1078,7 @@
|
||||
@if (_showNativeSourceForm)
|
||||
{
|
||||
var editing = _editNativeSourceId.HasValue;
|
||||
<div class="modal d-block" tabindex="-1" style="background: rgba(0,0,0,.5);">
|
||||
<div class="modal d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -1193,10 +1194,6 @@
|
||||
}
|
||||
};
|
||||
|
||||
private static bool IsAlarmCapable(string? protocol) =>
|
||||
string.Equals(protocol, "OpcUa", StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(protocol, "MxGateway", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private void BeginAddNativeSource()
|
||||
{
|
||||
_showNativeSourceForm = true;
|
||||
@@ -1299,7 +1296,7 @@
|
||||
@if (_showScriptForm)
|
||||
{
|
||||
var editingScript = _editScriptId.HasValue;
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1">
|
||||
<div class="modal-dialog modal-dialog-scrollable script-editor-modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
@@ -1400,6 +1397,19 @@
|
||||
}
|
||||
</div>
|
||||
}
|
||||
<div class="mt-3">
|
||||
<label class="form-label">Execution timeout</label>
|
||||
<div class="input-group" style="max-width: 280px;">
|
||||
<input type="number" min="1" step="1" class="form-control"
|
||||
placeholder="(site default)"
|
||||
@bind="_scriptExecutionTimeoutSeconds" @bind:event="oninput" />
|
||||
<span class="input-group-text">seconds</span>
|
||||
</div>
|
||||
<div class="form-text">
|
||||
Per-script execution timeout. Leave blank (or 0) to use the
|
||||
site's global default.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display: @(_scriptModalTab == "code" ? "block" : "none")">
|
||||
<MonacoEditor @ref="_scriptEditor" Value="@_scriptCode" ValueChanged="@(v => _scriptCode = v)"
|
||||
@@ -2057,8 +2067,7 @@
|
||||
_scriptParameters = script.ParameterDefinitions;
|
||||
_scriptReturn = script.ReturnDefinition;
|
||||
_scriptIsLocked = script.IsLocked;
|
||||
// Preserve any timeout set via Transport import — the UI has no authoring
|
||||
// control for this field, so we round-trip the loaded value unchanged.
|
||||
// Load the per-script execution timeout into the authoring input (null = use site default).
|
||||
_scriptExecutionTimeoutSeconds = script.ExecutionTimeoutSeconds;
|
||||
_scriptModalTab = "trigger";
|
||||
ResetScriptTestRun();
|
||||
@@ -2132,6 +2141,12 @@
|
||||
_ => "Error"
|
||||
};
|
||||
|
||||
// Normalizes the execution-timeout input: a null or non-positive value means
|
||||
// "use the site default", so it is stored as null (matching the Site Runtime's
|
||||
// own ≤0-means-default handling and the entity's documented contract).
|
||||
private static int? NormalizeExecutionTimeout(int? seconds)
|
||||
=> seconds is > 0 ? seconds : null;
|
||||
|
||||
private async Task SaveScript()
|
||||
{
|
||||
if (_selectedTemplate == null) return;
|
||||
@@ -2153,9 +2168,7 @@
|
||||
ReturnDefinition = _scriptReturn,
|
||||
IsLocked = _scriptIsLocked,
|
||||
MinTimeBetweenRuns = DurationInput.Compose(_scriptMinTimeValue, _scriptMinTimeUnit),
|
||||
// Round-trip the loaded value — no UI control, so preserve
|
||||
// any timeout set via Transport import unchanged.
|
||||
ExecutionTimeoutSeconds = _scriptExecutionTimeoutSeconds,
|
||||
ExecutionTimeoutSeconds = NormalizeExecutionTimeout(_scriptExecutionTimeoutSeconds),
|
||||
IsInherited = existing.IsInherited,
|
||||
LockedInDerived = existing.LockedInDerived,
|
||||
};
|
||||
@@ -2181,7 +2194,8 @@
|
||||
ParameterDefinitions = _scriptParameters,
|
||||
ReturnDefinition = _scriptReturn,
|
||||
IsLocked = _scriptIsLocked,
|
||||
MinTimeBetweenRuns = DurationInput.Compose(_scriptMinTimeValue, _scriptMinTimeUnit)
|
||||
MinTimeBetweenRuns = DurationInput.Compose(_scriptMinTimeValue, _scriptMinTimeUnit),
|
||||
ExecutionTimeoutSeconds = NormalizeExecutionTimeout(_scriptExecutionTimeoutSeconds)
|
||||
};
|
||||
|
||||
var addResult = await TemplateService.AddScriptAsync(_selectedTemplate.Id, script, user);
|
||||
|
||||
@@ -17,33 +17,6 @@
|
||||
<div class="container-fluid mt-3">
|
||||
<ToastNotification @ref="_toast" />
|
||||
|
||||
<RenameFolderDialog @bind-IsVisible="_showRenameFolderDialog"
|
||||
FolderId="_renameFolderId"
|
||||
InitialName="@_renameFolderInitialName"
|
||||
ErrorMessage="@_renameFolderError"
|
||||
OnSubmit="SubmitRenameFolder" />
|
||||
|
||||
<MoveTemplateDialog @bind-IsVisible="_showMoveTemplateDialog"
|
||||
TemplateId="_moveTemplateId"
|
||||
TemplateName="@_moveTemplateName"
|
||||
FolderOptions="EnumerateFolderOptions()"
|
||||
ErrorMessage="@_moveTemplateError"
|
||||
OnSubmit="SubmitMoveTemplate" />
|
||||
|
||||
<MoveFolderDialog @bind-IsVisible="_showMoveFolderDialog"
|
||||
FolderId="_moveFolderId"
|
||||
FolderName="@_moveFolderName"
|
||||
FolderOptions="EnumerateFolderOptionsExcluding(_moveFolderId)"
|
||||
ErrorMessage="@_moveFolderError"
|
||||
OnSubmit="SubmitMoveFolder" />
|
||||
|
||||
<ComposeIntoDialog @bind-IsVisible="_showComposeDialog"
|
||||
SourceTemplateId="_composeSourceId"
|
||||
SourceName="@_composeSourceName"
|
||||
ParentOptions="EnumerateComposableParents(_composeSourceId)"
|
||||
ErrorMessage="@_composeError"
|
||||
OnSubmit="SubmitCompose" />
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<LoadingSpinner IsLoading="true" />
|
||||
@@ -108,7 +81,8 @@
|
||||
SelectionMode="TreeViewSelectionMode.Single"
|
||||
ExtraTemplateChildren="BuildCompositionLeavesFor"
|
||||
Filter="@_searchText"
|
||||
StorageKey="templates-tree">
|
||||
StorageKey="templates-tree"
|
||||
OnNodeContextMenuOpened="DismissRootContextMenu">
|
||||
<NodeContent Context="node">
|
||||
@RenderNodeLabel(node)
|
||||
</NodeContent>
|
||||
@@ -125,8 +99,10 @@
|
||||
{
|
||||
<div class="tv-ctx-overlay" @onclick="DismissRootContextMenu"
|
||||
style="position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:1049;background:transparent;"></div>
|
||||
<div class="dropdown-menu show tv-root-menu" @onclick="DismissRootContextMenu"
|
||||
style="position:fixed;top:@(_rootMenuY)px;left:@(_rootMenuX)px;z-index:1050;">
|
||||
<div class="dropdown-menu show tv-root-menu" tabindex="-1" @ref="_rootMenuRef"
|
||||
@onclick="DismissRootContextMenu"
|
||||
@onkeydown="OnRootMenuKeyDown"
|
||||
style="position:fixed;top:@(_rootMenuY)px;left:@(_rootMenuX)px;z-index:1050;outline:none;">
|
||||
<button class="dropdown-item" @onclick="() => OpenNewFolderDialog(null)">New Folder</button>
|
||||
<button class="dropdown-item" @onclick='() => NavigationManager.NavigateTo("/design/templates/create")'>New Template</button>
|
||||
</div>
|
||||
@@ -314,34 +290,26 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Move-template dialog state
|
||||
private bool _showMoveTemplateDialog;
|
||||
private int _moveTemplateId;
|
||||
private string _moveTemplateName = string.Empty;
|
||||
private string? _moveTemplateError;
|
||||
|
||||
private void OpenMoveTemplateDialog(int templateId, string label)
|
||||
// Move-template dialog: opened via IDialogService.ShowAsync. The body returns
|
||||
// the picked folder id (null = Root) on Move, or null on Cancel; validation runs
|
||||
// here after the dialog closes and surfaces server guard failures via a toast.
|
||||
private async Task OpenMoveTemplateDialog(int templateId, string label)
|
||||
{
|
||||
_moveTemplateId = templateId;
|
||||
_moveTemplateName = label;
|
||||
_moveTemplateError = null;
|
||||
_showMoveTemplateDialog = true;
|
||||
}
|
||||
var result = await Dialog.ShowAsync<MoveTemplateDialog.MoveTemplateResult>(
|
||||
$"Move '{label}' to…",
|
||||
ctx => @<MoveTemplateDialog Context="ctx" FolderOptions="EnumerateFolderOptions()" />);
|
||||
if (result is null) return;
|
||||
|
||||
private async Task SubmitMoveTemplate((int TemplateId, int? NewFolderId) req)
|
||||
{
|
||||
_moveTemplateError = null;
|
||||
var user = await GetCurrentUserAsync();
|
||||
var result = await TemplateService.MoveTemplateAsync(req.TemplateId, req.NewFolderId, user);
|
||||
if (result.IsSuccess)
|
||||
var moved = await TemplateService.MoveTemplateAsync(templateId, result.NewFolderId, user);
|
||||
if (moved.IsSuccess)
|
||||
{
|
||||
_showMoveTemplateDialog = false;
|
||||
_toast.ShowSuccess($"Template '{_moveTemplateName}' moved.");
|
||||
_toast.ShowSuccess($"Template '{label}' moved.");
|
||||
await LoadTemplatesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_moveTemplateError = result.Error;
|
||||
_toast.ShowError(moved.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,34 +341,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Move-folder dialog state
|
||||
private bool _showMoveFolderDialog;
|
||||
private int _moveFolderId;
|
||||
private string _moveFolderName = string.Empty;
|
||||
private string? _moveFolderError;
|
||||
|
||||
private void OpenMoveFolderDialog(int folderId, string label)
|
||||
// Move-folder dialog: opened via IDialogService.ShowAsync. The picker prunes the
|
||||
// folder + its descendants (server still validates cycles). The body returns the
|
||||
// picked parent id (null = Root) on Move, or null on Cancel; server guard failures
|
||||
// surface via a toast.
|
||||
private async Task OpenMoveFolderDialog(int folderId, string label)
|
||||
{
|
||||
_moveFolderId = folderId;
|
||||
_moveFolderName = label;
|
||||
_moveFolderError = null;
|
||||
_showMoveFolderDialog = true;
|
||||
}
|
||||
var result = await Dialog.ShowAsync<MoveFolderDialog.MoveFolderResult>(
|
||||
$"Move '{label}' to…",
|
||||
ctx => @<MoveFolderDialog Context="ctx" FolderOptions="EnumerateFolderOptionsExcluding(folderId)" />);
|
||||
if (result is null) return;
|
||||
|
||||
private async Task SubmitMoveFolder((int FolderId, int? NewParentId) req)
|
||||
{
|
||||
_moveFolderError = null;
|
||||
var user = await GetCurrentUserAsync();
|
||||
var result = await TemplateFolderService.MoveFolderAsync(req.FolderId, req.NewParentId, user);
|
||||
if (result.IsSuccess)
|
||||
var moved = await TemplateFolderService.MoveFolderAsync(folderId, result.NewParentId, user);
|
||||
if (moved.IsSuccess)
|
||||
{
|
||||
_showMoveFolderDialog = false;
|
||||
_toast.ShowSuccess($"Folder '{_moveFolderName}' moved.");
|
||||
_toast.ShowSuccess($"Folder '{label}' moved.");
|
||||
await LoadTemplatesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_moveFolderError = result.Error;
|
||||
_toast.ShowError(moved.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -457,44 +418,62 @@
|
||||
private bool _showRootMenu;
|
||||
private double _rootMenuX;
|
||||
private double _rootMenuY;
|
||||
private bool _rootMenuNeedsFocus;
|
||||
private ElementReference _rootMenuRef;
|
||||
|
||||
private void OpenRootContextMenu(MouseEventArgs e)
|
||||
{
|
||||
// Guard: dismiss any open node context menu first so both menus are
|
||||
// never visible simultaneously (double-menu flash fix, #258).
|
||||
_tree.DismissNodeContextMenu();
|
||||
|
||||
_rootMenuX = e.ClientX;
|
||||
_rootMenuY = e.ClientY;
|
||||
_showRootMenu = true;
|
||||
_rootMenuNeedsFocus = true;
|
||||
}
|
||||
|
||||
private void DismissRootContextMenu() => _showRootMenu = false;
|
||||
|
||||
// Rename folder dialog state
|
||||
private bool _showRenameFolderDialog;
|
||||
private int _renameFolderId;
|
||||
private string _renameFolderInitialName = string.Empty;
|
||||
private string? _renameFolderError;
|
||||
|
||||
private void OpenRenameFolderDialog(int folderId, string currentName)
|
||||
private void OnRootMenuKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
_renameFolderId = folderId;
|
||||
_renameFolderInitialName = currentName;
|
||||
_renameFolderError = null;
|
||||
_showRenameFolderDialog = true;
|
||||
if (e.Key == "Escape")
|
||||
DismissRootContextMenu();
|
||||
}
|
||||
|
||||
private async Task SubmitRenameFolder((int FolderId, string NewName) req)
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
_renameFolderError = null;
|
||||
if (_rootMenuNeedsFocus && _showRootMenu)
|
||||
{
|
||||
_rootMenuNeedsFocus = false;
|
||||
try { await _rootMenuRef.FocusAsync(); }
|
||||
catch (Microsoft.JSInterop.JSException) { }
|
||||
catch (Microsoft.JSInterop.JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
}
|
||||
|
||||
// Rename folder dialog: opened via IDialogService.ShowAsync. The body seeds the
|
||||
// input from the current name and returns the trimmed new name on Save, or null on
|
||||
// Cancel; server guard failures surface via a toast.
|
||||
private async Task OpenRenameFolderDialog(int folderId, string currentName)
|
||||
{
|
||||
var newName = await Dialog.ShowAsync<string>(
|
||||
"Rename Folder",
|
||||
ctx => @<RenameFolderDialog Context="ctx" InitialName="@currentName" />,
|
||||
size: "modal-sm");
|
||||
if (string.IsNullOrWhiteSpace(newName)) return;
|
||||
|
||||
var user = await GetCurrentUserAsync();
|
||||
var result = await TemplateFolderService.RenameFolderAsync(req.FolderId, req.NewName, user);
|
||||
var result = await TemplateFolderService.RenameFolderAsync(folderId, newName, user);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_showRenameFolderDialog = false;
|
||||
_toast.ShowSuccess("Folder renamed.");
|
||||
await LoadTemplatesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_renameFolderError = result.Error;
|
||||
_toast.ShowError(result.Error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -545,17 +524,31 @@
|
||||
}
|
||||
|
||||
// ---- Compose-into dialog ----
|
||||
private bool _showComposeDialog;
|
||||
private int _composeSourceId;
|
||||
private string _composeSourceName = string.Empty;
|
||||
private string? _composeError;
|
||||
|
||||
private void OpenComposeDialog(Template source)
|
||||
// Opened via IDialogService.ShowAsync. The body returns the chosen parent template
|
||||
// + slot name on Compose (its own client-side guard keeps the button disabled until
|
||||
// both are set), or null on Cancel; server guard failures surface via a toast.
|
||||
private async Task OpenComposeDialog(Template source)
|
||||
{
|
||||
_composeSourceId = source.Id;
|
||||
_composeSourceName = source.Name;
|
||||
_composeError = null;
|
||||
_showComposeDialog = true;
|
||||
var sourceId = source.Id;
|
||||
var sourceName = source.Name;
|
||||
var result = await Dialog.ShowAsync<ComposeIntoDialog.ComposeResult>(
|
||||
$"Compose '{sourceName}' into…",
|
||||
ctx => @<ComposeIntoDialog Context="ctx"
|
||||
SourceName="@sourceName"
|
||||
ParentOptions="EnumerateComposableParents(sourceId)" />);
|
||||
if (result is null) return;
|
||||
|
||||
var user = await GetCurrentUserAsync();
|
||||
var composed = await TemplateService.AddCompositionAsync(result.ParentTemplateId, sourceId, result.SlotName, user);
|
||||
if (composed.IsSuccess)
|
||||
{
|
||||
_toast.ShowSuccess($"Composed '{sourceName}' as '{result.SlotName}'.");
|
||||
await LoadTemplatesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_toast.ShowError(composed.Error);
|
||||
}
|
||||
}
|
||||
|
||||
// Possible parents for a compose: every non-derived template except the source itself.
|
||||
@@ -568,23 +561,6 @@
|
||||
.Select(t => (t.Id, t.Name));
|
||||
}
|
||||
|
||||
private async Task SubmitCompose((int SourceTemplateId, int ParentTemplateId, string SlotName) req)
|
||||
{
|
||||
_composeError = null;
|
||||
var user = await GetCurrentUserAsync();
|
||||
var result = await TemplateService.AddCompositionAsync(req.ParentTemplateId, req.SourceTemplateId, req.SlotName, user);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
_showComposeDialog = false;
|
||||
_toast.ShowSuccess($"Composed '{_composeSourceName}' as '{req.SlotName}'.");
|
||||
await LoadTemplatesAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
_composeError = result.Error;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Composition leaf: rename + delete ----
|
||||
private async Task RenameComposition(TemplateComposition composition)
|
||||
{
|
||||
|
||||
@@ -138,6 +138,13 @@
|
||||
@RenderCheckboxList(_smtpConfigs, s => s.Id, s => s.Host, _selectedSmtpConfigs)
|
||||
</fieldset>
|
||||
|
||||
@* S10c: SMS provider configs, mirroring the SMTP section above. Labelled by
|
||||
AccountSid (the bundle key); the secret AuthToken is never rendered. *@
|
||||
<fieldset class="mb-4" data-testid="group-sms-configs">
|
||||
<legend class="h6">SMS Configurations</legend>
|
||||
@RenderCheckboxList(_smsConfigs, s => s.Id, s => s.AccountSid, _selectedSmsConfigs)
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="mb-4" data-testid="group-api-methods">
|
||||
<legend class="h6">API Methods</legend>
|
||||
@RenderCheckboxList(_apiMethods, m => m.Id, m => m.Name, _selectedApiMethods)
|
||||
@@ -354,6 +361,11 @@
|
||||
{
|
||||
<li>SmtpConfig: @s.Host</li>
|
||||
}
|
||||
@* S10c: SMS configs in the closure, mirroring SmtpConfig above; AccountSid only, never AuthToken. *@
|
||||
@foreach (var s in _resolved.SmsConfigs.OrderBy(s => s.AccountSid, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
<li>SmsConfig: @s.AccountSid</li>
|
||||
}
|
||||
@* Inbound API keys are not transported (re-arch C4) — methods only. *@
|
||||
@foreach (var m in _resolved.ApiMethods.OrderBy(m => m.Name, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
@@ -447,8 +459,8 @@
|
||||
{
|
||||
<div class="alert alert-warning" role="alert" data-testid="secrets-warning">
|
||||
<strong>@_secretCount</strong> secret @(_secretCount == 1 ? "field" : "fields")
|
||||
will be encrypted (external-system credentials, SMTP credentials, and database
|
||||
connection strings).
|
||||
will be encrypted (external-system credentials, SMTP credentials, SMS auth
|
||||
tokens, and database connection strings).
|
||||
</div>
|
||||
}
|
||||
else
|
||||
@@ -495,7 +507,7 @@
|
||||
<div class="alert alert-danger" data-testid="unencrypted-confirm">
|
||||
<strong>Unencrypted export</strong> — the bundle will contain all secret fields
|
||||
in plaintext. Anyone with the file can read external-system credentials, SMTP
|
||||
passwords, and database connection strings. The audit log will record this as
|
||||
passwords, SMS auth tokens, and database connection strings. The audit log will record this as
|
||||
<code>UnencryptedBundleExport</code>.
|
||||
<div class="mt-2 d-flex gap-2">
|
||||
<button class="btn btn-sm btn-danger" @onclick="ConfirmUnencryptedExport">
|
||||
|
||||
@@ -72,6 +72,9 @@ public partial class TransportExport : ComponentBase
|
||||
private List<DatabaseConnectionDefinition> _dbConnections = new();
|
||||
private List<NotificationList> _notificationLists = new();
|
||||
private List<SmtpConfiguration> _smtpConfigs = new();
|
||||
// S10c: SMS provider configs, mirroring _smtpConfigs. Keyed by AccountSid in the
|
||||
// bundle; the wizard selects by entity id (same as SMTP) and never surfaces AuthToken.
|
||||
private List<SmsConfiguration> _smsConfigs = new();
|
||||
// Inbound API keys are not transported between environments (re-arch C4); only methods.
|
||||
private List<ApiMethod> _apiMethods = new();
|
||||
// M8 (E1): site/instance-scoped export. Sites are listed flat; each site's
|
||||
@@ -90,6 +93,8 @@ public partial class TransportExport : ComponentBase
|
||||
private readonly HashSet<int> _selectedDbConnections = new();
|
||||
private readonly HashSet<int> _selectedNotificationLists = new();
|
||||
private readonly HashSet<int> _selectedSmtpConfigs = new();
|
||||
// S10c: SMS provider config selection, mirroring _selectedSmtpConfigs.
|
||||
private readonly HashSet<int> _selectedSmsConfigs = new();
|
||||
// No _selectedApiKeys: inbound API keys are not transported (re-arch C4).
|
||||
private readonly HashSet<int> _selectedApiMethods = new();
|
||||
// M8 (E1): site/instance selection backed by entity primary keys, matching the
|
||||
@@ -138,6 +143,8 @@ public partial class TransportExport : ComponentBase
|
||||
_dbConnections = (await ExternalRepo.GetAllDatabaseConnectionsAsync()).ToList();
|
||||
_notificationLists = (await NotificationRepo.GetAllNotificationListsAsync()).ToList();
|
||||
_smtpConfigs = (await NotificationRepo.GetAllSmtpConfigurationsAsync()).ToList();
|
||||
// S10c: SMS provider configs, mirroring the SMTP load path above.
|
||||
_smsConfigs = (await NotificationRepo.GetAllSmsConfigurationsAsync()).ToList();
|
||||
// Inbound API keys are not transported (re-arch C4) — only methods are loaded.
|
||||
_apiMethods = (await InboundApiRepo.GetAllApiMethodsAsync()).ToList();
|
||||
|
||||
@@ -199,6 +206,7 @@ public partial class TransportExport : ComponentBase
|
||||
|| _selectedDbConnections.Count > 0
|
||||
|| _selectedNotificationLists.Count > 0
|
||||
|| _selectedSmtpConfigs.Count > 0
|
||||
|| _selectedSmsConfigs.Count > 0
|
||||
|| _selectedApiMethods.Count > 0
|
||||
|| _selectedSites.Count > 0
|
||||
|| _selectedInstances.Count > 0;
|
||||
@@ -247,6 +255,9 @@ public partial class TransportExport : ComponentBase
|
||||
// already-selected owning site.
|
||||
SiteIds = _selectedSites.ToList(),
|
||||
InstanceIds = _selectedInstances.ToList(),
|
||||
// S10c: SMS provider config ids feed the resolver's SmsConfigurationIds,
|
||||
// exactly as SmtpConfigurationIds above (init-only, trailing additive shape).
|
||||
SmsConfigurationIds = _selectedSmsConfigs.ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -314,6 +325,11 @@ public partial class TransportExport : ComponentBase
|
||||
{
|
||||
if (!string.IsNullOrEmpty(smtp.Credentials)) count++;
|
||||
}
|
||||
// S10c: SMS provider AuthToken is a secret, mirroring SMTP Credentials above.
|
||||
foreach (var sms in resolved.SmsConfigs)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(sms.AuthToken)) count++;
|
||||
}
|
||||
foreach (var db in resolved.DatabaseConnections)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(db.ConnectionString)) count++;
|
||||
@@ -440,6 +456,7 @@ public partial class TransportExport : ComponentBase
|
||||
_selectedDbConnections.Clear();
|
||||
_selectedNotificationLists.Clear();
|
||||
_selectedSmtpConfigs.Clear();
|
||||
_selectedSmsConfigs.Clear();
|
||||
_selectedApiMethods.Clear();
|
||||
_selectedSites.Clear();
|
||||
_selectedInstances.Clear();
|
||||
|
||||
@@ -56,21 +56,10 @@
|
||||
<option>Error</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label small" for="filter-from">From</label>
|
||||
<input id="filter-from"
|
||||
type="datetime-local"
|
||||
class="form-control form-control-sm"
|
||||
aria-label="From timestamp"
|
||||
@bind="_filterFrom" />
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label small" for="filter-to">To</label>
|
||||
<input id="filter-to"
|
||||
type="datetime-local"
|
||||
class="form-control form-control-sm"
|
||||
aria-label="To timestamp"
|
||||
@bind="_filterTo" />
|
||||
<div class="col-md-4">
|
||||
<DateTimeRangeFilter From="_filterFrom" FromChanged="@(v => _filterFrom = v)"
|
||||
To="_filterTo" ToChanged="@(v => _filterTo = v)"
|
||||
IdPrefix="filter" />
|
||||
</div>
|
||||
<div class="col-md-1">
|
||||
<label class="form-label small" for="filter-keyword">Message contains</label>
|
||||
|
||||
@@ -89,10 +89,10 @@
|
||||
<h6 class="text-muted mb-0 me-3">Site Health Trends</h6>
|
||||
@if (_trendSiteKeys.Count > 0)
|
||||
{
|
||||
@* OnTrendSiteChangedAsync is async — Blazor wraps it in an EventCallback so the returned Task IS awaited; keep the Async signature, do not change it to a void/fire-and-forget handler. This comment MUST stay OUTSIDE the <select> start tag: a Razor comment placed between attributes renders as an invalid attribute name and crashes the SignalR circuit (InvalidCharacterError on setAttribute). *@
|
||||
<select class="form-select form-select-sm" style="width:auto"
|
||||
data-test="site-health-trends-site"
|
||||
value="@_trendSiteId"
|
||||
@* Blazor wraps this async handler in an EventCallback, so the returned Task IS awaited — keep the Async signature; do not change it to a void/fire-and-forget handler. *@
|
||||
@onchange="OnTrendSiteChangedAsync">
|
||||
@foreach (var key in _trendSiteKeys)
|
||||
{
|
||||
@@ -593,13 +593,13 @@
|
||||
var siteId = _trendSiteId;
|
||||
|
||||
(_connectionsDownSeries, _connectionsDownAvailable, _connectionsDownError) =
|
||||
await LoadTrendSeriesAsync("connectionsDown", siteId, fromUtc, toUtc);
|
||||
await LoadTrendSeriesAsync(KpiMetrics.SiteHealth.ConnectionsDown, siteId, fromUtc, toUtc);
|
||||
(_deadLettersSeries, _deadLettersAvailable, _deadLettersError) =
|
||||
await LoadTrendSeriesAsync("deadLetters", siteId, fromUtc, toUtc);
|
||||
await LoadTrendSeriesAsync(KpiMetrics.SiteHealth.DeadLetters, siteId, fromUtc, toUtc);
|
||||
(_scriptErrorsSeries, _scriptErrorsAvailable, _scriptErrorsError) =
|
||||
await LoadTrendSeriesAsync("scriptErrors", siteId, fromUtc, toUtc);
|
||||
await LoadTrendSeriesAsync(KpiMetrics.SiteHealth.ScriptErrors, siteId, fromUtc, toUtc);
|
||||
(_sfBufferDepthSeries, _sfBufferDepthAvailable, _sfBufferDepthError) =
|
||||
await LoadTrendSeriesAsync("sfBufferDepth", siteId, fromUtc, toUtc);
|
||||
await LoadTrendSeriesAsync(KpiMetrics.SiteHealth.SfBufferDepth, siteId, fromUtc, toUtc);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
+3
-3
@@ -279,11 +279,11 @@
|
||||
// one metric's failure only blanks that one chart while the others still
|
||||
// render their fetched data — and a throw never breaks the KPI tiles above.
|
||||
(_queueDepthSeries, _queueDepthAvailable, _queueDepthError) =
|
||||
await LoadSeries("queueDepth", fromUtc, toUtc);
|
||||
await LoadSeries(KpiMetrics.NotificationOutbox.QueueDepth, fromUtc, toUtc);
|
||||
(_parkedSeries, _parkedAvailable, _parkedError) =
|
||||
await LoadSeries("parkedCount", fromUtc, toUtc);
|
||||
await LoadSeries(KpiMetrics.NotificationOutbox.ParkedCount, fromUtc, toUtc);
|
||||
(_deliveredSeries, _deliveredAvailable, _deliveredError) =
|
||||
await LoadSeries("deliveredLastInterval", fromUtc, toUtc);
|
||||
await LoadSeries(KpiMetrics.NotificationOutbox.DeliveredLastInterval, fromUtc, toUtc);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
+99
-15
@@ -1,10 +1,13 @@
|
||||
@page "/notifications/lists/create"
|
||||
@page "/notifications/lists/{Id:int}/edit"
|
||||
@using ZB.MOM.WW.ScadaBridge.Security
|
||||
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
|
||||
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
|
||||
@inject INotificationRepository NotificationRepository
|
||||
@inject INotificationChannelCatalog ChannelCatalog
|
||||
@inject NavigationManager NavigationManager
|
||||
|
||||
<div class="container-fluid mt-3">
|
||||
@@ -25,6 +28,19 @@
|
||||
<input type="text" class="form-control" @bind="_name" />
|
||||
</div>
|
||||
|
||||
@* Type is create-only: a list's channel fixes which contact field its
|
||||
recipients carry (email vs phone), so changing it after recipients exist
|
||||
would orphan them. Disabled on edit (Id.HasValue). *@
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Type</label>
|
||||
<select class="form-select" @bind="_type" disabled="@Id.HasValue">
|
||||
@foreach (var channel in ChannelCatalog.SupportedChannels)
|
||||
{
|
||||
<option value="@channel">@ChannelLabel(channel)</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@if (_formError != null)
|
||||
{
|
||||
<div class="text-danger small mb-2">@_formError</div>
|
||||
@@ -47,10 +63,23 @@
|
||||
<label class="form-label">Name</label>
|
||||
<input type="text" class="form-control" @bind="_recipientName" />
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Email</label>
|
||||
<input type="email" class="form-control" @bind="_recipientEmail" />
|
||||
</div>
|
||||
@* Per-type contact field: email lists collect an email address; SMS
|
||||
lists collect an E.164 phone number. *@
|
||||
@if (_type == NotificationType.Sms)
|
||||
{
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Phone</label>
|
||||
<input type="tel" class="form-control" placeholder="+15551234567"
|
||||
@bind="_recipientPhone" />
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="mb-2">
|
||||
<label class="form-label">Email</label>
|
||||
<input type="email" class="form-control" @bind="_recipientEmail" />
|
||||
</div>
|
||||
}
|
||||
@if (_recipientFormError != null)
|
||||
{
|
||||
<div class="text-danger small mt-2">@_recipientFormError</div>
|
||||
@@ -65,7 +94,7 @@
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Email</th>
|
||||
<th>@(_type == NotificationType.Sms ? "Phone" : "Email")</th>
|
||||
<th style="width:80px;">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -80,7 +109,7 @@
|
||||
{
|
||||
<tr>
|
||||
<td>@r.Name</td>
|
||||
<td>@r.EmailAddress</td>
|
||||
<td>@(_type == NotificationType.Sms ? r.PhoneNumber : r.EmailAddress)</td>
|
||||
<td>
|
||||
<button class="btn btn-outline-danger btn-sm py-0 px-1" @onclick="() => DeleteRecipient(r)">Delete</button>
|
||||
</td>
|
||||
@@ -98,17 +127,29 @@
|
||||
|
||||
private bool _loading = true;
|
||||
private string _name = "";
|
||||
|
||||
// Delivery channel for the list. Selectable only on create (an empty Id); on edit it
|
||||
// reflects the persisted list's Type and the selector is disabled. Defaults to the
|
||||
// first supported channel so the create form never starts on an undeliverable type.
|
||||
private NotificationType _type = NotificationType.Email;
|
||||
private string? _formError;
|
||||
|
||||
private NotificationList? _existing;
|
||||
|
||||
// Recipients
|
||||
private List<NotificationRecipient> _recipients = new();
|
||||
private string _recipientName = "", _recipientEmail = "";
|
||||
private string _recipientName = "", _recipientEmail = "", _recipientPhone = "";
|
||||
private string? _recipientFormError;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
// Default the create-form selection to the first supported channel (catalog is
|
||||
// never empty on a correctly configured central node).
|
||||
if (!Id.HasValue && ChannelCatalog.SupportedChannels.Count > 0)
|
||||
{
|
||||
_type = ChannelCatalog.SupportedChannels[0];
|
||||
}
|
||||
|
||||
if (Id.HasValue)
|
||||
{
|
||||
try
|
||||
@@ -117,6 +158,7 @@
|
||||
if (_existing != null)
|
||||
{
|
||||
_name = _existing.Name;
|
||||
_type = _existing.Type;
|
||||
}
|
||||
_recipients = (await NotificationRepository.GetRecipientsByListIdAsync(Id.Value)).ToList();
|
||||
}
|
||||
@@ -125,6 +167,12 @@
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
private static string ChannelLabel(NotificationType type) => type switch
|
||||
{
|
||||
NotificationType.Sms => "SMS",
|
||||
_ => "Email"
|
||||
};
|
||||
|
||||
private async Task Save()
|
||||
{
|
||||
_formError = null;
|
||||
@@ -143,7 +191,10 @@
|
||||
}
|
||||
else
|
||||
{
|
||||
var nl = new NotificationList(_name.Trim());
|
||||
// Type is set at create time and never changes thereafter (the selector
|
||||
// is disabled on edit) so a list's recipients always carry the matching
|
||||
// contact field.
|
||||
var nl = new NotificationList(_name.Trim()) { Type = _type };
|
||||
await NotificationRepository.AddNotificationListAsync(nl);
|
||||
}
|
||||
await NotificationRepository.SaveChangesAsync();
|
||||
@@ -155,26 +206,59 @@
|
||||
private async Task SaveRecipient()
|
||||
{
|
||||
_recipientFormError = null;
|
||||
if (string.IsNullOrWhiteSpace(_recipientName) || string.IsNullOrWhiteSpace(_recipientEmail))
|
||||
if (string.IsNullOrWhiteSpace(_recipientName))
|
||||
{
|
||||
_recipientFormError = "Name and email required.";
|
||||
_recipientFormError = "Name required.";
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationRecipient r;
|
||||
if (_type == NotificationType.Sms)
|
||||
{
|
||||
var phone = _recipientPhone.Trim();
|
||||
if (!IsValidPhone(phone))
|
||||
{
|
||||
_recipientFormError = "A valid phone number is required (digits, optional leading +).";
|
||||
return;
|
||||
}
|
||||
r = NotificationRecipient.ForSms(_recipientName.Trim(), phone);
|
||||
}
|
||||
else
|
||||
{
|
||||
var email = _recipientEmail.Trim();
|
||||
if (string.IsNullOrWhiteSpace(email) || !email.Contains('@'))
|
||||
{
|
||||
_recipientFormError = "A valid email address is required.";
|
||||
return;
|
||||
}
|
||||
r = NotificationRecipient.ForEmail(_recipientName.Trim(), email);
|
||||
}
|
||||
r.NotificationListId = Id!.Value;
|
||||
|
||||
try
|
||||
{
|
||||
var r = new NotificationRecipient(_recipientName.Trim(), _recipientEmail.Trim())
|
||||
{
|
||||
NotificationListId = Id!.Value
|
||||
};
|
||||
await NotificationRepository.AddRecipientAsync(r);
|
||||
await NotificationRepository.SaveChangesAsync();
|
||||
_recipientName = _recipientEmail = string.Empty;
|
||||
_recipientName = _recipientEmail = _recipientPhone = string.Empty;
|
||||
_recipients = (await NotificationRepository.GetRecipientsByListIdAsync(Id.Value)).ToList();
|
||||
}
|
||||
catch (Exception ex) { _recipientFormError = ex.Message; }
|
||||
}
|
||||
|
||||
// E.164-ish: non-empty, an optional leading '+' then digits only. Kept permissive
|
||||
// (matches the SMS adapter's recipient handling) rather than enforcing a strict
|
||||
// regional format or length.
|
||||
private static bool IsValidPhone(string phone)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(phone))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var digits = phone.StartsWith('+') ? phone[1..] : phone;
|
||||
return digits.Length > 0 && digits.All(char.IsDigit);
|
||||
}
|
||||
|
||||
private async Task DeleteRecipient(NotificationRecipient r)
|
||||
{
|
||||
try
|
||||
|
||||
+10
-1
@@ -2,6 +2,7 @@
|
||||
@using ZB.MOM.WW.ScadaBridge.Security
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
|
||||
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
|
||||
@inject INotificationRepository NotificationRepository
|
||||
@inject NavigationManager NavigationManager
|
||||
@@ -45,6 +46,7 @@
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Recipients</th>
|
||||
<th class="text-end">Actions</th>
|
||||
</tr>
|
||||
@@ -56,6 +58,7 @@
|
||||
?? (IReadOnlyList<NotificationRecipient>)Array.Empty<NotificationRecipient>();
|
||||
<tr @key="list.Id">
|
||||
<td>@list.Name</td>
|
||||
<td>@list.Type</td>
|
||||
<td>
|
||||
@if (recipients.Count == 0)
|
||||
{
|
||||
@@ -65,7 +68,13 @@
|
||||
{
|
||||
@foreach (var r in recipients)
|
||||
{
|
||||
<span class="badge bg-light text-dark me-1 mb-1">@r.Name <@r.EmailAddress></span>
|
||||
@* Type-aware contact: SMS recipients carry a PhoneNumber and a null
|
||||
EmailAddress, so an email-shaped badge would render "Name <>". Fall
|
||||
back to whichever contact field is populated. *@
|
||||
var contact = list.Type == NotificationType.Sms
|
||||
? r.PhoneNumber
|
||||
: r.EmailAddress;
|
||||
<span class="badge bg-light text-dark me-1 mb-1">@r.Name <@contact></span>
|
||||
}
|
||||
}
|
||||
</td>
|
||||
|
||||
+11
-27
@@ -72,16 +72,9 @@
|
||||
data-test="notif-filter-node"
|
||||
@bind="_nodeFilter" />
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-1" for="no-from">From</label>
|
||||
<input id="no-from" type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_fromFilter" />
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-1" for="no-to">To</label>
|
||||
<input id="no-to" type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_toFilter" />
|
||||
</div>
|
||||
<DateTimeRangeFilter From="_fromFilter" FromChanged="(v => _fromFilter = v)"
|
||||
To="_toFilter" ToChanged="(v => _toFilter = v)"
|
||||
IdPrefix="no" />
|
||||
<div class="col">
|
||||
<label class="form-label small mb-1" for="no-search">Subject keyword</label>
|
||||
<input id="no-search" type="search" class="form-control form-control-sm"
|
||||
@@ -205,20 +198,12 @@
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@if (_totalCount > _pageSize)
|
||||
{
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted small">
|
||||
Page @_pageNumber of @((_totalCount + _pageSize - 1) / _pageSize) · @_totalCount total
|
||||
</span>
|
||||
<div>
|
||||
<button class="btn btn-outline-secondary btn-sm me-1"
|
||||
@onclick="PrevPage" disabled="@(_pageNumber <= 1 || _loading)">Previous</button>
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
@onclick="NextPage" disabled="@(_notifications.Count < _pageSize || _loading)">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<OffsetPager Page="_pageNumber"
|
||||
PageChanged="OnPageChanged"
|
||||
HasNextPage="@(_notifications.Count >= _pageSize)"
|
||||
TotalCount="_totalCount"
|
||||
PageSize="_pageSize"
|
||||
Disabled="_loading" />
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -226,7 +211,7 @@
|
||||
@if (_detailNotification != null)
|
||||
{
|
||||
var d = _detailNotification;
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);"
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1"
|
||||
@onclick="CloseDetail">
|
||||
<div class="modal-dialog modal-dialog-scrollable modal-lg" @onclick:stopPropagation="true">
|
||||
<div class="modal-content">
|
||||
@@ -432,8 +417,7 @@
|
||||
await FetchPage();
|
||||
}
|
||||
|
||||
private async Task PrevPage() { _pageNumber--; await FetchPage(); }
|
||||
private async Task NextPage() { _pageNumber++; await FetchPage(); }
|
||||
private async Task OnPageChanged(int page) { _pageNumber = page; await FetchPage(); }
|
||||
|
||||
private async Task FetchPage()
|
||||
{
|
||||
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
@page "/notifications/sms"
|
||||
@using ZB.MOM.WW.ScadaBridge.Security
|
||||
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
|
||||
@using SmsConfigurationEntity = ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmsConfiguration
|
||||
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
|
||||
@inject INotificationRepository NotificationRepository
|
||||
@inject NavigationManager NavigationManager
|
||||
|
||||
<div class="container-fluid mt-3">
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<h4 class="mb-0">SMS Configuration</h4>
|
||||
</div>
|
||||
|
||||
<ToastNotification @ref="_toast" />
|
||||
|
||||
@if (_loading)
|
||||
{
|
||||
<LoadingSpinner IsLoading="true" />
|
||||
}
|
||||
else if (_errorMessage != null)
|
||||
{
|
||||
<div class="alert alert-danger">@_errorMessage</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_smsConfigs.Count == 0 && !_showForm)
|
||||
{
|
||||
<div class="text-center py-5 text-muted">
|
||||
<p class="mb-3">No SMS configuration set.</p>
|
||||
<button class="btn btn-primary btn-sm" @onclick="ShowAddForm">
|
||||
Add SMS configuration
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var sms in _smsConfigs)
|
||||
{
|
||||
<div class="card mb-3" @key="sms.Id">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<strong>@sms.AccountSid</strong>
|
||||
@if (_editingSms?.Id != sms.Id || !_showForm)
|
||||
{
|
||||
<button class="btn btn-outline-primary btn-sm" @onclick="() => StartEdit(sms)">Edit</button>
|
||||
}
|
||||
</div>
|
||||
<div class="card-body small">
|
||||
<div class="row g-2">
|
||||
<div class="col-md-4 text-muted">Account SID</div>
|
||||
<div class="col-md-8">@sms.AccountSid</div>
|
||||
<div class="col-md-4 text-muted">From Number</div>
|
||||
<div class="col-md-8">@sms.FromNumber</div>
|
||||
<div class="col-md-4 text-muted">Messaging Service SID</div>
|
||||
<div class="col-md-8">@(string.IsNullOrWhiteSpace(sms.MessagingServiceSid) ? "(not set)" : sms.MessagingServiceSid)</div>
|
||||
<div class="col-md-4 text-muted">API Base URL</div>
|
||||
<div class="col-md-8">@(string.IsNullOrWhiteSpace(sms.ApiBaseUrl) ? "(provider default)" : sms.ApiBaseUrl)</div>
|
||||
<div class="col-md-4 text-muted">Auth Token</div>
|
||||
<div class="col-md-8">@(string.IsNullOrWhiteSpace(sms.AuthToken) ? "(not set)" : "(stored)")</div>
|
||||
<div class="col-md-4 text-muted">Connection Timeout</div>
|
||||
<div class="col-md-8">@sms.ConnectionTimeoutSeconds s</div>
|
||||
<div class="col-md-4 text-muted">Max Retries</div>
|
||||
<div class="col-md-8">@sms.MaxRetries</div>
|
||||
<div class="col-md-4 text-muted">Retry Delay</div>
|
||||
<div class="col-md-8">@((int)sms.RetryDelay.TotalSeconds) s</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (_showForm)
|
||||
{
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">@(_editingSms != null ? "Edit SMS Configuration" : "Add SMS Configuration")</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-12">
|
||||
<label class="form-label">Account SID</label>
|
||||
<input type="text" class="form-control" @bind="_accountSid" placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">From Number</label>
|
||||
<input type="text" class="form-control" @bind="_fromNumber" placeholder="+15551234567" />
|
||||
<div class="form-text">Provide a From Number or a Messaging Service SID (at least one is required).</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Messaging Service SID</label>
|
||||
<input type="text" class="form-control" @bind="_messagingServiceSid"
|
||||
placeholder="MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (optional)" />
|
||||
<div class="form-text">Optional — used instead of the From number when set.</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">API Base URL</label>
|
||||
<input type="text" class="form-control" @bind="_apiBaseUrl"
|
||||
placeholder="Leave blank to use the provider default" />
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label">Auth Token</label>
|
||||
<input type="password" class="form-control" @bind="_authToken"
|
||||
placeholder="@(_editingSms != null ? "Leave blank to keep the stored token" : "Twilio Auth Token")" />
|
||||
<div class="form-text">
|
||||
Treat as sensitive — visible to admins only.
|
||||
@if (_editingSms != null)
|
||||
{
|
||||
<span>Leave blank to keep the existing token.</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Connection Timeout (s)</label>
|
||||
<input type="number" class="form-control" @bind="_connectionTimeoutSeconds" min="1" />
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Max Retries</label>
|
||||
<input type="number" class="form-control" @bind="_maxRetries" min="0" />
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label">Retry Delay (s)</label>
|
||||
<input type="number" class="form-control" @bind="_retryDelaySeconds" min="0" />
|
||||
</div>
|
||||
@if (_formError != null)
|
||||
{
|
||||
<div class="col-12"><div class="text-danger small">@_formError</div></div>
|
||||
}
|
||||
<div class="col-12 text-end">
|
||||
<button class="btn btn-outline-secondary me-1" @onclick="CancelForm">Cancel</button>
|
||||
<button class="btn btn-success" @onclick="Save">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
else if (_smsConfigs.Count == 0)
|
||||
{
|
||||
<button class="btn btn-primary btn-sm" @onclick="ShowAddForm">Add SMS configuration</button>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private bool _loading = true;
|
||||
private string? _errorMessage;
|
||||
|
||||
private List<SmsConfigurationEntity> _smsConfigs = new();
|
||||
private bool _showForm;
|
||||
private SmsConfigurationEntity? _editingSms;
|
||||
|
||||
private string _accountSid = string.Empty;
|
||||
private string _fromNumber = string.Empty;
|
||||
private string? _messagingServiceSid;
|
||||
private string? _apiBaseUrl;
|
||||
private string? _authToken;
|
||||
private int _connectionTimeoutSeconds = 30;
|
||||
private int _maxRetries = 10;
|
||||
private int _retryDelaySeconds = 60;
|
||||
private string? _formError;
|
||||
|
||||
private ToastNotification _toast = default!;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await LoadAsync();
|
||||
}
|
||||
|
||||
private async Task LoadAsync()
|
||||
{
|
||||
_loading = true;
|
||||
_errorMessage = null;
|
||||
try
|
||||
{
|
||||
_smsConfigs = (await NotificationRepository.GetAllSmsConfigurationsAsync()).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_errorMessage = ex.Message;
|
||||
}
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
private void ShowAddForm()
|
||||
{
|
||||
_editingSms = null;
|
||||
_accountSid = string.Empty;
|
||||
_fromNumber = string.Empty;
|
||||
_messagingServiceSid = null;
|
||||
_apiBaseUrl = null;
|
||||
_authToken = null;
|
||||
_connectionTimeoutSeconds = 30;
|
||||
_maxRetries = 10;
|
||||
_retryDelaySeconds = 60;
|
||||
_formError = null;
|
||||
_showForm = true;
|
||||
}
|
||||
|
||||
private void StartEdit(SmsConfigurationEntity sms)
|
||||
{
|
||||
_editingSms = sms;
|
||||
_accountSid = sms.AccountSid;
|
||||
_fromNumber = sms.FromNumber ?? string.Empty;
|
||||
_messagingServiceSid = sms.MessagingServiceSid;
|
||||
_apiBaseUrl = sms.ApiBaseUrl;
|
||||
// Never pre-fill the stored secret; blank means "keep existing".
|
||||
_authToken = null;
|
||||
_connectionTimeoutSeconds = sms.ConnectionTimeoutSeconds;
|
||||
_maxRetries = sms.MaxRetries;
|
||||
_retryDelaySeconds = (int)sms.RetryDelay.TotalSeconds;
|
||||
_formError = null;
|
||||
_showForm = true;
|
||||
}
|
||||
|
||||
private void CancelForm()
|
||||
{
|
||||
_showForm = false;
|
||||
_formError = null;
|
||||
}
|
||||
|
||||
private async Task Save()
|
||||
{
|
||||
_formError = null;
|
||||
// A valid Twilio config needs an Account SID and at least one sender identity:
|
||||
// a From number OR a Messaging Service SID (the latter is used instead of From).
|
||||
if (string.IsNullOrWhiteSpace(_accountSid)
|
||||
|| (string.IsNullOrWhiteSpace(_fromNumber) && string.IsNullOrWhiteSpace(_messagingServiceSid)))
|
||||
{
|
||||
_formError = "Account SID and either a From Number or a Messaging Service SID are required.";
|
||||
return;
|
||||
}
|
||||
|
||||
var typedAuthToken = string.IsNullOrWhiteSpace(_authToken) ? null : _authToken.Trim();
|
||||
|
||||
try
|
||||
{
|
||||
if (_editingSms != null)
|
||||
{
|
||||
_editingSms.AccountSid = _accountSid.Trim();
|
||||
_editingSms.FromNumber = string.IsNullOrWhiteSpace(_fromNumber) ? null : _fromNumber.Trim();
|
||||
_editingSms.MessagingServiceSid = string.IsNullOrWhiteSpace(_messagingServiceSid)
|
||||
? null
|
||||
: _messagingServiceSid.Trim();
|
||||
_editingSms.ApiBaseUrl = string.IsNullOrWhiteSpace(_apiBaseUrl) ? null : _apiBaseUrl.Trim();
|
||||
// Preserve-if-blank: only overwrite the stored token when a new value was typed.
|
||||
if (typedAuthToken != null)
|
||||
{
|
||||
_editingSms.AuthToken = typedAuthToken;
|
||||
}
|
||||
_editingSms.ConnectionTimeoutSeconds = _connectionTimeoutSeconds;
|
||||
_editingSms.MaxRetries = _maxRetries;
|
||||
_editingSms.RetryDelay = TimeSpan.FromSeconds(_retryDelaySeconds);
|
||||
await NotificationRepository.UpdateSmsConfigurationAsync(_editingSms);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (typedAuthToken == null)
|
||||
{
|
||||
_formError = "Auth Token is required.";
|
||||
return;
|
||||
}
|
||||
|
||||
var sms = new SmsConfigurationEntity(
|
||||
_accountSid.Trim(),
|
||||
string.IsNullOrWhiteSpace(_fromNumber) ? null : _fromNumber.Trim())
|
||||
{
|
||||
MessagingServiceSid = string.IsNullOrWhiteSpace(_messagingServiceSid)
|
||||
? null
|
||||
: _messagingServiceSid.Trim(),
|
||||
ApiBaseUrl = string.IsNullOrWhiteSpace(_apiBaseUrl) ? null : _apiBaseUrl.Trim(),
|
||||
AuthToken = typedAuthToken,
|
||||
ConnectionTimeoutSeconds = _connectionTimeoutSeconds,
|
||||
MaxRetries = _maxRetries,
|
||||
RetryDelay = TimeSpan.FromSeconds(_retryDelaySeconds),
|
||||
};
|
||||
await NotificationRepository.AddSmsConfigurationAsync(sms);
|
||||
}
|
||||
await NotificationRepository.SaveChangesAsync();
|
||||
_showForm = false;
|
||||
_toast.ShowSuccess("SMS configuration saved.");
|
||||
await LoadAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_formError = ex.Message;
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-26
@@ -74,14 +74,9 @@
|
||||
@bind="_nodeFilter" />
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-1" for="sc-from">From</label>
|
||||
<input id="sc-from" type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_fromFilter" />
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-1" for="sc-to">To</label>
|
||||
<input id="sc-to" type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_toFilter" />
|
||||
<DateTimeRangeFilter From="_fromFilter" FromChanged="(v => _fromFilter = v)"
|
||||
To="_toFilter" ToChanged="(v => _toFilter = v)"
|
||||
IdPrefix="sc" />
|
||||
</div>
|
||||
<div class="col">
|
||||
<label class="form-label small mb-1" for="sc-search">Target keyword</label>
|
||||
@@ -215,23 +210,18 @@
|
||||
|
||||
@* Keyset paging — the Task 4 query response carries a (CreatedAtUtc, Id)
|
||||
cursor rather than page numbers, so we keep a stack of cursors to step
|
||||
backwards and the response's NextAfter* cursor to step forwards. *@
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted small">
|
||||
@* No "of N" total: keyset paging has no cheap total-count, so
|
||||
the label is intentionally page-number-only. Do not "fix"
|
||||
this by adding a total — that would require a COUNT(*). *@
|
||||
Page @(_cursorStack.Count + 1) · @_siteCalls.Count rows
|
||||
</span>
|
||||
<div>
|
||||
<button class="btn btn-outline-secondary btn-sm me-1"
|
||||
@onclick="PrevPage" disabled="@(_cursorStack.Count == 0 || _loading)"
|
||||
data-test="site-calls-prev">Previous</button>
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
@onclick="NextPage" disabled="@(!HasNextPage || _loading)"
|
||||
data-test="site-calls-next">Next</button>
|
||||
</div>
|
||||
</div>
|
||||
backwards and the response's NextAfter* cursor to step forwards. All
|
||||
cursor logic stays in this code-behind; KeysetPager is presentational.
|
||||
No "of N" total: keyset paging has no cheap total-count, so the label is
|
||||
intentionally page-number-only. Do not "fix" this by adding a total —
|
||||
that would require a COUNT(*). *@
|
||||
<KeysetPager PageNumber="@(_cursorStack.Count + 1)"
|
||||
RowCount="_siteCalls.Count"
|
||||
CanGoBack="@(_cursorStack.Count > 0)"
|
||||
HasNextPage="@(_nextCursor is not null)"
|
||||
Disabled="_loading"
|
||||
OnPrevious="PrevPage"
|
||||
OnNext="NextPage" />
|
||||
}
|
||||
|
||||
@* ── Trends (K14: collapsible KPI-history charts) ──
|
||||
@@ -292,7 +282,7 @@
|
||||
@if (_detailSiteCall != null)
|
||||
{
|
||||
var d = _detailSiteCall;
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);"
|
||||
<div class="modal show d-block sb-modal-backdrop" tabindex="-1"
|
||||
@onclick="CloseDetail">
|
||||
<div class="modal-dialog modal-dialog-scrollable modal-lg" @onclick:stopPropagation="true">
|
||||
<div class="modal-content">
|
||||
|
||||
+3
-3
@@ -591,11 +591,11 @@ public partial class SiteCallsReport
|
||||
var fromUtc = toUtc - TimeSpan.FromHours(_windowHours);
|
||||
|
||||
(_bufferedSeries, _bufferedAvailable, _bufferedError) =
|
||||
await LoadSeriesAsync("buffered", fromUtc, toUtc);
|
||||
await LoadSeriesAsync(KpiMetrics.SiteCallAudit.Buffered, fromUtc, toUtc);
|
||||
(_parkedSeries, _parkedAvailable, _parkedError) =
|
||||
await LoadSeriesAsync("parked", fromUtc, toUtc);
|
||||
await LoadSeriesAsync(KpiMetrics.SiteCallAudit.Parked, fromUtc, toUtc);
|
||||
(_failedSeries, _failedAvailable, _failedError) =
|
||||
await LoadSeriesAsync("failedLastInterval", fromUtc, toUtc);
|
||||
await LoadSeriesAsync(KpiMetrics.SiteCallAudit.FailedLastInterval, fromUtc, toUtc);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -220,6 +220,7 @@
|
||||
if (t == "Boolean")
|
||||
{
|
||||
<select class="form-select form-select-sm"
|
||||
data-test="alarm-matchvalue-input"
|
||||
@bind="_matchValueText"
|
||||
@bind:after="OnMatchValueChanged">
|
||||
<option value="True">True</option>
|
||||
@@ -229,6 +230,7 @@
|
||||
else if (IsNumericType(t ?? ""))
|
||||
{
|
||||
<input type="number" step="any" class="form-control form-control-sm"
|
||||
data-test="alarm-matchvalue-input"
|
||||
@bind="_matchValueText"
|
||||
@bind:event="oninput"
|
||||
@bind:after="OnMatchValueChanged" />
|
||||
@@ -236,6 +238,7 @@
|
||||
else
|
||||
{
|
||||
<input type="text" class="form-control form-control-sm"
|
||||
data-test="alarm-matchvalue-input"
|
||||
placeholder="value"
|
||||
@bind="_matchValueText"
|
||||
@bind:event="oninput"
|
||||
@@ -382,28 +385,28 @@
|
||||
_hiHiDeadbandText, v => _hiHiDeadbandText = v, OnHiHiDeadbandChanged,
|
||||
_hiHiPriorityText, v => _hiHiPriorityText = v, OnHiHiPriorityChanged,
|
||||
_hiHiMessageText, v => _hiHiMessageText = v, OnHiHiMessageChanged,
|
||||
"text-danger")
|
||||
"text-danger", "alarm-hilo-hihi")
|
||||
|
||||
@HiLoSetpointRow("HIGH (warning)",
|
||||
_hiText, v => _hiText = v, OnHiChanged,
|
||||
_hiDeadbandText, v => _hiDeadbandText = v, OnHiDeadbandChanged,
|
||||
_hiPriorityText, v => _hiPriorityText = v, OnHiPriorityChanged,
|
||||
_hiMessageText, v => _hiMessageText = v, OnHiMessageChanged,
|
||||
"text-warning-emphasis")
|
||||
"text-warning-emphasis", "alarm-hilo-hi")
|
||||
|
||||
@HiLoSetpointRow("LOW (warning)",
|
||||
_loText, v => _loText = v, OnLoChanged,
|
||||
_loDeadbandText, v => _loDeadbandText = v, OnLoDeadbandChanged,
|
||||
_loPriorityText, v => _loPriorityText = v, OnLoPriorityChanged,
|
||||
_loMessageText, v => _loMessageText = v, OnLoMessageChanged,
|
||||
"text-warning-emphasis")
|
||||
"text-warning-emphasis", "alarm-hilo-lo")
|
||||
|
||||
@HiLoSetpointRow("LOW-LOW (critical)",
|
||||
_loLoText, v => _loLoText = v, OnLoLoChanged,
|
||||
_loLoDeadbandText, v => _loLoDeadbandText = v, OnLoLoDeadbandChanged,
|
||||
_loLoPriorityText, v => _loLoPriorityText = v, OnLoLoPriorityChanged,
|
||||
_loLoMessageText, v => _loLoMessageText = v, OnLoLoMessageChanged,
|
||||
"text-danger")
|
||||
"text-danger", "alarm-hilo-lolo")
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -418,7 +421,7 @@
|
||||
string? deadband, Action<string?> deadbandSetter, Func<Task> onDeadbandChanged,
|
||||
string? priority, Action<string?> prioritySetter, Func<Task> onPriorityChanged,
|
||||
string? message, Action<string?> messageSetter, Func<Task> onMessageChanged,
|
||||
string severityClass) => __builder =>
|
||||
string severityClass, string setpointTestId) => __builder =>
|
||||
{
|
||||
<div class="row g-2 align-items-end mb-1">
|
||||
<div class="col-md-5">
|
||||
@@ -428,6 +431,7 @@
|
||||
<div class="input-group input-group-sm">
|
||||
<span class="input-group-text">setpoint</span>
|
||||
<input type="number" step="any" class="form-control"
|
||||
data-test="@setpointTestId"
|
||||
placeholder="—"
|
||||
value="@value"
|
||||
@oninput="@(e => { valueSetter(e.Value?.ToString()); _ = onValueChanged(); })" />
|
||||
|
||||
@@ -1,68 +1,57 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title">Compose '@SourceName' into…</h6>
|
||||
<button type="button" class="btn-close" @onclick="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="mb-3">
|
||||
<label class="form-label small text-muted mb-1">Parent template</label>
|
||||
<select class="form-select form-select-sm" @bind="_parentTemplateId">
|
||||
<option value="0" disabled selected>Select a parent template…</option>
|
||||
@foreach (var opt in ParentOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label class="form-label small text-muted mb-1">Slot name</label>
|
||||
<input type="text" class="form-control form-control-sm"
|
||||
placeholder="Slot name"
|
||||
@bind="_slotName" />
|
||||
</div>
|
||||
@if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-2">@ErrorMessage</div> }
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="Close">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit" disabled="@(_parentTemplateId == 0 || string.IsNullOrWhiteSpace(_slotName))">Compose</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@*
|
||||
T33b: body component for the "Compose into" dialog hosted by
|
||||
IDialogService.ShowAsync. Renders ONLY the parent/slot fields + action buttons
|
||||
inside the host's .modal-body; the host owns the backdrop, header, and focus
|
||||
trap. Closes with a ComposeResult (parent template id + slot name); Cancel
|
||||
resolves to null. The Compose button stays disabled until both a parent and a
|
||||
non-blank slot are chosen (client-side guard, preserved from the original).
|
||||
Server-side compose failures are surfaced by the parent via a toast.
|
||||
*@
|
||||
<div class="mb-3">
|
||||
<label class="form-label small text-muted mb-1">Parent template</label>
|
||||
<select class="form-select form-select-sm" @bind="_parentTemplateId">
|
||||
<option value="0" disabled selected>Select a parent template…</option>
|
||||
@foreach (var opt in ParentOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-1">
|
||||
<label class="form-label small text-muted mb-1">Slot name</label>
|
||||
<input type="text" class="form-control form-control-sm"
|
||||
placeholder="Slot name"
|
||||
@bind="_slotName" @bind:event="oninput" />
|
||||
</div>
|
||||
|
||||
<div class="modal-footer px-0 pb-0 mt-3">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit"
|
||||
disabled="@(_parentTemplateId == 0 || string.IsNullOrWhiteSpace(_slotName))">Compose</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool IsVisible { get; set; }
|
||||
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
|
||||
[Parameter] public int SourceTemplateId { get; set; }
|
||||
/// <summary>Host-supplied context used to close (with the chosen parent + slot) or cancel.</summary>
|
||||
[Parameter] public DialogContext<ComposeResult> Context { get; set; } = default!;
|
||||
[Parameter] public string SourceName { get; set; } = string.Empty;
|
||||
[Parameter] public IEnumerable<(int Id, string Label)> ParentOptions { get; set; } = Array.Empty<(int, string)>();
|
||||
[Parameter] public string? ErrorMessage { get; set; }
|
||||
[Parameter] public EventCallback<(int SourceTemplateId, int ParentTemplateId, string SlotName)> OnSubmit { get; set; }
|
||||
|
||||
private bool _wasVisible;
|
||||
private int _parentTemplateId;
|
||||
private string _slotName = string.Empty;
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
if (IsVisible && !_wasVisible)
|
||||
{
|
||||
_parentTemplateId = 0;
|
||||
_slotName = SourceName;
|
||||
}
|
||||
_wasVisible = IsVisible;
|
||||
}
|
||||
protected override void OnInitialized() => _slotName = SourceName;
|
||||
|
||||
private async Task Close() => await IsVisibleChanged.InvokeAsync(false);
|
||||
|
||||
private async Task Submit()
|
||||
private void Submit()
|
||||
{
|
||||
if (_parentTemplateId == 0 || string.IsNullOrWhiteSpace(_slotName)) return;
|
||||
await OnSubmit.InvokeAsync((SourceTemplateId, _parentTemplateId, _slotName.Trim()));
|
||||
Context.Close(new ComposeResult(_parentTemplateId, _slotName.Trim()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of the compose picker: the parent template to compose into and the
|
||||
/// slot name. ShowAsync resolves to this record on Compose, or <c>null</c> on Cancel.
|
||||
/// </summary>
|
||||
/// <param name="ParentTemplateId">The template the source is composed into.</param>
|
||||
/// <param name="SlotName">The trimmed slot (composition instance) name.</param>
|
||||
public sealed record ComposeResult(int ParentTemplateId, string SlotName);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
@inject IJSRuntime JS
|
||||
|
||||
@* T34b: dark-mode toggle. Pure JS-interop + localStorage — no DI service and no
|
||||
server state. The actual theme switch happens in the browser via window.sbTheme
|
||||
(wwwroot/js/theme.js); this button just drives toggle() and reflects the result.
|
||||
The page-load default (no-flash) is owned by the inline pre-hydration script in
|
||||
App.razor, not here. *@
|
||||
<button type="button"
|
||||
class="rail-btn sb-theme-toggle"
|
||||
aria-label="Toggle dark mode"
|
||||
aria-pressed="@(_isDark ? "true" : "false")"
|
||||
title="@(_isDark ? "Switch to light mode" : "Switch to dark mode")"
|
||||
@onclick="ToggleAsync">
|
||||
<i class="bi @(_isDark ? "bi-sun" : "bi-moon-stars")" aria-hidden="true"></i>
|
||||
</button>
|
||||
|
||||
@code {
|
||||
/// <summary>Mirrors the browser's current theme so the glyph + aria-pressed stay in sync.</summary>
|
||||
private bool _isDark;
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (!firstRender) return;
|
||||
|
||||
// Reflect the persisted theme once the circuit is interactive. Prerender
|
||||
// has no JS runtime, so guard the call; a disconnect/blip just leaves the
|
||||
// button on its default (light) glyph until the next render.
|
||||
try
|
||||
{
|
||||
var mode = await JS.InvokeAsync<string>("sbTheme.get");
|
||||
var isDark = mode == "dark";
|
||||
if (isDark != _isDark)
|
||||
{
|
||||
_isDark = isDark;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
catch (JSException) { }
|
||||
catch (JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
|
||||
private async Task ToggleAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var mode = await JS.InvokeAsync<string>("sbTheme.toggle");
|
||||
_isDark = mode == "dark";
|
||||
}
|
||||
catch (JSException) { }
|
||||
catch (JSDisconnectedException) { }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
@namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared
|
||||
|
||||
@* Reusable from/to datetime-local input pair for filter bars.
|
||||
INPUT-ONLY: emits raw DateTime? (Unspecified kind) via FromChanged / ToChanged.
|
||||
UTC conversion is the caller's responsibility — no Apply button, no service injection. *@
|
||||
|
||||
<div class="row g-2 align-items-end">
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-1" for="@(IdPrefix)-from">@FromLabel</label>
|
||||
<input id="@(IdPrefix)-from"
|
||||
type="datetime-local"
|
||||
class="form-control form-control-sm"
|
||||
data-test="@(IdPrefix)-from"
|
||||
value="@From?.ToString("yyyy-MM-ddTHH:mm")"
|
||||
@onchange="OnFromChanged" />
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<label class="form-label small mb-1" for="@(IdPrefix)-to">@ToLabel</label>
|
||||
<input id="@(IdPrefix)-to"
|
||||
type="datetime-local"
|
||||
class="form-control form-control-sm"
|
||||
data-test="@(IdPrefix)-to"
|
||||
value="@To?.ToString("yyyy-MM-ddTHH:mm")"
|
||||
@onchange="OnToChanged" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public DateTime? From { get; set; }
|
||||
[Parameter] public EventCallback<DateTime?> FromChanged { get; set; }
|
||||
[Parameter] public DateTime? To { get; set; }
|
||||
[Parameter] public EventCallback<DateTime?> ToChanged { get; set; }
|
||||
|
||||
/// <summary>Prefix applied to all id/data-test attributes. Pages pass short codes like "no", "sc", "audit-filter".</summary>
|
||||
[Parameter] public string IdPrefix { get; set; } = "dtr";
|
||||
|
||||
[Parameter] public string FromLabel { get; set; } = "From";
|
||||
[Parameter] public string ToLabel { get; set; } = "To";
|
||||
|
||||
private async Task OnFromChanged(ChangeEventArgs e)
|
||||
{
|
||||
var parsed = ParseInput(e.Value?.ToString());
|
||||
await FromChanged.InvokeAsync(parsed);
|
||||
}
|
||||
|
||||
private async Task OnToChanged(ChangeEventArgs e)
|
||||
{
|
||||
var parsed = ParseInput(e.Value?.ToString());
|
||||
await ToChanged.InvokeAsync(parsed);
|
||||
}
|
||||
|
||||
private static DateTime? ParseInput(string? raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(raw))
|
||||
return null;
|
||||
|
||||
return DateTime.TryParse(raw, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var dt) ? dt : null;
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,16 @@
|
||||
|
||||
@if (Service is DialogService svc && svc.Current is { } state)
|
||||
{
|
||||
<div class="modal-backdrop fade show"></div>
|
||||
@* `sb-modal-backdrop` is a tokenized hook: a separate task attaches the
|
||||
var-driven background rule to it. No inline style here. *@
|
||||
<div class="modal-backdrop fade show sb-modal-backdrop"></div>
|
||||
<div @ref="_modalRef"
|
||||
class="modal fade show d-block"
|
||||
tabindex="-1"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
@onkeydown="OnKeyDown">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-dialog modal-dialog-centered@(state.Size is null ? "" : $" {state.Size}")" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">@state.Title</h5>
|
||||
@@ -26,6 +28,10 @@
|
||||
{
|
||||
<p class="mb-0">@state.Body</p>
|
||||
}
|
||||
else if (state.Kind == DialogKind.Custom)
|
||||
{
|
||||
@state.Content
|
||||
}
|
||||
else
|
||||
{
|
||||
<label class="form-label">@state.Body</label>
|
||||
@@ -36,14 +42,19 @@
|
||||
@oninput="OnPromptInput" />
|
||||
}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" @onclick="Cancel">Cancel</button>
|
||||
<button type="button"
|
||||
class="btn @(state.Danger ? "btn-danger" : "btn-primary") btn-sm"
|
||||
@onclick="Confirm">
|
||||
@ConfirmLabel(state)
|
||||
</button>
|
||||
</div>
|
||||
@* Custom dialogs supply their own action buttons inside the body,
|
||||
so the standard footer is suppressed for that kind. *@
|
||||
@if (state.Kind != DialogKind.Custom)
|
||||
{
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" @onclick="Cancel">Cancel</button>
|
||||
<button type="button"
|
||||
class="btn @(state.Danger ? "btn-danger" : "btn-primary") btn-sm"
|
||||
@onclick="Confirm">
|
||||
@ConfirmLabel(state)
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -95,6 +106,13 @@
|
||||
if (!ReferenceEquals(current, _focusedForState))
|
||||
{
|
||||
_focusedForState = current;
|
||||
|
||||
// Stash the element that had focus when the dialog opened so it
|
||||
// can be restored on close. Must run BEFORE the modal steals
|
||||
// focus below, otherwise we'd capture a modal element.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.captureActiveElement"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
|
||||
try
|
||||
{
|
||||
if (current.Kind == DialogKind.Prompt)
|
||||
@@ -107,18 +125,37 @@
|
||||
}
|
||||
else
|
||||
{
|
||||
_focusedForState = null;
|
||||
try { await JS.InvokeVoidAsync("document.body.classList.remove", "modal-open"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
// Only clean up on the actual open→closed transition. Skipping when
|
||||
// _focusedForState is already null avoids spurious JS interop on
|
||||
// the initial render and every steady-state no-dialog render.
|
||||
if (_focusedForState is not null)
|
||||
{
|
||||
_focusedForState = null;
|
||||
try { await JS.InvokeVoidAsync("document.body.classList.remove", "modal-open"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
|
||||
// Return focus to whatever element triggered the dialog so keyboard
|
||||
// users are not dumped at the top of the document on close.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.restoreActiveElement"); }
|
||||
catch { /* prerender: no JS — ignore */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnKeyDown(KeyboardEventArgs e)
|
||||
private async Task OnKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Escape")
|
||||
{
|
||||
Cancel();
|
||||
}
|
||||
else if (e.Key == "Tab")
|
||||
{
|
||||
// Trap Tab/Shift+Tab inside the modal so focus cannot escape to the
|
||||
// (inert) page behind the backdrop. The JS helper wraps focus at the
|
||||
// first/last focusable element and prevents the default move there.
|
||||
try { await JS.InvokeVoidAsync("sbDialog.focusTrap", _modalRef, e.ShiftKey); }
|
||||
catch { /* prerender / no JS: skip — native Tab order still applies */ }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPromptInput(ChangeEventArgs e)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
|
||||
|
||||
/// <summary>
|
||||
@@ -54,6 +56,41 @@ public class DialogService : IDialogService
|
||||
return Project(tcs.Task, static r => r as string);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<TResult?> ShowAsync<TResult>(string title, RenderFragment<DialogContext<TResult>> body, string? size = null)
|
||||
{
|
||||
EnsureNoActiveDialog();
|
||||
var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_tcs = tcs;
|
||||
|
||||
// The context routes Close/Cancel back through the same boxed Resolve()
|
||||
// path the host uses for confirm/prompt — Close boxes the typed value,
|
||||
// Cancel passes null. Capturing Resolve (not a service reference) keeps
|
||||
// the body's surface narrow and the resolution path uniform.
|
||||
var context = new DialogContext<TResult>(Resolve);
|
||||
|
||||
// Materialise the caller's RenderFragment<DialogContext<TResult>> into a
|
||||
// plain RenderFragment bound to this context, so DialogState stays
|
||||
// generic-free and the host can render it without knowing TResult.
|
||||
var content = body(context);
|
||||
|
||||
Current = new DialogState(
|
||||
title,
|
||||
DialogKind.Custom,
|
||||
Body: string.Empty,
|
||||
Danger: false,
|
||||
PromptInitial: string.Empty,
|
||||
Placeholder: null,
|
||||
Content: content,
|
||||
Size: size);
|
||||
OnChange?.Invoke();
|
||||
|
||||
// Project the boxed result to TResult?: a Close value unboxes to the
|
||||
// typed result; a Cancel (null) yields default(TResult?). The cast is
|
||||
// safe because only Close (with a TResult) ever boxes a non-null value.
|
||||
return Project(tcs.Task, static r => r is TResult typed ? typed : default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Awaits the host's result and projects it to the caller's type. The
|
||||
/// <c>await</c> here resumes on the caller's captured context (the renderer
|
||||
@@ -66,11 +103,14 @@ public class DialogService : IDialogService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by the host component when the user dismisses or confirms the
|
||||
/// dialog. <paramref name="result"/> must be a <c>bool</c> for confirms
|
||||
/// and a <c>string?</c> for prompts (null = cancel).
|
||||
/// Called by the host component (or a custom dialog's
|
||||
/// <see cref="DialogContext{TResult}"/>) when the user dismisses or confirms
|
||||
/// the dialog. <paramref name="result"/> must be a <c>bool</c> for confirms,
|
||||
/// a <c>string?</c> for prompts, or the boxed <c>TResult</c> (null = cancel)
|
||||
/// for custom dialogs.
|
||||
/// </summary>
|
||||
/// <param name="result">The user's response: a <c>bool</c> for confirms or a <c>string?</c> for prompts.</param>
|
||||
/// <param name="result">The user's response: a <c>bool</c> for confirms, a
|
||||
/// <c>string?</c> for prompts, or the boxed custom result (null = cancel).</param>
|
||||
internal void Resolve(object? result)
|
||||
{
|
||||
var tcs = _tcs;
|
||||
@@ -92,24 +132,33 @@ public class DialogService : IDialogService
|
||||
|
||||
/// <summary>
|
||||
/// Snapshot of a dialog's display state, exposed read-only on
|
||||
/// <see cref="DialogService.Current"/> for the host component to render.
|
||||
/// <see cref="DialogService.Current"/> for the host component to render. New
|
||||
/// fields are appended as optional positional parameters so existing
|
||||
/// confirm/prompt construct calls keep compiling unchanged.
|
||||
/// </summary>
|
||||
/// <param name="Title">Modal title text.</param>
|
||||
/// <param name="Kind">Discriminates between confirm and prompt rendering.</param>
|
||||
/// <param name="Body">For confirm: the message; for prompt: the input label.</param>
|
||||
/// <param name="Kind">Discriminates between confirm, prompt, and custom rendering.</param>
|
||||
/// <param name="Body">For confirm: the message; for prompt: the input label; ignored for custom.</param>
|
||||
/// <param name="Danger">When true, the confirm button uses danger styling.</param>
|
||||
/// <param name="PromptInitial">Initial value for prompt-kind dialogs.</param>
|
||||
/// <param name="Placeholder">Placeholder shown when the prompt input is empty.</param>
|
||||
/// <param name="Content">For <see cref="DialogKind.Custom"/>: the body fragment to
|
||||
/// render inside <c>.modal-body</c>; <c>null</c> for confirm/prompt.</param>
|
||||
/// <param name="Size">Optional Bootstrap modal-dialog size modifier class applied
|
||||
/// to the <c>modal-dialog</c> element (e.g. <c>modal-lg</c>); <c>null</c> = default.</param>
|
||||
public record DialogState(
|
||||
string Title,
|
||||
DialogKind Kind,
|
||||
string Body,
|
||||
bool Danger,
|
||||
string PromptInitial,
|
||||
string? Placeholder);
|
||||
string? Placeholder,
|
||||
RenderFragment? Content = null,
|
||||
string? Size = null);
|
||||
|
||||
public enum DialogKind
|
||||
{
|
||||
Confirm,
|
||||
Prompt
|
||||
Prompt,
|
||||
Custom
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Centralised dialog/modal service. Pages inject this service and call
|
||||
/// <see cref="ConfirmAsync"/> or <see cref="PromptAsync"/> programmatically
|
||||
/// instead of embedding per-page modal components. A single <c>DialogHost</c>
|
||||
/// rendered in <c>MainLayout</c> displays the resulting dialog state.
|
||||
/// <see cref="ConfirmAsync"/>, <see cref="PromptAsync"/>, or
|
||||
/// <see cref="ShowAsync{TResult}"/> programmatically instead of embedding
|
||||
/// per-page modal components. A single <c>DialogHost</c> rendered in
|
||||
/// <c>MainLayout</c> displays the resulting dialog state.
|
||||
/// </summary>
|
||||
public interface IDialogService
|
||||
{
|
||||
@@ -31,4 +34,60 @@ public interface IDialogService
|
||||
/// <param name="placeholder">Optional placeholder shown when the input is empty.</param>
|
||||
/// <returns>A task that resolves to the entered string, or <c>null</c> if the user cancels.</returns>
|
||||
Task<string?> PromptAsync(string title, string label, string initialValue = "", string? placeholder = null);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a modal hosting arbitrary custom body content and resolves to the
|
||||
/// value the body closes with, or <c>default</c> (<c>null</c> for reference
|
||||
/// types) if the user cancels (the body's own cancel path, the header close
|
||||
/// button, or Escape). The body fragment receives a
|
||||
/// <see cref="DialogContext{TResult}"/> and supplies its own action buttons —
|
||||
/// the standard Cancel/Confirm footer is NOT rendered for this kind. Use this
|
||||
/// to centralise modal chrome (backdrop, focus trap, focus restoration) while
|
||||
/// keeping page-specific form content inside the body.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">The type the body closes the dialog with.</typeparam>
|
||||
/// <param name="title">Modal title text.</param>
|
||||
/// <param name="body">Renders the modal body; receives the context whose
|
||||
/// <c>Close</c>/<c>Cancel</c> methods resolve the returned task.</param>
|
||||
/// <param name="size">Optional Bootstrap modal-dialog size modifier applied to
|
||||
/// the <c>modal-dialog</c> element (e.g. <c>modal-lg</c>, <c>modal-sm</c>).
|
||||
/// <c>null</c> leaves the default width.</param>
|
||||
/// <returns>A task that resolves to the value passed to
|
||||
/// <see cref="DialogContext{TResult}.Close"/>, or <c>default</c> on cancel.</returns>
|
||||
Task<TResult?> ShowAsync<TResult>(string title, RenderFragment<DialogContext<TResult>> body, string? size = null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handed to the body fragment of a <see cref="IDialogService.ShowAsync{TResult}"/>
|
||||
/// dialog so the body can close itself with a typed result or cancel. Both
|
||||
/// methods route back through the owning <see cref="DialogService"/> to complete
|
||||
/// the awaited <c>ShowAsync</c> task and tear down the modal.
|
||||
/// </summary>
|
||||
/// <typeparam name="TResult">The type the dialog resolves with.</typeparam>
|
||||
public sealed class DialogContext<TResult>
|
||||
{
|
||||
// Routes the close back to the owning service's Resolve(). Held as a typed
|
||||
// delegate rather than a service reference so the context stays a small,
|
||||
// self-contained closure handle and never widens the body's surface.
|
||||
private readonly Action<object?> _resolve;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a context bound to the given resolve callback. The callback boxes
|
||||
/// the result and forwards it to <see cref="DialogService.Resolve"/>.
|
||||
/// </summary>
|
||||
/// <param name="resolve">Invoked with the boxed result (<c>null</c> = cancel).</param>
|
||||
internal DialogContext(Action<object?> resolve) => _resolve = resolve;
|
||||
|
||||
/// <summary>
|
||||
/// Closes the dialog and resolves the awaited <c>ShowAsync</c> task with
|
||||
/// <paramref name="result"/>.
|
||||
/// </summary>
|
||||
/// <param name="result">The value the caller awaits.</param>
|
||||
public void Close(TResult result) => _resolve(result);
|
||||
|
||||
/// <summary>
|
||||
/// Cancels the dialog and resolves the awaited <c>ShowAsync</c> task with
|
||||
/// <c>default</c> (<c>null</c> for reference types).
|
||||
/// </summary>
|
||||
public void Cancel() => _resolve(null);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
@namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared
|
||||
|
||||
@* Reusable keyset (cursor) pagination button bar — purely presentational.
|
||||
All cursor/navigation logic lives in the consuming page via callbacks. *@
|
||||
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
data-test="keyset-prev"
|
||||
disabled="@(!CanGoBack || Disabled)"
|
||||
@onclick="OnPrevious">Previous</button>
|
||||
<span data-test="keyset-summary">Page @PageNumber · @RowCount rows</span>
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
data-test="keyset-next"
|
||||
disabled="@(!HasNextPage || Disabled)"
|
||||
@onclick="OnNext">Next</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public int PageNumber { get; set; } = 1;
|
||||
[Parameter] public int RowCount { get; set; }
|
||||
[Parameter] public bool CanGoBack { get; set; }
|
||||
[Parameter] public bool HasNextPage { get; set; }
|
||||
[Parameter] public bool Disabled { get; set; }
|
||||
[Parameter] public EventCallback OnPrevious { get; set; }
|
||||
[Parameter] public EventCallback OnNext { get; set; }
|
||||
}
|
||||
+42
-66
@@ -2,84 +2,55 @@
|
||||
@inject IDataConnectionMoveService MoveService
|
||||
|
||||
@*
|
||||
M9-T24b: Move a data connection to another site. The picker lists the candidate
|
||||
target sites (the page excludes the connection's current site). On confirm the
|
||||
dialog dispatches MoveDataConnectionCommand through IDataConnectionMoveService —
|
||||
the guard-running ManagementActor path, NOT a direct repository write — so the
|
||||
server's Designer gate and every move guard (target exists, no name collision, no
|
||||
instance binding, no native-alarm-source name reference) run. A guard error is
|
||||
shown inline and the dialog stays open; success closes the dialog and raises
|
||||
OnMoved so the page reloads the tree. Mirrors the MoveFolderDialog idiom.
|
||||
M9-T24b / T33b: body component for the "Move data connection" dialog hosted by
|
||||
IDialogService.ShowAsync. Renders ONLY the site picker + action buttons inside
|
||||
the host's .modal-body; the host owns the backdrop, header, and focus trap.
|
||||
|
||||
The body still injects IDataConnectionMoveService and dispatches the
|
||||
MoveDataConnectionCommand through the guard-running ManagementActor path (NOT a
|
||||
direct repository write) so the server's Designer gate and every move guard run.
|
||||
A guard error is shown inline and the dialog STAYS OPEN; success closes the
|
||||
dialog with Close(true) so the parent reloads the tree. Cancel resolves to false.
|
||||
*@
|
||||
@if (IsVisible)
|
||||
@if (SiteOptions.Any())
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title">Move '@ConnectionName' to site…</h6>
|
||||
<button type="button" class="btn-close" @onclick="Close" disabled="@_busy"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
@if (SiteOptions.Any())
|
||||
{
|
||||
<select class="form-select form-select-sm" @bind="_targetSiteId">
|
||||
@foreach (var opt in SiteOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted small">No other site is available to move this connection to.</div>
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_error))
|
||||
{
|
||||
<div class="text-danger small mt-2" data-test="move-connection-error">@_error</div>
|
||||
}
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="Close" disabled="@_busy">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit"
|
||||
disabled="@(_busy || !SiteOptions.Any())">Move</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<select class="form-select form-select-sm" @bind="_targetSiteId">
|
||||
@foreach (var opt in SiteOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted small">No other site is available to move this connection to.</div>
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_error))
|
||||
{
|
||||
<div class="text-danger small mt-2" data-test="move-connection-error">@_error</div>
|
||||
}
|
||||
|
||||
<div class="modal-footer px-0 pb-0 mt-3">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()" disabled="@_busy">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit"
|
||||
disabled="@(_busy || !SiteOptions.Any())">Move</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool IsVisible { get; set; }
|
||||
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
|
||||
/// <summary>Host-supplied context: Close(true) on a successful move, Cancel on dismiss.</summary>
|
||||
[Parameter] public DialogContext<bool> Context { get; set; } = default!;
|
||||
[Parameter] public int ConnectionId { get; set; }
|
||||
[Parameter] public string ConnectionName { get; set; } = string.Empty;
|
||||
[Parameter] public IEnumerable<(int Id, string Label)> SiteOptions { get; set; } = Array.Empty<(int, string)>();
|
||||
|
||||
/// <summary>Raised after a successful move so the page can reload the tree.</summary>
|
||||
[Parameter] public EventCallback OnMoved { get; set; }
|
||||
|
||||
private bool _wasVisible;
|
||||
private int? _targetSiteId;
|
||||
private string? _error;
|
||||
private bool _busy;
|
||||
|
||||
protected override void OnParametersSet()
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
// Reset internal state on transition from hidden -> visible: default the
|
||||
// picker to the first candidate site and clear any prior error.
|
||||
if (IsVisible && !_wasVisible)
|
||||
{
|
||||
_targetSiteId = SiteOptions.Select(o => (int?)o.Id).FirstOrDefault();
|
||||
_error = null;
|
||||
_busy = false;
|
||||
}
|
||||
_wasVisible = IsVisible;
|
||||
}
|
||||
|
||||
private async Task Close()
|
||||
{
|
||||
await IsVisibleChanged.InvokeAsync(false);
|
||||
// Default the picker to the first candidate site.
|
||||
_targetSiteId = SiteOptions.Select(o => (int?)o.Id).FirstOrDefault();
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
@@ -94,8 +65,9 @@
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
await IsVisibleChanged.InvokeAsync(false);
|
||||
await OnMoved.InvokeAsync();
|
||||
// Success closes the dialog; the parent's post-ShowAsync block toasts
|
||||
// and reloads the tree.
|
||||
Context.Close(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -103,6 +75,10 @@
|
||||
_error = result.Error ?? "Move failed.";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = $"Move failed: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
|
||||
@@ -1,58 +1,38 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title">Move '@FolderName' to…</h6>
|
||||
<button type="button" class="btn-close" @onclick="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<select class="form-select form-select-sm" @bind="_targetParentId">
|
||||
@foreach (var opt in FolderOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
@if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-1">@ErrorMessage</div> }
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="Close">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@*
|
||||
T33b: body component for the "Move folder" dialog hosted by
|
||||
IDialogService.ShowAsync. Renders ONLY the picker + action buttons inside the
|
||||
host's .modal-body; the host owns the backdrop, header, and focus trap. The
|
||||
body closes with a MoveFolderResult carrying the picked parent id (null = Root,
|
||||
which is why a result record is used: Close(null) would otherwise be
|
||||
indistinguishable from a Cancel). The parent validates after the dialog closes
|
||||
and toasts any server guard failure.
|
||||
*@
|
||||
<select class="form-select form-select-sm" @bind="_targetParentId">
|
||||
@foreach (var opt in FolderOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
|
||||
<div class="modal-footer px-0 pb-0 mt-3">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool IsVisible { get; set; }
|
||||
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
|
||||
[Parameter] public int FolderId { get; set; }
|
||||
[Parameter] public string FolderName { get; set; } = string.Empty;
|
||||
/// <summary>Host-supplied context used to close (with the picked parent id) or cancel.</summary>
|
||||
[Parameter] public DialogContext<MoveFolderResult> Context { get; set; } = default!;
|
||||
[Parameter] public IEnumerable<(int? Id, string Label)> FolderOptions { get; set; } = Array.Empty<(int?, string)>();
|
||||
[Parameter] public string? ErrorMessage { get; set; }
|
||||
[Parameter] public EventCallback<(int FolderId, int? NewParentId)> OnSubmit { get; set; }
|
||||
|
||||
private bool _wasVisible;
|
||||
private int? _targetParentId;
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
if (IsVisible && !_wasVisible)
|
||||
{
|
||||
_targetParentId = null;
|
||||
}
|
||||
_wasVisible = IsVisible;
|
||||
}
|
||||
private void Submit() => Context.Close(new MoveFolderResult(_targetParentId));
|
||||
|
||||
private async Task Close()
|
||||
{
|
||||
await IsVisibleChanged.InvokeAsync(false);
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await OnSubmit.InvokeAsync((FolderId, _targetParentId));
|
||||
}
|
||||
/// <summary>
|
||||
/// Result of the move-folder picker. A reference type so a non-null close is
|
||||
/// distinguishable from a cancel even when the picked parent is null (Root):
|
||||
/// ShowAsync resolves to this record on Move and to <c>null</c> on Cancel.
|
||||
/// </summary>
|
||||
/// <param name="NewParentId">The chosen parent folder id, or <c>null</c> for Root.</param>
|
||||
public sealed record MoveFolderResult(int? NewParentId);
|
||||
}
|
||||
|
||||
@@ -1,59 +1,36 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title">Move '@TemplateName' to…</h6>
|
||||
<button type="button" class="btn-close" @onclick="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<select class="form-select form-select-sm" @bind="_targetFolderId">
|
||||
@foreach (var opt in FolderOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
@if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-1">@ErrorMessage</div> }
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="Close">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@*
|
||||
T33b: body component for the "Move template" dialog hosted by
|
||||
IDialogService.ShowAsync. Renders ONLY the picker + action buttons inside the
|
||||
host's .modal-body; the host owns the backdrop, header, and focus trap. Closes
|
||||
with a MoveTemplateResult carrying the picked folder id (null = Root) — a result
|
||||
record so Close(null) for the Root choice stays distinguishable from a Cancel.
|
||||
*@
|
||||
<select class="form-select form-select-sm" @bind="_targetFolderId">
|
||||
@foreach (var opt in FolderOptions)
|
||||
{
|
||||
<option value="@opt.Id">@opt.Label</option>
|
||||
}
|
||||
</select>
|
||||
|
||||
<div class="modal-footer px-0 pb-0 mt-3">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit">Move</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool IsVisible { get; set; }
|
||||
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
|
||||
[Parameter] public int TemplateId { get; set; }
|
||||
[Parameter] public string TemplateName { get; set; } = string.Empty;
|
||||
/// <summary>Host-supplied context used to close (with the picked folder id) or cancel.</summary>
|
||||
[Parameter] public DialogContext<MoveTemplateResult> Context { get; set; } = default!;
|
||||
[Parameter] public IEnumerable<(int? Id, string Label)> FolderOptions { get; set; } = Array.Empty<(int?, string)>();
|
||||
[Parameter] public string? ErrorMessage { get; set; }
|
||||
[Parameter] public EventCallback<(int TemplateId, int? NewFolderId)> OnSubmit { get; set; }
|
||||
|
||||
private bool _wasVisible;
|
||||
private int? _targetFolderId;
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
// Reset internal state on transition from hidden -> visible.
|
||||
if (IsVisible && !_wasVisible)
|
||||
{
|
||||
_targetFolderId = null;
|
||||
}
|
||||
_wasVisible = IsVisible;
|
||||
}
|
||||
private void Submit() => Context.Close(new MoveTemplateResult(_targetFolderId));
|
||||
|
||||
private async Task Close()
|
||||
{
|
||||
await IsVisibleChanged.InvokeAsync(false);
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await OnSubmit.InvokeAsync((TemplateId, _targetFolderId));
|
||||
}
|
||||
/// <summary>
|
||||
/// Result of the move-template picker. A reference type so a non-null close is
|
||||
/// distinguishable from a cancel even when the picked folder is null (Root):
|
||||
/// ShowAsync resolves to this record on Move and to <c>null</c> on Cancel.
|
||||
/// </summary>
|
||||
/// <param name="NewFolderId">The chosen destination folder id, or <c>null</c> for Root.</param>
|
||||
public sealed record MoveTemplateResult(int? NewFolderId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
@namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared
|
||||
|
||||
@* T35a — reusable offset-pagination bar. Purely presentational: the host page
|
||||
owns page-number state, query execution, and the HasNextPage decision.
|
||||
Parameters: Page, PageChanged, HasNextPage, TotalCount, PageSize, Disabled. *@
|
||||
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
data-test="pager-prev"
|
||||
disabled="@(!HasPrev || Disabled)"
|
||||
@onclick="OnPrevAsync">
|
||||
Previous
|
||||
</button>
|
||||
|
||||
<span data-test="pager-summary">@SummaryText</span>
|
||||
|
||||
<button class="btn btn-outline-secondary btn-sm"
|
||||
data-test="pager-next"
|
||||
disabled="@(!HasNextPage || Disabled)"
|
||||
@onclick="OnNextAsync">
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public int Page { get; set; } = 1;
|
||||
[Parameter] public EventCallback<int> PageChanged { get; set; }
|
||||
[Parameter] public bool HasNextPage { get; set; }
|
||||
[Parameter] public int? TotalCount { get; set; }
|
||||
[Parameter] public int PageSize { get; set; }
|
||||
[Parameter] public bool Disabled { get; set; }
|
||||
|
||||
private bool HasPrev => Page > 1;
|
||||
|
||||
private int? PageCount =>
|
||||
TotalCount is { } t && PageSize > 0
|
||||
? (int)Math.Ceiling(t / (double)PageSize)
|
||||
: (int?)null;
|
||||
|
||||
private string SummaryText
|
||||
{
|
||||
get
|
||||
{
|
||||
var text = $"Page {Page}";
|
||||
if (PageCount is { } pc) text += $" of {pc}";
|
||||
if (TotalCount is { } total) text += $" · {total} total";
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
private Task OnPrevAsync() => PageChanged.InvokeAsync(Page - 1);
|
||||
private Task OnNextAsync() => PageChanged.InvokeAsync(Page + 1);
|
||||
}
|
||||
@@ -53,12 +53,6 @@ else
|
||||
private InboundApiSchema? _rootSchema;
|
||||
private string? _parsedFor;
|
||||
|
||||
// The resolved root schema serialized back to a JSON Schema string (with every
|
||||
// {"$ref":"lib:Name"} inlined). Fed to the raw-JSON escape-hatch Monaco editor
|
||||
// so Monaco's built-in JSON language offers schema-driven hover + completion on
|
||||
// the entered JSON. Computed once per parse alongside the resolved schema.
|
||||
private string? _resolvedSchemaJson;
|
||||
|
||||
// Raw text and per-field parse/validation errors keyed by canonical PATH
|
||||
// (e.g. "order.id", "tags[0]") so nested inputs each carry their own state.
|
||||
private readonly Dictionary<string, string> _rawText = new();
|
||||
@@ -76,9 +70,22 @@ else
|
||||
_shapes = ScriptParameterNames.ParseShapes(ParameterDefinitions);
|
||||
_rootSchema = await ParseRootAsync();
|
||||
_topLevelFields = _rootSchema?.Type == "object" ? _rootSchema.Fields : Array.Empty<InboundApiSchemaField>();
|
||||
_resolvedSchemaJson = _rootSchema is null ? null : ToJsonSchema(_rootSchema);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serializes the escape-hatch FIELD's own (resolved) sub-schema to a JSON
|
||||
/// Schema string for that field's Monaco editor — NOT the whole root object
|
||||
/// schema. So a field's raw-JSON editor validates/completes against just that
|
||||
/// field's portion of the type, not the entire object. Any
|
||||
/// <c>{"$ref":"lib:Name"}</c> the parse already inlined is emitted as its
|
||||
/// resolved shape; a node whose ref could NOT be resolved (Type
|
||||
/// <c>"ref"</c>) — or any unknown type — has no derivable sub-schema and
|
||||
/// collapses to a permissive <c>{}</c>, so the editor still validates
|
||||
/// well-formed JSON without false errors. Cheap and on-demand: only the rare
|
||||
/// escape-hatch nodes pay for it, and only at render time.
|
||||
/// </summary>
|
||||
private static string FieldSchemaJson(InboundApiSchema fieldSchema) => ToJsonSchema(fieldSchema);
|
||||
|
||||
/// <summary>
|
||||
/// Serializes a (resolved) <see cref="InboundApiSchema"/> back to a JSON Schema
|
||||
/// string for the escape-hatch Monaco editor. Any <c>{"$ref":"lib:Name"}</c> the
|
||||
@@ -250,7 +257,7 @@ else
|
||||
default: // unresolved $ref / unknown — raw-JSON escape hatch (Monaco).
|
||||
<div class="param-json-editor" data-path="@path">
|
||||
<MonacoEditor Language="json" Height="120px" ShowToolbar="false"
|
||||
JsonSchema="@_resolvedSchemaJson"
|
||||
JsonSchema="@FieldSchemaJson(schema)"
|
||||
Value="@AsRaw(path)"
|
||||
ValueChanged="@(v => SetJson(path, v))" />
|
||||
</div>
|
||||
|
||||
@@ -1,53 +1,31 @@
|
||||
@if (IsVisible)
|
||||
{
|
||||
<div class="modal show d-block" tabindex="-1" style="background: rgba(0,0,0,0.4);">
|
||||
<div class="modal-dialog modal-sm">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h6 class="modal-title">Rename Folder</h6>
|
||||
<button type="button" class="btn-close" @onclick="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<input class="form-control form-control-sm" @bind="_name" />
|
||||
@if (!string.IsNullOrEmpty(ErrorMessage)) { <div class="text-danger small mt-1">@ErrorMessage</div> }
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="Close">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit">Save</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@*
|
||||
T33b: body component for the "Rename folder" dialog hosted by
|
||||
IDialogService.ShowAsync. Renders ONLY the input + action buttons inside the
|
||||
host's .modal-body; the host owns the backdrop, header, and focus trap. Closes
|
||||
with the trimmed new name (string); Cancel resolves to null. Save is disabled
|
||||
while the field is blank (client-side guard); server-side rename failures are
|
||||
surfaced by the parent via a toast.
|
||||
*@
|
||||
<input class="form-control form-control-sm" @bind="_name" @bind:event="oninput" />
|
||||
|
||||
<div class="modal-footer px-0 pb-0 mt-3">
|
||||
<button class="btn btn-outline-secondary btn-sm" @onclick="() => Context.Cancel()">Cancel</button>
|
||||
<button class="btn btn-primary btn-sm" @onclick="Submit"
|
||||
disabled="@string.IsNullOrWhiteSpace(_name)">Save</button>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Parameter] public bool IsVisible { get; set; }
|
||||
[Parameter] public EventCallback<bool> IsVisibleChanged { get; set; }
|
||||
[Parameter] public int FolderId { get; set; }
|
||||
/// <summary>Host-supplied context used to close (with the trimmed name) or cancel.</summary>
|
||||
[Parameter] public DialogContext<string> Context { get; set; } = default!;
|
||||
[Parameter] public string InitialName { get; set; } = string.Empty;
|
||||
[Parameter] public string? ErrorMessage { get; set; }
|
||||
[Parameter] public EventCallback<(int FolderId, string NewName)> OnSubmit { get; set; }
|
||||
|
||||
private bool _wasVisible;
|
||||
private string _name = string.Empty;
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
// Reset internal state on transition from hidden -> visible.
|
||||
if (IsVisible && !_wasVisible)
|
||||
{
|
||||
_name = InitialName;
|
||||
}
|
||||
_wasVisible = IsVisible;
|
||||
}
|
||||
protected override void OnInitialized() => _name = InitialName;
|
||||
|
||||
private async Task Close()
|
||||
private void Submit()
|
||||
{
|
||||
await IsVisibleChanged.InvokeAsync(false);
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await OnSubmit.InvokeAsync((FolderId, _name.Trim()));
|
||||
if (string.IsNullOrWhiteSpace(_name)) return;
|
||||
Context.Close(_name.Trim());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
SelectedKeys="SelectedKeys"
|
||||
SelectedKeysChanged="SelectedKeysChanged"
|
||||
InitiallyExpanded="@(_initiallyExpanded)"
|
||||
StorageKey="@StorageKey">
|
||||
StorageKey="@StorageKey"
|
||||
OnNodeContextMenuOpened="OnNodeContextMenuOpened">
|
||||
<NodeContent Context="node">
|
||||
@if (NodeContent != null)
|
||||
{
|
||||
@@ -72,6 +73,8 @@
|
||||
[Parameter] public RenderFragment? EmptyContent { get; set; }
|
||||
[Parameter] public EventCallback<TemplateTreeNode> OnNodeClick { get; set; }
|
||||
[Parameter] public string? StorageKey { get; set; }
|
||||
/// <summary>Raised when a node context menu opens; forwarded from the inner TreeView.</summary>
|
||||
[Parameter] public EventCallback OnNodeContextMenuOpened { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Optional: caller-supplied extra leaves to nest under a template. Used by
|
||||
@@ -225,4 +228,10 @@
|
||||
|
||||
/// <summary>Forwarded to the inner TreeView so callers can drive expand/collapse.</summary>
|
||||
public void CollapseAll() => _tree?.CollapseAll();
|
||||
|
||||
/// <summary>
|
||||
/// Close any open node context menu. Called by the host page when it opens the
|
||||
/// root context menu so both menus are never visible simultaneously.
|
||||
/// </summary>
|
||||
public void DismissNodeContextMenu() => _tree?.DismissContextMenu();
|
||||
}
|
||||
|
||||
@@ -51,7 +51,21 @@ else
|
||||
@oncontextmenu="(e) => OnContextMenu(e, item)" @oncontextmenu:preventDefault="@(ContextMenu != null)" @oncontextmenu:stopPropagation="@(ContextMenu != null)">
|
||||
@if (isBranch)
|
||||
{
|
||||
<span class="tv-toggle" @onclick="() => ToggleExpand(key)" @onclick:stopPropagation><i class="bi bi-chevron-right"></i></span>
|
||||
@* preventDefault on the toggle's keydown suppresses Space-bar page scroll on activation
|
||||
(intended for a role=button). It also suppresses Arrow-key default scroll while the toggle
|
||||
itself has focus — acceptable, as the chevron is Tab-navigated and Blazor offers no per-key
|
||||
conditional preventDefault. This comment MUST stay OUTSIDE the start tag: a Razor comment
|
||||
placed between attributes is emitted as an invalid attribute name and crashes the render
|
||||
(InvalidCharacterError → circuit teardown on any tree with branch nodes). *@
|
||||
<span class="tv-toggle"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
aria-label="@((isExpanded ? "Collapse " : "Expand ") + KeyStr(key))"
|
||||
aria-expanded="@(isExpanded ? "true" : "false")"
|
||||
@onclick="() => ToggleExpand(key)"
|
||||
@onclick:stopPropagation
|
||||
@onkeydown="(e) => OnToggleKey(e, key)"
|
||||
@onkeydown:preventDefault><i class="bi bi-chevron-right"></i></span>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -105,6 +119,8 @@ else
|
||||
[Parameter, EditorRequired] public RenderFragment<TItem> NodeContent { get; set; } = default!;
|
||||
[Parameter] public RenderFragment? EmptyContent { get; set; }
|
||||
[Parameter] public RenderFragment<TItem>? ContextMenu { get; set; }
|
||||
/// <summary>Raised when a node context menu opens, so the host page can dismiss any sibling menus.</summary>
|
||||
[Parameter] public EventCallback OnNodeContextMenuOpened { get; set; }
|
||||
[Parameter] public int IndentPx { get; set; } = 24;
|
||||
[Parameter] public bool ShowGuideLines { get; set; } = true;
|
||||
[Parameter] public Func<TItem, bool>? InitiallyExpanded { get; set; }
|
||||
@@ -276,6 +292,14 @@ else
|
||||
PersistExpandedState();
|
||||
}
|
||||
|
||||
private void OnToggleKey(KeyboardEventArgs e, object key)
|
||||
{
|
||||
if (e.Key == "Enter" || e.Key == " ")
|
||||
{
|
||||
ToggleExpand(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void PersistExpandedState()
|
||||
{
|
||||
if (StorageKey != null)
|
||||
@@ -293,7 +317,7 @@ else
|
||||
}
|
||||
}
|
||||
|
||||
private void OnContextMenu(MouseEventArgs e, TItem item)
|
||||
private async Task OnContextMenu(MouseEventArgs e, TItem item)
|
||||
{
|
||||
if (ContextMenu == null) return;
|
||||
|
||||
@@ -302,9 +326,13 @@ else
|
||||
_contextMenuY = e.ClientY;
|
||||
_showContextMenu = true;
|
||||
_contextMenuNeedsFocus = true;
|
||||
|
||||
if (OnNodeContextMenuOpened.HasDelegate)
|
||||
await OnNodeContextMenuOpened.InvokeAsync();
|
||||
}
|
||||
|
||||
private void DismissContextMenu()
|
||||
/// <summary>Programmatically close the node context menu (e.g. so a sibling menu can take over).</summary>
|
||||
public void DismissContextMenu()
|
||||
{
|
||||
_showContextMenu = false;
|
||||
_contextMenuItem = default;
|
||||
|
||||
@@ -148,6 +148,14 @@ public static class ServiceCollectionExtensions
|
||||
// + base-changed staleness banner; never mutates rows, not on the deploy path.
|
||||
services.AddScoped<ITemplateInheritanceQueryService, TemplateInheritanceQueryService>();
|
||||
|
||||
// SMS Notifications (S7): the NotificationListForm Type selector offers only the
|
||||
// notification channels that actually have a registered delivery adapter. The
|
||||
// catalog projects the registered INotificationDeliveryAdapter set (Email + SMS,
|
||||
// registered scoped by AddNotificationOutbox into this same container) to its
|
||||
// distinct NotificationType set — no hardcoded {Email, Sms}. Scoped because the
|
||||
// adapters it enumerates are scoped (they hold a scoped INotificationRepository).
|
||||
services.AddScoped<INotificationChannelCatalog, NotificationChannelCatalog>();
|
||||
|
||||
// Roslyn-backed C# analysis for the Monaco script editor.
|
||||
// Scoped because SharedScriptCatalog wraps a scoped service.
|
||||
services.AddMemoryCache(o => o.SizeLimit = 200);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Exposes the set of notification delivery channels that actually have a registered
|
||||
/// delivery adapter, so the Central UI never offers a notification-list Type that the
|
||||
/// central node cannot deliver. The list is derived from the registered
|
||||
/// <see cref="ZB.MOM.WW.ScadaBridge.NotificationOutbox.Delivery.INotificationDeliveryAdapter"/>
|
||||
/// set (each adapter handles a single <see cref="NotificationType"/>) rather than from
|
||||
/// the <see cref="NotificationType"/> enum, so adding/removing an adapter changes the UI
|
||||
/// options automatically.
|
||||
/// </summary>
|
||||
public interface INotificationChannelCatalog
|
||||
{
|
||||
/// <summary>
|
||||
/// The distinct notification channels that have a registered delivery adapter,
|
||||
/// in a stable order. Never empty in a correctly configured central node.
|
||||
/// </summary>
|
||||
IReadOnlyList<NotificationType> SupportedChannels { get; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.NotificationOutbox.Delivery;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Default <see cref="INotificationChannelCatalog"/> that derives the supported channels
|
||||
/// from the registered <see cref="INotificationDeliveryAdapter"/> set. The central Host
|
||||
/// registers the Email + SMS adapters (see <c>AddNotificationOutbox</c>) into the same DI
|
||||
/// container that hosts the Central UI, so projecting each adapter's
|
||||
/// <see cref="INotificationDeliveryAdapter.Type"/> yields exactly the channels the central
|
||||
/// node can actually deliver — no hardcoded <c>{Email, Sms}</c> list to drift.
|
||||
/// </summary>
|
||||
public sealed class NotificationChannelCatalog : INotificationChannelCatalog
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the catalog from the registered delivery adapters, snapshotting the
|
||||
/// distinct channel set once (the adapter registrations are fixed for the process
|
||||
/// lifetime). Ordering follows the <see cref="NotificationType"/> enum so the UI Type
|
||||
/// selector renders in a stable order regardless of adapter registration order.
|
||||
/// </summary>
|
||||
/// <param name="adapters">The registered delivery adapters (one per channel).</param>
|
||||
public NotificationChannelCatalog(IEnumerable<INotificationDeliveryAdapter> adapters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(adapters);
|
||||
|
||||
SupportedChannels = adapters
|
||||
.Select(a => a.Type)
|
||||
.Distinct()
|
||||
.OrderBy(t => (int)t)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<NotificationType> SupportedChannels { get; }
|
||||
}
|
||||
@@ -31,8 +31,11 @@ public sealed class SchemaLibraryQueryService : ISchemaLibraryQueryService
|
||||
var repo = scope.ServiceProvider.GetRequiredService<ISharedSchemaRepository>();
|
||||
var all = await repo.ListAsync(cancellationToken);
|
||||
|
||||
// Ordinal-keyed to match the lib:Name resolver's exact-name lookup. Last-wins on
|
||||
// the (DB-unique) name guards against a transient duplicate read.
|
||||
// Ordinal-keyed to match the lib:Name resolver's exact-name lookup. Name is
|
||||
// DB-unique, so a list yields at most one row per name and no real collision
|
||||
// occurs; the indexer assignment is defensive only — should two rows ever share
|
||||
// a name (e.g. a mid-write transient read), the later one in enumeration order
|
||||
// overwrites the earlier rather than throwing.
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var schema in all)
|
||||
{
|
||||
|
||||
@@ -28,6 +28,11 @@
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.TemplateEngine/ZB.MOM.WW.ScadaBridge.TemplateEngine.csproj" />
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.DeploymentManager/ZB.MOM.WW.ScadaBridge.DeploymentManager.csproj" />
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.HealthMonitoring/ZB.MOM.WW.ScadaBridge.HealthMonitoring.csproj" />
|
||||
<!-- SMS Notifications (S7): the NotificationListForm Type selector derives its options
|
||||
from the registered INotificationDeliveryAdapter set (via INotificationChannelCatalog)
|
||||
so it reflects the channels the central node can actually deliver — never a hardcoded
|
||||
{Email, Sms}. The adapters live in NotificationOutbox; no NuGet packages added. -->
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.NotificationOutbox/ZB.MOM.WW.ScadaBridge.NotificationOutbox.csproj" />
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.KpiHistory/ZB.MOM.WW.ScadaBridge.KpiHistory.csproj" />
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Communication/ZB.MOM.WW.ScadaBridge.Communication.csproj" />
|
||||
<ProjectReference Include="../ZB.MOM.WW.ScadaBridge.Transport/ZB.MOM.WW.ScadaBridge.Transport.csproj" />
|
||||
|
||||
@@ -4,6 +4,19 @@
|
||||
the side-rail shell; this sheet carries only app-specific rules the kit does
|
||||
not provide. */
|
||||
|
||||
/* ── App-level tokens (light defaults) ─────────────────────────────────────
|
||||
--sb-backdrop: semi-transparent overlay used by DialogHost and ad-hoc
|
||||
modal backdrops throughout the app. */
|
||||
:root {
|
||||
--sb-backdrop: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
/* Reusable backdrop class — applied by DialogHost and standalone modal
|
||||
backdrop divs so the overlay colour follows the active theme. */
|
||||
.sb-modal-backdrop {
|
||||
background: var(--sb-backdrop);
|
||||
}
|
||||
|
||||
#reconnect-modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
@@ -19,7 +32,7 @@
|
||||
max-width: 400px;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
background: var(--bs-white);
|
||||
background: var(--card, #fff);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
@@ -35,3 +48,64 @@
|
||||
.modal-dialog.script-editor-modal .modal-content {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* ── Dark-mode token overrides ───────────────────────────────────────────────
|
||||
Activated when <html data-bs-theme="dark"> is set (T34b toggle task).
|
||||
Loads after theme.css / layout.css so [data-bs-theme] specificity (0,1,0)
|
||||
beats the theme's :root (0,0,1) at equal cascade layer. */
|
||||
[data-bs-theme="dark"] {
|
||||
/* Surfaces & ink */
|
||||
--paper: #1b1d21;
|
||||
--card: #25282d;
|
||||
--ink: #e6e8ec;
|
||||
--ink-soft: #9aa0aa;
|
||||
--ink-faint: #6b727c;
|
||||
--rule: #33373e;
|
||||
--rule-strong: #3a3f46;
|
||||
|
||||
/* Accent — lightened for contrast on dark */
|
||||
--accent: #4d7fe8;
|
||||
--accent-deep: #7aa0ef;
|
||||
|
||||
/* Status — foregrounds unchanged (inherently visible on dark) */
|
||||
--ok: #40b856;
|
||||
--warn: #f0a030;
|
||||
--bad: #f05050;
|
||||
--idle: #7a8290;
|
||||
|
||||
/* Status — tinted backgrounds (dark surface tints) */
|
||||
--ok-bg: #1a2e1e;
|
||||
--warn-bg: #2e2210;
|
||||
--bad-bg: #2e1616;
|
||||
--idle-bg: #25282d;
|
||||
|
||||
/* Status — borders on dark tints */
|
||||
--ok-border: #2a5030;
|
||||
--warn-border: #4a3510;
|
||||
--bad-border: #4a2020;
|
||||
--ok-border-soft: #264a2c;
|
||||
--warn-border-soft: #44300e;
|
||||
--bad-border-soft: #44201e;
|
||||
|
||||
/* Warning ink — brightened amber for dark contrast */
|
||||
--warn-ink: #d4891a;
|
||||
--warn-ink-deep: #b8741a;
|
||||
|
||||
/* Info tint */
|
||||
--info-bg: #1a2240;
|
||||
--info-border: #2a3660;
|
||||
|
||||
/* Neutral surface washes */
|
||||
--zebra-bg: #202328;
|
||||
--hover-bg: #2a2e38;
|
||||
--active-bg: #1e2640;
|
||||
|
||||
/* Bootstrap bridge tokens */
|
||||
--bs-body-bg: var(--paper);
|
||||
--bs-body-color: var(--ink);
|
||||
--bs-border-color: var(--rule);
|
||||
--bs-emphasis-color: var(--ink);
|
||||
|
||||
/* Backdrop — slightly darker overlay in dark mode */
|
||||
--sb-backdrop: rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// Focus management helpers for the centralised DialogHost (T33a). Small and
|
||||
// dependency-free: capture/restore the trigger element's focus across a modal's
|
||||
// lifetime, and trap Tab focus inside an open modal. Blazor calls these via
|
||||
// JS interop (window.sbDialog.*); they are no-ops when there is nothing to act
|
||||
// on, so prerender / loose-mode test calls do no harm.
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// CSS selector for elements that can receive keyboard focus within the modal.
|
||||
const FOCUSABLE =
|
||||
"a[href],button:not([disabled]),input:not([disabled])," +
|
||||
"select:not([disabled]),textarea:not([disabled])," +
|
||||
"[tabindex]:not([tabindex='-1'])";
|
||||
|
||||
// The element that had focus when the most recent dialog opened. Module-level
|
||||
// so it survives between the capture (on open) and restore (on close) calls.
|
||||
let savedActiveElement = null;
|
||||
|
||||
window.sbDialog = {
|
||||
// Stash the currently focused element so it can be restored on close.
|
||||
// Called BEFORE the modal steals focus.
|
||||
captureActiveElement: function () {
|
||||
savedActiveElement = document.activeElement;
|
||||
},
|
||||
|
||||
// Return focus to the stashed element if it is still in the document,
|
||||
// then clear the stash so a later dialog starts fresh.
|
||||
restoreActiveElement: function () {
|
||||
const el = savedActiveElement;
|
||||
savedActiveElement = null;
|
||||
if (el && typeof el.focus === 'function' && el.isConnected) {
|
||||
el.focus();
|
||||
}
|
||||
},
|
||||
|
||||
// Cycle focus within the modal: at the first focusable element a
|
||||
// Shift+Tab wraps to the last; at the last a Tab wraps to the first. In
|
||||
// both cases the default browser move (which would leave the modal) is
|
||||
// prevented. Anywhere else, the native Tab order applies untouched.
|
||||
focusTrap: function (modalEl, shiftKey) {
|
||||
if (!modalEl) return;
|
||||
const focusable = modalEl.querySelectorAll(FOCUSABLE);
|
||||
if (focusable.length === 0) return;
|
||||
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
const active = document.activeElement;
|
||||
|
||||
// Blazor interop does not hand us the DOM event, but window.event is
|
||||
// populated during the synchronous keydown dispatch on the engines we
|
||||
// target — guard the preventDefault so the wrap still works if it is
|
||||
// ever absent (the explicit .focus() override is the real trap).
|
||||
const evt = window.event;
|
||||
if (shiftKey && active === first) {
|
||||
last.focus();
|
||||
if (evt) evt.preventDefault();
|
||||
} else if (!shiftKey && active === last) {
|
||||
first.focus();
|
||||
if (evt) evt.preventDefault();
|
||||
}
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -330,12 +330,16 @@
|
||||
// A json editor with a schema needs an explicitly-URI'd model so the
|
||||
// schema's fileMatch can target exactly this editor.
|
||||
let model = null;
|
||||
let hasSchema = false;
|
||||
if (isJson) {
|
||||
const uri = modelUriFor(id);
|
||||
model = monaco.editor.getModel(uri);
|
||||
if (model) { model.setValue(options.value || ""); }
|
||||
else { model = monaco.editor.createModel(options.value || "", "json", uri); }
|
||||
if (options.jsonSchema) { applyJsonSchema(id, options.jsonSchema); }
|
||||
if (options.jsonSchema && options.jsonSchema.trim().length > 0) {
|
||||
applyJsonSchema(id, options.jsonSchema);
|
||||
hasSchema = true;
|
||||
}
|
||||
}
|
||||
|
||||
const editor = monaco.editor.create(host, {
|
||||
@@ -372,7 +376,7 @@
|
||||
dotNetRef.invokeMethodAsync("OnValueChanged", value).catch(function () {});
|
||||
if (options.language === "csharp") scheduleDiagnostics();
|
||||
});
|
||||
editors[id] = { editor: editor, dotNetRef: dotNetRef, isJson: isJson };
|
||||
editors[id] = { editor: editor, dotNetRef: dotNetRef, isJson: isJson, hasSchema: hasSchema };
|
||||
|
||||
// Run an initial diagnostic pass so existing scripts show their markers.
|
||||
if (language === "csharp") scheduleDiagnostics();
|
||||
@@ -381,6 +385,9 @@
|
||||
function setJsonSchema(id, schemaJson) {
|
||||
const entry = editors[id];
|
||||
if (!entry || !entry.isJson) return;
|
||||
// Track whether this editor currently owns a schema entry in jsonDefaults
|
||||
// so dispose can skip the teardown interop when there is nothing to drop.
|
||||
entry.hasSchema = !!(schemaJson && schemaJson.trim().length > 0);
|
||||
applyJsonSchema(id, schemaJson);
|
||||
}
|
||||
|
||||
@@ -436,7 +443,9 @@
|
||||
if (!entry) return;
|
||||
// Drop this editor's json schema entry and its explicitly-URI'd model so
|
||||
// a disposed json editor leaves nothing behind in the global defaults.
|
||||
if (entry.isJson) {
|
||||
// Skip the schema teardown for a json editor that never had a schema —
|
||||
// there is no entry to remove, so the applyJsonSchema interop is spurious.
|
||||
if (entry.isJson && entry.hasSchema) {
|
||||
try { applyJsonSchema(id, null); } catch (e) {}
|
||||
}
|
||||
try { entry.editor.dispose(); } catch (e) {}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Dark-mode theme helper (T34b). Plain browser global in the treeview-storage.js
|
||||
// style (no ES-module export) so the App.razor <head> pre-hydration inline
|
||||
// script and this file agree on one localStorage key and one apply rule.
|
||||
//
|
||||
// * get() — reads the persisted choice ('dark' only when explicitly stored;
|
||||
// anything else is 'light').
|
||||
// * apply() — sets data-bs-theme on <html>; the site.css [data-bs-theme="dark"]
|
||||
// token-override block (T34a) does the rest, side-rail included.
|
||||
// * set() — persists + applies, returns the mode.
|
||||
// * toggle() — flips and persists, returns the new mode (the DarkModeToggle
|
||||
// component's click path).
|
||||
//
|
||||
// Every localStorage touch is wrapped in try/catch so private-browsing modes
|
||||
// (which throw on access) degrade to light rather than break the page.
|
||||
window.sbTheme = {
|
||||
KEY: 'sb-theme',
|
||||
get() {
|
||||
try { return localStorage.getItem(this.KEY) === 'dark' ? 'dark' : 'light'; }
|
||||
catch { return 'light'; }
|
||||
},
|
||||
apply(mode) {
|
||||
document.documentElement.setAttribute('data-bs-theme', mode);
|
||||
},
|
||||
set(mode) {
|
||||
try { localStorage.setItem(this.KEY, mode); } catch { }
|
||||
this.apply(mode);
|
||||
return mode;
|
||||
},
|
||||
toggle() {
|
||||
return this.set(this.get() === 'dark' ? 'light' : 'dark');
|
||||
}
|
||||
};
|
||||
@@ -8,17 +8,85 @@ public class NotificationRecipient
|
||||
public int NotificationListId { get; set; }
|
||||
/// <summary>Gets or sets the display name of the recipient.</summary>
|
||||
public string Name { get; set; }
|
||||
/// <summary>Gets or sets the recipient's email address.</summary>
|
||||
public string EmailAddress { get; set; }
|
||||
/// <summary>Gets or sets the recipient's email address, or null for non-email recipients.</summary>
|
||||
public string? EmailAddress { get; set; }
|
||||
/// <summary>Gets or sets the recipient's phone number (E.164), or null for non-SMS recipients.</summary>
|
||||
public string? PhoneNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new <see cref="NotificationRecipient"/> with the required fields.
|
||||
/// Initializes a new <see cref="NotificationRecipient"/> with the required fields (email path).
|
||||
/// </summary>
|
||||
/// <param name="name">Display name of the recipient.</param>
|
||||
/// <param name="emailAddress">Email address of the recipient.</param>
|
||||
public NotificationRecipient(string name, string emailAddress)
|
||||
{
|
||||
Name = name ?? throw new ArgumentNullException(nameof(name));
|
||||
// Match the ForEmail factory's guard so the invariant ("a recipient always
|
||||
// has a non-blank display name") holds regardless of construction path. EF
|
||||
// materializes via the private parameterless ctor + property injection — an
|
||||
// SMS-only recipient has a null EmailAddress — so this ctor is only reached
|
||||
// by code that genuinely intends the email path.
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
throw new ArgumentException("Name must not be empty.", nameof(name));
|
||||
}
|
||||
|
||||
Name = name;
|
||||
EmailAddress = emailAddress ?? throw new ArgumentNullException(nameof(emailAddress));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an email recipient with the given name and email address; the phone number is left null.
|
||||
/// </summary>
|
||||
/// <param name="name">Display name of the recipient.</param>
|
||||
/// <param name="emailAddress">Email address of the recipient.</param>
|
||||
/// <returns>A new email <see cref="NotificationRecipient"/>.</returns>
|
||||
public static NotificationRecipient ForEmail(string name, string emailAddress)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
throw new ArgumentException("Name must not be empty.", nameof(name));
|
||||
}
|
||||
|
||||
if (emailAddress is null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(emailAddress));
|
||||
}
|
||||
|
||||
return new NotificationRecipient(name, emailAddress);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an SMS recipient with the given name and phone number; the email address is left null.
|
||||
/// </summary>
|
||||
/// <param name="name">Display name of the recipient.</param>
|
||||
/// <param name="phoneNumber">Phone number (E.164) of the recipient.</param>
|
||||
/// <returns>A new SMS <see cref="NotificationRecipient"/>.</returns>
|
||||
public static NotificationRecipient ForSms(string name, string phoneNumber)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
throw new ArgumentException("Name must not be empty.", nameof(name));
|
||||
}
|
||||
|
||||
if (phoneNumber is null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(phoneNumber));
|
||||
}
|
||||
|
||||
return new NotificationRecipient
|
||||
{
|
||||
Name = name,
|
||||
PhoneNumber = phoneNumber
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Private parameterless constructor that backs the <see cref="ForSms"/> factory path,
|
||||
/// where the contact field is assigned via property setters rather than constructor
|
||||
/// parameters — without exposing a half-initialized public constructor to callers.
|
||||
/// </summary>
|
||||
private NotificationRecipient()
|
||||
{
|
||||
Name = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications;
|
||||
|
||||
public class SmsConfiguration
|
||||
{
|
||||
/// <summary>Gets or sets the primary key.</summary>
|
||||
public int Id { get; set; }
|
||||
/// <summary>Gets or sets the Twilio Account SID.</summary>
|
||||
public string AccountSid { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the Twilio Auth Token (secret). Stored encrypted; null only transiently
|
||||
/// during configuration, never a valid production value.
|
||||
/// </summary>
|
||||
public string? AuthToken { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the sender phone number (E.164) placed in the From field, or null when
|
||||
/// delivery is via a <see cref="MessagingServiceSid"/> instead. A valid config has a
|
||||
/// FromNumber and/or a MessagingServiceSid; that either-or invariant is enforced at the
|
||||
/// management/UI boundary and again by the delivery adapter (it is not a ctor invariant
|
||||
/// because MessagingServiceSid is a settable property assigned after construction).
|
||||
/// </summary>
|
||||
public string? FromNumber { get; set; }
|
||||
/// <summary>Gets or sets the Twilio Messaging Service SID used instead of a From number, or null.</summary>
|
||||
public string? MessagingServiceSid { get; set; }
|
||||
/// <summary>Gets or sets the Twilio REST API base URL, or null to use the provider default.</summary>
|
||||
public string? ApiBaseUrl { get; set; }
|
||||
/// <summary>Gets or sets the connection timeout in seconds. Honored per-send by the SMS delivery adapter.</summary>
|
||||
public int ConnectionTimeoutSeconds { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum number of delivery retries before parking.
|
||||
/// <para>
|
||||
/// RESERVED: the Notification Outbox dispatcher currently derives the retry policy
|
||||
/// (max-retries + interval) from the central SMTP configuration for <em>all</em>
|
||||
/// notification types — see the "retry reuses central SMTP max-retry-count and fixed
|
||||
/// interval" design decision and <c>NotificationOutboxActor.ResolveRetryPolicyAsync</c>.
|
||||
/// This per-SMS value is persisted/transported for forward-compatibility but is NOT
|
||||
/// yet read at dispatch time. Honoring it per-type is a deferred enhancement (it would
|
||||
/// supersede the shared-SMTP-policy decision and is not a silent behavioral change).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public int MaxRetries { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the delay between retry attempts. RESERVED — see <see cref="MaxRetries"/>:
|
||||
/// the dispatcher currently uses the shared SMTP-derived retry interval for all types.
|
||||
/// </summary>
|
||||
public TimeSpan RetryDelay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new <see cref="SmsConfiguration"/> with the required Account SID and
|
||||
/// sensible defaults for the numeric and timeout fields. <paramref name="fromNumber"/>
|
||||
/// is optional — a Twilio Messaging-Service-only config sets <see cref="MessagingServiceSid"/>
|
||||
/// instead and leaves the From number null.
|
||||
/// </summary>
|
||||
/// <param name="accountSid">Twilio Account SID.</param>
|
||||
/// <param name="fromNumber">Sender phone number (E.164) for the From field, or null for a Messaging-Service-only config.</param>
|
||||
public SmsConfiguration(string accountSid, string? fromNumber = null)
|
||||
{
|
||||
AccountSid = accountSid ?? throw new ArgumentNullException(nameof(accountSid));
|
||||
FromNumber = fromNumber;
|
||||
ConnectionTimeoutSeconds = 30;
|
||||
MaxRetries = 10;
|
||||
RetryDelay = TimeSpan.FromMinutes(1);
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,41 @@ public interface INotificationRepository
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
Task DeleteSmtpConfigurationAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
// SmsConfiguration
|
||||
/// <summary>Gets the SMS configuration, or null if none is configured.</summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The SMS configuration, or null if not found.</returns>
|
||||
Task<SmsConfiguration?> GetSmsConfigurationAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Gets an SMS configuration by ID.</summary>
|
||||
/// <param name="id">The SMS configuration ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The SMS configuration, or null if not found.</returns>
|
||||
Task<SmsConfiguration?> GetSmsConfigurationByIdAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Gets all SMS configurations.</summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A read-only list of SMS configurations.</returns>
|
||||
Task<IReadOnlyList<SmsConfiguration>> GetAllSmsConfigurationsAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Adds a new SMS configuration.</summary>
|
||||
/// <param name="smsConfiguration">The SMS configuration to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
Task AddSmsConfigurationAsync(SmsConfiguration smsConfiguration, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Updates an existing SMS configuration.</summary>
|
||||
/// <param name="smsConfiguration">The SMS configuration to update.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
Task UpdateSmsConfigurationAsync(SmsConfiguration smsConfiguration, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Deletes an SMS configuration by ID.</summary>
|
||||
/// <param name="id">The SMS configuration ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
Task DeleteSmsConfigurationAsync(int id, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Saves pending changes to the repository.</summary>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The number of entities saved.</returns>
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||
|
||||
public record ListNotificationListsCommand;
|
||||
public record GetNotificationListCommand(int NotificationListId);
|
||||
public record CreateNotificationListCommand(string Name, IReadOnlyList<string> RecipientEmails);
|
||||
public record UpdateNotificationListCommand(int NotificationListId, string Name, IReadOnlyList<string> RecipientEmails);
|
||||
public record CreateNotificationListCommand(string Name, IReadOnlyList<string> RecipientEmails, NotificationType Type = NotificationType.Email, IReadOnlyList<string>? RecipientPhones = null);
|
||||
public record UpdateNotificationListCommand(int NotificationListId, string Name, IReadOnlyList<string> RecipientEmails, NotificationType Type = NotificationType.Email, IReadOnlyList<string>? RecipientPhones = null);
|
||||
public record DeleteNotificationListCommand(int NotificationListId);
|
||||
public record ListSmtpConfigsCommand;
|
||||
public record UpdateSmtpConfigCommand(int SmtpConfigId, string Server, int Port, string AuthMode, string FromAddress, string? TlsMode = null, string? Credentials = null);
|
||||
public record ListSmsConfigsCommand;
|
||||
// FromNumber is optional: a Twilio Messaging-Service-only config supplies MessagingServiceSid
|
||||
// instead. At-least-one-of (FromNumber, MessagingServiceSid) is validated at the CLI/UI boundary.
|
||||
public record UpdateSmsConfigCommand(int SmsConfigId, string AccountSid, string? FromNumber, string? MessagingServiceSid = null, string? ApiBaseUrl = null, string? AuthToken = null);
|
||||
|
||||
@@ -29,8 +29,13 @@ public record AddTemplateNativeAlarmSourceCommand(int TemplateId, string Name, s
|
||||
public record UpdateTemplateNativeAlarmSourceCommand(int NativeAlarmSourceId, string Name, string ConnectionName, string SourceReference, string? ConditionFilter, string? Description, bool IsLocked);
|
||||
public record DeleteTemplateNativeAlarmSourceCommand(int NativeAlarmSourceId);
|
||||
public record ListTemplateNativeAlarmSourcesCommand(int TemplateId);
|
||||
public record AddTemplateScriptCommand(int TemplateId, string Name, string Code, string? TriggerType, string? TriggerConfiguration, bool IsLocked, string? ParameterDefinitions = null, string? ReturnDefinition = null);
|
||||
public record UpdateTemplateScriptCommand(int ScriptId, string Name, string Code, string? TriggerType, string? TriggerConfiguration, bool IsLocked, string? ParameterDefinitions = null, string? ReturnDefinition = null);
|
||||
// MinTimeBetweenRuns/ExecutionTimeoutSeconds are additive trailing optionals (default null = "unset"):
|
||||
// MinTimeBetweenRuns mirrors the TemplateScript.MinTimeBetweenRuns TimeSpan throttle/re-fire interval;
|
||||
// ExecutionTimeoutSeconds mirrors the per-script TemplateScript.ExecutionTimeoutSeconds override (seconds;
|
||||
// null/non-positive falls back to the site's global default). Both were previously settable only via
|
||||
// Transport bundle import — these fields close the CLI/UI authoring gap (#54). Additive-only: never reorder.
|
||||
public record AddTemplateScriptCommand(int TemplateId, string Name, string Code, string? TriggerType, string? TriggerConfiguration, bool IsLocked, string? ParameterDefinitions = null, string? ReturnDefinition = null, TimeSpan? MinTimeBetweenRuns = null, int? ExecutionTimeoutSeconds = null);
|
||||
public record UpdateTemplateScriptCommand(int ScriptId, string Name, string Code, string? TriggerType, string? TriggerConfiguration, bool IsLocked, string? ParameterDefinitions = null, string? ReturnDefinition = null, TimeSpan? MinTimeBetweenRuns = null, int? ExecutionTimeoutSeconds = null);
|
||||
public record DeleteTemplateScriptCommand(int ScriptId);
|
||||
public record AddTemplateCompositionCommand(int TemplateId, string InstanceName, int ComposedTemplateId);
|
||||
public record DeleteTemplateCompositionCommand(int CompositionId);
|
||||
|
||||
@@ -30,7 +30,12 @@ public sealed record ExportBundleCommand(
|
||||
// Defaulted null so every existing positional caller keeps compiling; the
|
||||
// handler normalizes null to "select nothing" (or everything under All=true).
|
||||
IReadOnlyList<string>? SiteNames = null,
|
||||
IReadOnlyList<string>? InstanceNames = null);
|
||||
IReadOnlyList<string>? InstanceNames = null,
|
||||
// Additive (S10b): SMS provider config selection, mirroring
|
||||
// SmtpConfigurationNames. SmsConfiguration is keyed by AccountSid (no Name
|
||||
// column), so tokens are AccountSid values. Defaulted null so every existing
|
||||
// positional caller keeps compiling.
|
||||
IReadOnlyList<string>? SmsConfigurationNames = null);
|
||||
|
||||
/// <summary>
|
||||
/// Bundle body returned as base64-encoded ZIP. <see cref="ByteCount"/> is the
|
||||
|
||||
@@ -64,7 +64,13 @@ public static class AttributeValueCodec
|
||||
_ => el.GetRawText() // number/bool → "10" / "1.5" / "true"
|
||||
};
|
||||
|
||||
private static Type ElementClrType(DataType t) => t switch
|
||||
/// <summary>
|
||||
/// The CLR element type backing a <see cref="DataType.List"/> of the given
|
||||
/// element scalar — the single source of truth for the List element CLR
|
||||
/// mapping. Throws <see cref="FormatException"/> for an unsupported element
|
||||
/// type (see <see cref="IsValidElementType"/>).
|
||||
/// </summary>
|
||||
public static Type ElementClrType(DataType t) => t switch
|
||||
{
|
||||
DataType.String => typeof(string),
|
||||
DataType.Int32 => typeof(int),
|
||||
@@ -75,6 +81,49 @@ public static class AttributeValueCodec
|
||||
_ => throw new FormatException($"Unsupported list element type '{t}'.")
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Coerces a live CLR enumerable (e.g. an OPC UA array) into a typed
|
||||
/// <c>List<<see cref="ElementClrType"/>></c> for the given element type,
|
||||
/// converting each element with invariant culture (round-trip parse for
|
||||
/// DateTime). Strings are parsed; other CLR types are converted via
|
||||
/// <see cref="Convert"/>. This is the object-input counterpart to the
|
||||
/// string-input parsing in <see cref="Decode"/>: callers holding decoded JSON
|
||||
/// strings go through <see cref="Decode"/>; callers holding a runtime
|
||||
/// collection use this. Throws <see cref="FormatException"/> for an
|
||||
/// unsupported element type and may throw on an element that cannot be
|
||||
/// converted (the caller decides how to handle the failure).
|
||||
/// </summary>
|
||||
public static IList CoerceEnumerable(IEnumerable source, DataType elementType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
var clrType = ElementClrType(elementType);
|
||||
var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(clrType))!;
|
||||
foreach (var element in source)
|
||||
list.Add(CoerceElement(element, elementType));
|
||||
return list;
|
||||
}
|
||||
|
||||
private static object CoerceElement(object? element, DataType t)
|
||||
{
|
||||
if (element is null)
|
||||
throw new FormatException("List elements may not be null.");
|
||||
|
||||
var c = CultureInfo.InvariantCulture;
|
||||
return t switch
|
||||
{
|
||||
DataType.String => Convert.ToString(element, c)
|
||||
?? throw new FormatException("Null string element."),
|
||||
DataType.Int32 => element is string si ? int.Parse(si, c) : Convert.ToInt32(element, c),
|
||||
DataType.Float => element is string sf ? float.Parse(sf, c) : Convert.ToSingle(element, c),
|
||||
DataType.Double => element is string sd ? double.Parse(sd, c) : Convert.ToDouble(element, c),
|
||||
DataType.Boolean => element is string sb ? bool.Parse(sb) : Convert.ToBoolean(element, c),
|
||||
DataType.DateTime => element is string sdt
|
||||
? DateTime.Parse(sdt, c, DateTimeStyles.RoundtripKind)
|
||||
: Convert.ToDateTime(element, c),
|
||||
_ => throw new FormatException($"Unsupported list element type '{t}'.")
|
||||
};
|
||||
}
|
||||
|
||||
private static object? ParseScalar(string? s, DataType t)
|
||||
{
|
||||
if (s is null) throw new FormatException("List elements may not be null.");
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// Delivery channel for a notification. Currently only email is supported.
|
||||
/// Delivery channel for a notification. Email and SMS are supported.
|
||||
/// </summary>
|
||||
public enum NotificationType
|
||||
{
|
||||
Email
|
||||
Email,
|
||||
Sms
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Kpi;
|
||||
|
||||
/// <summary>
|
||||
/// Canonical <em>charted</em> KPI metric-name identifiers (M6 "KPI History &
|
||||
/// Trends") — the value of <see cref="ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiSample.Metric"/>
|
||||
/// for every metric a Central UI trend chart renders. Each owning
|
||||
/// <see cref="ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Kpi.IKpiSampleSource"/> emits
|
||||
/// these strings and each trend page keys its <c>GetSeriesAsync</c> lookup on the same
|
||||
/// strings; promoting them to one shared public symbol means the source and the page key
|
||||
/// off a single declaration, so a future rename becomes a compiler-enforced single edit
|
||||
/// rather than a silently-blanked chart.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Each constant's value is the metric string <em>as persisted</em> in the tall/EAV
|
||||
/// <c>KpiSample</c> table and matched at query time. These values are therefore part of
|
||||
/// the on-disk data contract: this catalog is a symbol-promotion of the existing literals,
|
||||
/// <strong>not</strong> a rename — changing any value would orphan historical samples.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Only the metrics a trend page actually charts are catalogued here. Sources may emit
|
||||
/// additional internal metrics (e.g. the Notification Outbox <c>stuckCount</c> /
|
||||
/// <c>oldestPendingAgeSeconds</c>, the Site Call Audit <c>deliveredLastInterval</c> /
|
||||
/// <c>stuck</c> / <c>oldestPendingAgeSeconds</c>, and the bulk of the Site Health catalog)
|
||||
/// that no page references; those stay private to their source until a page charts them.
|
||||
/// Constants are grouped by source via nested static classes mirroring
|
||||
/// <see cref="KpiSources"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class KpiMetrics
|
||||
{
|
||||
/// <summary>
|
||||
/// Charted Notification Outbox (#21) metrics — <see cref="KpiSources.NotificationOutbox"/>.
|
||||
/// Rendered by the Central UI Notification Outbox KPIs trend panel.
|
||||
/// </summary>
|
||||
public static class NotificationOutbox
|
||||
{
|
||||
/// <summary>Pending-queue depth (rows awaiting delivery).</summary>
|
||||
public const string QueueDepth = "queueDepth";
|
||||
|
||||
/// <summary>Parked-row count.</summary>
|
||||
public const string ParkedCount = "parkedCount";
|
||||
|
||||
/// <summary>Rows delivered in the last KPI interval.</summary>
|
||||
public const string DeliveredLastInterval = "deliveredLastInterval";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Charted Site Call Audit (#22) metrics — <see cref="KpiSources.SiteCallAudit"/>.
|
||||
/// Rendered by the Central UI Site Calls report trend panel.
|
||||
/// </summary>
|
||||
public static class SiteCallAudit
|
||||
{
|
||||
/// <summary>Buffered (non-terminal) cached-call count.</summary>
|
||||
public const string Buffered = "buffered";
|
||||
|
||||
/// <summary>Parked cached-call count.</summary>
|
||||
public const string Parked = "parked";
|
||||
|
||||
/// <summary>Cached calls that failed permanently in the last KPI interval.</summary>
|
||||
public const string FailedLastInterval = "failedLastInterval";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Charted Audit Log (#23) metrics — <see cref="KpiSources.AuditLog"/>.
|
||||
/// Rendered by the Central UI Audit Log page trend panel.
|
||||
/// </summary>
|
||||
public static class AuditLog
|
||||
{
|
||||
/// <summary>Audit events recorded in the trailing hour.</summary>
|
||||
public const string TotalEventsLastHour = "totalEventsLastHour";
|
||||
|
||||
/// <summary>Error-row audit events recorded in the trailing hour.</summary>
|
||||
public const string ErrorEventsLastHour = "errorEventsLastHour";
|
||||
|
||||
/// <summary>Total pending (not-yet-forwarded) audit backlog.</summary>
|
||||
public const string BacklogTotal = "backlogTotal";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Charted Site Health (#11) metrics — <see cref="KpiSources.SiteHealth"/>.
|
||||
/// Rendered by the Central UI Health-dashboard per-site trend panel.
|
||||
/// </summary>
|
||||
public static class SiteHealth
|
||||
{
|
||||
/// <summary>Data connections not in the Connected state.</summary>
|
||||
public const string ConnectionsDown = "connectionsDown";
|
||||
|
||||
/// <summary>Dead-letter count reported by the site.</summary>
|
||||
public const string DeadLetters = "deadLetters";
|
||||
|
||||
/// <summary>Script-execution error count reported by the site.</summary>
|
||||
public const string ScriptErrors = "scriptErrors";
|
||||
|
||||
/// <summary>Summed store-and-forward buffer depth across all buffers.</summary>
|
||||
public const string SfBufferDepth = "sfBufferDepth";
|
||||
}
|
||||
}
|
||||
@@ -15,4 +15,8 @@ public sealed record BundleSummary(
|
||||
// written by older exporters (which omit these JSON properties) deserialize fine.
|
||||
int Sites = 0,
|
||||
int DataConnections = 0,
|
||||
int Instances = 0);
|
||||
int Instances = 0,
|
||||
// Additive (S10b): SMS provider config count, mirroring SmtpConfigs. Defaulted to
|
||||
// 0 so manifests written by older exporters (which omit this JSON property)
|
||||
// deserialize fine.
|
||||
int SmsConfigs = 0);
|
||||
|
||||
@@ -17,11 +17,18 @@ public sealed record ExportSelection(
|
||||
// Additive (M8 A1): site/instance-scoped export. Defaulted to empty so every
|
||||
// existing positional caller keeps compiling; older callers select no sites/instances.
|
||||
IReadOnlyList<int>? SiteIds = null,
|
||||
IReadOnlyList<int>? InstanceIds = null)
|
||||
IReadOnlyList<int>? InstanceIds = null,
|
||||
// Additive (S10b): SMS provider config export, mirroring SmtpConfigurationIds.
|
||||
// Defaulted null (trailing) so every existing positional caller keeps compiling;
|
||||
// older callers select no SMS configs.
|
||||
IReadOnlyList<int>? SmsConfigurationIds = null)
|
||||
{
|
||||
/// <summary>Sites selected for site/instance-scoped export (M8). Never null.</summary>
|
||||
public IReadOnlyList<int> SiteIds { get; init; } = SiteIds ?? Array.Empty<int>();
|
||||
|
||||
/// <summary>Instances selected for site/instance-scoped export (M8). Never null.</summary>
|
||||
public IReadOnlyList<int> InstanceIds { get; init; } = InstanceIds ?? Array.Empty<int>();
|
||||
|
||||
/// <summary>SMS provider configurations selected for export (S10b). Never null.</summary>
|
||||
public IReadOnlyList<int> SmsConfigurationIds { get; init; } = SmsConfigurationIds ?? Array.Empty<int>();
|
||||
}
|
||||
|
||||
+52
-1
@@ -42,9 +42,60 @@ public class NotificationRecipientConfiguration : IEntityTypeConfiguration<Notif
|
||||
.IsRequired()
|
||||
.HasMaxLength(200);
|
||||
|
||||
// EmailAddress is now nullable — an SMS-only recipient carries a PhoneNumber and no
|
||||
// email. The max length is unchanged from the original email-only mapping.
|
||||
builder.Property(r => r.EmailAddress)
|
||||
.IsRequired()
|
||||
.IsRequired(false)
|
||||
.HasMaxLength(500);
|
||||
|
||||
// PhoneNumber (E.164, e.g. +14155552671) — nullable, present only for SMS recipients.
|
||||
builder.Property(r => r.PhoneNumber)
|
||||
.IsRequired(false)
|
||||
.HasMaxLength(32);
|
||||
}
|
||||
}
|
||||
|
||||
public class SmsConfigurationConfiguration : IEntityTypeConfiguration<SmsConfiguration>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Configure(EntityTypeBuilder<SmsConfiguration> builder)
|
||||
{
|
||||
builder.HasKey(s => s.Id);
|
||||
|
||||
builder.Property(s => s.AccountSid)
|
||||
.IsRequired()
|
||||
.HasMaxLength(100);
|
||||
|
||||
// Stored encrypted at rest (EncryptedStringConverter, wired in
|
||||
// ScadaBridgeDbContext.ApplySecretColumnEncryption). Ciphertext is larger than the
|
||||
// plaintext, so the column is sized generously to avoid truncation — mirrors
|
||||
// SmtpConfiguration.Credentials.
|
||||
builder.Property(s => s.AuthToken)
|
||||
.HasMaxLength(8000);
|
||||
|
||||
// Optional: a Twilio Messaging-Service-only config has no From number (a valid
|
||||
// config carries a FromNumber and/or a MessagingServiceSid).
|
||||
builder.Property(s => s.FromNumber)
|
||||
.IsRequired(false)
|
||||
.HasMaxLength(32);
|
||||
|
||||
builder.Property(s => s.MessagingServiceSid)
|
||||
.HasMaxLength(100);
|
||||
|
||||
builder.Property(s => s.ApiBaseUrl)
|
||||
.HasMaxLength(500);
|
||||
|
||||
// The non-parameter constructor seeds ConnectionTimeoutSeconds/MaxRetries/RetryDelay
|
||||
// with sensible defaults; mapping them as REQUIRED columns preserves round-trip
|
||||
// fidelity for those values (S1 review note).
|
||||
builder.Property(s => s.ConnectionTimeoutSeconds)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.MaxRetries)
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(s => s.RetryDelay)
|
||||
.IsRequired();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+43
-4
@@ -7,18 +7,57 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
|
||||
/// <inheritdoc />
|
||||
public partial class ResyncLdapGroupMappingSeed : Migration
|
||||
{
|
||||
/// <summary>
|
||||
/// SQLite idempotent insert for the Id=5 (SCADA-Viewers → Viewer) seed row.
|
||||
/// <c>INSERT OR IGNORE</c> skips the row when the <c>Id</c> primary key already
|
||||
/// exists, so replaying this migration against a DB that already carries Id=5
|
||||
/// (e.g. one seeded by a newer HasData baseline) is a no-op rather than a PK
|
||||
/// violation. Kept as a named constant for readability and so the emitted
|
||||
/// SQLite SQL is documented in one place; the idempotency test drives the
|
||||
/// real migration through EF's SQL generator rather than reading this directly.
|
||||
/// </summary>
|
||||
internal const string SqliteInsertSql =
|
||||
"INSERT OR IGNORE INTO \"LdapGroupMappings\" (\"Id\", \"LdapGroupName\", \"Role\") " +
|
||||
"VALUES (5, 'SCADA-Viewers', 'Viewer');";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.InsertData(
|
||||
table: "LdapGroupMappings",
|
||||
columns: new[] { "Id", "LdapGroupName", "Role" },
|
||||
values: new object[] { 5, "SCADA-Viewers", "Viewer" });
|
||||
// #70: this seed insert must be idempotent. The original unconditional
|
||||
// InsertData threw a PK violation (and crash-looped startup, since dev
|
||||
// auto-applies migrations) on any pre-existing DB that already had Id=5
|
||||
// — e.g. one seeded via the old HasData baseline. Guard the insert so it
|
||||
// is a no-op when the row already exists. Provider-aware because the
|
||||
// production central DB is SQL Server while dev/test run on SQLite, and
|
||||
// the two speak different conditional-insert dialects (mirrors the
|
||||
// NotificationOutboxRepository.InsertIfNotExists pattern, #286).
|
||||
if (migrationBuilder.ActiveProvider == "Microsoft.EntityFrameworkCore.Sqlite")
|
||||
{
|
||||
// SQLite: INSERT OR IGNORE silently skips the row on a PK clash.
|
||||
migrationBuilder.Sql(SqliteInsertSql);
|
||||
}
|
||||
else
|
||||
{
|
||||
// SQL Server: guard with IF NOT EXISTS. LdapGroupMappings.Id is an
|
||||
// IDENTITY column (InitialSchema declares SqlServer:Identity "1, 1"),
|
||||
// so an explicit Id value requires SET IDENTITY_INSERT ON/OFF around
|
||||
// the INSERT — exactly what EF's InsertData emitted for this row.
|
||||
migrationBuilder.Sql(@"
|
||||
IF NOT EXISTS (SELECT 1 FROM [LdapGroupMappings] WHERE [Id] = 5)
|
||||
BEGIN
|
||||
SET IDENTITY_INSERT [LdapGroupMappings] ON;
|
||||
INSERT INTO [LdapGroupMappings] ([Id], [LdapGroupName], [Role])
|
||||
VALUES (5, N'SCADA-Viewers', N'Viewer');
|
||||
SET IDENTITY_INSERT [LdapGroupMappings] OFF;
|
||||
END");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// Idempotent delete: removes the Id=5 row if present, no-op otherwise.
|
||||
// Unchanged in behaviour from the original DeleteData.
|
||||
migrationBuilder.DeleteData(
|
||||
table: "LdapGroupMappings",
|
||||
keyColumn: "Id",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user