Merge branch 'review/wp2' into review/integration
This commit is contained in:
@@ -123,21 +123,27 @@ public static class ApiMethodCommands
|
||||
return cmd;
|
||||
}
|
||||
|
||||
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
/// <summary>
|
||||
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
|
||||
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
|
||||
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
|
||||
/// receives the built command record instead of sending it.
|
||||
/// </summary>
|
||||
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
|
||||
Func<object, int>? commandInterceptor = null)
|
||||
{
|
||||
var idOption = new Option<int>("--id") { Description = "API method ID", Required = true };
|
||||
var scriptOption = new Option<string>("--script") { Description = "Script code", Required = true };
|
||||
var timeoutOption = new Option<int>("--timeout") { Description = "Timeout in seconds" };
|
||||
timeoutOption.DefaultValueFactory = _ => 30;
|
||||
var parametersOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON" };
|
||||
var returnDefOption = new Option<string?>("--return-def") { Description = "Return type definition" };
|
||||
var scriptOption = new Option<string?>("--script") { Description = "Script code (omitted = unchanged)" };
|
||||
var timeoutOption = new Option<int?>("--timeout") { Description = "Timeout in seconds (omitted = unchanged)" };
|
||||
var parametersOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON (omitted = unchanged; \"\" clears)" };
|
||||
var returnDefOption = new Option<string?>("--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<bool?>("--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;
|
||||
}
|
||||
|
||||
@@ -58,18 +58,25 @@ public static class DataConnectionCommands
|
||||
return cmd;
|
||||
}
|
||||
|
||||
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
/// <summary>
|
||||
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
|
||||
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
|
||||
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
|
||||
/// receives the built command record instead of sending it.
|
||||
/// </summary>
|
||||
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
|
||||
Func<object, int>? commandInterceptor = null)
|
||||
{
|
||||
var idOption = new Option<int>("--id") { Description = "Data connection ID", Required = true };
|
||||
var nameOption = new Option<string>("--name") { Description = "Connection name", Required = true };
|
||||
var protocolOption = new Option<string>("--protocol") { Description = "Protocol", Required = true };
|
||||
var configOption = new Option<string?>("--primary-config", "--configuration") { Description = "Primary configuration JSON" };
|
||||
var backupConfigOption = new Option<string?>("--backup-config") { Description = "Backup configuration JSON" };
|
||||
var nameOption = new Option<string?>("--name") { Description = "Connection name (omitted = unchanged)" };
|
||||
var protocolOption = new Option<string?>("--protocol") { Description = "Protocol (omitted = unchanged)" };
|
||||
var configOption = new Option<string?>("--primary-config", "--configuration") { Description = "Primary configuration JSON (omitted = unchanged)" };
|
||||
var backupConfigOption = new Option<string?>("--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<int>("--failover-retry-count") { Description = "Number of retries before failover to backup", DefaultValueFactory = _ => 3 };
|
||||
var failoverRetryOption = new Option<int?>("--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;
|
||||
}
|
||||
|
||||
@@ -88,17 +88,24 @@ public static class SiteCommands
|
||||
return cmd;
|
||||
}
|
||||
|
||||
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||
/// <summary>
|
||||
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
|
||||
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
|
||||
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
|
||||
/// receives the built command record instead of sending it.
|
||||
/// </summary>
|
||||
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
|
||||
Func<object, int>? commandInterceptor = null)
|
||||
{
|
||||
var idOption = new Option<int>("--id") { Description = "Site ID", Required = true };
|
||||
var nameOption = new Option<string>("--name") { Description = "Site name", Required = true };
|
||||
var descOption = new Option<string?>("--description") { Description = "Site description" };
|
||||
var nodeAOption = new Option<string?>("--node-a-address") { Description = "Akka address for Node A" };
|
||||
var nodeBOption = new Option<string?>("--node-b-address") { Description = "Akka address for Node B" };
|
||||
var grpcNodeAOption = new Option<string?>("--grpc-node-a-address") { Description = "gRPC address for Node A" };
|
||||
var grpcNodeBOption = new Option<string?>("--grpc-node-b-address") { Description = "gRPC address for Node B" };
|
||||
var nameOption = new Option<string?>("--name") { Description = "Site name (omitted = unchanged)" };
|
||||
var descOption = new Option<string?>("--description") { Description = "Site description (omitted = unchanged; \"\" clears)" };
|
||||
var nodeAOption = new Option<string?>("--node-a-address") { Description = "Akka address for Node A (omitted = unchanged; \"\" clears)" };
|
||||
var nodeBOption = new Option<string?>("--node-b-address") { Description = "Akka address for Node B (omitted = unchanged; \"\" clears)" };
|
||||
var grpcNodeAOption = new Option<string?>("--grpc-node-a-address") { Description = "gRPC address for Node A (omitted = unchanged; \"\" clears)" };
|
||||
var grpcNodeBOption = new Option<string?>("--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;
|
||||
}
|
||||
|
||||
@@ -976,22 +976,21 @@ scadabridge --url <url> site create --name <string> --identifier <string> [--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 <url> site update --id <int> --name <string> [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
|
||||
scadabridge --url <url> site update --id <int> [--name <string>] [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
|
||||
```
|
||||
|
||||
| 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 <url> data-connection create --site-id <int> --name <string> -
|
||||
|
||||
#### `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 <url> data-connection update --id <int> --name <string> --protocol <string> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <int>]
|
||||
scadabridge --url <url> data-connection update --id <int> [--name <string>] [--protocol <string>] [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <int>]
|
||||
```
|
||||
|
||||
| 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 <url> api-method create --name <string> --script <string> [--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 <url> api-method update --id <int> --script <string> [--timeout <int>] [--parameters <json>] [--return-def <json>] [--trace-all-calls <true|false>]
|
||||
scadabridge --url <url> api-method update --id <int> [--script <string>] [--timeout <int>] [--parameters <json>] [--return-def <json>] [--trace-all-calls <true|false>]
|
||||
```
|
||||
|
||||
| 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.
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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).
|
||||
|
||||
+2
-1
@@ -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");
|
||||
}
|
||||
|
||||
@@ -482,7 +482,10 @@
|
||||
var key = (item.EntityType, item.Name);
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 align-items-center">
|
||||
@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}";
|
||||
<div class="form-check form-check-inline mb-0">
|
||||
|
||||
+54
-1
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
@@ -30,8 +30,15 @@ public interface IBundleImporter
|
||||
/// </summary>
|
||||
/// <param name="sessionId">Session id returned by <see cref="LoadAsync"/>.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <param name="nameMap">
|
||||
/// 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. <c>null</c> (the default) keeps the identity auto-match.
|
||||
/// </param>
|
||||
/// <returns>A task that resolves to a per-artifact import preview with conflict details.</returns>
|
||||
Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default);
|
||||
Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null);
|
||||
|
||||
/// <summary>
|
||||
/// Applies the chosen conflict resolutions and commits the import transaction.
|
||||
|
||||
@@ -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);
|
||||
/// <summary>
|
||||
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> 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).
|
||||
/// </summary>
|
||||
public record UpdateDataConnectionCommand(int DataConnectionId, string? Name, string? Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int? FailoverRetryCount = null);
|
||||
public record DeleteDataConnectionCommand(int DataConnectionId);
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -4,8 +4,13 @@ public record ListApiMethodsCommand;
|
||||
public record GetApiMethodCommand(int ApiMethodId);
|
||||
/// <param name="TraceAllCalls">Flow Debugger (design 2026-09-05 §5.2): trace every production call to this method. Additive; defaults to off.</param>
|
||||
public record CreateApiMethodCommand(string Name, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool TraceAllCalls = false);
|
||||
/// <summary>
|
||||
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> 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).
|
||||
/// </summary>
|
||||
/// <param name="TraceAllCalls">Flow Debugger (design 2026-09-05 §5.2): <c>null</c> leaves the stored value unchanged so an older CLI never resets it.</param>
|
||||
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);
|
||||
/// <summary>
|
||||
/// Compiles the method's stored script on the receiving central node and returns the
|
||||
|
||||
@@ -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);
|
||||
/// <summary>
|
||||
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> 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).
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
@@ -7,3 +7,25 @@ public sealed record ImportResolution(
|
||||
string Name,
|
||||
ResolutionAction Action,
|
||||
string? RenameTo);
|
||||
|
||||
/// <summary>
|
||||
/// TRN-9: which preview entity types a <see cref="ResolutionAction.Rename"/> 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
|
||||
/// <c>--conflict-policy rename</c> falls back to Skip for them with a warning.
|
||||
/// </summary>
|
||||
public static class ImportRenameSupport
|
||||
{
|
||||
private static readonly HashSet<string> Unsupported = new(StringComparer.Ordinal)
|
||||
{
|
||||
"Site", "DataConnection", "SmtpConfiguration", "SmsConfiguration",
|
||||
};
|
||||
|
||||
/// <summary>True when a Rename resolution is supported for <paramref name="entityType"/>.</summary>
|
||||
/// <param name="entityType">The preview item / resolution entity type.</param>
|
||||
/// <returns><c>false</c> for Site, DataConnection, SmtpConfiguration and SmsConfiguration.</returns>
|
||||
public static bool IsSupported(string entityType) => !Unsupported.Contains(entityType);
|
||||
}
|
||||
|
||||
+5
-2
@@ -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);
|
||||
}
|
||||
|
||||
+2313
File diff suppressed because it is too large
Load Diff
+38
@@ -0,0 +1,38 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class WidenSystemArtifactPerSiteStatus : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "PerSiteStatus",
|
||||
table: "SystemArtifactDeploymentRecords",
|
||||
type: "nvarchar(max)",
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(4000)",
|
||||
oldMaxLength: 4000,
|
||||
oldNullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "PerSiteStatus",
|
||||
table: "SystemArtifactDeploymentRecords",
|
||||
type: "nvarchar(4000)",
|
||||
maxLength: 4000,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(max)",
|
||||
oldNullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -381,8 +381,7 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("PerSiteStatus")
|
||||
.HasMaxLength(4000)
|
||||
.HasColumnType("nvarchar(4000)");
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
|
||||
+7
-1
@@ -30,7 +30,13 @@ public class NotificationRepository : INotificationRepository
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<NotificationList?> GetListByNameAsync(string name, CancellationToken cancellationToken = default)
|
||||
=> await _context.Set<NotificationList>().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<NotificationList>()
|
||||
.Include(n => n.Recipients)
|
||||
.FirstOrDefaultAsync(l => l.Name == name, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task AddNotificationListAsync(NotificationList list, CancellationToken cancellationToken = default)
|
||||
|
||||
@@ -2088,16 +2088,25 @@ public class ManagementActor : ReceiveActor
|
||||
|
||||
private static async Task<object?> HandleUpdateSite(IServiceProvider sp, UpdateSiteCommand cmd, string user)
|
||||
{
|
||||
ValidateSiteGrpcAddresses(cmd.GrpcNodeAAddress, cmd.GrpcNodeBAddress);
|
||||
var repo = sp.GetRequiredService<ISiteRepository>();
|
||||
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<CommunicationService>();
|
||||
@@ -2260,14 +2269,33 @@ public class ManagementActor : ReceiveActor
|
||||
var repo = sp.GetRequiredService<ISiteRepository>();
|
||||
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<IInboundApiRepository>();
|
||||
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<string>(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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-3: the operator's explicit MapToExisting redirects (a <c>--map-site</c> /
|
||||
/// <c>--map-connection</c> with a target) as a <see cref="BundleNameMap"/> for the
|
||||
/// preview, or <c>null</c> when there are none (the preview then keeps its identity
|
||||
/// auto-match). Create-new specs are not redirects and are left to
|
||||
/// <see cref="BuildNameMap"/>.
|
||||
/// </summary>
|
||||
private static BundleNameMap? BuildExplicitRedirectMap(ImportBundleCommand cmd)
|
||||
{
|
||||
var sites = (cmd.SiteMappings ?? Array.Empty<SiteMappingSpec>())
|
||||
.Where(s => !string.IsNullOrWhiteSpace(s.TargetSiteIdentifier))
|
||||
.Select(s => new SiteMapping(s.SourceSiteIdentifier, MappingAction.MapToExisting, s.TargetSiteIdentifier))
|
||||
.ToList();
|
||||
var connections = (cmd.ConnectionMappings ?? Array.Empty<ConnectionMappingSpec>())
|
||||
.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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges the operator-supplied <see cref="SiteMappingSpec"/> /
|
||||
/// <see cref="ConnectionMappingSpec"/> lists with the preview's auto-matches
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace ZB.MOM.WW.ScadaBridge.ManagementService;
|
||||
|
||||
/// <summary>
|
||||
/// Preserve-if-null merge rules for the partial update commands (CLI-2):
|
||||
/// <c>UpdateSiteCommand</c>, <c>UpdateDataConnectionCommand</c> and
|
||||
/// <c>UpdateApiMethodCommand</c>. A <c>null</c> 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.
|
||||
/// </summary>
|
||||
internal static class PartialUpdate
|
||||
{
|
||||
/// <summary>Merges an optional (nullable) string field.</summary>
|
||||
/// <param name="incoming">The value carried by the command, or <c>null</c> when not supplied.</param>
|
||||
/// <param name="stored">The value currently stored.</param>
|
||||
/// <returns><paramref name="stored"/> when <paramref name="incoming"/> is null; null when it is blank; otherwise <paramref name="incoming"/>.</returns>
|
||||
public static string? Optional(string? incoming, string? stored) =>
|
||||
incoming is null ? stored : string.IsNullOrWhiteSpace(incoming) ? null : incoming;
|
||||
}
|
||||
@@ -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<string, int>(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 <paramref name="prefix"/>
|
||||
/// is non-null the alarm names are returned bare (caller path-qualifies);
|
||||
/// the keys of the returned dictionary are always bare alarm names.
|
||||
/// <paramref name="alarmScriptIds"/> 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 <paramref name="prefix"/> is null,
|
||||
/// otherwise <c>prefix.name</c>).
|
||||
/// <para>
|
||||
/// Each alarm's on-trigger script is resolved <b>within this chain</b>: the
|
||||
/// <c>OnTriggerScriptId</c> is looked up among the script rows of every
|
||||
/// template in <paramref name="templateChain"/> and translated to that row's
|
||||
/// NAME, which is then path-qualified with <paramref name="prefix"/> and set
|
||||
/// as <see cref="ResolvedAlarm.OnTriggerScriptCanonicalName"/>. 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).
|
||||
/// </para>
|
||||
/// <paramref name="unresolvedScriptIds"/> 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.
|
||||
/// </summary>
|
||||
private static Dictionary<string, ResolvedAlarm> ResolveInheritedAlarms(
|
||||
IReadOnlyList<Template> templateChain,
|
||||
string? prefix,
|
||||
Dictionary<string, int> alarmScriptIds)
|
||||
out Dictionary<string, int> unresolvedScriptIds)
|
||||
{
|
||||
var result = new Dictionary<string, ResolvedAlarm>(StringComparer.Ordinal);
|
||||
var scriptIdByName = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
|
||||
// Script row id -> script name, over every template of this chain
|
||||
// (base rows, derived overrides and IsInherited placeholders alike).
|
||||
var chainScriptNameById = new Dictionary<int, string>();
|
||||
foreach (var t in templateChain)
|
||||
foreach (var script in t.Scripts)
|
||||
if (script.Id != 0)
|
||||
chainScriptNameById.TryAdd(script.Id, script.Name);
|
||||
|
||||
for (int i = templateChain.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var template = templateChain[i];
|
||||
@@ -468,10 +492,20 @@ public class FlatteningService
|
||||
}
|
||||
}
|
||||
|
||||
unresolvedScriptIds = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var (name, scriptId) in scriptIdByName)
|
||||
{
|
||||
var canonical = prefix == null ? name : $"{prefix}.{name}";
|
||||
alarmScriptIds[canonical] = scriptId;
|
||||
if (chainScriptNameById.TryGetValue(scriptId, out var scriptName))
|
||||
{
|
||||
result[name] = result[name] with
|
||||
{
|
||||
OnTriggerScriptCanonicalName = prefix == null ? scriptName : $"{prefix}.{scriptName}"
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
unresolvedScriptIds[name] = scriptId;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -652,7 +686,7 @@ public class FlatteningService
|
||||
if (!composedTemplateChains.TryGetValue(composition.ComposedTemplateId, out var composedChain))
|
||||
return;
|
||||
|
||||
var composedAlarms = ResolveInheritedAlarms(composedChain, prefix, alarmScriptIds);
|
||||
var composedAlarms = ResolveInheritedAlarms(composedChain, prefix, out var unresolvedScriptIds);
|
||||
foreach (var (name, alarm) in composedAlarms)
|
||||
{
|
||||
var canonicalName = $"{prefix}.{name}";
|
||||
@@ -664,6 +698,10 @@ public class FlatteningService
|
||||
TriggerConfiguration = PrefixTriggerAttribute(alarm.TriggerConfiguration, prefix),
|
||||
Source = "Composed"
|
||||
};
|
||||
// Only the pass that adds the alarm records its fallback script
|
||||
// id (TPL-5: a nested slot is visited twice under one prefix).
|
||||
if (unresolvedScriptIds.TryGetValue(name, out var scriptId))
|
||||
alarmScriptIds[canonicalName] = scriptId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1028,19 +1066,19 @@ public class FlatteningService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves alarm on-trigger script references from <see cref="TemplateScript.Id"/>
|
||||
/// values to the canonical (path-qualified) names of the corresponding
|
||||
/// resolved scripts. <paramref name="alarmScriptIds"/> maps an alarm's
|
||||
/// canonical name to the id of its on-trigger script; <paramref name="scriptCanonicalById"/>
|
||||
/// maps a script id to the canonical name it carries in the flattened
|
||||
/// configuration. An alarm whose on-trigger script id has no matching
|
||||
/// resolved script is left with a <c>null</c> reference — semantic
|
||||
/// validation then reports the dangling reference.
|
||||
/// Finalises alarm on-trigger script references. Most were resolved by name
|
||||
/// within the alarm's own chain in <see cref="ResolveInheritedAlarms"/>; this
|
||||
/// pass (1) resolves the legacy fallback — an on-trigger script id that is not
|
||||
/// a script row of the alarm's chain — through the flatten-wide
|
||||
/// <paramref name="scriptCanonicalById"/> map, and (2) clears any reference
|
||||
/// whose canonical name is not a resolved script, so a dangling reference is
|
||||
/// left <c>null</c> exactly as before.
|
||||
/// </summary>
|
||||
private static void ResolveAlarmScriptReferences(
|
||||
Dictionary<string, ResolvedAlarm> alarms,
|
||||
Dictionary<string, int> alarmScriptIds,
|
||||
Dictionary<int, string> scriptCanonicalById)
|
||||
Dictionary<int, string> scriptCanonicalById,
|
||||
IReadOnlyDictionary<string, ResolvedScript> scripts)
|
||||
{
|
||||
foreach (var (alarmCanonicalName, scriptId) in alarmScriptIds)
|
||||
{
|
||||
@@ -1053,5 +1091,11 @@ public class FlatteningService
|
||||
OnTriggerScriptCanonicalName = scriptCanonicalName
|
||||
};
|
||||
}
|
||||
|
||||
foreach (var (alarmCanonicalName, alarm) in alarms.ToList())
|
||||
{
|
||||
if (alarm.OnTriggerScriptCanonicalName is { } scriptName && !scripts.ContainsKey(scriptName))
|
||||
alarms[alarmCanonicalName] = alarm with { OnTriggerScriptCanonicalName = null };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,19 @@ public sealed class BundleSecretEncryptor
|
||||
throw new CryptographicException("Unsupported bundle encryption parameters.");
|
||||
}
|
||||
|
||||
// TRN-10: the iteration count comes from the uploaded (untrusted) manifest.
|
||||
// EncryptionMetadata's constructor range-checks it, but a record `with`
|
||||
// expression or any other non-constructor path bypasses that, so re-check
|
||||
// here — before PBKDF2 runs — or a hostile bundle declaring int.MaxValue
|
||||
// pins a thread (and the single-flight transport gate) for tens of minutes.
|
||||
if (metadata.Iterations < EncryptionMetadata.MinPbkdf2Iterations
|
||||
|| metadata.Iterations > EncryptionMetadata.MaxPbkdf2Iterations)
|
||||
{
|
||||
throw new CryptographicException(
|
||||
$"Bundle key-derivation iteration count {metadata.Iterations} is outside the supported range " +
|
||||
$"[{EncryptionMetadata.MinPbkdf2Iterations}, {EncryptionMetadata.MaxPbkdf2Iterations}].");
|
||||
}
|
||||
|
||||
var salt = Convert.FromBase64String(metadata.SaltB64);
|
||||
var nonce = Convert.FromBase64String(metadata.IvB64);
|
||||
var key = DeriveKey(passphrase, salt, metadata.Iterations);
|
||||
|
||||
@@ -106,6 +106,38 @@ public sealed class BundleExporter : IBundleExporter
|
||||
.ToDictionaryAsync(a => a.Id, a => a.Name, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// TRN-8: the full root→leaf path of each referenced area — the same leaf name
|
||||
// may exist under two parents. One read of the areas of the sites involved.
|
||||
var areaPathById = new Dictionary<int, IReadOnlyList<string>>();
|
||||
if (referencedAreaIds.Count > 0)
|
||||
{
|
||||
var areaSiteIds = await _dbContext.Areas
|
||||
.Where(a => referencedAreaIds.Contains(a.Id))
|
||||
.Select(a => a.SiteId)
|
||||
.Distinct()
|
||||
.ToListAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var siteAreas = await _dbContext.Areas.AsNoTracking()
|
||||
.Where(a => areaSiteIds.Contains(a.SiteId))
|
||||
.Select(a => new { a.Id, a.Name, a.ParentAreaId })
|
||||
.ToDictionaryAsync(a => a.Id, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
foreach (var areaId in referencedAreaIds)
|
||||
{
|
||||
var path = new List<string>();
|
||||
var seen = new HashSet<int>();
|
||||
int? current = areaId;
|
||||
while (current is { } id && siteAreas.TryGetValue(id, out var area) && seen.Add(id))
|
||||
{
|
||||
path.Add(area.Name);
|
||||
current = area.ParentAreaId;
|
||||
}
|
||||
if (path.Count == 0 || current is not null) continue; // orphan/cyclic chain: leaf name only
|
||||
path.Reverse();
|
||||
areaPathById[areaId] = path;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Convert to the wire-shaped DTO (strips EF identity, refs-by-name).
|
||||
// The resolver's site/dataConnection/instance closure is wired
|
||||
// through via object-initializer — without this the aggregate would
|
||||
@@ -134,6 +166,7 @@ public sealed class BundleExporter : IBundleExporter
|
||||
// Area id→name lookup for the exported instances — feeds the serializer's
|
||||
// AreaName projection so each instance's area travels by name.
|
||||
AreaNameById = areaNameById,
|
||||
AreaPathById = areaPathById,
|
||||
};
|
||||
var contentDto = _entitySerializer.ToBundleContent(aggregate);
|
||||
|
||||
|
||||
@@ -237,15 +237,10 @@ public sealed class ArtifactDiff
|
||||
// target's existing timeout untouched in that case.
|
||||
AddIfDifferent(changes, "TimeoutSeconds", existing.TimeoutSeconds, incoming.TimeoutSeconds ?? existing.TimeoutSeconds);
|
||||
|
||||
// Secrets: presence-only comparison (we never echo the value in the diff).
|
||||
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthConfiguration);
|
||||
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthConfiguration");
|
||||
if (existingHasSecret != incomingHasSecret)
|
||||
{
|
||||
changes.Add(new FieldChange("Secrets.AuthConfiguration",
|
||||
existingHasSecret ? "<present>" : null,
|
||||
incomingHasSecret ? "<present>" : null));
|
||||
}
|
||||
// Secrets: compared by hash, reported presence-only (TRN-2 — the value is never
|
||||
// echoed in the diff, but a changed value is no longer read as Identical).
|
||||
AddSecretChange(changes, "Secrets.AuthConfiguration",
|
||||
existing.AuthConfiguration, SecretValue(incoming.Secrets, "AuthConfiguration"));
|
||||
|
||||
// Methods are name-keyed children.
|
||||
var existingForCompare = existingMethods ?? Array.Empty<ExternalSystemMethod>();
|
||||
@@ -276,15 +271,10 @@ public sealed class ArtifactDiff
|
||||
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
|
||||
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
|
||||
|
||||
// ConnectionString lives in Secrets only — presence-only comparison.
|
||||
var existingHasSecret = !string.IsNullOrEmpty(existing.ConnectionString);
|
||||
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("ConnectionString");
|
||||
if (existingHasSecret != incomingHasSecret)
|
||||
{
|
||||
changes.Add(new FieldChange("Secrets.ConnectionString",
|
||||
existingHasSecret ? "<present>" : null,
|
||||
incomingHasSecret ? "<present>" : null));
|
||||
}
|
||||
// ConnectionString lives in Secrets only — compared by hash, reported
|
||||
// presence-only (TRN-2).
|
||||
AddSecretChange(changes, "Secrets.ConnectionString",
|
||||
existing.ConnectionString, SecretValue(incoming.Secrets, "ConnectionString"));
|
||||
|
||||
return BuildItem("DatabaseConnection", incoming.Name, changes);
|
||||
}
|
||||
@@ -345,14 +335,9 @@ public sealed class ArtifactDiff
|
||||
AddIfDifferent(changes, "OAuth2Scope", existing.OAuth2Scope, incoming.OAuth2Scope);
|
||||
AddIfDifferent(changes, "Transport", existing.Transport, incoming.Transport);
|
||||
|
||||
var existingHasSecret = !string.IsNullOrEmpty(existing.Credentials);
|
||||
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("Credentials");
|
||||
if (existingHasSecret != incomingHasSecret)
|
||||
{
|
||||
changes.Add(new FieldChange("Secrets.Credentials",
|
||||
existingHasSecret ? "<present>" : null,
|
||||
incomingHasSecret ? "<present>" : null));
|
||||
}
|
||||
// TRN-2: compared by hash, reported presence-only.
|
||||
AddSecretChange(changes, "Secrets.Credentials",
|
||||
existing.Credentials, SecretValue(incoming.Secrets, "Credentials"));
|
||||
|
||||
return BuildItem("SmtpConfiguration", incoming.Host, changes);
|
||||
}
|
||||
@@ -379,14 +364,9 @@ public sealed class ArtifactDiff
|
||||
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
|
||||
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
|
||||
|
||||
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthToken);
|
||||
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthToken");
|
||||
if (existingHasSecret != incomingHasSecret)
|
||||
{
|
||||
changes.Add(new FieldChange("Secrets.AuthToken",
|
||||
existingHasSecret ? "<present>" : null,
|
||||
incomingHasSecret ? "<present>" : null));
|
||||
}
|
||||
// TRN-2: compared by hash, reported presence-only.
|
||||
AddSecretChange(changes, "Secrets.AuthToken",
|
||||
existing.AuthToken, SecretValue(incoming.Secrets, "AuthToken"));
|
||||
|
||||
return BuildItem("SmsConfiguration", incoming.AccountSid, changes);
|
||||
}
|
||||
@@ -481,13 +461,12 @@ public sealed class ArtifactDiff
|
||||
AddIfDifferent(changes, "FailoverRetryCount", existing.FailoverRetryCount, incoming.FailoverRetryCount);
|
||||
|
||||
// Protocol config rides in Secrets (PrimaryConfiguration / BackupConfiguration).
|
||||
// Presence-only comparison — never echo the config value.
|
||||
AddSecretPresenceChange(changes, "Secrets.PrimaryConfiguration",
|
||||
!string.IsNullOrEmpty(existing.PrimaryConfiguration),
|
||||
HasSecretKey(incoming.Secrets, "PrimaryConfiguration"));
|
||||
AddSecretPresenceChange(changes, "Secrets.BackupConfiguration",
|
||||
!string.IsNullOrEmpty(existing.BackupConfiguration),
|
||||
HasSecretKey(incoming.Secrets, "BackupConfiguration"));
|
||||
// Compared by hash, reported presence-only — never echo the config value
|
||||
// (TRN-2: a changed endpoint URL used to read Identical and be force-skipped).
|
||||
AddSecretChange(changes, "Secrets.PrimaryConfiguration",
|
||||
existing.PrimaryConfiguration, SecretValue(incoming.Secrets, "PrimaryConfiguration"));
|
||||
AddSecretChange(changes, "Secrets.BackupConfiguration",
|
||||
existing.BackupConfiguration, SecretValue(incoming.Secrets, "BackupConfiguration"));
|
||||
|
||||
return BuildItem("DataConnection", incoming.Name, changes);
|
||||
}
|
||||
@@ -510,13 +489,19 @@ public sealed class ArtifactDiff
|
||||
/// <param name="existingTemplateName">The existing instance's template name (the entity carries only a FK), or null if unknown.</param>
|
||||
/// <param name="existingSiteIdentifier">The existing instance's site identifier (the entity carries only a FK), or null if unknown.</param>
|
||||
/// <param name="existingAreaName">The existing instance's area name (the entity carries only a FK), or null if unknown / unset.</param>
|
||||
/// <param name="existingConnectionNameById">TRN-6: id→name of the existing instance's site connections, so a
|
||||
/// binding's bound connection (stored as a FK) is compared by name. Null skips the connection comparison.</param>
|
||||
/// <param name="existingAreaPath">TRN-8: the existing instance's root→leaf area path; compared instead of the
|
||||
/// leaf name when the incoming instance carries an <see cref="InstanceDto.AreaPath"/>.</param>
|
||||
/// <returns>An import preview item describing the conflict type and differences.</returns>
|
||||
public ImportPreviewItem CompareInstance(
|
||||
InstanceDto incoming,
|
||||
Instance? existing,
|
||||
string? existingTemplateName = null,
|
||||
string? existingSiteIdentifier = null,
|
||||
string? existingAreaName = null)
|
||||
string? existingAreaName = null,
|
||||
IReadOnlyDictionary<int, string>? existingConnectionNameById = null,
|
||||
IReadOnlyList<string>? existingAreaPath = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(incoming);
|
||||
if (existing is null) return New("Instance", incoming.UniqueName);
|
||||
@@ -533,8 +518,21 @@ public sealed class ArtifactDiff
|
||||
{
|
||||
AddIfDifferent(changes, "SiteIdentifier", existingSiteIdentifier, incoming.SiteIdentifier);
|
||||
}
|
||||
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName);
|
||||
AddIfDifferent(changes, "State", existing.State.ToString(), incoming.State.ToString());
|
||||
if (incoming.AreaPath is { Count: > 0 } incomingPath && (existingAreaPath is not null || existing.AreaId is null))
|
||||
{
|
||||
// TRN-8: the same leaf name can sit under two parents — compare the full path.
|
||||
AddIfDifferent(changes, "AreaPath",
|
||||
existingAreaPath is null ? null : string.Join("/", existingAreaPath),
|
||||
string.Join("/", incomingPath));
|
||||
}
|
||||
else
|
||||
{
|
||||
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName);
|
||||
}
|
||||
// TRN-6: State is not compared — an import always writes NotDeployed for a new
|
||||
// instance and never carries a live state across environments, so a State-only
|
||||
// difference used to read Modified and an Overwrite then reset a live instance
|
||||
// to NotDeployed for no configuration change.
|
||||
|
||||
DiffChildren(
|
||||
existing.AttributeOverrides,
|
||||
@@ -573,10 +571,14 @@ public sealed class ArtifactDiff
|
||||
incoming.ConnectionBindings,
|
||||
e => e.AttributeName,
|
||||
i => i.AttributeName,
|
||||
// ConnectionName resolves to a FK on the entity (DataConnectionId) that
|
||||
// can't be compared cross-environment, so the binding diff compares only
|
||||
// the per-attribute DataSourceReference override.
|
||||
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride,
|
||||
// TRN-6: the entity binds by FK (DataConnectionId); the caller resolves it to
|
||||
// the target connection's name, which is compared (case-insensitively, like
|
||||
// the unique (SiteId, Name) index) together with the per-attribute
|
||||
// DataSourceReference override. A rebind OPC1 -> OPC2 used to read Identical.
|
||||
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride
|
||||
&& (existingConnectionNameById is null
|
||||
|| (existingConnectionNameById.TryGetValue(e.DataConnectionId, out var boundName)
|
||||
&& string.Equals(boundName, i.ConnectionName, StringComparison.OrdinalIgnoreCase))),
|
||||
"ConnectionBindings",
|
||||
changes);
|
||||
|
||||
@@ -657,24 +659,37 @@ public sealed class ArtifactDiff
|
||||
};
|
||||
|
||||
/// <summary>True if <paramref name="secrets"/> carries the named key.</summary>
|
||||
private static bool HasSecretKey(SecretsBlock? secrets, string key) =>
|
||||
secrets is not null && secrets.Values.ContainsKey(key);
|
||||
private static string? SecretValue(SecretsBlock? secrets, string key) =>
|
||||
secrets is not null && secrets.Values.TryGetValue(key, out var value) ? value : null;
|
||||
|
||||
/// <summary>
|
||||
/// Records a presence-only secret change (a flip in whether a value is set on
|
||||
/// each side) using the <c><present></c> / null marker convention. The
|
||||
/// secret value itself is NEVER read into the diff — only its presence.
|
||||
/// TRN-2: compares a secret-bearing value by SHA-256 hash and reports the result
|
||||
/// presence-only. A flip in presence uses the <c><present></c> / null markers;
|
||||
/// a value present on both sides that DIFFERS is reported as
|
||||
/// <c><present></c> → <c><changed></c>, so the row classifies Modified
|
||||
/// (it used to read Identical and be force-skipped) while the value itself never
|
||||
/// reaches the diff.
|
||||
/// </summary>
|
||||
private static void AddSecretPresenceChange(List<FieldChange> changes, string field, bool existingHasSecret, bool incomingHasSecret)
|
||||
private static void AddSecretChange(List<FieldChange> changes, string field, string? existingValue, string? incomingValue)
|
||||
{
|
||||
if (existingHasSecret != incomingHasSecret)
|
||||
var existingHas = !string.IsNullOrEmpty(existingValue);
|
||||
var incomingHas = !string.IsNullOrEmpty(incomingValue);
|
||||
if (existingHas != incomingHas)
|
||||
{
|
||||
changes.Add(new FieldChange(field,
|
||||
existingHasSecret ? "<present>" : null,
|
||||
incomingHasSecret ? "<present>" : null));
|
||||
existingHas ? "<present>" : null,
|
||||
incomingHas ? "<present>" : null));
|
||||
return;
|
||||
}
|
||||
if (existingHas && !SecretHash(existingValue!).AsSpan().SequenceEqual(SecretHash(incomingValue!)))
|
||||
{
|
||||
changes.Add(new FieldChange(field, "<present>", "<changed>"));
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] SecretHash(string value) =>
|
||||
System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value));
|
||||
|
||||
private static void DiffChildren<TExisting, TIncoming>(
|
||||
IEnumerable<TExisting> existing,
|
||||
IEnumerable<TIncoming> incoming,
|
||||
|
||||
@@ -477,7 +477,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
|
||||
public async Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
|
||||
{
|
||||
var session = _sessionStore.Get(sessionId)
|
||||
?? throw new InvalidOperationException($"Bundle session {sessionId} not found or expired.");
|
||||
@@ -628,10 +628,16 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
var targetConnectionsBySiteIdentifier =
|
||||
new Dictionary<string, IReadOnlyList<DataConnection>>(StringComparer.Ordinal);
|
||||
|
||||
// TRN-3: the preview honours the operator's name map, so the diffs, the
|
||||
// connection auto-match and the unresolved-connection blocker are computed
|
||||
// against the MAPPED target site / connection — not the source identity.
|
||||
var previewMap = new PreviewNameMap(nameMap ?? BundleNameMap.Empty);
|
||||
|
||||
async Task<Site?> ResolveTargetSiteAsync(string siteIdentifier)
|
||||
{
|
||||
if (targetSiteByIdentifier.TryGetValue(siteIdentifier, out var cached)) return cached;
|
||||
var site = await _siteRepo.GetSiteByIdentifierAsync(siteIdentifier, ct).ConfigureAwait(false);
|
||||
var site = await _siteRepo.GetSiteByIdentifierAsync(
|
||||
previewMap.TargetSiteIdentifier(siteIdentifier), ct).ConfigureAwait(false);
|
||||
targetSiteByIdentifier[siteIdentifier] = site;
|
||||
return site;
|
||||
}
|
||||
@@ -684,7 +690,10 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
foreach (var dcDto in content.DataConnections)
|
||||
{
|
||||
var targetConns = await ResolveTargetConnectionsAsync(dcDto.SiteIdentifier).ConfigureAwait(false);
|
||||
var existing = targetConns.FirstOrDefault(c => string.Equals(c.Name, dcDto.Name, StringComparison.Ordinal));
|
||||
// TRN-7: names compare the way the database's case-insensitive collation
|
||||
// (and its unique (SiteId, Name) index) does — exact spelling first.
|
||||
var existing = FindByName(targetConns, c => c.Name,
|
||||
previewMap.TargetConnectionName(dcDto.SiteIdentifier, dcDto.Name));
|
||||
var item = _diff.CompareDataConnection(dcDto, existing);
|
||||
items.Add(item with { Name = QualifiedConnectionName(dcDto.SiteIdentifier, dcDto.Name) });
|
||||
}
|
||||
@@ -698,14 +707,21 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// batched read for every bundled instance, and the template / site / area
|
||||
// names come from the library projection, one site list and one area list
|
||||
// per site — not four queries per instance.
|
||||
// TRN-7: case-insensitive like the unique index on UniqueName (exact spelling wins).
|
||||
var bundleInstanceNames = content.Instances.Select(i => i.UniqueName).ToHashSet(StringComparer.Ordinal);
|
||||
var existingInstanceByName = content.Instances.Count == 0
|
||||
? new Dictionary<string, Instance>(StringComparer.Ordinal)
|
||||
: (await _templateRepo
|
||||
? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
|
||||
: ToNameLookup(
|
||||
(await _templateRepo
|
||||
.GetInstancesByUniqueNamesAsync(content.Instances.Select(i => i.UniqueName), ct)
|
||||
.ConfigureAwait(false))
|
||||
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal);
|
||||
.OrderBy(i => bundleInstanceNames.Contains(i.UniqueName) ? 0 : 1),
|
||||
i => i.UniqueName);
|
||||
// TRN-6: an existing binding stores a DataConnectionId; resolve it to the
|
||||
// connection's name (per site, one read) so the diff can compare it.
|
||||
var connectionNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, string>>();
|
||||
Dictionary<int, string>? siteIdentifierById = null;
|
||||
var areaNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, string>>();
|
||||
var areaNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, Area>>();
|
||||
foreach (var instDto in content.Instances)
|
||||
{
|
||||
existingInstanceByName.TryGetValue(instDto.UniqueName, out var existing);
|
||||
@@ -713,8 +729,17 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
string? existingTemplateName = null;
|
||||
string? existingSiteIdentifier = null;
|
||||
string? existingAreaName = null;
|
||||
IReadOnlyList<string>? existingAreaPath = null;
|
||||
IReadOnlyDictionary<int, string>? existingConnectionNames = null;
|
||||
if (existing is not null)
|
||||
{
|
||||
if (!connectionNameByIdBySite.TryGetValue(existing.SiteId, out existingConnectionNames))
|
||||
{
|
||||
existingConnectionNames = (await _siteRepo.GetDataConnectionsBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
|
||||
.ToDictionary(c => c.Id, c => c.Name);
|
||||
connectionNameByIdBySite[existing.SiteId] = existingConnectionNames;
|
||||
}
|
||||
|
||||
// The entity stores template/site/area as numeric FKs that can't be
|
||||
// compared cross-environment, so resolve each to the same stable
|
||||
// string identity the incoming DTO carries.
|
||||
@@ -726,27 +751,39 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
|
||||
if (existing.AreaId is int areaId)
|
||||
{
|
||||
if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areaNames))
|
||||
if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areasById))
|
||||
{
|
||||
areaNames = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
|
||||
.ToDictionary(a => a.Id, a => a.Name);
|
||||
areaNameByIdBySite[existing.SiteId] = areaNames;
|
||||
areasById = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
|
||||
.ToDictionary(a => a.Id, a => a);
|
||||
areaNameByIdBySite[existing.SiteId] = areasById;
|
||||
}
|
||||
existingAreaName = areaNames.TryGetValue(areaId, out var an) ? an : null;
|
||||
existingAreaName = areasById.TryGetValue(areaId, out var area) ? area.Name : null;
|
||||
existingAreaPath = AreaPathOf(areaId, areasById);
|
||||
}
|
||||
}
|
||||
|
||||
// Compare against what the apply would write: the mapped target site and
|
||||
// the mapped target connection names (TRN-3).
|
||||
var mappedDto = instDto with
|
||||
{
|
||||
SiteIdentifier = previewMap.TargetSiteIdentifier(instDto.SiteIdentifier),
|
||||
ConnectionBindings = instDto.ConnectionBindings
|
||||
.Select(b => b with { ConnectionName = previewMap.TargetConnectionName(instDto.SiteIdentifier, b.ConnectionName) })
|
||||
.ToList(),
|
||||
};
|
||||
items.Add(_diff.CompareInstance(
|
||||
instDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName));
|
||||
mappedDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName,
|
||||
existingConnectionNames, existingAreaPath));
|
||||
}
|
||||
|
||||
// ---- Required site/connection mappings ----
|
||||
var (requiredSites, requiredConnections) = await BuildRequiredMappingsAsync(
|
||||
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync).ConfigureAwait(false);
|
||||
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName).ConfigureAwait(false);
|
||||
|
||||
// ---- Blocker detection ----
|
||||
items.AddRange(await DetectBlockersAsync(
|
||||
content, ResolveTargetConnectionsAsync, library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false));
|
||||
content, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName,
|
||||
library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false));
|
||||
|
||||
return new ImportPreview(sessionId, items, requiredSites, requiredConnections);
|
||||
}
|
||||
@@ -772,7 +809,8 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
BuildRequiredMappingsAsync(
|
||||
BundleContentDto content,
|
||||
Func<string, Task<Site?>> resolveTargetSite,
|
||||
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections)
|
||||
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
|
||||
Func<string, string, string> targetConnectionName)
|
||||
{
|
||||
// Distinct source-site identifiers, with a best-effort display name.
|
||||
// SiteDto carries a Name; instances / data-connections only carry the
|
||||
@@ -838,11 +876,11 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// Auto-match only WITHIN the auto-matched target site: a connection of
|
||||
// the same name under a different site is not a valid match.
|
||||
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false);
|
||||
var matched = targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal));
|
||||
var matched = FindByName(targetConns, c => c.Name, targetConnectionName(site, name));
|
||||
connectionMappings.Add(new RequiredConnectionMapping(
|
||||
SourceSiteIdentifier: site,
|
||||
SourceConnectionName: name,
|
||||
AutoMatchTargetName: matched ? name : null));
|
||||
AutoMatchTargetName: matched?.Name));
|
||||
}
|
||||
|
||||
return (siteMappings, connectionMappings);
|
||||
@@ -860,6 +898,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
private async Task<IReadOnlyList<ImportPreviewItem>> DetectBlockersAsync(
|
||||
BundleContentDto content,
|
||||
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
|
||||
Func<string, string, string> targetConnectionName,
|
||||
TemplateLibrary library,
|
||||
IReadOnlyList<SharedScript> allSharedScripts,
|
||||
IReadOnlyList<ExternalSystemDefinition> allExternalSystems,
|
||||
@@ -871,7 +910,8 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// The set of template names the import can satisfy = (in-bundle templates)
|
||||
// ∪ (templates already in the target DB). An instance whose TemplateName is
|
||||
// in neither is unresolvable.
|
||||
var bundleTemplateNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
// TRN-7: instance template names resolve case-insensitively on apply.
|
||||
var bundleTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
// A derived slot template is not something an instance is created from (#118).
|
||||
foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t))) bundleTemplateNames.Add(t.Name);
|
||||
// ScadaBridge#118: a malformed or cyclic derivation fails the apply outright.
|
||||
@@ -893,7 +933,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// Members + lock flags are needed below (CollectLockedOverrideWarnings) but
|
||||
// never script bodies — the body-free, untracked analysis projection (04/P4).
|
||||
var targetTemplates = await library.GetAnalysisAsync(ct).ConfigureAwait(false);
|
||||
var targetTemplateNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
var targetTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var t in targetTemplates)
|
||||
{
|
||||
targetTemplateNames.Add(t.Name);
|
||||
@@ -951,7 +991,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
{
|
||||
if (bundleConnections.Contains((site, name))) continue;
|
||||
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false);
|
||||
if (targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal))) continue;
|
||||
if (FindByName(targetConns, c => c.Name, targetConnectionName(site, name)) is not null) continue;
|
||||
// Site-qualify the blocker Name so two sites' same-named-but-missing
|
||||
// connections surface as distinct blockers (a bare name would collide).
|
||||
blockers.Add(new ImportPreviewItem(
|
||||
@@ -1613,6 +1653,21 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
ArgumentNullException.ThrowIfNull(resolutions);
|
||||
ArgumentNullException.ThrowIfNull(user);
|
||||
|
||||
// TRN-9: Rename is meaningless for a site, a data connection and the SMTP /
|
||||
// SMS configurations (it was silently Skipped, or wrote a mangled junk row
|
||||
// delivery never uses). Reject it up front rather than report "Renamed: 1".
|
||||
var unsupportedRenames = resolutions
|
||||
.Where(r => r.Action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(r.EntityType))
|
||||
.Select(r => $"{r.EntityType} '{r.Name}'")
|
||||
.ToList();
|
||||
if (unsupportedRenames.Count > 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"Rename is not supported for sites, data connections, SMTP or SMS configurations; "
|
||||
+ "choose Skip or Overwrite for: " + string.Join(", ", unsupportedRenames) + ".",
|
||||
nameof(resolutions));
|
||||
}
|
||||
|
||||
// Normalise null → Empty so the resolve-or-create logic always has a map
|
||||
// to consult. An empty map means "no explicit operator mappings" — every
|
||||
// referenced site/connection falls through to the identity auto-match.
|
||||
@@ -1995,9 +2050,10 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// It writes the instance row + its four child collections (attribute /
|
||||
// alarm / native-alarm-source overrides + connection bindings) and
|
||||
// rewires every name-keyed FK to the target environment's ids.
|
||||
var instanceWarnings = new List<string>();
|
||||
await ApplyInstancesAsync(
|
||||
content, resolutionMap, siteBySourceIdentifier, connectionMaps,
|
||||
library, user, summary, ct).ConfigureAwait(false);
|
||||
library, user, summary, instanceWarnings, ct).ConfigureAwait(false);
|
||||
|
||||
// ---- Pre-commit point: stale-instance computation ----
|
||||
// Everything the import will write is staged on the change tracker at
|
||||
@@ -2050,7 +2106,9 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
StaleInstanceIds: staleInstanceIds,
|
||||
AuditEventCorrelation: bundleImportId.ToString(),
|
||||
ApiKeysIgnored: apiKeysIgnored,
|
||||
Warnings: derivedWarnings.Count == 0 ? validationWarnings : validationWarnings.Concat(derivedWarnings).ToList());
|
||||
Warnings: derivedWarnings.Count == 0 && instanceWarnings.Count == 0
|
||||
? validationWarnings
|
||||
: validationWarnings.Concat(derivedWarnings).Concat(instanceWarnings).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -2208,7 +2266,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
{
|
||||
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
|
||||
if (resolution.Action != ResolutionAction.Overwrite) continue;
|
||||
if (targetTemplateIdByName.TryGetValue(dto.Name, out var templateId))
|
||||
if (TryGetIdByNameIgnoreCase(targetTemplateIdByName, dto.Name, out var templateId))
|
||||
{
|
||||
overwrittenTemplateIds.Add(templateId);
|
||||
}
|
||||
@@ -2418,6 +2476,96 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
/// throw on a duplicate key: the first row for a name wins. Used wherever a
|
||||
/// by-name DB result is re-keyed in memory (ScadaBridge#93).
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// TRN-7: finds the row named <paramref name="wanted"/> the way the database's
|
||||
/// case-insensitive collation (and its unique indexes) would — the exact spelling
|
||||
/// first, otherwise a case-insensitive match. Null when neither exists.
|
||||
/// </summary>
|
||||
internal static T? FindByName<T>(IEnumerable<T> rows, Func<T, string> name, string wanted)
|
||||
where T : class
|
||||
{
|
||||
T? ignoreCase = null;
|
||||
foreach (var row in rows)
|
||||
{
|
||||
var n = name(row);
|
||||
if (string.Equals(n, wanted, StringComparison.Ordinal)) return row;
|
||||
if (ignoreCase is null && string.Equals(n, wanted, StringComparison.OrdinalIgnoreCase)) ignoreCase = row;
|
||||
}
|
||||
return ignoreCase;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-8: the root→leaf name path of area <paramref name="areaId"/>, or null when the
|
||||
/// parent chain is broken or cyclic.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<string>? AreaPathOf(int areaId, IReadOnlyDictionary<int, Area> areasById)
|
||||
{
|
||||
var path = new List<string>();
|
||||
var seen = new HashSet<int>();
|
||||
int? current = areaId;
|
||||
while (current is { } id)
|
||||
{
|
||||
if (!seen.Add(id) || !areasById.TryGetValue(id, out var area)) return null;
|
||||
path.Add(area.Name);
|
||||
current = area.ParentAreaId;
|
||||
}
|
||||
path.Reverse();
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-7: looks <paramref name="name"/> up in an ordinal name→id map, falling back to a
|
||||
/// case-insensitive match when exactly one key matches that way (two case variants are
|
||||
/// ambiguous and resolve to nothing, as a missing name does).
|
||||
/// </summary>
|
||||
internal static bool TryGetIdByNameIgnoreCase(IReadOnlyDictionary<string, int> idByName, string name, out int id)
|
||||
{
|
||||
if (idByName.TryGetValue(name, out id)) return true;
|
||||
var found = false;
|
||||
foreach (var (key, value) in idByName)
|
||||
{
|
||||
if (!string.Equals(key, name, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (found) { id = 0; return false; }
|
||||
id = value;
|
||||
found = true;
|
||||
}
|
||||
if (!found) id = 0;
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-3: the operator's <see cref="BundleNameMap"/> as seen by the preview — the
|
||||
/// target site identifier and target connection name a source reference resolves to.
|
||||
/// Only a <see cref="MappingAction.MapToExisting"/> entry with an explicit target
|
||||
/// redirects; every other reference keeps its source identity (the identity
|
||||
/// auto-match the apply performs for it as well).
|
||||
/// </summary>
|
||||
private sealed class PreviewNameMap
|
||||
{
|
||||
private readonly Dictionary<string, string> _siteTargets = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<(string Site, string Name), string> _connectionTargets = new();
|
||||
|
||||
public PreviewNameMap(BundleNameMap map)
|
||||
{
|
||||
foreach (var m in map.Sites)
|
||||
{
|
||||
if (m.Action == MappingAction.MapToExisting && !string.IsNullOrEmpty(m.TargetSiteIdentifier))
|
||||
_siteTargets.TryAdd(m.SourceSiteIdentifier, m.TargetSiteIdentifier);
|
||||
}
|
||||
foreach (var m in map.Connections)
|
||||
{
|
||||
if (m.Action == MappingAction.MapToExisting && !string.IsNullOrEmpty(m.TargetConnectionName))
|
||||
_connectionTargets.TryAdd((m.SourceSiteIdentifier, m.SourceConnectionName), m.TargetConnectionName);
|
||||
}
|
||||
}
|
||||
|
||||
public string TargetSiteIdentifier(string sourceSiteIdentifier) =>
|
||||
_siteTargets.TryGetValue(sourceSiteIdentifier, out var t) ? t : sourceSiteIdentifier;
|
||||
|
||||
public string TargetConnectionName(string sourceSiteIdentifier, string sourceConnectionName) =>
|
||||
_connectionTargets.TryGetValue((sourceSiteIdentifier, sourceConnectionName), out var t) ? t : sourceConnectionName;
|
||||
}
|
||||
|
||||
internal static Dictionary<string, T> ToNameLookup<T>(IEnumerable<T> rows, Func<T, string> name)
|
||||
{
|
||||
var lookup = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
|
||||
@@ -3346,7 +3494,11 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
{
|
||||
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
|
||||
if (resolution.Action == ResolutionAction.Skip) continue;
|
||||
if (dto.Compositions.Count == 0) continue;
|
||||
// TRN-4: a bundle template with NO compositions must still run the
|
||||
// clear below when it overwrites an existing target row — the source
|
||||
// removed every slot, and the diff reports those removals. Only an
|
||||
// Add/Rename (a brand-new row with nothing to clear) can be skipped.
|
||||
if (dto.Compositions.Count == 0 && resolution.Action != ResolutionAction.Overwrite) continue;
|
||||
|
||||
var importedName = resolution.Action == ResolutionAction.Rename
|
||||
? (resolution.RenameTo ?? dto.Name)
|
||||
@@ -3378,9 +3530,42 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
var existingComps = parent.Compositions
|
||||
.Where(c => derivedSlots is null || !derivedSlots.Contains(c.InstanceName))
|
||||
.ToList();
|
||||
// TRN-5: a slot row owns its slot-derived template (OwnerCompositionId,
|
||||
// no database relationship), so deleting the row alone orphaned the
|
||||
// derived template with a live ParentTemplateId that then blocked
|
||||
// deleting its base. A slot the bundle REMOVES (its instance name is
|
||||
// not among the bundle's compositions for this owner, and no bundle
|
||||
// composition names its composed template) is deleted through
|
||||
// TemplateService.DeleteCompositionAsync, which cascades the slot-owned
|
||||
// derived templates (it saves inside the import's transaction, as the
|
||||
// derived-template pass already does). A slot the bundle re-composes
|
||||
// keeps the row-only delete: a pre-#118 bundle re-composes the slot
|
||||
// onto that very derived template by name, so it must survive.
|
||||
var bundleSlotNames = dto.Compositions
|
||||
.Select(c => c.InstanceName)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var bundleComposedNames = dto.Compositions
|
||||
.Where(c => !string.IsNullOrEmpty(c.ComposedTemplateName))
|
||||
.Select(c => c.ComposedTemplateName!)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
TemplateService? compositionService = null;
|
||||
foreach (var existing in existingComps)
|
||||
{
|
||||
await _templateRepo.DeleteTemplateCompositionAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
var removedSlot = !bundleSlotNames.Contains(existing.InstanceName)
|
||||
&& await IsRemovableSlotDerivedAsync(existing, bundleComposedNames, ct).ConfigureAwait(false);
|
||||
if (!removedSlot)
|
||||
{
|
||||
await _templateRepo.DeleteTemplateCompositionAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
compositionService ??= new TemplateService(_templateRepo, _auditService);
|
||||
var deleted = await compositionService.DeleteCompositionAsync(existing.Id, user, ct).ConfigureAwait(false);
|
||||
if (!deleted.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Could not remove composition '{parent.Name}.{existing.InstanceName}': {deleted.Error}");
|
||||
}
|
||||
}
|
||||
if (derivedSlots is null)
|
||||
{
|
||||
@@ -3421,11 +3606,13 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// The fallback is a dictionary lookup into the per-apply library
|
||||
// snapshot (04/P4) — a name not in Local is a pre-existing target
|
||||
// template this apply has not touched, so its pre-write id is current.
|
||||
localByName.TryGetValue(compDto.ComposedTemplateName, out var composedStub);
|
||||
// TRN-7: exact spelling first, then case-insensitive (the database's
|
||||
// collation treats a case variant as the same template).
|
||||
localByName.TryGetImported(compDto.ComposedTemplateName, out var composedStub);
|
||||
int? composedId = composedStub?.Id;
|
||||
if (composedId is null
|
||||
&& (await library.GetIdByNameAsync(ct).ConfigureAwait(false))
|
||||
.TryGetValue(compDto.ComposedTemplateName, out var libraryId))
|
||||
&& TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false),
|
||||
compDto.ComposedTemplateName, out var libraryId))
|
||||
{
|
||||
composedId = libraryId;
|
||||
}
|
||||
@@ -3514,10 +3701,13 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
? (baseResolution.RenameTo ?? dto.BaseTemplateName)
|
||||
: dto.BaseTemplateName;
|
||||
|
||||
localByName.TryGetValue(baseName, out var baseStub);
|
||||
// TRN-7: exact spelling first, then case-insensitive — a bundle base
|
||||
// 'PumpBase' overwriting target 'pumpbase' used to miss both lookups and
|
||||
// null the child's ParentTemplateId.
|
||||
localByName.TryGetImported(baseName, out var baseStub);
|
||||
int? baseId = baseStub?.Id;
|
||||
if (baseId is null
|
||||
&& (await library.GetIdByNameAsync(ct).ConfigureAwait(false)).TryGetValue(baseName, out var libraryId))
|
||||
&& TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false), baseName, out var libraryId))
|
||||
{
|
||||
baseId = libraryId;
|
||||
}
|
||||
@@ -3595,6 +3785,26 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
_exact.TryGetValue(name, out template!) || _ignoreCase.TryGetValue(name, out template!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-5: true when <paramref name="composition"/> owns a slot-derived template
|
||||
/// (<c>IsDerived</c> with <c>OwnerCompositionId</c> pointing back at the row) that no
|
||||
/// bundle composition of the same owner names — i.e. deleting the slot must cascade
|
||||
/// the derived template. A slot that composes a base directly (pre-derived data) has
|
||||
/// nothing to cascade and keeps the plain row delete.
|
||||
/// </summary>
|
||||
private async Task<bool> IsRemovableSlotDerivedAsync(
|
||||
TemplateComposition composition, IReadOnlySet<string> bundleComposedNames, CancellationToken ct)
|
||||
{
|
||||
var composed = await _dbContext.Templates.AsNoTracking()
|
||||
.Where(t => t.Id == composition.ComposedTemplateId)
|
||||
.Select(t => new { t.Name, t.IsDerived, t.OwnerCompositionId })
|
||||
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
return composed is not null
|
||||
&& composed.IsDerived
|
||||
&& composed.OwnerCompositionId == composition.Id
|
||||
&& !bundleComposedNames.Contains(composed.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the given tracked templates with their child collections in one batched
|
||||
/// read (Gitea #47 — previously one <c>GetTemplateWithChildrenAsync</c> per
|
||||
@@ -4581,7 +4791,11 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
target = await _siteRepo.GetSiteByIdentifierAsync(targetId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (action == MappingAction.CreateNew || target is null)
|
||||
// TRN-3: an explicit CreateNew for an identifier the target already holds
|
||||
// would violate the unique SiteIdentifier index and roll the whole import
|
||||
// back with a raw SQL error — treat it as a match to that existing site
|
||||
// (the site's own Skip/Overwrite resolution then applies).
|
||||
if (target is null)
|
||||
{
|
||||
var created = BuildSite(siteDto);
|
||||
await _siteRepo.AddSiteAsync(created, ct).ConfigureAwait(false);
|
||||
@@ -4756,13 +4970,14 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
&& mapping.TargetConnectionName is { Length: > 0 } tn
|
||||
? tn
|
||||
: dcDto.Name;
|
||||
var existing = targetConns.FirstOrDefault(c =>
|
||||
string.Equals(c.Name, targetName, StringComparison.Ordinal));
|
||||
// TRN-7: case-insensitive like the unique (SiteId, Name) index, exact first.
|
||||
var existing = FindByName(targetConns, c => c.Name, targetName);
|
||||
|
||||
var action = mapping?.Action
|
||||
?? (existing is not null ? MappingAction.MapToExisting : MappingAction.CreateNew);
|
||||
|
||||
if (action == MappingAction.CreateNew || existing is null)
|
||||
// TRN-3: CreateNew against a connection the target site already holds
|
||||
// (same name) would violate the unique (SiteId, Name) index and roll the
|
||||
// import back with a raw SQL error — match the existing row instead (the
|
||||
// connection's own Skip/Overwrite resolution then applies).
|
||||
if (existing is null)
|
||||
{
|
||||
var created = BuildDataConnection(dcDto, targetSite.Id);
|
||||
await _siteRepo.AddDataConnectionAsync(created, ct).ConfigureAwait(false);
|
||||
@@ -4836,8 +5051,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
: connName;
|
||||
|
||||
var targetConns = await TargetConnsAsync(targetSite.Id).ConfigureAwait(false);
|
||||
var existing = targetConns.FirstOrDefault(c =>
|
||||
string.Equals(c.Name, targetName, StringComparison.Ordinal));
|
||||
var existing = FindByName(targetConns, c => c.Name, targetName);
|
||||
if (existing is null)
|
||||
{
|
||||
// Should already be a preview blocker (present in neither bundle nor
|
||||
@@ -4937,6 +5151,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
TemplateLibrary library,
|
||||
string user,
|
||||
ImportSummary summary,
|
||||
List<string> warnings,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (content.Instances.Count == 0) return;
|
||||
@@ -4945,8 +5160,13 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
// for pre-existing templates, overlaid with the tracked (Local) templates —
|
||||
// which include everything this apply added or renamed, flushed (so their ids
|
||||
// are real) before this pass (review 2026-10-21 04/P4).
|
||||
var templateIdByName = new Dictionary<string, int>(
|
||||
await library.GetIdByNameAsync(ct).ConfigureAwait(false), StringComparer.Ordinal);
|
||||
// TRN-7: case-insensitive like the template name index (exact spelling wins —
|
||||
// the ordinal library map is copied first, so a case variant only fills a gap).
|
||||
var templateIdByName = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (name, id) in await library.GetIdByNameAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
templateIdByName.TryAdd(name, id);
|
||||
}
|
||||
foreach (var local in _dbContext.Templates.Local)
|
||||
{
|
||||
// A tracked derived slot template never displaces a base of the same name
|
||||
@@ -4966,14 +5186,19 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
lookupNames.Add(dto.UniqueName);
|
||||
if (r.Action == ResolutionAction.Rename && !string.IsNullOrEmpty(r.RenameTo)) lookupNames.Add(r.RenameTo);
|
||||
}
|
||||
// TRN-7: case-insensitive like the unique index on UniqueName; an exact-spelling
|
||||
// row wins over a case variant.
|
||||
var existingByName = lookupNames.Count == 0
|
||||
? new Dictionary<string, Instance>(StringComparer.Ordinal)
|
||||
: (await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false))
|
||||
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal);
|
||||
? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
|
||||
: ToNameLookup(
|
||||
(await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false))
|
||||
.OrderBy(i => lookupNames.Contains(i.UniqueName) ? 0 : 1),
|
||||
i => i.UniqueName);
|
||||
|
||||
// Memoise area resolution per (siteId, areaName) so two instances under the
|
||||
// Memoise area resolution per (siteId, area key) so two instances under the
|
||||
// same area don't each create a duplicate row.
|
||||
var areaIdByKey = new Dictionary<(int SiteId, string Name), int>();
|
||||
var areasBySite = new Dictionary<int, List<Area>>();
|
||||
|
||||
foreach (var dto in content.Instances)
|
||||
{
|
||||
@@ -5003,7 +5228,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
|
||||
int? areaId = await ResolveOrCreateAreaIdAsync(
|
||||
dto.AreaName, targetSite.Id, areaIdByKey, ct).ConfigureAwait(false);
|
||||
dto, targetSite.Id, areaIdByKey, areasBySite, warnings, ct).ConfigureAwait(false);
|
||||
|
||||
switch (resolution.Action)
|
||||
{
|
||||
@@ -5075,37 +5300,96 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves an instance's area by name within the target site, creating the
|
||||
/// area if it doesn't exist. Returns null when <paramref name="areaName"/> is
|
||||
/// null/empty (the instance has no area). Memoised via
|
||||
/// <paramref name="areaIdByKey"/> so repeated references resolve to one row.
|
||||
/// Resolves an instance's area within the target site, creating what is missing.
|
||||
/// Returns null when the instance has no area.
|
||||
/// <para>
|
||||
/// TRN-8: when the bundle carries <see cref="InstanceDto.AreaPath"/> the area is
|
||||
/// resolved level by level from the site root (exact name first, then
|
||||
/// case-insensitive, like the database collation), and any missing level is created
|
||||
/// under its real parent — the same leaf name may exist under two parents, and a
|
||||
/// missing nested area used to be recreated at the site root. A pre-TRN-8 bundle
|
||||
/// carries only the leaf <see cref="InstanceDto.AreaName"/>: it is matched across the
|
||||
/// site as before, but an ambiguous leaf (several areas with that name) is resolved
|
||||
/// deterministically (a root-level area, else the lowest id) and reported as a
|
||||
/// warning instead of silently taking whichever row came back first.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
private async Task<int?> ResolveOrCreateAreaIdAsync(
|
||||
string? areaName,
|
||||
InstanceDto dto,
|
||||
int siteId,
|
||||
Dictionary<(int SiteId, string Name), int> areaIdByKey,
|
||||
Dictionary<int, List<Area>> areasBySite,
|
||||
List<string> warnings,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrEmpty(areaName)) return null;
|
||||
IReadOnlyList<string>? path = dto.AreaPath is { Count: > 0 } p && p.All(segment => !string.IsNullOrEmpty(segment))
|
||||
? p
|
||||
: null;
|
||||
if (path is null && string.IsNullOrEmpty(dto.AreaName)) return null;
|
||||
|
||||
var key = (siteId, areaName);
|
||||
var key = (siteId, path is null ? "leaf:" + dto.AreaName : "path:" + string.Join("\u001f", path));
|
||||
if (areaIdByKey.TryGetValue(key, out var cached)) return cached;
|
||||
|
||||
var existingAreas = await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false);
|
||||
var match = existingAreas.FirstOrDefault(a => string.Equals(a.Name, areaName, StringComparison.Ordinal));
|
||||
if (match is not null)
|
||||
if (!areasBySite.TryGetValue(siteId, out var areas))
|
||||
{
|
||||
areaIdByKey[key] = match.Id;
|
||||
return match.Id;
|
||||
areas = (await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false)).ToList();
|
||||
areasBySite[siteId] = areas;
|
||||
}
|
||||
|
||||
var area = new Area(areaName) { SiteId = siteId };
|
||||
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false);
|
||||
// Flush so the area's surrogate id materialises before it's used as an
|
||||
// instance FK (relational provider). Rides the outer transaction.
|
||||
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
areaIdByKey[key] = area.Id;
|
||||
return area.Id;
|
||||
int resolvedId;
|
||||
if (path is not null)
|
||||
{
|
||||
int? parentId = null;
|
||||
Area? current = null;
|
||||
foreach (var segment in path)
|
||||
{
|
||||
var level = parentId;
|
||||
current = FindByName(areas.Where(a => a.ParentAreaId == level), a => a.Name, segment);
|
||||
if (current is null)
|
||||
{
|
||||
current = new Area(segment) { SiteId = siteId, ParentAreaId = parentId };
|
||||
await _templateRepo.AddAreaAsync(current, ct).ConfigureAwait(false);
|
||||
// Flush so the area's surrogate id materialises before it is used as a
|
||||
// parent / instance FK (relational provider). Rides the outer transaction.
|
||||
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
areas.Add(current);
|
||||
}
|
||||
parentId = current.Id;
|
||||
}
|
||||
resolvedId = current!.Id;
|
||||
}
|
||||
else
|
||||
{
|
||||
var leaf = dto.AreaName!;
|
||||
var exact = areas.Where(a => string.Equals(a.Name, leaf, StringComparison.Ordinal)).ToList();
|
||||
var matches = exact.Count > 0
|
||||
? exact
|
||||
: areas.Where(a => string.Equals(a.Name, leaf, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
if (matches.Count == 0)
|
||||
{
|
||||
var area = new Area(leaf) { SiteId = siteId };
|
||||
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false);
|
||||
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
|
||||
areas.Add(area);
|
||||
resolvedId = area.Id;
|
||||
}
|
||||
else
|
||||
{
|
||||
var chosen = matches.Where(a => a.ParentAreaId is null).OrderBy(a => a.Id).FirstOrDefault()
|
||||
?? matches.OrderBy(a => a.Id).First();
|
||||
if (matches.Count > 1)
|
||||
{
|
||||
warnings.Add(
|
||||
$"Instance '{dto.UniqueName}': area '{leaf}' matches {matches.Count} areas in the target site "
|
||||
+ "and the bundle carries no area path (it predates area paths); it was assigned to area id "
|
||||
+ $"{chosen.Id}. Check the instance's area after the import.");
|
||||
}
|
||||
resolvedId = chosen.Id;
|
||||
}
|
||||
}
|
||||
|
||||
areaIdByKey[key] = resolvedId;
|
||||
return resolvedId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -5380,7 +5664,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
? tn
|
||||
: name;
|
||||
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
|
||||
if (!conns.Any(c => string.Equals(c.Name, targetName, StringComparison.Ordinal)))
|
||||
if (FindByName(conns, c => c.Name, targetName) is null)
|
||||
{
|
||||
errors.Add(
|
||||
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
|
||||
@@ -5389,7 +5673,8 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
|
||||
// ---- Instance template references ----
|
||||
var bundleTemplateNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
// TRN-7: instance template names resolve case-insensitively on apply.
|
||||
var bundleTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t)))
|
||||
{
|
||||
var resolution = ResolveOrDefault(resolutionMap, "Template", t.Name);
|
||||
@@ -5400,7 +5685,7 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
}
|
||||
var targetTemplateNames = new HashSet<string>(
|
||||
(await library.GetIdByNameAsync(ct).ConfigureAwait(false)).Keys,
|
||||
StringComparer.Ordinal);
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var inst in content.Instances)
|
||||
{
|
||||
|
||||
@@ -67,6 +67,14 @@ public sealed record EntityAggregate(
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<int, string> AreaNameById { get; init; } =
|
||||
new Dictionary<int, string>();
|
||||
|
||||
/// <summary>
|
||||
/// TRN-8: lookup from area ID to the area's full path from the site root (one
|
||||
/// element per level) for the exported instances' <c>AreaId</c> FKs. Empty default:
|
||||
/// the serializer then emits <c>AreaPath: null</c> and the importer uses the leaf name.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<int, IReadOnlyList<string>> AreaPathById { get; init; } =
|
||||
new Dictionary<int, IReadOnlyList<string>>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -482,4 +490,16 @@ public sealed record InstanceDto(
|
||||
IReadOnlyList<InstanceAttributeOverrideDto> AttributeOverrides,
|
||||
IReadOnlyList<InstanceAlarmOverrideDto> AlarmOverrides,
|
||||
IReadOnlyList<InstanceNativeAlarmSourceOverrideDto> NativeAlarmSourceOverrides,
|
||||
IReadOnlyList<InstanceConnectionBindingDto> ConnectionBindings);
|
||||
IReadOnlyList<InstanceConnectionBindingDto> ConnectionBindings)
|
||||
{
|
||||
/// <summary>
|
||||
/// TRN-8 (additive, 2026-12-03): the instance's area as its full path from the site
|
||||
/// root, one element per level (e.g. <c>["Line2", "Cell"]</c>; the last element equals
|
||||
/// <see cref="AreaName"/>). The same leaf name may exist under two parents, so the
|
||||
/// importer resolves (and creates missing levels of) the path instead of matching the
|
||||
/// leaf name across the whole site. Null on a bundle written before the field existed
|
||||
/// (the importer then falls back to the leaf <see cref="AreaName"/>) and when the
|
||||
/// instance has no area. An older importer ignores the unknown property.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string>? AreaPath { get; init; }
|
||||
}
|
||||
|
||||
@@ -319,7 +319,14 @@ public sealed class EntitySerializer
|
||||
ConnectionBindings: inst.ConnectionBindings.Select(b => new InstanceConnectionBindingDto(
|
||||
AttributeName: b.AttributeName,
|
||||
ConnectionName: connectionNameByConnectionId.TryGetValue(b.DataConnectionId, out var cn) ? cn : string.Empty,
|
||||
DataSourceReferenceOverride: b.DataSourceReferenceOverride)).ToList())).ToList(),
|
||||
DataSourceReferenceOverride: b.DataSourceReferenceOverride)).ToList())
|
||||
{
|
||||
// TRN-8: the full area path (root → leaf) so the importer can tell two
|
||||
// same-named areas under different parents apart.
|
||||
AreaPath = inst.AreaId is { } pathAreaId && aggregate.AreaPathById.TryGetValue(pathAreaId, out var ap)
|
||||
? ap
|
||||
: null,
|
||||
}).ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user