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;
}
}
@@ -3,9 +3,12 @@
@inherits DocumentPage<SampleDocument, SampleLine>
@inject IWebHostEnvironment Environment
@inject TimeProvider Clock
@inject ShellSession Session
@inject AttachmentService Attachments
@using Khaemhat.Application.Audit
@* A document page built on DocumentPage (issue #29): toolbar, header, tabs with Righe first, shortcuts. Fake data,
development only. *@
development only; the attachments (issue #34) are real, on the test document of the generators. *@
<KhPageTitle Text="@T["Pages.Catalog.Document"]" Icon="file" />
@if (!Environment.IsDevelopment() || Record is null)
@@ -65,6 +68,14 @@ else
</KhForm>
break;
case TabIds.Attachments:
<div class="kh-tab-body"><KhAttachmentList Entity="@DemoDocument.Entity" EntityId="SampleId" OnCountChanged="SetAttachments" /></div>
break;
case TabIds.History:
<div class="kh-tab-body"><KhAuditList Items="History" FieldName="FieldLabel" /></div>
break;
default:
<div class="pb"><p class="muted">@T["Pages.Catalog.TabPlaceholder"]</p></div>
break;
@@ -72,13 +83,22 @@ else
</ChildContent>
</KhRecordLayout>
<KhDrawer Open="_drawer" Title="@T["Ui.Attachments.Title"]" Icon="paperclip" Wide="true" OnClose="() => _drawer = false">
<KhAttachmentList Entity="@DemoDocument.Entity" EntityId="SampleId" OnCountChanged="SetAttachments" />
</KhDrawer>
<KhRadarDialog TItem="SampleItem" Id="catalog.items" Open="_lookupLine is not null" Title="@T["Pages.Catalog.Grids.ItemRadar"]" Columns="ItemColumns"
Source="CatalogSamples.ItemsAsync" KeyOf="i => i.Code" InitialSearch="@_lookupLine?.Code" OnPick="PickItemAsync" OnClose="() => _lookupLine = null"
OnCreate="CreateItem" />
}
@code {
/// <summary>The test document the attachments belong to.</summary>
public const long SampleId = 1;
private int _saved;
private int _attachments;
private bool _drawer;
private KhLinesGrid<SampleLine>? _lines;
private SampleLine? _lookupLine;
private TaskCompletionSource? _lookupDone;
@@ -155,7 +175,7 @@ else
}
/// <inheritdoc />
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] : StandardTabs(attachments: 2, links: 1);
public override IReadOnlyList<KhTabItem> Tabs => Record is null ? [] : StandardTabs(attachments: _attachments, links: 1);
/// <inheritdoc />
public override bool IsReadOnly => Record?.Issued == true;
@@ -167,7 +187,7 @@ else
protected override string? NewUrl => "sviluppo/documento";
/// <inheritdoc />
protected override int? AttachmentCount => 2;
protected override int? AttachmentCount => _attachments;
/// <inheritdoc />
protected override bool CanMove => true;
@@ -187,6 +207,51 @@ else
Record = CatalogSamples.Document(Today);
}
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
if (Session.Actor is { CompanyCode: { } company } actor && Session.Permissions.Allows(AttachmentService.ReadPermission))
{
_attachments = await Attachments.CountAsync(actor, company, DemoDocument.Entity, SampleId);
}
}
/// <inheritdoc />
protected override Task AttachmentsAsync()
{
// Toolbar commands are plain callbacks: render the page for the panel.
_drawer = !_drawer;
StateHasChanged();
return Task.CompletedTask;
}
/// <inheritdoc />
protected override Task PrintAsync()
{
Navigation.NavigateTo("sviluppo/documento/stampa");
return Task.CompletedTask;
}
private void SetAttachments(int count) => _attachments = count;
// A pretend history: the sample document is not saved anywhere.
private IReadOnlyList<AuditItem> History =>
[
new(3, Clock.GetUtcNow().UtcDateTime.AddMinutes(-12), AuditAction.Update, Session.Actor?.UserName,
[new("Discount", "0", "5"), new("Notes", null, T["Pages.Catalog.Fields.Notes"])]),
new(2, Clock.GetUtcNow().UtcDateTime.AddHours(-3), AuditAction.Update, "anna", [new("Number", "2026/0417", Record?.Number)]),
new(1, Clock.GetUtcNow().UtcDateTime.AddDays(-1), AuditAction.Insert, "anna", []),
];
private string? FieldLabel(string field) => field switch
{
"Discount" => T["Pages.Catalog.Fields.Discount"],
"Notes" => T["Pages.Catalog.Fields.Notes"],
"Number" => T["Pages.Catalog.Fields.Number"],
_ => null,
};
/// <inheritdoc />
protected override IEnumerable<ToolbarItem> ContextActions()
{
@@ -0,0 +1,110 @@
@page "/sviluppo/documento/stampa"
@attribute [Authorize]
@using System.Globalization
@using Khaemhat.Application.Security
@using Khaemhat.Web.Hosting
@inject IWebHostEnvironment Environment
@inject ShellSession Session
@inject FileGenerationService Generation
@inject ToastService Toasts
@inject TimeProvider Clock
@* The print preview of the test document (issue #34, mockup 025): the same lines the PDF generator writes, as an A4
sheet in HTML; Stampa prints the sheet only, the PDF comes from DemoPdfGenerator. Development only. *@
<KhPageTitle Text="@T["Pages.Print.Title"]" Icon="printer" />
@if (!Environment.IsDevelopment())
{
<div class="kh-message"><h1>@T["Pages.Catalog.DevOnly"]</h1></div>
}
else
{
<div class="phead">
<div>
<div class="crumbs">@T["Pages.Print.Crumb"] › <b>@T["Pages.Print.Title"]</b></div>
<h1>@T.Format("Pages.Print.Heading", DemoDocument.Title, Number)</h1>
</div>
</div>
<KhPrintPreview PdfUrl="@PdfUrl(false)" PdfDownloadUrl="@PdfUrl(true)" OnSaveAttachment="SaveAsync" Saving="_saving">
<div class="kh-sheet-head">
<div>
<div class="kh-sheet-company">@(Session.Company?.Name ?? Company)</div>
<div class="kh-sheet-muted">@T.Format("Pages.Print.CompanyLine", Company)</div>
</div>
<div class="kh-sheet-title">
<div class="k">@DemoDocument.Title</div>
<div class="n">@T.Format("Pages.Print.Number", Number, T.Date(Today))</div>
</div>
</div>
<p class="kh-sheet-intro">@T.Format("Pages.Print.Intro", Company, Session.Actor?.UserName ?? string.Empty)</p>
<table class="kh-sheet-table">
<thead>
<tr>
@for (var i = 0; i < DemoDocument.Headers.Count; i++)
{
<th class="@(i >= 2 ? "num" : null)">@DemoDocument.Headers[i]</th>
}
</tr>
</thead>
<tbody>
@foreach (var line in DemoDocument.Lines)
{
<tr>
<td class="mono">@line.Code</td>
<td>@line.Description</td>
<td class="num">@line.Quantity.ToString("#,##0.##", T.Culture)</td>
<td class="num">@DemoDocument.Euro(line.UnitPrice, T.Culture)</td>
<td class="num">@DemoDocument.Euro(DemoDocument.Amount(line), T.Culture)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<td colspan="4" class="num">@T["Pages.Print.Total"]</td>
<td class="num"><b>@DemoDocument.Euro(DemoDocument.Total, T.Culture)</b></td>
</tr>
</tfoot>
</table>
<p class="kh-sheet-foot">@T["Pages.Print.Footer"]</p>
</KhPrintPreview>
}
@code {
private bool _saving;
private static string Number => SampleDocumentPage.SampleId.ToString(CultureInfo.InvariantCulture);
private string Company => Session.Actor?.CompanyCode ?? string.Empty;
private DateOnly Today => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(Clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
/// <inheritdoc />
protected override Task OnInitializedAsync() => Session.EnsureLoadedAsync();
private string? PdfUrl(bool download) =>
Session.Actor?.CompanyCode is null ? null : FileEndpoints.Generated(DemoDocument.Entity, SampleDocumentPage.SampleId, DemoPdfGenerator.GeneratorCode, download);
private async Task SaveAsync()
{
if (Session.Actor is not { CompanyCode: { } company } actor)
{
return;
}
_saving = true;
try
{
var saved = await Generation.GenerateAsync(actor, company, DemoDocument.Entity, SampleDocumentPage.SampleId, DemoPdfGenerator.GeneratorCode);
Toasts.Show(ToastKind.Success, T["Ui.Attachments.GeneratedToast"], saved.FileName);
}
catch (Exception ex) when (ex is AccessDeniedException or ValidationFailedException)
{
Toasts.Show(ToastKind.Error, T["Ui.Print.SaveAttachment"], T["Ui.Attachments.Denied"]);
}
finally
{
_saving = false;
}
}
}
@@ -0,0 +1,361 @@
@using Khaemhat.Application.Security
@using Khaemhat.Core.Files
@using Khaemhat.Web.Hosting
@inject ShellSession Session
@inject AttachmentService Attachments
@inject FileGenerationService Generation
@inject ToastService Toasts
@inject DialogService Dialogs
@inject TimeProvider Clock
@* The attachments of a record (SPEC §9.4, mockup 024): uploaded and generated files, newest first, with type, version,
size, who and when; preview, download, lock and trash; upload; all as ZIP; "Genera file" makes a new version of a
generated file (v1, v2...). An attachment belongs to one record only. *@
<div class="kh-att">
@if (Company is null)
{
<div class="callout warn"><KhIcon Name="alert" /> <span>@T["Ui.Attachments.NoCompany"]</span></div>
}
else
{
<div class="callout info"><KhIcon Name="info" /> <span>@T["Ui.Attachments.Intro"]</span></div>
<div class="kh-att-head">
<span class="kh-att-title">@T.Format("Ui.Attachments.Count", _items.Count)</span>
<span class="grow"></span>
<label class="chk kh-check"><input type="checkbox" checked="@_older" @onchange="ToggleOlderAsync" /> @T["Ui.Attachments.Older"]</label>
</div>
@if (!_loaded)
{
<p class="muted">@T["Common.Loading"]</p>
}
else if (_items.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="paperclip" /> @T["Ui.Attachments.None"]</p>
}
else
{
<ul class="kh-att-list">
@foreach (var item in _items)
{
<li class="kh-att-row @(item.IsLatest ? null : "old")" @key="item.Id">
<span class="kh-att-type @TypeClass(item)" aria-hidden="true">@TypeLabel(item)</span>
<span class="kh-att-main">
<span class="t">
@item.FileName
@if (item.Locked)
{
<span title="@T["Ui.Attachments.Locked"]"><KhIcon Name="lock" Class="sm" /></span>
}
</span>
<span class="m">@Meta(item)</span>
</span>
<span class="kh-att-actions">
@if (item.Preview != AttachmentPreview.None)
{
<button type="button" class="ib" title="@T["Ui.Attachments.Preview"]" aria-label="@T.Format("Ui.Attachments.PreviewOf", item.FileName)"
@onclick="() => _preview = item"><KhIcon Name="eye" /></button>
}
<a class="ib" href="@FileEndpoints.Download(item.Id)" title="@T["Ui.Attachments.Download"]" aria-label="@T.Format("Ui.Attachments.DownloadOf", item.FileName)"
download="@item.FileName"><KhIcon Name="download" /></a>
@if (CanWrite && !item.Locked)
{
<button type="button" class="ib" title="@T["Ui.Attachments.Lock"]" aria-label="@T.Format("Ui.Attachments.LockOf", item.FileName)"
@onclick="() => LockAsync(item)"><KhIcon Name="lock" /></button>
}
@if (CanDelete && !item.Locked)
{
<button type="button" class="ib" title="@T["Ui.Attachments.Delete"]" aria-label="@T.Format("Ui.Attachments.DeleteOf", item.FileName)"
@onclick="() => DeleteAsync(item)"><KhIcon Name="trash" /></button>
}
</span>
</li>
}
</ul>
}
<div class="kh-att-buttons">
@if (CanWrite)
{
<label class="btn primary kh-att-upload @(_busy ? "disabled" : null)">
<KhIcon Name="upload" /> @T["Ui.Attachments.Upload"]
<InputFile OnChange="UploadAsync" multiple disabled="@_busy" />
</label>
}
@if (_items.Count > 0)
{
<a class="btn" href="@FileEndpoints.Zip(Entity, EntityId)" download><KhIcon Name="folder" /> @T["Ui.Attachments.Zip"]</a>
}
</div>
@if (CanWrite && _limits is { } limits)
{
<p class="muted sm">@T.Format("Ui.Attachments.Limit", Size(limits.MaxBytes))</p>
}
@if (Generators.Count > 0)
{
<div class="kh-att-section">@T["Ui.Attachments.Generate"]</div>
<ul class="kh-att-list gen">
@foreach (var generator in Generators)
{
var existing = _items.FirstOrDefault(i => i.IsLatest && i.GeneratedBy == generator.Code);
<li class="kh-att-row" @key="generator.Code">
<span class="kh-att-type @TypeClass(generator.MediaType)" aria-hidden="true">@ExtensionLabel(generator.Extension)</span>
<span class="kh-att-main">
<span class="t">@T[generator.TitleKey]</span>
<span class="m">@(existing is null ? T["Ui.Attachments.NotGenerated"] : T.Format("Ui.Attachments.Generated", existing.VersionLabel, When(existing.CreatedAt)))</span>
</span>
@if (CanWrite)
{
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => GenerateAsync(generator)">
<KhIcon Name="@(existing is null ? "plus" : "refresh")" /> @T[existing is null ? "Ui.Attachments.GenerateOne" : "Ui.Attachments.Regenerate"]
</button>
}
</li>
}
</ul>
}
@if (_trash.Count > 0)
{
<div class="kh-att-section">@T["Ui.Attachments.Trash"]</div>
<ul class="kh-att-list trash">
@foreach (var item in _trash)
{
<li class="kh-att-row old" @key="item.Id">
<span class="kh-att-type @TypeClass(item)" aria-hidden="true">@TypeLabel(item)</span>
<span class="kh-att-main">
<span class="t">@item.FileName</span>
<span class="m">@T.Format("Ui.Attachments.TrashedOn", When(item.DeletedAt ?? item.CreatedAt), PurgeDate(item))</span>
</span>
@if (CanDelete)
{
<button type="button" class="btn sm" @onclick="() => RestoreAsync(item)"><KhIcon Name="undo" /> @T["Ui.Attachments.Restore"]</button>
}
</li>
}
</ul>
}
}
</div>
<KhFilePreview Attachment="_preview" OnClose="() => _preview = null" />
@code {
private List<AttachmentView> _items = [];
private List<AttachmentView> _trash = [];
private FileLimits? _limits;
private AttachmentView? _preview;
private bool _loaded;
private bool _older;
private bool _busy;
private (string Entity, long Id)? _shown;
private int? _reported;
/// <summary>The entity of the record, such as <c>sale.document</c>.</summary>
[Parameter, EditorRequired]
public string Entity { get; set; } = string.Empty;
/// <summary>The record.</summary>
[Parameter, EditorRequired]
public long EntityId { get; set; }
/// <summary>Called with the number of attachments in use after every change (the counter on the toolbar).</summary>
[Parameter]
public EventCallback<int> OnCountChanged { get; set; }
private string? Company => Session.Actor?.CompanyCode;
private bool CanWrite => Session.Permissions.Allows(AttachmentService.WritePermission);
private bool CanDelete => Session.Permissions.Allows(AttachmentService.DeletePermission);
private IReadOnlyList<IFileGenerator> Generators => Company is null ? [] : Generation.AvailableFor(Entity);
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
// The parent re-renders when the count changes: load again only for another record.
if (_shown == (Entity, EntityId))
{
return;
}
_shown = (Entity, EntityId);
_loaded = false;
await Session.EnsureLoadedAsync();
_limits ??= await Attachments.GetLimitsAsync();
await LoadAsync();
}
private async Task LoadAsync()
{
if (Session.Actor is not { CompanyCode: { } company } actor)
{
_loaded = true;
return;
}
var all = await Attachments.ListAsync(actor, company, Entity, EntityId, includeOlderVersions: true);
_items = [.. all.Where(a => _older || a.IsLatest)];
_trash = CanDelete
? [.. (await Attachments.ListTrashAsync(actor, company)).Where(a => a.Entity == Entity && a.EntityId == EntityId)]
: [];
_loaded = true;
var count = all.Count(a => a.IsLatest);
if (_reported != count)
{
_reported = count;
await OnCountChanged.InvokeAsync(count);
}
}
private Task ToggleOlderAsync(ChangeEventArgs e)
{
_older = e.Value is true;
return LoadAsync();
}
private async Task UploadAsync(InputFileChangeEventArgs e)
{
if (Session.Actor is not { CompanyCode: { } company } actor || _limits is not { } limits)
{
return;
}
_busy = true;
try
{
foreach (var file in e.GetMultipleFiles(20))
{
if (limits.MaxBytes > 0 && file.Size > limits.MaxBytes)
{
Toasts.Show(ToastKind.Error, file.Name, T.Format("Ui.Attachments.TooLarge", Size(limits.MaxBytes)));
continue;
}
await RunAsync(file.Name, async () =>
{
await using var stream = file.OpenReadStream(limits.MaxBytes > 0 ? limits.MaxBytes : long.MaxValue);
var added = await Attachments.UploadAsync(actor, company, Entity, EntityId, file.Name, file.ContentType, stream);
Toasts.Show(ToastKind.Success, T["Ui.Attachments.Uploaded"], added.FileName);
});
}
}
finally
{
_busy = false;
await LoadAsync();
}
}
private async Task GenerateAsync(IFileGenerator generator)
{
if (Session.Actor is not { CompanyCode: { } company } actor)
{
return;
}
_busy = true;
try
{
await RunAsync(T[generator.TitleKey], async () =>
{
var made = await Generation.GenerateAsync(actor, company, Entity, EntityId, generator.Code);
Toasts.Show(ToastKind.Success, T["Ui.Attachments.GeneratedToast"], made.FileName);
});
}
finally
{
_busy = false;
await LoadAsync();
}
}
private async Task LockAsync(AttachmentView item)
{
if (Session.Actor is not { CompanyCode: { } company } actor ||
!await Dialogs.ConfirmAsync(new(T["Ui.Attachments.LockTitle"], T.Format("Ui.Attachments.LockText", item.FileName), T["Ui.Attachments.Lock"], T["Common.Cancel"])))
{
return;
}
await RunAsync(item.FileName, () => Attachments.LockAsync(actor, company, item.Id));
await LoadAsync();
}
private async Task DeleteAsync(AttachmentView item)
{
if (Session.Actor is not { CompanyCode: { } company } actor ||
!await Dialogs.ConfirmAsync(new(T["Ui.Attachments.DeleteTitle"], T.Format("Ui.Attachments.DeleteText", item.FileName), T["Ui.Attachments.Delete"], T["Common.Cancel"], Danger: true)))
{
return;
}
await RunAsync(item.FileName, () => Attachments.DeleteAsync(actor, company, item.Id));
await LoadAsync();
}
private async Task RestoreAsync(AttachmentView item)
{
if (Session.Actor is not { CompanyCode: { } company } actor)
{
return;
}
await RunAsync(item.FileName, () => Attachments.RestoreAsync(actor, company, item.Id));
await LoadAsync();
}
// Errors of the services become a toast with their text; nothing else is caught.
private async Task RunAsync(string subject, Func<Task> action)
{
try
{
await action();
}
catch (ValidationFailedException ex)
{
Toasts.Show(ToastKind.Error, subject, string.Join(" ", ex.Errors.Select(ErrorText)));
}
catch (AccessDeniedException)
{
Toasts.Show(ToastKind.Error, subject, T["Ui.Attachments.Denied"]);
}
catch (IOException)
{
// The browser stream ended early or went over the limit.
Toasts.Show(ToastKind.Error, subject, T.Format("Ui.Attachments.TooLarge", Size(_limits?.MaxBytes ?? 0)));
}
}
private string ErrorText(string code) => T.Contains(code) ? T[code] : T["Ui.Attachments.Failed"];
private string Meta(AttachmentView item) =>
T.Format(item.Kind == AttachmentKind.Generated ? "Ui.Attachments.MetaGenerated" : "Ui.Attachments.MetaUploaded",
item.VersionLabel, Size(item.Size), item.CreatedBy ?? string.Empty, When(item.CreatedAt));
private string When(DateTime utc) => T.DateTime(utc, TimeZoneInfo.Local);
private string PurgeDate(AttachmentView item) =>
T.Date(DateOnly.FromDateTime((item.DeletedAt ?? Clock.GetUtcNow().UtcDateTime) + AttachmentService.TrashRetention));
private string Size(long bytes) => FileSizes.Format(bytes, T.Culture);
private static string TypeClass(AttachmentView item) => TypeClass(item.Mime);
private static string TypeClass(string mime) => MediaTypes.PreviewOf(mime) switch
{
AttachmentPreview.Pdf => "pdf",
AttachmentPreview.Image => "img",
AttachmentPreview.Xml => "xml",
AttachmentPreview.Csv or AttachmentPreview.Xlsx => "sheet",
_ => "file",
};
private static string TypeLabel(AttachmentView item) => ExtensionLabel(Path.GetExtension(item.FileName));
private static string ExtensionLabel(string extension) =>
extension.TrimStart('.') is { Length: > 0 and <= 4 } ext ? ext.ToUpperInvariant() : "FILE";
}
@@ -0,0 +1,78 @@
@using Khaemhat.Application.Audit
@* The history of a record (SPEC §7.4, the "Storico" tab): who did what and when, newest first, with the changed fields
and their old and new values. *@
@if (Items is null)
{
<p class="muted">@T["Common.Loading"]</p>
}
else if (Items.Count == 0)
{
<p class="kh-wempty"><KhIcon Name="history" /> @T["Ui.Audit.None"]</p>
}
else
{
<ol class="kh-audit">
@foreach (var item in Items)
{
<li class="kh-audit-item" @key="item.Id">
<span class="ico-box @ToneOf(item.Action)" aria-hidden="true"><KhIcon Name="@IconOf(item.Action)" /></span>
<div class="kh-audit-main">
<div class="t">
@T.Format(ActionKey(item.Action), item.UserName ?? T["Ui.Audit.Someone"])
<span class="muted">· @T.DateTime(item.At, TimeZoneInfo.Local)</span>
</div>
@if (item.Changes.Count > 0)
{
<table class="kh-audit-changes">
<thead>
<tr><th>@T["Ui.Audit.Field"]</th><th>@T["Ui.Audit.Before"]</th><th>@T["Ui.Audit.After"]</th></tr>
</thead>
<tbody>
@foreach (var change in item.Changes)
{
<tr>
<td>@(FieldName?.Invoke(change.Field) ?? change.Field)</td>
<td class="old">@(change.Before ?? "-")</td>
<td>@(change.After ?? "-")</td>
</tr>
}
</tbody>
</table>
}
</div>
</li>
}
</ol>
}
@code {
/// <summary>The rows, newest first; <see langword="null"/> while loading.</summary>
[Parameter]
public IReadOnlyList<AuditItem>? Items { get; set; }
/// <summary>The label of a field, when the page has one (the field name otherwise).</summary>
[Parameter]
public Func<string, string?>? FieldName { get; set; }
private static string ActionKey(AuditAction action) => action switch
{
AuditAction.Insert => "Ui.Audit.Inserted",
AuditAction.Delete => "Ui.Audit.Deleted",
_ => "Ui.Audit.Updated",
};
private static string IconOf(AuditAction action) => action switch
{
AuditAction.Insert => "plus",
AuditAction.Delete => "trash",
_ => "edit",
};
private static string ToneOf(AuditAction action) => action switch
{
AuditAction.Insert => "ok",
AuditAction.Delete => "err",
_ => string.Empty,
};
}
@@ -0,0 +1,111 @@
@using Khaemhat.Web.Hosting
@inject ShellSession Session
@inject AttachmentService Attachments
@* The preview of an attachment (SPEC §9.4, mockup 024): PDF and images in the viewer of the browser, XML and text as
text, CSV and XLSX as a table; long files are cut and say so. *@
<KhDialog Open="Attachment is not null" Title="@Attachment?.FileName" Icon="eye" Size="lg" OnClose="OnClose">
<ChildContent>
@if (Attachment is { } item)
{
<div class="kh-preview">
@switch (item.Preview)
{
case AttachmentPreview.Pdf:
<iframe class="kh-preview-frame" src="@FileEndpoints.View(item.Id)" title="@item.FileName"></iframe>
break;
case AttachmentPreview.Image:
<img class="kh-preview-img" src="@FileEndpoints.View(item.Id)" alt="@item.FileName" />
break;
default:
if (_content is null)
{
<p class="muted">@T["Common.Loading"]</p>
}
else if (_content.Rows is { } rows)
{
<div class="kh-preview-table">
<table class="grid">
<tbody>
@foreach (var row in rows)
{
<tr>
@foreach (var cell in row)
{
<td>@cell</td>
}
</tr>
}
</tbody>
</table>
</div>
}
else if (_content.Text is { } text)
{
<pre class="kh-preview-text">@text</pre>
}
else
{
<div class="callout warn"><KhIcon Name="alert" /> <span>@T["Ui.Preview.Unreadable"]</span></div>
}
@if (_content?.Truncated == true)
{
<p class="muted sm">@T["Ui.Preview.Truncated"]</p>
}
break;
}
</div>
}
</ChildContent>
<Footer>
@if (Attachment is { } item)
{
@if (FileEndpoints.OpensInBrowser(item.Mime))
{
<a class="btn" href="@FileEndpoints.View(item.Id)" target="_blank" rel="noopener"><KhIcon Name="external" /> @T["Ui.Preview.Open"]</a>
}
<a class="btn primary" href="@FileEndpoints.Download(item.Id)" download="@item.FileName"><KhIcon Name="download" /> @T["Ui.Attachments.Download"]</a>
}
</Footer>
</KhDialog>
@code {
private FilePreview? _content;
private long? _loadedId;
/// <summary>The attachment to show; <see langword="null"/> keeps the dialog closed.</summary>
[Parameter]
public AttachmentView? Attachment { get; set; }
/// <summary>Closes the dialog.</summary>
[Parameter]
public EventCallback OnClose { get; set; }
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
if (Attachment is not { } item)
{
_content = null;
_loadedId = null;
return;
}
if (_loadedId == item.Id || item.Preview is AttachmentPreview.Pdf or AttachmentPreview.Image or AttachmentPreview.None)
{
return;
}
_loadedId = item.Id;
_content = null;
if (Session.Actor is not { CompanyCode: { } company } actor)
{
return;
}
await using var file = await Attachments.OpenAsync(actor, company, item.Id);
_content = await FilePreview.ReadAsync(item.Preview, file.Content, T.Culture);
}
}
@@ -0,0 +1,71 @@
@inject IJSRuntime JS
@* The print preview of SPEC §9.4 (mockup 025): the document as an A4 sheet in HTML and CSS, with Stampa (the print of
the browser, which leaves out the rest of the window), the PDF made by Khaemhat (open or download) and "Salva come
allegato", which attaches the PDF to the record as a new version. Zoom only changes the view. *@
<div class="kh-print">
<div class="kh-print-bar">
<button type="button" class="btn primary" @onclick="PrintAsync"><KhIcon Name="printer" /> @T["Ui.Print.Print"]</button>
@if (PdfUrl is not null)
{
<a class="btn" href="@PdfUrl" target="_blank" rel="noopener"><KhIcon Name="external" /> @T["Ui.Print.OpenPdf"]</a>
}
@if (PdfDownloadUrl is not null)
{
<a class="btn" href="@PdfDownloadUrl" download><KhIcon Name="download" /> @T["Ui.Print.DownloadPdf"]</a>
}
@if (OnSaveAttachment.HasDelegate)
{
<button type="button" class="btn" disabled="@Saving" @onclick="OnSaveAttachment"><KhIcon Name="paperclip" /> @T["Ui.Print.SaveAttachment"]</button>
}
<span class="grow"></span>
<div class="kh-seg" role="group" aria-label="@T["Ui.Print.Zoom"]">
@foreach (var zoom in Zooms)
{
<button type="button" class="@(zoom == _zoom ? "on" : null)" aria-pressed="@(zoom == _zoom ? "true" : "false")" @onclick="() => _zoom = zoom">@(zoom)%</button>
}
</div>
</div>
<div class="kh-print-stage">
<div class="kh-sheet" style="@($"zoom:{_zoom}%")">
@ChildContent
</div>
</div>
</div>
@code {
private static readonly int[] Zooms = [75, 100, 125];
private int _zoom = 100;
/// <summary>The sheet: what is printed.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>The address of the PDF opened in the browser, if there is one.</summary>
[Parameter]
public string? PdfUrl { get; set; }
/// <summary>The address that downloads the PDF, if there is one.</summary>
[Parameter]
public string? PdfDownloadUrl { get; set; }
/// <summary>Attaches the PDF to the record; without it the button is not shown.</summary>
[Parameter]
public EventCallback OnSaveAttachment { get; set; }
/// <summary>Whether the attachment is being saved.</summary>
[Parameter]
public bool Saving { get; set; }
private async Task PrintAsync()
{
try
{
await JS.InvokeVoidAsync("print");
}
catch (JSDisconnectedException)
{
// The window is gone.
}
}
}
+134
View File
@@ -0,0 +1,134 @@
using System.Globalization;
using System.Net.Mime;
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Web.Security;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// The addresses that send files to the browser (SPEC §9.4, mockup 024-025): an attachment, all the attachments of a
/// record as ZIP, a file generated on the fly (print preview). The services check company and permissions; only PDF
/// and common images open in the browser, everything else is downloaded.
/// </summary>
public static class FileEndpoints
{
/// <summary>The content security policy of a file opened in the browser: framed by this site only, no scripts.</summary>
public const string InlinePolicy = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; object-src 'self'; frame-ancestors 'self'";
/// <summary>The base address.</summary>
public const string BasePath = "/files";
/// <summary>The address of an attachment, opened in the browser when it can be.</summary>
/// <param name="id">The attachment.</param>
/// <returns>The address relative to the application.</returns>
public static string View(long id) => BasePath[1..] + "/" + id.ToString(CultureInfo.InvariantCulture);
/// <summary>The address that downloads an attachment.</summary>
/// <param name="id">The attachment.</param>
/// <returns>The address relative to the application.</returns>
public static string Download(long id) => View(id) + "?download=1";
/// <summary>The address of the ZIP with all the attachments of a record.</summary>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <returns>The address relative to the application.</returns>
public static string Zip(string entity, long entityId) =>
BasePath[1..] + "/zip?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture);
/// <summary>The address of a file generated on the fly, without attaching it.</summary>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="generator">The generator code.</param>
/// <param name="download">Whether to download it instead of opening it.</param>
/// <returns>The address relative to the application.</returns>
public static string Generated(string entity, long entityId, string generator, bool download = false) =>
BasePath[1..] + "/generate?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture)
+ "&generator=" + Uri.EscapeDataString(generator) + (download ? "&download=1" : string.Empty);
/// <summary>Whether a media type may be shown by the browser instead of downloaded.</summary>
/// <param name="mime">The media type.</param>
/// <returns><see langword="true"/> for PDF and common images.</returns>
public static bool OpensInBrowser(string mime) => MediaTypes.PreviewOf(mime) is AttachmentPreview.Pdf or AttachmentPreview.Image;
/// <summary>Maps the addresses.</summary>
/// <param name="endpoints">The application.</param>
public static void MapFiles(this IEndpointRouteBuilder endpoints)
{
endpoints.MapGet(BasePath + "/{id:long}", (HttpContext context, long id, AttachmentService attachments) =>
RunAsync(context, async actor =>
{
var file = await attachments.OpenAsync(actor, Company(actor), id, context.RequestAborted).ConfigureAwait(false);
context.Response.RegisterForDisposeAsync(file);
return Send(context, file.Content, file.Attachment.Mime, file.Attachment.FileName);
}));
endpoints.MapGet(BasePath + "/zip", (HttpContext context, string entity, long id, AttachmentService attachments) =>
RunAsync(context, async actor =>
{
// Read the list first: missing rights fail before the download starts.
var company = Company(actor);
var list = await attachments.ListAsync(actor, company, entity, id, cancellationToken: context.RequestAborted).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(entity.Replace('.', '-') + "-" + id.ToString(CultureInfo.InvariantCulture) + "-allegati.zip");
return list.Count == 0
? Results.NotFound()
: Results.Stream(output => attachments.WriteZipAsync(actor, company, entity, id, output, context.RequestAborted), MediaTypes.Zip, name);
}));
endpoints.MapGet(BasePath + "/generate", (HttpContext context, string entity, long id, string generator, FileGenerationService files) =>
RunAsync(context, async actor =>
{
var content = new MemoryStream();
context.Response.RegisterForDisposeAsync(content);
var (name, mime) = await files.WriteAsync(actor, Company(actor), entity, id, generator, content, context.RequestAborted).ConfigureAwait(false);
content.Position = 0;
return Send(context, content, mime, name);
}));
}
private static string Company(Actor actor) =>
actor.CompanyCode ?? throw new AccessDeniedException(SecurityErrors.PermissionDenied, "Files belong to a company: choose one first.");
private static async Task<IResult> RunAsync(HttpContext context, Func<Actor, Task<IResult>> action)
{
if (SessionCookie.ActorOf(context.User) is not { } actor)
{
return Results.Unauthorized();
}
try
{
return await action(actor).ConfigureAwait(false);
}
catch (AccessDeniedException)
{
return Results.StatusCode(StatusCodes.Status403Forbidden);
}
catch (ValidationFailedException ex) when (ex.Errors.Contains(AttachmentService.NotFoundError))
{
return Results.NotFound();
}
catch (ValidationFailedException)
{
return Results.BadRequest();
}
}
private static IResult Send(HttpContext context, Stream content, string mime, string fileName)
{
var download = context.Request.Query.ContainsKey("download") || !OpensInBrowser(mime);
if (download)
{
return Results.File(content, mime, fileName, enableRangeProcessing: true);
}
var disposition = new ContentDisposition { Inline = true, FileName = fileName };
context.Response.Headers.ContentDisposition = disposition.ToString();
context.Response.Headers.CacheControl = "private, no-store";
// Shown inside the preview of this site only: no scripts, no other framing site.
context.Response.Headers.ContentSecurityPolicy = InlinePolicy;
context.Response.Headers.XFrameOptions = "SAMEORIGIN";
return Results.File(content, mime, enableRangeProcessing: true);
}
}
+1
View File
@@ -111,6 +111,7 @@ public static class KhaemhatApp
app.MapSignOut();
app.MapCompanySwitch();
app.MapHelp();
app.MapFiles();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
@@ -139,6 +139,7 @@ internal static class KhaemhatServices
// History of the records and scheduled tasks.
services.AddSingleton<AuditTrail>();
services.AddSingleton<AuditTrailService>();
services.AddSingleton<IScheduledJob, SessionCleanupJob>();
services.AddSingleton<IScheduledJob, LicenseCheckJob>();
services.AddSingleton<IScheduledJob, LogRetentionJob>();
+10 -4
View File
@@ -20,12 +20,18 @@ internal static class KhaemhatMiddleware
{
context.Response.OnStarting(() =>
{
// A file shown in the preview of the attachments sets its own, narrower policy that allows this site only
// to frame it (FileEndpoints); every other response gets the default.
var headers = context.Response.Headers;
headers.ContentSecurityPolicy =
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " +
"connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'";
if (headers.ContentSecurityPolicy != FileEndpoints.InlinePolicy)
{
headers.ContentSecurityPolicy =
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " +
"connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'";
headers.XFrameOptions = "DENY";
}
headers.XContentTypeOptions = "nosniff";
headers.XFrameOptions = "DENY";
headers["Referrer-Policy"] = "same-origin";
headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=()";
headers["Cross-Origin-Opener-Policy"] = "same-origin";
@@ -0,0 +1,19 @@
{
"attachments": {
"not_found": "Il file non esiste più.",
"locked": "Il file è bloccato e non si può eliminare.",
"file_too_large": "Il file supera la dimensione massima consentita.",
"quota_exceeded": "Lo spazio per i file dell'azienda è esaurito.",
"file_rejected": "Il file è stato rifiutato dal controllo antivirus.",
"owner_invalid": "Il documento a cui allegare il file non è valido.",
"file_empty": "Il file è vuoto.",
"generator_unknown": "Questo file non si può generare per il documento."
},
"files": {
"generators": {
"demo_pdf": "Documento di prova in PDF",
"demo_csv": "Righe in CSV (per Excel)",
"demo_xlsx": "Righe in Excel (XLSX)"
}
}
}
@@ -368,6 +368,16 @@
"Report": "Segnala un problema",
"Missing": "La copia della wiki non è presente in questa installazione: apri la wiki online.",
"NotFound": "La pagina «{0}» non esiste nella wiki: scegline una dall'indice."
},
"Print": {
"Title": "Anteprima di stampa",
"Crumb": "Sviluppo · Documento di prova",
"Heading": "Anteprima di stampa · {0} n. {1}",
"CompanyLine": "Azienda {0} · dati fittizi per provare la stampa",
"Number": "n. {0} del {1}",
"Intro": "Documento di prova di Khaemhat per l'azienda {0}, preparato da {1}. Righe, prezzi e importi sono inventati: servono a provare la stampa, il PDF e gli allegati.",
"Total": "Totale",
"Footer": "Documento senza valore fiscale, generato per prova."
}
}
}
+61
View File
@@ -144,6 +144,67 @@
"HintNext": "cella successiva",
"HintLookup": "cerca",
"HintRemove": "togli la riga"
},
"Attachments": {
"Title": "Allegati e file generati",
"Intro": "Gli allegati appartengono solo a questo documento. I file generati da Khaemhat hanno una versione: rigenerarli crea v2, v3 e le versioni precedenti restano consultabili.",
"NoCompany": "Gli allegati appartengono a un'azienda: scegline una dal selettore in alto.",
"Count": "Allegati ({0})",
"Older": "Versioni precedenti",
"None": "Nessun allegato. Carica un file o generane uno.",
"Locked": "Bloccato: non si può eliminare",
"Preview": "Anteprima",
"PreviewOf": "Anteprima di {0}",
"Download": "Scarica",
"DownloadOf": "Scarica {0}",
"Lock": "Blocca",
"LockOf": "Blocca {0}",
"LockTitle": "Bloccare il file?",
"LockText": "{0} non si potrà più eliminare, nemmeno da te. Si fa per i file inviati o conservati.",
"Delete": "Sposta nel cestino",
"DeleteOf": "Sposta {0} nel cestino",
"DeleteTitle": "Spostare il file nel cestino?",
"DeleteText": "{0} resta nel cestino per 30 giorni e si può ripristinare; poi viene eliminato.",
"Upload": "Carica file",
"Uploaded": "File caricato",
"Zip": "Scarica tutto (ZIP)",
"Limit": "Al massimo {0} per file.",
"TooLarge": "Il file supera il limite di {0}.",
"Generate": "Genera file",
"GenerateOne": "Genera",
"Regenerate": "Rigenera",
"NotGenerated": "Non ancora generato",
"Generated": "Ultima versione {0} del {1}",
"GeneratedToast": "File generato",
"MetaUploaded": "{0} · {1} · caricato da {2} · {3}",
"MetaGenerated": "{0} · {1} · generato da {2} · {3}",
"Trash": "Nel cestino",
"TrashedOn": "Eliminato il {0} · definitivo dal {1}",
"Restore": "Ripristina",
"Denied": "Non hai il permesso per questa operazione.",
"Failed": "L'operazione non è riuscita."
},
"Preview": {
"Open": "Apri in una nuova finestra",
"Unreadable": "Il contenuto del file non si può mostrare: scaricalo per aprirlo.",
"Truncated": "Il file è lungo: l'anteprima ne mostra solo l'inizio."
},
"Print": {
"Print": "Stampa",
"OpenPdf": "Apri PDF",
"DownloadPdf": "Scarica PDF",
"SaveAttachment": "Salva come allegato",
"Zoom": "Ingrandimento"
},
"Audit": {
"None": "Nessuna modifica registrata.",
"Someone": "qualcuno",
"Inserted": "Creato da {0}",
"Updated": "Modificato da {0}",
"Deleted": "Eliminato da {0}",
"Field": "Campo",
"Before": "Prima",
"After": "Dopo"
}
}
}
+28
View File
@@ -0,0 +1,28 @@
using System.Globalization;
namespace Khaemhat.Web.Ui;
/// <summary>File sizes as people read them: <c>840 B</c>, <c>184 KB</c>, <c>1,2 MB</c>.</summary>
public static class FileSizes
{
private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"];
/// <summary>Formats a size in bytes (1 KB = 1024 B).</summary>
/// <param name="bytes">The size.</param>
/// <param name="culture">The culture of the decimal separator.</param>
/// <returns>The text.</returns>
public static string Format(long bytes, CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(culture);
double value = Math.Max(0, bytes);
var unit = 0;
while (value >= 1024 && unit < Units.Length - 1)
{
value /= 1024;
unit++;
}
var format = unit == 0 || value >= 10 ? "0" : "0.#";
return value.ToString(format, culture) + " " + Units[unit];
}
}
+70
View File
@@ -241,3 +241,73 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; }
.palette .hit > span:first-of-type { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.palette .hit .d:last-child { margin-left: auto; }
@media (max-width: 899px) { .kh-help { grid-template-columns: 1fr; } .kh-help-index { position: static; max-height: 240px; } }
/* Attachments and generated files (SPEC §9.4, mockup 024). */
.kh-tab-body { padding: 14px 16px; }
.kh-att { display: flex; flex-direction: column; gap: 10px; }
.kh-att-head { display: flex; align-items: center; gap: 8px; }
.kh-att-title, .kh-att-section { font-size: 10.5px; text-transform: uppercase; letter-spacing: .5px; color: var(--kh-text-3); font-weight: 600; }
.kh-att-section { margin-top: 6px; }
.kh-att-list { list-style: none; margin: 0; padding: 0; border: 1px solid var(--kh-border); border-radius: 8px; }
.kh-att-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-bottom: 1px solid var(--kh-border); }
.kh-att-row:last-child { border-bottom: 0; }
.kh-att-row.old { opacity: .72; }
.kh-att-type { flex: 0 0 auto; width: 38px; height: 38px; border-radius: 7px; display: grid; place-items: center; font: 600 10px var(--kh-mono); letter-spacing: .3px; background: var(--kh-surface-2); color: var(--kh-text-2); }
.kh-att-type.pdf { background: var(--kh-err-soft); color: var(--kh-err); }
.kh-att-type.xml { background: var(--kh-info-soft); color: var(--kh-info); }
.kh-att-type.sheet { background: var(--kh-ok-soft); color: var(--kh-ok); }
.kh-att-type.img { background: var(--kh-warn-soft); color: var(--kh-warn); }
.kh-att-main { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
.kh-att-main .t { font-weight: 600; overflow-wrap: anywhere; display: flex; align-items: center; gap: 6px; }
.kh-att-main .m { color: var(--kh-text-3); font-size: 12px; }
.kh-att-actions { display: flex; gap: 2px; flex: 0 0 auto; }
.kh-att-buttons { display: flex; flex-wrap: wrap; gap: 8px; }
.kh-att-upload { cursor: pointer; }
.kh-att-upload input[type="file"] { display: none; }
.kh-att-upload.disabled { opacity: .6; pointer-events: none; }
/* Preview of a file (mockup 024). */
.kh-preview { min-height: 200px; }
.kh-preview-frame { width: 100%; height: 70vh; border: 1px solid var(--kh-border); border-radius: 6px; background: #fff; }
.kh-preview-img { display: block; max-width: 100%; max-height: 70vh; margin: 0 auto; }
.kh-preview-text { max-height: 70vh; overflow: auto; margin: 0; padding: 12px; background: var(--kh-surface-2); border-radius: 6px; font: 12px/1.5 var(--kh-mono); white-space: pre-wrap; overflow-wrap: anywhere; }
.kh-preview-table { max-height: 70vh; overflow: auto; }
.kh-preview-table td { white-space: nowrap; }
/* History of a record (SPEC §7.4). */
.kh-audit { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 12px; }
.kh-audit-item { display: flex; gap: 10px; align-items: flex-start; }
.kh-audit-main { flex: 1; min-width: 0; }
.kh-audit-main .t { font-weight: 600; margin-bottom: 4px; }
.kh-audit-main .t .muted { font-weight: 400; }
.kh-audit-changes { border-collapse: collapse; font-size: 12.5px; }
.kh-audit-changes th { text-align: left; font-weight: 600; color: var(--kh-text-3); padding: 2px 14px 2px 0; }
.kh-audit-changes td { padding: 2px 14px 2px 0; overflow-wrap: anywhere; }
.kh-audit-changes td.old { color: var(--kh-text-3); text-decoration: line-through; }
/* Print preview (SPEC §9.4, mockup 025): an A4 sheet; printing shows the sheet only. */
.kh-print { display: flex; flex-direction: column; gap: 12px; }
.kh-print-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.kh-print-stage { background: var(--kh-surface-2); border: 1px solid var(--kh-border); border-radius: 8px; padding: 24px; overflow: auto; }
.kh-sheet { width: 210mm; min-height: 297mm; margin: 0 auto; padding: 18mm 16mm; background: #fff; color: #1d2433; box-shadow: 0 2px 12px rgba(0,0,0,.12); font: 10pt/1.45 var(--kh-font, system-ui), sans-serif; box-sizing: border-box; }
.kh-sheet-head { display: flex; justify-content: space-between; gap: 16px; border-bottom: 2px solid #1F5F8B; padding-bottom: 10px; margin-bottom: 14px; }
.kh-sheet-company { font-size: 15pt; font-weight: 700; }
.kh-sheet-muted { color: #6b7280; font-size: 9pt; }
.kh-sheet-title { text-align: right; }
.kh-sheet-title .k { font-size: 16pt; font-weight: 700; color: #1F5F8B; }
.kh-sheet-title .n { color: #6b7280; }
.kh-sheet-intro { margin: 0 0 14px; }
.kh-sheet-table { width: 100%; border-collapse: collapse; font-size: 9.5pt; }
.kh-sheet-table th { background: #eceff3; text-align: left; padding: 5px 6px; }
.kh-sheet-table td { padding: 5px 6px; border-bottom: 1px solid #d9dde3; }
.kh-sheet-table .num { text-align: right; white-space: nowrap; }
.kh-sheet-table .mono { font-family: var(--kh-mono); }
.kh-sheet-table tfoot td { border-bottom: 0; padding-top: 8px; }
.kh-sheet-foot { margin-top: 24px; color: #6b7280; font-size: 8.5pt; }
@media (max-width: 899px) { .kh-print-stage { padding: 8px; } .kh-sheet { width: 100%; min-height: 0; padding: 16px; } }
@media print {
@page { size: A4; margin: 0; }
body * { visibility: hidden; }
.kh-sheet, .kh-sheet * { visibility: visible; }
.kh-sheet { position: absolute; left: 0; top: 0; zoom: 1 !important; width: 210mm; min-height: 0; box-shadow: none; margin: 0; }
}