diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b87950..890fb20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,16 @@ M3 — Framework UI, prima parte: la shell dell'applicazione, i testi localizzat `sys_notification_reads` e `notification_reads`). - Ricerca globale a fornitori (`GlobalSearchService`, `ISearchProvider`): oltre a pagine e comandi trova le pagine e le sezioni dell'aiuto; prefissi `#` documenti e `@` persone pronti per i moduli successivi. +- Allegati nell'interfaccia (mockup 024): `KhAttachmentList` con caricamento, anteprima, download, blocco, cestino + con ripristino, versioni precedenti, *Scarica tutto (ZIP)* e *Genera file* / *Rigenera*; anteprima di PDF e + immagini nel browser, di XML e testo come testo, di CSV e XLSX come griglia (lettore XLSX scritto in casa). +- Anteprima di stampa (mockup 025): `KhPrintPreview` con foglio A4 in HTML e CSS, *Stampa* del solo foglio, PDF da + aprire o scaricare e *Salva come allegato*; prova sul documento di sviluppo con `Ctrl+P`. +- Storico di un record: `AuditTrailService` legge il registro delle modifiche e `KhAuditList` mostra chi ha cambiato + cosa, con i valori prima e dopo. +- Indirizzi `/files/{id}`, `/files/zip` e `/files/generate` per scaricare gli allegati, tutti gli allegati di un + record e un file generato al volo; solo PDF e immagini si aprono nel browser, con una politica di sicurezza propria + che permette l'anteprima dentro Khaemhat. - Con la dashboard spenta, Home con licenza, moduli, azienda e aree disponibili; le aree delle prossime versioni aprono una pagina che dice con quale milestone arrivano. - Dashboard a widget (mockup 004-006, ADR 0022): Da fare oggi, Fatto oggi, Scadenze 30 giorni, Promemoria personali, diff --git a/docs/wiki/Allegati-e-file.md b/docs/wiki/Allegati-e-file.md index 5a8eb51..a24854f 100644 --- a/docs/wiki/Allegati-e-file.md +++ b/docs/wiki/Allegati-e-file.md @@ -1,7 +1,7 @@ # Allegati e file -> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M3, completata in M5) -> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.delete`, permessi di lettura del documento · **Specifica:** SPEC §9.4 +> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.3.0 (milestone M3, completata in M5) +> **Modulo di licenza:** CORE · **Permessi principali:** `attachments.read`, `attachments.write`, `attachments.delete` · **Specifica:** SPEC §9.4 Ogni documento e ogni anagrafica può avere **allegati**: file caricati dall'utente (l'ordine del cliente in PDF, una foto, un foglio di calcolo) e file **generati** da Khaemhat (PDF di stampa, XML FatturaPA, esportazioni, pacchetti @@ -12,6 +12,11 @@ ZIP). Gli allegati sono archiviati sul volume dei dati dell'istanza, con version Da qualunque documento: icona **Allegati** nella toolbar (con il numero degli allegati) oppure scheda **Allegati (n)**. Si apre il pannello laterale **Allegati e file generati**. +> **In questa versione** i documenti veri arrivano con le vendite (M5): pannello, anteprime e anteprima di stampa si +> provano sul **documento di prova** degli sviluppatori (dal catalogo dei componenti `/sviluppo/componenti`, +> solo in ambiente di sviluppo), che ha +> tre file generabili (PDF, righe in CSV, righe in Excel). Mancano ancora **Invia** per e-mail e **Da scanner / foto**. + ![024 · Allegati del documento e generazione file](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/024-allegati-e-file-generati.png) *Mockup 024 — pannello laterale sopra la fattura: elenco degli allegati con azioni, Carica file, Da scanner / foto, Scarica tutto (ZIP) e sezione Genera file (anteprima ridotta).* @@ -42,10 +47,12 @@ caricato o generato e quando, dimensione, versione, eventuale modello usato. |---|---| | occhio | **Anteprima** in app | | freccia in giù | **Scarica** | -| busta | **Invia** per e-mail | -| frecce circolari | **Rigenera**: crea una nuova versione del file generato | -| cestino | **Elimina** (solo file non bloccati e con permesso) | -| lucchetto | il file è bloccato | +| busta | **Invia** per e-mail (con le vendite) | +| frecce circolari | **Rigenera** (nella sezione *Genera file*): crea una nuova versione del file generato | +| lucchetto | **Blocca**: da quel momento il file non si può più eliminare; accanto al nome indica un file bloccato | +| cestino | **Sposta nel cestino** (solo file non bloccati e con permesso), dopo una conferma | + +La casella **Versioni precedenti** mostra anche le versioni superate dei file generati (`v1` quando c'è già `v2`). In fondo all'elenco: @@ -79,19 +86,35 @@ Il pannello apre in app l'anteprima di: | Formato | Come si vede | |---|---| -| PDF | visualizzatore integrato | -| Immagini | a dimensione piena con zoom | -| XML | testo formattato e indentato | -| CSV, XLSX | griglia | +| PDF | visualizzatore PDF del browser, dentro la finestra di anteprima | +| Immagini (JPEG, PNG, GIF, WebP) | adattate alla finestra | +| XML, testo | testo così com'è | +| CSV, XLSX | griglia (il primo foglio per gli XLSX) | -Gli altri formati si scaricano. Per i documenti c'è anche l'**anteprima di stampa** (`Ctrl+P`, mockup 025), descritta -in [Vendite](Vendite). +Dei file lunghi l'anteprima mostra l'inizio (200 righe, 200.000 caratteri) e lo dice. Gli altri formati si scaricano; +PDF e immagini si aprono anche in una nuova finestra del browser. + +### Anteprima di stampa + +![025 · Anteprima di stampa](https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/raw/branch/main/docs/mockups/thumbs/025-anteprima-stampa-pdf.png) +*Mockup 025 — anteprima di stampa di una fattura in formato A4 (anteprima ridotta).* + +`Ctrl+P` o l'icona **Stampa** del documento aprono in una scheda l'**anteprima di stampa**: il documento come foglio +A4, con ingrandimento al 75, 100 o 125%. In alto: + +- **Stampa** — la stampa del browser, che stampa solo il foglio (non menu e barre); +- **Apri PDF** e **Scarica PDF** — il PDF prodotto da Khaemhat, senza salvarlo fra gli allegati; +- **Salva come allegato** — salva il PDF fra gli allegati del documento come nuova versione. + +Modello di stampa, copie e lingua arrivano con i documenti di vendita ([Vendite](Vendite)). ## Cestino -Quando un documento viene cancellato, i suoi allegati non spariscono subito: restano nel **cestino dell'azienda per -30 giorni** e possono essere recuperati in quel periodo; poi vengono eliminati definitivamente. La maschera di -consultazione del cestino sarà definita in sviluppo. +Quando un allegato viene spostato nel cestino, o quando viene cancellato il suo documento, il file non sparisce +subito: resta nel **cestino dell'azienda per 30 giorni** e poi viene eliminato definitivamente da un'attività +programmata. In fondo al pannello degli allegati, la sezione **Nel cestino** elenca i file del documento +che sono nel cestino, con la data in cui saranno eliminati e il pulsante **Ripristina** (serve +`attachments.delete`). ## Limiti e archiviazione @@ -119,8 +142,10 @@ consultazione del cestino sarà definita in sviluppo. ## Permessi e licenza -Gli allegati sono nel modulo **CORE**. Chi può leggere un documento ne vede gli allegati; caricare richiede il -permesso di modifica del documento; cancellare richiede `attachments.delete`. Gli allegati sono raggiungibili anche +Gli allegati sono nel modulo **CORE**. Vedere e scaricare richiede `attachments.read`; caricare, generare e bloccare +richiede `attachments.write`; spostare nel cestino e ripristinare richiede `attachments.delete`. Un utente aziendale +vede solo gli allegati della propria azienda. I file si scaricano solo dopo l'accesso: un indirizzo copiato non +funziona per chi non è collegato. Gli allegati sono raggiungibili anche dalle API (download e caricamento su un documento, modulo API; vedi [API e MCP](API-e-MCP)). ## Domande frequenti diff --git a/src/Khaemhat.Application/Audit/AuditTrailService.cs b/src/Khaemhat.Application/Audit/AuditTrailService.cs new file mode 100644 index 0000000..ddc18cf --- /dev/null +++ b/src/Khaemhat.Application/Audit/AuditTrailService.cs @@ -0,0 +1,103 @@ +using System.Text.Json; +using Khaemhat.Application.Security; +using Khaemhat.Core.Instance; +using Khaemhat.Data; + +namespace Khaemhat.Application.Audit; + +/// A changed field in the history of a record. +/// The field name. +/// The old value as text; when empty. +/// The new value as text; when empty. +public sealed record AuditChange(string Field, string? Before, string? After); + +/// A row of the history of a record (the Storico tab, KhAuditList). +/// The row. +/// When (UTC). +/// What happened. +/// Who did it. +/// The changed fields. +public sealed record AuditItem(long Id, DateTime At, AuditAction Action, string? UserName, IReadOnlyList Changes); + +/// Reads the history written by for the interface (SPEC §7.4). +/// The units of work. +/// The permissions. +public sealed class AuditTrailService(IUnitOfWorkFactory factory, PermissionService permissions) +{ + /// The most rows shown. + public const int MaxItems = 200; + + /// The history of a record, newest first. + /// Who asks. + /// The company. + /// The entity, as written by the audit trail (the type name, such as Attachment). + /// The record. + /// The permission that lets the actor read the record. + /// Cancellation. + /// At most rows. + public async Task> HistoryAsync( + Actor actor, string companyCode, string entity, string entityId, string readPermission, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = CompanyCodes.Normalize(companyCode); + if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, company, StringComparison.Ordinal)) + { + throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company."); + } + + await permissions.DemandAsync(actor, readPermission, cancellationToken).ConfigureAwait(false); + await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var rows = await AuditTrail.HistoryAsync(unitOfWork, entity, entityId, cancellationToken).ConfigureAwait(false); + return [.. rows.Take(MaxItems).Select(Item)]; + } + + /// A row of the history, with the changes read from their JSON. + /// The row. + /// The item. + public static AuditItem Item(AuditEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + var action = Enum.TryParse(entry.Action, out var parsed) ? parsed : AuditAction.Update; + return new AuditItem(entry.Id, entry.At, action, entry.UserName, Changes(entry.Diff)); + } + + private static List Changes(string? diff) + { + var changes = new List(); + if (string.IsNullOrWhiteSpace(diff)) + { + return changes; + } + + try + { + using var document = JsonDocument.Parse(diff); + if (document.RootElement.ValueKind != JsonValueKind.Object) + { + return changes; + } + + foreach (var field in document.RootElement.EnumerateObject()) + { + var values = field.Value.ValueKind == JsonValueKind.Array ? field.Value.EnumerateArray().ToList() : []; + changes.Add(new AuditChange(field.Name, Text(values.ElementAtOrDefault(0)), Text(values.ElementAtOrDefault(1)))); + } + } + catch (JsonException) + { + // A row written by hand or damaged: show the action without the fields. + } + + return changes; + } + + private static string? Text(JsonElement value) => value.ValueKind switch + { + JsonValueKind.Undefined or JsonValueKind.Null => null, + JsonValueKind.String => value.GetString() is { Length: > 0 } text ? text : null, + JsonValueKind.True => "true", + JsonValueKind.False => "false", + JsonValueKind.Number => value.GetRawText(), + _ => value.GetRawText(), + }; +} diff --git a/src/Khaemhat.Application/Files/FilePreviews.cs b/src/Khaemhat.Application/Files/FilePreviews.cs new file mode 100644 index 0000000..5850d8a --- /dev/null +++ b/src/Khaemhat.Application/Files/FilePreviews.cs @@ -0,0 +1,355 @@ +using System.Globalization; +using System.IO.Compression; +using System.Text; +using System.Xml; + +namespace Khaemhat.Application.Files; + +/// What the preview of a text or table file shows (mockup 024: XML, CSV, XLSX). +/// The kind of preview. +/// The text (XML, plain text), possibly cut. +/// The cells (CSV, XLSX), possibly cut. +/// Whether the file goes on after what is shown. +public sealed record FilePreview(AttachmentPreview Kind, string? Text, IReadOnlyList>? Rows, bool Truncated) +{ + /// The most characters of text shown. + public const int MaxChars = 200_000; + + /// The most rows of a table shown. + public const int MaxRows = 200; + + /// The most columns of a table shown. + public const int MaxColumns = 40; + + /// Reads the preview of a file; PDF and images are shown by the browser and give no text. + /// The kind, from the media type. + /// The content, readable. + /// The culture for numbers of spreadsheets. + /// Cancellation. + /// The preview; with neither text nor rows when the file cannot be read. + public static async Task 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 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 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); + } + + /// Splits CSV text into cells: separator ; or , (the more frequent in the first line), quotes as RFC 4180. + /// The text. + /// Whether there were more rows than . + /// The rows. + public static List> 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>(); + var row = new List(); + 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 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 SharedStrings(ZipArchiveEntry entry) + { + var strings = new List(); + 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> Sheet(ZipArchiveEntry entry, List shared, CultureInfo culture, out bool truncated) + { + var rows = new List>(); + truncated = false; + using var reader = Reader(entry); + List? 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 element, leaving the reader on its end. + private static string Cell(XmlReader reader, string? type, List 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; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor b/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor index 3ea302b..82871fb 100644 --- a/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor +++ b/src/Khaemhat.Web/Components/Pages/Dev/SampleDocumentPage.razor @@ -3,9 +3,12 @@ @inherits DocumentPage @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. *@ @if (!Environment.IsDevelopment() || Record is null) @@ -65,6 +68,14 @@ else break; + case TabIds.Attachments: +
+ break; + + case TabIds.History: +
+ break; + default:

