diff --git a/docs/Uns.md b/docs/Uns.md index 5cf060ffc..f64525e32 100644 --- a/docs/Uns.md +++ b/docs/Uns.md @@ -123,6 +123,15 @@ unreachable, and the service also enforces `tag.cluster == equipment.cluster` on commit. Tick individual tag leaves, or use a device / tag-group's *"Select all tags below"* menu to pull many at once. +**Data-connection root pickers (#1077).** On a cluster's data-connections page the *Local export root* and +*Remote root entity* fields open a tree dialog (`DataRootPickerModal`) instead of a flat list. Raw realm reuses +`RawTree` in `NodePickMode` (single-select radio on any entity node — Cluster, Folder, Driver, Device, TagGroup, +Tag; the multi-select `PickerMode` used by "+ Add reference" is unchanged); UNS realm uses `UnsRootPicker` +(Cluster, Area, Line, Equipment, plus virtual-tag / tag-reference leaves for export roots). The trees are built from +the draft snapshot for ONE cluster (this cluster for exports; the connection's target cluster for remote roots), so +cross-cluster nodes are unreachable. The stored `RootKind` + `RootEntityId` strings and the save-time validation are +unchanged; the manual remote-root-ID input remains for separately managed clusters. + **Effective-name uniqueness:** within an equipment the effective name must be unique across references, VirtualTags, and ScriptedAlarms (they share the equipment's UNS NodeId space, `{EquipmentId}/{EffectiveName}`). This is enforced diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index 442a9cfb3..533d09913 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -2,6 +2,8 @@ @attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)] @rendermode RenderMode.InteractiveServer @using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections +@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns +@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.DataConnections @using ZB.MOM.WW.OtOpcUa.Configuration.Entities @using ZB.MOM.WW.OtOpcUa.Configuration.Validation @using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections @@ -114,7 +116,7 @@ else - +
@Operations(e.AllowedOperations, v => e.AllowedOperations = v) @@ -133,7 +135,7 @@ else -
The picker uses the configured target cluster. For a separately managed cluster, enter its root ID below.
+
The picker browses the configured target cluster. For a separately managed cluster, enter its root ID below.
Consumer nodes@foreach (var n in Nodes) { }
@@ -146,6 +148,10 @@ else
@Actions(m, m.RemoteNamespaceMappingRowId != Guid.Empty) } + } @@ -183,7 +189,7 @@ else private static string Time(DateTime? value) => value?.ToString("u") ?? "unavailable"; private static bool Same(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); private static T Clone(T value) => System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.Serialize(value))!; - private void Clear() { _connection = null; _export = null; _mapping = null; _deleteCandidate = null; _error = null; _message = null; } + private void Clear() { _picker = RootPicker.None; _connection = null; _export = null; _mapping = null; _deleteCandidate = null; _error = null; _message = null; } private void NewConnection() { Clear(); _connection = new(); _connection.Value.ClusterId = ClusterId; _connection.Value.SecretScopeClusterId = ClusterId; } private void NewExport() { Clear(); _export = new() { ClusterId = ClusterId, Realm = DataRealm.Raw, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe }; } private void NewMapping() { Clear(); _mapping = new(); _mapping.Value.ClusterId = ClusterId; SetRealm(_mapping.Value); } @@ -194,7 +200,6 @@ else private static void TargetChanged(DataConnection c) { if (c.TargetMode == DataTargetMode.Cluster) c.ExpectedNodeId = null; else c.EligibleTargetNodeIds.Clear(); } private static void SetRealm(RemoteNamespaceMapping m) { m.RemoteRealm = m.Realm; m.RemoteNamespaceUri = m.Realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri; } private static void SetParent(RemoteNamespaceMapping m, string? value) { var p = (value ?? "").Split('|', 2); m.LocalParentKind = p[0]; m.LocalParentId = p.Length > 1 ? p[1] : ""; } - private static void SetExportRoot(DataExport e, string? value) { var p = (value ?? "").Split('|', 2); e.RootKind = p[0]; e.RootEntityId = p.Length > 1 ? p[1] : ""; } private IEnumerable<(string Value, string Label)> Parents(DataRealm realm) { yield return ($"Cluster|{ClusterId}", "Cluster root"); @@ -219,51 +224,30 @@ else foreach (var x in _snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId))) yield return ($"Equipment|{x.EquipmentId}", $"Equipment: {x.Name} ({x.EquipmentId})"); } } - private IEnumerable<(string Value, string Label)> ExportRoots(DataRealm realm) + private enum RootPicker { None, Export, Remote } + private RootPicker _picker; + private string? RemoteTargetCluster(RemoteNamespaceMapping m) => Connections.FirstOrDefault(x => Same(x.DataConnectionId, m.DataConnectionId))?.ExpectedClusterId; + private DataRealm PickerRealm => _picker == RootPicker.Export ? _export?.Realm ?? DataRealm.Raw : _mapping?.Value.Realm ?? DataRealm.Raw; + private string? PickerCluster => _picker == RootPicker.Export ? ClusterId : _mapping is { } m ? RemoteTargetCluster(m.Value) : null; + // The trees are built once per open, from the snapshot, for the one cluster in scope. + private RawNode? PickerRaw; + private UnsPickNode? PickerUns; + private void OpenPicker(RootPicker which) { - foreach (var parent in Parents(realm)) yield return parent; - if (realm == DataRealm.Raw) - { - var drivers = _snapshot!.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase); - var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId))) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})"); - } - else if (realm == DataRealm.Uns) - { - var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase); - var lines = _snapshot.UnsLines.Where(x => areas.Contains(x.UnsAreaId)).Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase); - var equipment = _snapshot.Equipment.Where(x => lines.Contains(x.UnsLineId)).Select(x => x.EquipmentId).ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})"); - foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}"); - } + _picker = which; + PickerRaw = null; PickerUns = null; + var cluster = PickerCluster; + if (string.IsNullOrEmpty(cluster)) return; + if (PickerRealm == DataRealm.Raw) PickerRaw = DataRootTrees.BuildRaw(_snapshot!, cluster); + else PickerUns = DataRootTrees.BuildUns(_snapshot!, cluster, equipmentLeaves: which == RootPicker.Export); } - private IEnumerable<(string Id, string Label)> RemoteRoots(RemoteNamespaceMapping mapping) + private string? PickerKind => _picker == RootPicker.Export ? _export?.RootKind : null; + private string? PickerId => _picker == RootPicker.Export ? _export?.RootEntityId : _mapping?.Value.RemoteRootEntityId; + private void PickRoot((string Kind, string Id) picked) { - var target = Connections.FirstOrDefault(x => Same(x.DataConnectionId, mapping.DataConnectionId))?.ExpectedClusterId; - if (string.IsNullOrEmpty(target)) yield break; - yield return (target, "Cluster root: " + target); - if (mapping.Realm == DataRealm.Raw) - { - foreach (var x in _snapshot!.RawFolders.Where(x => Same(x.ClusterId, target))) yield return (x.RawFolderId, $"Folder: {x.Name} ({x.RawFolderId})"); - var drivers = _snapshot.DriverInstances.Where(x => Same(x.ClusterId, target)).ToList(); - foreach (var x in drivers) yield return (x.DriverInstanceId, $"Driver: {x.Name} ({x.DriverInstanceId})"); - var driverIds = drivers.Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase); - var devices = _snapshot.Devices.Where(x => driverIds.Contains(x.DriverInstanceId)).ToList(); - foreach (var x in devices) yield return (x.DeviceId, $"Device: {x.Name} ({x.DeviceId})"); - var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var x in _snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagGroupId, $"Tag group: {x.Name} ({x.TagGroupId})"); - foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})"); - } - else - { - var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, target)).ToList(); - foreach (var x in areas) yield return (x.UnsAreaId, $"Area: {x.Name} ({x.UnsAreaId})"); - var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase); - var lines = _snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToList(); - foreach (var x in lines) yield return (x.UnsLineId, $"Line: {x.Name} ({x.UnsLineId})"); - var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase); - foreach (var x in _snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId))) yield return (x.EquipmentId, $"Equipment: {x.Name} ({x.EquipmentId})"); - } + if (_picker == RootPicker.Export && _export is not null) { _export.RootKind = picked.Kind; _export.RootEntityId = picked.Id; } + else if (_picker == RootPicker.Remote && _mapping is not null) _mapping.Value.RemoteRootEntityId = picked.Id; + _picker = RootPicker.None; } private RenderFragment Operations(DataOperations current, Action set) => builder => { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DataConnections/DataRootPickerModal.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DataConnections/DataRootPickerModal.razor new file mode 100644 index 000000000..b64cc4f04 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DataConnections/DataRootPickerModal.razor @@ -0,0 +1,100 @@ +@* #1077 - tree picker for the cluster data-connections root fields. Raw realm reuses RawTree (node-pick mode, + single select of any node kind); Uns realm uses UnsRootPicker. The host supplies cluster-scoped trees, so + cluster scoping is structural. The host keeps its existing validation: this only chooses a kind + id. *@ +@using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections +@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw +@using ZB.MOM.WW.OtOpcUa.AdminUI.Uns +@using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections + + + +

