Files
Khaemhat/src/Khaemhat.Application/Audit/AuditTrailService.cs
T
Alby96andClaude Opus 5.5 8198e0a754 feat: attachments panel, file previews, print preview and history (#34)
Documents need to show, upload and generate their files from the interface,
and users need to see who changed a record. This adds the attachment list
(upload, preview, download, lock, trash and restore, older versions, ZIP,
generate/regenerate), in-app previews for PDF, images, XML, text, CSV and
XLSX, an A4 print preview with "save as attachment", and an audit history
list read through a permission-checked AuditTrailService.

Files are served by /files endpoints that require a signed-in user and the
company permissions; only PDF and images open inline, with their own CSP
that allows framing by this site only.

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

104 lines
4.7 KiB
C#

using System.Text.Json;
using Khaemhat.Application.Security;
using Khaemhat.Core.Instance;
using Khaemhat.Data;
namespace Khaemhat.Application.Audit;
/// <summary>A changed field in the history of a record.</summary>
/// <param name="Field">The field name.</param>
/// <param name="Before">The old value as text; <see langword="null"/> when empty.</param>
/// <param name="After">The new value as text; <see langword="null"/> when empty.</param>
public sealed record AuditChange(string Field, string? Before, string? After);
/// <summary>A row of the history of a record (the <i>Storico</i> tab, <c>KhAuditList</c>).</summary>
/// <param name="Id">The row.</param>
/// <param name="At">When (UTC).</param>
/// <param name="Action">What happened.</param>
/// <param name="UserName">Who did it.</param>
/// <param name="Changes">The changed fields.</param>
public sealed record AuditItem(long Id, DateTime At, AuditAction Action, string? UserName, IReadOnlyList<AuditChange> Changes);
/// <summary>Reads the history written by <see cref="AuditTrail"/> for the interface (SPEC §7.4).</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
public sealed class AuditTrailService(IUnitOfWorkFactory factory, PermissionService permissions)
{
/// <summary>The most rows shown.</summary>
public const int MaxItems = 200;
/// <summary>The history of a record, newest first.</summary>
/// <param name="actor">Who asks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity, as written by the audit trail (the type name, such as <c>Attachment</c>).</param>
/// <param name="entityId">The record.</param>
/// <param name="readPermission">The permission that lets the actor read the record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>At most <see cref="MaxItems"/> rows.</returns>
public async Task<IReadOnlyList<AuditItem>> 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)];
}
/// <summary>A row of the history, with the changes read from their JSON.</summary>
/// <param name="entry">The row.</param>
/// <returns>The item.</returns>
public static AuditItem Item(AuditEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var action = Enum.TryParse<AuditAction>(entry.Action, out var parsed) ? parsed : AuditAction.Update;
return new AuditItem(entry.Id, entry.At, action, entry.UserName, Changes(entry.Diff));
}
private static List<AuditChange> Changes(string? diff)
{
var changes = new List<AuditChange>();
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(),
};
}