feat: attachments, file store and in-house PDF/CSV/XLSX/ZIP writers (#34)
Documents need attachments and generated files (SPEC 9.4) before the UI of M3 can show them, and the spec forbids external libraries for PDF and spreadsheets. - VolumeFileStore keeps files under <data>/files/<COMPANY>/<yyyy>/<guid>, writing a .part file in the same folder with size limit and SHA-256, then quota and scanner checks (IFileScanner hook, no-op by default). - attachments table (migration 007) with kind, version series, lock, trash and the uploading user; AttachmentService uploads, adds generated files as the next version, lists, opens, zips, locks, trashes, restores and purges after 30 days (new system job system.attachments-trash). - FileGenerationService runs IFileGenerator implementations into the store; three generators for the fictitious test document (PDF, CSV, XLSX). - CsvWriter (Italian Excel defaults, formula-injection guard), XlsxWriter, ZipStreamWriter and PdfWriter (standard Type1 fonts, WinAnsi, AFM widths, JPEG, Flate, xref) only write asynchronously, so they can stream to an HTTP response. - ADR 0021 records versioning, storage layout, PDF scope and CSV defaults. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cf6f849cc1
commit
b341ade9e9
26 files changed
+5319
-2
No files matched your search
@@ -0,0 +1,80 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Files;
|
||||
|
||||
/// <summary>Where an attachment comes from (SPEC §9.4).</summary>
|
||||
public enum AttachmentKind
|
||||
{
|
||||
/// <summary>A file uploaded by a user (the customer's order, a photo, a spreadsheet).</summary>
|
||||
Uploaded = 0,
|
||||
|
||||
/// <summary>A file produced by Khaemhat (print PDF, exported rows, courtesy ZIP).</summary>
|
||||
Generated = 1,
|
||||
|
||||
/// <summary>An electronic invoice (FatturaPA XML, P7M) issued or received.</summary>
|
||||
EInvoice = 2,
|
||||
|
||||
/// <summary>A notification of the exchange system (SDI receipts).</summary>
|
||||
Notification = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file that belongs to exactly one record of the company (<c>attachments</c>, SPEC §9.4): a document, a party, an
|
||||
/// item... There are no loose attachments. The bytes live in the company folder of the file store under
|
||||
/// <see cref="StorageKey"/>; the row keeps name, type, size, SHA-256 and version.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Versions are numbered per <see cref="VersionKey"/> inside the record: a generated file counts per generator code
|
||||
/// (<see cref="GeneratedBy"/>), so "Rigenera" adds <c>v2</c>, <c>v3</c>...; an uploaded file counts per file name, so
|
||||
/// uploading a file with the same name again adds a version instead of replacing the previous one (ADR 0021).
|
||||
/// </remarks>
|
||||
public sealed class Attachment : Entity<long>
|
||||
{
|
||||
/// <summary>The entity of the owning record, for example <c>sales.invoice</c> or <c>parties.party</c>.</summary>
|
||||
public string Entity { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The identifier of the owning record.</summary>
|
||||
public long EntityId { get; set; }
|
||||
|
||||
/// <summary>Where the file comes from.</summary>
|
||||
public AttachmentKind Kind { get; set; }
|
||||
|
||||
/// <summary>The file name shown and used for downloads (without the version suffix).</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The media type, for example <c>application/pdf</c>.</summary>
|
||||
public string Mime { get; set; } = "application/octet-stream";
|
||||
|
||||
/// <summary>The size in bytes.</summary>
|
||||
public long Size { get; set; }
|
||||
|
||||
/// <summary>The SHA-256 of the content, 64 lowercase hexadecimal characters.</summary>
|
||||
public string Sha256 { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The version inside <see cref="VersionKey"/>, from 1.</summary>
|
||||
public int Version { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// The series the version counts in: <c>gen:<generator code></c> for generated files, <c>name:<lowercase
|
||||
/// name></c> otherwise. Unique with the record and <see cref="Version"/>.
|
||||
/// </summary>
|
||||
public string VersionKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The template or procedure that produced the file (generated files), for example <c>demo.test-pdf</c>.</summary>
|
||||
public string? GeneratedBy { get; set; }
|
||||
|
||||
/// <summary>Where the bytes are in the company folder of the file store (<c>yyyy/guid</c>).</summary>
|
||||
public string StorageKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Who uploaded or generated the file (the actor of the service call). The audit column <c>created_by</c> knows
|
||||
/// the user only inside an HTTP request; this one is always set.
|
||||
/// </summary>
|
||||
public string? UserName { get; set; }
|
||||
|
||||
/// <summary>A locked file (for example the XML sent to the SDI) cannot be deleted or replaced.</summary>
|
||||
public bool Locked { get; set; }
|
||||
|
||||
/// <summary>When the attachment was moved to the company trash; <see langword="null"/> while it is in use.</summary>
|
||||
public DateTime? DeletedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
namespace Khaemhat.Core.Files;
|
||||
|
||||
/// <summary>A file saved in the store.</summary>
|
||||
/// <param name="Key">Where it is in the company folder (<c>yyyy/guid</c>); keep it to open or delete the file.</param>
|
||||
/// <param name="Size">The size in bytes.</param>
|
||||
/// <param name="Sha256">The SHA-256 of the content, lowercase hexadecimal.</param>
|
||||
public sealed record StoredFile(string Key, long Size, string Sha256);
|
||||
|
||||
/// <summary>The space a company uses in the store.</summary>
|
||||
/// <param name="Files">How many files.</param>
|
||||
/// <param name="Bytes">Their total size.</param>
|
||||
/// <param name="QuotaBytes">The quota of the company; 0 means no quota.</param>
|
||||
public sealed record FileUsage(long Files, long Bytes, long QuotaBytes)
|
||||
{
|
||||
/// <summary>The bytes still available; <see cref="long.MaxValue"/> without quota.</summary>
|
||||
public long RemainingBytes => QuotaBytes <= 0 ? long.MaxValue : Math.Max(0, QuotaBytes - Bytes);
|
||||
|
||||
/// <summary>Whether the company uses more than its quota.</summary>
|
||||
public bool IsOverQuota => QuotaBytes > 0 && Bytes > QuotaBytes;
|
||||
}
|
||||
|
||||
/// <summary>The limits applied while a file is written.</summary>
|
||||
/// <param name="MaxBytes">The largest file accepted; 0 means no limit.</param>
|
||||
/// <param name="QuotaBytes">The space a company may use in all; 0 means no quota.</param>
|
||||
public sealed record FileLimits(long MaxBytes, long QuotaBytes)
|
||||
{
|
||||
/// <summary>The default size limit of an uploaded file (SPEC §9.4): 25 MB.</summary>
|
||||
public const long DefaultMaxBytes = 25L * 1024 * 1024;
|
||||
|
||||
/// <summary>No limit at all (generated files are bounded by their generator).</summary>
|
||||
public static FileLimits None { get; } = new(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>Why the store refused a file. <see cref="Code"/> is one of the constants of this class.</summary>
|
||||
public sealed class FileStoreException : Exception
|
||||
{
|
||||
/// <summary>The file is larger than <see cref="FileLimits.MaxBytes"/>.</summary>
|
||||
public const string TooLarge = "file_too_large";
|
||||
|
||||
/// <summary>The file would take the company over its quota.</summary>
|
||||
public const string QuotaExceeded = "file_quota_exceeded";
|
||||
|
||||
/// <summary>The scanner (<see cref="IFileScanner"/>) rejected the file.</summary>
|
||||
public const string Rejected = "file_rejected";
|
||||
|
||||
/// <summary>The file does not exist in the store.</summary>
|
||||
public const string NotFound = "file_not_found";
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public FileStoreException()
|
||||
: this(NotFound, "File store error.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public FileStoreException(string message)
|
||||
: this(NotFound, message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public FileStoreException(string message, Exception innerException)
|
||||
: base(message, innerException) => Code = NotFound;
|
||||
|
||||
/// <summary>Creates the exception.</summary>
|
||||
/// <param name="code">The error code.</param>
|
||||
/// <param name="message">The message.</param>
|
||||
public FileStoreException(string code, string message)
|
||||
: base(message) => Code = code;
|
||||
|
||||
/// <summary>The error code.</summary>
|
||||
public string Code { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file being written to the store: write the content to <see cref="Content"/>, then call
|
||||
/// <see cref="CommitAsync"/>. Disposing without committing discards what was written.
|
||||
/// </summary>
|
||||
public interface IFileStoreWriter : IAsyncDisposable
|
||||
{
|
||||
/// <summary>The write-only, non-seekable stream that receives the content (it counts bytes and computes SHA-256).</summary>
|
||||
/// <exception cref="FileStoreException">Writing goes past <see cref="FileLimits.MaxBytes"/> (code <see cref="FileStoreException.TooLarge"/>).</exception>
|
||||
Stream Content { get; }
|
||||
|
||||
/// <summary>Completes the file: checks quota and scanner, then makes it visible under its key.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored file.</returns>
|
||||
/// <exception cref="FileStoreException">The file is refused.</exception>
|
||||
Task<StoredFile> CommitAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where attachment bytes live (SPEC §9.4): one folder per company, one subfolder per year. Writes are streamed and
|
||||
/// atomic (a partial file is never visible under its key); every key belongs to one company and cannot reach outside
|
||||
/// its folder.
|
||||
/// </summary>
|
||||
public interface IFileStore
|
||||
{
|
||||
/// <summary>Saves a file read from a stream.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="content">The content, read to the end.</param>
|
||||
/// <param name="limits">The limits; <see langword="null"/> for the store defaults.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored file.</returns>
|
||||
/// <exception cref="FileStoreException">The file is refused (size, quota, scanner).</exception>
|
||||
Task<StoredFile> SaveAsync(string companyCode, Stream content, FileLimits? limits = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Starts a file that the caller writes (generators, ZIP packages).</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="limits">The limits; <see langword="null"/> for the store defaults.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The writer; dispose it in every case.</returns>
|
||||
Task<IFileStoreWriter> CreateAsync(string companyCode, FileLimits? limits = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Opens a file for reading.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key returned when the file was saved.</param>
|
||||
/// <returns>A read-only seekable stream; dispose it.</returns>
|
||||
/// <exception cref="FileStoreException">The file does not exist (code <see cref="FileStoreException.NotFound"/>).</exception>
|
||||
Stream OpenRead(string companyCode, string key);
|
||||
|
||||
/// <summary>Whether a file exists.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> if it exists.</returns>
|
||||
bool Exists(string companyCode, string key);
|
||||
|
||||
/// <summary>Deletes a file; nothing happens when it does not exist.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns><see langword="true"/> if a file was deleted.</returns>
|
||||
bool Delete(string companyCode, string key);
|
||||
|
||||
/// <summary>The space the company uses, with its quota.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="quotaBytes">The quota to report; <see langword="null"/> for the store default.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The usage.</returns>
|
||||
Task<FileUsage> GetUsageAsync(string companyCode, long? quotaBytes = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Removes the partial files (<c>.part</c>) left by writes interrupted more than <paramref name="olderThan"/> ago.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="olderThan">How old a partial file must be.</param>
|
||||
/// <returns>How many were removed.</returns>
|
||||
int DeleteAbandonedParts(string companyCode, TimeSpan olderThan);
|
||||
}
|
||||
|
||||
/// <summary>The verdict of a scanner.</summary>
|
||||
/// <param name="Clean">Whether the file may be stored.</param>
|
||||
/// <param name="Reason">Why it was refused (for example the name of the threat).</param>
|
||||
public sealed record FileScanResult(bool Clean, string? Reason = null)
|
||||
{
|
||||
/// <summary>The file may be stored.</summary>
|
||||
public static FileScanResult Ok { get; } = new(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The hook for an antivirus (SPEC §9.4): Khaemhat includes none, the default implementation accepts every file. It
|
||||
/// runs on the complete file before it becomes visible.
|
||||
/// </summary>
|
||||
public interface IFileScanner
|
||||
{
|
||||
/// <summary>Scans a file.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="content">The content, readable from the start.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The verdict.</returns>
|
||||
ValueTask<FileScanResult> ScanAsync(string companyCode, Stream content, CancellationToken cancellationToken = default);
|
||||
}
|
||||
Reference in new issue
Block a user