Files
Khaemhat/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.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

425 lines
23 KiB
C#

using System.Globalization;
using System.Net.Mail;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>A channel as the configuration page shows it: secrets never leave the service, only whether they are set.</summary>
/// <param name="Code">The code of the channel.</param>
/// <param name="Name">Its name.</param>
/// <param name="Polls">Whether Khaemhat reads it on a schedule (PEC, intermediaries) or receives a push (SdICoop).</param>
/// <param name="Setting">The settings, secrets removed (a new row when never saved).</param>
/// <param name="HasPassword">Whether a password is stored.</param>
/// <param name="HasCertificate">Whether a client certificate is stored.</param>
/// <param name="HasApiKey">Whether an API key is stored.</param>
public sealed record EInvoiceChannelView(string Code, string Name, bool Polls, EInvoiceChannelSetting Setting, bool HasPassword, bool HasCertificate, bool HasApiKey);
/// <summary>
/// What the user saves for a channel. Secrets: <see langword="null"/> keeps the stored one, an empty value removes it.
/// </summary>
public sealed record EInvoiceChannelInput
{
/// <summary>The code of the channel.</summary>
public required string Code { get; init; }
/// <summary>Whether the channel is used.</summary>
public bool Enabled { get; init; }
/// <summary>The certified mailbox.</summary>
public string? Mailbox { get; init; }
/// <summary>The SMTP server.</summary>
public string? SmtpHost { get; init; }
/// <summary>The SMTP port.</summary>
public int SmtpPort { get; init; } = 465;
/// <summary>The IMAP server.</summary>
public string? ImapHost { get; init; }
/// <summary>The IMAP port.</summary>
public int ImapPort { get; init; } = 993;
/// <summary>Whether TLS is used.</summary>
public bool Tls { get; init; } = true;
/// <summary>The user.</summary>
public string? UserName { get; init; }
/// <summary>The password: <see langword="null"/> keeps it, empty removes it.</summary>
public string? Password { get; init; }
/// <summary>The address of the SDI to write to.</summary>
public string? ExchangeAddress { get; init; }
/// <summary>The folder the processed messages go to.</summary>
public string? ArchiveFolder { get; init; }
/// <summary>The address of the web service or of the API.</summary>
public string? Endpoint { get; init; }
/// <summary>The client certificate (PKCS#12): <see langword="null"/> keeps it, empty removes it.</summary>
public byte[]? Certificate { get; init; }
/// <summary>The password of the certificate: <see langword="null"/> keeps it, empty removes it.</summary>
public string? CertificatePassword { get; init; }
/// <summary>The API key: <see langword="null"/> keeps it, empty removes it.</summary>
public string? ApiKey { get; init; }
/// <summary>Whether the test environment is used.</summary>
public bool TestEnvironment { get; init; }
}
/// <summary>
/// The channels to the SDI and the routing of the files (mockup 059, issues #76-#77): the PEC mailbox, the SdICoop web
/// service, the intermediaries; each can be tried, paused and resumed. Secrets are kept protected (SPEC §8.5) and never
/// shown again. The routing rules choose the channel of each file, with a fallback.
/// </summary>
/// <remarks>Permission: <c>einvoice.channel.manage</c>.</remarks>
public sealed class EInvoiceChannelService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly ISecretProtector _secrets;
private readonly AuditTrail _audit;
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="secrets">Protects the secrets.</param>
/// <param name="audit">The history of the changes.</param>
/// <param name="clock">The clock.</param>
public EInvoiceChannelService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, ISecretProtector secrets, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_secrets = secrets;
_audit = audit;
_clock = clock;
}
/// <summary>The channels of the pack with their settings.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The channels, in the order of the pack.</returns>
public async Task<IReadOnlyList<EInvoiceChannelView>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>(), cancellationToken).ConfigureAwait(false)).Items
.ToDictionary(r => r.Code, StringComparer.OrdinalIgnoreCase);
return [.. channels.All.Select(c => View(c, rows.GetValueOrDefault(c.Code) ?? new EInvoiceChannelSetting { Code = c.Code }))];
}
/// <summary>Saves the settings of a channel.</summary>
/// <param name="actor">Who saves: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The settings.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The channel.</returns>
public async Task<EInvoiceChannelView> SaveAsync(Actor actor, string companyCode, EInvoiceChannelInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(input.Code)
?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
Validate(input);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<EInvoiceChannelSetting, long>();
var code = channel.Code;
var row = await repository.FindAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false);
var before = row is null ? null : Copy(row);
row ??= new EInvoiceChannelSetting { Code = code };
row.Enabled = input.Enabled;
row.Mailbox = EInvoiceStore.Trim(input.Mailbox, 200);
row.SmtpHost = EInvoiceStore.Trim(input.SmtpHost, 200);
row.SmtpPort = input.SmtpPort;
row.ImapHost = EInvoiceStore.Trim(input.ImapHost, 200);
row.ImapPort = input.ImapPort;
row.Tls = input.Tls;
row.UserName = EInvoiceStore.Trim(input.UserName, 200);
row.ExchangeAddress = EInvoiceStore.Trim(input.ExchangeAddress, 200);
row.ArchiveFolder = EInvoiceStore.Trim(input.ArchiveFolder, 200);
row.Endpoint = EInvoiceStore.Trim(input.Endpoint, 500);
row.TestEnvironment = input.TestEnvironment;
row.ProtectedPassword = Secret(input.Password, row.ProtectedPassword);
row.ProtectedCertificate = input.Certificate is null
? row.ProtectedCertificate
: input.Certificate.Length == 0 ? null : _secrets.Protect(Convert.ToBase64String(input.Certificate), EInvoiceStore.SecretPurpose);
row.ProtectedCertificatePassword = Secret(input.CertificatePassword, row.ProtectedCertificatePassword);
row.ProtectedApiKey = Secret(input.ApiKey, row.ProtectedApiKey);
if (before is null)
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<EInvoiceChannelSetting>(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return View(channel, row);
}
/// <summary>Pauses or resumes a channel: a paused channel neither sends nor is read.</summary>
/// <param name="actor">Who does it: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="code">The channel.</param>
/// <param name="paused">Whether to pause.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task PauseAsync(Actor actor, string companyCode, string code, bool paused, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, 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<EInvoiceChannelSetting, long>();
var row = await repository.FindAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
var before = Copy(row);
row.Paused = paused;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Tries a channel with its saved settings (login to the mailbox, the service or the API) and keeps the outcome.</summary>
/// <param name="actor">Who tries: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="code">The channel.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The outcome.</returns>
public async Task<EInvoiceChannelCheck> CheckAsync(Actor actor, string companyCode, string code, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(code)
?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
EInvoiceChannelSetting row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
row = await uow.Repository<EInvoiceChannelSetting, long>().FindAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == channel.Code), cancellationToken)
.ConfigureAwait(false) ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]);
}
EInvoiceChannelCheck check;
try
{
check = await channel.Transport.CheckAsync(EInvoiceStore.Settings(row, _secrets), cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
check = new EInvoiceChannelCheck(false, ex.Message);
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoiceChannelSetting, long>().GetAsync(row.Id, cancellationToken).ConfigureAwait(false)!;
if (current is not null)
{
current.LastCheckAt = _clock.GetUtcNow().UtcDateTime;
current.LastCheckOk = check.Success;
current.LastCheckMessage = EInvoiceStore.Trim(check.Message, 1000);
await uow.Repository<EInvoiceChannelSetting, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return check;
}
/// <summary>The routing rules, in order.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rules.</returns>
public async Task<IReadOnlyList<SdiRoutingRule>> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository<SdiRoutingRule, long>().ListAsync(Query.For<SdiRoutingRule>().OrderBy(r => r.Position), cancellationToken).ConfigureAwait(false)).Items;
}
/// <summary>Adds or changes a routing rule.</summary>
/// <param name="actor">Who saves: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="rule">The rule (identifier 0 to add).</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rule.</returns>
public async Task<SdiRoutingRule> SaveRuleAsync(Actor actor, string companyCode, SdiRoutingRule rule, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(rule);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false);
var errors = new List<string>();
if (channels.Find(rule.ChannelCode) is null)
{
errors.Add(nameof(SdiRoutingRule.ChannelCode) + ":" + EInvoiceErrors.ChannelUnknown);
}
if (!string.IsNullOrWhiteSpace(rule.FallbackChannelCode) && (channels.Find(rule.FallbackChannelCode) is null
|| string.Equals(rule.FallbackChannelCode, rule.ChannelCode, StringComparison.OrdinalIgnoreCase)))
{
errors.Add(nameof(SdiRoutingRule.FallbackChannelCode) + ":" + EInvoiceErrors.ChannelUnknown);
}
var value = rule.Value?.Trim();
var valueOk = rule.Condition switch
{
SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType => !string.IsNullOrEmpty(value),
SdiRoutingCondition.DailyVolume => int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var limit) && limit > 0,
_ => true,
};
if (!valueOk)
{
errors.Add(nameof(SdiRoutingRule.Value) + ":" + EInvoiceErrors.RuleValueInvalid);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<SdiRoutingRule, long>();
var row = rule.Id == 0 ? new SdiRoutingRule() : await repository.GetAsync(rule.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var before = rule.Id == 0 ? null : CopyRule(row);
if (rule.Id == 0 && rule.Position <= 0)
{
var last = await repository.FindAsync(Query.For<SdiRoutingRule>().OrderByDescending(r => r.Position), cancellationToken).ConfigureAwait(false);
row.Position = (last?.Position ?? 0) + 10;
}
else
{
row.Position = rule.Position;
}
row.Condition = rule.Condition;
row.Value = rule.Condition is SdiRoutingCondition.Default or SdiRoutingCondition.PublicAdministration ? null : value!.ToUpperInvariant();
row.ChannelCode = rule.ChannelCode.Trim().ToUpperInvariant();
row.FallbackChannelCode = string.IsNullOrWhiteSpace(rule.FallbackChannelCode) ? null : rule.FallbackChannelCode.Trim().ToUpperInvariant();
row.Disabled = rule.Disabled;
if (before is null)
{
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<SdiRoutingRule>(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return row;
}
/// <summary>Removes a routing rule.</summary>
/// <param name="actor">Who removes: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The rule.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DeleteRuleAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, 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<SdiRoutingRule, long>();
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<SdiRoutingRule>(uow, AuditAction.Delete, row.Id, row, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<IEInvoiceChannels> ChannelsAsync(string company, CancellationToken cancellationToken) =>
(await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<IEInvoiceChannels>()
?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]);
private string? Secret(string? input, string? stored) =>
input is null ? stored : input.Length == 0 ? null : _secrets.Protect(input, EInvoiceStore.SecretPurpose);
private static void Validate(EInvoiceChannelInput input)
{
var errors = new List<string>();
if (input.SmtpPort is < 1 or > 65535)
{
errors.Add(nameof(input.SmtpPort) + ":" + EInvoiceErrors.PortInvalid);
}
if (input.ImapPort is < 1 or > 65535)
{
errors.Add(nameof(input.ImapPort) + ":" + EInvoiceErrors.PortInvalid);
}
if (!string.IsNullOrWhiteSpace(input.Mailbox) && !MailAddress.TryCreate(input.Mailbox.Trim(), out _))
{
errors.Add(nameof(input.Mailbox) + ":" + EInvoiceErrors.MailboxInvalid);
}
if (!string.IsNullOrWhiteSpace(input.ExchangeAddress) && !MailAddress.TryCreate(input.ExchangeAddress.Trim(), out _))
{
errors.Add(nameof(input.ExchangeAddress) + ":" + EInvoiceErrors.MailboxInvalid);
}
if (!string.IsNullOrWhiteSpace(input.Endpoint) && !IsServiceAddress(input.Endpoint.Trim()))
{
errors.Add(nameof(input.Endpoint) + ":" + EInvoiceErrors.EndpointInvalid);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
}
// https, or http only to this machine (a test service).
private static bool IsServiceAddress(string value) =>
Uri.TryCreate(value, UriKind.Absolute, out var uri)
&& (uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback));
private static EInvoiceChannelView View(EInvoiceChannel channel, EInvoiceChannelSetting row)
{
var shown = Copy(row);
shown.ProtectedPassword = null;
shown.ProtectedCertificate = null;
shown.ProtectedCertificatePassword = null;
shown.ProtectedApiKey = null;
return new EInvoiceChannelView(channel.Code, channel.Name, channel.Transport.Polls, shown,
!string.IsNullOrEmpty(row.ProtectedPassword), !string.IsNullOrEmpty(row.ProtectedCertificate), !string.IsNullOrEmpty(row.ProtectedApiKey));
}
private static EInvoiceChannelSetting Copy(EInvoiceChannelSetting row) => EInvoiceStore.Clone(row);
private static SdiRoutingRule CopyRule(SdiRoutingRule row) => EInvoiceStore.Clone(row);
}