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
@@ -71,7 +71,7 @@ public sealed class MappingTests
|
||||
[
|
||||
"sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log",
|
||||
"sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_user_settings", "sys_users",
|
||||
"audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users",
|
||||
"attachments", "audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "user_settings", "users",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||
|
||||
/// <summary>
|
||||
/// A write-only, non-seekable stream that refuses synchronous writes, like an ASP.NET Core response body: the writers
|
||||
/// must stream to it with asynchronous calls only.
|
||||
/// </summary>
|
||||
internal sealed class AsyncOnlyStream : Stream
|
||||
{
|
||||
private readonly MemoryStream _inner = new();
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => throw new NotSupportedException();
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public bool WasDisposed { get; private set; }
|
||||
|
||||
public byte[] ToArray() => _inner.ToArray();
|
||||
|
||||
public override void Flush() => throw new InvalidOperationException("Synchronous flush.");
|
||||
|
||||
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Synchronous write.");
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer) => throw new InvalidOperationException("Synchronous write.");
|
||||
|
||||
public override void WriteByte(byte value) => throw new InvalidOperationException("Synchronous write.");
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
_inner.WriteAsync(buffer, offset, count, cancellationToken);
|
||||
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) =>
|
||||
_inner.WriteAsync(buffer, cancellationToken);
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
WasDisposed = true;
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
WasDisposed = true;
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||
|
||||
/// <summary>The in-house PDF writer, first version (SPEC §2 "PDF e file", issue #34).</summary>
|
||||
[TestClass]
|
||||
public sealed partial class PdfWriterTests
|
||||
{
|
||||
private static readonly Encoding Latin1 = Encoding.Latin1;
|
||||
|
||||
[TestMethod]
|
||||
public async Task Document_HasHeaderTrailerAndXrefOffsetsThatPointAtTheObjects()
|
||||
{
|
||||
var bytes = await WriteAsync(async pdf =>
|
||||
{
|
||||
var first = await pdf.AddPageAsync();
|
||||
first.DrawText("Prima pagina", 50, 780, PdfFont.HelveticaBold, 16);
|
||||
first.DrawLine(50, 770, 545, 770, 1, PdfColor.FromHex("#1F5F8B"));
|
||||
first.DrawRectangle(50, 700, 200, 40, PdfColor.Black, PdfColor.Gray(230));
|
||||
var second = await pdf.AddPageAsync(PdfWriter.A4Height, PdfWriter.A4Width);
|
||||
second.DrawTextRight("€ 1.234,56", 800, 500, PdfFont.TimesRoman, 10);
|
||||
await pdf.AddPageAsync();
|
||||
Assert.AreEqual(3, pdf.PageCount);
|
||||
});
|
||||
var text = Latin1.GetString(bytes);
|
||||
|
||||
StringAssert.StartsWith(text, "%PDF-1.7\n");
|
||||
StringAssert.EndsWith(text, "%%EOF\n");
|
||||
StringAssert.Contains(text, "/Type /Pages /Kids [");
|
||||
StringAssert.Contains(text, "/Count 3");
|
||||
Assert.AreEqual(3, PageObject().Count(text));
|
||||
StringAssert.Contains(text, "/MediaBox [0 0 841.89 595.28]");
|
||||
|
||||
var startxref = long.Parse(StartXref().Match(text).Groups[1].Value, CultureInfo.InvariantCulture);
|
||||
Assert.AreEqual("xref", text.Substring((int)startxref, 4));
|
||||
var header = XrefHeader().Match(text, (int)startxref);
|
||||
var size = int.Parse(header.Groups[1].Value, CultureInfo.InvariantCulture);
|
||||
var entries = XrefEntry().Matches(text, header.Index + header.Length).Take(size).ToList();
|
||||
Assert.HasCount(size, entries);
|
||||
Assert.AreEqual("f", entries[0].Groups[3].Value);
|
||||
for (var i = 1; i < size; i++)
|
||||
{
|
||||
var offset = int.Parse(entries[i].Groups[1].Value, CultureInfo.InvariantCulture);
|
||||
StringAssert.StartsWith(text[offset..], $"{i} 0 obj\n", $"xref entry {i}");
|
||||
}
|
||||
|
||||
StringAssert.Contains(text, $"/Size {size} /Root 1 0 R /Info 3 0 R");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Text_IsWinAnsiEncoded_EuroAndAccentsIncluded()
|
||||
{
|
||||
var bytes = await WriteAsync(
|
||||
async pdf =>
|
||||
{
|
||||
var page = await pdf.AddPageAsync();
|
||||
page.DrawText("Totale € città (prova) \\ fine", 50, 700, PdfFont.Helvetica, 12, PdfColor.FromHex("#FF0000"));
|
||||
},
|
||||
compress: false);
|
||||
var text = Latin1.GetString(bytes);
|
||||
|
||||
// € is 0x80 (octal 200), à is 0xE0 (octal 340); parentheses and backslash are escaped.
|
||||
StringAssert.Contains(text, "(Totale \\200 citt\\340 \\(prova\\) \\\\ fine) Tj");
|
||||
StringAssert.Contains(text, "1 0 0 rg BT /F1 12 Tf 1 0 0 1 50 700 Tm");
|
||||
StringAssert.Contains(text, "/BaseFont /Helvetica /Encoding /WinAnsiEncoding");
|
||||
CollectionAssert.AreEqual(new byte[] { 0x80, 0xE0, 0xE8, 0xE9, 0xEC, 0xF2, 0xF9, (byte)'?' }, PdfTextLayout.EncodeWinAnsi("€àèéìòù漢"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ContentStreams_AreFlateCompressed()
|
||||
{
|
||||
var bytes = await WriteAsync(async pdf => (await pdf.AddPageAsync()).DrawText("Compresso è meglio", 50, 700, PdfFont.Courier, 10));
|
||||
var text = Latin1.GetString(bytes);
|
||||
var match = FlateStream().Match(text);
|
||||
Assert.IsTrue(match.Success);
|
||||
|
||||
var length = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
|
||||
var start = match.Index + match.Length;
|
||||
using var zlib = new ZLibStream(new MemoryStream(bytes, start, length), CompressionMode.Decompress);
|
||||
using var reader = new StreamReader(zlib, Latin1);
|
||||
StringAssert.Contains(reader.ReadToEnd(), "(Compresso \\350 meglio) Tj");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DocumentInfo_IsWritten_WithUnicodeAsUtf16()
|
||||
{
|
||||
var info = new PdfDocumentInfo { Title = "Fattura n. 7", Author = "Società Prova", CreationDate = new DateTimeOffset(2026, 11, 11, 10, 30, 0, TimeSpan.Zero) };
|
||||
var output = new AsyncOnlyStream();
|
||||
await using (var pdf = new PdfWriter(output, info, leaveOpen: true))
|
||||
{
|
||||
await pdf.AddPageAsync();
|
||||
}
|
||||
|
||||
var text = Latin1.GetString(output.ToArray());
|
||||
StringAssert.Contains(text, "/Title (Fattura n. 7)");
|
||||
StringAssert.Contains(text, "/Author <FEFF0053006F0063006900650074" + "00E0");
|
||||
StringAssert.Contains(text, "/Creator (Khaemhat)");
|
||||
StringAssert.Contains(text, "/CreationDate (D:20261111103000Z)");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EmptyDocument_GetsOneBlankPage()
|
||||
{
|
||||
var text = Latin1.GetString(await WriteAsync(_ => Task.CompletedTask));
|
||||
|
||||
StringAssert.Contains(text, "/Count 1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Jpeg_SizeAndComponents_AreReadFromTheFrameHeader()
|
||||
{
|
||||
var info = JpegInfo.Read(TinyJpeg(width: 64, height: 32, components: 3));
|
||||
|
||||
Assert.AreEqual(new JpegInfo(64, 32, 3, 8, false), info);
|
||||
Assert.AreEqual(1, JpegInfo.Read(TinyJpeg(10, 10, 1)).Components);
|
||||
Assert.IsTrue(JpegInfo.Read(TinyJpeg(10, 10, 4, adobe: true)).AdobeInverted);
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => JpegInfo.Read("not a jpeg"u8));
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => JpegInfo.Read(new byte[] { 0xFF, 0xD8, 0xFF, 0xD9 }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Jpeg_IsEmbeddedAsIs_WithDctDecode()
|
||||
{
|
||||
var jpeg = TinyJpeg(64, 32, 3);
|
||||
var bytes = await WriteAsync(async pdf =>
|
||||
{
|
||||
var image = pdf.AddJpeg(jpeg);
|
||||
var page = await pdf.AddPageAsync();
|
||||
page.DrawImage(image, 50, 600, 128, 64);
|
||||
Assert.AreEqual(64, image.Width);
|
||||
});
|
||||
var text = Latin1.GetString(bytes);
|
||||
|
||||
StringAssert.Contains(text, $"/Subtype /Image /Width 64 /Height 32 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length {jpeg.Length} >>");
|
||||
StringAssert.Contains(text, "/XObject << /Im1 ");
|
||||
Assert.IsGreaterThanOrEqualTo(0, text.IndexOf(Latin1.GetString(jpeg), StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Measure_UsesTheAfmWidths_AndWrapKeepsLinesInsideTheWidth()
|
||||
{
|
||||
// Helvetica: "A" = 667, "i" = 222; Helvetica-Bold: "A" = 722; Courier: 600 for every character.
|
||||
Assert.AreEqual(6.67, PdfTextLayout.Measure("A", PdfFont.Helvetica, 10), 1e-9);
|
||||
Assert.AreEqual(8.89, PdfTextLayout.Measure("Ai", PdfFont.Helvetica, 10), 1e-9);
|
||||
Assert.AreEqual(7.22, PdfTextLayout.Measure("A", PdfFont.HelveticaBold, 10), 1e-9);
|
||||
Assert.AreEqual(5.56, PdfTextLayout.Measure("€", PdfFont.Helvetica, 10), 1e-9);
|
||||
Assert.AreEqual(18, PdfTextLayout.Measure("abc", PdfFont.Courier, 10), 1e-9);
|
||||
Assert.AreEqual(PdfTextLayout.Measure("e", PdfFont.Helvetica, 10), PdfTextLayout.Measure("è", PdfFont.Helvetica, 10));
|
||||
|
||||
var text = "Questo è un paragrafo abbastanza lungo da andare a capo più volte, con una parolaincredibilmentelunghissimachenonstainriga.";
|
||||
var lines = PdfTextLayout.Wrap(text, PdfFont.Helvetica, 10, 120);
|
||||
Assert.IsGreaterThan(2, lines.Count);
|
||||
Assert.IsTrue(lines.All(l => PdfTextLayout.Measure(l, PdfFont.Helvetica, 10) <= 120));
|
||||
Assert.AreEqual(text.Replace(" ", string.Empty, StringComparison.Ordinal), string.Concat(lines).Replace(" ", string.Empty, StringComparison.Ordinal));
|
||||
Assert.HasCount(2, PdfTextLayout.Wrap("riga uno\nriga due", PdfFont.Helvetica, 10, 500));
|
||||
StringAssert.EndsWith(PdfTextLayout.Fit("Descrizione molto lunga di un articolo", PdfFont.Helvetica, 10, 60), "…");
|
||||
}
|
||||
|
||||
private static async Task<byte[]> WriteAsync(Func<PdfWriter, Task> draw, bool compress = true)
|
||||
{
|
||||
var output = new AsyncOnlyStream();
|
||||
var pdf = new PdfWriter(output, new PdfDocumentInfo { Title = "Prova" }, leaveOpen: true) { CompressContent = compress };
|
||||
await using (pdf)
|
||||
{
|
||||
await draw(pdf);
|
||||
await pdf.CloseAsync();
|
||||
}
|
||||
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The header of a JPEG file built by hand: SOI, APP0 (JFIF), optional APP14 (Adobe), SOF0, EOI. No pixels.</summary>
|
||||
private static byte[] TinyJpeg(int width, int height, int components, bool adobe = false)
|
||||
{
|
||||
var bytes = new List<byte> { 0xFF, 0xD8 };
|
||||
bytes.AddRange([0xFF, 0xE0, 0x00, 0x10, (byte)'J', (byte)'F', (byte)'I', (byte)'F', 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00]);
|
||||
if (adobe)
|
||||
{
|
||||
bytes.AddRange([0xFF, 0xEE, 0x00, 0x0E, (byte)'A', (byte)'d', (byte)'o', (byte)'b', (byte)'e', 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x02]);
|
||||
}
|
||||
|
||||
var length = 8 + (3 * components);
|
||||
bytes.AddRange([0xFF, 0xC0, (byte)(length >> 8), (byte)length, 0x08, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, (byte)components]);
|
||||
for (var c = 1; c <= components; c++)
|
||||
{
|
||||
bytes.AddRange([(byte)c, 0x11, 0x00]);
|
||||
}
|
||||
|
||||
bytes.AddRange([0xFF, 0xD9]);
|
||||
return [.. bytes];
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"/Type /Page /Parent")]
|
||||
private static partial Regex PageObject();
|
||||
|
||||
[GeneratedRegex(@"startxref\n(\d+)\n%%EOF")]
|
||||
private static partial Regex StartXref();
|
||||
|
||||
[GeneratedRegex(@"xref\n0 (\d+)\n")]
|
||||
private static partial Regex XrefHeader();
|
||||
|
||||
[GeneratedRegex(@"(\d{10}) (\d{5}) ([nf])\r\n")]
|
||||
private static partial Regex XrefEntry();
|
||||
|
||||
[GeneratedRegex(@"<< /Length (\d+) /Filter /FlateDecode >>\nstream\n")]
|
||||
private static partial Regex FlateStream();
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||
|
||||
/// <summary>CSV, ZIP and XLSX written in house (SPEC §2 "PDF e file", issue #34).</summary>
|
||||
[TestClass]
|
||||
public sealed class SpreadsheetWritersTests
|
||||
{
|
||||
private const string Main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("semplice", "semplice")]
|
||||
[DataRow("con;separatore", "\"con;separatore\"")]
|
||||
[DataRow("con \"virgolette\"", "\"con \"\"virgolette\"\"\"")]
|
||||
[DataRow("a capo\nqui", "\"a capo\nqui\"")]
|
||||
[DataRow(" spazio", "\" spazio\"")]
|
||||
[DataRow("=SUM(A1:A9)", "'=SUM(A1:A9)")]
|
||||
[DataRow("+39 333", "'+39 333")]
|
||||
[DataRow("-2+3", "'-2+3")]
|
||||
[DataRow("@cmd", "'@cmd")]
|
||||
[DataRow("\tTab", "'\tTab")]
|
||||
[DataRow("=1;2", "\"'=1;2\"")]
|
||||
public void Csv_TextIsQuotedAndProtected(string value, string expected) =>
|
||||
Assert.AreEqual(expected, CsvWriter.FormatValue(value, CsvOptions.Italian));
|
||||
|
||||
[TestMethod]
|
||||
public void Csv_NumbersAreNotProtected_AndFollowTheFormat()
|
||||
{
|
||||
Assert.AreEqual("-1234,5", CsvWriter.FormatValue(-1234.5m, CsvOptions.Italian));
|
||||
Assert.AreEqual("-1234.5", CsvWriter.FormatValue(-1234.5m, CsvOptions.Invariant));
|
||||
Assert.AreEqual("\"0,25\"", CsvWriter.FormatValue(0.25m, CsvOptions.Italian with { Separator = ',' }));
|
||||
Assert.AreEqual("11/11/2026", CsvWriter.FormatValue(new DateOnly(2026, 11, 11), CsvOptions.Italian));
|
||||
Assert.AreEqual("2026-11-11", CsvWriter.FormatValue(new DateTime(2026, 11, 11), CsvOptions.Invariant));
|
||||
Assert.AreEqual("VERO", CsvWriter.FormatValue(true, CsvOptions.Italian));
|
||||
Assert.AreEqual(string.Empty, CsvWriter.FormatValue(null, CsvOptions.Italian));
|
||||
Assert.AreEqual("-5", CsvWriter.FormatValue(-5, CsvOptions.Italian));
|
||||
Assert.AreEqual("'-5", CsvWriter.FormatValue("-5", CsvOptions.Italian));
|
||||
Assert.AreEqual("-5", CsvWriter.FormatValue("-5", CsvOptions.Italian with { ProtectFormulas = false }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Csv_StreamsRowsWithBom_AndOnlyAsynchronousWrites()
|
||||
{
|
||||
var output = new AsyncOnlyStream();
|
||||
await using (var csv = new CsvWriter(output, leaveOpen: true))
|
||||
{
|
||||
await csv.WriteRowAsync(["Descrizione", "Importo"]);
|
||||
for (var i = 0; i < 2000; i++)
|
||||
{
|
||||
await csv.WriteRowAsync(["Riga è più lunga; con separatore", 1234.5m + i]);
|
||||
}
|
||||
|
||||
Assert.AreEqual(2001, csv.RowCount);
|
||||
}
|
||||
|
||||
var bytes = output.ToArray();
|
||||
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3]);
|
||||
var lines = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3).Split("\r\n");
|
||||
Assert.AreEqual("Descrizione;Importo", lines[0]);
|
||||
Assert.AreEqual("\"Riga è più lunga; con separatore\";1234,5", lines[1]);
|
||||
Assert.AreEqual(string.Empty, lines[^1]);
|
||||
Assert.HasCount(2002, lines);
|
||||
Assert.IsFalse(output.WasDisposed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Csv_InvariantOptions_HaveNoBom()
|
||||
{
|
||||
using var output = new MemoryStream();
|
||||
using (var csv = new CsvWriter(output, CsvOptions.Invariant, leaveOpen: true))
|
||||
{
|
||||
csv.WriteRow("a,b", 1.5m);
|
||||
}
|
||||
|
||||
Assert.AreEqual("\"a,b\",1.5\r\n", Encoding.UTF8.GetString(output.ToArray()));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Zip_WritesToANonSeekableStream_WithCleanUniqueNames()
|
||||
{
|
||||
var output = new AsyncOnlyStream();
|
||||
await using (var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true))
|
||||
{
|
||||
Assert.AreEqual("fattura.pdf", await zip.AddAsync("fattura.pdf", "uno"u8.ToArray()));
|
||||
Assert.AreEqual("FATTURA (2).pdf", await zip.AddAsync("FATTURA.pdf", new MemoryStream("due"u8.ToArray())));
|
||||
Assert.AreEqual("cartella/file_.txt", await zip.AddAsync("..\\..\\cartella/file?.txt", "tre"u8.ToArray()));
|
||||
var (name, entry) = await zip.OpenEntryAsync("scritto.txt");
|
||||
await using (entry)
|
||||
{
|
||||
await entry.WriteAsync("quattro"u8.ToArray());
|
||||
}
|
||||
|
||||
Assert.AreEqual("scritto.txt", name);
|
||||
Assert.AreEqual(4, zip.Count);
|
||||
}
|
||||
|
||||
using var archive = new ZipArchive(new MemoryStream(output.ToArray()), ZipArchiveMode.Read);
|
||||
CollectionAssert.AreEqual(new[] { "fattura.pdf", "FATTURA (2).pdf", "cartella/file_.txt", "scritto.txt" }, archive.Entries.Select(e => e.FullName).ToArray());
|
||||
using var reader = new StreamReader(archive.GetEntry("FATTURA (2).pdf")!.Open());
|
||||
Assert.AreEqual("due", reader.ReadToEnd());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("Righe", "Righe")]
|
||||
[DataRow("a[b]c:d*e?f/g\\h", "abcdefgh")]
|
||||
[DataRow("'quoted'", "quoted")]
|
||||
[DataRow("", "Foglio1")]
|
||||
[DataRow("Un nome di foglio davvero troppo lungo per Excel", "Un nome di foglio davvero tropp")]
|
||||
public void Xlsx_SheetNamesAreCleaned(string name, string expected) =>
|
||||
Assert.AreEqual(expected, XlsxWriter.CleanSheetName(name, []));
|
||||
|
||||
[TestMethod]
|
||||
public void Xlsx_SheetNamesAreUnique_AndColumnsAreLettered()
|
||||
{
|
||||
Assert.AreEqual("righe (2)", XlsxWriter.CleanSheetName("righe", ["Righe"]));
|
||||
Assert.AreEqual(31, XlsxWriter.CleanSheetName(new string('x', 40), [new string('x', 31)]).Length);
|
||||
Assert.AreEqual("A", XlsxWriter.ColumnName(0));
|
||||
Assert.AreEqual("Z", XlsxWriter.ColumnName(25));
|
||||
Assert.AreEqual("AA", XlsxWriter.ColumnName(26));
|
||||
Assert.AreEqual("XFD", XlsxWriter.ColumnName(16383));
|
||||
Assert.AreEqual(46337, XlsxWriter.ToSerialDate(new DateTime(2026, 11, 11)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task Xlsx_HasTheRequiredParts_AndTheCellsReadBack(bool sharedStrings)
|
||||
{
|
||||
var output = new AsyncOnlyStream();
|
||||
await using (var xlsx = await XlsxWriter.CreateAsync(output, new XlsxOptions { UseSharedStrings = sharedStrings }, leaveOpen: true))
|
||||
{
|
||||
await xlsx.StartSheetAsync("Righe/2026", [new("Codice", 12), new("Descrizione", 40), new("Importo", 14, XlsxFormat.Euro), new("Data"), new("Ok")]);
|
||||
await xlsx.WriteRowAsync(["A1", " Vite à testa piatta ", 1234.5m, new DateTime(2026, 11, 11), true]);
|
||||
await xlsx.WriteRowAsync(["B2", null, -3, new DateOnly(2026, 1, 1), false]);
|
||||
await xlsx.StartSheetAsync("Altro");
|
||||
await xlsx.WriteRowAsync(["solo testo\u0001"]);
|
||||
}
|
||||
|
||||
using var archive = new ZipArchive(new MemoryStream(output.ToArray()), ZipArchiveMode.Read);
|
||||
var parts = archive.Entries.Select(e => e.FullName).ToHashSet();
|
||||
foreach (var part in new[] { "[Content_Types].xml", "_rels/.rels", "xl/workbook.xml", "xl/_rels/workbook.xml.rels", "xl/styles.xml", "xl/worksheets/sheet1.xml", "xl/worksheets/sheet2.xml" })
|
||||
{
|
||||
Assert.Contains(part, parts);
|
||||
}
|
||||
|
||||
Assert.AreEqual(sharedStrings, parts.Contains("xl/sharedStrings.xml"));
|
||||
var shared = sharedStrings ? ReadSharedStrings(archive) : [];
|
||||
var cells = ReadCells(archive, "xl/worksheets/sheet1.xml", shared);
|
||||
|
||||
Assert.AreEqual(("Codice", "1"), (cells["A1"].Value, cells["A1"].Style));
|
||||
Assert.AreEqual(" Vite à testa piatta ", cells["B2"].Value);
|
||||
Assert.AreEqual(("1234.5", "6"), (cells["C2"].Value, cells["C2"].Style));
|
||||
Assert.AreEqual(("46337", "2"), (cells["D2"].Value, cells["D2"].Style));
|
||||
Assert.AreEqual(("1", "b"), (cells["E2"].Value, cells["E2"].Type));
|
||||
Assert.IsFalse(cells.ContainsKey("B3"), "A null leaves the cell empty.");
|
||||
Assert.AreEqual("-3", cells["C3"].Value);
|
||||
Assert.AreEqual("0", cells["E3"].Value);
|
||||
Assert.AreEqual("solo testo", ReadCells(archive, "xl/worksheets/sheet2.xml", shared)["A1"].Value);
|
||||
|
||||
var workbook = Read(archive, "xl/workbook.xml");
|
||||
StringAssert.Contains(workbook, "name=\"Righe2026\"");
|
||||
StringAssert.Contains(workbook, "name=\"Altro\"");
|
||||
StringAssert.Contains(Read(archive, "xl/worksheets/sheet1.xml"), "state=\"frozen\"");
|
||||
StringAssert.Contains(Read(archive, "xl/worksheets/sheet1.xml"), "customWidth=\"1\"");
|
||||
}
|
||||
|
||||
private static string Read(ZipArchive archive, string part)
|
||||
{
|
||||
using var reader = new StreamReader(archive.GetEntry(part)!.Open());
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
private static List<string> ReadSharedStrings(ZipArchive archive)
|
||||
{
|
||||
var strings = new List<string>();
|
||||
using var reader = XmlReader.Create(archive.GetEntry("xl/sharedStrings.xml")!.Open());
|
||||
while (reader.ReadToFollowing("t", Main))
|
||||
{
|
||||
strings.Add(reader.ReadElementContentAsString());
|
||||
}
|
||||
|
||||
return strings;
|
||||
}
|
||||
|
||||
private static Dictionary<string, (string Value, string? Style, string? Type)> ReadCells(ZipArchive archive, string part, List<string> shared)
|
||||
{
|
||||
var cells = new Dictionary<string, (string, string?, string?)>();
|
||||
using var reader = XmlReader.Create(archive.GetEntry(part)!.Open());
|
||||
while (reader.ReadToFollowing("c", Main))
|
||||
{
|
||||
var reference = reader.GetAttribute("r")!;
|
||||
var style = reader.GetAttribute("s");
|
||||
var type = reader.GetAttribute("t");
|
||||
using var cell = reader.ReadSubtree();
|
||||
var value = string.Empty;
|
||||
while (cell.Read())
|
||||
{
|
||||
if (cell.NodeType == XmlNodeType.Element && cell.LocalName is "v" or "t")
|
||||
{
|
||||
value = cell.ReadElementContentAsString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
cells[reference] = (type == "s" ? shared[int.Parse(value, System.Globalization.CultureInfo.InvariantCulture)] : value, style, type);
|
||||
}
|
||||
|
||||
return cells;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Security.Cryptography;
|
||||
using Khaemhat.Core.Files;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests.Files;
|
||||
|
||||
/// <summary>The file store on the data volume (SPEC §9.4, issue #34).</summary>
|
||||
[TestClass]
|
||||
public sealed class VolumeFileStoreTests
|
||||
{
|
||||
private const string Company = "ACME";
|
||||
private string _root = string.Empty;
|
||||
|
||||
[TestInitialize]
|
||||
public void CreateRoot() => _root = Path.Combine(Path.GetTempPath(), "khaemhat-tests", "files-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
[TestCleanup]
|
||||
public void DeleteRoot()
|
||||
{
|
||||
if (Directory.Exists(_root))
|
||||
{
|
||||
Directory.Delete(_root, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Save_StoresUnderCompanyAndYear_WithSizeAndSha256()
|
||||
{
|
||||
var store = NewStore();
|
||||
var content = RandomNumberGenerator.GetBytes(200_000);
|
||||
|
||||
var stored = await store.SaveAsync("acme", new MemoryStream(content));
|
||||
|
||||
StringAssert.Matches(stored.Key, new System.Text.RegularExpressions.Regex("^2026/[0-9a-f]{32}$"));
|
||||
Assert.AreEqual(content.Length, stored.Size);
|
||||
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), stored.Sha256);
|
||||
Assert.IsTrue(File.Exists(Path.Combine(_root, Company, "2026", stored.Key[5..])));
|
||||
Assert.IsEmpty(Directory.GetFiles(_root, "*.part", SearchOption.AllDirectories));
|
||||
|
||||
await using (var read = store.OpenRead(Company, stored.Key))
|
||||
{
|
||||
using var copy = new MemoryStream();
|
||||
await read.CopyToAsync(copy);
|
||||
CollectionAssert.AreEqual(content, copy.ToArray());
|
||||
}
|
||||
|
||||
var usage = await store.GetUsageAsync(Company);
|
||||
Assert.AreEqual((1L, (long)content.Length), (usage.Files, usage.Bytes));
|
||||
Assert.IsTrue(store.Delete(Company, stored.Key));
|
||||
Assert.IsFalse(store.Delete(Company, stored.Key));
|
||||
Assert.ThrowsExactly<FileStoreException>(() => store.OpenRead(Company, stored.Key));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TooLarge_IsRefused_AndLeavesNothingBehind()
|
||||
{
|
||||
var store = NewStore(new FileStoreOptions(_root) { MaxFileBytes = 1000 });
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<FileStoreException>(() => store.SaveAsync(Company, new MemoryStream(new byte[1001])));
|
||||
|
||||
Assert.AreEqual(FileStoreException.TooLarge, error.Code);
|
||||
Assert.IsEmpty(Directory.GetFiles(_root, "*", SearchOption.AllDirectories));
|
||||
Assert.AreEqual(1000, (await store.SaveAsync(Company, new MemoryStream(new byte[1000]))).Size);
|
||||
Assert.AreEqual(5000, (await store.SaveAsync(Company, new MemoryStream(new byte[5000]), FileLimits.None)).Size);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Quota_IsCheckedPerCompany()
|
||||
{
|
||||
var store = NewStore();
|
||||
var limits = new FileLimits(0, 1500);
|
||||
await store.SaveAsync(Company, new MemoryStream(new byte[1000]), limits);
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<FileStoreException>(() => store.SaveAsync(Company, new MemoryStream(new byte[600]), limits));
|
||||
|
||||
Assert.AreEqual(FileStoreException.QuotaExceeded, error.Code);
|
||||
await store.SaveAsync("OTHER", new MemoryStream(new byte[600]), limits);
|
||||
var usage = await store.GetUsageAsync(Company, 1500);
|
||||
Assert.AreEqual(500, usage.RemainingBytes);
|
||||
Assert.IsFalse(usage.IsOverQuota);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Scanner_CanRejectAFile()
|
||||
{
|
||||
var store = new VolumeFileStore(new FileStoreOptions(_root), new RejectingScanner(), new FixedClock());
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<FileStoreException>(() => store.SaveAsync(Company, new MemoryStream("X5O!EICAR"u8.ToArray())));
|
||||
|
||||
Assert.AreEqual(FileStoreException.Rejected, error.Code);
|
||||
StringAssert.Contains(error.Message, "EICAR");
|
||||
Assert.IsEmpty(Directory.GetFiles(_root, "*", SearchOption.AllDirectories));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Writer_NotCommitted_IsDiscarded_AndKeysCannotEscapeTheCompanyFolder()
|
||||
{
|
||||
var store = NewStore();
|
||||
await using (var writer = await store.CreateAsync(Company))
|
||||
{
|
||||
await writer.Content.WriteAsync(new byte[10]);
|
||||
Assert.HasCount(1, Directory.GetFiles(_root, "*.part", SearchOption.AllDirectories));
|
||||
}
|
||||
|
||||
Assert.IsEmpty(Directory.GetFiles(_root, "*", SearchOption.AllDirectories));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => store.OpenRead(Company, "../OTHER/2026/" + new string('a', 32)));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => store.Exists(Company, "2026/x"));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => store.OpenRead("../etc", "2026/" + new string('a', 32)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AbandonedParts_AreRemoved()
|
||||
{
|
||||
var store = NewStore();
|
||||
var folder = Directory.CreateDirectory(Path.Combine(_root, Company, "2026")).FullName;
|
||||
var old = Path.Combine(folder, Guid.NewGuid().ToString("N") + ".part");
|
||||
File.WriteAllBytes(old, [1, 2, 3]);
|
||||
File.SetLastWriteTimeUtc(old, new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc));
|
||||
var recent = Path.Combine(folder, Guid.NewGuid().ToString("N") + ".part");
|
||||
File.WriteAllBytes(recent, [1]);
|
||||
File.SetLastWriteTimeUtc(recent, new DateTime(2026, 11, 11, 9, 0, 0, DateTimeKind.Utc));
|
||||
|
||||
Assert.AreEqual(1, store.DeleteAbandonedParts(Company, TimeSpan.FromDays(1)));
|
||||
Assert.IsFalse(File.Exists(old));
|
||||
Assert.IsTrue(File.Exists(recent));
|
||||
}
|
||||
|
||||
private VolumeFileStore NewStore(FileStoreOptions? options = null) =>
|
||||
new(options ?? new FileStoreOptions(_root), new NoOpFileScanner(), new FixedClock());
|
||||
|
||||
private sealed class FixedClock : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero);
|
||||
}
|
||||
|
||||
private sealed class RejectingScanner : IFileScanner
|
||||
{
|
||||
public async ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var reader = new StreamReader(content);
|
||||
var text = await reader.ReadToEndAsync(cancellationToken);
|
||||
return text.Contains("EICAR", StringComparison.Ordinal) ? new FileScanResult(false, "EICAR test signature") : FileScanResult.Ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
using Khaemhat.Application.Audit;
|
||||
using Khaemhat.Application.Files;
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Files;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
using Khaemhat.Web.Tests.Hosting;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Files;
|
||||
|
||||
/// <summary>
|
||||
/// Attachments and generated files on a real instance (issue #34): versions, download, trash and purge, locks, limits.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class AttachmentServiceTests
|
||||
{
|
||||
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
|
||||
[TestMethod]
|
||||
public async Task GeneratedAttachment_IsVersioned_AndRegenerateAddsTheNextVersion()
|
||||
{
|
||||
await using var fixture = await Fixture.StartAsync();
|
||||
var (attachments, generation, company) = (fixture.Attachments, fixture.Generation, fixture.Company);
|
||||
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { DemoCsvGenerator.GeneratorCode, DemoPdfGenerator.GeneratorCode, DemoXlsxGenerator.GeneratorCode },
|
||||
generation.AvailableFor(DemoDocument.Entity).Select(g => g.Code).ToArray());
|
||||
Assert.IsEmpty(generation.AvailableFor("sales.invoice"));
|
||||
|
||||
var v1 = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoPdfGenerator.GeneratorCode);
|
||||
var v2 = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoPdfGenerator.GeneratorCode);
|
||||
await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoCsvGenerator.GeneratorCode);
|
||||
await generation.GenerateAsync(Root, company, DemoDocument.Entity, 7, DemoXlsxGenerator.GeneratorCode);
|
||||
|
||||
Assert.AreEqual((1, AttachmentKind.Generated, "documento-di-prova-7.pdf"), (v1.Version, v1.Kind, v1.FileName));
|
||||
Assert.AreEqual((2, "v2", "documento-di-prova-7_v2.pdf"), (v2.Version, v2.VersionLabel, v2.FileName));
|
||||
Assert.AreEqual((PdfWriter.MediaType, AttachmentPreview.Pdf, DemoPdfGenerator.GeneratorCode), (v2.Mime, v2.Preview, v2.GeneratedBy));
|
||||
Assert.AreEqual(TestInstance.SuperUser, v2.CreatedBy);
|
||||
|
||||
var latest = await attachments.ListAsync(Root, company, DemoDocument.Entity, 7);
|
||||
Assert.HasCount(3, latest);
|
||||
Assert.AreEqual(v2.Id, latest.Single(a => a.GeneratedBy == DemoPdfGenerator.GeneratorCode).Id);
|
||||
Assert.IsTrue(latest.All(a => a.IsLatest));
|
||||
Assert.AreEqual(3, await attachments.CountAsync(Root, company, DemoDocument.Entity, 7));
|
||||
|
||||
var all = await attachments.ListAsync(Root, company, DemoDocument.Entity, 7, includeOlderVersions: true);
|
||||
Assert.HasCount(4, all);
|
||||
Assert.IsFalse(all.Single(a => a.Id == v1.Id).IsLatest);
|
||||
Assert.IsEmpty(await attachments.ListAsync(Root, company, DemoDocument.Entity, 8), "Attachments belong to one record only.");
|
||||
|
||||
// The generated PDF is a PDF, and the history records the insert.
|
||||
await using (var pdf = await attachments.OpenAsync(Root, company, v2.Id))
|
||||
{
|
||||
using var reader = new StreamReader(pdf.Content);
|
||||
var text = await reader.ReadToEndAsync();
|
||||
StringAssert.StartsWith(text, "%PDF-1.7");
|
||||
StringAssert.EndsWith(text, "%%EOF\n");
|
||||
}
|
||||
|
||||
await using var unitOfWork = await fixture.Factory.CreateAsync(DatabaseScope.Company(company));
|
||||
Assert.HasCount(1, await AuditTrail.HistoryAsync(unitOfWork, nameof(Attachment), v2.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
||||
Assert.ThrowsExactly<ValidationFailedException>(() => generation.GenerateAsync(Root, company, "sales.invoice", 7, DemoPdfGenerator.GeneratorCode).GetAwaiter().GetResult());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Upload_ThenDownload_ReturnsTheSameBytes()
|
||||
{
|
||||
await using var fixture = await Fixture.StartAsync();
|
||||
var (attachments, company) = (fixture.Attachments, fixture.Company);
|
||||
var content = RandomNumberGenerator.GetBytes(300_000);
|
||||
|
||||
var uploaded = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "C:\\Documenti\\ordine cliente.PDF", "text/html", new MemoryStream(content));
|
||||
var again = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "Ordine Cliente.pdf", null, new MemoryStream(content[..1000]));
|
||||
|
||||
Assert.AreEqual(("ordine cliente.PDF", MediaTypes.Pdf, AttachmentKind.Uploaded, 1), (uploaded.Name, uploaded.Mime, uploaded.Kind, uploaded.Version));
|
||||
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), uploaded.Sha256);
|
||||
Assert.AreEqual(content.Length, uploaded.Size);
|
||||
Assert.AreEqual(2, again.Version, "A file with the same name becomes the next version.");
|
||||
|
||||
await using var download = await attachments.OpenAsync(Root, company, uploaded.Id);
|
||||
using var copy = new MemoryStream();
|
||||
await download.Content.CopyToAsync(copy);
|
||||
CollectionAssert.AreEqual(content, copy.ToArray());
|
||||
Assert.AreEqual(uploaded.Sha256, Convert.ToHexStringLower(SHA256.HashData(copy.ToArray())));
|
||||
|
||||
// "Scarica tutto": a ZIP with the latest versions.
|
||||
var csv = await attachments.UploadAsync(Root, company, "sales.invoice", 15, "righe.csv", null, new MemoryStream("a;b\r\n"u8.ToArray()));
|
||||
using var zipped = new MemoryStream();
|
||||
Assert.AreEqual(2, await attachments.WriteZipAsync(Root, company, "sales.invoice", 15, zipped));
|
||||
using var zip = new ZipArchive(new MemoryStream(zipped.ToArray()), ZipArchiveMode.Read);
|
||||
CollectionAssert.AreEquivalent(new[] { "Ordine Cliente_v2.pdf", "righe.csv" }, zip.Entries.Select(e => e.FullName).ToArray());
|
||||
Assert.AreEqual(AttachmentPreview.Csv, csv.Preview);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeletingTheDocument_MovesAttachmentsToTheTrash_AndThePurgeRemovesThemAfter30Days()
|
||||
{
|
||||
await using var fixture = await Fixture.StartAsync();
|
||||
var (attachments, generation, company) = (fixture.Attachments, fixture.Generation, fixture.Company);
|
||||
var pdf = await generation.GenerateAsync(Root, company, DemoDocument.Entity, 3, DemoPdfGenerator.GeneratorCode);
|
||||
var photo = await attachments.UploadAsync(Root, company, DemoDocument.Entity, 3, "foto.jpg", null, new MemoryStream(new byte[100]));
|
||||
var keys = await fixture.StorageKeysAsync();
|
||||
Assert.IsTrue(keys.All(k => fixture.Store.Exists(company, k)));
|
||||
|
||||
Assert.AreEqual(2, await attachments.TrashForEntityAsync(Root, company, DemoDocument.Entity, 3));
|
||||
|
||||
Assert.IsEmpty(await attachments.ListAsync(Root, company, DemoDocument.Entity, 3));
|
||||
CollectionAssert.AreEquivalent(new[] { pdf.Id, photo.Id }, (await attachments.ListTrashAsync(Root, company)).Select(a => a.Id).ToArray());
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => attachments.OpenAsync(Root, company, pdf.Id));
|
||||
|
||||
// Restorable within 30 days; deleting one attachment also goes through the trash.
|
||||
Assert.AreEqual(2, await attachments.RestoreForEntityAsync(Root, company, DemoDocument.Entity, 3));
|
||||
await attachments.DeleteAsync(Root, company, photo.Id);
|
||||
await attachments.RestoreAsync(Root, company, photo.Id);
|
||||
Assert.HasCount(2, await attachments.ListAsync(Root, company, DemoDocument.Entity, 3));
|
||||
await attachments.TrashForEntityAsync(Root, company, DemoDocument.Entity, 3);
|
||||
|
||||
fixture.Clock.Advance(TimeSpan.FromDays(29));
|
||||
Assert.AreEqual(0, await attachments.PurgeTrashAsync(company));
|
||||
fixture.Clock.Advance(TimeSpan.FromDays(2));
|
||||
Assert.AreEqual(2, await attachments.PurgeTrashAsync(company));
|
||||
|
||||
Assert.IsEmpty(await fixture.StorageKeysAsync());
|
||||
Assert.IsTrue(keys.All(k => !fixture.Store.Exists(company, k)));
|
||||
Assert.IsEmpty(await attachments.ListTrashAsync(Root, company));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task LockedAttachment_CannotBeDeleted_NorItsDocument()
|
||||
{
|
||||
await using var fixture = await Fixture.StartAsync();
|
||||
var (attachments, company) = (fixture.Attachments, fixture.Company);
|
||||
var xml = await attachments.AddAsync(
|
||||
Root, company, "sales.invoice", 21, new AttachmentFile(AttachmentKind.EInvoice, "IT01234567890_00001.xml"),
|
||||
(output, ct) => output.WriteAsync("<FatturaElettronica/>"u8.ToArray(), ct).AsTask());
|
||||
var other = await attachments.UploadAsync(Root, company, "sales.invoice", 21, "nota.txt", null, new MemoryStream("x"u8.ToArray()));
|
||||
|
||||
await attachments.LockAsync(Root, company, xml.Id);
|
||||
|
||||
Assert.IsTrue((await attachments.GetAsync(Root, company, xml.Id))!.Locked);
|
||||
Assert.AreEqual((MediaTypes.Xml, AttachmentPreview.Xml), (xml.Mime, xml.Preview));
|
||||
var error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => attachments.DeleteAsync(Root, company, xml.Id));
|
||||
CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.LockedError);
|
||||
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => attachments.TrashForEntityAsync(Root, company, "sales.invoice", 21));
|
||||
Assert.HasCount(2, await attachments.ListAsync(Root, company, "sales.invoice", 21), "A refused deletion changes nothing.");
|
||||
await attachments.DeleteAsync(Root, company, other.Id);
|
||||
Assert.HasCount(1, await attachments.ListAsync(Root, company, "sales.invoice", 21));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SizeLimit_IsEnforced_AndUsersStayInTheirCompany()
|
||||
{
|
||||
await using var fixture = await Fixture.StartAsync();
|
||||
var (attachments, company) = (fixture.Attachments, fixture.Company);
|
||||
var settings = fixture.App.Services.GetRequiredService<SystemSettingsStore>();
|
||||
Assert.AreEqual(FileLimits.DefaultMaxBytes, (await attachments.GetLimitsAsync()).MaxBytes);
|
||||
await settings.SetAsync(AttachmentService.MaxUploadSetting, "1");
|
||||
|
||||
var error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(
|
||||
() => attachments.UploadAsync(Root, company, "sales.invoice", 1, "grande.pdf", null, new MemoryStream(new byte[(1024 * 1024) + 1])));
|
||||
|
||||
CollectionAssert.Contains(error.Errors.ToList(), AttachmentService.TooLargeError);
|
||||
Assert.IsEmpty(await attachments.ListAsync(Root, company, "sales.invoice", 1));
|
||||
Assert.AreEqual(0, (await attachments.GetUsageAsync(Root, company)).Files);
|
||||
await attachments.UploadAsync(Root, company, "sales.invoice", 1, "giusto.pdf", null, new MemoryStream(new byte[1024 * 1024]));
|
||||
await Assert.ThrowsExactlyAsync<ValidationFailedException>(
|
||||
() => attachments.UploadAsync(Root, company, "sales.invoice", 1, "vuoto.pdf", null, new MemoryStream()));
|
||||
await Assert.ThrowsExactlyAsync<ValidationFailedException>(
|
||||
() => attachments.UploadAsync(Root, company, "Not An Entity", 1, "a.pdf", null, new MemoryStream(new byte[1])));
|
||||
|
||||
var stranger = new Actor("mario", UserLevel.Standard, null, 1, "ALTRA");
|
||||
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => attachments.ListAsync(stranger, company, "sales.invoice", 1));
|
||||
var withoutRoles = new Actor("lucia", UserLevel.Standard, null, 999, company);
|
||||
await Assert.ThrowsExactlyAsync<AccessDeniedException>(() => attachments.ListAsync(withoutRoles, company, "sales.invoice", 1));
|
||||
await settings.SetAsync(AttachmentService.MaxUploadSetting, null);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TrashPurge_IsASystemTask()
|
||||
{
|
||||
await using var fixture = await Fixture.StartAsync();
|
||||
var scheduler = fixture.App.Services.GetRequiredService<JobScheduler>();
|
||||
await scheduler.EnsureSystemTasksAsync();
|
||||
|
||||
Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync("system.attachments-trash"));
|
||||
}
|
||||
|
||||
/// <summary>A started instance with an attachment service on a clock the test moves.</summary>
|
||||
private sealed class Fixture : IAsyncDisposable
|
||||
{
|
||||
private Fixture(WebApplication app, string company)
|
||||
{
|
||||
App = app;
|
||||
Company = company;
|
||||
var services = app.Services;
|
||||
Factory = services.GetRequiredService<IUnitOfWorkFactory>();
|
||||
Store = services.GetRequiredService<IFileStore>();
|
||||
Attachments = new AttachmentService(
|
||||
Factory, Store, services.GetRequiredService<PermissionService>(), services.GetRequiredService<AuditTrail>(),
|
||||
services.GetRequiredService<SystemSettingsStore>(), services.GetRequiredService<FileStoreOptions>(), Clock);
|
||||
Generation = new FileGenerationService(services.GetRequiredService<FileGeneratorRegistry>(), Attachments, services.GetRequiredService<PermissionService>(), Clock);
|
||||
}
|
||||
|
||||
public WebApplication App { get; }
|
||||
|
||||
public string Company { get; }
|
||||
|
||||
public MovableClock Clock { get; } = new();
|
||||
|
||||
public IUnitOfWorkFactory Factory { get; }
|
||||
|
||||
public IFileStore Store { get; }
|
||||
|
||||
public AttachmentService Attachments { get; }
|
||||
|
||||
public FileGenerationService Generation { get; }
|
||||
|
||||
public static async Task<Fixture> StartAsync()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
return new Fixture(app, company);
|
||||
}
|
||||
|
||||
public async Task<List<string>> StorageKeysAsync()
|
||||
{
|
||||
await using var unitOfWork = await Factory.CreateAsync(DatabaseScope.Company(Company));
|
||||
return (await unitOfWork.Repository<Attachment, long>().ListAsync(Query.For<Attachment>())).Items.Select(a => a.StorageKey).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await App.StopAsync();
|
||||
await App.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class MovableClock : TimeProvider
|
||||
{
|
||||
private DateTimeOffset _now = DateTimeOffset.UtcNow;
|
||||
|
||||
public void Advance(TimeSpan time) => _now += time;
|
||||
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user