Files
Khaemhat/src/Khaemhat.Application/Audit/AuditTrail.cs
T
Alby96andClaude Opus 5.5 fb12411404 feat: e-invoice services, SDI channels, inbox, polling and conservation (#74 #75 #76 #77 #79)
Adds the company tables of the electronic invoice and the services that drive them:
the builder turns an issued document into the FatturaPA model, the service generates,
checks and sends the file through the channel chosen by the routing rules (with a
fallback) and applies the SDI notifications to the e-invoice and its document. The
channel settings keep their secrets protected and out of the audit trail; a job reads
the PEC mailbox and the intermediaries every 15 minutes, storing supplier invoices in
the inbox and acknowledging a message only once all its files are kept. The inbox
registers received invoices through the purchase import, and the conservation export
packs a period with a SHA-256 index. A rejected invoice can now be corrected and
generated again; the courtesy PDF embeds the XML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:20:59 +01:00

126 lines
5.5 KiB
C#

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;
/// <summary>What happened to a record.</summary>
public enum AuditAction
{
/// <summary>Created.</summary>
Insert = 0,
/// <summary>Changed.</summary>
Update = 1,
/// <summary>Deleted.</summary>
Delete = 2,
}
/// <summary>
/// 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 <c>audit_log</c>, in the same unit of work as the change, with the
/// changed fields as JSON <c>{"Field": [old, new]}</c>. Audit columns and secrets are never written.
/// </summary>
public sealed class AuditTrail(TimeProvider clock)
{
private static readonly HashSet<string> 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",
};
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="unitOfWork">The company unit of work holding the change.</param>
/// <param name="action">What happened.</param>
/// <param name="entityId">The record.</param>
/// <param name="before">The record before (updates and deletes).</param>
/// <param name="after">The record after (inserts and updates).</param>
/// <param name="userName">Who did it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> when a row was written (an update that changes nothing writes none).</returns>
public async Task<bool> RecordAsync<T>(
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<AuditEntry, long>().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;
}
/// <summary>The history of a record, newest first (the "Storico" panel).</summary>
/// <param name="unitOfWork">A company unit of work.</param>
/// <param name="entity">The entity name.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public static async Task<IReadOnlyList<AuditEntry>> HistoryAsync(IUnitOfWork unitOfWork, string entity, string entityId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
return (await unitOfWork.Repository<AuditEntry, long>().ListAsync(
Query.For<AuditEntry>().Where(a => a.Entity == entity && a.EntityId == entityId).OrderByDescending(a => a.Id), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>The changed fields between two versions of a record.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="before">The old version, or <see langword="null"/>.</param>
/// <param name="after">The new version, or <see langword="null"/>.</param>
/// <returns>Field name to <c>[old, new]</c>.</returns>
public static IReadOnlyDictionary<string, object?[]> Diff<T>(T? before, T? after)
where T : class
{
var result = new SortedDictionary<string, object?[]>(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(),
};
}