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>
166 lines
8.8 KiB
C#
166 lines
8.8 KiB
C#
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);
|
|
}
|