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;
/// A channel as the configuration page shows it: secrets never leave the service, only whether they are set.
/// The code of the channel.
/// Its name.
/// Whether Khaemhat reads it on a schedule (PEC, intermediaries) or receives a push (SdICoop).
/// The settings, secrets removed (a new row when never saved).
/// Whether a password is stored.
/// Whether a client certificate is stored.
/// Whether an API key is stored.
public sealed record EInvoiceChannelView(string Code, string Name, bool Polls, EInvoiceChannelSetting Setting, bool HasPassword, bool HasCertificate, bool HasApiKey);
///
/// What the user saves for a channel. Secrets: keeps the stored one, an empty value removes it.
///
public sealed record EInvoiceChannelInput
{
/// The code of the channel.
public required string Code { get; init; }
/// Whether the channel is used.
public bool Enabled { get; init; }
/// The certified mailbox.
public string? Mailbox { get; init; }
/// The SMTP server.
public string? SmtpHost { get; init; }
/// The SMTP port.
public int SmtpPort { get; init; } = 465;
/// The IMAP server.
public string? ImapHost { get; init; }
/// The IMAP port.
public int ImapPort { get; init; } = 993;
/// Whether TLS is used.
public bool Tls { get; init; } = true;
/// The user.
public string? UserName { get; init; }
/// The password: keeps it, empty removes it.
public string? Password { get; init; }
/// The address of the SDI to write to.
public string? ExchangeAddress { get; init; }
/// The folder the processed messages go to.
public string? ArchiveFolder { get; init; }
/// The address of the web service or of the API.
public string? Endpoint { get; init; }
/// The client certificate (PKCS#12): keeps it, empty removes it.
public byte[]? Certificate { get; init; }
/// The password of the certificate: keeps it, empty removes it.
public string? CertificatePassword { get; init; }
/// The API key: keeps it, empty removes it.
public string? ApiKey { get; init; }
/// Whether the test environment is used.
public bool TestEnvironment { get; init; }
}
///
/// 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.
///
/// Permission: einvoice.channel.manage.
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;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The fiscal pack of each company.
/// Protects the secrets.
/// The history of the changes.
/// The clock.
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;
}
/// The channels of the pack with their settings.
/// Who looks: needs einvoice.channel.manage.
/// The company.
/// Cancellation.
/// The channels, in the order of the pack.
public async Task> 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().ListAsync(Query.For(), 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 }))];
}
/// Saves the settings of a channel.
/// Who saves: needs einvoice.channel.manage.
/// The company.
/// The settings.
/// Cancellation.
/// The channel.
public async Task 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();
var code = channel.Code;
var row = await repository.FindAsync(Query.For().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(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);
}
/// Pauses or resumes a channel: a paused channel neither sends nor is read.
/// Who does it: needs einvoice.channel.manage.
/// The company.
/// The channel.
/// Whether to pause.
/// Cancellation.
/// A task.
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();
var row = await repository.FindAsync(Query.For().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);
}
/// Tries a channel with its saved settings (login to the mailbox, the service or the API) and keeps the outcome.
/// Who tries: needs einvoice.channel.manage.
/// The company.
/// The channel.
/// Cancellation.
/// The outcome.
public async Task 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().FindAsync(Query.For().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().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().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
return check;
}
/// The routing rules, in order.
/// Who looks: needs einvoice.channel.manage.
/// The company.
/// Cancellation.
/// The rules.
public async Task> 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().ListAsync(Query.For().OrderBy(r => r.Position), cancellationToken).ConfigureAwait(false)).Items;
}
/// Adds or changes a routing rule.
/// Who saves: needs einvoice.channel.manage.
/// The company.
/// The rule (identifier 0 to add).
/// Cancellation.
/// The rule.
public async Task 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();
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();
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().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(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;
}
/// Removes a routing rule.
/// Who removes: needs einvoice.channel.manage.
/// The company.
/// The rule.
/// Cancellation.
/// A task.
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();
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(uow, AuditAction.Delete, row.Id, row, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
private async Task ChannelsAsync(string company, CancellationToken cancellationToken) =>
(await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature()
?? 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();
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);
}