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

+175
View File
@@ -733,6 +733,7 @@ Migrazioni applicate in ordine:
- `core` 20261113001 `create_inventory` (M20261113_001_CreateInventory)
- `core` 20261113002 `create_ledger` (M20261113_002_CreateLedger)
- `core` 20261113003 `create_treasury` (M20261113_003_CreateTreasury)
- `core` 20261113004 `create_einvoicing` (M20261113_004_CreateEInvoicing)
#### `attachments`
@@ -1241,6 +1242,180 @@ Migrazioni applicate in ordine:
- indice unico `ux_dunning_levels_level` su `level`
#### `e_invoice_channels`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `code` | String(20) | no | | |
| `enabled` | Bool | no | `false` | |
| `paused` | Bool | no | `false` | |
| `mailbox` | String(254) | sì | | |
| `smtp_host` | String(200) | sì | | |
| `smtp_port` | Int32 | no | `465` | |
| `imap_host` | String(200) | sì | | |
| `imap_port` | Int32 | no | `993` | |
| `tls` | Bool | no | `true` | |
| `user_name` | String(254) | sì | | |
| `protected_password` | Text | sì | | |
| `exchange_address` | String(254) | sì | | |
| `archive_folder` | String(100) | sì | | |
| `endpoint` | String(300) | sì | | |
| `protected_certificate` | Text | sì | | |
| `protected_certificate_password` | Text | sì | | |
| `protected_api_key` | Text | sì | | |
| `test_environment` | Bool | no | `false` | |
| `last_check_at` | DateTimeUtc | sì | | |
| `last_check_ok` | Bool | sì | | |
| `last_check_message` | String(1000) | sì | | |
| `last_poll_at` | DateTimeUtc | sì | | |
| `last_poll_message` | String(1000) | sì | | |
| `last_poll_failed` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice unico `ux_e_invoice_channels_code` su `code`
#### `e_invoice_conservation`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `from_date` | Date | no | | |
| `to_date` | Date | no | | |
| `file_count` | Int32 | no | `0` | |
| `file_name` | String(100) | no | | |
| `hash` | String(64) | no | | |
| `size` | Int64 | no | `0` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `e_invoice_inbox`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `file_name` | String(100) | no | | |
| `hash` | String(64) | no | | |
| `content` | Bytes | no | | |
| `metadata_file_name` | String(100) | sì | | |
| `metadata` | Bytes | sì | | |
| `exchange_id` | String(40) | sì | | |
| `received_at` | DateTimeUtc | no | | |
| `channel_code` | String(20) | sì | | |
| `supplier_vat` | String(30) | sì | | |
| `supplier_name` | String(200) | sì | | |
| `document_type` | String(10) | sì | | |
| `number` | String(40) | sì | | |
| `document_date` | Date | sì | | |
| `total_amount` | Decimal(19,6) | sì | | |
| `party_id` | Int64 | sì | | |
| `status` | String(40) | no | | |
| `purchase_document_id` | Int64 | sì | | |
| `error` | String(500) | sì | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_e_invoice_inbox_file` su `file_name`
- indice `ix_e_invoice_inbox_status` su `status`, `received_at`
- indice unico `ux_e_invoice_inbox_hash` su `hash`
#### `e_invoice_notifications`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `e_invoice_id` | Int64 | sì | | -> `e_invoices` (Cascade) |
| `code` | String(4) | no | | |
| `file_name` | String(100) | no | | |
| `invoice_file_name` | String(100) | sì | | |
| `exchange_id` | String(40) | sì | | |
| `received_at` | DateTimeUtc | no | | |
| `outcome` | String(10) | sì | | |
| `description` | String(1000) | sì | | |
| `errors` | Text | sì | | |
| `channel_code` | String(20) | sì | | |
| `content` | Bytes | no | | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_e_invoice_notifications_invoice` su `e_invoice_id`
- indice unico `ux_e_invoice_notifications_file` su `file_name`
#### `e_invoice_routing`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `position` | Int32 | no | `0` | |
| `condition` | String(40) | no | | |
| `value` | String(40) | sì | | |
| `channel_code` | String(20) | no | | |
| `fallback_channel_code` | String(20) | sì | | |
| `disabled` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
#### `e_invoices`
| Colonna | Tipo | Null | Default | Note |
|---|---|---|---|---|
| `id` | Int64 | no | | chiave primaria, identity |
| `family` | String(40) | no | | |
| `document_id` | Int64 | no | | |
| `kind` | String(40) | no | | |
| `document_number` | String(40) | sì | | |
| `document_date` | Date | no | | |
| `party_id` | Int64 | sì | | |
| `document_type` | String(10) | no | | |
| `file_name` | String(60) | no | | |
| `progressive` | Int64 | no | | |
| `format` | String(10) | no | | |
| `recipient_code` | String(7) | sì | | |
| `recipient_pec` | String(254) | sì | | |
| `total_amount` | Decimal(19,6) | no | `0` | |
| `status` | String(40) | no | | |
| `channel_code` | String(20) | sì | | |
| `exchange_id` | String(40) | sì | | |
| `message_id` | String(200) | sì | | |
| `generated_at` | DateTimeUtc | no | | |
| `sent_at` | DateTimeUtc | sì | | |
| `last_notification_at` | DateTimeUtc | sì | | |
| `last_message` | String(1000) | sì | | |
| `send_attempts` | Int32 | no | `0` | |
| `content` | Bytes | no | | |
| `superseded` | Bool | no | `false` | |
| `is_demo` | Bool | no | `false` | |
| `created_at` | DateTimeUtc | no | | |
| `created_by` | String(100) | sì | | |
| `updated_at` | DateTimeUtc | sì | | |
| `updated_by` | String(100) | sì | | |
| `row_version` | Int64 | no | `1` | |
- indice `ix_e_invoices_document` su `family`, `document_id`
- indice `ix_e_invoices_exchange` su `exchange_id`
- indice `ix_e_invoices_status` su `superseded`, `status`
- indice unico `ux_e_invoices_file` su `file_name`
#### `exchange_rates`
| Colonna | Tipo | Null | Default | Note |
@@ -33,6 +33,7 @@ public sealed class AuditTrail(TimeProvider clock)
{
nameof(IAuditable.CreatedAt), nameof(IAuditable.CreatedBy), nameof(IAuditable.UpdatedAt), nameof(IAuditable.UpdatedBy), "RowVersion",
"PasswordHash", "PasswordHistory", "TotpSecret", "TotpRecoveryCodes", "RecoveryTokenHash", "TokenHash", "ConnectionString",
"ProtectedPassword", "ProtectedCertificate", "ProtectedCertificatePassword", "ProtectedApiKey", "Content", "Metadata",
};
/// <summary>Writes the history row of a change, inside the caller's unit of work.</summary>
@@ -451,6 +451,48 @@ public sealed partial class DocumentEngine
}, null, cancellationToken);
}
/// <summary>
/// Moves a document along the steps of the electronic invoice inside the transaction of the caller (the e-invoice
/// service and its jobs, ADR 0039), which has already checked the permission. Steps the state does not allow are
/// skipped: a late or repeated notification never fails.
/// </summary>
/// <param name="uow">The open unit of work.</param>
/// <param name="family">The family.</param>
/// <param name="id">The document.</param>
/// <param name="steps">The steps, in order, from the state the document is in.</param>
/// <param name="userName">Who, for the history.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The state reached, or <see langword="null"/> when the document does not exist.</returns>
internal async Task<DocumentStatus?> AdvanceExchangeAsync(
IUnitOfWork uow, DocumentFamily family, long id, Func<DocumentStatus, IReadOnlyList<DocumentAction>> steps, string userName, CancellationToken cancellationToken)
{
var store = DocumentStores.Of(family);
var header = await store.GetAsync(uow, id, cancellationToken).ConfigureAwait(false);
if (header is null)
{
return null;
}
var lifecycle = DocumentBehaviors.Of(header.Kind).Lifecycle;
var old = header.Clone();
foreach (var step in steps(header.Status))
{
if (DocumentStateMachine.Allows(lifecycle, header.Status, step))
{
header.Status = DocumentStateMachine.Apply(lifecycle, header.Status, step);
header.XmlGenerated |= step == DocumentAction.GenerateXml;
}
}
if (header.Status != old.Status || header.XmlGenerated != old.XmlGenerated)
{
await store.UpdateAsync(uow, header, cancellationToken).ConfigureAwait(false);
await store.RecordAsync(_audit, uow, AuditAction.Update, id, old, header, userName, cancellationToken).ConfigureAwait(false);
}
return header.Status;
}
/// <summary>Records that the document was printed (its PDF kept among the attachments); the state does not change.</summary>
/// <param name="actor">Who prints: needs to read the document.</param>
/// <param name="companyCode">The company.</param>
@@ -52,7 +52,24 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, [], cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The courtesy copy of an e-invoice (SPEC §11.9, issue #79): the print of the document with the XML sent to the
/// exchange system embedded as an associated file (structure of PDF/A-3, <c>/AF</c>).
/// </summary>
/// <param name="context">The document.</param>
/// <param name="xmlName">The name of the XML file.</param>
/// <param name="xml">The XML file.</param>
/// <param name="output">The stream that receives the PDF.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CourtesyCopyAsync(FileGenerationContext context, string xmlName, byte[] xml, Stream output, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
var model = await ModelAsync(context, cancellationToken).ConfigureAwait(false);
await WriteAsync(model, context, output, [(xmlName, xml)], cancellationToken).ConfigureAwait(false);
}
// The file name follows the document (number and kind); without the logo, which the name does not need.
@@ -95,7 +112,8 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment
}
}
private static async Task WriteAsync(DocumentPrintModel model, FileGenerationContext context, Stream output, CancellationToken cancellationToken)
private static async Task WriteAsync(
DocumentPrintModel model, FileGenerationContext context, Stream output, IReadOnlyList<(string Name, byte[] Content)> embedded, CancellationToken cancellationToken)
{
var info = new PdfDocumentInfo
{
@@ -111,6 +129,11 @@ public sealed class DocumentPdfGenerator(DocumentPrintService prints, Attachment
await sheet.LinesAsync().ConfigureAwait(false);
await sheet.FooterBlocksAsync().ConfigureAwait(false);
sheet.Finish();
foreach (var (name, content) in embedded)
{
pdf.AddAttachment(name, "application/xml", content, "Fattura elettronica " + model.Number, "Source");
}
await pdf.CloseAsync(cancellationToken).ConfigureAwait(false);
}
@@ -0,0 +1,194 @@
using System.Globalization;
using System.IO.Compression;
using System.Text;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.EInvoicing;
/// <summary>A conservation package made.</summary>
/// <param name="Export">The row that records it.</param>
/// <param name="Content">The ZIP.</param>
public sealed record ConservationPackage(ConservationExport Export, byte[] Content);
/// <summary>
/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent
/// (<c>emesse/</c>), their notifications (<c>notifiche/</c>) and the files received (<c>ricevute/</c>), each as it
/// travelled, an index <c>indice.csv</c> with the SHA-256 of every file and a <c>LEGGIMI.txt</c>. It is what a
/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself.
/// </summary>
/// <remarks>Permission: <c>einvoice.document.read</c>. Every package made is recorded with its hash.</remarks>
public sealed class ConservationExportService
{
private static readonly DateTimeOffset Stamp = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
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="clock">The clock.</param>
public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_clock = clock;
}
/// <summary>The packages made, newest first.</summary>
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<ConservationExport>> ListAsync(Actor actor, string companyCode, 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);
return (await uow.Repository<ConservationExport, long>().ListAsync(Query.For<ConservationExport>().OrderByDescending(e => e.Id).Take(50), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// <summary>Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival.</summary>
/// <param name="actor">Who makes it: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">First day.</param>
/// <param name="to">Last day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The package.</returns>
public async Task<ConservationPackage> ExportAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
if (to < from || to.DayNumber - from.DayNumber > 400)
{
throw new ValidationFailedException(["To:" + EInvoiceErrors.PeriodInvalid]);
}
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 sent = (await uow.Repository<EInvoice, long>()
.ListAsync(Query.For<EInvoice>().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken)
.ConfigureAwait(false)).Items;
var notifications = new List<EInvoiceNotification>();
foreach (var chunk in sent.Select(e => e.Id).Chunk(500))
{
var ids = chunk.ToList();
notifications.AddRange((await uow.Repository<EInvoiceNotification, long>()
.ListAsync(Query.For<EInvoiceNotification>().Where(n => n.EInvoiceId != null && ids.Contains(n.EInvoiceId.Value)).OrderBy(n => n.ReceivedAt), cancellationToken)
.ConfigureAwait(false)).Items);
}
var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
var received = (await uow.Repository<EInvoiceInboxFile, long>()
.ListAsync(Query.For<EInvoiceInboxFile>().Where(f => f.ReceivedAt >= start && f.ReceivedAt < end && f.Status != InboxFileStatus.Discarded).OrderBy(f => f.ReceivedAt), cancellationToken)
.ConfigureAwait(false)).Items;
var index = new StringBuilder("cartella;file;tipo;documento;data;controparte;identificativo_sdi;stato;sha256\r\n");
var count = 0;
using var buffer = new MemoryStream();
using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
{
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
void Add(string folder, string name, byte[] content, string kind, string? number, string? date, string? party, string? exchange, string state)
{
var path = Unique(names, folder + "/" + Path.GetFileName(name));
var entry = zip.CreateEntry(path, CompressionLevel.Optimal);
entry.LastWriteTime = Stamp;
using (var stream = entry.Open())
{
stream.Write(content);
}
index.Append(string.Join(';', folder, Csv(Path.GetFileName(path)), kind, Csv(number), date, Csv(party), Csv(exchange), state, EInvoiceStore.Hash(content))).Append("\r\n");
count++;
}
foreach (var e in sent)
{
Add("emesse", e.FileName, e.Content, e.DocumentType, e.DocumentNumber, Date(e.DocumentDate), e.RecipientCode, e.ExchangeId, e.Status.ToString());
}
foreach (var n in notifications)
{
Add("notifiche", n.FileName, n.Content, n.Code, n.InvoiceFileName, Date(DateOnly.FromDateTime(n.ReceivedAt)), null, n.ExchangeId, n.Outcome ?? string.Empty);
}
foreach (var f in received)
{
Add("ricevute", f.FileName, f.Content, f.DocumentType ?? string.Empty, f.Number, f.DocumentDate is { } d ? Date(d) : null, f.SupplierName, f.ExchangeId, f.Status.ToString());
if (f.Metadata is { Length: > 0 } metadata && f.MetadataFileName is { } metadataName)
{
Add("ricevute", metadataName, metadata, "MT", f.Number, null, f.SupplierName, f.ExchangeId, string.Empty);
}
}
Write(zip, "indice.csv", Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(index.ToString())).ToArray());
Write(zip, "LEGGIMI.txt", Encoding.UTF8.GetBytes(Readme(company, from, to, sent.Count, notifications.Count, received.Count)));
}
var content = buffer.ToArray();
var fileName = string.Create(CultureInfo.InvariantCulture, $"conservazione-{company}-{from:yyyyMMdd}-{to:yyyyMMdd}.zip");
var export = new ConservationExport
{
FromDate = from,
ToDate = to,
FileCount = count,
FileName = fileName,
Hash = EInvoiceStore.Hash(content),
Size = content.LongLength,
};
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
export.Id = await uow.Repository<ConservationExport, long>().InsertAsync(export, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new ConservationPackage(export, content);
}
private static void Write(ZipArchive zip, string name, byte[] content)
{
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
entry.LastWriteTime = Stamp;
using var stream = entry.Open();
stream.Write(content);
}
private static string Unique(HashSet<string> names, string path)
{
var candidate = path;
for (var i = 2; !names.Add(candidate); i++)
{
candidate = Path.ChangeExtension(path, null) + "-" + i.ToString(CultureInfo.InvariantCulture) + Path.GetExtension(path);
}
return candidate;
}
private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
private static string Csv(string? value) =>
string.IsNullOrEmpty(value) ? string.Empty : value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
private string Readme(string company, DateOnly from, DateOnly to, int sent, int notifications, int received) =>
string.Create(CultureInfo.InvariantCulture, $"""
Khaemhat - pacchetto per la conservazione delle fatture elettroniche
Azienda: {company}
Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy}
Creato il: {_clock.GetUtcNow():yyyy-MM-dd HH:mm} UTC
emesse/ {sent} fatture inviate al SDI, nel formato in cui sono state trasmesse
notifiche/ {notifications} ricevute e notifiche del SDI relative alle fatture emesse
ricevute/ {received} fatture ricevute dai fornitori, con i file metadati (MT)
indice.csv l'elenco dei file con l'impronta SHA-256 di ciascuno
I file sono quelli originali: nessuno è stato modificato. Il pacchetto va consegnato al servizio di
conservazione (ad esempio il servizio gratuito dell'Agenzia delle Entrate o un conservatore accreditato);
Khaemhat non sostituisce la conservazione a norma.
""");
}
@@ -0,0 +1,553 @@
using Khaemhat.Application.Documents;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>
/// Turns a document into the model of the e-invoice (SPEC §11.9, ADR 0039): the company and the customer (or the
/// supplier and the company for a self-invoice), the lines with their codes, units and discounts, the summary by rate
/// and nature, stamp duty, withholding, social security fund, the documents referred to (order with CIG and CUP,
/// delivery notes, the invoice a credit note corrects) and the installments.
/// </summary>
/// <remarks>
/// <para>Amounts follow the document as computed by Khaemhat: a footer discount becomes one discount line (<c>SC</c>)
/// per rate, prices that include tax are taken back to their taxable amount, what is left by rounding goes in
/// <c>Arrotondamento</c> of the summary. A stamp duty charged to the customer is a line excluded from VAT (N1).</para>
/// <para>The file name is not set here: the service gives it with the progressive.</para>
/// </remarks>
internal static class EInvoiceBuilder
{
/// <summary>The country code of foreign customers without a VAT number (FatturaPA: eleven nines).</summary>
public const string NoVatNumber = "99999999999";
/// <summary>The recipient code of a foreign customer.</summary>
public const string ForeignRecipient = "XXXXXXX";
/// <summary>The recipient code when the file goes to a certified mailbox or to the tax drawer.</summary>
public const string NoRecipient = "0000000";
/// <summary>The type of the format of a document: the one of its document type, otherwise the default of its kind.</summary>
/// <param name="kind">The kind.</param>
/// <param name="type">The document type.</param>
/// <returns>The type (TD01 …), or <see langword="null"/> when the kind has no e-invoice.</returns>
public static string? DocumentTypeOf(DocumentKind kind, DocumentType? type)
{
if (!string.IsNullOrWhiteSpace(type?.EInvoiceType))
{
return type.EInvoiceType.Trim().ToUpperInvariant();
}
return kind switch
{
DocumentKind.ImmediateInvoice or DocumentKind.AccompanyingInvoice => "TD01",
DocumentKind.DeferredInvoice => "TD24",
DocumentKind.DownPaymentInvoice => "TD02",
DocumentKind.CreditNote => "TD04",
DocumentKind.DebitNote => "TD05",
DocumentKind.Fee => "TD06",
DocumentKind.SelfInvoice when type?.Code is { Length: 4 } code && code.StartsWith("AF", StringComparison.OrdinalIgnoreCase) => "TD" + code[2..],
_ => null,
};
}
/// <summary>Whether a kind of document goes to the exchange system.</summary>
/// <param name="kind">The kind.</param>
/// <returns><see langword="true"/> for invoices, credit and debit notes, fees and self-invoices.</returns>
public static bool IsElectronic(DocumentKind kind) => DocumentBehaviors.Of(kind).Effects.HasFlag(DocumentEffects.EInvoice);
/// <summary>Builds the file of a document.</summary>
/// <param name="uow">The unit of work of the company.</param>
/// <param name="record">The document, with lines and figures.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The model (file name empty), the party and whether it is a public administration.</returns>
public static async Task<(EInvoiceFile File, Party Party, bool PublicAdministration)> BuildAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken)
{
var header = record.Header;
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException([":" + EInvoiceErrors.CompanyProfileMissing]);
var party = header.PartyId is { } partyId ? await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null;
if (party is null)
{
throw new ValidationFailedException(["PartyId:" + DocumentErrors.PartyRequired]);
}
var fiscal = await uow.Repository<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().Where(f => f.PartyId == party.Id), cancellationToken).ConfigureAwait(false);
var type = await uow.Repository<DocumentType, long>().GetAsync(header.DocumentTypeId, cancellationToken).ConfigureAwait(false);
var documentType = DocumentTypeOf(header.Kind, type) ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotElectronic]);
var self = header.Kind == DocumentKind.SelfInvoice;
var publicAdministration = !self && party.SubjectType == SubjectType.PublicAdministration;
var company = CompanyParty(profile);
var counterpart = PartyOf(party, fiscal, self);
var foreign = !string.Equals(party.CountryCode, "IT", StringComparison.OrdinalIgnoreCase);
var (recipientCode, recipientPec) = self
? ((string Code, string? Pec))(profile.RecipientCode?.Trim().ToUpperInvariant() is { Length: > 0 } own ? own : NoRecipient, null)
: Recipient(party, fiscal, publicAdministration, foreign);
var body = await BodyAsync(uow, record, documentType, profile, fiscal, cancellationToken).ConfigureAwait(false);
var intermediary = !string.IsNullOrWhiteSpace(profile.IntermediaryTaxCode)
? new EInvoiceParty("IT", null, profile.IntermediaryTaxCode.Trim().ToUpperInvariant(), profile.IntermediaryName, null, null,
null, null, null, null, null, null, null, null, null, null, null)
: null;
var file = new EInvoiceFile(
string.Empty,
publicAdministration ? "FPA12" : "FPR12",
null,
recipientCode,
self ? counterpart : company,
self ? company with { TaxRegime = null, ReaOffice = null, ReaNumber = null, ShareCapital = null, Shareholders = null, LiquidationStatus = null } : counterpart,
[body],
null,
[])
{
TransmitterCountry = (profile.TransmitterCountry ?? "IT").Trim().ToUpperInvariant(),
TransmitterId = (profile.TransmitterId ?? profile.TaxCode ?? profile.VatNumber)?.Trim().ToUpperInvariant(),
RecipientPec = recipientPec,
Intermediary = intermediary,
IssuedBy = self ? "CC" : intermediary is not null ? "TZ" : null,
};
return (file, party, publicAdministration);
}
/// <summary>The company as it appears in the file.</summary>
/// <param name="profile">The profile.</param>
/// <returns>The party.</returns>
public static EInvoiceParty CompanyParty(CompanyProfile profile)
{
ArgumentNullException.ThrowIfNull(profile);
var country = (profile.AddressCountry ?? profile.Country ?? "IT").Trim().ToUpperInvariant();
return new EInvoiceParty(
(profile.Country ?? "IT").Trim().ToUpperInvariant(),
Digits(profile.VatNumber, profile.Country),
profile.TaxCode?.Trim().ToUpperInvariant(),
profile.LegalName,
null,
null,
profile.Address,
profile.StreetNumber,
profile.PostalCode,
profile.City,
country == "IT" ? profile.ProvinceCode : null,
country,
string.IsNullOrWhiteSpace(profile.TaxRegime) ? "RF01" : profile.TaxRegime,
profile.Email,
profile.Phone,
string.IsNullOrWhiteSpace(profile.ReaNumber) ? null : profile.ReaOffice,
string.IsNullOrWhiteSpace(profile.ReaOffice) ? null : profile.ReaNumber)
{
ShareCapital = profile.ShareCapital,
Shareholders = profile.Shareholders,
LiquidationStatus = string.IsNullOrWhiteSpace(profile.ReaNumber) ? null : profile.LiquidationStatus ?? "LN",
};
}
// The customer, or the supplier of a self-invoice.
private static EInvoiceParty PartyOf(Party party, PartyFiscal? fiscal, bool supplier)
{
var country = (party.CountryCode ?? "IT").Trim().ToUpperInvariant();
var italian = country == "IT";
var vat = Digits(party.VatNumber, country);
var taxCode = italian ? party.TaxCode?.Trim().ToUpperInvariant() : null;
if (!italian && vat is null)
{
vat = NoVatNumber;
}
var person = party.SubjectType == SubjectType.Person && !string.IsNullOrWhiteSpace(party.LastName);
return new EInvoiceParty(
vat is null ? null : country,
vat,
taxCode,
person ? null : party.Name,
person ? party.FirstName : null,
person ? party.LastName : null,
party.Address,
party.StreetNumber,
party.PostalCode,
party.City,
italian ? party.Province : null,
country,
supplier ? (italian ? "RF01" : "RF18") : null,
null,
null,
null,
null)
{
AdministrationReference = supplier ? null : fiscal?.AdministrationReference,
};
}
// The recipient: the code of the party, its certified mailbox, the code of foreign customers, or none.
private static (string Code, string? Pec) Recipient(Party party, PartyFiscal? fiscal, bool publicAdministration, bool foreign)
{
var code = fiscal?.RecipientCode?.Trim().ToUpperInvariant();
if (!string.IsNullOrEmpty(code) && (publicAdministration ? code.Length == 6 : code.Length == 7) && code != NoRecipient)
{
return (code, null);
}
if (foreign && !publicAdministration)
{
return (ForeignRecipient, null);
}
var pec = fiscal?.RecipientPec ?? party.Pec;
return (publicAdministration ? code ?? string.Empty : NoRecipient, string.IsNullOrWhiteSpace(pec) || publicAdministration ? null : pec.Trim());
}
private static async Task<EInvoiceBody> BodyAsync(
IUnitOfWork uow, DocumentRecord record, string documentType, CompanyProfile profile, PartyFiscal? fiscal, CancellationToken cancellationToken)
{
var header = record.Header;
var taxIds = record.Lines.Select(l => l.TaxCodeId).Append(header.SocialSecurityTaxCodeId).OfType<long>().Distinct().ToList();
var taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(t => taxIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(t => t.Id);
var unitIds = record.Lines.Select(l => l.UnitOfMeasureId).OfType<long>().Distinct().ToList();
var units = (await uow.Repository<UnitOfMeasure, long>().ListAsync(Query.For<UnitOfMeasure>().Where(u => unitIds.Contains(u.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(u => u.Id);
var itemIds = record.Lines.Select(l => l.ItemId).OfType<long>().Distinct().ToList();
var items = itemIds.Count == 0
? []
: (await uow.Repository<Item, long>().ListAsync(Query.For<Item>().Where(i => itemIds.Contains(i.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(i => i.Id);
var summary = record.Figures.Summary;
var first = summary.Count > 0 ? summary[0] : null;
var withholding = header.WithholdingRate is > 0m && header.WithholdingAmount != 0m;
var intent = fiscal is { IntentActive: true } && !string.IsNullOrWhiteSpace(fiscal.IntentProtocol);
var lines = new List<EInvoiceLine>();
var sourceLines = new Dictionary<int, DocumentLine>();
foreach (var line in record.Lines.OrderBy(l => l.LineNumber))
{
var tax = line.TaxCodeId is { } taxId && taxCodes.TryGetValue(taxId, out var code) ? code : null;
var rate = tax?.Rate ?? first?.Rate ?? 0m;
var nature = tax is null ? first?.Nature : tax.Nature;
var number = lines.Count + 1;
var description = string.IsNullOrWhiteSpace(line.Description) ? "-" : line.Description;
if (line.Kind == DocumentLineKind.Description)
{
lines.Add(new EInvoiceLine(number, [], description, null, null, 0m, 0m, rate, rate == 0m ? nature ?? "N2.2" : null, [], false, null, null, null, null));
continue;
}
var amount = line.TaxableAmount;
var quantity = line.Quantity;
var price = line.Price;
var discounts = DiscountsOf(line.DiscountFormula);
if (header.PricesIncludeTax && rate != 0m)
{
// The file has taxable amounts: the line becomes its taxable part, discounts included.
amount = Math.Round(amount * 100m / (100m + rate), 2, MidpointRounding.AwayFromZero);
price = quantity == 0m ? amount : Math.Round(amount / quantity, 8, MidpointRounding.AwayFromZero);
discounts = [];
if (quantity < 0m)
{
price = -price;
}
}
if (quantity < 0m)
{
// A negative quantity (a return on the invoice): the sign goes to the price.
quantity = -quantity;
price = -price;
}
var lineType = line.Kind switch
{
DocumentLineKind.Discount => "SC",
DocumentLineKind.Expense => "AC",
_ => null,
};
if (line.Kind == DocumentLineKind.Discount)
{
price = -Math.Abs(amount);
quantity = 0m;
discounts = [];
}
var codes = line.ItemId is { } itemId && items.TryGetValue(itemId, out var item) ? new[] { new EInvoiceItemCode("INTERNO", item.Code) } : [];
var unit = line.UnitOfMeasureId is { } unitId && units.TryGetValue(unitId, out var uom) ? uom.EInvoiceCode ?? uom.Code : null;
var withheld = withholding && !line.WithholdingExcluded && line.Kind != DocumentLineKind.Discount;
sourceLines[number] = line;
lines.Add(new EInvoiceLine(
number,
codes,
description,
quantity == 0m ? null : quantity,
quantity == 0m ? null : unit,
quantity == 0m ? amount : price,
amount,
rate,
rate == 0m ? nature : null,
discounts,
withheld,
lineType,
null,
null,
fiscal?.AdministrationReference)
{
OtherData = intent && nature == "N3.5"
? [new EInvoiceOtherData("INTENTO", fiscal!.IntentProtocol, null, fiscal.IntentDate)]
: [],
});
}
// The social security fund is part of the taxable of its rate, not of a line.
EInvoiceSocialSecurity? fund = null;
decimal fundRate = 0m;
string? fundNature = null;
if (header.SocialSecurityAmount != 0m && header.SocialSecurityRate is > 0m and var socialRate)
{
var fundTax = header.SocialSecurityTaxCodeId is { } fundTaxId && taxCodes.TryGetValue(fundTaxId, out var ft) ? ft : null;
fundRate = fundTax?.Rate ?? summary.Where(s => s.Rate > 0m).Select(s => s.Rate).FirstOrDefault();
fundNature = fundTax is null ? (fundRate == 0m ? first?.Nature : null) : fundTax.Nature;
fund = new EInvoiceSocialSecurity(
string.IsNullOrWhiteSpace(header.SocialSecurityFund) ? "TC22" : header.SocialSecurityFund,
socialRate,
header.SocialSecurityAmount,
Math.Round(header.SocialSecurityAmount * 100m / socialRate, 2, MidpointRounding.AwayFromZero),
fundRate,
withholding && header.SocialSecurityWithheld,
fundRate == 0m ? fundNature : null);
}
// The summary; what the lines do not explain becomes a discount line (footer discount) or the rounding.
var rows = new List<EInvoiceTaxSummary>();
foreach (var row in summary)
{
var linesSum = lines.Where(l => l.TaxRate == row.Rate && (row.Rate != 0m || l.Nature == row.Nature)).Sum(l => l.TotalPrice);
var fundPart = fund is not null && fundRate == row.Rate && (row.Rate != 0m || fundNature == row.Nature) ? fund.Amount : 0m;
var rest = row.Taxable - linesSum - fundPart;
decimal? rounding = null;
if (Math.Abs(rest) >= 0.01m && header.FooterDiscountAmount != 0m)
{
lines.Add(new EInvoiceLine(
lines.Count + 1, [], "Sconto di fine documento" + (string.IsNullOrWhiteSpace(header.FooterDiscount) ? string.Empty : " " + header.FooterDiscount + "%"),
null, null, rest, rest, row.Rate, row.Rate == 0m ? row.Nature : null, [], withholding, "SC", null, null, null));
}
else if (Math.Abs(rest) >= 0.01m)
{
rounding = rest;
}
rows.Add(new EInvoiceTaxSummary(
row.Rate,
row.Rate == 0m ? row.Nature : null,
row.Taxable,
row.Tax,
row.Rate == 0m ? null : row.Exigibility switch
{
TaxExigibility.Deferred => "D",
TaxExigibility.SplitPayment => "S",
_ => "I",
},
row.Rate == 0m ? row.LegalReference : null,
null,
rounding));
}
// Stamp duty charged to the customer: a line excluded from VAT, and its row in the summary.
if (header.StampDutyCharged && header.StampDuty > 0m)
{
lines.Add(new EInvoiceLine(lines.Count + 1, [], "Imposta di bollo", null, null, header.StampDuty, header.StampDuty, 0m, "N1", [], false, "AC", null, null, null));
var n1 = rows.FindIndex(r => r.Rate == 0m && r.Nature == "N1");
rows = n1 < 0
? [.. rows, new EInvoiceTaxSummary(0m, "N1", header.StampDuty, 0m, null, "Escluso art. 15 DPR 633/72", null, null)]
: [.. rows.Select((r, i) => i == n1 ? r with { Taxable = r.Taxable + header.StampDuty } : r)];
}
var (orders, related, deliveries) = await ReferencesAsync(uow, record, sourceLines, cancellationToken).ConfigureAwait(false);
var payments = await PaymentsAsync(uow, record, profile, cancellationToken).ConfigureAwait(false);
return new EInvoiceBody(
documentType,
header.CurrencyCode,
header.DocumentDate,
header.DocumentNumber ?? string.Empty,
header.TotalAmount,
null,
string.IsNullOrWhiteSpace(header.Notes) ? [] : [header.Notes.Trim()],
false,
withholding
? [new EInvoiceWithholding(string.IsNullOrWhiteSpace(header.WithholdingType) ? "RT01" : header.WithholdingType, header.WithholdingAmount, header.WithholdingRate!.Value,
string.IsNullOrWhiteSpace(header.WithholdingReason) ? "A" : header.WithholdingReason)]
: [],
header.StampDuty > 0m ? new EInvoiceStampDuty(true, header.StampDuty) : null,
fund is null ? [] : [fund],
[],
orders,
[],
related,
deliveries,
lines,
rows,
payments,
[])
{
Transport = await TransportAsync(uow, header, cancellationToken).ConfigureAwait(false),
PaymentConditions = payments.FirstOrDefault()?.Conditions,
};
}
// "10+5" gives two discounts in percent, in order.
private static IReadOnlyList<EInvoiceDiscount> DiscountsOf(string? formula) =>
DiscountFormula.TryParse(formula, out var steps)
? [.. steps.Select(s => s < 0m ? new EInvoiceDiscount(true, -s, null) : new EInvoiceDiscount(false, s, null))]
: [];
// The order of the customer (with CIG and CUP), the invoice corrected, the delivery notes of the lines.
private static async Task<(List<EInvoiceReference> Orders, List<EInvoiceReference> Related, List<EInvoiceReference> Deliveries)> ReferencesAsync(
IUnitOfWork uow, DocumentRecord record, Dictionary<int, DocumentLine> sourceLines, CancellationToken cancellationToken)
{
var header = record.Header;
var orders = new List<EInvoiceReference>();
if (!string.IsNullOrWhiteSpace(header.Cig) || !string.IsNullOrWhiteSpace(header.Cup) || !string.IsNullOrWhiteSpace(header.ExternalReference))
{
orders.Add(new EInvoiceReference(
string.IsNullOrWhiteSpace(header.ExternalReference) ? header.DocumentNumber : header.ExternalReference.Trim(),
header.ExternalDate,
[],
string.IsNullOrWhiteSpace(header.Cig) ? null : header.Cig.Trim().ToUpperInvariant(),
string.IsNullOrWhiteSpace(header.Cup) ? null : header.Cup.Trim().ToUpperInvariant()));
}
var related = new List<EInvoiceReference>();
if (!string.IsNullOrWhiteSpace(header.RelatedNumber))
{
related.Add(new EInvoiceReference(header.RelatedNumber.Trim(), header.RelatedDate, [], null, null));
}
else if (header.RelatedDocumentId is { } relatedId)
{
// A self-invoice integrates the supplier's invoice: its number is the one of the supplier.
var family = header.Kind == DocumentKind.SelfInvoice ? DocumentFamily.PurchaseDocument : record.Family;
if (await DocumentStores.Of(family).GetAsync(uow, relatedId, cancellationToken).ConfigureAwait(false) is { } other)
{
related.Add(family == DocumentFamily.PurchaseDocument
? new EInvoiceReference(other.ExternalReference ?? other.DocumentNumber, other.ExternalDate ?? other.DocumentDate, [], null, null)
: new EInvoiceReference(other.DocumentNumber, other.DocumentDate, [], null, null));
}
}
var deliveries = new Dictionary<long, (DocumentHeader Note, List<int> Lines)>();
var store = DocumentStores.Of(DocumentFamily.SaleDocument);
foreach (var (number, line) in sourceLines)
{
if (line.SourceFamily != DocumentFamily.SaleDocument || line.SourceLineId is not { } sourceLineId)
{
continue;
}
var source = await store.GetLineAsync(uow, sourceLineId, cancellationToken).ConfigureAwait(false);
if (source is null)
{
continue;
}
if (!deliveries.TryGetValue(source.DocumentId, out var entry))
{
if (await store.GetAsync(uow, source.DocumentId, cancellationToken).ConfigureAwait(false) is not { Kind: DocumentKind.DeliveryNote } note)
{
continue;
}
entry = (note, []);
deliveries[source.DocumentId] = entry;
}
entry.Lines.Add(number);
}
return (orders, related, [.. deliveries.Values.Select(d => new EInvoiceReference(d.Note.DocumentNumber, d.Note.DocumentDate, d.Lines, null, null))]);
}
// The installments with the method of each; the IBAN of the company for bank transfers.
private static async Task<List<EInvoicePayment>> PaymentsAsync(IUnitOfWork uow, DocumentRecord record, CompanyProfile profile, CancellationToken cancellationToken)
{
var header = record.Header;
var methodIds = record.Figures.Installments.Select(i => i.PaymentMethodId).Append(header.PaymentMethodId).OfType<long>().Distinct().ToList();
var methods = methodIds.Count == 0
? []
: (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>().Where(m => methodIds.Contains(m.Id)), cancellationToken).ConfigureAwait(false))
.Items.ToDictionary(m => m.Id);
var bankId = header.BankAccountId ?? profile.DefaultBankAccountId;
var bank = bankId is { } id ? await uow.Repository<BankAccount, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) : null;
string? Code(long? methodId) => methodId is { } m && methods.TryGetValue(m, out var method) && !string.IsNullOrWhiteSpace(method.EInvoiceCode) ? method.EInvoiceCode : null;
var installments = record.Figures.Installments.OrderBy(i => i.Number).ToList();
var conditions = header.Kind == DocumentKind.DownPaymentInvoice ? "TP03" : installments.Count > 1 ? "TP01" : "TP02";
var result = new List<EInvoicePayment>();
if (installments.Count == 0)
{
if (Code(header.PaymentMethodId) is { } only)
{
result.Add(new EInvoicePayment(conditions, only, null, header.NetAmount, only == "MP05" ? bank?.Iban : null, only == "MP05" ? bank?.Bic : null, null));
}
return result;
}
foreach (var installment in installments)
{
if (Code(installment.PaymentMethodId ?? header.PaymentMethodId) is not { } method)
{
continue;
}
result.Add(new EInvoicePayment(conditions, method, installment.DueDate, installment.Amount,
method == "MP05" ? bank?.Iban?.Replace(" ", string.Empty, StringComparison.Ordinal) : null, method == "MP05" ? bank?.Bic : null, null));
}
return result;
}
// The transport of an accompanying invoice: carrier, packages, weights, start.
private static async Task<EInvoiceTransport?> TransportAsync(IUnitOfWork uow, DocumentHeader header, CancellationToken cancellationToken)
{
if (header.Kind != DocumentKind.AccompanyingInvoice && header.CarrierId is null && header.Packages is null)
{
return null;
}
var carrier = header.CarrierId is { } carrierId ? await uow.Repository<Carrier, long>().GetAsync(carrierId, cancellationToken).ConfigureAwait(false) : null;
var reason = header.TransportReasonId is { } reasonId ? await uow.Repository<TransportReason, long>().GetAsync(reasonId, cancellationToken).ConfigureAwait(false) : null;
var vat = carrier?.VatNumber?.Trim();
return new EInvoiceTransport(
carrier?.Description,
string.IsNullOrWhiteSpace(vat) ? null : "IT",
string.IsNullOrWhiteSpace(vat) ? null : Digits(vat, "IT"),
header.TransportBy switch
{
TransportResponsibility.Sender => "Mittente",
TransportResponsibility.Recipient => "Destinatario",
TransportResponsibility.Carrier => "Vettore",
_ => null,
},
reason?.Description,
header.Packages,
null,
header.GrossWeight,
header.NetWeight,
header.TransportStart,
null);
}
// A VAT number without the country prefix and spaces.
private static string? Digits(string? vat, string? country)
{
if (string.IsNullOrWhiteSpace(vat))
{
return null;
}
var value = vat.Replace(" ", string.Empty, StringComparison.Ordinal).Trim().ToUpperInvariant();
return country is { Length: 2 } prefix && value.StartsWith(prefix.ToUpperInvariant(), StringComparison.Ordinal) && value.Length > 2 ? value[2..] : value;
}
}
@@ -0,0 +1,424 @@
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);
}
@@ -0,0 +1,60 @@
using Khaemhat.Application.Dashboard;
using Khaemhat.Application.Localization;
using Khaemhat.Application.Security;
namespace Khaemhat.Application.EInvoicing;
/// <summary>
/// The electronic invoice on the dashboard (SPEC §10.3): the files rejected by the SDI or refused by a public
/// administration, the documents to generate or send, the invoices received to register. Only for who may see them.
/// </summary>
/// <param name="invoices">The e-invoices.</param>
/// <param name="permissions">The permissions, licence included.</param>
/// <param name="texts">The texts.</param>
public sealed class EInvoiceFeedSource(EInvoiceService invoices, PermissionService permissions, ITexts texts) : ITodoSource
{
/// <summary>The text key of the area.</summary>
public const string Area = "Dashboard.Areas.EInvoicing";
/// <inheritdoc />
public async Task<IReadOnlyList<FeedItem>> GetAsync(FeedContext context, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(context);
if (context.Actor.CompanyCode is not { } company
|| !(await permissions.CheckAsync(context.Actor, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false)).Allowed)
{
return [];
}
var counters = (await invoices.DashboardAsync(context.Actor, company, new EInvoiceFilter(EInvoiceView.ToDo), cancellationToken).ConfigureAwait(false)).Counters;
var result = new List<FeedItem>();
if (counters.Rejected > 0)
{
result.Add(new FeedItem("einvoice-rejected", texts.Format("Dashboard.Feed.EInvoiceRejected", counters.Rejected), Area, FeedTone.Error)
{
Priority = 30,
Href = "/fatturazione-elettronica?vista=da-fare",
});
}
if (counters.ToGenerate + counters.ToSend > 0)
{
result.Add(new FeedItem("einvoice-to-send", texts.Format("Dashboard.Feed.EInvoiceToSend", counters.ToGenerate + counters.ToSend), Area, FeedTone.Warning)
{
Priority = 50,
Href = "/fatturazione-elettronica?vista=da-fare",
});
}
if (counters.Received > 0 && (await permissions.CheckAsync(context.Actor, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false)).Allowed)
{
result.Add(new FeedItem("einvoice-received", texts.Format("Dashboard.Feed.EInvoiceReceived", counters.Received), Area, FeedTone.Info)
{
Priority = 60,
Href = "/fatturazione-elettronica/ricevute",
});
}
return result;
}
}
@@ -0,0 +1,302 @@
using System.Globalization;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Instance;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
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>What reading one channel brought.</summary>
/// <param name="Channel">The channel.</param>
/// <param name="Messages">Messages read.</param>
/// <param name="Invoices">Invoices received and stored.</param>
/// <param name="Receipts">Notifications applied.</param>
/// <param name="Skipped">Files already known.</param>
/// <param name="Error">Why the channel could not be read.</param>
public sealed record EInvoicePollOutcome(string Channel, int Messages, int Invoices, int Receipts, int Skipped, string? Error);
/// <summary>
/// Reads the channels of the SDI (issue #76): the PEC mailbox and the intermediaries on a schedule, the SdICoop web
/// service when it calls. Every file is sorted: supplier invoices to the inbox, their metadata (MT) with them, the
/// notifications to the e-invoices they are about. A message is acknowledged (archived, marked as read) only when all
/// its files were kept, so nothing is lost when Khaemhat stops halfway.
/// </summary>
public sealed partial class EInvoicePollingService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly EInvoiceService _invoices;
private readonly ISecretProtector _secrets;
private readonly TimeProvider _clock;
private readonly ILogger<EInvoicePollingService> _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="invoices">The e-invoices (notifications).</param>
/// <param name="secrets">Opens the secrets of the channels.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public EInvoicePollingService(
IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, EInvoiceService invoices, ISecretProtector secrets, TimeProvider clock,
ILogger<EInvoicePollingService> logger)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(invoices);
ArgumentNullException.ThrowIfNull(secrets);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(logger);
_factory = factory;
_permissions = permissions;
_packs = packs;
_invoices = invoices;
_secrets = secrets;
_clock = clock;
_logger = logger;
}
/// <summary>Reads the channels of the company now (the button <i>Leggi ora</i>).</summary>
/// <param name="actor">Who asks: needs <c>einvoice.channel.manage</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What each channel brought.</returns>
public async Task<IReadOnlyList<EInvoicePollOutcome>> PollNowAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false);
return await PollCompanyAsync(company, cancellationToken).ConfigureAwait(false);
}
/// <summary>Reads every enabled, not paused channel of a company that is read on a schedule.</summary>
/// <param name="company">The company.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What each channel brought.</returns>
public async Task<IReadOnlyList<EInvoicePollOutcome>> PollCompanyAsync(string company, CancellationToken cancellationToken = default)
{
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature<IEInvoiceChannels>() is not { } channels)
{
return [];
}
List<EInvoiceChannelSetting> rows;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
rows = [.. (await uow.Repository<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().Where(c => c.Enabled && !c.Paused), cancellationToken)
.ConfigureAwait(false)).Items];
}
var result = new List<EInvoicePollOutcome>();
foreach (var row in rows)
{
if (channels.Find(row.Code) is not { Transport.Polls: true } channel)
{
continue;
}
result.Add(await PollChannelAsync(company, pack, channel, row, cancellationToken).ConfigureAwait(false));
}
return result;
}
/// <summary>Takes the files a channel pushed (SdICoop: <c>RiceviFatture</c>, <c>RiceviNotifica</c>) for a company.</summary>
/// <param name="company">The company the endpoint belongs to.</param>
/// <param name="channel">The channel.</param>
/// <param name="files">The files.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What the files brought.</returns>
public async Task<EInvoicePollOutcome> ReceivePushedAsync(string company, string channel, IReadOnlyList<EInvoiceIncoming> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var (invoices, receipts, skipped, _) = await ProcessAsync(company, pack, channel, files, cancellationToken).ConfigureAwait(false);
return new EInvoicePollOutcome(channel, 1, invoices, receipts, skipped, null);
}
private async Task<EInvoicePollOutcome> PollChannelAsync(string company, IFiscalPack pack, EInvoiceChannel channel, EInvoiceChannelSetting row, CancellationToken cancellationToken)
{
using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing));
var settings = EInvoiceStore.Settings(row, _secrets);
EInvoicePollOutcome outcome;
string? learned = null;
try
{
var fetched = await channel.Transport.FetchAsync(settings, cancellationToken).ConfigureAwait(false);
learned = fetched.ExchangeAddress;
var (invoices, receipts, skipped, done) = await ProcessAsync(company, pack, channel.Code, fetched.Files, cancellationToken).ConfigureAwait(false);
var keys = fetched.Files.GroupBy(f => f.MessageKey, StringComparer.Ordinal).Where(g => g.All(done.Contains)).Select(g => g.Key).ToList();
if (keys.Count > 0)
{
await channel.Transport.AcknowledgeAsync(settings, keys, cancellationToken).ConfigureAwait(false);
}
outcome = new EInvoicePollOutcome(channel.Code, fetched.MessagesRead, invoices, receipts, skipped, null);
LogPolled(_logger, channel.Code, company, fetched.MessagesRead, invoices, receipts);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
outcome = new EInvoicePollOutcome(channel.Code, 0, 0, 0, 0, ex.Message);
LogPollFailed(_logger, ex, channel.Code, company);
}
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (await uow.Repository<EInvoiceChannelSetting, long>().GetAsync(row.Id, cancellationToken).ConfigureAwait(false) is { } current)
{
current.LastPollAt = _clock.GetUtcNow().UtcDateTime;
current.LastPollFailed = outcome.Error is not null;
current.LastPollMessage = EInvoiceStore.Trim(
outcome.Error ?? string.Create(CultureInfo.InvariantCulture, $"{outcome.Messages} messaggi, {outcome.Invoices} fatture, {outcome.Receipts} notifiche"), 1000);
if (!string.IsNullOrWhiteSpace(learned) && !string.Equals(current.ExchangeAddress, learned, StringComparison.OrdinalIgnoreCase))
{
current.ExchangeAddress = learned;
}
await uow.Repository<EInvoiceChannelSetting, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return outcome;
}
// Invoices first, then their metadata, then the notifications: each file in its own transaction.
private async Task<(int Invoices, int Receipts, int Skipped, HashSet<EInvoiceIncoming> Done)> ProcessAsync(
string company, IFiscalPack pack, string channel, IReadOnlyList<EInvoiceIncoming> files, CancellationToken cancellationToken)
{
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var receiptReader = pack.GetFeature<IEInvoiceReceiptReader>();
var sorted = files.Select(f => (File: f, Receipt: ReadReceipt(receiptReader, f)))
.OrderBy(x => x.Receipt is null ? 0 : x.Receipt.Kind == EInvoiceReceiptKind.Metadata ? 1 : 2)
.ToList();
int invoices = 0, receipts = 0, skipped = 0;
var done = new HashSet<EInvoiceIncoming>();
foreach (var (file, receipt) in sorted)
{
try
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
if (receipt is null)
{
var stored = await SdiInboxService.StoreCoreAsync(uow, reader, file.FileName, file.Content, file.ReceivedAt.UtcDateTime, channel, null, false, cancellationToken)
.ConfigureAwait(false);
if (stored.Error is null)
{
invoices++;
}
else
{
skipped++;
}
}
else if (receipt.Kind == EInvoiceReceiptKind.Metadata)
{
await SdiInboxService.AttachMetadataCoreAsync(uow, receipt, cancellationToken).ConfigureAwait(false);
}
else
{
var applied = await _invoices.ApplyReceiptCoreAsync(uow, receipt, channel, Actor.System.UserName, false, cancellationToken).ConfigureAwait(false);
if (applied.Error == EInvoiceErrors.ReceiptDuplicate)
{
skipped++;
}
else
{
receipts++;
}
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
done.Add(file);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogFileFailed(_logger, ex, file.FileName, channel, company);
}
}
return (invoices, receipts, skipped, done);
}
private static EInvoiceReceipt? ReadReceipt(IEInvoiceReceiptReader? reader, EInvoiceIncoming file)
{
if (reader is null || !reader.IsReceipt(file.FileName, file.Content))
{
return null;
}
try
{
return reader.Read(file.FileName, file.Content);
}
catch (IncomingInvoiceException)
{
return null;
}
}
[LoggerMessage(EventId = 9111, Level = LogLevel.Information, Message = "Channel {Channel} of {Company}: {Messages} messages, {Invoices} invoices, {Receipts} notifications.")]
private static partial void LogPolled(ILogger logger, string channel, string company, int messages, int invoices, int receipts);
[LoggerMessage(EventId = 9112, Level = LogLevel.Warning, Message = "Channel {Channel} of {Company} could not be read.")]
private static partial void LogPollFailed(ILogger logger, Exception exception, string channel, string company);
[LoggerMessage(EventId = 9113, Level = LogLevel.Error, Message = "File {FileName} from channel {Channel} of {Company} was not kept; the message stays to read again.")]
private static partial void LogFileFailed(ILogger logger, Exception exception, string fileName, string channel, string company);
}
/// <summary>Reads the channels of the SDI of every company (job <c>einvoice.poll</c>, every 15 minutes).</summary>
/// <param name="companies">The companies.</param>
/// <param name="service">The reading of the channels.</param>
/// <param name="license">The licence.</param>
public sealed class EInvoicePollingJob(ICompanyRegistry companies, EInvoicePollingService service, ILicenseGate license) : IScheduledJob
{
/// <summary>The job type.</summary>
public const string JobType = "einvoice.poll";
/// <inheritdoc />
public string Type => JobType;
/// <inheritdoc />
public async Task<string?> RunAsync(JobContext context, CancellationToken cancellationToken)
{
if (!license.IsModuleActive(ModuleCodes.EInvoicing))
{
return "Modulo fatturazione elettronica non attivo.";
}
int done = 0, invoices = 0, receipts = 0, failed = 0;
foreach (var company in await companies.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (company.Status is CompanyStatus.Disabled)
{
continue;
}
foreach (var outcome in await service.PollCompanyAsync(company.Code, cancellationToken).ConfigureAwait(false))
{
invoices += outcome.Invoices;
receipts += outcome.Receipts;
failed += outcome.Error is null ? 0 : 1;
}
done++;
}
return string.Create(CultureInfo.InvariantCulture, $"{done} aziende, {invoices} fatture ricevute, {receipts} notifiche, {failed} canali non letti.");
}
}
@@ -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);
}
@@ -0,0 +1,283 @@
using System.Security.Cryptography;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Security;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The permissions of the electronic invoice (module EINV, <see cref="Modules.BuiltInModules"/>).</summary>
public static class EInvoicePermissions
{
/// <summary>See the e-invoices, their notifications and the conservation packages.</summary>
public const string Read = "einvoice.document.read";
/// <summary>Generate, send and send again; import notifications.</summary>
public const string Send = "einvoice.document.send";
/// <summary>See the invoices received.</summary>
public const string InboxRead = "einvoice.inbox.read";
/// <summary>Register, discard and upload the invoices received.</summary>
public const string InboxImport = "einvoice.inbox.import";
/// <summary>Configure the channels and the routing; read the channels now.</summary>
public const string ChannelManage = "einvoice.channel.manage";
}
/// <summary>The error codes of the electronic invoice (texts in <c>EInvoicing.json</c>).</summary>
public static class EInvoiceErrors
{
/// <summary>No e-invoice, notification or file with that identifier.</summary>
public const string NotFound = "einvoice.not-found";
/// <summary>The kind of document does not go to the exchange system.</summary>
public const string NotElectronic = "einvoice.not-electronic";
/// <summary>The document is not issued yet.</summary>
public const string NotIssued = "einvoice.not-issued";
/// <summary>The file was already sent: it can only receive notifications.</summary>
public const string AlreadySent = "einvoice.already-sent";
/// <summary>The profile of the company is missing.</summary>
public const string CompanyProfileMissing = "einvoice.profile-missing";
/// <summary>The fiscal pack of the company does not write e-invoices.</summary>
public const string NotSupported = "einvoice.not-supported";
/// <summary>No channel is enabled.</summary>
public const string NoChannel = "einvoice.no-channel";
/// <summary>The file is not a notification of the exchange system.</summary>
public const string NotAReceipt = "einvoice.not-a-receipt";
/// <summary>The notification is about a file Khaemhat did not send.</summary>
public const string ReceiptUnmatched = "einvoice.receipt-unmatched";
/// <summary>The notification was already imported.</summary>
public const string ReceiptDuplicate = "einvoice.receipt-duplicate";
/// <summary>The channel is not one of the pack.</summary>
public const string ChannelUnknown = "einvoice.channel-unknown";
/// <summary>A port out of range.</summary>
public const string PortInvalid = "einvoice.port-invalid";
/// <summary>The mailbox is not an e-mail address.</summary>
public const string MailboxInvalid = "einvoice.mailbox-invalid";
/// <summary>The address of the service is not an https address.</summary>
public const string EndpointInvalid = "einvoice.endpoint-invalid";
/// <summary>The value of a routing rule is missing or wrong.</summary>
public const string RuleValueInvalid = "einvoice.rule-value";
/// <summary>The received file is already in the inbox.</summary>
public const string InboxDuplicate = "einvoice.inbox-duplicate";
/// <summary>The received file is not in a state that allows the action.</summary>
public const string InboxState = "einvoice.inbox-state";
/// <summary>The period of the conservation package is wrong.</summary>
public const string PeriodInvalid = "einvoice.period-invalid";
}
/// <summary>An e-invoice in the lists, with its counterpart.</summary>
/// <param name="Invoice">The e-invoice (the file is not loaded for lists).</param>
/// <param name="PartyCode">The code of the customer or supplier.</param>
/// <param name="PartyName">The name.</param>
public sealed record EInvoiceRow(EInvoice Invoice, string? PartyCode, string? PartyName);
/// <summary>An issued document without its file yet, or whose file was rejected.</summary>
/// <param name="Family">The family.</param>
/// <param name="DocumentId">The document.</param>
/// <param name="Kind">The kind.</param>
/// <param name="Number">The number.</param>
/// <param name="Date">The date.</param>
/// <param name="PartyName">The customer, or the supplier of a self-invoice.</param>
/// <param name="Total">The total.</param>
/// <param name="Status">The state of the document.</param>
public sealed record PendingEInvoice(DocumentFamily Family, long DocumentId, DocumentKind Kind, string? Number, DateOnly Date, string? PartyName, decimal Total, DocumentStatus Status);
/// <summary>What the dashboard shows.</summary>
public enum EInvoiceView
{
/// <summary>Invoices, notes and fees sent to customers.</summary>
Issued = 0,
/// <summary>Self-invoices and integrations.</summary>
SelfInvoices = 1,
/// <summary>Everything that needs the user: to generate, to send, rejected, refused.</summary>
ToDo = 2,
}
/// <summary>The filter of the dashboard.</summary>
/// <param name="View">The view.</param>
/// <param name="Status">Only this state.</param>
/// <param name="From">From this date of the document.</param>
/// <param name="To">Up to this date.</param>
/// <param name="Search">Number, file name, identifier of the SDI or counterpart.</param>
public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EInvoiceStatus? Status = null, DateOnly? From = null, DateOnly? To = null, string? Search = null);
/// <summary>The counters of the dashboard (mockup 058).</summary>
/// <param name="ToGenerate">Issued documents without a file.</param>
/// <param name="ToSend">Files generated and not sent.</param>
/// <param name="Waiting">Sent, waiting for the receipt.</param>
/// <param name="Delivered">Delivered or issued (RC, MC, NE EC01, DT, AT).</param>
/// <param name="Rejected">Rejected by the SDI or refused by a public administration.</param>
/// <param name="Received">Invoices received to register.</param>
public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int Received);
/// <summary>The dashboard.</summary>
/// <param name="Rows">The e-invoices of the view.</param>
/// <param name="Pending">The documents to generate (view <see cref="EInvoiceView.ToDo"/> and the counters).</param>
/// <param name="Counters">The counters.</param>
public sealed record EInvoiceDashboard(IReadOnlyList<EInvoiceRow> Rows, IReadOnlyList<PendingEInvoice> Pending, EInvoiceCounters Counters);
/// <summary>The outcome of a generation: the file, or why not.</summary>
/// <param name="Invoice">The e-invoice written.</param>
/// <param name="Problems">Errors (nothing written) and warnings.</param>
public sealed record EInvoiceGeneration(EInvoice? Invoice, IReadOnlyList<EInvoiceProblem> Problems)
{
/// <summary>Whether the file was written.</summary>
public bool Success => Invoice is not null;
}
/// <summary>The outcome of sending one file.</summary>
/// <param name="EInvoiceId">The e-invoice.</param>
/// <param name="FileName">The file.</param>
/// <param name="DocumentNumber">The document.</param>
/// <param name="Sent">Whether a channel took it.</param>
/// <param name="ChannelCode">The channel that took it, or the last one tried.</param>
/// <param name="Error">Why not (a message of the channel, or an error code).</param>
public sealed record EInvoiceSendOutcome(long EInvoiceId, string FileName, string? DocumentNumber, bool Sent, string? ChannelCode, string? Error);
/// <summary>The outcome of a notification imported or received.</summary>
/// <param name="FileName">The notification.</param>
/// <param name="Code">Its code (RC, NS …).</param>
/// <param name="InvoiceFileName">The file it is about.</param>
/// <param name="EInvoiceId">The e-invoice updated.</param>
/// <param name="Status">The state it reached.</param>
/// <param name="Error">Why it was not applied (error code).</param>
public sealed record ReceiptOutcome(string FileName, string? Code, string? InvoiceFileName, long? EInvoiceId, EInvoiceStatus? Status, string? Error);
/// <summary>What the services of the electronic invoice share.</summary>
internal static class EInvoiceStore
{
/// <summary>The channel of what the user uploads or sends from the portal of the AdE.</summary>
public const string ManualChannel = "MANUAL";
/// <summary>The purpose of the protection of the secrets of the channels.</summary>
public const string SecretPurpose = "einvoice.channel";
/// <summary>The SHA-256 of a file in lower-case hexadecimal.</summary>
public static string Hash(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content));
/// <summary>A text cut to a length.</summary>
public static string? Trim(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Trim().Length <= length ? text.Trim() : text.Trim()[..length];
/// <summary>The settings of a channel for its transport, secrets unprotected.</summary>
public static EInvoiceChannelSettings Settings(EInvoiceChannelSetting row, ISecretProtector secrets)
{
string? Open(string? value) => string.IsNullOrEmpty(value) ? null : secrets.Unprotect(value, SecretPurpose);
var certificate = Open(row.ProtectedCertificate);
return new EInvoiceChannelSettings
{
Code = row.Code,
Mailbox = row.Mailbox,
SmtpHost = row.SmtpHost,
SmtpPort = row.SmtpPort,
ImapHost = row.ImapHost,
ImapPort = row.ImapPort,
Tls = row.Tls,
User = row.UserName,
Password = Open(row.ProtectedPassword),
ExchangeAddress = row.ExchangeAddress,
ArchiveFolder = row.ArchiveFolder,
Endpoint = row.Endpoint,
Certificate = certificate is null ? null : Convert.FromBase64String(certificate),
CertificatePassword = Open(row.ProtectedCertificatePassword),
ApiKey = Open(row.ProtectedApiKey),
TestEnvironment = row.TestEnvironment,
};
}
/// <summary>The name of the invoice file a notification is about, from the name of the notification.</summary>
/// <param name="receiptFileName">The notification (<c>IT01234567890_00001_RC_001.xml</c>).</param>
/// <returns>The stem of the invoice file (<c>IT01234567890_00001</c>), or <see langword="null"/>.</returns>
public static string? InvoiceStem(string receiptFileName)
{
var name = Path.GetFileName(receiptFileName);
var parts = name.Split('_');
return parts.Length >= 4 ? string.Join('_', parts[..^2]) : null;
}
/// <summary>The stem of a file name: without <c>.xml</c> and <c>.p7m</c>.</summary>
public static string Stem(string fileName)
{
var name = Path.GetFileName(fileName);
foreach (var extension in new[] { ".p7m", ".xml" })
{
if (name.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
name = name[..^extension.Length];
}
}
return name;
}
/// <summary>A shallow copy of a row (public properties that can be written), for the history of a change.</summary>
public static T Clone<T>(T row)
where T : class, new()
{
var copy = new T();
foreach (var property in typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (property is { CanRead: true, CanWrite: true } && property.GetIndexParameters().Length == 0)
{
property.SetValue(copy, property.GetValue(row));
}
}
return copy;
}
/// <summary>A copy without the file, for lists and history.</summary>
public static EInvoice Light(EInvoice e) => new()
{
Id = e.Id,
Family = e.Family,
DocumentId = e.DocumentId,
Kind = e.Kind,
DocumentNumber = e.DocumentNumber,
DocumentDate = e.DocumentDate,
PartyId = e.PartyId,
DocumentType = e.DocumentType,
FileName = e.FileName,
Progressive = e.Progressive,
Format = e.Format,
RecipientCode = e.RecipientCode,
RecipientPec = e.RecipientPec,
TotalAmount = e.TotalAmount,
Status = e.Status,
ChannelCode = e.ChannelCode,
ExchangeId = e.ExchangeId,
MessageId = e.MessageId,
GeneratedAt = e.GeneratedAt,
SentAt = e.SentAt,
LastNotificationAt = e.LastNotificationAt,
LastMessage = e.LastMessage,
SendAttempts = e.SendAttempts,
Superseded = e.Superseded,
IsDemo = e.IsDemo,
CreatedAt = e.CreatedAt,
CreatedBy = e.CreatedBy,
UpdatedAt = e.UpdatedAt,
UpdatedBy = e.UpdatedBy,
RowVersion = e.RowVersion,
};
}
@@ -0,0 +1,351 @@
using Khaemhat.Application.Purchases;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.EInvoicing;
/// <summary>The filter of the invoices received.</summary>
/// <param name="Status">Only this state.</param>
/// <param name="Search">Supplier, VAT number, number or file name.</param>
public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null);
/// <summary>A received file stored, or why not.</summary>
/// <param name="FileName">The file.</param>
/// <param name="Id">The row of the inbox.</param>
/// <param name="Status">Its state.</param>
/// <param name="Error">Why it was not stored (error code).</param>
public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error);
/// <summary>A received invoice registered as a supplier document, or why not.</summary>
/// <param name="Id">The row of the inbox.</param>
/// <param name="FileName">The file.</param>
/// <param name="PurchaseDocumentId">The draft supplier document.</param>
/// <param name="Error">Why it was not registered (error code).</param>
/// <param name="Warnings">What to check on the draft (codes).</param>
public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList<string> Warnings);
/// <summary>
/// The invoices received from the SDI (SPEC §11.9, issue #79): every file that arrives through a channel, or that the
/// user uploads, is kept as it was received with its metadata file (MT); the user registers it as a draft supplier
/// invoice (with the import of mockup 034), or discards it. A file is kept once, by its hash.
/// </summary>
/// <remarks>Permissions: <c>einvoice.inbox.read</c> to see, <c>einvoice.inbox.import</c> to upload, register and discard
/// (registering also needs <c>purchases.invoice.write</c>).</remarks>
public sealed class SdiInboxService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly PurchaseInvoiceImportService _import;
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="import">The import of supplier invoices.</param>
/// <param name="clock">The clock.</param>
public SdiInboxService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, PurchaseInvoiceImportService import, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(import);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_import = import;
_clock = clock;
}
/// <summary>The invoices received, newest first (files not loaded).</summary>
/// <param name="actor">Who looks: needs <c>einvoice.inbox.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows.</returns>
public async Task<IReadOnlyList<EInvoiceInboxFile>> ListAsync(Actor actor, string companyCode, InboxFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<EInvoiceInboxFile>();
if (filter.Status is { } status)
{
query = query.Where(f => f.Status == status);
}
var rows = (await uow.Repository<EInvoiceInboxFile, long>().ListAsync(query.OrderByDescending(f => f.ReceivedAt), cancellationToken).ConfigureAwait(false)).Items
.Select(Light);
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var text = filter.Search.Trim();
rows = rows.Where(f => Has(f.SupplierName, text) || Has(f.SupplierVat, text) || Has(f.Number, text) || Has(f.FileName, text) || Has(f.ExchangeId, text));
}
return [.. rows];
}
/// <summary>The received file, as it arrived.</summary>
/// <param name="actor">Who downloads: needs <c>einvoice.inbox.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="metadata">The metadata file (MT) instead of the 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, bool metadata = false, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
return metadata
? (row.MetadataFileName ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound), row.Metadata ?? [])
: (row.FileName, row.Content);
}
/// <summary>Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere).</summary>
/// <param name="actor">Who uploads: needs <c>einvoice.inbox.import</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<InboxStored>> UploadAsync(
Actor actor, string companyCode, IReadOnlyList<(string FileName, byte[] Content)> files, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(files);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
var reader = pack.GetFeature<IIncomingInvoiceReader>();
var receipts = pack.GetFeature<IEInvoiceReceiptReader>();
var result = new List<InboxStored>();
foreach (var (name, content) in files)
{
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
InboxStored stored;
if (receipts is not null && receipts.IsReceipt(name, content) && TryRead(receipts, name, content) is { Kind: EInvoiceReceiptKind.Metadata } meta)
{
var row = await AttachMetadataCoreAsync(uow, meta, cancellationToken).ConfigureAwait(false);
stored = new InboxStored(name, row?.Id, row?.Status, row is null ? EInvoiceErrors.ReceiptUnmatched : null);
}
else
{
stored = await StoreCoreAsync(uow, reader, name, content, _clock.GetUtcNow().UtcDateTime, EInvoiceStore.ManualChannel, null, false, cancellationToken)
.ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
result.Add(stored);
}
return result;
}
/// <summary>
/// Registers received invoices as draft supplier documents, through the import of supplier invoices: the supplier is
/// found or added, the lines take their items and tax codes, the file is attached.
/// </summary>
/// <param name="actor">Who registers: needs <c>einvoice.inbox.import</c> and <c>purchases.invoice.write</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="ids">The rows.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>What happened to each.</returns>
public async Task<IReadOnlyList<InboxRegistered>> RegisterAsync(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.InboxImport, cancellationToken).ConfigureAwait(false);
var result = new List<InboxRegistered>();
foreach (var id in ids.Distinct())
{
EInvoiceInboxFile row;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
row = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
}
if (row.Status != InboxFileStatus.New)
{
result.Add(new InboxRegistered(id, row.FileName, row.PurchaseDocumentId, EInvoiceErrors.InboxState, []));
continue;
}
var reading = await _import.ReadAsync(actor, company, [(row.FileName, row.Content)], cancellationToken).ConfigureAwait(false);
if (reading.Rejected.Count > 0 || reading.Invoices.Count == 0)
{
result.Add(new InboxRegistered(id, row.FileName, null, (reading.Rejected.Count > 0 ? reading.Rejected[0].Error : PurchaseInvoiceImportService.EmptyArchive), []));
continue;
}
var blocked = reading.Invoices.FirstOrDefault(c => !c.CanImport);
if (blocked is not null)
{
result.Add(new InboxRegistered(id, row.FileName, null, (blocked.Problems.Count > 0 ? blocked.Problems[0] : PurchaseInvoiceImportService.UnsupportedType), blocked.Problems));
continue;
}
var imported = await _import.ImportAsync(actor, company, reading.Invoices, cancellationToken).ConfigureAwait(false);
var failed = imported.FirstOrDefault(i => i.Error is not null);
var first = imported.FirstOrDefault(i => i.Record is not null);
var documentId = first?.Record?.Header.Id;
await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var current = await uow.Repository<EInvoiceInboxFile, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
if (documentId is not null)
{
current.Status = InboxFileStatus.Registered;
current.PurchaseDocumentId = documentId;
current.PartyId = first!.Record!.Header.PartyId ?? current.PartyId;
}
current.Error = failed?.Error;
await uow.Repository<EInvoiceInboxFile, long>().UpdateAsync(current, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
result.Add(new InboxRegistered(id, row.FileName, documentId, failed?.Error, [.. imported.SelectMany(i => i.Warnings).Distinct(StringComparer.Ordinal)]));
}
return result;
}
/// <summary>Discards a received invoice (a copy, a file not for the company), or takes it back.</summary>
/// <param name="actor">Who does it: needs <c>einvoice.inbox.import</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The row.</param>
/// <param name="discard">Discard, or take back.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task DiscardAsync(Actor actor, string companyCode, long id, bool discard, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.InboxImport, 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<EInvoiceInboxFile, long>();
var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound);
var allowed = discard ? row.Status is InboxFileStatus.New or InboxFileStatus.Unreadable : row.Status == InboxFileStatus.Discarded;
if (!allowed)
{
throw new ValidationFailedException([":" + EInvoiceErrors.InboxState]);
}
row.Status = discard ? InboxFileStatus.Discarded : row.SupplierVat is null && row.Number is null ? InboxFileStatus.Unreadable : InboxFileStatus.New;
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stores a received file in the transaction of the caller: read by the pack for the list (supplier, number, date,
/// total); a file the pack cannot read is kept as unreadable, a file already kept is not stored again.
/// </summary>
internal static async Task<InboxStored> StoreCoreAsync(
IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo,
CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoiceInboxFile, long>();
var hash = EInvoiceStore.Hash(content);
if (await repository.FindAsync(Query.For<EInvoiceInboxFile>().Where(f => f.Hash == hash), cancellationToken).ConfigureAwait(false) is { } known)
{
return new InboxStored(fileName, known.Id, known.Status, EInvoiceErrors.InboxDuplicate);
}
var row = new EInvoiceInboxFile
{
FileName = EInvoiceStore.Trim(Path.GetFileName(fileName), 200) ?? "fattura.xml",
Hash = hash,
Content = content,
ReceivedAt = receivedAt,
ChannelCode = channel,
ExchangeId = EInvoiceStore.Trim(exchangeId, 40),
Status = InboxFileStatus.Unreadable,
IsDemo = demo,
};
try
{
if (reader is not null && reader.CanRead(fileName, content))
{
var file = reader.Read(fileName, content);
var invoice = file.Invoices[0];
row.SupplierVat = EInvoiceStore.Trim((file.Supplier.CountryCode ?? string.Empty) + (file.Supplier.VatNumber ?? file.Supplier.TaxCode), 30);
row.SupplierName = EInvoiceStore.Trim(file.Supplier.DisplayName, 200);
row.DocumentType = invoice.DocumentType;
row.Number = EInvoiceStore.Trim(invoice.Number, 40);
row.DocumentDate = invoice.Date;
row.TotalAmount = file.Invoices.Count == 1 ? invoice.Total ?? invoice.TaxSummary.Sum(t => t.Taxable + t.Tax) : null;
row.PartyId = await PurchaseInvoiceImportService.FindSupplierAsync(uow, file.Supplier, cancellationToken).ConfigureAwait(false);
row.Status = InboxFileStatus.New;
}
else
{
row.Error = IncomingInvoiceErrors.NotReadable;
}
}
catch (IncomingInvoiceException ex)
{
row.Error = ex.Code;
}
row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false);
return new InboxStored(fileName, row.Id, row.Status, null);
}
/// <summary>Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file.</summary>
internal static async Task<EInvoiceInboxFile?> AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken)
{
var repository = uow.Repository<EInvoiceInboxFile, long>();
var stem = metadata.InvoiceFileName is { } name ? EInvoiceStore.Stem(name) : EInvoiceStore.InvoiceStem(metadata.FileName);
if (stem is null)
{
return null;
}
EInvoiceInboxFile? row = null;
foreach (var candidate in new[] { stem + ".xml", stem + ".xml.p7m" })
{
row = await repository.FindAsync(Query.For<EInvoiceInboxFile>().Where(f => f.FileName == candidate).OrderByDescending(f => f.Id), cancellationToken).ConfigureAwait(false);
if (row is not null)
{
break;
}
}
if (row is null)
{
return null;
}
row.MetadataFileName = EInvoiceStore.Trim(metadata.FileName, 200);
row.Metadata = metadata.Content;
row.ExchangeId ??= EInvoiceStore.Trim(metadata.ExchangeId, 40);
await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false);
return row;
}
private static EInvoiceReceipt? TryRead(IEInvoiceReceiptReader reader, string name, byte[] content)
{
try
{
return reader.Read(name, content);
}
catch (IncomingInvoiceException)
{
return null;
}
}
private static EInvoiceInboxFile Light(EInvoiceInboxFile row)
{
var copy = EInvoiceStore.Clone(row);
copy.Content = [];
copy.Metadata = null;
return copy;
}
private static bool Has(string? value, string text) => value?.Contains(text, StringComparison.CurrentCultureIgnoreCase) == true;
}
@@ -61,6 +61,7 @@ public sealed class JobScheduler
new("inventory.rebuild", "Ricostruzione del magazzino", Inventory.InventoryRebuildJob.JobType, "15 2 * * 0", 3600),
new("ledger.recurring", "Registrazioni ricorrenti", Ledger.RecurringEntriesJob.JobType, "0 5 * * *", 1800),
new("finance.dunning", "Solleciti automatici", Treasury.DunningJob.JobType, "0 7 * * 1-5", 1800, UsesNetwork: true),
new("einvoice.poll", "Lettura dei canali SDI", EInvoicing.EInvoicePollingJob.JobType, "*/15 * * * *", 900, UsesNetwork: true),
];
private readonly IUnitOfWorkFactory _factory;
@@ -70,7 +70,8 @@ public static class BuiltInModules
("einvoice.document.read", "Vedere i documenti elettronici"),
("einvoice.document.send", "Inviare documenti allo SDI"),
("einvoice.inbox.read", "Vedere le fatture ricevute"),
("einvoice.inbox.import", "Importare le fatture ricevute")),
("einvoice.inbox.import", "Importare le fatture ricevute"),
("einvoice.channel.manage", "Configurare i canali verso lo SDI")),
Module(ModuleCodes.Intrastat, "Intrastat",
("intrastat.list.read", "Vedere gli elenchi Intrastat"),
("intrastat.list.write", "Compilare gli elenchi Intrastat"),
@@ -339,7 +339,7 @@ public sealed class PurchaseInvoiceImportService
: party.CountryCode is null or "IT" ? vat
: vat.StartsWith(party.CountryCode, StringComparison.OrdinalIgnoreCase) ? vat : party.CountryCode + vat;
private static async Task<long?> FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken)
internal static async Task<long?> FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken)
{
var parties = uow.Repository<Party, long>();
if (VatOf(party) is { } vat)
@@ -94,7 +94,7 @@ public static class DocumentStateMachine
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiGenerated, (Copy, null), (DocumentAction.GenerateXml, null), (DocumentAction.Send, DocumentStatus.SdiSent), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiSent, (Copy, null), (DocumentAction.MarkDelivered, DocumentStatus.SdiDelivered),
(DocumentAction.MarkRejected, DocumentStatus.SdiRejected), (DocumentAction.MarkNotDelivered, DocumentStatus.SdiNotDelivered));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiRejected, (Edit, null), (Copy, null), (DocumentAction.GenerateXml, DocumentStatus.SdiGenerated), (DocumentAction.Cancel, DocumentStatus.Cancelled));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiDelivered, (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.SdiNotDelivered, (Copy, null));
Add(DocumentLifecycle.Invoice, DocumentStatus.Cancelled, (Copy, null));
+534
View File
@@ -0,0 +1,534 @@
using Khaemhat.Core.Documents;
using Khaemhat.Core.Entities;
namespace Khaemhat.Core.EInvoicing;
/// <summary>Where an e-invoice is in its exchange with the SDI (SPEC §11.9, mockup 058).</summary>
public enum EInvoiceStatus
{
/// <summary>The file was written and checked; not sent yet.</summary>
Generated = 0,
/// <summary>Taken by the channel; waiting for the receipt of the SDI.</summary>
Sent = 1,
/// <summary>Delivered to the customer (RC).</summary>
Delivered = 2,
/// <summary>Not delivered, but available in the customer's tax drawer (MC): the invoice is issued.</summary>
NotDelivered = 3,
/// <summary>Rejected by the SDI (NS): the invoice is not issued; correct it and send it again.</summary>
Rejected = 4,
/// <summary>Accepted by the public administration (NE EC01).</summary>
Accepted = 5,
/// <summary>Refused by the public administration (NE EC02): a credit note is needed.</summary>
Refused = 6,
/// <summary>The public administration did not answer within 15 days (DT).</summary>
TermsElapsed = 7,
/// <summary>A public administration could not be reached (AT): the invoice is issued.</summary>
Undeliverable = 8,
}
/// <summary>What a notification of the SDI does to an e-invoice.</summary>
public static class EInvoiceStates
{
/// <summary>The state after a notification, by its code (RC, NS, MC, NE, DT, AT); <see langword="null"/> when it does not change.</summary>
/// <param name="code">The code of the notification.</param>
/// <param name="outcome">The outcome of an NE (EC01, EC02).</param>
/// <returns>The new state.</returns>
public static EInvoiceStatus? After(string code, string? outcome) => code switch
{
"RC" => EInvoiceStatus.Delivered,
"NS" => EInvoiceStatus.Rejected,
"MC" => EInvoiceStatus.NotDelivered,
"NE" => outcome == "EC02" ? EInvoiceStatus.Refused : EInvoiceStatus.Accepted,
"DT" => EInvoiceStatus.TermsElapsed,
"AT" => EInvoiceStatus.Undeliverable,
_ => null,
};
/// <summary>The state of the document for a state of its e-invoice.</summary>
/// <param name="status">The state of the e-invoice.</param>
/// <returns>The state of the document.</returns>
public static DocumentStatus DocumentStatusOf(EInvoiceStatus status) => status switch
{
EInvoiceStatus.Generated => DocumentStatus.SdiGenerated,
EInvoiceStatus.Sent => DocumentStatus.SdiSent,
EInvoiceStatus.Rejected => DocumentStatus.SdiRejected,
EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable => DocumentStatus.SdiNotDelivered,
_ => DocumentStatus.SdiDelivered,
};
/// <summary>The steps of the document that lead from one state to another.</summary>
/// <param name="current">The state of the document now.</param>
/// <param name="target">The state of the e-invoice.</param>
/// <returns>The actions, in order (empty when already there).</returns>
public static IReadOnlyList<DocumentAction> StepsTo(DocumentStatus current, EInvoiceStatus target)
{
var steps = new List<DocumentAction>();
var wanted = DocumentStatusOf(target);
if (current == wanted && target != EInvoiceStatus.Generated)
{
return steps;
}
if (current is DocumentStatus.Issued or DocumentStatus.SdiRejected || target == EInvoiceStatus.Generated)
{
steps.Add(DocumentAction.GenerateXml);
}
if (target == EInvoiceStatus.Generated)
{
return steps;
}
// A notification for a file never marked as sent (sent from the portal of the AdE): it was sent.
if (current is not DocumentStatus.SdiSent)
{
steps.Add(DocumentAction.Send);
}
if (target == EInvoiceStatus.Sent)
{
return steps;
}
steps.Add(wanted switch
{
DocumentStatus.SdiRejected => DocumentAction.MarkRejected,
DocumentStatus.SdiNotDelivered => DocumentAction.MarkNotDelivered,
_ => DocumentAction.MarkDelivered,
});
return steps;
}
/// <summary>Whether the invoice is legally issued in this state (everything after the SDI took it, except a rejection).</summary>
/// <param name="status">The state.</param>
/// <returns><see langword="true"/> when issued.</returns>
public static bool IsIssued(EInvoiceStatus status) => status is not (EInvoiceStatus.Generated or EInvoiceStatus.Sent or EInvoiceStatus.Rejected);
/// <summary>Whether the state needs the user (a rejection, a refusal).</summary>
/// <param name="status">The state.</param>
/// <returns><see langword="true"/> when something must be done.</returns>
public static bool NeedsAction(EInvoiceStatus status) => status is EInvoiceStatus.Rejected or EInvoiceStatus.Refused;
}
/// <summary>
/// An e-invoice file of a document (SPEC §11.9, <c>e_invoices</c>): the file as sent, its name and progressive, the
/// channel and the identifier of the SDI, the last state. A file rejected and sent again leaves its row, marked as
/// superseded, and a new one takes its place.
/// </summary>
public sealed class EInvoice : Entity<long>, IDemoMarkable
{
/// <summary>The family of the document.</summary>
public DocumentFamily Family { get; set; }
/// <summary>The document.</summary>
public long DocumentId { get; set; }
/// <summary>The kind of the document.</summary>
public DocumentKind Kind { get; set; }
/// <summary>The number of the document, for the lists.</summary>
public string? DocumentNumber { get; set; }
/// <summary>The date of the document.</summary>
public DateOnly DocumentDate { get; set; }
/// <summary>The customer, or the supplier of a self-invoice.</summary>
public long? PartyId { get; set; }
/// <summary>The type of the format (Italy: TD01 …).</summary>
public string DocumentType { get; set; } = string.Empty;
/// <summary>The name of the file (Italy: <c>IT01234567890_00001.xml</c>).</summary>
public string FileName { get; set; } = string.Empty;
/// <summary>The progressive number of the file in the company.</summary>
public long Progressive { get; set; }
/// <summary>The format (Italy: FPR12, FPA12).</summary>
public string Format { get; set; } = string.Empty;
/// <summary>The recipient code.</summary>
public string? RecipientCode { get; set; }
/// <summary>The certified mailbox of the recipient.</summary>
public string? RecipientPec { get; set; }
/// <summary>The total of the document.</summary>
public decimal TotalAmount { get; set; }
/// <summary>The state.</summary>
public EInvoiceStatus Status { get; set; }
/// <summary>The channel it was sent through (<c>MANUAL</c> when sent from the portal of the AdE).</summary>
public string? ChannelCode { get; set; }
/// <summary>The identifier of the SDI.</summary>
public string? ExchangeId { get; set; }
/// <summary>The identifier at the channel.</summary>
public string? MessageId { get; set; }
/// <summary>When the file was written (UTC).</summary>
public DateTime GeneratedAt { get; set; }
/// <summary>When it was sent (UTC).</summary>
public DateTime? SentAt { get; set; }
/// <summary>When the last notification arrived (UTC).</summary>
public DateTime? LastNotificationAt { get; set; }
/// <summary>The last message: the error of the channel, or the description of the last notification.</summary>
public string? LastMessage { get; set; }
/// <summary>How many times sending failed.</summary>
public int SendAttempts { get; set; }
/// <summary>The file.</summary>
public byte[] Content { get; set; } = [];
/// <summary>Whether a newer file of the same document replaced it.</summary>
public bool Superseded { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>A notification of the SDI (<c>e_invoice_notifications</c>), kept as received.</summary>
public sealed class EInvoiceNotification : Entity<long>, IDemoMarkable
{
/// <summary>The e-invoice it is about, when found.</summary>
public long? EInvoiceId { get; set; }
/// <summary>The code (RC, NS, MC, NE, DT, AT, SE).</summary>
public string Code { get; set; } = string.Empty;
/// <summary>The name of the notification file.</summary>
public string FileName { get; set; } = string.Empty;
/// <summary>The name of the invoice file it is about.</summary>
public string? InvoiceFileName { get; set; }
/// <summary>The identifier of the SDI.</summary>
public string? ExchangeId { get; set; }
/// <summary>When it was received (UTC).</summary>
public DateTime ReceivedAt { get; set; }
/// <summary>The outcome of an NE (EC01, EC02).</summary>
public string? Outcome { get; set; }
/// <summary>The description.</summary>
public string? Description { get; set; }
/// <summary>The errors of a rejection, one per line: <c>code - description</c>.</summary>
public string? Errors { get; set; }
/// <summary>The channel it came from (<c>MANUAL</c> when uploaded).</summary>
public string? ChannelCode { get; set; }
/// <summary>The file.</summary>
public byte[] Content { get; set; } = [];
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>Where a received invoice is.</summary>
public enum InboxFileStatus
{
/// <summary>Received, to register.</summary>
New = 0,
/// <summary>Registered as a supplier invoice or credit note.</summary>
Registered = 1,
/// <summary>Set aside by the user (a duplicate, an invoice not for the company).</summary>
Discarded = 2,
/// <summary>The file could not be read.</summary>
Unreadable = 3,
}
/// <summary>
/// A supplier invoice received through a channel or uploaded (<c>e_invoice_inbox</c>, issue #79): the file with its
/// metadata, what it says, and the purchase document that registers it. The same file never enters twice (hash).
/// </summary>
public sealed class EInvoiceInboxFile : Entity<long>, IDemoMarkable
{
/// <summary>The name of the file.</summary>
public string FileName { get; set; } = string.Empty;
/// <summary>The SHA-256 of the file, in hexadecimal.</summary>
public string Hash { get; set; } = string.Empty;
/// <summary>The file.</summary>
public byte[] Content { get; set; } = [];
/// <summary>The name of the metadata file (MT).</summary>
public string? MetadataFileName { get; set; }
/// <summary>The metadata file.</summary>
public byte[]? Metadata { get; set; }
/// <summary>The identifier of the SDI.</summary>
public string? ExchangeId { get; set; }
/// <summary>When it was received (UTC).</summary>
public DateTime ReceivedAt { get; set; }
/// <summary>The channel (<c>MANUAL</c> when uploaded).</summary>
public string? ChannelCode { get; set; }
/// <summary>The VAT number of the supplier.</summary>
public string? SupplierVat { get; set; }
/// <summary>The name of the supplier.</summary>
public string? SupplierName { get; set; }
/// <summary>The type of the document (TD01 …).</summary>
public string? DocumentType { get; set; }
/// <summary>The number of the invoice.</summary>
public string? Number { get; set; }
/// <summary>The date of the invoice.</summary>
public DateOnly? DocumentDate { get; set; }
/// <summary>The total of the invoice.</summary>
public decimal? TotalAmount { get; set; }
/// <summary>The supplier in the archive, when found.</summary>
public long? PartyId { get; set; }
/// <summary>The state.</summary>
public InboxFileStatus Status { get; set; }
/// <summary>The purchase document that registers it.</summary>
public long? PurchaseDocumentId { get; set; }
/// <summary>Why it could not be read or registered.</summary>
public string? Error { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>
/// The settings of a channel in a company (<c>e_invoice_channels</c>, mockup 059). Passwords, keys and certificates are
/// stored protected (<c>ISecretProtector</c>, purpose <c>einvoice.channel</c>) and never shown again.
/// </summary>
public sealed class EInvoiceChannelSetting : Entity<long>, IDemoMarkable
{
/// <summary>The code of the channel.</summary>
public string Code { get; set; } = string.Empty;
/// <summary>Whether it is used.</summary>
public bool Enabled { get; set; }
/// <summary>Whether it is paused: no sending and no polling until resumed.</summary>
public bool Paused { get; set; }
/// <summary>The certified mailbox (PEC).</summary>
public string? Mailbox { get; set; }
/// <summary>The SMTP server.</summary>
public string? SmtpHost { get; set; }
/// <summary>The SMTP port.</summary>
public int SmtpPort { get; set; } = 465;
/// <summary>The IMAP server.</summary>
public string? ImapHost { get; set; }
/// <summary>The IMAP port.</summary>
public int ImapPort { get; set; } = 993;
/// <summary>Whether the connections use TLS.</summary>
public bool Tls { get; set; } = true;
/// <summary>The user.</summary>
public string? UserName { get; set; }
/// <summary>The password, protected.</summary>
public string? ProtectedPassword { get; set; }
/// <summary>The address of the SDI to write to (PEC), learned from its messages.</summary>
public string? ExchangeAddress { get; set; }
/// <summary>The folder of the mailbox for processed messages.</summary>
public string? ArchiveFolder { get; set; }
/// <summary>The address of the web service or API.</summary>
public string? Endpoint { get; set; }
/// <summary>The client certificate (PKCS#12, base64), protected.</summary>
public string? ProtectedCertificate { get; set; }
/// <summary>The password of the certificate, protected.</summary>
public string? ProtectedCertificatePassword { get; set; }
/// <summary>The API key, protected.</summary>
public string? ProtectedApiKey { get; set; }
/// <summary>Whether the test environment is used.</summary>
public bool TestEnvironment { get; set; }
/// <summary>When the connection was last tested (UTC).</summary>
public DateTime? LastCheckAt { get; set; }
/// <summary>Whether the last test worked.</summary>
public bool? LastCheckOk { get; set; }
/// <summary>What the last test said.</summary>
public string? LastCheckMessage { get; set; }
/// <summary>When the channel was last read (UTC).</summary>
public DateTime? LastPollAt { get; set; }
/// <summary>What the last reading found, or its error.</summary>
public string? LastPollMessage { get; set; }
/// <summary>Whether the last reading failed.</summary>
public bool LastPollFailed { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>When a routing rule applies.</summary>
public enum SdiRoutingCondition
{
/// <summary>Always (the last rule, usually).</summary>
Default = 0,
/// <summary>The customer is a public administration.</summary>
PublicAdministration = 1,
/// <summary>The customer has the code in <see cref="SdiRoutingRule.Value"/>.</summary>
Party = 2,
/// <summary>The type of the format is the one in <see cref="SdiRoutingRule.Value"/> (TD01, TD17 …).</summary>
DocumentType = 3,
/// <summary>The files sent today are at least the number in <see cref="SdiRoutingRule.Value"/>.</summary>
DailyVolume = 4,
}
/// <summary>A rule of the router (<c>e_invoice_routing</c>, issue #77): the first enabled rule that applies chooses the channel.</summary>
public sealed class SdiRoutingRule : Entity<long>, IDemoMarkable
{
/// <summary>The order (lower first).</summary>
public int Position { get; set; }
/// <summary>When it applies.</summary>
public SdiRoutingCondition Condition { get; set; }
/// <summary>The value of the condition.</summary>
public string? Value { get; set; }
/// <summary>The channel.</summary>
public string ChannelCode { get; set; } = string.Empty;
/// <summary>The channel used when the first is paused, disabled or fails.</summary>
public string? FallbackChannelCode { get; set; }
/// <summary>Whether the rule is ignored.</summary>
public bool Disabled { get; set; }
/// <inheritdoc />
public bool IsDemo { get; set; }
}
/// <summary>What the router knows of a file to send.</summary>
/// <param name="DocumentType">The type of the format.</param>
/// <param name="PartyCode">The code of the customer.</param>
/// <param name="PublicAdministration">Whether the customer is a public administration.</param>
/// <param name="SentToday">How many files were sent today.</param>
public sealed record SdiRoutingInput(string DocumentType, string? PartyCode, bool PublicAdministration, int SentToday);
/// <summary>The channels chosen for a file.</summary>
/// <param name="Channel">The channel to use.</param>
/// <param name="Fallback">The channel to try when the first fails.</param>
/// <param name="RuleId">The rule that chose them.</param>
public sealed record SdiRoute(string Channel, string? Fallback, long? RuleId);
/// <summary>
/// Chooses the channel of a file (SPEC §11.9, issue #77): the enabled rules in order, the first that applies wins; a
/// channel that is paused or disabled gives way to the fallback of the rule. Without rules, the first usable channel
/// in the order of the pack.
/// </summary>
public static class SdiRouter
{
/// <summary>Chooses.</summary>
/// <param name="input">The file.</param>
/// <param name="rules">The rules.</param>
/// <param name="usable">The codes of the channels enabled and not paused, in the order of the pack.</param>
/// <returns>The route, or <see langword="null"/> when no channel can take the file.</returns>
public static SdiRoute? Choose(SdiRoutingInput input, IEnumerable<SdiRoutingRule> rules, IReadOnlyList<string> usable)
{
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(rules);
ArgumentNullException.ThrowIfNull(usable);
bool Usable(string? code) => code is not null && usable.Contains(code, StringComparer.OrdinalIgnoreCase);
foreach (var rule in rules.Where(r => !r.Disabled).OrderBy(r => r.Position).ThenBy(r => r.Id))
{
if (!Applies(rule, input))
{
continue;
}
if (Usable(rule.ChannelCode))
{
return new SdiRoute(rule.ChannelCode, Usable(rule.FallbackChannelCode) ? rule.FallbackChannelCode : null, rule.Id);
}
if (Usable(rule.FallbackChannelCode))
{
return new SdiRoute(rule.FallbackChannelCode!, null, rule.Id);
}
}
return usable.Count == 0 ? null : new SdiRoute(usable[0], usable.Count > 1 ? usable[1] : null, null);
}
private static bool Applies(SdiRoutingRule rule, SdiRoutingInput input) => rule.Condition switch
{
SdiRoutingCondition.Default => true,
SdiRoutingCondition.PublicAdministration => input.PublicAdministration,
SdiRoutingCondition.Party => string.Equals(rule.Value?.Trim(), input.PartyCode, StringComparison.OrdinalIgnoreCase),
SdiRoutingCondition.DocumentType => string.Equals(rule.Value?.Trim(), input.DocumentType, StringComparison.OrdinalIgnoreCase),
SdiRoutingCondition.DailyVolume => int.TryParse(rule.Value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var limit)
&& input.SentToday >= limit,
_ => false,
};
}
/// <summary>A conservation package exported (<c>e_invoice_conservation</c>, issue #79): what went out, and its fingerprint.</summary>
public sealed class ConservationExport : Entity<long>
{
/// <summary>The first day.</summary>
public DateOnly FromDate { get; set; }
/// <summary>The last day.</summary>
public DateOnly ToDate { get; set; }
/// <summary>The files in the package.</summary>
public int FileCount { get; set; }
/// <summary>The name of the package.</summary>
public string FileName { get; set; } = string.Empty;
/// <summary>The SHA-256 of the package.</summary>
public string Hash { get; set; } = string.Empty;
/// <summary>The size in bytes.</summary>
public long Size { get; set; }
}
@@ -0,0 +1,106 @@
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.CompanyDatabase;
/// <summary>Map of <see cref="EInvoice"/> to <c>e_invoices</c>.</summary>
public sealed class EInvoiceMap : EntityMap<EInvoice>
{
/// <summary>Creates the map.</summary>
public EInvoiceMap()
{
ToTable("e_invoices");
Map(x => x.DocumentNumber).MaxLength(40);
Map(x => x.DocumentType).MaxLength(10);
Map(x => x.FileName).MaxLength(60);
Map(x => x.Format).MaxLength(10);
Map(x => x.RecipientCode).MaxLength(7);
Map(x => x.RecipientPec).MaxLength(254);
Map(x => x.ChannelCode).MaxLength(20);
Map(x => x.ExchangeId).MaxLength(40);
Map(x => x.MessageId).MaxLength(200);
Map(x => x.LastMessage).MaxLength(1000);
}
}
/// <summary>Map of <see cref="EInvoiceNotification"/> to <c>e_invoice_notifications</c>.</summary>
public sealed class EInvoiceNotificationMap : EntityMap<EInvoiceNotification>
{
/// <summary>Creates the map.</summary>
public EInvoiceNotificationMap()
{
ToTable("e_invoice_notifications");
Map(x => x.Code).MaxLength(4);
Map(x => x.FileName).MaxLength(100);
Map(x => x.InvoiceFileName).MaxLength(100);
Map(x => x.ExchangeId).MaxLength(40);
Map(x => x.Outcome).MaxLength(10);
Map(x => x.Description).MaxLength(1000);
Map(x => x.ChannelCode).MaxLength(20);
}
}
/// <summary>Map of <see cref="EInvoiceInboxFile"/> to <c>e_invoice_inbox</c>.</summary>
public sealed class EInvoiceInboxFileMap : EntityMap<EInvoiceInboxFile>
{
/// <summary>Creates the map.</summary>
public EInvoiceInboxFileMap()
{
ToTable("e_invoice_inbox");
Map(x => x.FileName).MaxLength(100);
Map(x => x.Hash).MaxLength(64);
Map(x => x.MetadataFileName).MaxLength(100);
Map(x => x.ExchangeId).MaxLength(40);
Map(x => x.ChannelCode).MaxLength(20);
Map(x => x.SupplierVat).MaxLength(30);
Map(x => x.SupplierName).MaxLength(200);
Map(x => x.DocumentType).MaxLength(10);
Map(x => x.Number).MaxLength(40);
Map(x => x.Error).MaxLength(500);
}
}
/// <summary>Map of <see cref="EInvoiceChannelSetting"/> to <c>e_invoice_channels</c>.</summary>
public sealed class EInvoiceChannelSettingMap : EntityMap<EInvoiceChannelSetting>
{
/// <summary>Creates the map.</summary>
public EInvoiceChannelSettingMap()
{
ToTable("e_invoice_channels");
Map(x => x.Code).MaxLength(20);
Map(x => x.Mailbox).MaxLength(254);
Map(x => x.SmtpHost).MaxLength(200);
Map(x => x.ImapHost).MaxLength(200);
Map(x => x.UserName).MaxLength(254);
Map(x => x.ExchangeAddress).MaxLength(254);
Map(x => x.ArchiveFolder).MaxLength(100);
Map(x => x.Endpoint).MaxLength(300);
Map(x => x.LastCheckMessage).MaxLength(1000);
Map(x => x.LastPollMessage).MaxLength(1000);
}
}
/// <summary>Map of <see cref="SdiRoutingRule"/> to <c>e_invoice_routing</c>.</summary>
public sealed class SdiRoutingRuleMap : EntityMap<SdiRoutingRule>
{
/// <summary>Creates the map.</summary>
public SdiRoutingRuleMap()
{
ToTable("e_invoice_routing");
Map(x => x.Value).MaxLength(40);
Map(x => x.ChannelCode).MaxLength(20);
Map(x => x.FallbackChannelCode).MaxLength(20);
}
}
/// <summary>Map of <see cref="ConservationExport"/> to <c>e_invoice_conservation</c>.</summary>
public sealed class ConservationExportMap : EntityMap<ConservationExport>
{
/// <summary>Creates the map.</summary>
public ConservationExportMap()
{
ToTable("e_invoice_conservation");
Map(x => x.FileName).MaxLength(100);
Map(x => x.Hash).MaxLength(64);
}
}
@@ -0,0 +1,159 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.CompanyDatabase.Migrations;
/// <summary>
/// The electronic invoice (SPEC §11.9, ADR 0039, issues #74-#79): the files sent with their state, the notifications
/// of the SDI, the invoices received, the channels with their protected settings, the rules of the router and the log
/// of the conservation packages.
/// </summary>
[Migration(20261113_004, "create_einvoicing")]
public sealed class M20261113_004_CreateEInvoicing : IMigration
{
/// <inheritdoc />
public void Up(ISchemaBuilder schema)
{
ArgumentNullException.ThrowIfNull(schema);
schema.CreateTable("e_invoices", t =>
{
t.Id();
t.String("family", 40).NotNull();
t.Int64("document_id").NotNull();
t.String("kind", 40).NotNull();
t.String("document_number", 40);
t.Date("document_date").NotNull();
t.Int64("party_id");
t.String("document_type", 10).NotNull();
t.String("file_name", 60).NotNull();
t.Int64("progressive").NotNull();
t.String("format", 10).NotNull();
t.String("recipient_code", 7);
t.String("recipient_pec", 254);
t.Decimal("total_amount").NotNull().Default(0m);
t.String("status", 40).NotNull();
t.String("channel_code", 20);
t.String("exchange_id", 40);
t.String("message_id", 200);
t.DateTimeUtc("generated_at").NotNull();
t.DateTimeUtc("sent_at");
t.DateTimeUtc("last_notification_at");
t.String("last_message", 1000);
t.Int32("send_attempts").NotNull().Default(0);
t.Bytes("content").NotNull();
t.Bool("superseded").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_e_invoices_file", "file_name");
t.Index("ix_e_invoices_document", "family", "document_id");
t.Index("ix_e_invoices_status", "superseded", "status");
t.Index("ix_e_invoices_exchange", "exchange_id");
});
schema.CreateTable("e_invoice_notifications", t =>
{
t.Id();
t.Int64("e_invoice_id");
t.String("code", 4).NotNull();
t.String("file_name", 100).NotNull();
t.String("invoice_file_name", 100);
t.String("exchange_id", 40);
t.DateTimeUtc("received_at").NotNull();
t.String("outcome", 10);
t.String("description", 1000);
t.Text("errors");
t.String("channel_code", 20);
t.Bytes("content").NotNull();
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_e_invoice_notifications_file", "file_name");
t.Index("ix_e_invoice_notifications_invoice", "e_invoice_id");
t.ForeignKey("fk_e_invoice_notifications_invoice", "e_invoice_id", "e_invoices", ReferentialAction.Cascade);
});
schema.CreateTable("e_invoice_inbox", t =>
{
t.Id();
t.String("file_name", 100).NotNull();
t.String("hash", 64).NotNull();
t.Bytes("content").NotNull();
t.String("metadata_file_name", 100);
t.Bytes("metadata");
t.String("exchange_id", 40);
t.DateTimeUtc("received_at").NotNull();
t.String("channel_code", 20);
t.String("supplier_vat", 30);
t.String("supplier_name", 200);
t.String("document_type", 10);
t.String("number", 40);
t.Date("document_date");
t.Decimal("total_amount");
t.Int64("party_id");
t.String("status", 40).NotNull();
t.Int64("purchase_document_id");
t.String("error", 500);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_e_invoice_inbox_hash", "hash");
t.Index("ix_e_invoice_inbox_status", "status", "received_at");
t.Index("ix_e_invoice_inbox_file", "file_name");
});
schema.CreateTable("e_invoice_channels", t =>
{
t.Id();
t.String("code", 20).NotNull();
t.Bool("enabled").NotNull().Default(false);
t.Bool("paused").NotNull().Default(false);
t.String("mailbox", 254);
t.String("smtp_host", 200);
t.Int32("smtp_port").NotNull().Default(465);
t.String("imap_host", 200);
t.Int32("imap_port").NotNull().Default(993);
t.Bool("tls").NotNull().Default(true);
t.String("user_name", 254);
t.Text("protected_password");
t.String("exchange_address", 254);
t.String("archive_folder", 100);
t.String("endpoint", 300);
t.Text("protected_certificate");
t.Text("protected_certificate_password");
t.Text("protected_api_key");
t.Bool("test_environment").NotNull().Default(false);
t.DateTimeUtc("last_check_at");
t.Bool("last_check_ok");
t.String("last_check_message", 1000);
t.DateTimeUtc("last_poll_at");
t.String("last_poll_message", 1000);
t.Bool("last_poll_failed").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
t.Unique("ux_e_invoice_channels_code", "code");
});
schema.CreateTable("e_invoice_routing", t =>
{
t.Id();
t.Int32("position").NotNull().Default(0);
t.String("condition", 40).NotNull();
t.String("value", 40);
t.String("channel_code", 20).NotNull();
t.String("fallback_channel_code", 20);
t.Bool("disabled").NotNull().Default(false);
t.DemoColumn();
t.AuditColumns();
});
schema.CreateTable("e_invoice_conservation", t =>
{
t.Id();
t.Date("from_date").NotNull();
t.Date("to_date").NotNull();
t.Int32("file_count").NotNull().Default(0);
t.String("file_name", 100).NotNull();
t.String("hash", 64).NotNull();
t.Int64("size").NotNull().Default(0L);
t.AuditColumns();
});
}
}
+45 -1
View File
@@ -418,6 +418,7 @@ public sealed class PdfWriter : IAsyncDisposable
private readonly List<long> _offsets = [0, -1, -1, -1];
private readonly List<int> _pageObjects = [];
private readonly Dictionary<PdfFont, int> _fontObjects = [];
private readonly List<(string Name, int Spec)> _attachments = [];
private long _flushed;
private int _images;
private PdfPage? _page;
@@ -483,6 +484,45 @@ public sealed class PdfWriter : IAsyncDisposable
return new PdfImage(number, "Im" + _images.ToString(CultureInfo.InvariantCulture), info);
}
/// <summary>
/// Embeds a file in the document, as PDF/A-3 does for the XML of an e-invoice: an embedded file stream, its file
/// specification with the relationship to the document (<c>/AFRelationship</c>), listed in the names of the catalogue
/// and in its associated files (<c>/AF</c>). Readers show it among the attachments.
/// </summary>
/// <remarks>This gives the structure of PDF/A-3 for attachments; the document still uses the standard fonts without
/// embedding them, so it does not claim PDF/A conformance.</remarks>
/// <param name="fileName">The name of the file.</param>
/// <param name="mediaType">The media type, such as <c>application/xml</c>.</param>
/// <param name="content">The file.</param>
/// <param name="description">What it is.</param>
/// <param name="relationship">The relationship: <c>Source</c>, <c>Data</c>, <c>Alternative</c>, <c>Supplement</c> or <c>Unspecified</c>.</param>
public void AddAttachment(string fileName, string mediaType, ReadOnlySpan<byte> content, string? description = null, string relationship = "Alternative")
{
ObjectDisposedException.ThrowIf(_closed, this);
ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
ArgumentException.ThrowIfNullOrWhiteSpace(mediaType);
if (relationship is not ("Source" or "Data" or "Alternative" or "Supplement" or "Unspecified"))
{
throw new ArgumentOutOfRangeException(nameof(relationship), relationship, "Not a relationship of PDF/A-3.");
}
var created = PdfDate(_info.CreationDate ?? DateTimeOffset.UtcNow);
var length = content.Length.ToString(CultureInfo.InvariantCulture);
var stream = Allocate();
BeginObject(stream);
Ascii("<< /Type /EmbeddedFile /Subtype /" + mediaType.Trim().Replace("/", "#2F", StringComparison.Ordinal) + " /Length " + length
+ " /Params << /Size " + length + " /ModDate (" + created + ") >> >>\nstream\n");
_buffer.Write(content);
Ascii("\nendstream\nendobj\n");
var spec = Allocate();
BeginObject(spec);
Ascii("<< /Type /Filespec /F " + TextString(fileName) + " /UF " + TextString(fileName)
+ (string.IsNullOrWhiteSpace(description) ? string.Empty : " /Desc " + TextString(description))
+ " /AFRelationship /" + relationship + " /EF << /F " + Ref(stream) + " /UF " + Ref(stream) + " >> >>\nendobj\n");
_attachments.Add((fileName, spec));
}
/// <summary>Writes what is buffered to the output.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
@@ -527,7 +567,11 @@ public sealed class PdfWriter : IAsyncDisposable
Ascii("<< /Type /Pages /Kids [" + string.Join(' ', _pageObjects.Select(p => Ref(p))) + "] /Count "
+ _pageObjects.Count.ToString(CultureInfo.InvariantCulture) + " >>\nendobj\n");
BeginObject(CatalogObject);
Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + " >>\nendobj\n");
var attachments = _attachments.Count == 0
? string.Empty
: " /Names << /EmbeddedFiles << /Names [" + string.Join(' ', _attachments.OrderBy(a => a.Name, StringComparer.Ordinal).Select(a => TextString(a.Name) + " " + Ref(a.Spec)))
+ "] >> >> /AF [" + string.Join(' ', _attachments.Select(a => Ref(a.Spec))) + "] /PageMode /UseAttachments";
Ascii("<< /Type /Catalog /Pages " + Ref(PagesObject) + attachments + " >>\nendobj\n");
BeginObject(InfoObject);
Ascii("<< " + InfoEntries() + ">>\nendobj\n");
+11 -1
View File
@@ -174,6 +174,14 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Treasury.CashFlowService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.Treasury.DunningJob>();
// Electronic invoice (SPEC §11.9, M9): files, channels to the SDI, inbox, conservation.
services.AddSingleton<Khaemhat.Application.EInvoicing.EInvoiceService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.EInvoiceChannelService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.SdiInboxService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.EInvoicePollingService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.ConservationExportService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.EInvoicing.EInvoicePollingJob>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family.
services.AddSingleton<Khaemhat.Application.Documents.DocumentEngine>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentCopyService>();
@@ -247,6 +255,7 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.Treasury.TreasuryFeedSource>();
services.AddSingleton<ITodoSource>(sp => sp.GetRequiredService<Khaemhat.Application.Treasury.TreasuryFeedSource>());
services.AddSingleton<IDeadlineSource>(sp => sp.GetRequiredService<Khaemhat.Application.Treasury.TreasuryFeedSource>());
services.AddSingleton<ITodoSource, Khaemhat.Application.EInvoicing.EInvoiceFeedSource>();
services.AddSingleton<SystemStatusService>();
services.AddSingleton<TodoAggregator>();
services.AddSingleton<DoneAggregator>();
@@ -265,7 +274,8 @@ internal static class KhaemhatServices
services.AddSingleton<IFileStore, VolumeFileStore>();
services.AddSingleton<AttachmentService>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentPrintService>();
services.AddSingleton<IFileGenerator, Khaemhat.Application.Documents.DocumentPdfGenerator>();
services.AddSingleton<Khaemhat.Application.Documents.DocumentPdfGenerator>();
services.AddSingleton<IFileGenerator>(sp => sp.GetRequiredService<Khaemhat.Application.Documents.DocumentPdfGenerator>());
// Mail (#52): the SMTP client written in house, the queue that sends in the background, documents by e-mail.
services.AddSingleton(new Khaemhat.Infrastructure.Mail.SmtpSettings(
@@ -51,7 +51,8 @@
"Areas": {
"System": "Sistema",
"Notifications": "Avvisi",
"Treasury": "Tesoreria"
"Treasury": "Tesoreria",
"EInvoicing": "Fatturazione elettronica"
},
"Coming": {
"Text": "Questo widget si riempie con i dati di {0}, in arrivo con la milestone {1}. Intanto puoi già metterlo dove ti serve.",
@@ -75,7 +76,10 @@
"JobFailed": "Attività «{0}» non riuscita",
"DueReceivable": "Incasso da {0}: {1}",
"DuePayable": "Pagamento a {0}: {1}",
"Overdue": "{0} partite di clienti scadute da incassare ({1})"
"Overdue": "{0} partite di clienti scadute da incassare ({1})",
"EInvoiceRejected": "{0} fatture elettroniche scartate o rifiutate da correggere",
"EInvoiceToSend": "{0} fatture elettroniche da generare o inviare allo SDI",
"EInvoiceReceived": "{0} fatture ricevute dallo SDI da registrare"
},
"Widgets": {
"Kpi": {
@@ -64,7 +64,7 @@ public sealed class DocumentRulesTests
Assert.AreEqual(DocumentStatus.SdiDelivered, status);
CollectionAssert.AreEqual(new[] { DocumentAction.Copy }, DocumentStateMachine.Actions(Invoice, DocumentStatus.SdiDelivered).ToArray());
foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s != DocumentStatus.Draft))
foreach (var issued in DocumentStateMachine.States(Invoice).Where(s => s is not (DocumentStatus.Draft or DocumentStatus.SdiRejected)))
{
Assert.IsFalse(DocumentStateMachine.IsEditable(Invoice, issued), issued.ToString());
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, issued, DocumentAction.Delete), issued.ToString());
@@ -72,6 +72,8 @@ public sealed class DocumentRulesTests
Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiGenerated, DocumentAction.Cancel));
Assert.IsTrue(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Cancel));
Assert.IsTrue(DocumentStateMachine.IsEditable(Invoice, DocumentStatus.SdiRejected), "A rejected invoice is corrected and sent again.");
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiRejected, DocumentAction.Delete));
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.SdiSent, DocumentAction.Cancel));
Assert.IsFalse(DocumentStateMachine.Allows(Invoice, DocumentStatus.Draft, DocumentAction.Confirm), "Invoices are issued, not confirmed.");
Assert.AreEqual(DocumentStatus.SdiGenerated, DocumentStateMachine.Apply(Invoice, DocumentStatus.SdiRejected, DocumentAction.GenerateXml));
@@ -86,6 +86,7 @@ public sealed class MappingTests
"gl_open_items", "gl_recurring_entries", "vat_settlements", "vat_settlement_lines", "tax_payments", "withholdings", "vat_register_prints",
"payments", "payment_lines", "remittances", "remittance_lines", "sdd_mandates", "bank_statements", "bank_statement_lines",
"bank_match_rules", "dunning_levels", "dunning_letters",
"e_invoices", "e_invoice_notifications", "e_invoice_inbox", "e_invoice_channels", "e_invoice_routing", "e_invoice_conservation",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}