using System.Globalization; using Khaemhat.Application.Security; using Khaemhat.Core.Files; using Khaemhat.Data; namespace Khaemhat.Application.Files; /// What a generator receives besides the output stream. /// Who asked for the file (the generator reads data on its behalf). /// The company. /// The entity of the record, for example sales.invoice. /// The record. /// The culture of numbers, dates and texts (it-IT). /// When the file is generated (UTC). public sealed record FileGenerationContext(Actor Actor, string CompanyCode, string Entity, long EntityId, CultureInfo Culture, DateTime Now); /// /// An output of the Genera file section (SPEC §9.4): print PDF, XML FatturaPA, rows in XLSX/CSV, courtesy ZIP... /// Modules register theirs as singletons; runs them. /// public interface IFileGenerator { /// The unique code, also written in attachments.generated_by (versions count per code), for example sales.invoice.pdf. string Code { get; } /// The text key of the label shown in the interface (Italian text in the Web resources). string TitleKey { get; } /// The media type of the output. string MediaType { get; } /// The extension of the output, with the dot (.pdf). string Extension { get; } /// Whether the generator applies to records of an entity. /// The entity. /// if it does. bool Supports(string entity); /// The file name for a record, with extension (for example Fattura-2026-15.pdf). /// The record. /// The file name. string FileName(FileGenerationContext context); /// Writes the file. The stream is write-only and not seekable; write with asynchronous calls. /// The record. /// The stream that receives the file; do not close it. /// Cancellation. /// A task. Task GenerateAsync(FileGenerationContext context, Stream output, CancellationToken cancellationToken); } /// The registered generators, by code. public sealed class FileGeneratorRegistry { private readonly Dictionary _byCode; /// Creates the registry. /// The generators (codes must be unique). public FileGeneratorRegistry(IEnumerable generators) { ArgumentNullException.ThrowIfNull(generators); _byCode = new Dictionary(StringComparer.Ordinal); foreach (var generator in generators) { if (!_byCode.TryAdd(generator.Code, generator)) { throw new InvalidOperationException($"Two file generators have code {generator.Code}."); } } } /// Every generator, by code. public IReadOnlyCollection All => _byCode.Values; /// The generator with a code. /// The code. /// The generator, or . public IFileGenerator? Find(string code) => _byCode.GetValueOrDefault(code); /// The generators that apply to an entity, by code. /// The entity. /// The generators. public IReadOnlyList For(string entity) => _byCode.Values.Where(g => g.Supports(entity)).OrderBy(g => g.Code, StringComparer.Ordinal).ToList(); } /// /// Runs the generators (SPEC §9.4): writes the file straight into the file store and /// records it as a generated attachment of the record, with the next version (v1, v2... "Rigenera"); /// writes it to any stream without keeping it (print preview, direct download). /// /// The generators. /// Records the generated files. /// Checks permissions for . /// The clock. public sealed class FileGenerationService(FileGeneratorRegistry registry, AttachmentService attachments, PermissionService permissions, TimeProvider clock) { /// Error: no generator with that code applies to the record. public const string UnknownGeneratorError = "attachments.generator_unknown"; private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); /// The generators that apply to an entity (the Genera file list). /// The entity. /// The generators. public IReadOnlyList AvailableFor(string entity) => registry.For(entity); /// Generates a file and attaches it to the record as the next version of the generator's series. /// Who generates (needs attachments.write). /// The company. /// The entity. /// The record. /// The generator. /// Cancellation. /// The new attachment. /// No such generator for the entity (). public Task 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); } /// Generates a file into a stream without attaching it (print preview, report download). /// Who asks (needs attachments.read). /// The company. /// The entity. /// The record. /// The generator. /// The stream; left open. /// Cancellation. /// The file name and media type of what was written. 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); }