using System.Security.Cryptography; using System.Text; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates; namespace ZB.MOM.WW.ScadaBridge.TemplateEngine; /// /// Compact after-state shapes for the configuration audit log (review 2026-10-21 /// 08/G1). IAuditService.LogAsync serialises whatever it is handed into /// AuditLogEntries.AfterStateJson — an indefinitely-retained table — so /// handing it a tracked wrote the whole loaded graph, /// every attribute, alarm and script body included, on each create / rename / move. /// These shapes keep the identity, the scalar fields, per-collection member counts /// and the fields that changed. Script bodies are never written: a body is /// represented by its length and SHA-256, which still lets an auditor tell whether /// (and to what) a body changed without storing it again on every edit. /// internal static class TemplateAuditShapes { /// Summary of a template: identity, scalars and member counts — no member rows. /// The template. /// Names of the fields this operation changed, if known. /// The audit after-state object. internal static object Template(Template template, IReadOnlyList? changedFields = null) => new { template.Id, template.Name, template.Description, template.ParentTemplateId, template.FolderId, template.IsDerived, template.OwnerCompositionId, AttributeCount = template.Attributes.Count, AlarmCount = template.Alarms.Count, ScriptCount = template.Scripts.Count, CompositionCount = template.Compositions.Count, NativeAlarmSourceCount = template.NativeAlarmSources.Count, ChangedFields = changedFields, }; /// A template script without its body (length + SHA-256 instead). /// The script. /// The audit after-state object. internal static object Script(TemplateScript script) => new { script.Id, script.TemplateId, script.Name, script.IsLocked, script.LockedInDerived, script.IsInherited, script.TriggerType, script.TriggerConfiguration, script.ParameterDefinitions, script.ReturnDefinition, script.MinTimeBetweenRuns, script.ExecutionTimeoutSeconds, CodeLength = script.Code?.Length ?? 0, CodeSha256 = HashCode(script.Code), }; /// A shared script without its body (length + SHA-256 instead). /// The shared script. /// The audit after-state object. internal static object SharedScript(SharedScript script) => new { script.Id, script.Name, script.ParameterDefinitions, script.ReturnDefinition, CodeLength = script.Code?.Length ?? 0, CodeSha256 = HashCode(script.Code), }; private static string? HashCode(string? code) => code == null ? null : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(code))); }