@Hint

+
+ @if (Realm == DataRealm.Raw && RawRoot is not null) + { + + } + else if (Realm == DataRealm.Uns && UnsRoot is not null) + { + + } + else + { +

Nothing to pick: no cluster is selected.

+ } +
+
Selected: @(_kind is null ? "none" : $"{_kind} {_id}")
+
+
+
+ + +
+
+
+ +@code { + /// Whether the dialog is shown. + [Parameter] public bool Visible { get; set; } + /// The dialog title. + [Parameter] public string Title { get; set; } = "Choose a root"; + /// Help text. + [Parameter] public string? Hint { get; set; } + /// Which realm's tree is shown. + [Parameter] public DataRealm Realm { get; set; } + /// The cluster-scoped Raw tree. + [Parameter] public RawNode? RawRoot { get; set; } + /// The cluster-scoped UNS tree. + [Parameter] public UnsPickNode? UnsRoot { get; set; } + /// The currently stored kind (pre-selects the node). + [Parameter] public string? CurrentKind { get; set; } + /// The currently stored entity id. + [Parameter] public string? CurrentId { get; set; } + /// Raised with (kind, entity id) when the user confirms. + [Parameter] public EventCallback<(string Kind, string Id)> OnPicked { get; set; } + /// Raised when the user cancels or closes. + [Parameter] public EventCallback OnCancel { get; set; } + + private IReadOnlyList _rawRoots = Array.Empty(); + private RawNode? _lastRaw; + private bool _lastVisible; + private string? _kind, _id, _key; + + protected override void OnParametersSet() + { + if (!ReferenceEquals(_lastRaw, RawRoot)) { _lastRaw = RawRoot; _rawRoots = RawRoot is null ? [] : [RawRoot]; } + if (Visible && !_lastVisible) + { + // Fresh presentation: start from what the field currently holds. + _kind = string.IsNullOrEmpty(CurrentKind) || string.IsNullOrEmpty(CurrentId) ? null : CurrentKind; + _id = _kind is null ? null : CurrentId; + _key = Realm == DataRealm.Raw ? RawKey(_kind, _id) : (_kind is null ? null : _kind + "|" + _id); + } + _lastVisible = Visible; + } + + private string? RawKey(string? kind, string? id) + { + if (kind is null || id is null || RawRoot is null) return null; + var stack = new Stack(); stack.Push(RawRoot); + while (stack.Count > 0) + { + var n = stack.Pop(); + if (n.EntityId == id && DataRootTrees.RootKind(n.Kind) == kind) return n.Key; + foreach (var c in n.Children) stack.Push(c); + } + return null; + } + + private void PickRaw(RawNode node) + { + var kind = DataRootTrees.RootKind(node.Kind); + if (kind is null || node.EntityId is null) return; + _kind = kind; _id = node.EntityId; _key = node.Key; + } + + private void PickUns(UnsPickNode node) { _kind = node.Kind; _id = node.EntityId; _key = node.Key; } + + private Task Confirm() => _kind is null || _id is null ? Task.CompletedTask : OnPicked.InvokeAsync((_kind, _id)); + private Task Cancel() => OnCancel.InvokeAsync(); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DataConnections/UnsRootPicker.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DataConnections/UnsRootPicker.razor new file mode 100644 index 000000000..a1ba6e4e2 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/DataConnections/UnsRootPicker.razor @@ -0,0 +1,46 @@ +@* #1077 - single-select UNS tree (Cluster, Area, Line, Equipment) for the data-connection root pickers. + Read-only, in-memory: the host passes a cluster-scoped tree, so other clusters are unreachable. *@ +@using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections + +
+ @RenderNode(Root, 0) +
+ +@code { + /// The cluster-scoped tree root. + [Parameter, EditorRequired] public UnsPickNode Root { get; set; } = default!; + + /// The currently picked. + [Parameter] public string? SelectedKey { get; set; } + + /// Raised when the user picks a node. + [Parameter] public EventCallback OnPicked { get; set; } + + private readonly string _scope = "uns-pick-" + Guid.NewGuid().ToString("N"); + private readonly HashSet _collapsed = new(StringComparer.Ordinal); + + private void Toggle(UnsPickNode node) { if (!_collapsed.Add(node.Key)) _collapsed.Remove(node.Key); } + + private RenderFragment RenderNode(UnsPickNode node, int depth) => __builder => + { + var open = !_collapsed.Contains(node.Key); + var labelId = _scope + "-" + Convert.ToHexString(System.Text.Encoding.UTF8.GetBytes(node.Key)); +
+ @if (node.Children.Count > 0) + { + + } + else { } + + @node.Label + @if (node.Children.Count > 0) { @node.Children.Count } +
+ @if (open) + { + @foreach (var child in node.Children) { @RenderNode(child, depth + 1) } + } + }; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Raw/RawTree.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Raw/RawTree.razor index c022f9a77..00baac460 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Raw/RawTree.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Raw/RawTree.razor @@ -185,6 +185,21 @@ /// affordance (picker mode). The host wires this to IUnsTreeService.LoadDescendantTagIdsAsync. [Parameter] public Func>>? ResolveDescendantTagIds { get; set; } + // --------------------------------------------------------------------------- + // #1077 — single-select NODE picker (opt-in; default off). Every node that has an entity id (Cluster, + // Folder, Driver, Device, TagGroup, Tag) renders a radio; mutation menus are suppressed. Independent of + // PickerMode (the multi-select raw-tag picker), whose behaviour is unchanged. + // --------------------------------------------------------------------------- + + /// When true, render a single-select radio on every entity node (any kind) and suppress menus. + [Parameter] public bool NodePickMode { get; set; } + + /// The of the currently picked node (node-pick mode only). + [Parameter] public string? SelectedNodeKey { get; set; } + + /// Raised when the user picks a node (node-pick mode). + [Parameter] public EventCallback OnNodePicked { get; set; } + // --- Configure-driver modal (edit) --- private bool _driverCfgVisible; private string? _driverCfgId; @@ -336,6 +351,14 @@ @onchange="@(e => ToggleTagSelection(node, e.Value is true))" /> } + @if (NodePickMode && node.EntityId is not null && node.Kind != RawNodeKind.Enterprise) + { + + } @node.DisplayName @if (muted) @@ -401,6 +424,7 @@ private IReadOnlyList MenuFor(RawNode node) { + if (NodePickMode) { return Array.Empty(); } // Picker mode: no mutation menus. Device/TagGroup containers get a "select all tags below" // affordance; every other kind (and Tag leaves, which carry the checkbox) has no menu. if (PickerMode) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataRootTrees.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataRootTrees.cs new file mode 100644 index 000000000..dfa6736a5 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/DataConnections/DataRootTrees.cs @@ -0,0 +1,130 @@ +using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; + +/// One node of the UNS root-picker tree (Area, Line, Equipment, or an equipment-level export leaf). +/// The persisted root-kind string (UnsArea, UnsLine, Equipment, VirtualTag, UnsTagReference, or Cluster). +/// The entity id (the cluster id for Cluster). +/// The display label (a DB value; render it, never slice it). +/// Child nodes. +public sealed record UnsPickNode(string Kind, string EntityId, string Label, IReadOnlyList Children) +{ + /// A key unique within the tree. + public string Key => Kind + "|" + EntityId; +} + +/// +/// Builds the cluster-scoped root-picker trees (#1077) from a draft snapshot. Scoping is structural: only the +/// named cluster's entities are reachable from the returned roots. The kind strings are the ones the +/// data-export / mapping editors already persist (RootKind / LocalParentKind). +/// +public static class DataRootTrees +{ + private static bool Same(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase); + + /// The persisted root-kind for a Raw tree node kind, or null for kinds that are not selectable. + /// The tree node kind. + /// The kind string, or null. + public static string? RootKind(RawNodeKind kind) => kind switch + { + RawNodeKind.Cluster => "Cluster", + RawNodeKind.Folder => "RawFolder", + RawNodeKind.Driver => "RawDriver", + RawNodeKind.Device => "RawDevice", + RawNodeKind.TagGroup => "RawTagGroup", + RawNodeKind.Tag => "RawTag", + _ => null, + }; + + /// Builds the Raw tree (Cluster, Folder, Driver, Device, TagGroup, Tag) for one cluster. + /// The draft snapshot. + /// The cluster whose entities are shown. + /// Whether Tag leaves are included (export roots may be a tag; mapping parents may not). + /// A single cluster root with everything eagerly materialised. + public static RawNode BuildRaw(DraftSnapshot snapshot, string clusterId, bool includeTags = true) + { + var root = new RawNode { Kind = RawNodeKind.Cluster, Key = "cluster:" + clusterId, DisplayName = "Cluster root: " + clusterId, ClusterId = clusterId, EntityId = clusterId, Expanded = true }; + RawNode Make(RawNodeKind kind, string prefix, string id, string name) => + new() { Kind = kind, Key = prefix + id, DisplayName = name, ClusterId = clusterId, EntityId = id }; + + var folders = snapshot.RawFolders.Where(x => Same(x.ClusterId, clusterId)).ToList(); + var folderNodes = folders.ToDictionary(x => x.RawFolderId, x => Make(RawNodeKind.Folder, "folder:", x.RawFolderId, x.Name), StringComparer.OrdinalIgnoreCase); + foreach (var f in folders) + { + var self = folderNodes[f.RawFolderId]; + var parent = f.ParentRawFolderId is { } p && folderNodes.TryGetValue(p, out var pn) && pn != self ? pn : root; + parent.Children.Add(self); + } + + var drivers = snapshot.DriverInstances.Where(x => Same(x.ClusterId, clusterId)).ToList(); + var driverNodes = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var d in drivers) + { + var node = Make(RawNodeKind.Driver, "drv:", d.DriverInstanceId, d.Name); + driverNodes[d.DriverInstanceId] = node; + (d.RawFolderId is { } fid && folderNodes.TryGetValue(fid, out var fn) ? fn : root).Children.Add(node); + } + + var deviceNodes = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var d in snapshot.Devices.Where(x => driverNodes.ContainsKey(x.DriverInstanceId))) + { + var node = Make(RawNodeKind.Device, "dev:", d.DeviceId, d.Name); + deviceNodes[d.DeviceId] = node; + driverNodes[d.DriverInstanceId].Children.Add(node); + } + + var groupNodes = new Dictionary(StringComparer.OrdinalIgnoreCase); + var groups = snapshot.TagGroups.Where(x => deviceNodes.ContainsKey(x.DeviceId)).ToList(); + foreach (var g in groups) groupNodes[g.TagGroupId] = Make(RawNodeKind.TagGroup, "grp:", g.TagGroupId, g.Name); + foreach (var g in groups) + { + var self = groupNodes[g.TagGroupId]; + var parent = g.ParentTagGroupId is { } pid && groupNodes.TryGetValue(pid, out var gp) && gp != self ? gp : deviceNodes[g.DeviceId]; + parent.Children.Add(self); + } + + if (includeTags) + { + foreach (var t in snapshot.Tags.Where(x => deviceNodes.ContainsKey(x.DeviceId))) + { + var parent = t.TagGroupId is { } gid && groupNodes.TryGetValue(gid, out var g) ? g : deviceNodes[t.DeviceId]; + parent.Children.Add(Make(RawNodeKind.Tag, "tag:", t.TagId, t.Name)); + } + } + + foreach (var n in folderNodes.Values.Concat(driverNodes.Values).Concat(deviceNodes.Values).Concat(groupNodes.Values).Append(root)) n.ChildCount = n.Children.Count; + return root; + } + + /// Builds the UNS tree (Cluster, Area, Line, Equipment, optional equipment-level leaves) for one cluster. + /// The draft snapshot. + /// The cluster whose entities are shown. + /// Whether equipment-level virtual tags / tag references are shown (export roots only). + /// The cluster root node. + public static UnsPickNode BuildUns(DraftSnapshot snapshot, string clusterId, bool equipmentLeaves) + { + var areaNodes = new List(); + foreach (var area in snapshot.UnsAreas.Where(x => Same(x.ClusterId, clusterId))) + { + var lineNodes = new List(); + foreach (var line in snapshot.UnsLines.Where(x => Same(x.UnsAreaId, area.UnsAreaId))) + { + var equipmentNodes = new List(); + foreach (var e in snapshot.Equipment.Where(x => Same(x.UnsLineId, line.UnsLineId))) + { + var leaves = new List(); + if (equipmentLeaves) + { + leaves.AddRange(snapshot.VirtualTags.Where(x => Same(x.EquipmentId, e.EquipmentId)).Select(x => new UnsPickNode("VirtualTag", x.VirtualTagId, "Virtual tag: " + x.Name, []))); + leaves.AddRange(snapshot.UnsTagReferences.Where(x => Same(x.EquipmentId, e.EquipmentId)).Select(x => new UnsPickNode("UnsTagReference", x.UnsTagReferenceId, "Tag reference: " + x.UnsTagReferenceId, []))); + } + equipmentNodes.Add(new UnsPickNode("Equipment", e.EquipmentId, e.Name, leaves)); + } + lineNodes.Add(new UnsPickNode("UnsLine", line.UnsLineId, line.Name, equipmentNodes)); + } + areaNodes.Add(new UnsPickNode("UnsArea", area.UnsAreaId, area.Name, lineNodes)); + } + return new UnsPickNode("Cluster", clusterId, "Cluster root: " + clusterId, areaNodes); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs new file mode 100644 index 000000000..1d42578e1 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs @@ -0,0 +1,188 @@ +using System.Security.Claims; +using Bunit; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.JSInterop; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters; +using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw; +using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections; +using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns; +using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Security.Auth; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages; + +/// #1077: the export-root / remote-root fields are cluster-scoped tree pickers. +[Trait("Category", "Unit")] +public sealed class DataConnectionRootPickerTests : BunitContext +{ + private const string Cluster = RawTreeTestDb.ClusterId; + + private sealed class NoDiagnostics : IFleetDiagnosticsClient + { + public Task GetDiagnosticsAsync(NodeId nodeId, CancellationToken ct) => throw new NotSupportedException(); + } + + private sealed class PrincipalState : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => Task.FromResult( + new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.Name, "fixture"), new(ClaimTypes.Role, "Administrator")], "fixture")))); + } + + public DataConnectionRootPickerTests() + { + // Node-pick mode never mutates or lazy-loads, so RawTree's mutation dialogs are stubbed and its service refuses any call. + var names = new HashSet { "DriverConfigModal", "DeviceModal", "RawTagModal", "RawManualTagEntryModal", "RawCsvImportModal", "RawCsvExportModal", "RawBrowseModal", "RawNameDialog", "RawConfirmDialog", "RawDriverTypeDialog", "RawStubModal" }; + ComponentFactories.AddStub(type => names.Contains(type.Name)); + Services.AddSingleton(System.Reflection.DispatchProxy.Create()); + JSInterop.Mode = JSRuntimeMode.Loose; + JSInterop.Setup("otDialog.activate", _ => true).SetResult(true); // ModalFrame closes itself when activation is refused. + } + + public class RefusingRawService : System.Reflection.DispatchProxy + { + protected override object? Invoke(System.Reflection.MethodInfo? method, object?[]? args) => throw new NotSupportedException("Node-pick mode must not call " + method?.Name); + } + + private IRenderedComponent>> RenderPage() + { + Services.RemoveAll(); + Services.RemoveAll(); + Services.AddAuthorizationCore(o => o.AddPolicy(AdminUiPolicies.ConfigEditor, p => p.RequireRole("Administrator", "Designer"))); + Services.AddCascadingAuthenticationState(); + Services.AddSingleton(new PrincipalState()); + Services.AddSingleton(new NoDiagnostics()); + var name = RawTreeTestDb.SeedFresh(); + using (var db = RawTreeTestDb.CreateNamed(name)) + { + db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = Cluster, Name = "Packaging" }); + db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "Line one" }); + // Another cluster's entities must be unreachable from this cluster's pickers. + db.ServerClusters.Add(new ServerCluster { ClusterId = "OTHER", Name = "Other", Enterprise = "zb", Site = "x", RedundancyMode = RedundancyMode.None, CreatedBy = "test" }); + db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-OTHER", ClusterId = "OTHER", Name = "Foreign area" }); + db.DataConnections.Add(new DataConnection { DataConnectionId = "CONN-1", ClusterId = Cluster, ExpectedClusterId = "OTHER" }); + db.SaveChanges(); + } + Services.AddSingleton(RawTreeTestDb.Factory(name)); + Services.AddSingleton(); + var state = new PrincipalState().GetAuthenticationStateAsync(); + return Render>>(p => p.Add(x => x.Value, state) + .AddChildContent(c => c.Add(x => x.ClusterId, Cluster))); + } + + [Fact] + public void ExportRoot_RawTreePicker_PicksADeviceAndFillsTheField() + { + var cut = RenderPage(); + cut.WaitForAssertion(() => cut.Find("button.btn-primary:contains('New export')")); + cut.Find("button:contains('New export')").Click(); + cut.WaitForAssertion(() => cut.Find("#export-root")); + cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen"); + cut.Find("#export-root-browse").Click(); + // A dialog opened by a click renders on a later pass. + cut.WaitForAssertion(() => cut.Find("[role=dialog]")); + cut.WaitForAssertion(() => cut.FindAll("input[type=radio]").Count.ShouldBeGreaterThan(0)); + cut.Find("#root-picker-confirm").HasAttribute("disabled").ShouldBeTrue(); + // Expand down to the device: cluster root is open; folder -> driver -> device. + cut.Find("button[aria-label='Expand PLCs']").Click(); + cut.WaitForElement("button[aria-label='Expand modbus-1']").Click(); + cut.WaitForElement("input[title='Device dev:" + RawTreeTestDb.FolderedDeviceId + "']").Change(true); + cut.WaitForAssertion(() => cut.Find("#root-picker-selected").TextContent.ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId)); + cut.Find("#root-picker-confirm").Click(); + cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId)); + cut.FindAll("[role=dialog]").Count.ShouldBe(0); + } + + [Fact] + public void ExportRoot_UnsTreePicker_IsClusterScopedAndPicksAnArea() + { + var cut = RenderPage(); + cut.WaitForElement("button:contains('New export')").Click(); + cut.WaitForElement("#export-realm").Change("Uns"); + cut.Find("#export-root-browse").Click(); + cut.WaitForAssertion(() => cut.Find("[role=dialog]")); + cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0)); + cut.Markup.ShouldContain("Packaging"); + cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Foreign area"); + cut.Find("input[title='UnsArea AREA-1']").Change(true); + cut.Find("#root-picker-confirm").Click(); + cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("UnsArea AREA-1")); + } + + [Fact] + public void RemoteRoot_PickerBrowsesTheTargetClusterOnly_AndFillsTheRootId() + { + var cut = RenderPage(); + cut.WaitForElement("button:contains('New mapping')").Click(); + cut.WaitForElement("#remote-root-browse").HasAttribute("disabled").ShouldBeTrue(); // no connection chosen yet + cut.Find("#mapping-connection").Change("CONN-1"); + cut.Find("#mapping-realm").Change("Uns"); + cut.Find("#remote-root-browse").HasAttribute("disabled").ShouldBeFalse(); + cut.Find("#remote-root-browse").Click(); + cut.WaitForElement("[role=dialog]"); + cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0)); + cut.Find("[role=dialog]").InnerHtml.ShouldContain("Foreign area"); + cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Packaging"); + cut.Find("input[title='UnsArea AREA-OTHER']").Change(true); + cut.Find("#root-picker-confirm").Click(); + cut.WaitForAssertion(() => cut.Find("#remote-root").GetAttribute("value").ShouldBe("AREA-OTHER")); + } + + [Fact] + public void Cancel_LeavesTheFieldUnchanged() + { + var cut = RenderPage(); + cut.WaitForElement("button:contains('New export')").Click(); + cut.WaitForElement("#export-root-browse").Click(); + cut.WaitForAssertion(() => cut.Find("[role=dialog]")); + cut.Find("[role=dialog] .modal-footer button:contains('Cancel')").Click(); + cut.WaitForAssertion(() => cut.FindAll("[role=dialog]").Count.ShouldBe(0)); + cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen"); + } + + [Fact] + public void RawTree_NodePickMode_OffersARadioOnEveryEntityKind_AndLeavesTagPickerModeAlone() + { + var tag = new RawNode { Kind = RawNodeKind.Tag, Key = "tag:t", EntityId = "t", DisplayName = "T" }; + var device = new RawNode { Kind = RawNodeKind.Device, Key = "dev:d", EntityId = "d", DisplayName = "D", Expanded = true }; + device.Children.Add(tag); + RawNode? picked = null; + var cut = Render(p => p.Add(x => x.Roots, new[] { device }).Add(x => x.NodePickMode, true) + .Add(x => x.OnNodePicked, n => picked = n)); + cut.FindAll("input[type=radio]").Count.ShouldBe(2); + cut.Find("input[title='Device dev:d']").Change(true); + picked.ShouldBeSameAs(device); + + // The tag picker mode is unchanged: a checkbox on tags only, no radios. + var multi = Render(p => p.Add(x => x.Roots, new[] { device }).Add(x => x.PickerMode, true).Add(x => x.SelectedTagIds, new HashSet())); + multi.FindAll("input[type=radio]").Count.ShouldBe(0); + multi.FindAll("input[type=checkbox]").Count.ShouldBe(1); + } + + [Fact] + public async Task Trees_AreClusterScoped_AndNestFoldersGroupsAndTags() + { + var name = RawTreeTestDb.SeedFresh(); + using var db = RawTreeTestDb.CreateNamed(name); + var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, CancellationToken.None); + var raw = DataRootTrees.BuildRaw(snapshot, Cluster); + raw.Children.Select(c => c.EntityId).ShouldContain(RawTreeTestDb.RootFolderId); + var group = raw.Children.Single(c => c.EntityId == RawTreeTestDb.RootFolderId).Children.Single().Children.Single().Children.Single(); + group.Kind.ShouldBe(RawNodeKind.TagGroup); + group.Children.Select(c => c.EntityId).ShouldBe([RawTreeTestDb.HistorizedTagId, RawTreeTestDb.PlainTagId], ignoreOrder: true); + DataRootTrees.BuildRaw(snapshot, "NOPE").Children.ShouldBeEmpty(); + DataRootTrees.BuildRaw(snapshot, Cluster, includeTags: false).Children.SelectMany(Flatten).ShouldNotContain(n => n.Kind == RawNodeKind.Tag); + } + + private static IEnumerable Flatten(RawNode n) => new[] { n }.Concat(n.Children.SelectMany(Flatten)); +}