Files
Khaemhat/src/Khaemhat.Fiscal.Italy/Sdi/PecSdiTransport.cs
T
Alby96andClaude Opus 5.5 709bb13532 feat: FatturaPA writer, validator, SDI receipts and transport channels (#74 #75 #76 #77)
The Italian pack can now produce and check the e-invoice and talk to the SDI:
- FatturaPaWriter writes FPR12/FPA12 v1.2 with SDI file naming; FatturaPaValidator
  checks it against an embedded schema and the AdE semantic rules (official codes).
- SdiReceiptReader reads RC, NS, MC, NE, DT, AT, MT and SE notifications.
- The incoming-invoice model becomes the shared EInvoice* model, read and written.
- In-house ImapClient and MimeParser (no external libraries) back the PEC channel;
  SdICoop (SOAP/MTOM with client certificate) and two generic REST intermediaries
  sit behind the same IEInvoiceTransport contract, with fake-server tests.

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

277 lines
13 KiB
C#

using System.Globalization;
using System.Net.Security;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Infrastructure.Mail;
namespace Khaemhat.Fiscal.Italy.Sdi;
/// <summary>
/// The PEC channel to the SDI (SPEC §11.9, issue #76): files go by certified mail to the address of the SDI
/// (<c>sdi01@pec.fatturapa.it</c> the first time, then the <c>sdiNN</c> address the SDI writes from), receipts and
/// supplier invoices are read from the mailbox by IMAP.
/// </summary>
/// <remarks>
/// <para>Only messages whose sender contains <c>fatturapa.it</c> are read: the acceptance and delivery receipts of the
/// PEC provider stay where they are. The files are the <c>.xml</c> and <c>.p7m</c> attachments of the original message
/// (<c>postacert.eml</c>); <c>daticert.xml</c> and the signature of the provider are ignored.</para>
/// <para>With an archive folder, processed messages are moved there and every message of the SDI still in the inbox is
/// read again at the next poll (the services discard what they already have); without it, messages are marked as read
/// and only unread ones are fetched, so a message opened in webmail before the poll is missed: the archive folder is
/// the recommended setting.</para>
/// </remarks>
/// <param name="clock">The clock (date of the messages sent).</param>
/// <param name="certificateValidation">A custom check of the server certificates (tests only).</param>
public sealed partial class PecSdiTransport(TimeProvider? clock = null, RemoteCertificateValidationCallback? certificateValidation = null) : IEInvoiceTransport
{
/// <summary>The code of the channel.</summary>
public const string ChannelCode = "PEC";
/// <summary>The address of the SDI for the first file.</summary>
public const string FirstAddress = "sdi01@pec.fatturapa.it";
/// <summary>The most messages read in one poll.</summary>
public const int MaxMessages = 200;
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(2);
private readonly TimeProvider _clock = clock ?? TimeProvider.System;
/// <inheritdoc />
public string Code => ChannelCode;
/// <inheritdoc />
public bool Polls => true;
/// <summary>Whether an address is one the SDI writes from (<c>sdiNN@pec.fatturapa.it</c>).</summary>
/// <param name="address">The address, possibly with a display name.</param>
/// <returns>The bare address when it is one, otherwise <see langword="null"/>.</returns>
public static string? SdiAddress(string? address)
{
var match = SdiAddressPattern().Match(address ?? string.Empty);
return match.Success ? match.Value.ToLowerInvariant() : null;
}
/// <inheritdoc />
public async Task<EInvoiceSendResult> SendAsync(EInvoiceChannelSettings settings, EInvoiceOutgoing file, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(file);
if (Missing(settings, smtp: true) is { } missing)
{
return new EInvoiceSendResult(false, null, null, missing);
}
var to = SdiAddress(settings.ExchangeAddress) ?? settings.ExchangeAddress ?? FirstAddress;
var mediaType = file.FileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" : "application/xml";
var mail = new OutgoingMail([to], "Invio file " + file.FileName, "File " + file.FileName + (file.Reference is null ? string.Empty : " (" + file.Reference + ")") + ".")
{
Attachments = [new MailAttachment(file.FileName, mediaType, file.Content)],
Reference = file.Reference,
};
try
{
await new SmtpMailSender(Smtp(settings), _clock).SendAsync(mail, cancellationToken).ConfigureAwait(false);
return new EInvoiceSendResult(true, null, null, null);
}
catch (MailException ex)
{
return new EInvoiceSendResult(false, null, null, ex.Message);
}
}
/// <inheritdoc />
public async Task<EInvoiceFetchResult> FetchAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (Missing(settings, smtp: false) is { } missing)
{
throw new MailException(missing);
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
var token = timeout.Token;
await using var imap = await OpenAsync(settings, token).ConfigureAwait(false);
var criteria = (string.IsNullOrWhiteSpace(settings.ArchiveFolder) ? "UNSEEN " : string.Empty) + "FROM " + ImapClient.Quote("fatturapa.it");
var uids = (await imap.SearchAsync(criteria, token).ConfigureAwait(false)).Take(MaxMessages).ToList();
var files = new List<EInvoiceIncoming>();
var empty = new List<long>();
string? exchange = null;
foreach (var uid in uids)
{
var message = await imap.FetchAsync(uid, token).ConfigureAwait(false);
if (message is null)
{
continue;
}
var (found, sender) = Files(message.Content, uid.ToString(CultureInfo.InvariantCulture), _clock.GetUtcNow());
exchange = SdiAddress(sender) ?? exchange;
if (found.Count == 0)
{
empty.Add(uid);
}
files.AddRange(found);
}
// A message of the SDI with no file (rare: a notice) is done at once.
foreach (var uid in empty)
{
await DoneAsync(imap, settings, uid, token).ConfigureAwait(false);
}
await imap.LogoutAsync(token).ConfigureAwait(false);
var known = SdiAddress(settings.ExchangeAddress);
return new EInvoiceFetchResult(files, uids.Count, exchange is not null && exchange != known ? exchange : null);
}
/// <inheritdoc />
public async Task AcknowledgeAsync(EInvoiceChannelSettings settings, IReadOnlyCollection<string> messageKeys, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(messageKeys);
var uids = messageKeys.Select(k => long.TryParse(k, NumberStyles.None, CultureInfo.InvariantCulture, out var uid) ? uid : -1).Where(u => u > 0).Distinct().ToList();
if (uids.Count == 0)
{
return;
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(Timeout);
await using var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false);
foreach (var uid in uids)
{
await DoneAsync(imap, settings, uid, timeout.Token).ConfigureAwait(false);
}
await imap.LogoutAsync(timeout.Token).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<EInvoiceChannelCheck> CheckAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
if (Missing(settings, smtp: true) is { } missing)
{
return new EInvoiceChannelCheck(false, missing);
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
try
{
int count;
await using (var imap = await OpenAsync(settings, timeout.Token).ConfigureAwait(false))
{
count = (await imap.SearchAsync("FROM " + ImapClient.Quote("fatturapa.it"), timeout.Token).ConfigureAwait(false)).Count;
await imap.LogoutAsync(timeout.Token).ConfigureAwait(false);
}
using var smtp = new TcpClient();
await smtp.ConnectAsync(settings.SmtpHost!, settings.SmtpPort, timeout.Token).ConfigureAwait(false);
return new EInvoiceChannelCheck(true, $"IMAP {settings.ImapHost}:{settings.ImapPort}: login OK, {count} SDI messages in the inbox; SMTP {settings.SmtpHost}:{settings.SmtpPort}: reachable.");
}
catch (Exception ex) when (ex is MailException or SocketException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
return new EInvoiceChannelCheck(false, ex.Message);
}
}
/// <summary>
/// The files of the SDI in a message: the <c>.xml</c> and <c>.p7m</c> attachments of the original message of a
/// certified mail (or of the message itself when it is not certified).
/// </summary>
/// <param name="message">The raw message.</param>
/// <param name="key">The key of the message.</param>
/// <param name="now">The time used when the message has no date.</param>
/// <returns>The files and the sender of the original message.</returns>
public static (IReadOnlyList<EInvoiceIncoming> Files, string? Sender) Files(byte[] message, string key, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(message);
var root = MimeParser.Parse(message);
var original = Original(root) ?? root;
var sender = original.Header("from");
var date = DateTimeOffset.TryParse(Strip(original.Header("date")), CultureInfo.InvariantCulture, DateTimeStyles.None, out var parsed) ? parsed : now;
var files = original.Attachments()
.Where(a => a.FileName is { } name && IsSdiFile(name))
.Select(a => new EInvoiceIncoming(Path.GetFileName(a.FileName!), a.Body, date, key, SdiAddress(sender) ?? sender))
.ToList();
return (files, sender);
}
private static bool IsSdiFile(string name) =>
(name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase))
&& !name.Equals("daticert.xml", StringComparison.OrdinalIgnoreCase)
&& !name.Equals("smime.p7m", StringComparison.OrdinalIgnoreCase);
// The message enclosed by the PEC provider (postacert.eml), searched in the parts of the envelope.
private static MimePart? Original(MimePart part)
{
if (part.Enclosed is not null)
{
return part.Enclosed;
}
return part.Parts.Select(Original).FirstOrDefault(p => p is not null);
}
// "Thu, 12 Nov 2026 10:15:00 +0100 (CET)": the comment is not part of the date.
private static string? Strip(string? date)
{
if (date is null)
{
return null;
}
var comment = date.IndexOf('(', StringComparison.Ordinal);
return (comment < 0 ? date : date[..comment]).Trim();
}
private static string? Missing(EInvoiceChannelSettings settings, bool smtp)
{
if (string.IsNullOrWhiteSpace(settings.ImapHost) || string.IsNullOrWhiteSpace(settings.User) || string.IsNullOrEmpty(settings.Password))
{
return "The PEC channel needs the IMAP server, the user and the password.";
}
return smtp && (string.IsNullOrWhiteSpace(settings.SmtpHost) || string.IsNullOrWhiteSpace(settings.Mailbox))
? "The PEC channel needs the SMTP server and the address of the mailbox."
: null;
}
private static SmtpSettings Smtp(EInvoiceChannelSettings settings) => new(
settings.SmtpHost,
settings.SmtpPort,
settings.User,
settings.Password,
settings.Mailbox,
!settings.Tls ? SmtpTransportSecurity.None : settings.SmtpPort == 587 ? SmtpTransportSecurity.StartTls : SmtpTransportSecurity.Ssl);
private async Task<ImapClient> OpenAsync(EInvoiceChannelSettings settings, CancellationToken cancellationToken)
{
var imap = await ImapClient.ConnectAsync(
new ImapSettings(settings.ImapHost!, settings.ImapPort, settings.Tls, settings.User!, settings.Password!), cancellationToken, certificateValidation).ConfigureAwait(false);
try
{
await imap.LoginAsync(settings.User!, settings.Password!, cancellationToken).ConfigureAwait(false);
await imap.SelectAsync("INBOX", cancellationToken).ConfigureAwait(false);
return imap;
}
catch
{
await imap.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private static Task DoneAsync(ImapClient imap, EInvoiceChannelSettings settings, long uid, CancellationToken cancellationToken) =>
string.IsNullOrWhiteSpace(settings.ArchiveFolder)
? imap.AddFlagsAsync(uid, @"\Seen", cancellationToken)
: imap.MoveAsync(uid, settings.ArchiveFolder.Trim(), cancellationToken);
[GeneratedRegex(@"sdi[0-9]{2}@pec\.fatturapa\.it", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex SdiAddressPattern();
}