Documents need attachments and generated files (SPEC 9.4) before the UI of M3 can show them, and the spec forbids external libraries for PDF and spreadsheets. - VolumeFileStore keeps files under <data>/files/<COMPANY>/<yyyy>/<guid>, writing a .part file in the same folder with size limit and SHA-256, then quota and scanner checks (IFileScanner hook, no-op by default). - attachments table (migration 007) with kind, version series, lock, trash and the uploading user; AttachmentService uploads, adds generated files as the next version, lists, opens, zips, locks, trashes, restores and purges after 30 days (new system job system.attachments-trash). - FileGenerationService runs IFileGenerator implementations into the store; three generators for the fictitious test document (PDF, CSV, XLSX). - CsvWriter (Italian Excel defaults, formula-injection guard), XlsxWriter, ZipStreamWriter and PdfWriter (standard Type1 fonts, WinAnsi, AFM widths, JPEG, Flate, xref) only write asynchronously, so they can stream to an HTTP response. - ADR 0021 records versioning, storage layout, PDF scope and CSV defaults. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
239 lines
10 KiB
C#
239 lines
10 KiB
C#
using System.Globalization;
|
||
using Khaemhat.Infrastructure.Files;
|
||
|
||
namespace Khaemhat.Application.Files;
|
||
|
||
/// <summary>
|
||
/// The <i>documento di prova</i> of issue #34: a clearly fictitious document (entity <see cref="Entity"/>) used to try
|
||
/// attachments, generation, versions and print preview before the real documents exist (M5). Every value is invented.
|
||
/// </summary>
|
||
public static class DemoDocument
|
||
{
|
||
/// <summary>The entity of the test document.</summary>
|
||
public const string Entity = "demo.document";
|
||
|
||
/// <summary>The title printed on the test document.</summary>
|
||
public const string Title = "Documento di prova";
|
||
|
||
/// <summary>The fictitious lines: code, description, quantity, unit price.</summary>
|
||
public static IReadOnlyList<(string Code, string Description, decimal Quantity, decimal UnitPrice)> Lines { get; } =
|
||
[
|
||
("PROVA-001", "Articolo di prova – vite inventata", 10m, 1.25m),
|
||
("PROVA-002", "Servizio fittizio di consulenza (non reale)", 2m, 480m),
|
||
("PROVA-003", "Materiale d'esempio: cavo €uro-test 3×1,5", 25.5m, 3.9m),
|
||
("PROVA-004", "Riga con accenti: perché, città, più, così", 1m, 1234.56m),
|
||
("PROVA-005", "Sconto finto", 1m, -50m),
|
||
];
|
||
|
||
/// <summary>The headers of the line table.</summary>
|
||
public static IReadOnlyList<string> Headers { get; } = ["Codice", "Descrizione", "Quantità", "Prezzo unitario", "Importo"];
|
||
|
||
/// <summary>The amount of a line.</summary>
|
||
/// <param name="line">The line.</param>
|
||
/// <returns>Quantity times unit price, rounded to cents.</returns>
|
||
public static decimal Amount((string Code, string Description, decimal Quantity, decimal UnitPrice) line) =>
|
||
Math.Round(line.Quantity * line.UnitPrice, 2, MidpointRounding.AwayFromZero);
|
||
|
||
/// <summary>The total of the lines.</summary>
|
||
public static decimal Total => Lines.Sum(Amount);
|
||
|
||
/// <summary>An amount in euro as Italians write it: <c>€ 1.234,56</c>.</summary>
|
||
/// <param name="value">The amount.</param>
|
||
/// <param name="culture">The culture (it-IT).</param>
|
||
/// <returns>The text.</returns>
|
||
public static string Euro(decimal value, CultureInfo culture) =>
|
||
(value < 0 ? "-€ " : "€ ") + Math.Abs(value).ToString("N2", culture);
|
||
|
||
/// <summary>The file name stem for a record.</summary>
|
||
/// <param name="context">The record.</param>
|
||
/// <returns>For example <c>documento-di-prova-7</c>.</returns>
|
||
public static string Stem(FileGenerationContext context)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(context);
|
||
return "documento-di-prova-" + context.EntityId.ToString(CultureInfo.InvariantCulture);
|
||
}
|
||
}
|
||
|
||
/// <summary>The test PDF of the test document: title, a paragraph and the table of lines with amounts aligned right.</summary>
|
||
public sealed class DemoPdfGenerator : IFileGenerator
|
||
{
|
||
/// <summary>The generator code.</summary>
|
||
public const string GeneratorCode = "demo.test-pdf";
|
||
|
||
/// <inheritdoc />
|
||
public string Code => GeneratorCode;
|
||
|
||
/// <inheritdoc />
|
||
public string TitleKey => "files.generators.demo_pdf";
|
||
|
||
/// <inheritdoc />
|
||
public string MediaType => PdfWriter.MediaType;
|
||
|
||
/// <inheritdoc />
|
||
public string Extension => ".pdf";
|
||
|
||
/// <inheritdoc />
|
||
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||
|
||
/// <inheritdoc />
|
||
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + Extension;
|
||
|
||
/// <inheritdoc />
|
||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(context);
|
||
var culture = context.Culture;
|
||
var accent = PdfColor.FromHex("#1F5F8B");
|
||
var muted = PdfColor.Gray(110);
|
||
var info = new PdfDocumentInfo
|
||
{
|
||
Title = DemoDocument.Title + " n. " + context.EntityId.ToString(CultureInfo.InvariantCulture),
|
||
Author = context.CompanyCode,
|
||
Subject = "Documento fittizio per provare la generazione dei file",
|
||
CreationDate = new DateTimeOffset(DateTime.SpecifyKind(context.Now, DateTimeKind.Utc)),
|
||
};
|
||
|
||
await using var pdf = new PdfWriter(output, info, leaveOpen: true);
|
||
var page = await pdf.AddPageAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
|
||
const double left = 50;
|
||
var right = page.Width - 50;
|
||
var y = page.Height - 70;
|
||
|
||
page.DrawText(DemoDocument.Title, left, y, PdfFont.HelveticaBold, 20, accent);
|
||
page.DrawTextRight("n. " + context.EntityId.ToString(CultureInfo.InvariantCulture) + " del " + context.Now.ToString("d", culture), right, y, PdfFont.Helvetica, 10, muted);
|
||
y -= 12;
|
||
page.DrawLine(left, y, right, y, 1, accent);
|
||
y -= 22;
|
||
y = page.DrawParagraph(
|
||
"Questo è un documento di prova generato da Khaemhat: azienda " + context.CompanyCode + ", generato da " + context.Actor.UserName
|
||
+ ". Righe, prezzi e importi sono inventati e servono solo a provare stampa, allegati e versioni (v1, v2…).",
|
||
left, y, right - left, PdfFont.Helvetica, 10, 13);
|
||
y -= 16;
|
||
|
||
// Table: code, description, quantity, unit price, amount (the last three aligned right).
|
||
double[] edges = [left, left + 75, right - 205, right - 135, right - 65, right];
|
||
page.DrawRectangle(left, y - 6, right - left, 18, fill: PdfColor.Gray(235));
|
||
for (var i = 0; i < DemoDocument.Headers.Count; i++)
|
||
{
|
||
if (i < 2)
|
||
{
|
||
page.DrawText(DemoDocument.Headers[i], edges[i] + 4, y, PdfFont.HelveticaBold, 9);
|
||
}
|
||
else
|
||
{
|
||
page.DrawTextRight(DemoDocument.Headers[i], edges[i + 1] - 4, y, PdfFont.HelveticaBold, 9);
|
||
}
|
||
}
|
||
|
||
y -= 20;
|
||
foreach (var line in DemoDocument.Lines)
|
||
{
|
||
page.DrawText(line.Code, edges[0] + 4, y, PdfFont.Courier, 9);
|
||
page.DrawText(PdfTextLayout.Fit(line.Description, PdfFont.Helvetica, 9, edges[2] - edges[1] - 8), edges[1] + 4, y, PdfFont.Helvetica, 9);
|
||
page.DrawTextRight(line.Quantity.ToString("#,##0.##", culture), edges[3] - 4, y, PdfFont.Helvetica, 9);
|
||
page.DrawTextRight(DemoDocument.Euro(line.UnitPrice, culture), edges[4] - 4, y, PdfFont.Helvetica, 9);
|
||
page.DrawTextRight(DemoDocument.Euro(DemoDocument.Amount(line), culture), edges[5] - 4, y, PdfFont.Helvetica, 9);
|
||
y -= 6;
|
||
page.DrawLine(left, y, right, y, 0.25, PdfColor.Gray(200));
|
||
y -= 12;
|
||
}
|
||
|
||
y -= 4;
|
||
page.DrawText("Totale", edges[3] + 4, y, PdfFont.HelveticaBold, 11);
|
||
page.DrawTextRight(DemoDocument.Euro(DemoDocument.Total, culture), right - 4, y, PdfFont.HelveticaBold, 11, accent);
|
||
|
||
page.DrawText("Documento fittizio – nessun valore fiscale", left, 40, PdfFont.HelveticaOblique, 8, muted);
|
||
page.DrawTextRight("Pagina 1", right, 40, PdfFont.Helvetica, 8, muted);
|
||
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
/// <summary>The lines of the test document as CSV (Italian Excel: <c>;</c>, decimal comma, BOM).</summary>
|
||
public sealed class DemoCsvGenerator : IFileGenerator
|
||
{
|
||
/// <summary>The generator code.</summary>
|
||
public const string GeneratorCode = "demo.test-csv";
|
||
|
||
/// <inheritdoc />
|
||
public string Code => GeneratorCode;
|
||
|
||
/// <inheritdoc />
|
||
public string TitleKey => "files.generators.demo_csv";
|
||
|
||
/// <inheritdoc />
|
||
public string MediaType => MediaTypes.Csv;
|
||
|
||
/// <inheritdoc />
|
||
public string Extension => ".csv";
|
||
|
||
/// <inheritdoc />
|
||
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||
|
||
/// <inheritdoc />
|
||
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
|
||
|
||
/// <inheritdoc />
|
||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||
{
|
||
await using var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true);
|
||
await csv.WriteRowAsync(DemoDocument.Headers, cancellationToken).ConfigureAwait(false);
|
||
foreach (var line in DemoDocument.Lines)
|
||
{
|
||
await csv.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false);
|
||
}
|
||
|
||
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||
}
|
||
}
|
||
|
||
/// <summary>The lines of the test document as an XLSX sheet with bold header and euro amounts.</summary>
|
||
public sealed class DemoXlsxGenerator : IFileGenerator
|
||
{
|
||
/// <summary>The generator code.</summary>
|
||
public const string GeneratorCode = "demo.test-xlsx";
|
||
|
||
/// <inheritdoc />
|
||
public string Code => GeneratorCode;
|
||
|
||
/// <inheritdoc />
|
||
public string TitleKey => "files.generators.demo_xlsx";
|
||
|
||
/// <inheritdoc />
|
||
public string MediaType => XlsxWriter.MediaType;
|
||
|
||
/// <inheritdoc />
|
||
public string Extension => ".xlsx";
|
||
|
||
/// <inheritdoc />
|
||
public bool Supports(string entity) => entity == DemoDocument.Entity;
|
||
|
||
/// <inheritdoc />
|
||
public string FileName(FileGenerationContext context) => DemoDocument.Stem(context) + "-righe" + Extension;
|
||
|
||
/// <inheritdoc />
|
||
public async Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken)
|
||
{
|
||
var xlsx = await XlsxWriter.CreateAsync(output, leaveOpen: true, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||
await using (xlsx.ConfigureAwait(false))
|
||
{
|
||
await xlsx.StartSheetAsync(
|
||
"Righe",
|
||
[
|
||
new XlsxColumn(DemoDocument.Headers[0], 14),
|
||
new XlsxColumn(DemoDocument.Headers[1], 48),
|
||
new XlsxColumn(DemoDocument.Headers[2], 12, XlsxFormat.TwoDecimals),
|
||
new XlsxColumn(DemoDocument.Headers[3], 16, XlsxFormat.Euro),
|
||
new XlsxColumn(DemoDocument.Headers[4], 16, XlsxFormat.Euro),
|
||
],
|
||
cancellationToken).ConfigureAwait(false);
|
||
foreach (var line in DemoDocument.Lines)
|
||
{
|
||
await xlsx.WriteRowAsync([line.Code, line.Description, line.Quantity, line.UnitPrice, DemoDocument.Amount(line)], cancellationToken).ConfigureAwait(false);
|
||
}
|
||
|
||
await xlsx.WriteRowAsync([null, "Totale", null, null, DemoDocument.Total], cancellationToken).ConfigureAwait(false);
|
||
await xlsx.CompleteAsync(cancellationToken).ConfigureAwait(false);
|
||
}
|
||
}
|
||
}
|