@page "/scripts/new" @page "/scripts/{ScriptId}" @* Script CRUD. SourceHash is computed automatically from SourceCode on save so the integrity check in v2's deployment pipeline doesn't require operator action. *@ @attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)] @rendermode RenderMode.InteractiveServer @using Microsoft.AspNetCore.Components.Forms @using Microsoft.EntityFrameworkCore @using System.ComponentModel.DataAnnotations @using System.Security.Cryptography @using System.Text @using ZB.MOM.WW.OtOpcUa.Configuration @using ZB.MOM.WW.OtOpcUa.Configuration.Entities @using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw @using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis @inject IDbContextFactory DbFactory @inject NavigationManager Nav @implements IDisposable @{ var presentation = _generation; var form = _form; var confirmation = _confirmationEpoch; } Script editor · OtOpcUa

@(IsNew ? "New script" : "Edit script")

Cancel
@if (!_loaded) {

Loading script…

} else if (_loadError is not null) { } else if (!IsNew && _existing is null) {
@ScriptId not found.
} else { @* OnSubmit (not OnValidSubmit): the editor text is pulled from Monaco FIRST, then validated — the bound SourceCode is only refreshed at blur, so validating before the pull could judge stale text. *@

Identity

@* ScriptId is system-generated (SC-…) on create, never operator-supplied — shown read-only when editing an existing script, hidden on the New page. *@ @if (!IsNew) {
}

Source

SHA-256 hash is computed automatically on save.
@if (!string.IsNullOrWhiteSpace(_error)) { }
Cancel
@if (!IsNew) { }
@* R04 H1: the delete used to run on the first click. *@ }
@code { [Parameter] public string? ScriptId { get; set; } private bool IsNew => string.IsNullOrEmpty(ScriptId); private readonly string _fieldId = "script-" + Guid.NewGuid().ToString("N"); private FormModel _form = new(); private Script? _existing; private bool _loaded, _busy, _disposed, _hasTarget; private string? _target, _error, _loadError; private long _generation, _confirmationEpoch; private bool _confirmDeleteVisible; private string _deleteMessage = ""; private DeleteIntent? _deleteIntent; private MonacoEditor? _editor; private ScriptProblemReport _markers = ScriptProblemReport.Empty; private sealed record DeleteIntent(string Id, byte[] RowVersion); private bool Current(long generation) => !_disposed && generation == _generation; private void ChangeName(string value, long generation, FormModel form) { if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.Name = value; } private void ChangeSource(string value, long generation, FormModel form) { if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.SourceCode = value; } private void OnMarkersChanged(ScriptProblemReport report, long generation) { if (Current(generation)) _markers = report; } private Task RevealProblemAsync(DiagnosticMarker marker, long generation) => !Current(generation) || _editor is null ? Task.CompletedTask : _editor.RevealLineAsync(marker.StartLineNumber, marker.StartColumn); protected override async Task OnParametersSetAsync() { if (_disposed || (_hasTarget && string.Equals(_target, ScriptId, StringComparison.Ordinal))) return; _hasTarget = true; _target = ScriptId; var id = ScriptId; var generation = ++_generation; ++_confirmationEpoch; _loaded = _busy = _confirmDeleteVisible = false; _existing = null; _editor = null; _deleteIntent = null; _form = new(); _markers = ScriptProblemReport.Empty; _error = _loadError = null; try { if (!string.IsNullOrEmpty(id)) { await using var db = await DbFactory.CreateDbContextAsync(); if (!Current(generation)) return; var existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == id); if (!Current(generation)) return; _existing = existing; if (existing is not null) _form = new FormModel { ScriptId = existing.ScriptId, Name = existing.Name, SourceCode = existing.SourceCode, RowVersion = existing.RowVersion.ToArray() }; } } catch (Exception ex) { if (Current(generation)) _loadError = $"The script could not be loaded: {ex.Message}"; } finally { if (Current(generation)) _loaded = true; } } private async Task SubmitAsync(EditContext editContext, long generation, FormModel form) { if (!Current(generation) || _busy || !_loaded || !ReferenceEquals(form, _form) || _confirmDeleteVisible) return; var id = _target; var name = form.Name; var version = form.RowVersion.ToArray(); var editor = _editor; _busy = true; _error = null; try { // Monaco is authoritative at Save. Capture the editor/context before awaiting its current text. var source = form.SourceCode; if (editor is not null) { var read = await editor.GetValueAsync(); if (!Current(generation)) return; if (!read.Ok) { _error = $"Not saved: {read.Error}"; return; } source = read.Value!; } if (!Current(generation)) return; form.SourceCode = source; if (!editContext.Validate()) return; var sourceHash = HashSource(source); await using var db = await DbFactory.CreateDbContextAsync(); if (!Current(generation)) return; if (string.IsNullOrEmpty(id)) { // Preserve system-generated SC- identity and the CSharp language contract. db.Scripts.Add(new Script { ScriptId = $"SC-{Guid.NewGuid().ToString("N")[..12]}", Name = name, Language = "CSharp", SourceCode = source, SourceHash = sourceHash }); } else { var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == id); if (!Current(generation)) return; if (entity is null) { _error = "Row no longer exists."; return; } db.Entry(entity).Property(e => e.RowVersion).OriginalValue = version; entity.Name = name; entity.SourceCode = source; entity.SourceHash = sourceHash; } await db.SaveChangesAsync(); // Already-dispatched writes finish independently of route lifetime. if (Current(generation)) Nav.NavigateTo("/scripts"); } catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were editing."; } catch (Exception ex) { if (Current(generation)) _error = ex.Message; } finally { if (Current(generation)) _busy = false; } } private void OpenDelete(long generation, FormModel form) { if (!Current(generation) || _busy || _confirmDeleteVisible || string.IsNullOrEmpty(_target) || !ReferenceEquals(form, _form)) return; _deleteIntent = new(_target, form.RowVersion.ToArray()); _deleteMessage = $"Delete the script '{_existing?.Name ?? form.Name}'? This cannot be undone."; ++_confirmationEpoch; _confirmDeleteVisible = true; } private void ChangeDeleteVisibility(bool visible, long generation, long confirmation) { if (!Current(generation) || confirmation != _confirmationEpoch || _busy || visible) return; _confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch; } private async Task DeleteAsync(long generation, long confirmation) { if (!Current(generation) || _busy || !_confirmDeleteVisible || confirmation != _confirmationEpoch || _deleteIntent is not { } intent) return; _busy = true; _error = null; try { await using var db = await DbFactory.CreateDbContextAsync(); if (!Current(generation)) return; var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id); if (!Current(generation)) return; if (entity is null) { Nav.NavigateTo("/scripts"); return; } // lmxopcua#978 (review C-2): no FK protects a script in use, so refuse here and name the users — // a deleted predicate used to drop its scripted alarm silently on the next green deploy. var inUse = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.DescribeBlockingUsageAsync(db, intent.Id); if (!Current(generation)) return; if (inUse is not null) { // Close the confirmation so the page-level alert naming the users is what the operator sees. _confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch; _error = $"Not deleted. {inUse}"; return; } db.Entry(entity).Property(e => e.RowVersion).OriginalValue = intent.RowVersion; db.Scripts.Remove(entity); await db.SaveChangesAsync(); if (Current(generation)) Nav.NavigateTo("/scripts"); } catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; } catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}."; } finally { if (Current(generation)) _busy = false; } } public void Dispose() { if (_disposed) return; _disposed = true; ++_generation; ++_confirmationEpoch; } private static string HashSource(string source) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source))); private sealed class FormModel { // ScriptId is system-generated, display-only (not user-entered) — no validation. public string ScriptId { get; set; } = ""; [Required] public string Name { get; set; } = ""; [Required] public string SourceCode { get; set; } = ""; public byte[] RowVersion { get; set; } = []; } }