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

@@ -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.
}
}
}