diff --git a/docs/plans/sql/WidenSystemArtifactPerSiteStatus.sql b/docs/plans/sql/WidenSystemArtifactPerSiteStatus.sql new file mode 100644 index 00000000..5e481b57 --- /dev/null +++ b/docs/plans/sql/WidenSystemArtifactPerSiteStatus.sql @@ -0,0 +1,20 @@ +-- WidenSystemArtifactPerSiteStatus (2026-12-03, DEP-3 / code-review WP2 task 2.9). Widens +-- SystemArtifactDeploymentRecords.PerSiteStatus from nvarchar(4000) to nvarchar(max): one serialized +-- per-site result per site overflowed 4000 chars at ~25 sites, failing Deploy Artifacts after every +-- site had applied. The table holds one small row per Deploy Artifacts run. Not yet applied to QA/DEV. +BEGIN TRANSACTION; +DECLARE @var nvarchar(max); +SELECT @var = QUOTENAME([d].[name]) +FROM [sys].[default_constraints] [d] +INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id] +WHERE ([d].[parent_object_id] = OBJECT_ID(N'[SystemArtifactDeploymentRecords]') AND [c].[name] = N'PerSiteStatus'); +IF @var IS NOT NULL EXEC(N'ALTER TABLE [SystemArtifactDeploymentRecords] DROP CONSTRAINT ' + @var + ';'); +ALTER TABLE [SystemArtifactDeploymentRecords] ALTER COLUMN [PerSiteStatus] nvarchar(max) NULL; + +INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) +VALUES (N'20261203151127_WidenSystemArtifactPerSiteStatus', N'10.0.13'); + +COMMIT; +GO + + diff --git a/docs/requirements/Component-CLI.md b/docs/requirements/Component-CLI.md index 0a07e74f..c22023d6 100644 --- a/docs/requirements/Component-CLI.md +++ b/docs/requirements/Component-CLI.md @@ -171,6 +171,8 @@ scadabridge site area delete --id scadabridge site deploy-artifacts [--site-id ] ``` +`site update`, `data-connection update` and `api-method update` are **partial** updates (CLI-2, 2026-12-03): only the options passed are sent; an omitted option travels as null and the server keeps the stored value (preserve-if-null in the `ManagementActor` handler), and an empty string (`""`) clears an optional field. Previously every omitted option was sent as null or a default (`--failover-retry-count` 3, `--timeout` 30) and overwrote the stored value — `site update --id 3 --name X` nulled both gRPC addresses. An older CLI that always sends every field still deserializes unchanged. + ### Deployment Commands ``` scadabridge deploy instance --id @@ -185,7 +187,7 @@ scadabridge deploy status [--instance-id ] [--status ] [--page ] scadabridge data-connection list [--site-id ] scadabridge data-connection get --id scadabridge data-connection create --site-id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] -scadabridge data-connection update --id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] +scadabridge data-connection update --id [--name ] [--protocol ] [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] scadabridge data-connection delete --id scadabridge data-connection move --id --site-id ``` @@ -423,7 +425,7 @@ scadabridge db-connection delete --id scadabridge api-method list scadabridge api-method get --id scadabridge api-method create --name --script [--timeout ] [--parameters ] [--return-def ] -scadabridge api-method update --id --script [--timeout ] [--parameters ] [--return-def ] +scadabridge api-method update --id [--script ] [--timeout ] [--parameters ] [--return-def ] scadabridge api-method delete --id scadabridge api-method validate --id scadabridge api-method recompile --id diff --git a/docs/requirements/Component-TemplateEngine.md b/docs/requirements/Component-TemplateEngine.md index 836b8925..a28f0c0f 100644 --- a/docs/requirements/Component-TemplateEngine.md +++ b/docs/requirements/Component-TemplateEngine.md @@ -156,6 +156,8 @@ When an instance is deployed, the Template Engine resolves the full configuratio 5. Resolve data connection bindings — replace connection name references with concrete connection details from the site. 6. Output a flat structure: list of attributes with resolved values and data source addresses, list of alarms with resolved trigger definitions, list of scripts with resolved code and triggers. +**Alarm on-trigger script resolution (2026-12-03, TPL-1/TPL-2/TPL-5).** An alarm's `OnTriggerScriptId` is resolved **by name within the alarm's own chain**: the id is looked up among the script rows of every template in that alarm's inheritance chain (base rows, derived overrides and `IsInherited` placeholders), and the row's *name* is path-qualified with the alarm's composition prefix (`Pump1.HighTemp` → `Pump1.OnHigh`). It used to go through one flatten-wide `script id → canonical name` map, which (a) made every slot of a module composed twice run the **last** slot's script, since all slots share the base script row id; (b) dropped the link (null on-trigger script) when a derived template overrode the script, since the override row has a different id; and (c) let the second visit of a nested slot overwrite a slot-level on-trigger override. The value is decided by the pass that actually adds the alarm (first wins, same as the alarm itself). An id that is not a script row of the alarm's own chain keeps the old flatten-wide fallback, and a reference that names no resolved script is still left null. **This changes the revision hash** of any instance whose flattened alarms were affected — such instances read *Out of date* once and redeploy with the corrected script link. + ### Flatten-session caching and the graph watermark (WP2.5) The flatten above is driven per instance, so an unmemoised implementation re-walks diff --git a/docs/requirements/Component-Transport.md b/docs/requirements/Component-Transport.md index 6a52e102..1886dca4 100644 --- a/docs/requirements/Component-Transport.md +++ b/docs/requirements/Component-Transport.md @@ -22,7 +22,7 @@ As of M8 (T18), Transport is no longer limited to central-only configuration: it - Move **site-scoped configuration** (T18): `Site` definitions, site-scoped `DataConnection`s (protocol connections — distinct from External-System `DatabaseConnection`s), and `Instance`s along with their `InstanceAttributeOverride` / `InstanceAlarmOverride` / `InstanceNativeAlarmSourceOverride` / `InstanceConnectionBinding` children and `Area` membership (carried by name). - Reconcile cross-environment site identifiers and connection names through the **name-mapping subsystem** (`BundleNameMap`): auto-match by identifier/name, operator override via the import-wizard Map step or CLI flags, and per-conflict create-or-bind resolution (see "Name Mapping"). - Compute a **per-line (Myers) diff** for code fields on Modified artifacts (T20) via the pure `LineDiffer`, embedding a size-capped structured line diff in each `ArtifactDiff`. Two independent caps guard the diff: a 400-line **output** cap on the emitted hunk list, and — as of arch-review 05 (Task 22) — a `MaxInputLines` **input** cap (4000 combined lines) that short-circuits the O((N+M)²) Myers trace to a summary-only result (`Truncated = true`, add/remove totals only) so a bloated or crafted bundle cannot OOM the active central node from the import preview. -- Serialize and deserialize all transportable entity types to/from bundle DTOs, carving secret fields into an isolated `SecretsBlock`. A template travels with **all** of its child collections — `TemplateAttribute`, `TemplateAlarm`, `TemplateScript`, `TemplateComposition`, and `TemplateNativeAlarmSource` (including `IsInherited` placeholder rows, which the collision detector depends on) — each field-faithful on Add and reconciled add/update/delete on Overwrite. Field completeness is verified by a reflection round-trip guard over every writable property (Add + Overwrite), and includes the fields earlier revisions dropped: the derived-lock flag `LockedInDerived` on attributes/alarms/scripts, script cadence/timeout (`MinTimeBetweenRuns` / `ExecutionTimeoutSeconds`), and — for instances — the real `AreaName` (the exporter previously emitted `null`, half-shipping the Area-by-name feature). Carrying the native alarm sources is what keeps an imported `InstanceNativeAlarmSourceOverride` from dangling against a source the target template would otherwise lack. +- Serialize and deserialize all transportable entity types to/from bundle DTOs, carving secret fields into an isolated `SecretsBlock`. A template travels with **all** of its child collections — `TemplateAttribute`, `TemplateAlarm`, `TemplateScript`, `TemplateComposition`, and `TemplateNativeAlarmSource` (including `IsInherited` placeholder rows, which the collision detector depends on) — each field-faithful on Add and reconciled add/update/delete on Overwrite. Field completeness is verified by a reflection round-trip guard over every writable property (Add + Overwrite), and includes the fields earlier revisions dropped: the derived-lock flag `LockedInDerived` on attributes/alarms/scripts, script cadence/timeout (`MinTimeBetweenRuns` / `ExecutionTimeoutSeconds`), and — for instances — the real `AreaName` (the exporter previously emitted `null`, half-shipping the Area-by-name feature) plus, since 2026-12-03 (TRN-8), the additive `AreaPath` (root→leaf names): the importer resolves the area level by level and creates any missing level under its real parent, since the same leaf name may sit under two parents. A pre-TRN-8 bundle carries only the leaf; an ambiguous leaf then resolves deterministically (a root-level area, else the lowest id) with an `ImportResult.Warnings` entry instead of taking whichever row came back first. Carrying the native alarm sources is what keeps an imported `InstanceNativeAlarmSourceOverride` from dangling against a source the target template would otherwise lack. - Encrypt content with AES-256-GCM + PBKDF2-SHA256 (600 000 iterations) when a passphrase is supplied; leave content plaintext with a UI warning and an `UnencryptedBundleExport` audit event when none is given. - Validate `manifest.json` on upload: format version gating, SHA-256 content hash verification. - **Optionally sign** exported bundles (ECDSA P-256 detached signature in `manifest.sig`) and enforce an import-side signature policy against a trust store — off by default (ScadaBridge#45; see "Bundle Signing"). @@ -97,7 +97,7 @@ The manifest is plaintext so the import wizard can preview bundle contents and s ### `content.json` / `content.enc` - One top-level array per entity type, POCO shapes serialized via `System.Text.Json`. As of schema 1.1 (T18) this includes `sites`, `dataConnections`, and `instances` arrays (`SiteDto`, `DataConnectionDto`, `InstanceDto` + its override-child and connection-binding DTOs) alongside the existing central-config arrays. -- Secret fields (API key hashes, SMTP password, external system credentials, DB connection passwords) live in a nested `secrets` block on each affected entity. Per the D3 "carry full config (encrypted secrets)" decision, a `DataConnection`'s `PrimaryConfiguration` / `BackupConfiguration` (endpoint + credentials) also ride inside this encrypted `SecretsBlock`; they appear in diffs as presence-only and are never echoed in plaintext. A `Site`'s `NodeA`/`NodeB` and `GrpcNodeA`/`GrpcNodeB` addresses travel as ordinary (non-secret) `SiteDto` fields. +- Secret fields (API key hashes, SMTP password, external system credentials, DB connection passwords) live in a nested `secrets` block on each affected entity. Per the D3 "carry full config (encrypted secrets)" decision, a `DataConnection`'s `PrimaryConfiguration` / `BackupConfiguration` (endpoint + credentials) also ride inside this encrypted `SecretsBlock`; they appear in diffs presence-only and are never echoed in plaintext. **Secret values are still compared (2026-12-03, TRN-2):** the preview hashes both sides (SHA-256) and, when a value present on both sides differs, reports the value-free marker `` → ``, so the row classifies **Modified**. Before, only a presence flip counted, so a changed OPC UA endpoint (or DB connection string, external-system auth, SMTP credentials, SMS token) read *Identical* and was force-skipped, and an Overwrite driven by an unrelated field replaced the value unseen. A `Site`'s `NodeA`/`NodeB` and `GrpcNodeA`/`GrpcNodeB` addresses travel as ordinary (non-secret) `SiteDto` fields. - The whole `content` blob is AES-256-GCM encrypted with a key derived via PBKDF2-SHA256 (600 000 iterations) from the user's passphrase, with per-bundle random salt and per-encryption random IV. - Unencrypted bundles are allowed but the UI warns and audit-tags them `UnencryptedBundleExport`. @@ -234,7 +234,7 @@ Upload → Passphrase → Diff → Confirm → Result. The **Map** step is not a **Step 4 — Diff & resolve conflicts.** For each artifact in the bundle, compare to existing by name: - **Identical** (field-by-field) → marked, auto-skipped, cannot be selected. -- **Modified** → shows a real per-line `+/-` diff for code fields (`TemplateScript.Code`, `SharedScript.Code`, `ApiMethod.Script`), rendered by the shared `LineDiffView` component from the structured `lineDiff` payload (T20). User picks Skip / Overwrite / Rename. +- **Modified** → shows a real per-line `+/-` diff for code fields (`TemplateScript.Code`, `SharedScript.Code`, `ApiMethod.Script`), rendered by the shared `LineDiffView` component from the structured `lineDiff` payload (T20). User picks Skip / Overwrite / Rename — **Rename is not offered for a Site, DataConnection, SmtpConfiguration or SmsConfiguration (TRN-9, 2026-12-03)**: it was silently treated as Skip for sites/connections and wrote a junk second SMTP/SMS row (mangled Host / AccountSid) that delivery never used. `ApplyAsync` rejects such a resolution (`ImportRenameSupport`), and the CLI's `--on-conflict rename` falls back to Skip for those types with a result warning. - **New** → marked `+ Add`. User can opt to skip individually. Bulk "Apply to all" at the top (Overwrite / Skip / Rename), overridable per row. Summary line at the bottom: "5 add · 2 overwrite · 1 skip · 0 rename". @@ -302,7 +302,7 @@ Site identifiers and connection names are environment-specific, so a bundle expo **Identity keys.** Sites are matched by `SiteIdentifier`; connections by the **site-qualified** key `{SiteIdentifier}/{Name}`; instances by `UniqueName`. -**Auto-match → operator override → apply.** The importer first auto-matches every source site and connection against the target by these identity keys. The operator confirms/overrides via the Central UI **Map step** (Step 3) or the CLI `--map-site` / `--map-connection` / `--create-missing-*` flags. References that neither auto-match nor are set to Create-new become **blocker rows** (UI) — or, on the CLI without `--create-missing-sites` / `--create-missing-connections`, abort before apply. +**Auto-match → operator override → apply.** The importer first auto-matches every source site and connection against the target by these identity keys. **The preview honours the name map (2026-12-03, TRN-3):** `PreviewAsync` takes an optional `BundleNameMap`; under a MapToExisting redirect, the connection / instance diffs, the connection auto-match and the unresolved-connection blocker run against the **mapped** target site and connection. The CLI import passes its explicit `--map-site` / `--map-connection` redirects to the preview before the blocker gate (a connection present only on the mapped site used to be a blocker no mapping could clear), and the Central UI re-runs the preview under the Map-step choices when Confirm is pressed. On apply, a Create-new for a site identifier or a `(site, connection)` name the target already holds binds to that existing row (its own Skip/Overwrite resolution then applies) instead of inserting a duplicate the unique index rejects. **Site-scoped and template-reference lookups are case-insensitive (TRN-7)** — connections, instances, the instance's template, and the composition / inheritance rewire fallbacks match exact spelling first, then case-insensitively, the way the database collation and its unique indexes do. **Instance diff (TRN-6):** a binding's bound connection is compared by name (the existing FK is resolved per site), and `State` is no longer compared — the import never carries a live state, so a State-only difference read Modified and an Overwrite reset a live instance to `NotDeployed` for nothing. The operator confirms/overrides via the Central UI **Map step** (Step 3) or the CLI `--map-site` / `--map-connection` / `--create-missing-*` flags. References that neither auto-match nor are set to Create-new become **blocker rows** (UI) — or, on the CLI without `--create-missing-sites` / `--create-missing-connections`, abort before apply. **Template library reads (review 2026-10-21 04/P4 + 08/P1).** A preview and each apply attempt read the target template library **once**, through body-free projections (`GetTemplateStubsAsync` for id/name maps, `GetAllTemplatesForAnalysisAsync` — untracked, members and lock flags but no script bodies — where members or edges are needed), held on a per-session `TemplateLibrary` and threaded to every consumer: preview diff names, blocker and locked-override scans, apply-time validation, the composition/inheritance rewire fallbacks (formerly a full library reload *inside* the per-template loop), the instance pass's name→id map (overlaid with the change tracker's just-flushed templates), the acyclicity guard and the stale-instance expansion. The full tracked graph is loaded only for the templates the bundle **Overwrites** (`GetTemplatesWithChildrenAsync` by name), since their child syncs mutate it. The acyclicity guard reads the change tracker's staged templates overlaid on that snapshot — the untouched part of the graph has not changed during the apply. Instance lookups are batched by name set (`ITemplateEngineRepository.GetInstancesByUniqueNamesAsync`, one tracked + hydrated read for preview and one for the instance pass, Rename targets included), and the preview resolves an existing instance's template / site / area names from the library, one site list and one area list per site, and reads shared scripts and external systems once each. @@ -315,6 +315,8 @@ Site identifiers and connection names are environment-specific, so a bundle expo - `InstanceConnectionBinding.DataConnectionId` is resolved via the connection map, with a **Pass-2** that also binds connections which already exist in the target but were not carried in the bundle. - `InstanceNativeAlarmSourceOverride.ConnectionNameOverride` is rewritten to the **mapped target** connection name. +**Composition Overwrite (2026-12-03, TRN-4/TRN-5).** An Overwrite of a template whose bundle copy has **no** compositions still runs the composition clear — it used to skip the template entirely, so the target's slots survived an Overwrite the preview said would remove them. A slot the bundle **removes** (its instance name is not among the bundle owner's compositions, and no bundle composition names its composed template) is deleted through `TemplateService.DeleteCompositionAsync`, which also deletes its slot-owned derived template (and that template's nested slots); before, only the row was deleted, leaving a derived template with a dangling `OwnerCompositionId` and a live `ParentTemplateId` that then blocked deleting its base. A slot the bundle re-composes keeps the plain row delete-and-re-add, so a pre-#118 bundle that re-composes a slot onto its derived template by name still resolves. + ### Derived (composition-slot) templates (ScadaBridge#118) Composing a template into a slot creates a slot-owned **derived** template (`IsDerived`, `ParentTemplateId` = the base, `OwnerCompositionId` = the slot) named after the slot. Before #118 the bundle did not say so, and the importer re-created every such template as a **base** template named after its slot. Owner decision (2026-11-10): carry the relationship and rebuild the slot through the normal compose flow. diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs index 546075e6..3ef8dbcf 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs @@ -123,21 +123,27 @@ public static class ApiMethodCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "API method ID", Required = true }; - var scriptOption = new Option("--script") { Description = "Script code", Required = true }; - var timeoutOption = new Option("--timeout") { Description = "Timeout in seconds" }; - timeoutOption.DefaultValueFactory = _ => 30; - var parametersOption = new Option("--parameters") { Description = "Parameter definitions JSON" }; - var returnDefOption = new Option("--return-def") { Description = "Return type definition" }; + var scriptOption = new Option("--script") { Description = "Script code (omitted = unchanged)" }; + var timeoutOption = new Option("--timeout") { Description = "Timeout in seconds (omitted = unchanged)" }; + var parametersOption = new Option("--parameters") { Description = "Parameter definitions JSON (omitted = unchanged; \"\" clears)" }; + var returnDefOption = new Option("--return-def") { Description = "Return type definition (omitted = unchanged; \"\" clears)" }; // bool? so an update that omits the flag leaves the stored value unchanged. var traceAllCallsOption = new Option("--trace-all-calls") { Description = "Trace every production call to this method for the Flow Debugger (true/false; omitted = unchanged; adds 7-10 audit rows per call)" }; - var cmd = new Command("update") { Description = "Update an API method" }; + var cmd = new Command("update") { Description = "Update an API method (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(scriptOption); cmd.Add(timeoutOption); @@ -147,14 +153,16 @@ public static class ApiMethodCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var script = result.GetValue(scriptOption)!; + var script = result.GetValue(scriptOption); var timeout = result.GetValue(timeoutOption); var parameters = result.GetValue(parametersOption); var returnDef = result.GetValue(returnDefOption); var traceAllCalls = result.GetValue(traceAllCallsOption); + var command = new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs index 4a06dd19..8839b319 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs @@ -58,18 +58,25 @@ public static class DataConnectionCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "Data connection ID", Required = true }; - var nameOption = new Option("--name") { Description = "Connection name", Required = true }; - var protocolOption = new Option("--protocol") { Description = "Protocol", Required = true }; - var configOption = new Option("--primary-config", "--configuration") { Description = "Primary configuration JSON" }; - var backupConfigOption = new Option("--backup-config") { Description = "Backup configuration JSON" }; + var nameOption = new Option("--name") { Description = "Connection name (omitted = unchanged)" }; + var protocolOption = new Option("--protocol") { Description = "Protocol (omitted = unchanged)" }; + var configOption = new Option("--primary-config", "--configuration") { Description = "Primary configuration JSON (omitted = unchanged)" }; + var backupConfigOption = new Option("--backup-config") { Description = "Backup configuration JSON (omitted = unchanged; \"\" removes the backup)" }; var configFileOption = ValueSourceOptions.CreateFileOption(configOption, "the primary configuration JSON"); var backupConfigFileOption = ValueSourceOptions.CreateFileOption(backupConfigOption, "the backup configuration JSON"); - var failoverRetryOption = new Option("--failover-retry-count") { Description = "Number of retries before failover to backup", DefaultValueFactory = _ => 3 }; + var failoverRetryOption = new Option("--failover-retry-count") { Description = "Number of retries before failover to backup (omitted = unchanged)" }; - var cmd = new Command("update") { Description = "Update a data connection" }; + var cmd = new Command("update") { Description = "Update a data connection (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(nameOption); cmd.Add(protocolOption); @@ -80,14 +87,16 @@ public static class DataConnectionCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var name = result.GetValue(nameOption)!; - var protocol = result.GetValue(protocolOption)!; + var name = result.GetValue(nameOption); + var protocol = result.GetValue(protocolOption); var config = ValueSourceOptions.GetValue(result, configOption, configFileOption); var backupConfig = ValueSourceOptions.GetValue(result, backupConfigOption, backupConfigFileOption); var failoverRetryCount = result.GetValue(failoverRetryOption); + var command = new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs index 6c0a900f..efd76b5d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs @@ -88,17 +88,24 @@ public static class SiteCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "Site ID", Required = true }; - var nameOption = new Option("--name") { Description = "Site name", Required = true }; - var descOption = new Option("--description") { Description = "Site description" }; - var nodeAOption = new Option("--node-a-address") { Description = "Akka address for Node A" }; - var nodeBOption = new Option("--node-b-address") { Description = "Akka address for Node B" }; - var grpcNodeAOption = new Option("--grpc-node-a-address") { Description = "gRPC address for Node A" }; - var grpcNodeBOption = new Option("--grpc-node-b-address") { Description = "gRPC address for Node B" }; + var nameOption = new Option("--name") { Description = "Site name (omitted = unchanged)" }; + var descOption = new Option("--description") { Description = "Site description (omitted = unchanged; \"\" clears)" }; + var nodeAOption = new Option("--node-a-address") { Description = "Akka address for Node A (omitted = unchanged; \"\" clears)" }; + var nodeBOption = new Option("--node-b-address") { Description = "Akka address for Node B (omitted = unchanged; \"\" clears)" }; + var grpcNodeAOption = new Option("--grpc-node-a-address") { Description = "gRPC address for Node A (omitted = unchanged; \"\" clears)" }; + var grpcNodeBOption = new Option("--grpc-node-b-address") { Description = "gRPC address for Node B (omitted = unchanged; \"\" clears)" }; - var cmd = new Command("update") { Description = "Update an existing site" }; + var cmd = new Command("update") { Description = "Update an existing site (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(nameOption); cmd.Add(descOption); @@ -109,15 +116,17 @@ public static class SiteCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var name = result.GetValue(nameOption)!; + var name = result.GetValue(nameOption); var desc = result.GetValue(descOption); var nodeA = result.GetValue(nodeAOption); var nodeB = result.GetValue(nodeBOption); var grpcNodeA = result.GetValue(grpcNodeAOption); var grpcNodeB = result.GetValue(grpcNodeBOption); + var command = new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md index 73e2fa41..01388f3c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md @@ -976,22 +976,21 @@ scadabridge --url site create --name --identifier [--des #### `site update` -Update an existing site. An update **replaces** the whole entity — every required field -below must be supplied with its post-update value, even if unchanged. +Update an existing site. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url site update --id --name [--description ] [--node-a-address ] [--node-b-address ] [--grpc-node-a-address ] [--grpc-node-b-address ] +scadabridge --url site update --id [--name ] [--description ] [--node-a-address ] [--node-b-address ] [--grpc-node-a-address ] [--grpc-node-b-address ] ``` | Option | Required | Description | |--------|----------|-------------| | `--id` | yes | Site ID | -| `--name` | yes | Human-readable site name | -| `--description` | no | Site description | -| `--node-a-address` | no | Akka.NET cluster address for Node A | -| `--node-b-address` | no | Akka.NET cluster address for Node B | -| `--grpc-node-a-address` | no | gRPC streaming address for Node A | -| `--grpc-node-b-address` | no | gRPC streaming address for Node B | +| `--name` | no | Human-readable site name (omitted = unchanged) | +| `--description` | no | Site description (omitted = unchanged; `""` clears) | +| `--node-a-address` | no | Akka.NET cluster address for Node A (omitted = unchanged; `""` clears) | +| `--node-b-address` | no | Akka.NET cluster address for Node B (omitted = unchanged; `""` clears) | +| `--grpc-node-a-address` | no | gRPC streaming address for Node A (omitted = unchanged; `""` clears) | +| `--grpc-node-b-address` | no | gRPC streaming address for Node B (omitted = unchanged; `""` clears) | #### `site delete` @@ -1263,23 +1262,22 @@ scadabridge --url data-connection create --site-id --name - #### `data-connection update` -Update a data connection definition. An update **replaces** the whole entity — every -required field below must be supplied, even if unchanged. +Update a data connection definition. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url data-connection update --id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] +scadabridge --url data-connection update --id [--name ] [--protocol ] [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] ``` | Option | Required | Description | |--------|----------|-------------| | `--id` | yes | Data connection ID | -| `--name` | yes | Connection name | -| `--protocol` | yes | Protocol identifier | -| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`) | +| `--name` | no | Connection name (omitted = unchanged) | +| `--protocol` | no | Protocol identifier (omitted = unchanged) | +| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`; omitted = unchanged) | | `--primary-config-file` | no | Read the primary configuration from a file, or stdin with `-` — use it when the config carries a secret (MxGateway `apiKey`, OPC UA password). Not together with `--primary-config`. | -| `--backup-config` | no | Backup protocol-specific configuration as a JSON string | +| `--backup-config` | no | Backup protocol-specific configuration as a JSON string (omitted = unchanged; `""` removes the backup) | | `--backup-config-file` | no | Read the backup configuration from a file, or stdin with `-`. Not together with `--backup-config`. | -| `--failover-retry-count` | no | Retries before failover to the backup configuration (default: `3`) | +| `--failover-retry-count` | no | Retries before failover to the backup configuration (omitted = unchanged) | #### `data-connection move` @@ -2497,21 +2495,20 @@ scadabridge --url api-method create --name --script [--t #### `api-method update` -Update an inbound API method. An update **replaces** the whole entity — every required -field below must be supplied, even if unchanged. +Update an inbound API method. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url api-method update --id --script [--timeout ] [--parameters ] [--return-def ] [--trace-all-calls ] +scadabridge --url api-method update --id [--script ] [--timeout ] [--parameters ] [--return-def ] [--trace-all-calls ] ``` | Option | Required | Default | Description | |--------|----------|---------|-------------| | `--id` | yes | — | API method ID | -| `--script` | yes | — | Script source code implementing the method | -| `--timeout` | no | `30` | Timeout in seconds | -| `--parameters` | no | — | Parameter definitions JSON | -| `--return-def` | no | — | Return type definition JSON | -| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only). Omitted = the stored value is left as-is (the one field the replace-all rule does not apply to) | +| `--script` | no | unchanged | Script source code implementing the method | +| `--timeout` | no | unchanged | Timeout in seconds | +| `--parameters` | no | unchanged | Parameter definitions JSON (`""` clears) | +| `--return-def` | no | unchanged | Return type definition JSON (`""` clears) | +| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only) | Script changes take effect immediately — the updated code is recompiled in-memory on the active central node. No restart is required. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor index 9c325214..11d3b548 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor @@ -168,8 +168,11 @@ return; } await MutationServices.ExecuteConfigurationAsync(_editingSite is not null - ? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim(), - _formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim()) + // Update is preserve-if-null (CLI-2): this full-entity form sends "" for a + // field the operator cleared so the server clears it rather than keeping it. + ? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim() ?? "", + _formNodeAAddress?.Trim() ?? "", _formNodeBAddress?.Trim() ?? "", + _formGrpcNodeAAddress?.Trim() ?? "", _formGrpcNodeBAddress?.Trim() ?? "") : new CreateSiteCommand(_formName.Trim(), _formIdentifier.Trim(), _formDescription?.Trim(), _formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim())); CommunicationService.RefreshSiteAddresses(); diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor index e36eddfd..d68ddd86 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor @@ -399,7 +399,8 @@ { var methodName = _existing?.Name ?? _name.Trim(); await MutationServices.ExecuteConfigurationAsync(_existing is not null - ? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls) + // Update is preserve-if-null (CLI-2): "" clears a removed definition. + ? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? "", _returns?.Trim() ?? "", _traceAllCalls) : new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)); // Reconcile per-key method-scopes for the affected keys (added/removed vs. load time). diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor index 6f40918e..913839ab 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor @@ -382,7 +382,8 @@ try { await MutationServices.ExecuteConfigurationAsync(_editingConnection is not null - ? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3) + // Update is preserve-if-null (CLI-2): "" clears a removed backup endpoint. + ? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson ?? "", _showBackup ? _formFailoverRetryCount : 3) : new CreateDataConnectionCommand(_formSiteId, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3)); NavigationManager.NavigateTo("/design/connections"); } diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor index 0659a4e2..1ce3bce2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor @@ -482,7 +482,10 @@ var key = (item.EntityType, item.Name);
- @foreach (var action in new[] { ResolutionAction.Overwrite, ResolutionAction.Skip, ResolutionAction.Rename }) + @* TRN-9: Rename is not offered where it has no meaning (site, data connection, SMTP/SMS). *@ + @foreach (var action in ImportRenameSupport.IsSupported(item.EntityType) + ? new[] { ResolutionAction.Overwrite, ResolutionAction.Skip, ResolutionAction.Rename } + : new[] { ResolutionAction.Overwrite, ResolutionAction.Skip }) { var inputId = $"res-{item.EntityType}-{item.Name}-{action}";
diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs index f6f7fe3e..6c2f7fc8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs @@ -823,9 +823,10 @@ public partial class TransportImport : ComponentBase, IDisposable return (adds, overs, skips, renames, blockers); } - private void GoToConfirm() + private async Task GoToConfirm() { if (_preview is null) return; + await RefreshPreviewUnderMappingAsync(); if (_preview.Items.Any(i => i.Kind == ConflictKind.Blocker)) { _errorMessage = "Cannot proceed while blockers exist — resolve or remove blocker rows first."; @@ -835,6 +836,58 @@ public partial class TransportImport : ComponentBase, IDisposable _step = ImportWizardStep.Confirm; } + /// + /// TRN-3: when the Map step redirects a source site or connection to a differently + /// named target, the diff rows, auto-matches and unresolved-connection blockers of + /// the first preview were computed against the SOURCE identity. Re-run the preview + /// under the current name map so the blocker gate (and the diff table) reflect the + /// mapped targets. The Map step's required-mapping lists are kept (they are keyed + /// by source reference); resolutions the operator already chose are kept unless the + /// row's conflict kind changed, in which case that row gets its new default. + /// + private async Task RefreshPreviewUnderMappingAsync() + { + if (_session is null || _preview is null || _resolutions is null) return; + var map = BuildNameMap(); + var redirects = map.Sites.Any(m => m.Action == MappingAction.MapToExisting + && !string.Equals(m.TargetSiteIdentifier, m.SourceSiteIdentifier, StringComparison.Ordinal)) + || map.Connections.Any(m => m.Action == MappingAction.MapToExisting + && !string.Equals(m.TargetConnectionName, m.SourceConnectionName, StringComparison.Ordinal)); + if (!redirects) return; + + ImportPreview? refreshed; + try + { + refreshed = await BundleImporter.PreviewAsync(_session.SessionId, CancellationToken.None, map); + } + catch (Exception ex) + { + _errorMessage = $"Failed to refresh the import preview for the chosen mappings: {ex.Message}"; + return; + } + if (refreshed is null) return; + + var previousKinds = new Dictionary<(string, string), ConflictKind>(); + foreach (var item in _preview.Items) previousKinds[(item.EntityType, item.Name)] = item.Kind; + var defaults = BuildDefaultResolutions(refreshed); + foreach (var item in refreshed.Items) + { + var key = (item.EntityType, item.Name); + if (!_resolutions.ContainsKey(key) + || !previousKinds.TryGetValue(key, out var previousKind) + || previousKind != item.Kind) + { + _resolutions[key] = defaults[key]; + } + } + + _preview = refreshed with + { + RequiredSiteMappings = _preview.RequiredSiteMappings, + RequiredConnectionMappings = _preview.RequiredConnectionMappings, + }; + } + private void BackToDiff() { _step = ImportWizardStep.Diff; diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs index 4e6d6176..4fff74f4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs @@ -30,8 +30,15 @@ public interface IBundleImporter /// /// Session id returned by . /// Cancellation token. + /// + /// TRN-3: optional operator site/connection mapping. When supplied, every site-scoped + /// preview lookup (connection and instance diffs, the required-mapping auto-match and + /// the unresolved-connection blocker) runs against the MAPPED target site and connection + /// names instead of the source identity, so a preview reflects what the apply with the + /// same map will do. null (the default) keeps the identity auto-match. + /// /// A task that resolves to a per-artifact import preview with conflict details. - Task PreviewAsync(Guid sessionId, CancellationToken ct = default); + Task PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null); /// /// Applies the chosen conflict resolutions and commits the import transaction. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs index 08881df9..0fd06067 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs @@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; public record ListDataConnectionsCommand(int? SiteId = null); public record GetDataConnectionCommand(int DataConnectionId); public record CreateDataConnectionCommand(int SiteId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3); -public record UpdateDataConnectionCommand(int DataConnectionId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// +public record UpdateDataConnectionCommand(int DataConnectionId, string? Name, string? Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int? FailoverRetryCount = null); public record DeleteDataConnectionCommand(int DataConnectionId); /// diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs index 1119f586..63435f79 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs @@ -4,8 +4,13 @@ public record ListApiMethodsCommand; public record GetApiMethodCommand(int ApiMethodId); /// Flow Debugger (design 2026-09-05 §5.2): trace every production call to this method. Additive; defaults to off. public record CreateApiMethodCommand(string Name, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool TraceAllCalls = false); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// /// Flow Debugger (design 2026-09-05 §5.2): null leaves the stored value unchanged so an older CLI never resets it. -public record UpdateApiMethodCommand(int ApiMethodId, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null); +public record UpdateApiMethodCommand(int ApiMethodId, string? Script, int? TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null); public record DeleteApiMethodCommand(int ApiMethodId); /// /// Compiles the method's stored script on the receiving central node and returns the diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs index 4fac1070..284c73f5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs @@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; public record ListSitesCommand; public record GetSiteCommand(int SiteId); public record CreateSiteCommand(string Name, string SiteIdentifier, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); -public record UpdateSiteCommand(int SiteId, string Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// +public record UpdateSiteCommand(int SiteId, string? Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); public record DeleteSiteCommand(int SiteId); public record ListAreasCommand(int SiteId); public record CreateAreaCommand(int SiteId, string Name, int? ParentAreaId); diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs index af41e137..e7b6b1fe 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs @@ -7,3 +7,25 @@ public sealed record ImportResolution( string Name, ResolutionAction Action, string? RenameTo); + +/// +/// TRN-9: which preview entity types a resolution +/// is meaningful for. A Site, a site-scoped DataConnection, an SMTP configuration and +/// an SMS configuration have no renameable identity: a renamed site/connection was +/// silently treated as Skip, and a renamed SMTP/SMS row mangled the Host / AccountSid +/// into a junk second row that delivery (lowest-id wins) never used. The importer +/// rejects Rename for these types, the Central UI does not offer it, and the CLI's +/// --conflict-policy rename falls back to Skip for them with a warning. +/// +public static class ImportRenameSupport +{ + private static readonly HashSet Unsupported = new(StringComparer.Ordinal) + { + "Site", "DataConnection", "SmtpConfiguration", "SmsConfiguration", + }; + + /// True when a Rename resolution is supported for . + /// The preview item / resolution entity type. + /// false for Site, DataConnection, SmtpConfiguration and SmsConfiguration. + public static bool IsSupported(string entityType) => !Unsupported.Contains(entityType); +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/DeploymentConfiguration.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/DeploymentConfiguration.cs index 0c2ba2fe..453f8f10 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/DeploymentConfiguration.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/DeploymentConfiguration.cs @@ -113,8 +113,11 @@ public class SystemArtifactDeploymentRecordConfiguration : IEntityTypeConfigurat .IsRequired() .HasMaxLength(200); - builder.Property(d => d.PerSiteStatus) - .HasMaxLength(4000); + // DEP-3: unbounded. One serialized SiteArtifactResult per site (identifier, name, + // error text, removed secret names) is ~155 chars for a clean site, so 4000 ran + // out at ~25 sites (fewer with long errors) — and that save runs AFTER every site + // has applied the artifacts, so the run failed with nothing stamped. + builder.Property(d => d.PerSiteStatus); builder.HasIndex(d => d.DeployedAt); } diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203151127_WidenSystemArtifactPerSiteStatus.Designer.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203151127_WidenSystemArtifactPerSiteStatus.Designer.cs new file mode 100644 index 00000000..e706e28f --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203151127_WidenSystemArtifactPerSiteStatus.Designer.cs @@ -0,0 +1,2313 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase; + +#nullable disable + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations +{ + [DbContext(typeof(ScadaBridgeDbContext))] + [Migration("20261203151127_WidenSystemArtifactPerSiteStatus")] + partial class WidenSystemArtifactPerSiteStatus + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.AuditLogEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("AfterStateJson") + .HasColumnType("nvarchar(max)"); + + b.Property("BundleImportId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityId") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("EntityName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Timestamp") + .HasColumnType("datetimeoffset"); + + b.Property("User") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("Action"); + + b.HasIndex("BundleImportId") + .HasDatabaseName("IX_AuditLogEntries_BundleImportId"); + + b.HasIndex("EntityId"); + + b.HasIndex("EntityName") + .HasDatabaseName("IX_AuditLogEntries_EntityName"); + + b.HasIndex("EntityType"); + + b.HasIndex("Timestamp"); + + b.HasIndex("User"); + + b.HasIndex("EntityType", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLogEntries_EntityType_Timestamp"); + + b.HasIndex("Timestamp", "Id") + .IsDescending() + .HasDatabaseName("IX_AuditLogEntries_Timestamp_Id"); + + b.HasIndex("User", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLogEntries_User_Timestamp"); + + b.ToTable("AuditLogEntries"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Audit.SiteCall", b => + { + b.Property("TrackedOperationId") + .HasMaxLength(36) + .IsUnicode(false) + .HasColumnType("varchar(36)"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2"); + + b.Property("HttpStatus") + .HasColumnType("int"); + + b.Property("IngestedAtUtc") + .HasColumnType("datetime2"); + + b.Property("LastError") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RetryCount") + .HasColumnType("int"); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceSite") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("Target") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.Property("TerminalAtUtc") + .HasColumnType("datetime2"); + + b.Property("UpdatedAtUtc") + .HasColumnType("datetime2"); + + b.HasKey("TrackedOperationId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_SiteCalls_NonTerminal") + .HasFilter("[TerminalAtUtc] IS NULL"); + + SqlServerIndexBuilderExtensions.IncludeProperties(b.HasIndex("CreatedAtUtc"), new[] { "SourceSite", "SourceNode", "Status" }); + + b.HasIndex("TerminalAtUtc") + .HasDatabaseName("IX_SiteCalls_Terminal") + .HasFilter("[TerminalAtUtc] IS NOT NULL"); + + b.HasIndex("CreatedAtUtc", "TrackedOperationId") + .IsDescending() + .HasDatabaseName("IX_SiteCalls_Created_TrackedOperationId"); + + b.HasIndex("SourceSite", "CreatedAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_SiteCalls_Source_Created"); + + b.HasIndex("Status", "UpdatedAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_SiteCalls_Status_Updated"); + + b.ToTable("SiteCalls", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeployedConfigSnapshot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConfigurationJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("DeploymentId"); + + b.HasIndex("InstanceId") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("DeployedConfigSnapshots"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeploymentRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CompletedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ErrorMessage") + .HasColumnType("nvarchar(max)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("DeployedBy") + .HasDatabaseName("IX_DeploymentRecords_DeployedBy"); + + b.HasIndex("DeploymentId") + .IsUnique(); + + b.HasIndex("InstanceId"); + + b.HasIndex("RevisionHash") + .HasDatabaseName("IX_DeploymentRecords_RevisionHash"); + + b.HasIndex("DeployedAt", "Id") + .IsDescending() + .HasDatabaseName("IX_DeploymentRecords_DeployedAt_Id"); + + b.ToTable("DeploymentRecords"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.PendingDeployment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConfigurationJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetimeoffset"); + + b.Property("DeploymentId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ExpiresAtUtc") + .HasColumnType("datetimeoffset"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("Id"); + + b.HasIndex("DeploymentId") + .IsUnique(); + + b.HasIndex("ExpiresAtUtc"); + + b.HasIndex("InstanceId"); + + b.ToTable("PendingDeployments", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.SystemArtifactDeploymentRecord", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ArtifactType") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeployedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("PerSiteStatus") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("DeployedAt"); + + b.ToTable("SystemArtifactDeploymentRecords"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.DatabaseConnectionDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConnectionString") + .IsRequired() + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("DatabaseConnectionDefinitions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthConfiguration") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("AuthType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("EndpointUrl") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TimeoutSeconds") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("ExternalSystemDefinitions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ExternalSystemDefinitionId") + .HasColumnType("int"); + + b.Property("HttpMethod") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("nvarchar(10)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("ExternalSystemDefinitionId", "Name") + .IsUnique(); + + b.ToTable("ExternalSystemMethods"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi.ApiMethod", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("Script") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TimeoutSeconds") + .HasColumnType("int"); + + b.Property("TraceAllCalls") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("ApiMethods"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParentAreaId") + .HasColumnType("int"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentAreaId"); + + b.HasIndex("SiteId", "ParentAreaId", "Name") + .IsUnique() + .HasFilter("[ParentAreaId] IS NOT NULL"); + + b.ToTable("Areas"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AreaId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.Property("State") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("UniqueName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("AreaId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteId"); + + b.HasIndex("TemplateId"); + + b.HasIndex("UniqueName") + .IsUnique(); + + b.ToTable("Instances"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAlarmOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AlarmCanonicalName") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("IsMesReportableOverride") + .HasColumnType("bit"); + + b.Property("PriorityLevelOverride") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TriggerConfigurationOverride") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AlarmCanonicalName") + .IsUnique(); + + b.ToTable("InstanceAlarmOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAttributeOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttributeName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ElementDataType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("OverrideValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AttributeName") + .IsUnique(); + + b.ToTable("InstanceAttributeOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceConnectionBinding", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttributeName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("DataConnectionId") + .HasColumnType("int"); + + b.Property("DataSourceReferenceOverride") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("DataConnectionId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "AttributeName") + .IsUnique(); + + b.ToTable("InstanceConnectionBindings"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceNativeAlarmSourceOverride", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConditionFilterOverride") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ConnectionNameOverride") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("InstanceId") + .HasColumnType("int"); + + b.Property("IsMesReportableOverride") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SourceCanonicalName") + .IsRequired() + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("SourceReferenceOverride") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("InstanceId", "SourceCanonicalName") + .IsUnique(); + + b.ToTable("InstanceNativeAlarmSourceOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiRollupHourly", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("HourStartUtc") + .HasColumnType("datetime2"); + + b.Property("MaxValue") + .HasColumnType("float"); + + b.Property("Metric") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("MinValue") + .HasColumnType("float"); + + b.Property("SampleCount") + .HasColumnType("int"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ScopeKey") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Value") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("HourStartUtc") + .HasDatabaseName("IX_KpiRollupHourly_Hour"); + + b.HasIndex("Source", "Metric", "Scope", "ScopeKey", "HourStartUtc") + .IsUnique() + .HasDatabaseName("IX_KpiRollupHourly_Series"); + + b.ToTable("KpiRollupHourly", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Kpi.KpiSample", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CapturedAtUtc") + .HasColumnType("datetime2"); + + b.Property("Metric") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Scope") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ScopeKey") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Value") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("CapturedAtUtc") + .HasDatabaseName("IX_KpiSample_Captured"); + + b.HasIndex("Source", "Metric", "Scope", "ScopeKey", "CapturedAtUtc") + .HasDatabaseName("IX_KpiSample_Series"); + + b.ToTable("KpiSample", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.Notification", b => + { + b.Property("NotificationId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Body") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("CreatedAt") + .HasColumnType("datetimeoffset"); + + b.Property("DeliveredAt") + .HasColumnType("datetimeoffset"); + + b.Property("LastAttemptAt") + .HasColumnType("datetimeoffset"); + + b.Property("LastError") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ListName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NextAttemptAt") + .HasColumnType("datetimeoffset"); + + b.Property("OriginExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("OriginParentExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("ResolvedTargets") + .HasColumnType("nvarchar(max)"); + + b.Property("RetryCount") + .HasColumnType("int"); + + b.Property("SiteEnqueuedAt") + .HasColumnType("datetimeoffset"); + + b.Property("SourceInstanceId") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceScript") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SourceSiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("TypeData") + .HasColumnType("nvarchar(max)"); + + b.HasKey("NotificationId"); + + b.HasIndex("DeliveredAt") + .HasDatabaseName("IX_Notifications_Delivered") + .HasFilter("[Status] = 'Delivered'"); + + b.HasIndex("CreatedAt", "NotificationId") + .IsDescending() + .HasDatabaseName("IX_Notifications_Created_NotificationId"); + + b.HasIndex("SourceSiteId", "CreatedAt"); + + b.HasIndex("Status", "NextAttemptAt"); + + b.ToTable("Notifications"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("NotificationLists"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationRecipient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("EmailAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NotificationListId") + .HasColumnType("int"); + + b.Property("PhoneNumber") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("NotificationListId"); + + b.ToTable("NotificationRecipients"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmsConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AccountSid") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ApiBaseUrl") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("AuthToken") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("ConnectionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("FromNumber") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("MessagingServiceSid") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.HasKey("Id"); + + b.ToTable("SmsConfigurations"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.SmtpConfiguration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AuthType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("ConnectionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("Credentials") + .HasMaxLength(8000) + .HasColumnType("nvarchar(max)"); + + b.Property("FromAddress") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("MaxConcurrentConnections") + .HasColumnType("int"); + + b.Property("MaxRetries") + .HasColumnType("int"); + + b.Property("OAuth2Authority") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("OAuth2Scope") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Port") + .HasColumnType("int"); + + b.Property("RetryDelay") + .HasColumnType("time"); + + b.Property("TlsMode") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Transport") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.ToTable("SmtpConfigurations"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas.SharedSchema", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("SchemaJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Scope") + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("SharedSchemas"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts.SharedScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Code") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.ToTable("SharedScripts"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.SecuredWrites.PendingSecuredWrite", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConnectionName") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("DecidedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ExecutedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ExecutionError") + .HasMaxLength(2048) + .IsUnicode(false) + .HasColumnType("varchar(2048)"); + + b.Property("OperatorComment") + .HasMaxLength(1024) + .IsUnicode(false) + .HasColumnType("varchar(1024)"); + + b.Property("OperatorUser") + .IsRequired() + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)"); + + b.Property("SubmittedAtUtc") + .HasColumnType("datetime2"); + + b.Property("TagPath") + .IsRequired() + .HasMaxLength(512) + .IsUnicode(false) + .HasColumnType("varchar(512)"); + + b.Property("ValueJson") + .IsRequired() + .HasMaxLength(4000) + .IsUnicode(false) + .HasColumnType("varchar(4000)"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(128) + .IsUnicode(false) + .HasColumnType("varchar(128)"); + + b.Property("VerifierComment") + .HasMaxLength(1024) + .IsUnicode(false) + .HasColumnType("varchar(1024)"); + + b.Property("VerifierUser") + .HasMaxLength(256) + .IsUnicode(false) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("SiteId") + .HasDatabaseName("IX_PendingSecuredWrites_Site"); + + b.HasIndex("Status", "SubmittedAtUtc") + .HasDatabaseName("IX_PendingSecuredWrites_Status_Submitted"); + + b.ToTable("PendingSecuredWrites", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.LdapGroupMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LdapGroupName") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("LdapGroupName") + .IsUnique(); + + b.ToTable("LdapGroupMappings"); + + b.HasData( + new + { + Id = 1, + LdapGroupName = "SCADA-Admins", + Role = "Administrator" + }, + new + { + Id = 2, + LdapGroupName = "SCADA-Designers", + Role = "Designer" + }, + new + { + Id = 3, + LdapGroupName = "SCADA-Deploy-All", + Role = "Deployer" + }, + new + { + Id = 4, + LdapGroupName = "SCADA-Deploy-SiteA", + Role = "Deployer" + }, + new + { + Id = 5, + LdapGroupName = "SCADA-Viewers", + Role = "Viewer" + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.SiteScopeRule", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("LdapGroupMappingId") + .HasColumnType("int"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("SiteId"); + + b.HasIndex("LdapGroupMappingId", "SiteId") + .IsUnique(); + + b.ToTable("SiteScopeRules"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BackupConfiguration") + .HasColumnType("nvarchar(max)"); + + b.Property("FailoverRetryCount") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(3); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("PrimaryConfiguration") + .HasColumnType("nvarchar(max)"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteId", "Name") + .IsUnique(); + + b.ToTable("DataConnections"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ArtifactRevisionHash") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ArtifactsDeployedAt") + .HasColumnType("datetimeoffset"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("GrpcNodeAAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("GrpcNodeBAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("NodeAAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("NodeBAddress") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SiteIdentifier") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.HasIndex("RowVersion"); + + b.HasIndex("SiteIdentifier") + .IsUnique(); + + b.ToTable("Sites"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("FolderId") + .HasColumnType("int"); + + b.Property("IsDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OwnerCompositionId") + .HasColumnType("int"); + + b.Property("ParentTemplateId") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("Id"); + + b.HasIndex("FolderId"); + + b.HasIndex("Name") + .IsUnique() + .HasFilter("[IsDerived] = 0"); + + b.HasIndex("ParentTemplateId"); + + b.HasIndex("RowVersion"); + + b.ToTable("Templates"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAlarm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("IsMesReportable") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("OnTriggerScriptId") + .HasColumnType("int"); + + b.Property("PriorityLevel") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("TriggerConfiguration") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("TriggerType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateAlarms"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DataSourceReference") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("ElementDataType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateAttributes"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateComposition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComposedTemplateId") + .HasColumnType("int"); + + b.Property("InstanceName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComposedTemplateId"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "InstanceName") + .IsUnique(); + + b.ToTable("TemplateCompositions"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParentFolderId") + .HasColumnType("int"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ParentFolderId", "Name") + .IsUnique() + .HasFilter("[ParentFolderId] IS NOT NULL"); + + b.ToTable("TemplateFolders"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateNativeAlarmSource", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ConditionFilter") + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("ConnectionName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("IsMesReportable") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SourceReference") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateNativeAlarmSources"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateScript", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Code") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionTimeoutSeconds") + .HasColumnType("int"); + + b.Property("IsInherited") + .HasColumnType("bit"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("LockedInDerived") + .HasColumnType("bit"); + + b.Property("MinTimeBetweenRuns") + .HasColumnType("time"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("ParameterDefinitions") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("ReturnDefinition") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("RowVersion") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TemplateId") + .HasColumnType("int"); + + b.Property("TriggerConfiguration") + .HasMaxLength(4000) + .HasColumnType("nvarchar(4000)"); + + b.Property("TriggerType") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("RowVersion"); + + b.HasIndex("TemplateId", "Name") + .IsUnique(); + + b.ToTable("TemplateScripts"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Transport.BundleUnlockAttempt", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AttemptedAtUtc") + .HasColumnType("datetime2"); + + b.Property("ClientKey") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.HasKey("Id"); + + b.HasIndex("ClientKey", "AttemptedAtUtc") + .HasDatabaseName("IX_BundleUnlockAttempt_Client_Attempted"); + + b.ToTable("BundleUnlockAttempt", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Entities.AuditLogRow", b => + { + b.Property("OccurredAtUtc") + .HasColumnType("datetime2"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("Action") + .IsRequired() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("Actor") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Channel") + .IsRequired() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasColumnName("Category"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ExecutionId") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("uniqueidentifier") + .HasComputedColumnSql("CAST(JSON_VALUE(DetailsJson,'$.executionId') AS uniqueidentifier)", true); + + b.Property("IngestedAtUtc") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime2(7)") + .HasComputedColumnSql("CAST(SWITCHOFFSET(CAST(JSON_VALUE(DetailsJson,'$.ingestedAtUtc') AS datetimeoffset), 0) AS datetime2(7))", false); + + b.Property("Kind") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.kind')", true); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .IsUnicode(false) + .HasColumnType("varchar(16)"); + + b.Property("ParentExecutionId") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("uniqueidentifier") + .HasComputedColumnSql("CAST(JSON_VALUE(DetailsJson,'$.parentExecutionId') AS uniqueidentifier)", true); + + b.Property("SourceNode") + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)"); + + b.Property("SourceSiteId") + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(64) + .IsUnicode(false) + .HasColumnType("varchar(64)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.sourceSiteId')", true); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasMaxLength(32) + .IsUnicode(false) + .HasColumnType("varchar(32)") + .HasComputedColumnSql("JSON_VALUE(DetailsJson,'$.status')", true); + + b.Property("Target") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("OccurredAtUtc", "EventId"); + + b.HasIndex("CorrelationId") + .HasDatabaseName("IX_AuditLog_CorrelationId") + .HasFilter("[CorrelationId] IS NOT NULL"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_AuditLog_Execution"); + + b.HasIndex("OccurredAtUtc") + .IsDescending() + .HasDatabaseName("IX_AuditLog_OccurredAtUtc"); + + SqlServerIndexBuilderExtensions.IncludeProperties(b.HasIndex("OccurredAtUtc"), new[] { "Status" }); + + b.HasIndex("ParentExecutionId") + .HasDatabaseName("IX_AuditLog_ParentExecution"); + + b.HasIndex("Actor", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Actor_Occurred"); + + b.HasIndex("EventId", "OccurredAtUtc") + .IsUnique() + .HasDatabaseName("UX_AuditLog_EventId_Occurred"); + + b.HasIndex("Kind", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Kind_Occurred"); + + b.HasIndex("SourceNode", "OccurredAtUtc") + .HasDatabaseName("IX_AuditLog_Node_Occurred"); + + b.HasIndex("SourceSiteId", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Site_Occurred"); + + b.HasIndex("Target", "OccurredAtUtc") + .IsDescending(false, true) + .HasDatabaseName("IX_AuditLog_Target_Occurred") + .HasFilter("[Target] IS NOT NULL"); + + b.HasIndex("Channel", "Status", "OccurredAtUtc") + .IsDescending(false, false, true) + .HasDatabaseName("IX_AuditLog_Channel_Status_Occurred"); + + b.ToTable("AuditLog", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeployedConfigSnapshot", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.DeploymentRecord", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment.PendingDeployment", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany() + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemMethod", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems.ExternalSystemDefinition", null) + .WithMany() + .HasForeignKey("ExternalSystemDefinitionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", null) + .WithMany("Children") + .HasForeignKey("ParentAreaId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", null) + .WithMany() + .HasForeignKey("AreaId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAlarmOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("AlarmOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceAttributeOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("AttributeOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceConnectionBinding", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", null) + .WithMany() + .HasForeignKey("DataConnectionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("ConnectionBindings") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.InstanceNativeAlarmSourceOverride", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", null) + .WithMany("NativeAlarmSourceOverrides") + .HasForeignKey("InstanceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationRecipient", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", null) + .WithMany("Recipients") + .HasForeignKey("NotificationListId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.SiteScopeRule", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Security.LdapGroupMapping", null) + .WithMany() + .HasForeignKey("LdapGroupMappingId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.DataConnection", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site", null) + .WithMany() + .HasForeignKey("SiteId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", null) + .WithMany() + .HasForeignKey("FolderId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("ParentTemplateId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAlarm", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Alarms") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateAttribute", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Attributes") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateComposition", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany() + .HasForeignKey("ComposedTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Compositions") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateFolder", null) + .WithMany() + .HasForeignKey("ParentFolderId") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateNativeAlarmSource", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("NativeAlarmSources") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.TemplateScript", b => + { + b.HasOne("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", null) + .WithMany("Scripts") + .HasForeignKey("TemplateId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Area", b => + { + b.Navigation("Children"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances.Instance", b => + { + b.Navigation("AlarmOverrides"); + + b.Navigation("AttributeOverrides"); + + b.Navigation("ConnectionBindings"); + + b.Navigation("NativeAlarmSourceOverrides"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications.NotificationList", b => + { + b.Navigation("Recipients"); + }); + + modelBuilder.Entity("ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates.Template", b => + { + b.Navigation("Alarms"); + + b.Navigation("Attributes"); + + b.Navigation("Compositions"); + + b.Navigation("NativeAlarmSources"); + + b.Navigation("Scripts"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203151127_WidenSystemArtifactPerSiteStatus.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203151127_WidenSystemArtifactPerSiteStatus.cs new file mode 100644 index 00000000..d2a0178b --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/20261203151127_WidenSystemArtifactPerSiteStatus.cs @@ -0,0 +1,38 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations +{ + /// + public partial class WidenSystemArtifactPerSiteStatus : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "PerSiteStatus", + table: "SystemArtifactDeploymentRecords", + type: "nvarchar(max)", + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(4000)", + oldMaxLength: 4000, + oldNullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "PerSiteStatus", + table: "SystemArtifactDeploymentRecords", + type: "nvarchar(4000)", + maxLength: 4000, + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(max)", + oldNullable: true); + } + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs index 150d4bd5..eef72f42 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Migrations/ScadaBridgeDbContextModelSnapshot.cs @@ -381,8 +381,7 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations .HasColumnType("nvarchar(200)"); b.Property("PerSiteStatus") - .HasMaxLength(4000) - .HasColumnType("nvarchar(4000)"); + .HasColumnType("nvarchar(max)"); b.HasKey("Id"); diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs index cca96c99..6d538b68 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/NotificationRepository.cs @@ -30,7 +30,13 @@ public class NotificationRepository : INotificationRepository /// public async Task GetListByNameAsync(string name, CancellationToken cancellationToken = default) - => await _context.Set().FirstOrDefaultAsync(l => l.Name == name, cancellationToken); + // Eager-load Recipients (TRN-1): the Transport importer's Overwrite clears and + // re-adds the recipient collection. Without the Include the Clear() ran on an + // unloaded collection, deleted nothing, and the bundle's recipients were appended + // to the target's — duplicates plus recipients the source had removed. + => await _context.Set() + .Include(n => n.Recipients) + .FirstOrDefaultAsync(l => l.Name == name, cancellationToken); /// public async Task AddNotificationListAsync(NotificationList list, CancellationToken cancellationToken = default) diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 00fabf04..37c222a5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -2088,16 +2088,25 @@ public class ManagementActor : ReceiveActor private static async Task HandleUpdateSite(IServiceProvider sp, UpdateSiteCommand cmd, string user) { - ValidateSiteGrpcAddresses(cmd.GrpcNodeAAddress, cmd.GrpcNodeBAddress); var repo = sp.GetRequiredService(); var site = await repo.GetSiteByIdAsync(cmd.SiteId) ?? throw new ManagementCommandException($"Site with ID {cmd.SiteId} not found."); - site.Name = cmd.Name; - site.Description = cmd.Description; - site.NodeAAddress = cmd.NodeAAddress; - site.NodeBAddress = cmd.NodeBAddress; - site.GrpcNodeAAddress = cmd.GrpcNodeAAddress; - site.GrpcNodeBAddress = cmd.GrpcNodeBAddress; + // CLI-2: preserve-if-null partial update. Validate the EFFECTIVE addresses + // (the merge of the command and the stored row) before anything is written. + var grpcNodeA = PartialUpdate.Optional(cmd.GrpcNodeAAddress, site.GrpcNodeAAddress); + var grpcNodeB = PartialUpdate.Optional(cmd.GrpcNodeBAddress, site.GrpcNodeBAddress); + ValidateSiteGrpcAddresses(grpcNodeA, grpcNodeB); + if (cmd.Name is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Name)) + throw new ManagementCommandException("Site name must not be empty."); + site.Name = cmd.Name; + } + site.Description = PartialUpdate.Optional(cmd.Description, site.Description); + site.NodeAAddress = PartialUpdate.Optional(cmd.NodeAAddress, site.NodeAAddress); + site.NodeBAddress = PartialUpdate.Optional(cmd.NodeBAddress, site.NodeBAddress); + site.GrpcNodeAAddress = grpcNodeA; + site.GrpcNodeBAddress = grpcNodeB; await repo.UpdateSiteAsync(site); await repo.SaveChangesAsync(); var commService = sp.GetService(); @@ -2260,14 +2269,33 @@ public class ManagementActor : ReceiveActor var repo = sp.GetRequiredService(); var conn = await repo.GetDataConnectionByIdAsync(cmd.DataConnectionId) ?? throw new ManagementCommandException($"DataConnection with ID {cmd.DataConnectionId} not found."); - conn.Name = cmd.Name; - conn.Protocol = cmd.Protocol; + // CLI-2: preserve-if-null partial update — an omitted field keeps the stored + // value; an empty string clears an optional configuration. + if (cmd.Name is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Name)) + throw new ManagementCommandException("Data connection name must not be empty."); + conn.Name = cmd.Name; + } + if (cmd.Protocol is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Protocol)) + throw new ManagementCommandException("Data connection protocol must not be empty."); + conn.Protocol = cmd.Protocol; + } // Sentinel-preserving merge: a client that round-trips a scrubbed config // (secrets replaced with the redaction sentinel) keeps the stored secret // rather than wiping it. Non-sentinel values overwrite as usual. - conn.PrimaryConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration); - conn.BackupConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration); - conn.FailoverRetryCount = cmd.FailoverRetryCount; + if (cmd.PrimaryConfiguration is not null) + conn.PrimaryConfiguration = string.IsNullOrWhiteSpace(cmd.PrimaryConfiguration) + ? null + : ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration); + if (cmd.BackupConfiguration is not null) + conn.BackupConfiguration = string.IsNullOrWhiteSpace(cmd.BackupConfiguration) + ? null + : ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration); + if (cmd.FailoverRetryCount is { } failoverRetryCount) + conn.FailoverRetryCount = failoverRetryCount; await repo.UpdateDataConnectionAsync(conn); await repo.SaveChangesAsync(); var publicShape = DataConnectionPublicShape(conn); @@ -4006,10 +4034,19 @@ public class ManagementActor : ReceiveActor var repo = sp.GetRequiredService(); var method = await repo.GetApiMethodByIdAsync(cmd.ApiMethodId) ?? throw new ManagementCommandException($"ApiMethod with ID {cmd.ApiMethodId} not found."); - method.Script = cmd.Script; - method.TimeoutSeconds = cmd.TimeoutSeconds; - method.ParameterDefinitions = cmd.ParameterDefinitions; - method.ReturnDefinition = cmd.ReturnDefinition; + // CLI-2: preserve-if-null partial update — an omitted field keeps the stored + // value (an omitted --timeout used to reset it to 30 and drop both + // definitions); an empty string clears an optional definition. + if (cmd.Script is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Script)) + throw new ManagementCommandException("API method script must not be empty."); + method.Script = cmd.Script; + } + if (cmd.TimeoutSeconds is { } timeoutSeconds) + method.TimeoutSeconds = timeoutSeconds; + method.ParameterDefinitions = PartialUpdate.Optional(cmd.ParameterDefinitions, method.ParameterDefinitions); + method.ReturnDefinition = PartialUpdate.Optional(cmd.ReturnDefinition, method.ReturnDefinition); if (cmd.TraceAllCalls is { } traceAllCalls) method.TraceAllCalls = traceAllCalls; await repo.UpdateApiMethodAsync(method); @@ -4676,7 +4713,13 @@ public class ManagementActor : ReceiveActor // is safe even when ApplyAsync already released the same id. try { - var preview = await importer.PreviewAsync(session.SessionId); + // TRN-3: an explicit --map-site / --map-connection redirect changes what + // the site-scoped preview rows resolve against, so the preview (and its + // unresolved-connection blockers and auto-matches) runs under those + // redirects — otherwise a connection present only on the MAPPED site was + // a blocker no mapping could clear. + var preview = await importer.PreviewAsync( + session.SessionId, nameMap: BuildExplicitRedirectMap(cmd)); var blockers = preview.Items.Where(i => i.Kind == ConflictKind.Blocker).ToList(); if (blockers.Count > 0) @@ -4702,6 +4745,7 @@ public class ManagementActor : ReceiveActor // automatically correct — no bare-connection-name special case needed. var renameStamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); var resolutionsMap = new Dictionary<(string, string), ImportResolution>(); + var renameFallbacks = new SortedSet(StringComparer.Ordinal); foreach (var item in preview.Items) { var action = item.Kind switch @@ -4711,15 +4755,31 @@ public class ManagementActor : ReceiveActor ConflictKind.Modified => policy, _ => ResolutionAction.Skip, }; - var renameTo = (item.Kind == ConflictKind.Modified && policy == ResolutionAction.Rename) + // TRN-9: --conflict-policy rename has no meaning for a site, data + // connection or SMTP/SMS configuration (the importer rejects it); + // fall back to Skip for those and say so in the result. + if (action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(item.EntityType)) + { + action = ResolutionAction.Skip; + renameFallbacks.Add($"{item.EntityType} '{item.Name}'"); + } + var renameTo = (item.Kind == ConflictKind.Modified && action == ResolutionAction.Rename) ? $"{item.Name}-imported-{renameStamp}" : null; resolutionsMap[(item.EntityType, item.Name)] = new ImportResolution( item.EntityType, item.Name, action, renameTo); } - return await importer.ApplyAsync( + var importResult = await importer.ApplyAsync( session.SessionId, resolutionsMap.Values.ToList(), username, nameMap: nameMap); + if (renameFallbacks.Count == 0) return importResult; + return importResult with + { + Warnings = importResult.Warnings + .Concat(renameFallbacks.Select(f => + $"{f} was skipped: Rename is not supported for sites, data connections, SMTP or SMS configurations.")) + .ToList(), + }; } finally { @@ -4732,6 +4792,27 @@ public class ManagementActor : ReceiveActor } } + /// + /// TRN-3: the operator's explicit MapToExisting redirects (a --map-site / + /// --map-connection with a target) as a for the + /// preview, or null when there are none (the preview then keeps its identity + /// auto-match). Create-new specs are not redirects and are left to + /// . + /// + private static BundleNameMap? BuildExplicitRedirectMap(ImportBundleCommand cmd) + { + var sites = (cmd.SiteMappings ?? Array.Empty()) + .Where(s => !string.IsNullOrWhiteSpace(s.TargetSiteIdentifier)) + .Select(s => new SiteMapping(s.SourceSiteIdentifier, MappingAction.MapToExisting, s.TargetSiteIdentifier)) + .ToList(); + var connections = (cmd.ConnectionMappings ?? Array.Empty()) + .Where(c => !string.IsNullOrWhiteSpace(c.TargetConnectionName)) + .Select(c => new ConnectionMapping( + c.SourceSiteIdentifier, c.SourceConnectionName, MappingAction.MapToExisting, c.TargetConnectionName)) + .ToList(); + return sites.Count == 0 && connections.Count == 0 ? null : new BundleNameMap(sites, connections); + } + /// /// Merges the operator-supplied / /// lists with the preview's auto-matches diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs new file mode 100644 index 00000000..c317a242 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs @@ -0,0 +1,19 @@ +namespace ZB.MOM.WW.ScadaBridge.ManagementService; + +/// +/// Preserve-if-null merge rules for the partial update commands (CLI-2): +/// UpdateSiteCommand, UpdateDataConnectionCommand and +/// UpdateApiMethodCommand. A null field means "not supplied — keep the +/// stored value"; an empty (or whitespace-only) string means "clear this optional +/// field". The CLI sends only the options that were actually passed, and the Central +/// UI's full-entity forms send an empty string for a field the operator cleared. +/// +internal static class PartialUpdate +{ + /// Merges an optional (nullable) string field. + /// The value carried by the command, or null when not supplied. + /// The value currently stored. + /// when is null; null when it is blank; otherwise . + public static string? Optional(string? incoming, string? stored) => + incoming is null ? stored : string.IsNullOrWhiteSpace(incoming) ? null : incoming; +} diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs index 1fca35fb..06b7eea5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Flattening/FlatteningService.cs @@ -78,11 +78,15 @@ public class FlatteningService // Step 4: Apply connection bindings ApplyConnectionBindings(instance.ConnectionBindings, attributes, dataConnections); - // Step 5: Resolve alarms from inheritance chain. - // alarmScriptIds maps a resolved alarm's canonical name to the - // TemplateScript.Id of its on-trigger script (if any). + // Step 5: Resolve alarms from inheritance chain. Each alarm's on-trigger + // script is resolved by NAME within the alarm's own chain and + // path-qualified with the alarm's prefix (TPL-1/TPL-2/TPL-5). + // alarmScriptIds only carries the legacy fallback: an on-trigger script + // id that is not a script row of the alarm's own chain. var alarmScriptIds = new Dictionary(StringComparer.Ordinal); - var alarms = ResolveInheritedAlarms(templateChain, prefix: null, alarmScriptIds); + var alarms = ResolveInheritedAlarms(templateChain, prefix: null, out var rootUnresolvedScriptIds); + foreach (var (alarmName, scriptId) in rootUnresolvedScriptIds) + alarmScriptIds[alarmName] = scriptId; ResolveComposedAlarms(templateChain, compositionMap, composedTemplateChains, alarms, alarmScriptIds); ApplyInstanceAlarmOverrides(instance.AlarmOverrides, alarms); @@ -94,7 +98,7 @@ public class FlatteningService ResolveComposedScripts(templateChain, compositionMap, composedTemplateChains, scripts, scriptCanonicalById); // Step 7: Resolve alarm on-trigger script references to canonical names - ResolveAlarmScriptReferences(alarms, alarmScriptIds, scriptCanonicalById); + ResolveAlarmScriptReferences(alarms, alarmScriptIds, scriptCanonicalById, scripts); // Step 7b: Resolve native alarm source bindings (connection + source // reference). Conditions under each source are discovered at runtime; @@ -405,19 +409,39 @@ public class FlatteningService /// Resolves alarms from an inheritance chain. When /// is non-null the alarm names are returned bare (caller path-qualifies); /// the keys of the returned dictionary are always bare alarm names. - /// is populated with the on-trigger - /// script id of each resolved alarm keyed by the canonical name the alarm - /// will ultimately carry (bare name when is null, - /// otherwise prefix.name). + /// + /// Each alarm's on-trigger script is resolved within this chain: the + /// OnTriggerScriptId is looked up among the script rows of every + /// template in and translated to that row's + /// NAME, which is then path-qualified with and set + /// as . Resolving by + /// name per chain (not through a flatten-wide id map) is what keeps two + /// slots of the same module apart (TPL-1: both slots share the base script + /// row id, so a global map made every slot's alarm run the LAST slot's + /// script) and keeps the link when a derived template overrides the script + /// with a row of a different id (TPL-2). The value travels on the alarm, so + /// only the pass that actually adds the alarm decides it (TPL-5). + /// + /// receives, keyed by bare alarm name, + /// any on-trigger script id that is NOT a script row of this chain; the + /// caller records it for the legacy flatten-wide id fallback. /// private static Dictionary ResolveInheritedAlarms( IReadOnlyList