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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 12:20:59 +01:00
1 parent 709bb13532
commit fb12411404
24 files changed
+4016 -10

No files matched your search

@@ -0,0 +1,283 @@
using System.Security.Cryptography;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Security;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The permissions of the electronic invoice (module EINV, <see cref="Modules.BuiltInModules"/>).</summary>
public static class EInvoicePermissions
{
/// <summary>See the e-invoices, their notifications and the conservation packages.</summary>
public const string Read = "einvoice.document.read";
/// <summary>Generate, send and send again; import notifications.</summary>
public const string Send = "einvoice.document.send";
/// <summary>See the invoices received.</summary>
public const string InboxRead = "einvoice.inbox.read";
/// <summary>Register, discard and upload the invoices received.</summary>
public const string InboxImport = "einvoice.inbox.import";
/// <summary>Configure the channels and the routing; read the channels now.</summary>
public const string ChannelManage = "einvoice.channel.manage";
}
/// <summary>The error codes of the electronic invoice (texts in <c>EInvoicing.json</c>).</summary>
public static class EInvoiceErrors
{
/// <summary>No e-invoice, notification or file with that identifier.</summary>
public const string NotFound = "einvoice.not-found";
/// <summary>The kind of document does not go to the exchange system.</summary>
public const string NotElectronic = "einvoice.not-electronic";
/// <summary>The document is not issued yet.</summary>
public const string NotIssued = "einvoice.not-issued";
/// <summary>The file was already sent: it can only receive notifications.</summary>
public const string AlreadySent = "einvoice.already-sent";
/// <summary>The profile of the company is missing.</summary>
public const string CompanyProfileMissing = "einvoice.profile-missing";
/// <summary>The fiscal pack of the company does not write e-invoices.</summary>
public const string NotSupported = "einvoice.not-supported";
/// <summary>No channel is enabled.</summary>
public const string NoChannel = "einvoice.no-channel";
/// <summary>The file is not a notification of the exchange system.</summary>
public const string NotAReceipt = "einvoice.not-a-receipt";
/// <summary>The notification is about a file Khaemhat did not send.</summary>
public const string ReceiptUnmatched = "einvoice.receipt-unmatched";
/// <summary>The notification was already imported.</summary>
public const string ReceiptDuplicate = "einvoice.receipt-duplicate";
/// <summary>The channel is not one of the pack.</summary>
public const string ChannelUnknown = "einvoice.channel-unknown";
/// <summary>A port out of range.</summary>
public const string PortInvalid = "einvoice.port-invalid";
/// <summary>The mailbox is not an e-mail address.</summary>
public const string MailboxInvalid = "einvoice.mailbox-invalid";
/// <summary>The address of the service is not an https address.</summary>
public const string EndpointInvalid = "einvoice.endpoint-invalid";
/// <summary>The value of a routing rule is missing or wrong.</summary>
public const string RuleValueInvalid = "einvoice.rule-value";
/// <summary>The received file is already in the inbox.</summary>
public const string InboxDuplicate = "einvoice.inbox-duplicate";
/// <summary>The received file is not in a state that allows the action.</summary>
public const string InboxState = "einvoice.inbox-state";
/// <summary>The period of the conservation package is wrong.</summary>
public const string PeriodInvalid = "einvoice.period-invalid";
}
/// <summary>An e-invoice in the lists, with its counterpart.</summary>
/// <param name="Invoice">The e-invoice (the file is not loaded for lists).</param>
/// <param name="PartyCode">The code of the customer or supplier.</param>
/// <param name="PartyName">The name.</param>
public sealed record EInvoiceRow(EInvoice Invoice, string? PartyCode, string? PartyName);
/// <summary>An issued document without its file yet, or whose file was rejected.</summary>
/// <param name="Family">The family.</param>
/// <param name="DocumentId">The document.</param>
/// <param name="Kind">The kind.</param>
/// <param name="Number">The number.</param>
/// <param name="Date">The date.</param>
/// <param name="PartyName">The customer, or the supplier of a self-invoice.</param>
/// <param name="Total">The total.</param>
/// <param name="Status">The state of the document.</param>
public sealed record PendingEInvoice(DocumentFamily Family, long DocumentId, DocumentKind Kind, string? Number, DateOnly Date, string? PartyName, decimal Total, DocumentStatus Status);
/// <summary>What the dashboard shows.</summary>
public enum EInvoiceView
{
/// <summary>Invoices, notes and fees sent to customers.</summary>
Issued = 0,
/// <summary>Self-invoices and integrations.</summary>
SelfInvoices = 1,
/// <summary>Everything that needs the user: to generate, to send, rejected, refused.</summary>
ToDo = 2,
}
/// <summary>The filter of the dashboard.</summary>
/// <param name="View">The view.</param>
/// <param name="Status">Only this state.</param>
/// <param name="From">From this date of the document.</param>
/// <param name="To">Up to this date.</param>
/// <param name="Search">Number, file name, identifier of the SDI or counterpart.</param>
public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EInvoiceStatus? Status = null, DateOnly? From = null, DateOnly? To = null, string? Search = null);
/// <summary>The counters of the dashboard (mockup 058).</summary>
/// <param name="ToGenerate">Issued documents without a file.</param>
/// <param name="ToSend">Files generated and not sent.</param>
/// <param name="Waiting">Sent, waiting for the receipt.</param>
/// <param name="Delivered">Delivered or issued (RC, MC, NE EC01, DT, AT).</param>
/// <param name="Rejected">Rejected by the SDI or refused by a public administration.</param>
/// <param name="Received">Invoices received to register.</param>
public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int Received);
/// <summary>The dashboard.</summary>
/// <param name="Rows">The e-invoices of the view.</param>
/// <param name="Pending">The documents to generate (view <see cref="EInvoiceView.ToDo"/> and the counters).</param>
/// <param name="Counters">The counters.</param>
public sealed record EInvoiceDashboard(IReadOnlyList<EInvoiceRow> Rows, IReadOnlyList<PendingEInvoice> Pending, EInvoiceCounters Counters);
/// <summary>The outcome of a generation: the file, or why not.</summary>
/// <param name="Invoice">The e-invoice written.</param>
/// <param name="Problems">Errors (nothing written) and warnings.</param>
public sealed record EInvoiceGeneration(EInvoice? Invoice, IReadOnlyList<EInvoiceProblem> Problems)
{
/// <summary>Whether the file was written.</summary>
public bool Success => Invoice is not null;
}
/// <summary>The outcome of sending one file.</summary>
/// <param name="EInvoiceId">The e-invoice.</param>
/// <param name="FileName">The file.</param>
/// <param name="DocumentNumber">The document.</param>
/// <param name="Sent">Whether a channel took it.</param>
/// <param name="ChannelCode">The channel that took it, or the last one tried.</param>
/// <param name="Error">Why not (a message of the channel, or an error code).</param>
public sealed record EInvoiceSendOutcome(long EInvoiceId, string FileName, string? DocumentNumber, bool Sent, string? ChannelCode, string? Error);
/// <summary>The outcome of a notification imported or received.</summary>
/// <param name="FileName">The notification.</param>
/// <param name="Code">Its code (RC, NS …).</param>
/// <param name="InvoiceFileName">The file it is about.</param>
/// <param name="EInvoiceId">The e-invoice updated.</param>
/// <param name="Status">The state it reached.</param>
/// <param name="Error">Why it was not applied (error code).</param>
public sealed record ReceiptOutcome(string FileName, string? Code, string? InvoiceFileName, long? EInvoiceId, EInvoiceStatus? Status, string? Error);
/// <summary>What the services of the electronic invoice share.</summary>
internal static class EInvoiceStore
{
/// <summary>The channel of what the user uploads or sends from the portal of the AdE.</summary>
public const string ManualChannel = "MANUAL";
/// <summary>The purpose of the protection of the secrets of the channels.</summary>
public const string SecretPurpose = "einvoice.channel";
/// <summary>The SHA-256 of a file in lower-case hexadecimal.</summary>
public static string Hash(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content));
/// <summary>A text cut to a length.</summary>
public static string? Trim(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Trim().Length <= length ? text.Trim() : text.Trim()[..length];
/// <summary>The settings of a channel for its transport, secrets unprotected.</summary>
public static EInvoiceChannelSettings Settings(EInvoiceChannelSetting row, ISecretProtector secrets)
{
string? Open(string? value) => string.IsNullOrEmpty(value) ? null : secrets.Unprotect(value, SecretPurpose);
var certificate = Open(row.ProtectedCertificate);
return new EInvoiceChannelSettings
{
Code = row.Code,
Mailbox = row.Mailbox,
SmtpHost = row.SmtpHost,
SmtpPort = row.SmtpPort,
ImapHost = row.ImapHost,
ImapPort = row.ImapPort,
Tls = row.Tls,
User = row.UserName,
Password = Open(row.ProtectedPassword),
ExchangeAddress = row.ExchangeAddress,
ArchiveFolder = row.ArchiveFolder,
Endpoint = row.Endpoint,
Certificate = certificate is null ? null : Convert.FromBase64String(certificate),
CertificatePassword = Open(row.ProtectedCertificatePassword),
ApiKey = Open(row.ProtectedApiKey),
TestEnvironment = row.TestEnvironment,
};
}
/// <summary>The name of the invoice file a notification is about, from the name of the notification.</summary>
/// <param name="receiptFileName">The notification (<c>IT01234567890_00001_RC_001.xml</c>).</param>
/// <returns>The stem of the invoice file (<c>IT01234567890_00001</c>), or <see langword="null"/>.</returns>
public static string? InvoiceStem(string receiptFileName)
{
var name = Path.GetFileName(receiptFileName);
var parts = name.Split('_');
return parts.Length >= 4 ? string.Join('_', parts[..^2]) : null;
}
/// <summary>The stem of a file name: without <c>.xml</c> and <c>.p7m</c>.</summary>
public static string Stem(string fileName)
{
var name = Path.GetFileName(fileName);
foreach (var extension in new[] { ".p7m", ".xml" })
{
if (name.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
name = name[..^extension.Length];
}
}
return name;
}
/// <summary>A shallow copy of a row (public properties that can be written), for the history of a change.</summary>
public static T Clone<T>(T row)
where T : class, new()
{
var copy = new T();
foreach (var property in typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (property is { CanRead: true, CanWrite: true } && property.GetIndexParameters().Length == 0)
{
property.SetValue(copy, property.GetValue(row));
}
}
return copy;
}
/// <summary>A copy without the file, for lists and history.</summary>
public static EInvoice Light(EInvoice e) => new()
{
Id = e.Id,
Family = e.Family,
DocumentId = e.DocumentId,
Kind = e.Kind,
DocumentNumber = e.DocumentNumber,
DocumentDate = e.DocumentDate,
PartyId = e.PartyId,
DocumentType = e.DocumentType,
FileName = e.FileName,
Progressive = e.Progressive,
Format = e.Format,
RecipientCode = e.RecipientCode,
RecipientPec = e.RecipientPec,
TotalAmount = e.TotalAmount,
Status = e.Status,
ChannelCode = e.ChannelCode,
ExchangeId = e.ExchangeId,
MessageId = e.MessageId,
GeneratedAt = e.GeneratedAt,
SentAt = e.SentAt,
LastNotificationAt = e.LastNotificationAt,
LastMessage = e.LastMessage,
SendAttempts = e.SendAttempts,
Superseded = e.Superseded,
IsDemo = e.IsDemo,
CreatedAt = e.CreatedAt,
CreatedBy = e.CreatedBy,
UpdatedAt = e.UpdatedAt,
UpdatedBy = e.UpdatedBy,
RowVersion = e.RowVersion,
};
}