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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 19:59:37 +01:00
1 parent f415dc37a8
commit 8198e0a754
20 files changed
+1786 -24

No files matched your search

@@ -0,0 +1,103 @@
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(),
};
}
@@ -0,0 +1,355 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using System.Xml;
namespace Khaemhat.Application.Files;
/// <summary>What the preview of a text or table file shows (mockup 024: XML, CSV, XLSX).</summary>
/// <param name="Kind">The kind of preview.</param>
/// <param name="Text">The text (XML, plain text), possibly cut.</param>
/// <param name="Rows">The cells (CSV, XLSX), possibly cut.</param>
/// <param name="Truncated">Whether the file goes on after what is shown.</param>
public sealed record FilePreview(AttachmentPreview Kind, string? Text, IReadOnlyList<IReadOnlyList<string>>? Rows, bool Truncated)
{
/// <summary>The most characters of text shown.</summary>
public const int MaxChars = 200_000;
/// <summary>The most rows of a table shown.</summary>
public const int MaxRows = 200;
/// <summary>The most columns of a table shown.</summary>
public const int MaxColumns = 40;
/// <summary>Reads the preview of a file; PDF and images are shown by the browser and give no text.</summary>
/// <param name="kind">The kind, from the media type.</param>
/// <param name="content">The content, readable.</param>
/// <param name="culture">The culture for numbers of spreadsheets.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The preview; with neither text nor rows when the file cannot be read.</returns>
public static async Task<FilePreview> ReadAsync(AttachmentPreview kind, Stream content, CultureInfo culture, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentNullException.ThrowIfNull(culture);
try
{
return kind switch
{
AttachmentPreview.Xml or AttachmentPreview.Text => await TextAsync(kind, content, cancellationToken).ConfigureAwait(false),
AttachmentPreview.Csv => await CsvAsync(content, cancellationToken).ConfigureAwait(false),
AttachmentPreview.Xlsx => await XlsxAsync(content, culture, cancellationToken).ConfigureAwait(false),
_ => new FilePreview(kind, null, null, false),
};
}
catch (Exception ex) when (ex is InvalidDataException or XmlException or IOException)
{
return new FilePreview(kind, null, null, false);
}
}
private static async Task<(string Text, bool Truncated)> ReadTextAsync(Stream content, CancellationToken cancellationToken)
{
using var reader = new StreamReader(content, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true);
var buffer = new char[MaxChars + 1];
var read = 0;
while (read < buffer.Length)
{
var n = await reader.ReadAsync(buffer.AsMemory(read), cancellationToken).ConfigureAwait(false);
if (n == 0)
{
break;
}
read += n;
}
return read > MaxChars ? (new string(buffer, 0, MaxChars), true) : (new string(buffer, 0, read), false);
}
private static async Task<FilePreview> TextAsync(AttachmentPreview kind, Stream content, CancellationToken cancellationToken)
{
var (text, truncated) = await ReadTextAsync(content, cancellationToken).ConfigureAwait(false);
return new FilePreview(kind, text, null, truncated);
}
private static async Task<FilePreview> CsvAsync(Stream content, CancellationToken cancellationToken)
{
var (text, truncated) = await ReadTextAsync(content, cancellationToken).ConfigureAwait(false);
var rows = Csv(text, out var more);
return new FilePreview(AttachmentPreview.Csv, null, rows, truncated || more);
}
/// <summary>Splits CSV text into cells: separator <c>;</c> or <c>,</c> (the more frequent in the first line), quotes as RFC 4180.</summary>
/// <param name="text">The text.</param>
/// <param name="truncated">Whether there were more rows than <see cref="MaxRows"/>.</param>
/// <returns>The rows.</returns>
public static List<IReadOnlyList<string>> Csv(string text, out bool truncated)
{
ArgumentNullException.ThrowIfNull(text);
var firstLine = text.AsSpan(0, Math.Max(0, text.IndexOf('\n') is var nl and >= 0 ? nl : text.Length));
var separator = firstLine.Count(';') >= firstLine.Count(',') ? ';' : ',';
var rows = new List<IReadOnlyList<string>>();
var row = new List<string>();
var cell = new StringBuilder();
var quoted = false;
truncated = false;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (quoted)
{
if (c == '"' && i + 1 < text.Length && text[i + 1] == '"')
{
cell.Append('"');
i++;
}
else if (c == '"')
{
quoted = false;
}
else
{
cell.Append(c);
}
}
else if (c == '"' && cell.Length == 0)
{
quoted = true;
}
else if (c == separator)
{
AddCell();
}
else if (c == '\n')
{
if (!EndRow())
{
truncated = true;
return rows;
}
}
else if (c != '\r' && c != '')
{
cell.Append(c);
}
}
if (cell.Length > 0 || row.Count > 0)
{
EndRow();
}
return rows;
void AddCell()
{
if (row.Count < MaxColumns)
{
row.Add(cell.ToString());
}
cell.Clear();
}
bool EndRow()
{
AddCell();
if (rows.Count == MaxRows)
{
return false;
}
rows.Add([.. row]);
row.Clear();
return true;
}
}
private static async Task<FilePreview> XlsxAsync(Stream content, CultureInfo culture, CancellationToken cancellationToken)
{
// ZipArchive needs a seekable stream; attachments are files, generated content is copied first.
var source = content;
MemoryStream? copy = null;
if (!content.CanSeek)
{
copy = new MemoryStream();
await content.CopyToAsync(copy, cancellationToken).ConfigureAwait(false);
copy.Position = 0;
source = copy;
}
try
{
using var zip = new ZipArchive(source, ZipArchiveMode.Read, leaveOpen: true);
var shared = zip.GetEntry("xl/sharedStrings.xml") is { } strings ? SharedStrings(strings) : [];
var sheet = zip.GetEntry("xl/worksheets/sheet1.xml")
?? zip.Entries.Where(e => e.FullName.StartsWith("xl/worksheets/", StringComparison.Ordinal) && e.FullName.EndsWith(".xml", StringComparison.Ordinal))
.OrderBy(e => e.FullName, StringComparer.Ordinal).FirstOrDefault();
if (sheet is null)
{
return new FilePreview(AttachmentPreview.Xlsx, null, null, false);
}
var rows = Sheet(sheet, shared, culture, out var truncated);
return new FilePreview(AttachmentPreview.Xlsx, null, rows, truncated);
}
finally
{
if (copy is not null)
{
await copy.DisposeAsync().ConfigureAwait(false);
}
}
}
private static XmlReader Reader(ZipArchiveEntry entry) =>
XmlReader.Create(entry.Open(), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, IgnoreWhitespace = false, CloseInput = true });
private static List<string> SharedStrings(ZipArchiveEntry entry)
{
var strings = new List<string>();
using var reader = Reader(entry);
StringBuilder? current = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "si")
{
current = new StringBuilder();
if (reader.IsEmptyElement)
{
strings.Add(string.Empty);
current = null;
}
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t" && current is not null)
{
current.Append(reader.ReadElementContentAsString());
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "si" && current is not null)
{
strings.Add(current.ToString());
current = null;
}
}
return strings;
}
private static List<IReadOnlyList<string>> Sheet(ZipArchiveEntry entry, List<string> shared, CultureInfo culture, out bool truncated)
{
var rows = new List<IReadOnlyList<string>>();
truncated = false;
using var reader = Reader(entry);
List<string>? row = null;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "row")
{
if (rows.Count == MaxRows)
{
truncated = true;
break;
}
// Empty rows in between keep their place.
if (int.TryParse(reader.GetAttribute("r"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var number))
{
while (rows.Count < Math.Min(number - 1, MaxRows))
{
rows.Add([]);
}
}
row = [];
if (reader.IsEmptyElement)
{
rows.Add(row);
row = null;
}
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "c" && row is not null)
{
var column = Column(reader.GetAttribute("r")) ?? row.Count;
var type = reader.GetAttribute("t");
var value = reader.IsEmptyElement ? string.Empty : Cell(reader, type, shared, culture);
if (column < MaxColumns)
{
while (row.Count < column)
{
row.Add(string.Empty);
}
row.Add(value);
}
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "row" && row is not null)
{
rows.Add(row);
row = null;
}
}
return rows;
}
// Reads the content of a <c> element, leaving the reader on its end.
private static string Cell(XmlReader reader, string? type, List<string> shared, CultureInfo culture)
{
var depth = reader.Depth;
var text = new StringBuilder();
string? value = null;
while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth))
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "v")
{
value = reader.ReadElementContentAsString();
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
else if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "t")
{
text.Append(reader.ReadElementContentAsString());
if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth)
{
break;
}
}
}
return type switch
{
"s" => int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var index) && index >= 0 && index < shared.Count ? shared[index] : string.Empty,
"inlineStr" => text.ToString(),
"b" or "str" or "e" => value ?? string.Empty,
_ => decimal.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? number.ToString("G", culture) : value ?? string.Empty,
};
}
// "BC12" -> 54 (zero-based column).
private static int? Column(string? reference)
{
if (string.IsNullOrEmpty(reference))
{
return null;
}
var column = 0;
var letters = 0;
foreach (var c in reference)
{
if (c is >= 'A' and <= 'Z')
{
column = (column * 26) + (c - 'A' + 1);
letters++;
}
else
{
break;
}
}
return letters is 0 or > 3 ? null : column - 1;
}
}