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,736 @@
using System.Globalization;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Files;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Microsoft.Extensions.Logging;
namespace Khaemhat.Application.EInvoicing;
/// <summary>
/// The electronic invoices of the company (SPEC §11.9, mockup 058, ADR 0039, issues #74-#75): the dashboard, the file
/// of each issued document written and checked by the fiscal pack, sending through the channel the router chooses
/// (with its fallback), the notifications of the SDI that move the e-invoice and its document, the correction of a
/// rejected invoice and the courtesy copy.
/// </summary>
/// <remarks>
/// Permissions: <c>einvoice.document.read</c> to see, <c>einvoice.document.send</c> to generate, send and import
/// notifications. The state of the document follows the e-invoice in the same transaction (generated, sent, delivered,
/// rejected, not delivered); a rejected invoice can be changed and generated again with a new progressive.
/// </remarks>
public sealed partial class EInvoiceService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly DocumentEngine _engine;
private readonly ISecretProtector _secrets;
private readonly DocumentPdfGenerator _pdf;
private readonly TimeProvider _clock;
private readonly ILogger<EInvoiceService> _logger;
/// <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="engine">The document engine.</param>
/// <param name="secrets">Opens the secrets of the channels.</param>
/// <param name="pdf">The print of the documents (courtesy copy).</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public EInvoiceService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, ISecretProtector secrets,
DocumentPdfGenerator pdf, TimeProvider clock, ILogger<EInvoiceService> logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(engine);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(pdf);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_permissions = permissions;
_packs = packs;
_engine = engine;
_secrets = secrets;
_pdf = pdf;
_clock = clock;
_logger = logger;
}
/// <summary>The dashboard: the e-invoices of the view, the documents to generate, the counters.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The dashboard.</returns>
public async Task<EInvoiceDashboard> DashboardAsync(Actor actor, string companyCode, EInvoiceFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<EInvoice>().Where(e => !e.Superseded);
if (filter.From is { } from)
{
query = query.Where(e => e.DocumentDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(e => e.DocumentDate <= to);
}
var all = (await uow.Repository<EInvoice, long>().ListAsync(query.OrderByDescending(e => e.DocumentDate), cancellationToken).ConfigureAwait(false)).Items
.Select(EInvoiceStore.Light)
.ToList();
var pending = await PendingAsync(uow, filter, cancellationToken).ConfigureAwait(false);
var received = await uow.Repository<EInvoiceInboxFile, long>().CountAsync(Query.For<EInvoiceInboxFile>().Where(f => f.Status == InboxFileStatus.New), cancellationToken)
.ConfigureAwait(false);
var counters = new EInvoiceCounters(
pending.Count(p => p.Status == DocumentStatus.Issued),
all.Count(e => e.Status == EInvoiceStatus.Generated),
all.Count(e => e.Status == EInvoiceStatus.Sent),
all.Count(e => EInvoiceStates.IsIssued(e.Status) && e.Status != EInvoiceStatus.Refused),
all.Count(e => EInvoiceStates.NeedsAction(e.Status)),
received);
IEnumerable<EInvoice> rows = filter.View switch
{
EInvoiceView.SelfInvoices => all.Where(e => e.Kind == DocumentKind.SelfInvoice),
EInvoiceView.ToDo => all.Where(e => e.Status == EInvoiceStatus.Generated || EInvoiceStates.NeedsAction(e.Status)),
_ => all.Where(e => e.Kind != DocumentKind.SelfInvoice),
};
if (filter.Status is { } status)
{
rows = rows.Where(e => e.Status == status);
}
var list = rows.ToList();
var parties = await PartiesAsync(uow, list.Select(e => e.PartyId).OfType<long>(), cancellationToken).ConfigureAwait(false);
var result = list.Select(e => new EInvoiceRow(e, parties.GetValueOrDefault(e.PartyId ?? 0)?.Code, parties.GetValueOrDefault(e.PartyId ?? 0)?.Name));
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
result = result.Where(r => Contains(r.Invoice.DocumentNumber, text) || Contains(r.Invoice.FileName, text) || Contains(r.Invoice.ExchangeId, text)
|| Contains(r.PartyName, text) || Contains(r.PartyCode, text));
}
var visiblePending = filter.View switch
{
EInvoiceView.SelfInvoices => pending.Where(p => p.Kind == DocumentKind.SelfInvoice),
EInvoiceView.ToDo => pending,
_ => pending.Where(p => p.Kind != DocumentKind.SelfInvoice),
};
return new EInvoiceDashboard([.. result], [.. visiblePending], counters);
}
/// <summary>The e-invoices of a document with their notifications, newest first (the page of the document).</summary>
/// <param name="actor">Who looks.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The files and their notifications.</returns>
public async Task<IReadOnlyList<(EInvoice Invoice, IReadOnlyList<EInvoiceNotification> Notifications)>> HistoryAsync(
Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var invoices = (await uow.Repository<EInvoice, long>()
.ListAsync(Query.For<EInvoice>().Where(e => e.Family == family && e.DocumentId == documentId).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items;
var result = new List<(EInvoice, IReadOnlyList<EInvoiceNotification>)>();
foreach (var invoice in invoices)
{
var id = invoice.Id;
var notifications = (await uow.Repository<EInvoiceNotification, long>()
.ListAsync(Query.For<EInvoiceNotification>().Where(n => n.EInvoiceId == id).OrderBy(n => n.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items;
result.Add((EInvoiceStore.Light(invoice), [.. notifications.Select(n => { n.Content = []; return n; })]));
}
return result;
}
/// <summary>Checks the file a document would have, without writing it.</summary>
/// <param name="actor">Who checks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The problems, empty when the file can be sent.</returns>
public async Task<IReadOnlyList<EInvoiceProblem>> CheckAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (!EInvoiceBuilder.IsElectronic(record.Header.Kind))
{
return [Problem(EInvoiceErrors.NotElectronic)];
}
var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
file = file with { FileName = writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? "0", 1), ProgressiveNumber = writer.Progressive(1) };
var problems = validator.Validate(file).ToList();
if (problems.All(p => p.Severity != EInvoiceProblemSeverity.Error))
{
problems.AddRange(validator.ValidateXml(writer.Write(file)));
}
return problems;
}
/// <summary>
/// Writes the file of an issued document (or of one rejected by the SDI): built from the document, checked against
/// the rules of the pack and its schema; the document goes to <i>XML generato</i>. A file generated and not sent is
/// written again with the same name; a rejected one is kept, superseded, and the new file has a new progressive.
/// </summary>
/// <param name="actor">Who generates: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="family">The family.</param>
/// <param name="documentId">The document.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The e-invoice, or the errors.</returns>
public async Task<EInvoiceGeneration> GenerateAsync(Actor actor, string companyCode, DocumentFamily family, long documentId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var (writer, validator, _) = await FeaturesAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var result = await GenerateCoreAsync(uow, writer, validator, family, documentId, actor.UserName, cancellationToken).ConfigureAwait(false);
if (result.Success)
{
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogGenerated(_logger, result.Invoice!.FileName, result.Invoice.DocumentNumber, company);
}
}
return result;
}
/// <summary>Generates the files of several documents and sends them (the button <i>Genera e invia</i>).</summary>
/// <param name="actor">Who sends.</param>
/// <param name="companyCode">The company.</param>
/// <param name="documents">The documents.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>For each document, the generation and the sending.</returns>
public async Task<IReadOnlyList<(PendingEInvoice? Document, EInvoiceGeneration Generation, EInvoiceSendOutcome? Sending)>> GenerateAndSendAsync(
Actor actor, string companyCode, IReadOnlyList<(DocumentFamily Family, long DocumentId)> documents, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(documents);
var result = new List<(PendingEInvoice?, EInvoiceGeneration, EInvoiceSendOutcome?)>();
foreach (var (family, id) in documents)
{
var generation = await GenerateAsync(actor, companyCode, family, id, cancellationToken).ConfigureAwait(false);
EInvoiceSendOutcome? sending = null;
if (generation.Invoice is { } invoice)
{
sending = (await SendAsync(actor, companyCode, [invoice.Id], cancellationToken).ConfigureAwait(false))[0];
}
result.Add((null, generation, sending));
}
return result;
}
/// <summary>
/// Sends generated files through the channel the router chooses; when the channel refuses the file the fallback of
/// the rule is tried. A file a channel took goes to <i>Inviato</i> with its document; one no channel took keeps its
/// state and the error.
/// </summary>
/// <param name="actor">Who sends: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The e-invoices.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<EInvoiceSendOutcome>> SendAsync(Actor actor, string companyCode, IReadOnlyList<long> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(ids);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var channels = pack.GetFeature<IEInvoiceChannels>();
var result = new List<EInvoiceSendOutcome>();
foreach (var id in ids.Distinct())
{
result.Add(await SendOneAsync(company, channels, id, actor.UserName, cancellationToken).ConfigureAwait(false));
}
return result;
}
/// <summary>Records that a generated file was sent outside Khaemhat (portal of the AdE, another program).</summary>
/// <param name="actor">Who records it: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The e-invoice.</param>
/// <param name="exchangeId">The identifier of the SDI, when known.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The e-invoice.</returns>
public async Task<EInvoice> MarkSentAsync(Actor actor, string companyCode, long id, string? exchangeId, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated)
{
throw new ValidationFailedException([":" + EInvoiceErrors.AlreadySent]);
}
await MarkSentCoreAsync(uow, invoice, EInvoiceStore.ManualChannel, EInvoiceStore.Trim(exchangeId, 40), null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return EInvoiceStore.Light(invoice);
}
/// <summary>Imports notifications downloaded from the portal of the AdE or from another program.</summary>
/// <param name="actor">Who imports: needs <c>einvoice.document.send</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="files">The files.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<ReceiptOutcome>> ImportReceiptsAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Send, cancellationToken).ConfigureAwait(false);
var reader = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<IEInvoiceReceiptReader>()
?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]);
var result = new List<ReceiptOutcome>();
foreach (var (name, content) in files)
{
EInvoiceReceipt receipt;
try
{
if (!reader.IsReceipt(name, content))
{
result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt));
continue;
}
receipt = reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
result.Add(new ReceiptOutcome(name, null, null, null, null, EInvoiceErrors.NotAReceipt));
continue;
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var outcome = await ApplyReceiptCoreAsync(uow, receipt, EInvoiceStore.ManualChannel, actor.UserName, false, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(outcome);
}
return result;
}
/// <summary>The file of an e-invoice, as sent.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The e-invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content.</returns>
public async Task<(string FileName, byte[] Content)> FileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return (invoice.FileName, invoice.Content);
}
/// <summary>The file of a notification.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The notification.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content.</returns>
public async Task<(string FileName, byte[] Content)> NotificationFileAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var notification = await uow.Repository<EInvoiceNotification, long>().GetAsync(id, cancellationToken).ConfigureAwait(false)
?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return (notification.FileName, notification.Content);
}
/// <summary>The courtesy copy: the print of the document with the XML of the e-invoice embedded.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.document.read</c> and to read the document.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The e-invoice.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>Name and content of the PDF.</returns>
public async Task<(string FileName, byte[] Content)> CourtesyCopyAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var (name, xml) = await FileAsync(actor, companyCode, id, cancellationToken).ConfigureAwait(false);
EInvoice invoice;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
using var output = new MemoryStream();
var context = new FileGenerationContext(actor, companyCode, DocumentPrintService.EntityOf(invoice.Family), invoice.DocumentId, CultureInfo.GetCultureInfo("it-IT"), _clock.GetUtcNow().UtcDateTime);
await _pdf.CourtesyCopyAsync(context, name, xml, output, cancellationToken).ConfigureAwait(false);
return (EInvoiceStore.Stem(name) + ".pdf", output.ToArray());
}
/// <summary>The core of the generation, in the transaction of the caller (also the demo seed).</summary>
internal async Task<EInvoiceGeneration> GenerateCoreAsync(
IUnitOfWork uow, IEInvoiceWriter writer, IEInvoiceValidator validator, DocumentFamily family, long documentId, string userName, CancellationToken cancellationToken)
{
var record = await DocumentEngine.LoadAsync(uow, family, documentId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var header = record.Header;
if (!EInvoiceBuilder.IsElectronic(header.Kind))
{
return new(null, [Problem(EInvoiceErrors.NotElectronic)]);
}
if (header.Status is DocumentStatus.Draft or DocumentStatus.Cancelled)
{
return new(null, [Problem(EInvoiceErrors.NotIssued)]);
}
var repository = uow.Repository<EInvoice, long>();
var active = await repository.FindAsync(Query.For<EInvoice>().Where(e => e.Family == family && e.DocumentId == documentId && !e.Superseded), cancellationToken)
.ConfigureAwait(false);
if (header.Status is not (DocumentStatus.Issued or DocumentStatus.SdiGenerated or DocumentStatus.SdiRejected)
|| active is { Status: not (EInvoiceStatus.Generated or EInvoiceStatus.Rejected) })
{
return new(null, [Problem(EInvoiceErrors.AlreadySent)]);
}
var (file, party, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false);
var problems = validator.Validate(file).ToList();
if (problems.Any(p => p.Severity == EInvoiceProblemSeverity.Error))
{
return new(null, problems);
}
var reuse = active is { Status: EInvoiceStatus.Generated };
var progressive = reuse ? active!.Progressive : await NextProgressiveAsync(uow, cancellationToken).ConfigureAwait(false);
var fileName = reuse ? active!.FileName : writer.FileName(file.TransmitterCountry ?? "IT", file.TransmitterId ?? string.Empty, progressive);
file = file with { FileName = fileName, ProgressiveNumber = writer.Progressive(progressive) };
var xml = writer.Write(file);
var schema = validator.ValidateXml(xml);
if (schema.Any(p => p.Severity == EInvoiceProblemSeverity.Error))
{
return new(null, [.. problems, .. schema]);
}
var now = _clock.GetUtcNow().UtcDateTime;
var invoice = reuse ? active! : new EInvoice();
invoice.Family = family;
invoice.DocumentId = documentId;
invoice.Kind = header.Kind;
invoice.DocumentNumber = header.DocumentNumber;
invoice.DocumentDate = header.DocumentDate;
invoice.PartyId = party.Id;
invoice.DocumentType = file.Invoices[0].DocumentType;
invoice.FileName = fileName;
invoice.Progressive = progressive;
invoice.Format = file.TransmissionFormat ?? string.Empty;
invoice.RecipientCode = file.RecipientCode;
invoice.RecipientPec = file.RecipientPec;
invoice.TotalAmount = header.TotalAmount;
invoice.Status = EInvoiceStatus.Generated;
invoice.GeneratedAt = now;
invoice.LastMessage = null;
invoice.Content = xml;
invoice.IsDemo = header.IsDemo;
if (reuse)
{
await repository.UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
}
else
{
if (active is not null)
{
active.Superseded = true;
await repository.UpdateAsync(active, cancellationToken).ConfigureAwait(false);
}
invoice.Id = await repository.InsertAsync(invoice, cancellationToken).ConfigureAwait(false);
}
await _engine.AdvanceExchangeAsync(uow, family, documentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Generated), userName, cancellationToken).ConfigureAwait(false);
return new(invoice, problems);
}
/// <summary>A file taken by a channel: <i>Inviato</i>, with the document.</summary>
internal async Task MarkSentCoreAsync(IUnitOfWork uow, EInvoice invoice, string channel, string? exchangeId, string? messageId, string userName, CancellationToken cancellationToken)
{
invoice.Status = EInvoiceStatus.Sent;
invoice.SentAt = _clock.GetUtcNow().UtcDateTime;
invoice.ChannelCode = channel;
invoice.ExchangeId = exchangeId ?? invoice.ExchangeId;
invoice.MessageId = EInvoiceStore.Trim(messageId, 200);
invoice.LastMessage = null;
await uow.Repository<EInvoice, long>().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Sent), userName, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Applies a notification in the transaction of the caller: kept as received (once: the file name is unique), the
/// e-invoice found by file name or identifier of the SDI gets the new state and its document follows.
/// </summary>
internal async Task<ReceiptOutcome> ApplyReceiptCoreAsync(
IUnitOfWork uow, EInvoiceReceipt receipt, string? channel, string userName, bool demo, CancellationToken cancellationToken)
{
var notifications = uow.Repository<EInvoiceNotification, long>();
var name = receipt.FileName;
if (await notifications.FindAsync(Query.For<EInvoiceNotification>().Where(n => n.FileName == name), cancellationToken).ConfigureAwait(false) is { } known)
{
return new ReceiptOutcome(name, receipt.Code, known.InvoiceFileName, known.EInvoiceId, null, EInvoiceErrors.ReceiptDuplicate);
}
var invoice = await FindInvoiceAsync(uow, receipt, cancellationToken).ConfigureAwait(false);
var errors = receipt.Errors.Count == 0 ? null : string.Join('\n', receipt.Errors.Select(e => e.Code + " - " + e.Description + (e.Hint is null ? string.Empty : " (" + e.Hint + ")")));
var receivedAt = (receipt.ReceivedAt ?? _clock.GetUtcNow()).UtcDateTime;
await notifications.InsertAsync(
new EInvoiceNotification
{
EInvoiceId = invoice?.Id,
Code = receipt.Code,
FileName = EInvoiceStore.Trim(name, 100)!,
InvoiceFileName = EInvoiceStore.Trim(receipt.InvoiceFileName ?? invoice?.FileName, 100),
ExchangeId = EInvoiceStore.Trim(receipt.ExchangeId, 40),
ReceivedAt = receivedAt,
Outcome = EInvoiceStore.Trim(receipt.Outcome, 10),
Description = EInvoiceStore.Trim(receipt.Description, 1000),
Errors = errors,
ChannelCode = channel,
Content = receipt.Content,
IsDemo = demo || invoice?.IsDemo == true,
},
cancellationToken).ConfigureAwait(false);
if (invoice is null)
{
return new ReceiptOutcome(name, receipt.Code, receipt.InvoiceFileName, null, null, receipt.Code is "MT" or "SE" ? null : EInvoiceErrors.ReceiptUnmatched);
}
var next = EInvoiceStates.After(receipt.Code, receipt.Outcome);
if (next is { } status)
{
if (invoice.Status == EInvoiceStatus.Generated)
{
invoice.SentAt ??= receivedAt;
invoice.ChannelCode ??= channel;
}
invoice.Status = status;
invoice.ExchangeId ??= EInvoiceStore.Trim(receipt.ExchangeId, 40);
invoice.LastNotificationAt = receivedAt;
invoice.LastMessage = EInvoiceStore.Trim(errors ?? receipt.Description, 1000);
await uow.Repository<EInvoice, long>().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false);
await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, status), userName, cancellationToken).ConfigureAwait(false);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogReceipt(_logger, receipt.Code, invoice.FileName, status);
}
}
return new ReceiptOutcome(name, receipt.Code, invoice.FileName, invoice.Id, next, null);
}
private static async Task<EInvoice?> FindInvoiceAsync(IUnitOfWork uow, EInvoiceReceipt receipt, CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoice, long>();
var stem = receipt.InvoiceFileName is { } invoiceName ? EInvoiceStore.Stem(invoiceName) : EInvoiceStore.InvoiceStem(receipt.FileName);
if (stem is not null)
{
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
if (await repository.FindAsync(Query.For<EInvoice>().Where(e => e.FileName == candidate), cancellationToken).ConfigureAwait(false) is { } byName)
{
return byName;
}
}
}
if (receipt.ExchangeId is { Length: > 0 } exchange)
{
return await repository.FindAsync(Query.For<EInvoice>().Where(e => e.ExchangeId == exchange).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false);
}
return null;
}
private async Task<EInvoiceSendOutcome> SendOneAsync(string company, IEInvoiceChannels? channels, long id, string userName, CancellationToken cancellationToken)
{
EInvoice invoice;
List<(string Code, EInvoiceChannelSettings Settings)> route;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
invoice = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (invoice.Superseded || invoice.Status != EInvoiceStatus.Generated)
{
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, invoice.ChannelCode, EInvoiceErrors.AlreadySent);
}
route = await RouteAsync(uow, channels, invoice, cancellationToken).ConfigureAwait(false);
}
if (route.Count == 0 || channels is null)
{
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, false, null, EInvoiceErrors.NoChannel);
}
EInvoiceSendResult? result = null;
string? used = null;
var errors = new List<string>();
foreach (var (code, settings) in route)
{
var transport = channels.Find(code)!.Transport;
used = code;
result = await transport.SendAsync(settings, new EInvoiceOutgoing(invoice.FileName, invoice.Content, invoice.DocumentNumber), cancellationToken).ConfigureAwait(false);
if (result.Accepted)
{
break;
}
errors.Add(code + ": " + result.Error);
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogSendFailed(_logger, invoice.FileName, code, result.Error);
}
}
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoice, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (result is { Accepted: true })
{
await MarkSentCoreAsync(uow, current, used!, EInvoiceStore.Trim(result.ExchangeId, 40), result.MessageId, userName, cancellationToken).ConfigureAwait(false);
}
else
{
current.SendAttempts++;
current.LastMessage = EInvoiceStore.Trim(string.Join(" | ", errors), 1000);
await uow.Repository<EInvoice, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
if (result is { Accepted: true })
{
using (_logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)))
{
LogSent(_logger, invoice.FileName, used!, company);
}
}
return new EInvoiceSendOutcome(id, invoice.FileName, invoice.DocumentNumber, result?.Accepted == true, used, result?.Accepted == true ? null : string.Join(" | ", errors));
}
// The channels to try, in order: the one of the router, then its fallback; each with its settings.
private async Task<List<(string Code, EInvoiceChannelSettings Settings)>> RouteAsync(IUnitOfWork uow, IEInvoiceChannels? channels, EInvoice invoice, CancellationToken cancellationToken)
{
if (channels is null)
{
return [];
}
var rows = (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Enabled && !c.Paused), cancellationToken)
.ConfigureAwait(false)).Items.ToDictionary(c => c.Code, StringComparer.OrdinalIgnoreCase);
var usable = channels.All.Select(c => c.Code).Where(rows.ContainsKey).ToList();
var rules = (await uow.Repository<SdiRoutingRule, long>().ListAsync(Query.For<SdiRoutingRule>(), cancellationToken).ConfigureAwait(false)).Items;
var party = invoice.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
var today = _clock.GetUtcNow().UtcDateTime.Date;
var sentToday = await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>().Where(e => e.SentAt >= today), cancellationToken).ConfigureAwait(false);
var choice = SdiRouter.Choose(new SdiRoutingInput(invoice.DocumentType, party?.Code, invoice.Format == "FPA12", sentToday), rules, usable);
if (choice is null)
{
return [];
}
return [.. new[] { choice.Channel, choice.Fallback }.OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase)
.Select(code => (code, EInvoiceStore.Settings(rows[code], _secrets)))];
}
private async Task<(IEInvoiceWriter Writer, IEInvoiceValidator Validator, IFiscalPack Pack)> FeaturesAsync(string company, CancellationToken cancellationToken)
{
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var writer = pack.GetFeature<IEInvoiceWriter>();
var validator = pack.GetFeature<IEInvoiceValidator>();
return writer is null || validator is null ? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]) : (writer, validator, pack);
}
private static async Task<long> NextProgressiveAsync(IUnitOfWork uow, CancellationToken cancellationToken)
{
var last = await uow.Repository<EInvoice, long>().FindAsync(Query.For<EInvoice>().OrderByDescending(e => e.Progressive), cancellationToken).ConfigureAwait(false);
return (last?.Progressive ?? 0L) + 1L;
}
// Issued (or rejected) electronic documents without a file ready to send.
private static async Task<List<PendingEInvoice>> PendingAsync(IUnitOfWork uow, EInvoiceFilter filter, CancellationToken cancellationToken)
{
var query = Query.For<SaleDocument>().Where(d => d.Status == DocumentStatus.Issued || d.Status == DocumentStatus.SdiRejected);
if (filter.From is { } from)
{
query = query.Where(d => d.DocumentDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(d => d.DocumentDate <= to);
}
var documents = (await uow.Repository<SaleDocument, long>().ListAsync(query.OrderBy(d => d.DocumentDate), cancellationToken).ConfigureAwait(false)).Items
.Where(d => EInvoiceBuilder.IsElectronic(d.Kind))
.ToList();
var parties = await PartiesAsync(uow, documents.Select(d => d.PartyId).OfType<long>(), cancellationToken).ConfigureAwait(false);
return [.. documents.Select(d => new PendingEInvoice(DocumentFamily.SaleDocument, d.Id, d.Kind, d.DocumentNumber, d.DocumentDate,
parties.GetValueOrDefault(d.PartyId ?? 0)?.Name, d.TotalAmount, d.Status))];
}
private static async Task<Dictionary<long, Party>> PartiesAsync(IUnitOfWork uow, IEnumerable<long> ids, CancellationToken cancellationToken)
{
var set = ids.Distinct().ToList();
var result = new Dictionary<long, Party>();
foreach (var chunk in set.Chunk(500))
{
var list = chunk.ToList();
foreach (var party in (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items)
{
result[party.Id] = party;
}
}
return result;
}
private static bool Contains(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
private static EInvoiceProblem Problem(string code) => new(code, string.Empty, code, EInvoiceProblemSeverity.Error);
[LoggerMessage(EventId = 9101, Level = LogLevel.Information, Message = "E-invoice {FileName} generated for document {Number} in {Company}.")]
private static partial void LogGenerated(ILogger logger, string fileName, string? number, string company);
[LoggerMessage(EventId = 9102, Level = LogLevel.Information, Message = "E-invoice {FileName} sent through {Channel} in {Company}.")]
private static partial void LogSent(ILogger logger, string fileName, string channel, string company);
[LoggerMessage(EventId = 9103, Level = LogLevel.Warning, Message = "E-invoice {FileName} not taken by channel {Channel}: {Error}")]
private static partial void LogSendFailed(ILogger logger, string fileName, string channel, string? error);
[LoggerMessage(EventId = 9104, Level = LogLevel.Information, Message = "Notification {Code} for {FileName}: now {Status}.")]
private static partial void LogReceipt(ILogger logger, string code, string fileName, EInvoiceStatus status);
}