Files
Khaemhat/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs
T
Alby96andClaude Opus 5.5 fb12411404 feat: e-invoice services, SDI channels, inbox, polling and conservation (#74 #75 #76 #77 #79)
Adds the company tables of the electronic invoice and the services that drive them:
the builder turns an issued document into the FatturaPA model, the service generates,
checks and sends the file through the channel chosen by the routing rules (with a
fallback) and applies the SDI notifications to the e-invoice and its document. The
channel settings keep their secrets protected and out of the audit trail; a job reads
the PEC mailbox and the intermediaries every 15 minutes, storing supplier invoices in
the inbox and acknowledging a message only once all its files are kept. The inbox
registers received invoices through the purchase import, and the conservation export
packs a period with a SHA-256 index. A rejected invoice can now be corrected and
generated again; the courtesy PDF embeds the XML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:20:59 +01:00

352 lines
18 KiB
C#

using Khaemhat.Application.Purchases;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The filter of the invoices received.</summary>
/// <param name="Status">Only this state.</param>
/// <param name="Search">Supplier, VAT number, number or file name.</param>
public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null);
/// <summary>A received file stored, or why not.</summary>
/// <param name="FileName">The file.</param>
/// <param name="Id">The row of the inbox.</param>
/// <param name="Status">Its state.</param>
/// <param name="Error">Why it was not stored (error code).</param>
public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error);
/// <summary>A received invoice registered as a supplier document, or why not.</summary>
/// <param name="Id">The row of the inbox.</param>
/// <param name="FileName">The file.</param>
/// <param name="PurchaseDocumentId">The draft supplier document.</param>
/// <param name="Error">Why it was not registered (error code).</param>
/// <param name="Warnings">What to check on the draft (codes).</param>
public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList<string> Warnings);
/// <summary>
/// The invoices received from the SDI (SPEC §11.9, issue #79): every file that arrives through a channel, or that the
/// user uploads, is kept as it was received with its metadata file (MT); the user registers it as a draft supplier
/// invoice (with the import of mockup 034), or discards it. A file is kept once, by its hash.
/// </summary>
/// <remarks>Permissions: <c>einvoice.inbox.read</c> to see, <c>einvoice.inbox.import</c> to upload, register and discard
/// (registering also needs <c>purchases.invoice.write</c>).</remarks>
public sealed class SdiInboxService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly PurchaseInvoiceImportService _import;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="import">The import of supplier invoices.</param>
/// <param name="clock">The clock.</param>
public SdiInboxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, PurchaseInvoiceImportService import, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(import);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_import = import;
_clock = clock;
}
/// <summary>The invoices received, newest first (files not loaded).</summary>
/// <param name="actor">Who looks: needs <c>einvoice.inbox.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<EInvoiceInboxFile>> ListAsync(Actor actor, string companyCode, InboxFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<EInvoiceInboxFile>();
if (filter.Status is { } status)
{
query = query.Where(f => f.Status == status);
}
var rows = (await uow.Repository<EInvoiceInboxFile, long>().ListAsync(query.OrderByDescending(f => f.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items
.Select(Light);
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
rows = rows.Where(f => Has(f.SupplierName, text) || Has(f.SupplierVat, text) || Has(f.Number, text) || Has(f.FileName, text) || Has(f.ExchangeId, text));
}
return [.. rows];
}
/// <summary>The received file, as it arrived.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.inbox.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="metadata">The metadata file (MT) instead of the invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content.</returns>
public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, bool metadata = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return metadata
? (row.MetadataFileName ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound), row.Metadata ?? [])
: (row.FileName, row.Content);
}
/// <summary>Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere).</summary>
/// <param name="actor">Who uploads: needs <c>einvoice.inbox.import</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<InboxStored>> UploadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var receipts = pack.GetFeature<IEInvoiceReceiptReader>();
var result = new List<InboxStored>();
foreach (var (name, content) in files)
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
InboxStored stored;
if (receipts is not null && receipts.IsReceipt(name, content) && TryRead(receipts, name, content) is { Kind: EInvoiceReceiptKind.Metadata } meta)
{
var row = await AttachMetadataCoreAsync(uow, meta, cancellationToken).ConfigureAwait(false);
stored = new InboxStored(name, row?.Id, row?.Status, row is null ? EInvoiceErrors.ReceiptUnmatched : null);
}
else
{
stored = await StoreCoreAsync(uow, reader, name, content, _clock.GetUtcNow().UtcDateTime, EInvoiceStore.ManualChannel, null, false, cancellationToken)
.ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(stored);
}
return result;
}
/// <summary>
/// Registers received invoices as draft supplier documents, through the import of supplier invoices: the supplier is
/// found or added, the lines take their items and tax codes, the file is attached.
/// </summary>
/// <param name="actor">Who registers: needs <c>einvoice.inbox.import</c> and <c>purchases.invoice.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<InboxRegistered>> RegisterAsync(Actor actor, string companyCode, IReadOnlyList<long> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var result = new List<InboxRegistered>();
foreach (var id in ids.Distinct())
{
EInvoiceInboxFile row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
if (row.Status != InboxFileStatus.New)
{
result.Add(new InboxRegistered(id, row.FileName, row.PurchaseDocumentId, EInvoiceErrors.InboxState, []));
continue;
}
var reading = await _import.ReadAsync(actor, company, [(row.FileName, row.Content)], cancellationToken).ConfigureAwait(false);
if (reading.Rejected.Count > 0 || reading.Invoices.Count == 0)
{
result.Add(new InboxRegistered(id, row.FileName, null, (reading.Rejected.Count > 0 ? reading.Rejected[0].Error : PurchaseInvoiceImportService.EmptyArchive), []));
continue;
}
var blocked = reading.Invoices.FirstOrDefault(c => !c.CanImport);
if (blocked is not null)
{
result.Add(new InboxRegistered(id, row.FileName, null, (blocked.Problems.Count > 0 ? blocked.Problems[0] : PurchaseInvoiceImportService.UnsupportedType), blocked.Problems));
continue;
}
var imported = await _import.ImportAsync(actor, company, reading.Invoices, cancellationToken).ConfigureAwait(false);
var failed = imported.FirstOrDefault(i => i.Error is not null);
var first = imported.FirstOrDefault(i => i.Record is not null);
var documentId = first?.Record?.Header.Id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (documentId is not null)
{
current.Status = InboxFileStatus.Registered;
current.PurchaseDocumentId = documentId;
current.PartyId = first!.Record!.Header.PartyId ?? current.PartyId;
}
current.Error = failed?.Error;
await uow.Repository<EInvoiceInboxFile, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
result.Add(new InboxRegistered(id, row.FileName, documentId, failed?.Error, [.. imported.SelectMany(i => i.Warnings).Distinct(StringComparer.Ordinal)]));
}
return result;
}
/// <summary>Discards a received invoice (a copy, a file not for the company), or takes it back.</summary>
/// <param name="actor">Who does it: needs <c>einvoice.inbox.import</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="discard">Discard, or take back.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DiscardAsync(Actor actor, string companyCode, long id, bool discard, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<EInvoiceInboxFile, long>();
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var allowed = discard ? row.Status is InboxFileStatus.New or InboxFileStatus.Unreadable : row.Status == InboxFileStatus.Discarded;
if (!allowed)
{
throw new ValidationFailedException([":" + EInvoiceErrors.InboxState]);
}
row.Status = discard ? InboxFileStatus.Discarded : row.SupplierVat is null && row.Number is null ? InboxFileStatus.Unreadable : InboxFileStatus.New;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stores a received file in the transaction of the caller: read by the pack for the list (supplier, number, date,
/// total); a file the pack cannot read is kept as unreadable, a file already kept is not stored again.
/// </summary>
internal static async Task<InboxStored> StoreCoreAsync(
IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo,
CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoiceInboxFile, long>();
var hash = EInvoiceStore.Hash(content);
if (await repository.FindAsync(Query.For<EInvoiceInboxFile>().Where(f => f.Hash == hash), cancellationToken).ConfigureAwait(false) is { } known)
{
return new InboxStored(fileName, known.Id, known.Status, EInvoiceErrors.InboxDuplicate);
}
var row = new EInvoiceInboxFile
{
FileName = EInvoiceStore.Trim(Path.GetFileName(fileName), 200) ?? "fattura.xml",
Hash = hash,
Content = content,
ReceivedAt = receivedAt,
ChannelCode = channel,
ExchangeId = EInvoiceStore.Trim(exchangeId, 40),
Status = InboxFileStatus.Unreadable,
IsDemo = demo,
};
try
{
if (reader is not null && reader.CanRead(fileName, content))
{
var file = reader.Read(fileName, content);
var invoice = file.Invoices[0];
row.SupplierVat = EInvoiceStore.Trim((file.Supplier.CountryCode ?? string.Empty) + (file.Supplier.VatNumber ?? file.Supplier.TaxCode), 30);
row.SupplierName = EInvoiceStore.Trim(file.Supplier.DisplayName, 200);
row.DocumentType = invoice.DocumentType;
row.Number = EInvoiceStore.Trim(invoice.Number, 40);
row.DocumentDate = invoice.Date;
row.TotalAmount = file.Invoices.Count == 1 ? invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) : null;
row.PartyId = await PurchaseInvoiceImportService.FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
row.Status = InboxFileStatus.New;
}
else
{
row.Error = IncomingInvoiceErrors.NotReadable;
}
}
catch (IncomingInvoiceException ex)
{
row.Error = ex.Code;
}
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
return new InboxStored(fileName, row.Id, row.Status, null);
}
/// <summary>Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file.</summary>
internal static async Task<EInvoiceInboxFile?> AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoiceInboxFile, long>();
var stem = metadata.InvoiceFileName is { } name ? EInvoiceStore.Stem(name) : EInvoiceStore.InvoiceStem(metadata.FileName);
if (stem is null)
{
return null;
}
EInvoiceInboxFile? row = null;
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
row = await repository.FindAsync(Query.For<EInvoiceInboxFile>().Where(f => f.FileName == candidate).OrderByDescending(f => f.Id), cancellationToken).ConfigureAwait(false);
if (row is not null)
{
break;
}
}
if (row is null)
{
return null;
}
row.MetadataFileName = EInvoiceStore.Trim(metadata.FileName, 200);
row.Metadata = metadata.Content;
row.ExchangeId ??= EInvoiceStore.Trim(metadata.ExchangeId, 40);
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
return row;
}
private static EInvoiceReceipt? TryRead(IEInvoiceReceiptReader reader, string name, byte[] content)
{
try
{
return reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
return null;
}
}
private static EInvoiceInboxFile Light(EInvoiceInboxFile row)
{
var copy = EInvoiceStore.Clone(row);
copy.Content = [];
copy.Metadata = null;
return copy;
}
private static bool Has(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
}