Files
Khaemhat/src/Khaemhat.Application/EInvoicing/SdiPushService.cs
T
Alby96andClaude Opus 5.5 b78260beb0 feat: e-invoice screens and SdICoop push endpoint (#74 #75 #76 #77 #79)
The SDI dashboard (mockup 058) with its six counters, the documents to
generate, generate+send, manual receipts import, history, courtesy copy
and mark-as-sent; the channels page (mockup 059) with settings, test,
pause and routing rules; the received invoices, the notifications and
the conservation packages. The SdICoop web service receives pushes at
/sdicoop/{company}, authenticated by the key of the channel, through a
new IEInvoicePushReader feature so the web layer stays country-neutral.
The menu gives each e-invoice page its own permission and keeps the
intent declarations under M10.

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

139 lines
6.6 KiB
C#

using System.Security.Cryptography;
using System.Text;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The answer to a push of the exchange system.</summary>
/// <param name="StatusCode">The HTTP status.</param>
/// <param name="ContentType">The content type.</param>
/// <param name="Body">The body.</param>
public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body);
/// <summary>
/// Takes what the SDI pushes to the web service of a company (SdICoop, issue #76): invoices of suppliers and
/// notifications. The request carries the key stored in the channel (header <c>X-Khaemhat-SdiCoop-Key</c>); the mutual
/// TLS with the SDI is the job of the reverse proxy in front of Khaemhat. A disabled company, a channel that is not
/// enabled or a wrong key get nothing.
/// </summary>
public sealed partial class SdiPushService
{
/// <summary>The header with the key of the channel.</summary>
public const string KeyHeader = "X-Khaemhat-SdiCoop-Key";
private readonly ICompanyRegistry _companies;
private readonly ILicenseGate _license;
private readonly IUnitOfWorkFactory _factory;
private readonly CompanyFiscalContext _packs;
private readonly ISecretProtector _secrets;
private readonly EInvoicePollingService _polling;
private readonly TimeProvider _clock;
private readonly ILogger<SdiPushService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="companies">The companies.</param>
/// <param name="license">The licence.</param>
/// <param name="factory">The units of work.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="secrets">Opens the key of the channel.</param>
/// <param name="polling">Sorts the files received.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public SdiPushService(
ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets,
EInvoicePollingService polling, TimeProvider clock, ILogger<SdiPushService> logger)
{
ArgumentNullException.ThrowIfNull(companies);
ArgumentNullException.ThrowIfNull(license);
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(polling);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_companies = companies;
_license = license;
_factory = factory;
_packs = packs;
_secrets = secrets;
_polling = polling;
_clock = clock;
_logger = logger;
}
/// <summary>Takes a push.</summary>
/// <param name="companyCode">The company in the address.</param>
/// <param name="key">The key in the header.</param>
/// <param name="contentType">The content type.</param>
/// <param name="body">The body.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The answer.</returns>
public async Task<SdiPushAnswer> ReceiveAsync(string companyCode, string? key, string? contentType, byte[] body, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(body);
using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing));
var notFound = new SdiPushAnswer(404, "text/plain", "Not found.");
if (!_license.IsModuleActive(ModuleCodes.EInvoicing)
|| await _companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false) is not { } company
|| company.Status is CompanyStatus.Disabled)
{
return notFound;
}
var pack = await _packs.PackOfAsync(company.Code, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IEInvoicePushReader>() is not { } reader)
{
return notFound;
}
var channel = reader.Channel;
EInvoiceChannelSetting? row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false))
{
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Code == channel).Take(1), cancellationToken)
.ConfigureAwait(false)).Items;
row = rows.Count > 0 ? rows[0] : null;
}
var expected = row is { Enabled: true, ProtectedApiKey: { Length: > 0 } stored } ? _secrets.Unprotect(stored, EInvoiceStore.SecretPurpose) : null;
if (expected is null || key is null || !SameKey(expected, key))
{
LogRefused(_logger, company.Code, channel);
return new SdiPushAnswer(401, "text/plain", "Unauthorized.");
}
if (reader.Read(contentType, body) is not { } push)
{
var (type, refusal) = reader.Refusal();
return new SdiPushAnswer(400, type, refusal);
}
var now = _clock.GetUtcNow();
var messageKey = push.ExchangeId ?? EInvoiceStore.Hash(body);
var files = push.Files.Select(f => new EInvoiceIncoming(f.FileName, f.Content, now, messageKey, null)).ToList();
var outcome = await _polling.ReceivePushedAsync(company.Code, channel, files, cancellationToken).ConfigureAwait(false);
LogReceived(_logger, company.Code, channel, outcome.Invoices, outcome.Receipts);
return new SdiPushAnswer(200, push.AnswerContentType, push.Answer);
}
private static bool SameKey(string expected, string given) =>
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(expected)), SHA256.HashData(Encoding.UTF8.GetBytes(given)));
[LoggerMessage(Level = LogLevel.Warning, Message = "Push of channel {Channel} for company {Company} refused: wrong key or channel not enabled.")]
private static partial void LogRefused(ILogger logger, string company, string channel);
[LoggerMessage(Level = LogLevel.Information, Message = "Push of channel {Channel} for company {Company}: {Invoices} invoices, {Receipts} notifications.")]
private static partial void LogReceived(ILogger logger, string company, string channel, int invoices, int receipts);
}