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:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:06:48 +01:00
1 parent cf6f849cc1
commit b341ade9e9
26 files changed
+5319 -2

No files matched your search

@@ -0,0 +1,732 @@
using System.Data.Common;
using System.Globalization;
using System.Text.RegularExpressions;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Security;
using Khaemhat.Core.Files;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Files;
/// <summary>An attachment as the interface shows it.</summary>
/// <param name="Id">The identifier.</param>
/// <param name="Entity">The entity of the owning record.</param>
/// <param name="EntityId">The owning record.</param>
/// <param name="Kind">Uploaded, generated, e-invoice or notification.</param>
/// <param name="Name">The name.</param>
/// <param name="FileName">The download name, with the version suffix from v2 (<c>fattura_v2.pdf</c>).</param>
/// <param name="Mime">The media type.</param>
/// <param name="Size">The size in bytes.</param>
/// <param name="Sha256">The SHA-256 of the content.</param>
/// <param name="Version">The version, from 1.</param>
/// <param name="GeneratedBy">The generator code (generated files).</param>
/// <param name="Locked">Whether it is locked (cannot be deleted).</param>
/// <param name="IsLatest">Whether it is the latest version of its series.</param>
/// <param name="CreatedAt">When it was uploaded or generated (UTC).</param>
/// <param name="CreatedBy">Who uploaded or generated it.</param>
/// <param name="DeletedAt">When it was moved to the trash; <see langword="null"/> if in use.</param>
public sealed record AttachmentView(
long Id, string Entity, long EntityId, AttachmentKind Kind, string Name, string FileName, string Mime, long Size, string Sha256,
int Version, string? GeneratedBy, bool Locked, bool IsLatest, DateTime CreatedAt, string? CreatedBy, DateTime? DeletedAt)
{
/// <summary>How the interface can preview the file.</summary>
public AttachmentPreview Preview => MediaTypes.PreviewOf(Mime);
/// <summary>The version label, <c>v1</c>, <c>v2</c>...</summary>
public string VersionLabel => "v" + Version.ToString(CultureInfo.InvariantCulture);
/// <summary>The view of a row.</summary>
/// <param name="row">The row.</param>
/// <param name="isLatest">Whether it is the latest of its series.</param>
/// <returns>The view.</returns>
public static AttachmentView From(Attachment row, bool isLatest)
{
ArgumentNullException.ThrowIfNull(row);
return new AttachmentView(
row.Id, row.Entity, row.EntityId, row.Kind, row.Name, MediaTypes.VersionedFileName(row.Name, row.Version), row.Mime, row.Size, row.Sha256,
row.Version, row.GeneratedBy, row.Locked, isLatest, row.CreatedAt, row.UserName ?? row.CreatedBy, row.DeletedAt);
}
}
/// <summary>An open attachment: its description and its content. Dispose it to close the file.</summary>
/// <param name="attachment">The attachment.</param>
/// <param name="content">The content, a read-only seekable stream.</param>
public sealed class AttachmentContent(AttachmentView attachment, Stream content) : IAsyncDisposable, IDisposable
{
/// <summary>The attachment.</summary>
public AttachmentView Attachment { get; } = attachment;
/// <summary>The content.</summary>
public Stream Content { get; } = content;
/// <inheritdoc />
public ValueTask DisposeAsync() => Content.DisposeAsync();
/// <inheritdoc />
public void Dispose() => Content.Dispose();
}
/// <summary>A file to attach that is not uploaded by a user: an e-invoice, a notification, a file from a procedure.</summary>
/// <param name="Kind">The kind.</param>
/// <param name="FileName">The file name.</param>
/// <param name="Mime">The media type; from the extension when <see langword="null"/>.</param>
/// <param name="GeneratedBy">The procedure that produced it: the versions count per this code when set, per name otherwise.</param>
/// <param name="Locked">Whether it is locked from the start (for example the XML sent to the SDI).</param>
public sealed record AttachmentFile(AttachmentKind Kind, string FileName, string? Mime = null, string? GeneratedBy = null, bool Locked = false);
/// <summary>
/// The attachments of the company records (SPEC §9.4; wiki <i>Allegati e file</i>): upload, generated files with
/// versions, list, download, ZIP of all, lock, trash and restore. An attachment belongs to exactly one record
/// (<c>entity</c> + <c>entity_id</c>); its bytes are in the <see cref="IFileStore"/>, its row in <c>attachments</c>,
/// and every change writes the history (<see cref="AuditTrail"/>).
/// </summary>
/// <remarks>
/// Permissions: reading needs <c>attachments.read</c>, uploading, generating and locking <c>attachments.write</c>,
/// deleting and restoring <c>attachments.delete</c>. The permission on the owning record is checked by the caller (the
/// document service or page), which knows it. A company user works only in its own company. Deleting moves to the
/// company trash; <see cref="PurgeTrashAsync"/> removes rows and files 30 days later.
/// </remarks>
public sealed partial class AttachmentService
{
/// <summary>Permission to see and download attachments.</summary>
public const string ReadPermission = "attachments.read";
/// <summary>Permission to upload and generate attachments.</summary>
public const string WritePermission = "attachments.write";
/// <summary>Permission to delete and restore attachments.</summary>
public const string DeletePermission = "attachments.delete";
/// <summary>The instance setting with the largest upload in MB (default 25).</summary>
public const string MaxUploadSetting = "files.max-upload-mb";
/// <summary>The instance setting with the space each company may use in MB (default: no quota).</summary>
public const string CompanyQuotaSetting = "files.company-quota-mb";
/// <summary>Error: no such attachment (or not in this company).</summary>
public const string NotFoundError = "attachments.not_found";
/// <summary>Error: the attachment is locked.</summary>
public const string LockedError = "attachments.locked";
/// <summary>Error: the file is larger than the limit.</summary>
public const string TooLargeError = "attachments.file_too_large";
/// <summary>Error: the company has no space left.</summary>
public const string QuotaError = "attachments.quota_exceeded";
/// <summary>Error: the scanner rejected the file.</summary>
public const string RejectedError = "attachments.file_rejected";
/// <summary>Error: the entity or record is not valid.</summary>
public const string InvalidOwnerError = "attachments.owner_invalid";
/// <summary>Error: the file is empty.</summary>
public const string EmptyError = "attachments.file_empty";
/// <summary>How long attachments stay in the trash.</summary>
public static readonly TimeSpan TrashRetention = TimeSpan.FromDays(30);
private const int MaxVersionAttempts = 3;
private const long Megabyte = 1024 * 1024;
private readonly IUnitOfWorkFactory _factory;
private readonly IFileStore _store;
private readonly PermissionService _permissions;
private readonly AuditTrail _audit;
private readonly SystemSettingsStore _settings;
private readonly FileStoreOptions _options;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">Opens the company databases.</param>
/// <param name="store">The file store.</param>
/// <param name="permissions">Checks permissions.</param>
/// <param name="audit">Writes the history.</param>
/// <param name="settings">Reads the limits set by the administrators.</param>
/// <param name="options">The default limits.</param>
/// <param name="clock">The clock (trash dates).</param>
public AttachmentService(
IUnitOfWorkFactory factory, IFileStore store, PermissionService permissions, AuditTrail audit, SystemSettingsStore settings, FileStoreOptions options, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(store);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_store = store;
_permissions = permissions;
_audit = audit;
_settings = settings;
_options = options;
_clock = clock;
}
/// <summary>The limits in force: the instance settings, else the store defaults (25 MB, no quota).</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The limits for uploads.</returns>
public async Task<FileLimits> GetLimitsAsync(CancellationToken cancellationToken = default)
{
var max = await ReadMegabytesAsync(MaxUploadSetting, cancellationToken).ConfigureAwait(false) ?? _options.MaxFileBytes;
var quota = await ReadMegabytesAsync(CompanyQuotaSetting, cancellationToken).ConfigureAwait(false) ?? _options.CompanyQuotaBytes;
return new FileLimits(max, quota);
}
/// <summary>Uploads a file to a record (streaming; the size limit and the quota apply).</summary>
/// <param name="actor">Who uploads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity of the record, for example <c>sales.invoice</c>.</param>
/// <param name="entityId">The record.</param>
/// <param name="fileName">The file name as received.</param>
/// <param name="declaredMime">The type declared by the client (used only when the extension is unknown).</param>
/// <param name="content">The content.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment; a file with the same name as an existing one becomes its next version.</returns>
/// <exception cref="AccessDeniedException">The actor may not upload.</exception>
/// <exception cref="ValidationFailedException">The file is empty, too large, over quota or rejected.</exception>
public async Task<AttachmentView> UploadAsync(
Actor actor, string companyCode, string entity, long entityId, string fileName, string? declaredMime, Stream content, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(content);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
CheckOwner(entity, entityId);
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
var stored = await StoreAsync(company, limits, (target, ct) => content.CopyToAsync(target, ct), cancellationToken).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(fileName);
return await RecordAsync(actor, company, entity, entityId, new AttachmentFile(AttachmentKind.Uploaded, name, MediaTypes.Resolve(name, declaredMime)), stored, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Adds a file produced by Khaemhat, written by <paramref name="write"/> straight into the store. Each call adds
/// the next version of the series of <see cref="AttachmentFile.GeneratedBy"/> (or of the name): this is "Rigenera".
/// </summary>
/// <param name="actor">Who generates.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity of the record.</param>
/// <param name="entityId">The record.</param>
/// <param name="file">Kind, name, type, generator, lock.</param>
/// <param name="write">Writes the content to the stream it receives (write-only, not seekable).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment.</returns>
/// <exception cref="AccessDeniedException">The actor may not add attachments.</exception>
/// <exception cref="ValidationFailedException">The company has no space left, or the file is empty.</exception>
public async Task<AttachmentView> AddAsync(
Actor actor, string companyCode, string entity, long entityId, AttachmentFile file, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(file);
ArgumentNullException.ThrowIfNull(write);
var company = await DemandAsync(actor, companyCode, WritePermission, cancellationToken).ConfigureAwait(false);
CheckOwner(entity, entityId);
if (file.GeneratedBy is { } generator && (generator.Length is 0 or > 100))
{
throw new ValidationFailedException([InvalidOwnerError]);
}
// Files made by Khaemhat are bounded by their generator: only the quota applies.
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
var stored = await StoreAsync(company, new FileLimits(0, limits.QuotaBytes), write, cancellationToken).ConfigureAwait(false);
var name = MediaTypes.CleanFileName(file.FileName);
var normalized = file with { FileName = name, Mime = MediaTypes.Resolve(name, file.Mime) };
return await RecordAsync(actor, company, entity, entityId, normalized, stored, cancellationToken).ConfigureAwait(false);
}
/// <summary>The attachments of a record, newest first (trash excluded).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="includeOlderVersions">Whether to list the earlier versions too (marked not <see cref="AttachmentView.IsLatest"/>).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachments.</returns>
public async Task<IReadOnlyList<AttachmentView>> ListAsync(
Actor actor, string companyCode, string entity, long entityId, bool includeOlderVersions = false, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return Views(await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false), includeOlderVersions);
}
/// <summary>How many attachments a record has (latest versions only): the number on the toolbar icon.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The count.</returns>
public async Task<int> CountAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
(await ListAsync(actor, companyCode, entity, entityId, false, cancellationToken).ConfigureAwait(false)).Count;
/// <summary>One attachment, in use or in the trash.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachment, or <see langword="null"/>.</returns>
public async Task<AttachmentView?> GetAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
return (await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false))?.View;
}
/// <summary>Opens an attachment for download or preview.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachment and its content; dispose it.</returns>
/// <exception cref="KeyNotFoundException">No such attachment in use, or its file is missing.</exception>
public async Task<AttachmentContent> OpenAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var loaded = await LoadAsync(company, attachmentId, cancellationToken).ConfigureAwait(false);
if (loaded is not { } found || found.Row.DeletedAt is not null)
{
throw new KeyNotFoundException(NotFoundError);
}
var (row, view) = found;
try
{
return new AttachmentContent(view, _store.OpenRead(company, row.StorageKey));
}
catch (FileStoreException ex) when (ex.Code == FileStoreException.NotFound)
{
throw new KeyNotFoundException(NotFoundError, ex);
}
}
/// <summary>
/// Writes a ZIP with the latest version of every attachment of a record ("Scarica tutto"), streaming: the output
/// can be the HTTP response.
/// </summary>
/// <param name="actor">Who downloads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="output">The stream that receives the ZIP; it is left open.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many files were written.</returns>
public async Task<int> WriteZipAsync(Actor actor, string companyCode, string entity, long entityId, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(output);
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var rows = await ListRowsAsync(company, entity, entityId, cancellationToken).ConfigureAwait(false);
var keys = rows.ToDictionary(r => r.Id, r => r.StorageKey);
await using var zip = await ZipStreamWriter.CreateAsync(output, leaveOpen: true, cancellationToken).ConfigureAwait(false);
foreach (var attachment in Views(rows, includeOlderVersions: false))
{
var key = keys[attachment.Id];
if (!_store.Exists(company, key))
{
continue;
}
var content = _store.OpenRead(company, key);
await using (content.ConfigureAwait(false))
{
var level = attachment.Mime is "image/jpeg" or "image/png" or MediaTypes.Zip or MediaTypes.Xlsx
? System.IO.Compression.CompressionLevel.NoCompression
: System.IO.Compression.CompressionLevel.Optimal;
await zip.AddAsync(attachment.FileName, content, new DateTimeOffset(DateTime.SpecifyKind(attachment.CreatedAt, DateTimeKind.Utc)), level, cancellationToken).ConfigureAwait(false);
}
}
return zip.Count;
}
/// <summary>Locks an attachment: from now on it cannot be deleted (for example the XML sent to the SDI). Locks are permanent.</summary>
/// <param name="actor">Who locks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task LockAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor, companyCode, attachmentId, WritePermission,
row =>
{
if (row.Locked)
{
return false;
}
row.Locked = true;
return true;
},
cancellationToken);
/// <summary>Moves one attachment to the company trash (restorable for 30 days).</summary>
/// <param name="actor">Who deletes.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
/// <exception cref="ValidationFailedException">The attachment is locked (<see cref="LockedError"/>).</exception>
public Task DeleteAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default)
{
var now = _clock.GetUtcNow().UtcDateTime;
return ChangeAsync(
actor, companyCode, attachmentId, DeletePermission,
row =>
{
if (row.Locked)
{
throw new ValidationFailedException([LockedError]);
}
if (row.DeletedAt is not null)
{
return false;
}
row.DeletedAt = now;
return true;
},
cancellationToken);
}
/// <summary>Takes an attachment back from the trash.</summary>
/// <param name="actor">Who restores.</param>
/// <param name="companyCode">The company.</param>
/// <param name="attachmentId">The attachment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public Task RestoreAsync(Actor actor, string companyCode, long attachmentId, CancellationToken cancellationToken = default) =>
ChangeAsync(
actor, companyCode, attachmentId, DeletePermission,
row =>
{
if (row.DeletedAt is null)
{
return false;
}
row.DeletedAt = null;
return true;
},
cancellationToken);
/// <summary>
/// Moves every attachment of a record to the trash: call it in the deletion of the record (the caller has checked
/// that the record may be deleted). Refused when an attachment is locked: a record with a sent e-invoice cannot go.
/// </summary>
/// <param name="actor">Who deletes the record.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were moved.</returns>
/// <exception cref="ValidationFailedException">An attachment is locked (<see cref="LockedError"/>).</exception>
public Task<int> TrashForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: true, cancellationToken);
/// <summary>Takes back from the trash every attachment of a record (the record was restored).</summary>
/// <param name="actor">Who restores.</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were restored.</returns>
public Task<int> RestoreForEntityAsync(Actor actor, string companyCode, string entity, long entityId, CancellationToken cancellationToken = default) =>
ChangeEntityAsync(actor, companyCode, entity, entityId, toTrash: false, cancellationToken);
/// <summary>The company trash, most recently deleted first.</summary>
/// <param name="actor">Who looks (needs <c>attachments.delete</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The attachments in the trash.</returns>
public async Task<IReadOnlyList<AttachmentView>> ListTrashAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, DeletePermission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await unitOfWork.Repository<Attachment, long>().ListAsync(
Query.For<Attachment>().Where(a => a.DeletedAt != null).OrderByDescending(a => a.DeletedAt).Take(1000), cancellationToken).ConfigureAwait(false)).Items;
return rows.Select(r => AttachmentView.From(r, isLatest: false)).ToList();
}
/// <summary>The space the company uses in the file store, with the quota in force.</summary>
/// <param name="actor">Who looks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The usage.</returns>
public async Task<FileUsage> GetUsageAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await DemandAsync(actor, companyCode, ReadPermission, cancellationToken).ConfigureAwait(false);
var limits = await GetLimitsAsync(cancellationToken).ConfigureAwait(false);
return await _store.GetUsageAsync(company, limits.QuotaBytes, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Removes for good the attachments in the trash for more than 30 days, rows and files, and the partial files of
/// interrupted uploads. Run by the scheduled job <see cref="AttachmentTrashPurgeJob"/>.
/// </summary>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>How many attachments were removed.</returns>
public async Task<int> PurgeTrashAsync(string companyCode, CancellationToken cancellationToken = default)
{
var company = CompanyCodes.Normalize(companyCode);
var limit = _clock.GetUtcNow().UtcDateTime - TrashRetention;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
var rows = (await repository.ListAsync(Query.For<Attachment>().Where(a => a.DeletedAt != null && a.DeletedAt < limit), cancellationToken).ConfigureAwait(false)).Items;
var removed = 0;
foreach (var row in rows)
{
await unitOfWork.InTransactionAsync(
async ct =>
{
await repository.DeleteAsync(row.Id, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Delete, row.Id, row, null, Actor.System.UserName, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
// The row is gone: the file follows (a file left behind by a crash here is only wasted space).
if (!await StorageKeyInUseAsync(repository, row.StorageKey, cancellationToken).ConfigureAwait(false))
{
_store.Delete(company, row.StorageKey);
}
removed++;
}
_store.DeleteAbandonedParts(company, TimeSpan.FromDays(1));
return removed;
}
private static List<AttachmentView> Views(IReadOnlyList<Attachment> rows, bool includeOlderVersions)
{
var latest = rows.GroupBy(r => r.VersionKey, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Max(r => r.Version), StringComparer.Ordinal);
return rows
.Select(r => AttachmentView.From(r, r.Version == latest[r.VersionKey]))
.Where(v => includeOlderVersions || v.IsLatest)
.ToList();
}
private static void CheckOwner(string entity, long entityId)
{
if (entity is null || entity.Length > 100 || !EntityPattern().IsMatch(entity) || entityId <= 0)
{
throw new ValidationFailedException([InvalidOwnerError]);
}
}
private static string VersionKeyOf(AttachmentFile file) =>
file.GeneratedBy is { } generator ? "gen:" + generator : "name:" + file.FileName.ToLowerInvariant();
private static async Task<bool> IsLatestAsync(IUnitOfWork unitOfWork, Attachment row, CancellationToken cancellationToken)
{
var (entity, id, key, version) = (row.Entity, row.EntityId, row.VersionKey, row.Version);
return await unitOfWork.Repository<Attachment, long>().CountAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == id && a.VersionKey == key && a.Version > version),
cancellationToken).ConfigureAwait(false) == 0;
}
private static async Task<bool> StorageKeyInUseAsync(IRepository<Attachment, long> repository, string key, CancellationToken cancellationToken) =>
await repository.CountAsync(Query.For<Attachment>().Where(a => a.StorageKey == key), cancellationToken).ConfigureAwait(false) > 0;
[GeneratedRegex("^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_-]*)*$", RegexOptions.CultureInvariant)]
private static partial Regex EntityPattern();
private async Task<string> DemandAsync(Actor actor, string companyCode, string permission, CancellationToken cancellationToken)
{
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, permission, cancellationToken).ConfigureAwait(false);
return company;
}
private async Task<long?> ReadMegabytesAsync(string key, CancellationToken cancellationToken)
{
var value = await _settings.GetAsync(key, cancellationToken).ConfigureAwait(false);
return long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var megabytes) && megabytes >= 0 ? megabytes * Megabyte : null;
}
private async Task<StoredFile> StoreAsync(string company, FileLimits limits, Func<Stream, CancellationToken, Task> write, CancellationToken cancellationToken)
{
try
{
await using var writer = await _store.CreateAsync(company, limits, cancellationToken).ConfigureAwait(false);
await write(writer.Content, cancellationToken).ConfigureAwait(false);
if (writer.Content.Length == 0)
{
throw new ValidationFailedException([EmptyError]);
}
return await writer.CommitAsync(cancellationToken).ConfigureAwait(false);
}
catch (FileStoreException ex)
{
var code = ex.Code switch
{
FileStoreException.TooLarge => TooLargeError,
FileStoreException.QuotaExceeded => QuotaError,
_ => RejectedError,
};
throw new ValidationFailedException(code, ex);
}
}
private async Task<AttachmentView> RecordAsync(
Actor actor, string company, string entity, long entityId, AttachmentFile file, StoredFile stored, CancellationToken cancellationToken)
{
var key = VersionKeyOf(file);
try
{
for (var attempt = 1; ; attempt++)
{
try
{
return await InsertAsync(actor, company, entity, entityId, file, key, stored, cancellationToken).ConfigureAwait(false);
}
catch (DbException) when (attempt < MaxVersionAttempts)
{
// Two versions of the same series at once: the unique index refused one; take the next number.
}
}
}
catch
{
_store.Delete(company, stored.Key);
throw;
}
}
private async Task<AttachmentView> InsertAsync(
Actor actor, string company, string entity, long entityId, AttachmentFile file, string key, StoredFile stored, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
Attachment? row = null;
await unitOfWork.InTransactionAsync(
async ct =>
{
var last = await repository.FindAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.VersionKey == key).OrderByDescending(a => a.Version).Take(1),
ct).ConfigureAwait(false);
row = new Attachment
{
Entity = entity,
EntityId = entityId,
Kind = file.Kind,
Name = file.FileName,
Mime = file.Mime ?? MediaTypes.OctetStream,
Size = stored.Size,
Sha256 = stored.Sha256,
Version = (last?.Version ?? 0) + 1,
VersionKey = key,
GeneratedBy = file.GeneratedBy,
StorageKey = stored.Key,
UserName = actor.UserName.Length > 100 ? actor.UserName[..100] : actor.UserName,
Locked = file.Locked,
};
await repository.InsertAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Insert, row.Id, null, row, actor.UserName, ct).ConfigureAwait(false);
},
cancellationToken).ConfigureAwait(false);
return AttachmentView.From(row!, isLatest: true);
}
private async Task ChangeAsync(Actor actor, string companyCode, long attachmentId, string permission, Func<Attachment, bool> change, CancellationToken cancellationToken)
{
var company = await DemandAsync(actor, companyCode, permission, cancellationToken).ConfigureAwait(false);
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
var row = await repository.GetAsync(attachmentId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException(NotFoundError);
var before = Copy(row);
if (change(row))
{
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
}
},
cancellationToken).ConfigureAwait(false);
}
private async Task<int> ChangeEntityAsync(Actor actor, string companyCode, string entity, long entityId, bool toTrash, CancellationToken cancellationToken)
{
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.");
}
CheckOwner(entity, entityId);
var now = _clock.GetUtcNow().UtcDateTime;
var changed = 0;
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var repository = unitOfWork.Repository<Attachment, long>();
await unitOfWork.InTransactionAsync(
async ct =>
{
var query = toTrash
? Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null)
: Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt != null);
var rows = (await repository.ListAsync(query, ct).ConfigureAwait(false)).Items;
if (toTrash && rows.Any(r => r.Locked))
{
throw new ValidationFailedException([LockedError]);
}
foreach (var row in rows)
{
var before = Copy(row);
row.DeletedAt = toTrash ? now : null;
await repository.UpdateAsync(row, ct).ConfigureAwait(false);
await _audit.RecordAsync(unitOfWork, AuditAction.Update, row.Id, before, row, actor.UserName, ct).ConfigureAwait(false);
changed++;
}
},
cancellationToken).ConfigureAwait(false);
return changed;
}
private async Task<IReadOnlyList<Attachment>> ListRowsAsync(string company, string entity, long entityId, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await unitOfWork.Repository<Attachment, long>().ListAsync(
Query.For<Attachment>().Where(a => a.Entity == entity && a.EntityId == entityId && a.DeletedAt == null).OrderByDescending(a => a.Id),
cancellationToken).ConfigureAwait(false)).Items;
}
private async Task<(Attachment Row, AttachmentView View)?> LoadAsync(string company, long attachmentId, CancellationToken cancellationToken)
{
await using var unitOfWork = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await unitOfWork.Repository<Attachment, long>().GetAsync(attachmentId, cancellationToken).ConfigureAwait(false);
return row is null ? null : (row, AttachmentView.From(row, await IsLatestAsync(unitOfWork, row, cancellationToken).ConfigureAwait(false)));
}
private static Attachment Copy(Attachment row) => new()
{
Id = row.Id,
Entity = row.Entity,
EntityId = row.EntityId,
Kind = row.Kind,
Name = row.Name,
Mime = row.Mime,
Size = row.Size,
Sha256 = row.Sha256,
Version = row.Version,
VersionKey = row.VersionKey,
GeneratedBy = row.GeneratedBy,
StorageKey = row.StorageKey,
UserName = row.UserName,
Locked = row.Locked,
DeletedAt = row.DeletedAt,
};
}
@@ -0,0 +1,36 @@
using System.Globalization;
using Khaemhat.Application.Jobs;
using Khaemhat.Core.Instance;
using Khaemhat.Data.Companies;
namespace Khaemhat.Application.Files;
/// <summary>
/// Empties the company trash of attachments (SPEC §9.4): every night, in every company that is not disabled, removes
/// rows and files deleted more than 30 days ago and the partial files of interrupted uploads.
/// </summary>
/// <param name="attachments">The attachments.</param>
/// <param name="companies">The companies.</param>
public sealed class AttachmentTrashPurgeJob(AttachmentService attachments, ICompanyRegistry companies) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "system.attachments-trash";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
var removed = 0;
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is not CompanyStatus.Disabled)
{
removed += await attachments.PurgeTrashAsync(company.Code, cancellationToken).ConfigureAwait(false);
}
}
return string.Create(CultureInfo.InvariantCulture, $"{removed} allegati eliminati dal cestino.");
}
}
@@ -0,0 +1,238 @@
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);
}
}
}
@@ -0,0 +1,165 @@
using System.Globalization;
using Khaemhat.Application.Security;
using Khaemhat.Core.Files;
using Khaemhat.Data;
namespace Khaemhat.Application.Files;
/// <summary>What a generator receives besides the output stream.</summary>
/// <param name="Actor">Who asked for the file (the generator reads data on its behalf).</param>
/// <param name="CompanyCode">The company.</param>
/// <param name="Entity">The entity of the record, for example <c>sales.invoice</c>.</param>
/// <param name="EntityId">The record.</param>
/// <param name="Culture">The culture of numbers, dates and texts (it-IT).</param>
/// <param name="Now">When the file is generated (UTC).</param>
public sealed record FileGenerationContext(Actor Actor, string CompanyCode, string Entity, long EntityId, CultureInfo Culture, DateTime Now);
/// <summary>
/// An output of the <i>Genera file</i> section (SPEC §9.4): print PDF, XML FatturaPA, rows in XLSX/CSV, courtesy ZIP...
/// Modules register theirs as <see cref="IFileGenerator"/> singletons; <see cref="FileGenerationService"/> runs them.
/// </summary>
public interface IFileGenerator
{
/// <summary>The unique code, also written in <c>attachments.generated_by</c> (versions count per code), for example <c>sales.invoice.pdf</c>.</summary>
string Code { get; }
/// <summary>The text key of the label shown in the interface (Italian text in the Web resources).</summary>
string TitleKey { get; }
/// <summary>The media type of the output.</summary>
string MediaType { get; }
/// <summary>The extension of the output, with the dot (<c>.pdf</c>).</summary>
string Extension { get; }
/// <summary>Whether the generator applies to records of an entity.</summary>
/// <param name="entity">The entity.</param>
/// <returns><see langword="true"/> if it does.</returns>
bool Supports(string entity);
/// <summary>The file name for a record, with extension (for example <c>Fattura-2026-15.pdf</c>).</summary>
/// <param name="context">The record.</param>
/// <returns>The file name.</returns>
string FileName(FileGenerationContext context);
/// <summary>Writes the file. The stream is write-only and not seekable; write with asynchronous calls.</summary>
/// <param name="context">The record.</param>
/// <param name="output">The stream that receives the file; do not close it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken);
}
/// <summary>The registered generators, by code.</summary>
public sealed class FileGeneratorRegistry
{
private readonly Dictionary<string, IFileGenerator> _byCode;
/// <summary>Creates the registry.</summary>
/// <param name="generators">The generators (codes must be unique).</param>
public FileGeneratorRegistry(IEnumerable<IFileGenerator> generators)
{
ArgumentNullException.ThrowIfNull(generators);
_byCode = new Dictionary<string, IFileGenerator>(StringComparer.Ordinal);
foreach (var generator in generators)
{
if (!_byCode.TryAdd(generator.Code, generator))
{
throw new InvalidOperationException($"Two file generators have code {generator.Code}.");
}
}
}
/// <summary>Every generator, by code.</summary>
public IReadOnlyCollection<IFileGenerator> All => _byCode.Values;
/// <summary>The generator with a code.</summary>
/// <param name="code">The code.</param>
/// <returns>The generator, or <see langword="null"/>.</returns>
public IFileGenerator? Find(string code) => _byCode.GetValueOrDefault(code);
/// <summary>The generators that apply to an entity, by code.</summary>
/// <param name="entity">The entity.</param>
/// <returns>The generators.</returns>
public IReadOnlyList<IFileGenerator> For(string entity) =>
_byCode.Values.Where(g => g.Supports(entity)).OrderBy(g => g.Code, StringComparer.Ordinal).ToList();
}
/// <summary>
/// Runs the generators (SPEC §9.4): <see cref="GenerateAsync"/> writes the file straight into the file store and
/// records it as a generated attachment of the record, with the next version (<c>v1</c>, <c>v2</c>... "Rigenera");
/// <see cref="WriteAsync"/> writes it to any stream without keeping it (print preview, direct download).
/// </summary>
/// <param name="registry">The generators.</param>
/// <param name="attachments">Records the generated files.</param>
/// <param name="permissions">Checks permissions for <see cref="WriteAsync"/>.</param>
/// <param name="clock">The clock.</param>
public sealed class FileGenerationService(FileGeneratorRegistry registry, AttachmentService attachments, PermissionService permissions, TimeProvider clock)
{
/// <summary>Error: no generator with that code applies to the record.</summary>
public const string UnknownGeneratorError = "attachments.generator_unknown";
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
/// <summary>The generators that apply to an entity (the <i>Genera file</i> list).</summary>
/// <param name="entity">The entity.</param>
/// <returns>The generators.</returns>
public IReadOnlyList<IFileGenerator> AvailableFor(string entity) => registry.For(entity);
/// <summary>Generates a file and attaches it to the record as the next version of the generator's series.</summary>
/// <param name="actor">Who generates (needs <c>attachments.write</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="generatorCode">The generator.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new attachment.</returns>
/// <exception cref="ValidationFailedException">No such generator for the entity (<see cref="UnknownGeneratorError"/>).</exception>
public Task<AttachmentView> GenerateAsync(
Actor actor, string companyCode, string entity, long entityId, string generatorCode, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var generator = Resolve(entity, generatorCode);
var context = Context(actor, companyCode, entity, entityId);
var file = new AttachmentFile(AttachmentKind.Generated, generator.FileName(context), generator.MediaType, generator.Code);
return attachments.AddAsync(actor, companyCode, entity, entityId, file, (output, ct) => generator.GenerateAsync(context, output, ct), cancellationToken);
}
/// <summary>Generates a file into a stream without attaching it (print preview, report download).</summary>
/// <param name="actor">Who asks (needs <c>attachments.read</c>).</param>
/// <param name="companyCode">The company.</param>
/// <param name="entity">The entity.</param>
/// <param name="entityId">The record.</param>
/// <param name="generatorCode">The generator.</param>
/// <param name="output">The stream; left open.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file name and media type of what was written.</returns>
public async Task<(string FileName, string MediaType)> WriteAsync(
Actor actor, string companyCode, string entity, long entityId, string generatorCode, Stream output, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(output);
var generator = Resolve(entity, generatorCode);
if (!actor.IsInstanceAccount && !string.Equals(actor.CompanyCode, CompanyCodes.Normalize(companyCode), StringComparison.Ordinal))
{
throw new AccessDeniedException(SecurityErrors.PermissionDenied, "A company user works only in its own company.");
}
await permissions.DemandAsync(actor, AttachmentService.ReadPermission, cancellationToken).ConfigureAwait(false);
var context = Context(actor, companyCode, entity, entityId);
await generator.GenerateAsync(context, output, cancellationToken).ConfigureAwait(false);
return (MediaTypes.CleanFileName(generator.FileName(context)), generator.MediaType);
}
private IFileGenerator Resolve(string entity, string generatorCode)
{
ArgumentNullException.ThrowIfNull(entity);
ArgumentNullException.ThrowIfNull(generatorCode);
return registry.Find(generatorCode) is { } generator && generator.Supports(entity)
? generator
: throw new ValidationFailedException([UnknownGeneratorError]);
}
private FileGenerationContext Context(Actor actor, string companyCode, string entity, long entityId) =>
new(actor, CompanyCodes.Normalize(companyCode), entity, entityId, Italian, clock.GetUtcNow().UtcDateTime);
}
@@ -0,0 +1,157 @@
using System.Text;
namespace Khaemhat.Application.Files;
/// <summary>How the interface can show a file in the preview (SPEC §9.4: PDF, images, XML, CSV/XLSX).</summary>
public enum AttachmentPreview
{
/// <summary>No preview: the file can only be downloaded.</summary>
None = 0,
/// <summary>The integrated PDF viewer.</summary>
Pdf = 1,
/// <summary>An image, at full size with zoom.</summary>
Image = 2,
/// <summary>XML, formatted and indented.</summary>
Xml = 3,
/// <summary>CSV, as a grid.</summary>
Csv = 4,
/// <summary>XLSX, as a grid.</summary>
Xlsx = 5,
/// <summary>Plain text.</summary>
Text = 6,
}
/// <summary>
/// Media types and file names of attachments. The media type is taken from the extension when it is known (the type
/// declared by a browser is not trusted), and file names are cleaned so they are safe on every file system and in a
/// ZIP.
/// </summary>
public static class MediaTypes
{
/// <summary>The type of unknown content.</summary>
public const string OctetStream = "application/octet-stream";
/// <summary>PDF.</summary>
public const string Pdf = "application/pdf";
/// <summary>CSV.</summary>
public const string Csv = "text/csv";
/// <summary>XLSX.</summary>
public const string Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/// <summary>ZIP.</summary>
public const string Zip = "application/zip";
/// <summary>XML.</summary>
public const string Xml = "application/xml";
/// <summary>The longest file name kept.</summary>
public const int MaxFileNameLength = 255;
private static readonly Dictionary<string, string> ByExtension = new(StringComparer.OrdinalIgnoreCase)
{
[".pdf"] = Pdf,
[".xml"] = Xml,
[".p7m"] = "application/pkcs7-mime",
[".csv"] = Csv,
[".txt"] = "text/plain",
[".json"] = "application/json",
[".xlsx"] = Xlsx,
[".xls"] = "application/vnd.ms-excel",
[".ods"] = "application/vnd.oasis.opendocument.spreadsheet",
[".docx"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
[".doc"] = "application/msword",
[".odt"] = "application/vnd.oasis.opendocument.text",
[".zip"] = Zip,
[".jpg"] = "image/jpeg",
[".jpeg"] = "image/jpeg",
[".png"] = "image/png",
[".gif"] = "image/gif",
[".webp"] = "image/webp",
[".tif"] = "image/tiff",
[".tiff"] = "image/tiff",
[".eml"] = "message/rfc822",
};
/// <summary>The media type of a file: from its extension when known, else the declared type when well formed.</summary>
/// <param name="fileName">The file name.</param>
/// <param name="declared">The type declared by the client, if any.</param>
/// <returns>The media type.</returns>
public static string Resolve(string fileName, string? declared = null)
{
if (ByExtension.TryGetValue(Path.GetExtension(fileName ?? string.Empty), out var known))
{
return known;
}
return IsWellFormed(declared) ? declared!.Trim().ToLowerInvariant() : OctetStream;
}
/// <summary>How a file can be previewed.</summary>
/// <param name="mime">The media type.</param>
/// <returns>The preview.</returns>
public static AttachmentPreview PreviewOf(string? mime) => mime switch
{
Pdf => AttachmentPreview.Pdf,
"image/jpeg" or "image/png" or "image/gif" or "image/webp" => AttachmentPreview.Image,
Xml or "text/xml" => AttachmentPreview.Xml,
Csv => AttachmentPreview.Csv,
Xlsx => AttachmentPreview.Xlsx,
"text/plain" or "application/json" => AttachmentPreview.Text,
_ => AttachmentPreview.None,
};
/// <summary>
/// Cleans a file name: no folders, no control characters or characters Windows refuses, at most 255 characters
/// keeping the extension; <c>file</c> when nothing is left.
/// </summary>
/// <param name="fileName">The name as received.</param>
/// <returns>The clean name.</returns>
public static string CleanFileName(string? fileName)
{
var name = (fileName ?? string.Empty).Replace('\\', '/');
name = name[(name.LastIndexOf('/') + 1)..];
var builder = new StringBuilder(name.Length);
foreach (var c in name)
{
builder.Append(char.IsControl(c) || c is ':' or '*' or '?' or '"' or '<' or '>' or '|' ? '_' : c);
}
var clean = builder.ToString().Trim().TrimEnd('.').Trim();
if (clean.Length > MaxFileNameLength)
{
var extension = Path.GetExtension(clean);
extension = extension.Length > 20 ? string.Empty : extension;
clean = clean[..(MaxFileNameLength - extension.Length)] + extension;
}
return clean.Length == 0 || clean is "." or ".." ? "file" : clean;
}
/// <summary>The download name of a version: <c>name.pdf</c> for v1, <c>name_v2.pdf</c> after.</summary>
/// <param name="name">The attachment name.</param>
/// <param name="version">The version.</param>
/// <returns>The file name.</returns>
public static string VersionedFileName(string name, int version)
{
ArgumentNullException.ThrowIfNull(name);
if (version <= 1)
{
return name;
}
var extension = Path.GetExtension(name);
return name[..^extension.Length] + "_v" + version.ToString(System.Globalization.CultureInfo.InvariantCulture) + extension;
}
private static bool IsWellFormed(string? mime) =>
mime is { Length: > 2 and <= 150 } && mime.Count(c => c == '/') == 1
&& mime.Trim().All(c => char.IsAsciiLetterOrDigit(c) || c is '/' or '.' or '+' or '-');
}
@@ -49,12 +49,13 @@ public sealed record SystemTaskDefinition(string Code, string Name, string JobTy
/// </summary>
public sealed class JobScheduler
{
/// <summary>The system tasks of M2.</summary>
/// <summary>The system tasks (M2, attachments trash from M3).</summary>
public static readonly IReadOnlyList<SystemTaskDefinition> SystemTasks =
[
new("system.sessions-cleanup", "Pulizia sessioni scadute", SessionCleanupJob.JobType, "15 * * * *", 300),
new("system.license-check", "Verifica licenza", LicenseCheckJob.JobType, "0 * * * *", 120),
new("system.log-retention", "Conservazione del log", LogRetentionJob.JobType, "30 3 * * *", 1800),
new("system.attachments-trash", "Svuotamento cestino allegati", Files.AttachmentTrashPurgeJob.JobType, "45 3 * * *", 1800),
];
private readonly IUnitOfWorkFactory _factory;