using System.Text.Json;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
namespace Khaemhat.Application.Audit;
/// A changed field in the history of a record.
/// The field name.
/// The old value as text; when empty.
/// The new value as text; when empty.
public sealed record AuditChange(string Field, string? Before, string? After);
/// A row of the history of a record (the Storico tab, KhAuditList).
/// The row.
/// When (UTC).
/// What happened.
/// Who did it.
/// The changed fields.
public sealed record AuditItem(long Id, DateTime At, AuditAction Action, string? UserName, IReadOnlyList Changes);
/// Reads the history written by for the interface (SPEC ยง7.4).
/// The units of work.
/// The permissions.
public sealed class AuditTrailService(IUnitOfWorkFactory factory, PermissionService permissions)
{
/// The most rows shown.
public const int MaxItems = 200;
/// The history of a record, newest first.
/// Who asks.
/// The company.
/// The entity, as written by the audit trail (the type name, such as Attachment).
/// The record.
/// The permission that lets the actor read the record.
/// Cancellation.
/// At most rows.
public async Task> HistoryAsync(
Actor actor, string companyCode, string entity, string entityId, string readPermission, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = CompanyCodes.Normalize(companyCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await permissions.DemandAsync(actor, readPermission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = await AuditTrail.HistoryAsync(unitOfWork, entity, entityId, cancellationToken).ConfigureAwait(false);
return [.. rows.Take(MaxItems).Select(Item)];
}
/// A row of the history, with the changes read from their JSON.
/// The row.
/// The item.
public static AuditItem Item(AuditEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var action = Enum.TryParse(entry.Action, out var parsed) ? parsed : AuditAction.Update;
return new AuditItem(entry.Id, entry.At, action, entry.UserName, Changes(entry.Diff));
}
private static List Changes(string? diff)
{
var changes = new List();
if (string.IsNullOrWhiteSpace(diff))
{
return changes;
}
try
{
using var document = JsonDocument.Parse(diff);
if (document.RootElement.ValueKind != JsonValueKind.Object)
{
return changes;
}
foreach (var field in document.RootElement.EnumerateObject())
{
var values = field.Value.ValueKind == JsonValueKind.Array ? field.Value.EnumerateArray().ToList() : [];
changes.Add(new AuditChange(field.Name, Text(values.ElementAtOrDefault(0)), Text(values.ElementAtOrDefault(1))));
}
}
catch (JsonException)
{
// A row written by hand or damaged: show the action without the fields.
}
return changes;
}
private static string? Text(JsonElement value) => value.ValueKind switch
{
JsonValueKind.Undefined or JsonValueKind.Null => null,
JsonValueKind.String => value.GetString() is { Length: > 0 } text ? text : null,
JsonValueKind.True => "true",
JsonValueKind.False => "false",
JsonValueKind.Number => value.GetRawText(),
_ => value.GetRawText(),
};
}