feat: attachments, file store and in-house PDF/CSV/XLSX/ZIP writers (#34)
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>
This commit is contained in:
1 parent
cf6f849cc1
commit
b341ade9e9
26 files changed
+5319
-2
No files matched your search
@@ -0,0 +1,310 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Files;
|
||||
|
||||
/// <summary>How numbers and dates are written in a CSV file.</summary>
|
||||
public enum CsvNumberFormat
|
||||
{
|
||||
/// <summary>Italian Excel: decimal comma (<c>1234,5</c>), dates <c>dd/MM/yyyy</c>, booleans <c>VERO</c>/<c>FALSO</c>.</summary>
|
||||
Italian = 0,
|
||||
|
||||
/// <summary>Machine readable: decimal point (<c>1234.5</c>), ISO 8601 dates, booleans <c>true</c>/<c>false</c>.</summary>
|
||||
Invariant = 1,
|
||||
}
|
||||
|
||||
/// <summary>The options of a <see cref="CsvWriter"/>. The defaults suit Excel in Italian (ADR 0021).</summary>
|
||||
public sealed record CsvOptions
|
||||
{
|
||||
/// <summary>The field separator: <c>;</c> by default, because Italian Excel uses the comma for decimals.</summary>
|
||||
public char Separator { get; init; } = ';';
|
||||
|
||||
/// <summary>Whether the file starts with the UTF-8 byte order mark, which Excel needs to read accented letters.</summary>
|
||||
public bool WriteByteOrderMark { get; init; } = true;
|
||||
|
||||
/// <summary>How numbers, dates and booleans are formatted.</summary>
|
||||
public CsvNumberFormat NumberFormat { get; init; } = CsvNumberFormat.Italian;
|
||||
|
||||
/// <summary>
|
||||
/// Whether text cells that a spreadsheet would read as a formula (starting with <c>=</c>, <c>+</c>, <c>-</c>,
|
||||
/// <c>@</c>, tab or carriage return) get a leading apostrophe (CSV injection, OWASP). Numbers are never changed.
|
||||
/// </summary>
|
||||
public bool ProtectFormulas { get; init; } = true;
|
||||
|
||||
/// <summary>The line terminator: CRLF as RFC 4180 says.</summary>
|
||||
public string NewLine { get; init; } = "\r\n";
|
||||
|
||||
/// <summary>The Italian Excel defaults.</summary>
|
||||
public static CsvOptions Italian { get; } = new();
|
||||
|
||||
/// <summary>Comma separator, invariant numbers, no byte order mark: for other programs.</summary>
|
||||
public static CsvOptions Invariant { get; } = new() { Separator = ',', NumberFormat = CsvNumberFormat.Invariant, WriteByteOrderMark = false };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes CSV files (RFC 4180) row by row (SPEC §2, §9.4). Fields with separator, quotes or line breaks are quoted and
|
||||
/// quotes doubled. Rows are buffered in memory and written to the stream when the buffer grows past a few KB: use the
|
||||
/// <c>Async</c> methods when the stream is an HTTP response, where synchronous writes are not allowed.
|
||||
/// </summary>
|
||||
/// <example>
|
||||
/// <code>
|
||||
/// await using var csv = new CsvWriter(response.Body);
|
||||
/// await csv.WriteRowAsync(["Codice", "Descrizione", "Importo"]);
|
||||
/// await csv.WriteRowAsync(["A1", "Vite M4", 12.5m]);
|
||||
/// </code>
|
||||
/// </example>
|
||||
public sealed class CsvWriter : IDisposable, IAsyncDisposable
|
||||
{
|
||||
private const int FlushThreshold = 16 * 1024;
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||
private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false);
|
||||
|
||||
private readonly Stream _output;
|
||||
private readonly bool _leaveOpen;
|
||||
private readonly StringBuilder _buffer = new();
|
||||
private bool _rowHasFields;
|
||||
private bool _preambleWritten;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Creates a writer.</summary>
|
||||
/// <param name="output">The stream that receives the file.</param>
|
||||
/// <param name="options">The options; <see langword="null"/> for <see cref="CsvOptions.Italian"/>.</param>
|
||||
/// <param name="leaveOpen">Whether to leave <paramref name="output"/> open on dispose.</param>
|
||||
public CsvWriter(Stream output, CsvOptions? options = null, bool leaveOpen = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
_output = output;
|
||||
_leaveOpen = leaveOpen;
|
||||
Options = options ?? CsvOptions.Italian;
|
||||
if (Options.Separator is '"' or '\r' or '\n')
|
||||
{
|
||||
throw new ArgumentException("The separator cannot be a quote or a line break.", nameof(options));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The options.</summary>
|
||||
public CsvOptions Options { get; }
|
||||
|
||||
/// <summary>The number of rows completed.</summary>
|
||||
public long RowCount { get; private set; }
|
||||
|
||||
/// <summary>Formats a text field: formula protection, then quoting when needed.</summary>
|
||||
/// <param name="value">The text.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>The field as written in the file.</returns>
|
||||
public static string EscapeText(string? value, CsvOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (options.ProtectFormulas && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r')
|
||||
{
|
||||
value = "'" + value;
|
||||
}
|
||||
|
||||
return Quote(value, options.Separator);
|
||||
}
|
||||
|
||||
/// <summary>Formats a value as it would be written (numbers and dates by <see cref="CsvOptions.NumberFormat"/>).</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>The field as written in the file.</returns>
|
||||
public static string FormatValue(object? value, CsvOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
var culture = options.NumberFormat == CsvNumberFormat.Italian ? Italian : CultureInfo.InvariantCulture;
|
||||
var italian = options.NumberFormat == CsvNumberFormat.Italian;
|
||||
var text = value switch
|
||||
{
|
||||
null => null,
|
||||
string s => s,
|
||||
bool b => italian ? (b ? "VERO" : "FALSO") : (b ? "true" : "false"),
|
||||
DateOnly d => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d when d.TimeOfDay == TimeSpan.Zero => d.ToString(italian ? "dd/MM/yyyy" : "yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
DateTime d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture),
|
||||
DateTimeOffset d => d.ToString(italian ? "dd/MM/yyyy HH:mm:ss" : "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture),
|
||||
decimal m => m.ToString("0.############################", culture),
|
||||
double x when double.IsFinite(x) => x.ToString("0.###############", culture),
|
||||
float x when float.IsFinite(x) => x.ToString("0.#######", culture),
|
||||
double or float => string.Empty,
|
||||
IFormattable f => f.ToString(null, culture),
|
||||
_ => value.ToString(),
|
||||
};
|
||||
|
||||
// Only text can carry a formula: numbers, dates and booleans are written as they are.
|
||||
return value is string or char or Enum || value is not IFormattable and not bool
|
||||
? EscapeText(text, options)
|
||||
: Quote(text ?? string.Empty, options.Separator);
|
||||
}
|
||||
|
||||
/// <summary>Adds a field to the current row.</summary>
|
||||
/// <param name="value">Text, number, date, boolean or <see langword="null"/> (empty field).</param>
|
||||
/// <returns>This writer.</returns>
|
||||
public CsvWriter WriteField(object? value)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_rowHasFields)
|
||||
{
|
||||
_buffer.Append(Options.Separator);
|
||||
}
|
||||
|
||||
_buffer.Append(FormatValue(value, Options));
|
||||
_rowHasFields = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Ends the current row; writes to the stream synchronously when the buffer is large.</summary>
|
||||
public void EndRow()
|
||||
{
|
||||
CompleteRow();
|
||||
if (_buffer.Length >= FlushThreshold)
|
||||
{
|
||||
Flush();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the current row; writes to the stream when the buffer is large.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask EndRowAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
CompleteRow();
|
||||
if (_buffer.Length >= FlushThreshold)
|
||||
{
|
||||
await FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes a whole row (synchronous stream).</summary>
|
||||
/// <param name="values">The fields.</param>
|
||||
public void WriteRow(params IEnumerable<object?> values)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
foreach (var value in values)
|
||||
{
|
||||
WriteField(value);
|
||||
}
|
||||
|
||||
EndRow();
|
||||
}
|
||||
|
||||
/// <summary>Writes a whole row.</summary>
|
||||
/// <param name="values">The fields.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public ValueTask WriteRowAsync(IEnumerable<object?> values, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
foreach (var value in values)
|
||||
{
|
||||
WriteField(value);
|
||||
}
|
||||
|
||||
return EndRowAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Writes the buffered rows to the stream synchronously.</summary>
|
||||
public void Flush()
|
||||
{
|
||||
var bytes = TakeBytes();
|
||||
if (bytes.Length > 0)
|
||||
{
|
||||
_output.Write(bytes);
|
||||
}
|
||||
|
||||
_output.Flush();
|
||||
}
|
||||
|
||||
/// <summary>Writes the buffered rows to the stream.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public async Task FlushAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var bytes = TakeBytes();
|
||||
if (bytes.Length > 0)
|
||||
{
|
||||
await _output.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _output.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Ends a pending row, writes the buffer synchronously and closes the stream unless left open.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_rowHasFields)
|
||||
{
|
||||
CompleteRow();
|
||||
}
|
||||
|
||||
Flush();
|
||||
_disposed = true;
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
_output.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends a pending row, writes the buffer and closes the stream unless left open.</summary>
|
||||
/// <returns>A task.</returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_rowHasFields)
|
||||
{
|
||||
CompleteRow();
|
||||
}
|
||||
|
||||
await FlushAsync().ConfigureAwait(false);
|
||||
_disposed = true;
|
||||
if (!_leaveOpen)
|
||||
{
|
||||
await _output.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Quote(string value, char separator)
|
||||
{
|
||||
var needsQuotes = value.Length > 0
|
||||
&& (value.Contains(separator, StringComparison.Ordinal) || value.AsSpan().IndexOfAny("\"\r\n") >= 0
|
||||
|| char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1]));
|
||||
return needsQuotes ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
||||
}
|
||||
|
||||
private void CompleteRow()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
_buffer.Append(Options.NewLine);
|
||||
_rowHasFields = false;
|
||||
RowCount++;
|
||||
}
|
||||
|
||||
private byte[] TakeBytes()
|
||||
{
|
||||
var preamble = !_preambleWritten && Options.WriteByteOrderMark ? Encoding.UTF8.Preamble.ToArray() : [];
|
||||
_preambleWritten = true;
|
||||
if (_buffer.Length == 0 && preamble.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var text = _buffer.ToString();
|
||||
_buffer.Clear();
|
||||
var bytes = new byte[preamble.Length + Utf8.GetByteCount(text)];
|
||||
preamble.CopyTo(bytes, 0);
|
||||
Utf8.GetBytes(text, 0, text.Length, bytes, preamble.Length);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user