using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text.Json; using Khaemhat.Core.Entities; using Khaemhat.Core.Instance; using Khaemhat.Data; using Khaemhat.Data.Querying; namespace Khaemhat.Application.Audit; /// What happened to a record. public enum AuditAction { /// Created. Insert = 0, /// Changed. Update = 1, /// Deleted. Delete = 2, } /// /// The history of the records of a company (SPEC ยง7.4): every insert, update and delete of master data, documents, /// entries and settings writes a row in the company's audit_log, in the same unit of work as the change, with the /// changed fields as JSON {"Field": [old, new]}. Audit columns and secrets are never written. /// public sealed class AuditTrail(TimeProvider clock) { private static readonly HashSet Skipped = new(StringComparer.Ordinal) { nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion", "PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString", "ProtectedPassword", "ProtectedCertificate", "ProtectedCertificatePassword", "ProtectedApiKey", "Content", "Metadata", }; /// Writes the history row of a change, inside the caller's unit of work. /// The entity type. /// The company unit of work holding the change. /// What happened. /// The record. /// The record before (updates and deletes). /// The record after (inserts and updates). /// Who did it. /// Cancellation. /// when a row was written (an update that changes nothing writes none). public async Task RecordAsync( IUnitOfWork unitOfWork, AuditAction action, object entityId, T? before, T? after, string? userName, CancellationToken cancellationToken = default) where T : class { ArgumentNullException.ThrowIfNull(unitOfWork); ArgumentNullException.ThrowIfNull(entityId); var diff = Diff(before, after); if (action == AuditAction.Update && diff.Count == 0) { return false; } await unitOfWork.Repository().InsertAsync( new AuditEntry { At = clock.GetUtcNow().UtcDateTime, Entity = typeof(T).Name, EntityId = Convert.ToString(entityId, CultureInfo.InvariantCulture) ?? string.Empty, Action = action.ToString(), UserName = userName, Diff = JsonSerializer.Serialize(diff), TraceId = Activity.Current?.TraceId.ToString(), }, cancellationToken).ConfigureAwait(false); return true; } /// The history of a record, newest first (the "Storico" panel). /// A company unit of work. /// The entity name. /// The record. /// Cancellation. /// The rows. public static async Task> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(unitOfWork); return (await unitOfWork.Repository().ListAsync( Query.For().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items; } /// The changed fields between two versions of a record. /// The entity type. /// The old version, or . /// The new version, or . /// Field name to [old, new]. public static IReadOnlyDictionary Diff(T? before, T? after) where T : class { var result = new SortedDictionary(StringComparer.Ordinal); foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (!property.CanRead || property.GetIndexParameters().Length > 0 || Skipped.Contains(property.Name)) { continue; } var old = before is null ? null : Simple(property.GetValue(before)); var current = after is null ? null : Simple(property.GetValue(after)); if (!Equals(old, current)) { result[property.Name] = [old, current]; } } return result; } private static object? Simple(object? value) => value switch { null => null, string or bool or int or long or decimal or double => value, DateTime date => date.ToString("O", CultureInfo.InvariantCulture), Enum e => e.ToString(), IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString(), }; }