@T["Pages.Catalog.TabPlaceholder"]

break; @@ -72,13 +83,22 @@ else + + + + } @code { + /// The test document the attachments belong to. + public const long SampleId = 1; + private int _saved; + private int _attachments; + private bool _drawer; private KhLinesGrid? _lines; private SampleLine? _lookupLine; private TaskCompletionSource? _lookupDone; @@ -155,7 +175,7 @@ else } /// - public override IReadOnlyList Tabs => Record is null ? [] : StandardTabs(attachments: 2, links: 1); + public override IReadOnlyList Tabs => Record is null ? [] : StandardTabs(attachments: _attachments, links: 1); /// public override bool IsReadOnly => Record?.Issued == true; @@ -167,7 +187,7 @@ else protected override string? NewUrl => "sviluppo/documento"; /// - protected override int? AttachmentCount => 2; + protected override int? AttachmentCount => _attachments; /// protected override bool CanMove => true; @@ -187,6 +207,51 @@ else Record = CatalogSamples.Document(Today); } + /// + 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); + } + } + + /// + protected override Task AttachmentsAsync() + { + // Toolbar commands are plain callbacks: render the page for the panel. + _drawer = !_drawer; + StateHasChanged(); + return Task.CompletedTask; + } + + /// + 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 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, + }; + /// protected override IEnumerable ContextActions() { diff --git a/src/Khaemhat.Web/Components/Pages/Dev/SamplePrintPage.razor b/src/Khaemhat.Web/Components/Pages/Dev/SamplePrintPage.razor new file mode 100644 index 0000000..4878470 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/Dev/SamplePrintPage.razor @@ -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. *@ + + +@if (!Environment.IsDevelopment()) +{ +

@T["Pages.Catalog.DevOnly"]

+} +else +{ +
+
+
@T["Pages.Print.Crumb"] › @T["Pages.Print.Title"]
+

@T.Format("Pages.Print.Heading", DemoDocument.Title, Number)

+
+
+ + +
+
+
@(Session.Company?.Name ?? Company)
+
@T.Format("Pages.Print.CompanyLine", Company)
+
+
+
@DemoDocument.Title
+
@T.Format("Pages.Print.Number", Number, T.Date(Today))
+
+
+

@T.Format("Pages.Print.Intro", Company, Session.Actor?.UserName ?? string.Empty)

+ + + + @for (var i = 0; i < DemoDocument.Headers.Count; i++) + { + + } + + + + @foreach (var line in DemoDocument.Lines) + { + + + + + + + + } + + + + + + + +
@DemoDocument.Headers[i]
@line.Code@line.Description@line.Quantity.ToString("#,##0.##", T.Culture)@DemoDocument.Euro(line.UnitPrice, T.Culture)@DemoDocument.Euro(DemoDocument.Amount(line), T.Culture)
@T["Pages.Print.Total"]@DemoDocument.Euro(DemoDocument.Total, T.Culture)
+

@T["Pages.Print.Footer"]

+
+} + +@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); + + /// + 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; + } + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhAttachmentList.razor b/src/Khaemhat.Web/Components/Ui/KhAttachmentList.razor new file mode 100644 index 0000000..45a64ea --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhAttachmentList.razor @@ -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. *@ +
+ @if (Company is null) + { +
@T["Ui.Attachments.NoCompany"]
+ } + else + { +
@T["Ui.Attachments.Intro"]
+ +
+ @T.Format("Ui.Attachments.Count", _items.Count) + + +
+ + @if (!_loaded) + { +

@T["Common.Loading"]

+ } + else if (_items.Count == 0) + { +

@T["Ui.Attachments.None"]

+ } + else + { +
    + @foreach (var item in _items) + { +
  • + + + + @item.FileName + @if (item.Locked) + { + + } + + @Meta(item) + + + @if (item.Preview != AttachmentPreview.None) + { + + } + + @if (CanWrite && !item.Locked) + { + + } + @if (CanDelete && !item.Locked) + { + + } + +
  • + } +
+ } + +
+ @if (CanWrite) + { + + } + @if (_items.Count > 0) + { + @T["Ui.Attachments.Zip"] + } +
+ @if (CanWrite && _limits is { } limits) + { +

@T.Format("Ui.Attachments.Limit", Size(limits.MaxBytes))

+ } + + @if (Generators.Count > 0) + { +
@T["Ui.Attachments.Generate"]
+
    + @foreach (var generator in Generators) + { + var existing = _items.FirstOrDefault(i => i.IsLatest && i.GeneratedBy == generator.Code); +
  • + + + @T[generator.TitleKey] + @(existing is null ? T["Ui.Attachments.NotGenerated"] : T.Format("Ui.Attachments.Generated", existing.VersionLabel, When(existing.CreatedAt))) + + @if (CanWrite) + { + + } +
  • + } +
+ } + + @if (_trash.Count > 0) + { +
@T["Ui.Attachments.Trash"]
+
    + @foreach (var item in _trash) + { +
  • + + + @item.FileName + @T.Format("Ui.Attachments.TrashedOn", When(item.DeletedAt ?? item.CreatedAt), PurgeDate(item)) + + @if (CanDelete) + { + + } +
  • + } +
+ } + } +
+ + + +@code { + private List _items = []; + private List _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; + + /// The entity of the record, such as sale.document. + [Parameter, EditorRequired] + public string Entity { get; set; } = string.Empty; + + /// The record. + [Parameter, EditorRequired] + public long EntityId { get; set; } + + /// Called with the number of attachments in use after every change (the counter on the toolbar). + [Parameter] + public EventCallback 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 Generators => Company is null ? [] : Generation.AvailableFor(Entity); + + /// + 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 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"; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhAuditList.razor b/src/Khaemhat.Web/Components/Ui/KhAuditList.razor new file mode 100644 index 0000000..fd05f44 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhAuditList.razor @@ -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) +{ +

@T["Common.Loading"]

+} +else if (Items.Count == 0) +{ +

@T["Ui.Audit.None"]

+} +else +{ +
    + @foreach (var item in Items) + { +
  1. + +
    +
    + @T.Format(ActionKey(item.Action), item.UserName ?? T["Ui.Audit.Someone"]) + · @T.DateTime(item.At, TimeZoneInfo.Local) +
    + @if (item.Changes.Count > 0) + { + + + + + + @foreach (var change in item.Changes) + { + + + + + + } + +
    @T["Ui.Audit.Field"]@T["Ui.Audit.Before"]@T["Ui.Audit.After"]
    @(FieldName?.Invoke(change.Field) ?? change.Field)@(change.Before ?? "-")@(change.After ?? "-")
    + } +
    +
  2. + } +
+} + +@code { + /// The rows, newest first; while loading. + [Parameter] + public IReadOnlyList? Items { get; set; } + + /// The label of a field, when the page has one (the field name otherwise). + [Parameter] + public Func? 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, + }; +} diff --git a/src/Khaemhat.Web/Components/Ui/KhFilePreview.razor b/src/Khaemhat.Web/Components/Ui/KhFilePreview.razor new file mode 100644 index 0000000..71fe361 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhFilePreview.razor @@ -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. *@ + + + @if (Attachment is { } item) + { +
+ @switch (item.Preview) + { + case AttachmentPreview.Pdf: + + break; + case AttachmentPreview.Image: + @item.FileName + break; + default: + if (_content is null) + { +

@T["Common.Loading"]

+ } + else if (_content.Rows is { } rows) + { +
+ + + @foreach (var row in rows) + { + + @foreach (var cell in row) + { + + } + + } + +
@cell
+
+ } + else if (_content.Text is { } text) + { +
@text
+ } + else + { +
@T["Ui.Preview.Unreadable"]
+ } + + @if (_content?.Truncated == true) + { +

@T["Ui.Preview.Truncated"]

+ } + + break; + } +
+ } +
+ +
+ +@code { + private FilePreview? _content; + private long? _loadedId; + + /// The attachment to show; keeps the dialog closed. + [Parameter] + public AttachmentView? Attachment { get; set; } + + /// Closes the dialog. + [Parameter] + public EventCallback OnClose { get; set; } + + /// + 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); + } +} diff --git a/src/Khaemhat.Web/Components/Ui/KhPrintPreview.razor b/src/Khaemhat.Web/Components/Ui/KhPrintPreview.razor new file mode 100644 index 0000000..c6292d3 --- /dev/null +++ b/src/Khaemhat.Web/Components/Ui/KhPrintPreview.razor @@ -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. *@ +
+
+ + @if (PdfUrl is not null) + { + @T["Ui.Print.OpenPdf"] + } + @if (PdfDownloadUrl is not null) + { + @T["Ui.Print.DownloadPdf"] + } + @if (OnSaveAttachment.HasDelegate) + { + + } + +
+ @foreach (var zoom in Zooms) + { + + } +
+
+
+
+ @ChildContent +
+
+
+ +@code { + private static readonly int[] Zooms = [75, 100, 125]; + private int _zoom = 100; + + /// The sheet: what is printed. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// The address of the PDF opened in the browser, if there is one. + [Parameter] + public string? PdfUrl { get; set; } + + /// The address that downloads the PDF, if there is one. + [Parameter] + public string? PdfDownloadUrl { get; set; } + + /// Attaches the PDF to the record; without it the button is not shown. + [Parameter] + public EventCallback OnSaveAttachment { get; set; } + + /// Whether the attachment is being saved. + [Parameter] + public bool Saving { get; set; } + + private async Task PrintAsync() + { + try + { + await JS.InvokeVoidAsync("print"); + } + catch (JSDisconnectedException) + { + // The window is gone. + } + } +} diff --git a/src/Khaemhat.Web/Hosting/FileEndpoints.cs b/src/Khaemhat.Web/Hosting/FileEndpoints.cs new file mode 100644 index 0000000..a488c62 --- /dev/null +++ b/src/Khaemhat.Web/Hosting/FileEndpoints.cs @@ -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; + +/// +/// 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. +/// +public static class FileEndpoints +{ + /// The content security policy of a file opened in the browser: framed by this site only, no scripts. + public const string InlinePolicy = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; object-src 'self'; frame-ancestors 'self'"; + + /// The base address. + public const string BasePath = "/files"; + + /// The address of an attachment, opened in the browser when it can be. + /// The attachment. + /// The address relative to the application. + public static string View(long id) => BasePath[1..] + "/" + id.ToString(CultureInfo.InvariantCulture); + + /// The address that downloads an attachment. + /// The attachment. + /// The address relative to the application. + public static string Download(long id) => View(id) + "?download=1"; + + /// The address of the ZIP with all the attachments of a record. + /// The entity. + /// The record. + /// The address relative to the application. + public static string Zip(string entity, long entityId) => + BasePath[1..] + "/zip?entity=" + Uri.EscapeDataString(entity) + "&id=" + entityId.ToString(CultureInfo.InvariantCulture); + + /// The address of a file generated on the fly, without attaching it. + /// The entity. + /// The record. + /// The generator code. + /// Whether to download it instead of opening it. + /// The address relative to the application. + 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); + + /// Whether a media type may be shown by the browser instead of downloaded. + /// The media type. + /// for PDF and common images. + public static bool OpensInBrowser(string mime) => MediaTypes.PreviewOf(mime) is AttachmentPreview.Pdf or AttachmentPreview.Image; + + /// Maps the addresses. + /// The application. + 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 RunAsync(HttpContext context, Func> 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); + } +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs index 260b160..2fb6022 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs @@ -111,6 +111,7 @@ public static class KhaemhatApp app.MapSignOut(); app.MapCompanySwitch(); app.MapHelp(); + app.MapFiles(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 8e30840..487119e 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -139,6 +139,7 @@ internal static class KhaemhatServices // History of the records and scheduled tasks. services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Khaemhat.Web/Hosting/Middleware.cs b/src/Khaemhat.Web/Hosting/Middleware.cs index 9794813..0d38591 100644 --- a/src/Khaemhat.Web/Hosting/Middleware.cs +++ b/src/Khaemhat.Web/Hosting/Middleware.cs @@ -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"; diff --git a/src/Khaemhat.Web/Resources/it-IT/Files.json b/src/Khaemhat.Web/Resources/it-IT/Files.json new file mode 100644 index 0000000..90ea636 --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/Files.json @@ -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)" + } + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Pages.json b/src/Khaemhat.Web/Resources/it-IT/Pages.json index 33bdc39..9694e51 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Pages.json +++ b/src/Khaemhat.Web/Resources/it-IT/Pages.json @@ -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." } } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Ui.json b/src/Khaemhat.Web/Resources/it-IT/Ui.json index 47078a0..718a871 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Ui.json +++ b/src/Khaemhat.Web/Resources/it-IT/Ui.json @@ -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" } } } diff --git a/src/Khaemhat.Web/Ui/FileSizes.cs b/src/Khaemhat.Web/Ui/FileSizes.cs new file mode 100644 index 0000000..fe79a6e --- /dev/null +++ b/src/Khaemhat.Web/Ui/FileSizes.cs @@ -0,0 +1,28 @@ +using System.Globalization; + +namespace Khaemhat.Web.Ui; + +/// File sizes as people read them: 840 B, 184 KB, 1,2 MB. +public static class FileSizes +{ + private static readonly string[] Units = ["B", "KB", "MB", "GB", "TB"]; + + /// Formats a size in bytes (1 KB = 1024 B). + /// The size. + /// The culture of the decimal separator. + /// The text. + 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]; + } +} diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index d978806..b9e6b7a 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -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; } +} diff --git a/tests/Khaemhat.Web.Tests/Files/AttachmentUiTests.cs b/tests/Khaemhat.Web.Tests/Files/AttachmentUiTests.cs new file mode 100644 index 0000000..94c815c --- /dev/null +++ b/tests/Khaemhat.Web.Tests/Files/AttachmentUiTests.cs @@ -0,0 +1,143 @@ +using System.Globalization; +using System.Net; +using System.Text; +using Khaemhat.Application.Audit; +using Khaemhat.Application.Files; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.Security; +using Khaemhat.Web.Hosting; +using Khaemhat.Web.Tests.Hosting; +using Khaemhat.Web.Ui; +using Microsoft.Extensions.DependencyInjection; + +namespace Khaemhat.Web.Tests.Files; + +/// What the interface of the attachments needs (issue #34, mockup 024-025): previews, sizes, texts, history, addresses. +[TestClass] +public sealed class AttachmentUiTests +{ + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null); + + [TestMethod] + public void Csv_Preview_ReadsSeparatorQuotesAndLimits() + { + var rows = FilePreview.Csv("Codice;Descrizione;Importo\r\nA1;\"Vite; \"\"zincata\"\"\";1,25\r\nA2;\"riga\nsu due\";3\n", out var truncated); + + Assert.IsFalse(truncated); + Assert.HasCount(3, rows); + CollectionAssert.AreEqual(new[] { "Codice", "Descrizione", "Importo" }, rows[0].ToList()); + CollectionAssert.AreEqual(new[] { "A1", "Vite; \"zincata\"", "1,25" }, rows[1].ToList()); + Assert.AreEqual("riga\nsu due", rows[2][1]); + CollectionAssert.AreEqual(new[] { "a", "b" }, FilePreview.Csv("a,b", out _)[0].ToList()); + + var many = FilePreview.Csv(string.Concat(Enumerable.Repeat("x;y\n", FilePreview.MaxRows + 5)), out var cut); + Assert.IsTrue(cut); + Assert.HasCount(FilePreview.MaxRows, many); + } + + [TestMethod] + public async Task Xlsx_Preview_ReadsWhatTheGeneratorWrites() + { + var generator = new DemoXlsxGenerator(); + using var content = new MemoryStream(); + await generator.GenerateAsync(new FileGenerationContext(Root, "DEMO", DemoDocument.Entity, 3, Italian, new DateTime(2026, 11, 11, 10, 0, 0, DateTimeKind.Utc)), content, CancellationToken.None); + content.Position = 0; + + var preview = await FilePreview.ReadAsync(AttachmentPreview.Xlsx, content, Italian); + + Assert.IsNotNull(preview.Rows); + var cells = preview.Rows.SelectMany(r => r).ToList(); + foreach (var header in DemoDocument.Headers) + { + CollectionAssert.Contains(cells, header); + } + + CollectionAssert.Contains(cells, "PROVA-001"); + Assert.IsTrue(preview.Rows.Any(r => r.Contains("PROVA-003") && r.Any(c => c.Contains("25,5", StringComparison.Ordinal))), "Numbers in Italian form."); + } + + [TestMethod] + public async Task Text_Preview_IsCut_AndBrokenFilesSayNothing() + { + using var big = new MemoryStream(Encoding.UTF8.GetBytes(new string('x', FilePreview.MaxChars + 10))); + var text = await FilePreview.ReadAsync(AttachmentPreview.Xml, big, Italian); + Assert.IsTrue(text.Truncated); + Assert.AreEqual(FilePreview.MaxChars, text.Text!.Length); + + using var broken = new MemoryStream(Encoding.UTF8.GetBytes("not a zip")); + var xlsx = await FilePreview.ReadAsync(AttachmentPreview.Xlsx, broken, Italian); + Assert.IsNull(xlsx.Rows); + Assert.IsNull(xlsx.Text); + } + + [TestMethod] + [DataRow(0L, "0 B")] + [DataRow(840L, "840 B")] + [DataRow(1536L, "1,5 KB")] + [DataRow(188_416L, "184 KB")] + [DataRow(26_214_400L, "25 MB")] + public void Sizes_AreReadable(long bytes, string expected) => Assert.AreEqual(expected, FileSizes.Format(bytes, Italian)); + + [TestMethod] + public void EveryErrorAndGenerator_HasItsText() + { + var texts = JsonTextProvider.FromAssembly(typeof(FileEndpoints).Assembly, Italian); + string[] codes = + [ + AttachmentService.NotFoundError, AttachmentService.LockedError, AttachmentService.TooLargeError, AttachmentService.QuotaError, + AttachmentService.RejectedError, AttachmentService.InvalidOwnerError, AttachmentService.EmptyError, FileGenerationService.UnknownGeneratorError, + ]; + IFileGenerator[] generators = [new DemoPdfGenerator(), new DemoCsvGenerator(), new DemoXlsxGenerator()]; + + var missing = codes.Concat(generators.Select(g => g.TitleKey)).Where(k => !texts.Contains(k)).ToList(); + + Assert.IsEmpty(missing, string.Join(", ", missing)); + } + + [TestMethod] + public void Addresses_OpenOnlySafeTypesInTheBrowser() + { + Assert.AreEqual("files/42", FileEndpoints.View(42)); + Assert.AreEqual("files/42?download=1", FileEndpoints.Download(42)); + Assert.AreEqual("files/zip?entity=demo.document&id=7", FileEndpoints.Zip("demo.document", 7)); + Assert.AreEqual("files/generate?entity=demo.document&id=7&generator=demo.test-pdf&download=1", FileEndpoints.Generated("demo.document", 7, "demo.test-pdf", true)); + Assert.IsTrue(FileEndpoints.OpensInBrowser(MediaTypes.Pdf)); + Assert.IsTrue(FileEndpoints.OpensInBrowser("image/png")); + Assert.IsFalse(FileEndpoints.OpensInBrowser("image/svg+xml"), "SVG can carry scripts."); + Assert.IsFalse(FileEndpoints.OpensInBrowser("text/html")); + Assert.IsFalse(FileEndpoints.OpensInBrowser(MediaTypes.Xml)); + } + + [TestMethod] + public async Task Files_NeedASignedInUser_AndTheHistoryShowsTheUpload() + { + var (app, address, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + var attachments = app.Services.GetRequiredService(); + var added = await attachments.UploadAsync(Root, company, DemoDocument.Entity, 5, "nota.txt", "text/plain", new MemoryStream(Encoding.UTF8.GetBytes("ciao"))); + + using var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = address }; + foreach (var path in new[] { "/" + FileEndpoints.View(added.Id), "/" + FileEndpoints.Zip(DemoDocument.Entity, 5), "/" + FileEndpoints.Generated(DemoDocument.Entity, 5, DemoPdfGenerator.GeneratorCode) }) + { + using var response = await client.GetAsync(new Uri(path, UriKind.Relative)); + Assert.AreNotEqual(HttpStatusCode.OK, response.StatusCode, path); + Assert.AreNotEqual("ciao", await response.Content.ReadAsStringAsync(), path); + } + + var history = await app.Services.GetRequiredService().HistoryAsync( + Root, company, "Attachment", added.Id.ToString(CultureInfo.InvariantCulture), AttachmentService.ReadPermission); + var insert = history.Single(); + Assert.AreEqual(AuditAction.Insert, insert.Action); + Assert.AreEqual(TestInstance.SuperUser, insert.UserName); + Assert.IsTrue(insert.Changes.Any(c => c.Field == "Name" && c.Before is null && c.After == "nota.txt")); + + var stranger = new Actor("anna", UserLevel.Standard, null, 999, "ALTRA"); + await Assert.ThrowsExactlyAsync(() => app.Services.GetRequiredService().HistoryAsync( + stranger, company, "Attachment", added.Id.ToString(CultureInfo.InvariantCulture), AttachmentService.ReadPermission)); + await app.StopAsync(); + } + } +}