diff --git a/docs/DATA-MODEL.md b/docs/DATA-MODEL.md index b87cc6b..c53aef5 100644 --- a/docs/DATA-MODEL.md +++ b/docs/DATA-MODEL.md @@ -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 | diff --git a/src/Khaemhat.Application/Audit/AuditTrail.cs b/src/Khaemhat.Application/Audit/AuditTrail.cs index dd024d8..16bd38e 100644 --- a/src/Khaemhat.Application/Audit/AuditTrail.cs +++ b/src/Khaemhat.Application/Audit/AuditTrail.cs @@ -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", }; /// Writes the history row of a change, inside the caller's unit of work. diff --git a/src/Khaemhat.Application/Documents/DocumentEngine.cs b/src/Khaemhat.Application/Documents/DocumentEngine.cs index 97c8cc2..4acf027 100644 --- a/src/Khaemhat.Application/Documents/DocumentEngine.cs +++ b/src/Khaemhat.Application/Documents/DocumentEngine.cs @@ -451,6 +451,48 @@ public sealed partial class DocumentEngine }, null, cancellationToken); } + /// + /// 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. + /// + /// The open unit of work. + /// The family. + /// The document. + /// The steps, in order, from the state the document is in. + /// Who, for the history. + /// Cancellation. + /// The state reached, or when the document does not exist. + internal async Task AdvanceExchangeAsync( + IUnitOfWork uow, DocumentFamily family, long id, Func> 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; + } + /// Records that the document was printed (its PDF kept among the attachments); the state does not change. /// Who prints: needs to read the document. /// The company. diff --git a/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs index b9bf3b8..6f0b0e4 100644 --- a/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs +++ b/src/Khaemhat.Application/Documents/DocumentPdfGenerator.cs @@ -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); + } + + /// + /// 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, /AF). + /// + /// The document. + /// The name of the XML file. + /// The XML file. + /// The stream that receives the PDF. + /// Cancellation. + /// A task. + 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); } diff --git a/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs b/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs new file mode 100644 index 0000000..e8a7f3c --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs @@ -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; + +/// A conservation package made. +/// The row that records it. +/// The ZIP. +public sealed record ConservationPackage(ConservationExport Export, byte[] Content); + +/// +/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent +/// (emesse/), their notifications (notifiche/) and the files received (ricevute/), each as it +/// travelled, an index indice.csv with the SHA-256 of every file and a LEGGIMI.txt. It is what a +/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself. +/// +/// Permission: einvoice.document.read. Every package made is recorded with its hash. +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; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The clock. + public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _clock = clock; + } + + /// The packages made, newest first. + /// Who looks: needs einvoice.document.read. + /// The company. + /// Cancellation. + /// The rows. + public async Task> 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().ListAsync(Query.For().OrderByDescending(e => e.Id).Take(50), cancellationToken) + .ConfigureAwait(false)).Items; + } + + /// Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival. + /// Who makes it: needs einvoice.document.read. + /// The company. + /// First day. + /// Last day. + /// Cancellation. + /// The package. + public async Task 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() + .ListAsync(Query.For().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken) + .ConfigureAwait(false)).Items; + var notifications = new List(); + foreach (var chunk in sent.Select(e => e.Id).Chunk(500)) + { + var ids = chunk.ToList(); + notifications.AddRange((await uow.Repository() + .ListAsync(Query.For().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() + .ListAsync(Query.For().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(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().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 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. + """); +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs new file mode 100644 index 0000000..539ef4d --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs @@ -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; + +/// +/// 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. +/// +/// +/// Amounts follow the document as computed by Khaemhat: a footer discount becomes one discount line (SC) +/// per rate, prices that include tax are taken back to their taxable amount, what is left by rounding goes in +/// Arrotondamento of the summary. A stamp duty charged to the customer is a line excluded from VAT (N1). +/// The file name is not set here: the service gives it with the progressive. +/// +internal static class EInvoiceBuilder +{ + /// The country code of foreign customers without a VAT number (FatturaPA: eleven nines). + public const string NoVatNumber = "99999999999"; + + /// The recipient code of a foreign customer. + public const string ForeignRecipient = "XXXXXXX"; + + /// The recipient code when the file goes to a certified mailbox or to the tax drawer. + public const string NoRecipient = "0000000"; + + /// The type of the format of a document: the one of its document type, otherwise the default of its kind. + /// The kind. + /// The document type. + /// The type (TD01 …), or when the kind has no e-invoice. + 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, + }; + } + + /// Whether a kind of document goes to the exchange system. + /// The kind. + /// for invoices, credit and debit notes, fees and self-invoices. + public static bool IsElectronic(DocumentKind kind) => DocumentBehaviors.Of(kind).Effects.HasFlag(DocumentEffects.EInvoice); + + /// Builds the file of a document. + /// The unit of work of the company. + /// The document, with lines and figures. + /// Cancellation. + /// The model (file name empty), the party and whether it is a public administration. + 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().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException([":" + EInvoiceErrors.CompanyProfileMissing]); + var party = header.PartyId is { } partyId ? await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null; + if (party is null) + { + throw new ValidationFailedException(["PartyId:" + DocumentErrors.PartyRequired]); + } + + var fiscal = await uow.Repository().FindAsync(Query.For().Where(f => f.PartyId == party.Id), cancellationToken).ConfigureAwait(false); + var type = await uow.Repository().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); + } + + /// The company as it appears in the file. + /// The profile. + /// The party. + 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 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().Distinct().ToList(); + var taxCodes = (await uow.Repository().ListAsync(Query.For().Where(t => taxIds.Contains(t.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(t => t.Id); + var unitIds = record.Lines.Select(l => l.UnitOfMeasureId).OfType().Distinct().ToList(); + var units = (await uow.Repository().ListAsync(Query.For().Where(u => unitIds.Contains(u.Id)), cancellationToken).ConfigureAwait(false)) + .Items.ToDictionary(u => u.Id); + var itemIds = record.Lines.Select(l => l.ItemId).OfType().Distinct().ToList(); + var items = itemIds.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().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(); + var sourceLines = new Dictionary(); + 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(); + 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 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 Orders, List Related, List Deliveries)> ReferencesAsync( + IUnitOfWork uow, DocumentRecord record, Dictionary sourceLines, CancellationToken cancellationToken) + { + var header = record.Header; + var orders = new List(); + 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(); + 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 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> 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().Distinct().ToList(); + var methods = methodIds.Count == 0 + ? [] + : (await uow.Repository().ListAsync(Query.For().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().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(); + 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 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().GetAsync(carrierId, cancellationToken).ConfigureAwait(false) : null; + var reason = header.TransportReasonId is { } reasonId ? await uow.Repository().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; + } +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.cs new file mode 100644 index 0000000..13a02c4 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceChannelService.cs @@ -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; + +/// A channel as the configuration page shows it: secrets never leave the service, only whether they are set. +/// The code of the channel. +/// Its name. +/// Whether Khaemhat reads it on a schedule (PEC, intermediaries) or receives a push (SdICoop). +/// The settings, secrets removed (a new row when never saved). +/// Whether a password is stored. +/// Whether a client certificate is stored. +/// Whether an API key is stored. +public sealed record EInvoiceChannelView(string Code, string Name, bool Polls, EInvoiceChannelSetting Setting, bool HasPassword, bool HasCertificate, bool HasApiKey); + +/// +/// What the user saves for a channel. Secrets: keeps the stored one, an empty value removes it. +/// +public sealed record EInvoiceChannelInput +{ + /// The code of the channel. + public required string Code { get; init; } + + /// Whether the channel is used. + public bool Enabled { get; init; } + + /// The certified mailbox. + public string? Mailbox { get; init; } + + /// The SMTP server. + public string? SmtpHost { get; init; } + + /// The SMTP port. + public int SmtpPort { get; init; } = 465; + + /// The IMAP server. + public string? ImapHost { get; init; } + + /// The IMAP port. + public int ImapPort { get; init; } = 993; + + /// Whether TLS is used. + public bool Tls { get; init; } = true; + + /// The user. + public string? UserName { get; init; } + + /// The password: keeps it, empty removes it. + public string? Password { get; init; } + + /// The address of the SDI to write to. + public string? ExchangeAddress { get; init; } + + /// The folder the processed messages go to. + public string? ArchiveFolder { get; init; } + + /// The address of the web service or of the API. + public string? Endpoint { get; init; } + + /// The client certificate (PKCS#12): keeps it, empty removes it. + public byte[]? Certificate { get; init; } + + /// The password of the certificate: keeps it, empty removes it. + public string? CertificatePassword { get; init; } + + /// The API key: keeps it, empty removes it. + public string? ApiKey { get; init; } + + /// Whether the test environment is used. + public bool TestEnvironment { get; init; } +} + +/// +/// The channels to the SDI and the routing of the files (mockup 059, issues #76-#77): the PEC mailbox, the SdICoop web +/// service, the intermediaries; each can be tried, paused and resumed. Secrets are kept protected (SPEC §8.5) and never +/// shown again. The routing rules choose the channel of each file, with a fallback. +/// +/// Permission: einvoice.channel.manage. +public sealed class EInvoiceChannelService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly ISecretProtector _secrets; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// Protects the secrets. + /// The history of the changes. + /// The clock. + public EInvoiceChannelService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, ISecretProtector secrets, AuditTrail audit, TimeProvider clock) + { + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(permissions); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(secrets); + ArgumentNullException.ThrowIfNull(audit); + ArgumentNullException.ThrowIfNull(clock); + _factory = factory; + _permissions = permissions; + _packs = packs; + _secrets = secrets; + _audit = audit; + _clock = clock; + } + + /// The channels of the pack with their settings. + /// Who looks: needs einvoice.channel.manage. + /// The company. + /// Cancellation. + /// The channels, in the order of the pack. + public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var rows = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items + .ToDictionary(r => r.Code, StringComparer.OrdinalIgnoreCase); + return [.. channels.All.Select(c => View(c, rows.GetValueOrDefault(c.Code) ?? new EInvoiceChannelSetting { Code = c.Code }))]; + } + + /// Saves the settings of a channel. + /// Who saves: needs einvoice.channel.manage. + /// The company. + /// The settings. + /// Cancellation. + /// The channel. + public async Task SaveAsync(Actor actor, string companyCode, EInvoiceChannelInput input, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(input); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(input.Code) + ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + Validate(input); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var code = channel.Code; + var row = await repository.FindAsync(Query.For().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false); + var before = row is null ? null : Copy(row); + row ??= new EInvoiceChannelSetting { Code = code }; + row.Enabled = input.Enabled; + row.Mailbox = EInvoiceStore.Trim(input.Mailbox, 200); + row.SmtpHost = EInvoiceStore.Trim(input.SmtpHost, 200); + row.SmtpPort = input.SmtpPort; + row.ImapHost = EInvoiceStore.Trim(input.ImapHost, 200); + row.ImapPort = input.ImapPort; + row.Tls = input.Tls; + row.UserName = EInvoiceStore.Trim(input.UserName, 200); + row.ExchangeAddress = EInvoiceStore.Trim(input.ExchangeAddress, 200); + row.ArchiveFolder = EInvoiceStore.Trim(input.ArchiveFolder, 200); + row.Endpoint = EInvoiceStore.Trim(input.Endpoint, 500); + row.TestEnvironment = input.TestEnvironment; + row.ProtectedPassword = Secret(input.Password, row.ProtectedPassword); + row.ProtectedCertificate = input.Certificate is null + ? row.ProtectedCertificate + : input.Certificate.Length == 0 ? null : _secrets.Protect(Convert.ToBase64String(input.Certificate), EInvoiceStore.SecretPurpose); + row.ProtectedCertificatePassword = Secret(input.CertificatePassword, row.ProtectedCertificatePassword); + row.ProtectedApiKey = Secret(input.ApiKey, row.ProtectedApiKey); + if (before is null) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return View(channel, row); + } + + /// Pauses or resumes a channel: a paused channel neither sends nor is read. + /// Who does it: needs einvoice.channel.manage. + /// The company. + /// The channel. + /// Whether to pause. + /// Cancellation. + /// A task. + public async Task PauseAsync(Actor actor, string companyCode, string code, bool paused, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = await repository.FindAsync(Query.For().Where(c => c.Code == code), cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + var before = Copy(row); + row.Paused = paused; + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Tries a channel with its saved settings (login to the mailbox, the service or the API) and keeps the outcome. + /// Who tries: needs einvoice.channel.manage. + /// The company. + /// The channel. + /// Cancellation. + /// The outcome. + public async Task CheckAsync(Actor actor, string companyCode, string code, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channel = (await ChannelsAsync(company, cancellationToken).ConfigureAwait(false)).Find(code) + ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + EInvoiceChannelSetting row; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + row = await uow.Repository().FindAsync(Query.For().Where(c => c.Code == channel.Code), cancellationToken) + .ConfigureAwait(false) ?? throw new ValidationFailedException(["Code:" + EInvoiceErrors.ChannelUnknown]); + } + + EInvoiceChannelCheck check; + try + { + check = await channel.Transport.CheckAsync(EInvoiceStore.Settings(row, _secrets), cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + check = new EInvoiceChannelCheck(false, ex.Message); + } + + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var current = await uow.Repository().GetAsync(row.Id, cancellationToken).ConfigureAwait(false)!; + if (current is not null) + { + current.LastCheckAt = _clock.GetUtcNow().UtcDateTime; + current.LastCheckOk = check.Success; + current.LastCheckMessage = EInvoiceStore.Trim(check.Message, 1000); + await uow.Repository().UpdateAsync(current, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + return check; + } + + /// The routing rules, in order. + /// Who looks: needs einvoice.channel.manage. + /// The company. + /// Cancellation. + /// The rules. + public async Task> RulesAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default) + { + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + return (await uow.Repository().ListAsync(Query.For().OrderBy(r => r.Position), cancellationToken).ConfigureAwait(false)).Items; + } + + /// Adds or changes a routing rule. + /// Who saves: needs einvoice.channel.manage. + /// The company. + /// The rule (identifier 0 to add). + /// Cancellation. + /// The rule. + public async Task SaveRuleAsync(Actor actor, string companyCode, SdiRoutingRule rule, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + ArgumentNullException.ThrowIfNull(rule); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + var channels = await ChannelsAsync(company, cancellationToken).ConfigureAwait(false); + var errors = new List(); + if (channels.Find(rule.ChannelCode) is null) + { + errors.Add(nameof(SdiRoutingRule.ChannelCode) + ":" + EInvoiceErrors.ChannelUnknown); + } + + if (!string.IsNullOrWhiteSpace(rule.FallbackChannelCode) && (channels.Find(rule.FallbackChannelCode) is null + || string.Equals(rule.FallbackChannelCode, rule.ChannelCode, StringComparison.OrdinalIgnoreCase))) + { + errors.Add(nameof(SdiRoutingRule.FallbackChannelCode) + ":" + EInvoiceErrors.ChannelUnknown); + } + + var value = rule.Value?.Trim(); + var valueOk = rule.Condition switch + { + SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType => !string.IsNullOrEmpty(value), + SdiRoutingCondition.DailyVolume => int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var limit) && limit > 0, + _ => true, + }; + if (!valueOk) + { + errors.Add(nameof(SdiRoutingRule.Value) + ":" + EInvoiceErrors.RuleValueInvalid); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = rule.Id == 0 ? new SdiRoutingRule() : await repository.GetAsync(rule.Id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + var before = rule.Id == 0 ? null : CopyRule(row); + if (rule.Id == 0 && rule.Position <= 0) + { + var last = await repository.FindAsync(Query.For().OrderByDescending(r => r.Position), cancellationToken).ConfigureAwait(false); + row.Position = (last?.Position ?? 0) + 10; + } + else + { + row.Position = rule.Position; + } + + row.Condition = rule.Condition; + row.Value = rule.Condition is SdiRoutingCondition.Default or SdiRoutingCondition.PublicAdministration ? null : value!.ToUpperInvariant(); + row.ChannelCode = rule.ChannelCode.Trim().ToUpperInvariant(); + row.FallbackChannelCode = string.IsNullOrWhiteSpace(rule.FallbackChannelCode) ? null : rule.FallbackChannelCode.Trim().ToUpperInvariant(); + row.Disabled = rule.Disabled; + if (before is null) + { + row.Id = await repository.InsertAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Insert, row.Id, null, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + else + { + await repository.UpdateAsync(row, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Update, row.Id, before, row, actor.UserName, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return row; + } + + /// Removes a routing rule. + /// Who removes: needs einvoice.channel.manage. + /// The company. + /// The rule. + /// Cancellation. + /// A task. + public async Task DeleteRuleAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(actor); + var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.ChannelManage, cancellationToken).ConfigureAwait(false); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var repository = uow.Repository(); + var row = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + await repository.DeleteAsync(row.Id, cancellationToken).ConfigureAwait(false); + await _audit.RecordAsync(uow, AuditAction.Delete, row.Id, row, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + private async Task ChannelsAsync(string company, CancellationToken cancellationToken) => + (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature() + ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]); + + private string? Secret(string? input, string? stored) => + input is null ? stored : input.Length == 0 ? null : _secrets.Protect(input, EInvoiceStore.SecretPurpose); + + private static void Validate(EInvoiceChannelInput input) + { + var errors = new List(); + if (input.SmtpPort is < 1 or > 65535) + { + errors.Add(nameof(input.SmtpPort) + ":" + EInvoiceErrors.PortInvalid); + } + + if (input.ImapPort is < 1 or > 65535) + { + errors.Add(nameof(input.ImapPort) + ":" + EInvoiceErrors.PortInvalid); + } + + if (!string.IsNullOrWhiteSpace(input.Mailbox) && !MailAddress.TryCreate(input.Mailbox.Trim(), out _)) + { + errors.Add(nameof(input.Mailbox) + ":" + EInvoiceErrors.MailboxInvalid); + } + + if (!string.IsNullOrWhiteSpace(input.ExchangeAddress) && !MailAddress.TryCreate(input.ExchangeAddress.Trim(), out _)) + { + errors.Add(nameof(input.ExchangeAddress) + ":" + EInvoiceErrors.MailboxInvalid); + } + + if (!string.IsNullOrWhiteSpace(input.Endpoint) && !IsServiceAddress(input.Endpoint.Trim())) + { + errors.Add(nameof(input.Endpoint) + ":" + EInvoiceErrors.EndpointInvalid); + } + + if (errors.Count > 0) + { + throw new ValidationFailedException(errors); + } + } + + // https, or http only to this machine (a test service). + private static bool IsServiceAddress(string value) => + Uri.TryCreate(value, UriKind.Absolute, out var uri) + && (uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback)); + + private static EInvoiceChannelView View(EInvoiceChannel channel, EInvoiceChannelSetting row) + { + var shown = Copy(row); + shown.ProtectedPassword = null; + shown.ProtectedCertificate = null; + shown.ProtectedCertificatePassword = null; + shown.ProtectedApiKey = null; + return new EInvoiceChannelView(channel.Code, channel.Name, channel.Transport.Polls, shown, + !string.IsNullOrEmpty(row.ProtectedPassword), !string.IsNullOrEmpty(row.ProtectedCertificate), !string.IsNullOrEmpty(row.ProtectedApiKey)); + } + + private static EInvoiceChannelSetting Copy(EInvoiceChannelSetting row) => EInvoiceStore.Clone(row); + + private static SdiRoutingRule CopyRule(SdiRoutingRule row) => EInvoiceStore.Clone(row); +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceFeedSource.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceFeedSource.cs new file mode 100644 index 0000000..e422972 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceFeedSource.cs @@ -0,0 +1,60 @@ +using Khaemhat.Application.Dashboard; +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; + +namespace Khaemhat.Application.EInvoicing; + +/// +/// 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. +/// +/// The e-invoices. +/// The permissions, licence included. +/// The texts. +public sealed class EInvoiceFeedSource(EInvoiceService invoices, PermissionService permissions, ITexts texts) : ITodoSource +{ + /// The text key of the area. + public const string Area = "Dashboard.Areas.EInvoicing"; + + /// + public async Task> 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(); + 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; + } +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoicePollingService.cs b/src/Khaemhat.Application/EInvoicing/EInvoicePollingService.cs new file mode 100644 index 0000000..64dcce1 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoicePollingService.cs @@ -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; + +/// What reading one channel brought. +/// The channel. +/// Messages read. +/// Invoices received and stored. +/// Notifications applied. +/// Files already known. +/// Why the channel could not be read. +public sealed record EInvoicePollOutcome(string Channel, int Messages, int Invoices, int Receipts, int Skipped, string? Error); + +/// +/// 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. +/// +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 _logger; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The e-invoices (notifications). + /// Opens the secrets of the channels. + /// The clock. + /// The log (section SDI). + public EInvoicePollingService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, EInvoiceService invoices, ISecretProtector secrets, TimeProvider clock, + ILogger 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; + } + + /// Reads the channels of the company now (the button Leggi ora). + /// Who asks: needs einvoice.channel.manage. + /// The company. + /// Cancellation. + /// What each channel brought. + public async Task> 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); + } + + /// Reads every enabled, not paused channel of a company that is read on a schedule. + /// The company. + /// Cancellation. + /// What each channel brought. + public async Task> PollCompanyAsync(string company, CancellationToken cancellationToken = default) + { + var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } channels) + { + return []; + } + + List rows; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false)) + { + rows = [.. (await uow.Repository().ListAsync(Query.For().Where(c => c.Enabled && !c.Paused), cancellationToken) + .ConfigureAwait(false)).Items]; + } + + var result = new List(); + 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; + } + + /// Takes the files a channel pushed (SdICoop: RiceviFatture, RiceviNotifica) for a company. + /// The company the endpoint belongs to. + /// The channel. + /// The files. + /// Cancellation. + /// What the files brought. + public async Task ReceivePushedAsync(string company, string channel, IReadOnlyList 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 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().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().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 Done)> ProcessAsync( + string company, IFiscalPack pack, string channel, IReadOnlyList files, CancellationToken cancellationToken) + { + var reader = pack.GetFeature(); + var receiptReader = pack.GetFeature(); + 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(); + 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); +} + +/// Reads the channels of the SDI of every company (job einvoice.poll, every 15 minutes). +/// The companies. +/// The reading of the channels. +/// The licence. +public sealed class EInvoicePollingJob(ICompanyRegistry companies, EInvoicePollingService service, ILicenseGate license) : IScheduledJob +{ + /// The job type. + public const string JobType = "einvoice.poll"; + + /// + public string Type => JobType; + + /// + public async Task 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."); + } +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs new file mode 100644 index 0000000..bed773c --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs @@ -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; + +/// +/// 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. +/// +/// +/// Permissions: einvoice.document.read to see, einvoice.document.send 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. +/// +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 _logger; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The document engine. + /// Opens the secrets of the channels. + /// The print of the documents (courtesy copy). + /// The clock. + /// The log (section SDI). + public EInvoiceService( + IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, DocumentEngine engine, ISecretProtector secrets, + DocumentPdfGenerator pdf, TimeProvider clock, ILogger 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; + } + + /// The dashboard: the e-invoices of the view, the documents to generate, the counters. + /// Who looks: needs einvoice.document.read. + /// The company. + /// The filter. + /// Cancellation. + /// The dashboard. + public async Task 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().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().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().CountAsync(Query.For().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 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(), 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); + } + + /// The e-invoices of a document with their notifications, newest first (the page of the document). + /// Who looks. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The files and their notifications. + public async Task 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() + .ListAsync(Query.For().Where(e => e.Family == family && e.DocumentId == documentId).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false)).Items; + var result = new List<(EInvoice, IReadOnlyList)>(); + foreach (var invoice in invoices) + { + var id = invoice.Id; + var notifications = (await uow.Repository() + .ListAsync(Query.For().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; + } + + /// Checks the file a document would have, without writing it. + /// Who checks: needs einvoice.document.read. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The problems, empty when the file can be sent. + public async Task> 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; + } + + /// + /// 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 XML generato. 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. + /// + /// Who generates: needs einvoice.document.send. + /// The company. + /// The family. + /// The document. + /// Cancellation. + /// The e-invoice, or the errors. + public async Task 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; + } + + /// Generates the files of several documents and sends them (the button Genera e invia). + /// Who sends. + /// The company. + /// The documents. + /// Cancellation. + /// For each document, the generation and the sending. + public async Task> 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; + } + + /// + /// 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 Inviato with its document; one no channel took keeps its + /// state and the error. + /// + /// Who sends: needs einvoice.document.send. + /// The company. + /// The e-invoices. + /// Cancellation. + /// What happened to each. + public async Task> SendAsync(Actor actor, string companyCode, IReadOnlyList 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(); + var result = new List(); + foreach (var id in ids.Distinct()) + { + result.Add(await SendOneAsync(company, channels, id, actor.UserName, cancellationToken).ConfigureAwait(false)); + } + + return result; + } + + /// Records that a generated file was sent outside Khaemhat (portal of the AdE, another program). + /// Who records it: needs einvoice.document.send. + /// The company. + /// The e-invoice. + /// The identifier of the SDI, when known. + /// Cancellation. + /// The e-invoice. + public async Task 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().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); + } + + /// Imports notifications downloaded from the portal of the AdE or from another program. + /// Who imports: needs einvoice.document.send. + /// The company. + /// The files. + /// Cancellation. + /// What happened to each. + public async Task> 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() + ?? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]); + var result = new List(); + 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; + } + + /// The file of an e-invoice, as sent. + /// Who downloads: needs einvoice.document.read. + /// The company. + /// The e-invoice. + /// Cancellation. + /// Name and content. + 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().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + return (invoice.FileName, invoice.Content); + } + + /// The file of a notification. + /// Who downloads: needs einvoice.document.read. + /// The company. + /// The notification. + /// Cancellation. + /// Name and content. + 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().GetAsync(id, cancellationToken).ConfigureAwait(false) + ?? throw new KeyNotFoundException(EInvoiceErrors.NotFound); + return (notification.FileName, notification.Content); + } + + /// The courtesy copy: the print of the document with the XML of the e-invoice embedded. + /// Who downloads: needs einvoice.document.read and to read the document. + /// The company. + /// The e-invoice. + /// Cancellation. + /// Name and content of the PDF. + 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().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()); + } + + /// The core of the generation, in the transaction of the caller (also the demo seed). + internal async Task 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(); + var active = await repository.FindAsync(Query.For().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); + } + + /// A file taken by a channel: Inviato, with the document. + 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().UpdateAsync(invoice, cancellationToken).ConfigureAwait(false); + await _engine.AdvanceExchangeAsync(uow, invoice.Family, invoice.DocumentId, s => EInvoiceStates.StepsTo(s, EInvoiceStatus.Sent), userName, cancellationToken).ConfigureAwait(false); + } + + /// + /// 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. + /// + internal async Task ApplyReceiptCoreAsync( + IUnitOfWork uow, EInvoiceReceipt receipt, string? channel, string userName, bool demo, CancellationToken cancellationToken) + { + var notifications = uow.Repository(); + var name = receipt.FileName; + if (await notifications.FindAsync(Query.For().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().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 FindInvoiceAsync(IUnitOfWork uow, EInvoiceReceipt receipt, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + 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().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().Where(e => e.ExchangeId == exchange).OrderByDescending(e => e.Id), cancellationToken).ConfigureAwait(false); + } + + return null; + } + + private async Task 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().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(); + 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().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().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> RouteAsync(IUnitOfWork uow, IEInvoiceChannels? channels, EInvoice invoice, CancellationToken cancellationToken) + { + if (channels is null) + { + return []; + } + + var rows = (await uow.Repository().ListAsync(Query.For().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().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items; + var party = invoice.PartyId is { } partyId ? await uow.Repository().GetAsync(partyId, cancellationToken).ConfigureAwait(false) : null; + var today = _clock.GetUtcNow().UtcDateTime.Date; + var sentToday = await uow.Repository().CountAsync(Query.For().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().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(); + var validator = pack.GetFeature(); + return writer is null || validator is null ? throw new ValidationFailedException([":" + EInvoiceErrors.NotSupported]) : (writer, validator, pack); + } + + private static async Task NextProgressiveAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var last = await uow.Repository().FindAsync(Query.For().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> PendingAsync(IUnitOfWork uow, EInvoiceFilter filter, CancellationToken cancellationToken) + { + var query = Query.For().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().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(), 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> PartiesAsync(IUnitOfWork uow, IEnumerable ids, CancellationToken cancellationToken) + { + var set = ids.Distinct().ToList(); + var result = new Dictionary(); + foreach (var chunk in set.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var party in (await uow.Repository().ListAsync(Query.For().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); +} diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs new file mode 100644 index 0000000..d01021f --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs @@ -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; + +/// The permissions of the electronic invoice (module EINV, ). +public static class EInvoicePermissions +{ + /// See the e-invoices, their notifications and the conservation packages. + public const string Read = "einvoice.document.read"; + + /// Generate, send and send again; import notifications. + public const string Send = "einvoice.document.send"; + + /// See the invoices received. + public const string InboxRead = "einvoice.inbox.read"; + + /// Register, discard and upload the invoices received. + public const string InboxImport = "einvoice.inbox.import"; + + /// Configure the channels and the routing; read the channels now. + public const string ChannelManage = "einvoice.channel.manage"; +} + +/// The error codes of the electronic invoice (texts in EInvoicing.json). +public static class EInvoiceErrors +{ + /// No e-invoice, notification or file with that identifier. + public const string NotFound = "einvoice.not-found"; + + /// The kind of document does not go to the exchange system. + public const string NotElectronic = "einvoice.not-electronic"; + + /// The document is not issued yet. + public const string NotIssued = "einvoice.not-issued"; + + /// The file was already sent: it can only receive notifications. + public const string AlreadySent = "einvoice.already-sent"; + + /// The profile of the company is missing. + public const string CompanyProfileMissing = "einvoice.profile-missing"; + + /// The fiscal pack of the company does not write e-invoices. + public const string NotSupported = "einvoice.not-supported"; + + /// No channel is enabled. + public const string NoChannel = "einvoice.no-channel"; + + /// The file is not a notification of the exchange system. + public const string NotAReceipt = "einvoice.not-a-receipt"; + + /// The notification is about a file Khaemhat did not send. + public const string ReceiptUnmatched = "einvoice.receipt-unmatched"; + + /// The notification was already imported. + public const string ReceiptDuplicate = "einvoice.receipt-duplicate"; + + /// The channel is not one of the pack. + public const string ChannelUnknown = "einvoice.channel-unknown"; + + /// A port out of range. + public const string PortInvalid = "einvoice.port-invalid"; + + /// The mailbox is not an e-mail address. + public const string MailboxInvalid = "einvoice.mailbox-invalid"; + + /// The address of the service is not an https address. + public const string EndpointInvalid = "einvoice.endpoint-invalid"; + + /// The value of a routing rule is missing or wrong. + public const string RuleValueInvalid = "einvoice.rule-value"; + + /// The received file is already in the inbox. + public const string InboxDuplicate = "einvoice.inbox-duplicate"; + + /// The received file is not in a state that allows the action. + public const string InboxState = "einvoice.inbox-state"; + + /// The period of the conservation package is wrong. + public const string PeriodInvalid = "einvoice.period-invalid"; +} + +/// An e-invoice in the lists, with its counterpart. +/// The e-invoice (the file is not loaded for lists). +/// The code of the customer or supplier. +/// The name. +public sealed record EInvoiceRow(EInvoice Invoice, string? PartyCode, string? PartyName); + +/// An issued document without its file yet, or whose file was rejected. +/// The family. +/// The document. +/// The kind. +/// The number. +/// The date. +/// The customer, or the supplier of a self-invoice. +/// The total. +/// The state of the document. +public sealed record PendingEInvoice(DocumentFamily Family, long DocumentId, DocumentKind Kind, string? Number, DateOnly Date, string? PartyName, decimal Total, DocumentStatus Status); + +/// What the dashboard shows. +public enum EInvoiceView +{ + /// Invoices, notes and fees sent to customers. + Issued = 0, + + /// Self-invoices and integrations. + SelfInvoices = 1, + + /// Everything that needs the user: to generate, to send, rejected, refused. + ToDo = 2, +} + +/// The filter of the dashboard. +/// The view. +/// Only this state. +/// From this date of the document. +/// Up to this date. +/// Number, file name, identifier of the SDI or counterpart. +public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EInvoiceStatus? Status = null, DateOnly? From = null, DateOnly? To = null, string? Search = null); + +/// The counters of the dashboard (mockup 058). +/// Issued documents without a file. +/// Files generated and not sent. +/// Sent, waiting for the receipt. +/// Delivered or issued (RC, MC, NE EC01, DT, AT). +/// Rejected by the SDI or refused by a public administration. +/// Invoices received to register. +public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int Received); + +/// The dashboard. +/// The e-invoices of the view. +/// The documents to generate (view and the counters). +/// The counters. +public sealed record EInvoiceDashboard(IReadOnlyList Rows, IReadOnlyList Pending, EInvoiceCounters Counters); + +/// The outcome of a generation: the file, or why not. +/// The e-invoice written. +/// Errors (nothing written) and warnings. +public sealed record EInvoiceGeneration(EInvoice? Invoice, IReadOnlyList Problems) +{ + /// Whether the file was written. + public bool Success => Invoice is not null; +} + +/// The outcome of sending one file. +/// The e-invoice. +/// The file. +/// The document. +/// Whether a channel took it. +/// The channel that took it, or the last one tried. +/// Why not (a message of the channel, or an error code). +public sealed record EInvoiceSendOutcome(long EInvoiceId, string FileName, string? DocumentNumber, bool Sent, string? ChannelCode, string? Error); + +/// The outcome of a notification imported or received. +/// The notification. +/// Its code (RC, NS …). +/// The file it is about. +/// The e-invoice updated. +/// The state it reached. +/// Why it was not applied (error code). +public sealed record ReceiptOutcome(string FileName, string? Code, string? InvoiceFileName, long? EInvoiceId, EInvoiceStatus? Status, string? Error); + +/// What the services of the electronic invoice share. +internal static class EInvoiceStore +{ + /// The channel of what the user uploads or sends from the portal of the AdE. + public const string ManualChannel = "MANUAL"; + + /// The purpose of the protection of the secrets of the channels. + public const string SecretPurpose = "einvoice.channel"; + + /// The SHA-256 of a file in lower-case hexadecimal. + public static string Hash(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content)); + + /// A text cut to a length. + public static string? Trim(string? text, int length) => + string.IsNullOrWhiteSpace(text) ? null : text.Trim().Length <= length ? text.Trim() : text.Trim()[..length]; + + /// The settings of a channel for its transport, secrets unprotected. + 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, + }; + } + + /// The name of the invoice file a notification is about, from the name of the notification. + /// The notification (IT01234567890_00001_RC_001.xml). + /// The stem of the invoice file (IT01234567890_00001), or . + public static string? InvoiceStem(string receiptFileName) + { + var name = Path.GetFileName(receiptFileName); + var parts = name.Split('_'); + return parts.Length >= 4 ? string.Join('_', parts[..^2]) : null; + } + + /// The stem of a file name: without .xml and .p7m. + 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; + } + + /// A shallow copy of a row (public properties that can be written), for the history of a change. + public static T Clone(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; + } + + /// A copy without the file, for lists and history. + 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, + }; +} diff --git a/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs b/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs new file mode 100644 index 0000000..c68bce6 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/SdiInboxService.cs @@ -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; + +/// The filter of the invoices received. +/// Only this state. +/// Supplier, VAT number, number or file name. +public sealed record InboxFilter(InboxFileStatus? Status = null, string? Search = null); + +/// A received file stored, or why not. +/// The file. +/// The row of the inbox. +/// Its state. +/// Why it was not stored (error code). +public sealed record InboxStored(string FileName, long? Id, InboxFileStatus? Status, string? Error); + +/// A received invoice registered as a supplier document, or why not. +/// The row of the inbox. +/// The file. +/// The draft supplier document. +/// Why it was not registered (error code). +/// What to check on the draft (codes). +public sealed record InboxRegistered(long Id, string FileName, long? PurchaseDocumentId, string? Error, IReadOnlyList Warnings); + +/// +/// 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. +/// +/// Permissions: einvoice.inbox.read to see, einvoice.inbox.import to upload, register and discard +/// (registering also needs purchases.invoice.write). +public sealed class SdiInboxService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly PurchaseInvoiceImportService _import; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The import of supplier invoices. + /// The clock. + 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; + } + + /// The invoices received, newest first (files not loaded). + /// Who looks: needs einvoice.inbox.read. + /// The company. + /// The filter. + /// Cancellation. + /// The rows. + public async Task> 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(); + if (filter.Status is { } status) + { + query = query.Where(f => f.Status == status); + } + + var rows = (await uow.Repository().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]; + } + + /// The received file, as it arrived. + /// Who downloads: needs einvoice.inbox.read. + /// The company. + /// The row. + /// The metadata file (MT) instead of the invoice. + /// Cancellation. + /// Name and content. + 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().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); + } + + /// Stores files the user uploads (downloaded from the portal of the AdE or received elsewhere). + /// Who uploads: needs einvoice.inbox.import. + /// The company. + /// The files. + /// Cancellation. + /// What happened to each. + public async Task> 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(); + var receipts = pack.GetFeature(); + var result = new List(); + 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; + } + + /// + /// 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. + /// + /// Who registers: needs einvoice.inbox.import and purchases.invoice.write. + /// The company. + /// The rows. + /// Cancellation. + /// What happened to each. + public async Task> RegisterAsync(Actor actor, string companyCode, IReadOnlyList 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(); + 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().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().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().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; + } + + /// Discards a received invoice (a copy, a file not for the company), or takes it back. + /// Who does it: needs einvoice.inbox.import. + /// The company. + /// The row. + /// Discard, or take back. + /// Cancellation. + /// A task. + 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(); + 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); + } + + /// + /// 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. + /// + internal static async Task StoreCoreAsync( + IUnitOfWork uow, IIncomingInvoiceReader? reader, string fileName, byte[] content, DateTime receivedAt, string? channel, string? exchangeId, bool demo, + CancellationToken cancellationToken) + { + var repository = uow.Repository(); + var hash = EInvoiceStore.Hash(content); + if (await repository.FindAsync(Query.For().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); + } + + /// Keeps the metadata file (MT) with the invoice it describes, by the name of the invoice file. + internal static async Task AttachMetadataCoreAsync(IUnitOfWork uow, EInvoiceReceipt metadata, CancellationToken cancellationToken) + { + var repository = uow.Repository(); + 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().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; +} diff --git a/src/Khaemhat.Application/Jobs/JobScheduler.cs b/src/Khaemhat.Application/Jobs/JobScheduler.cs index 51c3d98..7bb9b04 100644 --- a/src/Khaemhat.Application/Jobs/JobScheduler.cs +++ b/src/Khaemhat.Application/Jobs/JobScheduler.cs @@ -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; diff --git a/src/Khaemhat.Application/Modules/BuiltInModules.cs b/src/Khaemhat.Application/Modules/BuiltInModules.cs index ca98c18..e9a2e92 100644 --- a/src/Khaemhat.Application/Modules/BuiltInModules.cs +++ b/src/Khaemhat.Application/Modules/BuiltInModules.cs @@ -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"), diff --git a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs index 0dc30e0..39a9256 100644 --- a/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs +++ b/src/Khaemhat.Application/Purchases/PurchaseInvoiceImportService.cs @@ -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 FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken) + internal static async Task FindSupplierAsync(IUnitOfWork uow, EInvoiceParty party, CancellationToken cancellationToken) { var parties = uow.Repository(); if (VatOf(party) is { } vat) diff --git a/src/Khaemhat.Core/Documents/DocumentStateMachine.cs b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs index 69b5b60..6057681 100644 --- a/src/Khaemhat.Core/Documents/DocumentStateMachine.cs +++ b/src/Khaemhat.Core/Documents/DocumentStateMachine.cs @@ -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)); diff --git a/src/Khaemhat.Core/EInvoicing/EInvoicing.cs b/src/Khaemhat.Core/EInvoicing/EInvoicing.cs new file mode 100644 index 0000000..0a6268c --- /dev/null +++ b/src/Khaemhat.Core/EInvoicing/EInvoicing.cs @@ -0,0 +1,534 @@ +using Khaemhat.Core.Documents; +using Khaemhat.Core.Entities; + +namespace Khaemhat.Core.EInvoicing; + +/// Where an e-invoice is in its exchange with the SDI (SPEC §11.9, mockup 058). +public enum EInvoiceStatus +{ + /// The file was written and checked; not sent yet. + Generated = 0, + + /// Taken by the channel; waiting for the receipt of the SDI. + Sent = 1, + + /// Delivered to the customer (RC). + Delivered = 2, + + /// Not delivered, but available in the customer's tax drawer (MC): the invoice is issued. + NotDelivered = 3, + + /// Rejected by the SDI (NS): the invoice is not issued; correct it and send it again. + Rejected = 4, + + /// Accepted by the public administration (NE EC01). + Accepted = 5, + + /// Refused by the public administration (NE EC02): a credit note is needed. + Refused = 6, + + /// The public administration did not answer within 15 days (DT). + TermsElapsed = 7, + + /// A public administration could not be reached (AT): the invoice is issued. + Undeliverable = 8, +} + +/// What a notification of the SDI does to an e-invoice. +public static class EInvoiceStates +{ + /// The state after a notification, by its code (RC, NS, MC, NE, DT, AT); when it does not change. + /// The code of the notification. + /// The outcome of an NE (EC01, EC02). + /// The new state. + 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, + }; + + /// The state of the document for a state of its e-invoice. + /// The state of the e-invoice. + /// The state of the document. + 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, + }; + + /// The steps of the document that lead from one state to another. + /// The state of the document now. + /// The state of the e-invoice. + /// The actions, in order (empty when already there). + public static IReadOnlyList StepsTo(DocumentStatus current, EInvoiceStatus target) + { + var steps = new List(); + 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; + } + + /// Whether the invoice is legally issued in this state (everything after the SDI took it, except a rejection). + /// The state. + /// when issued. + public static bool IsIssued(EInvoiceStatus status) => status is not (EInvoiceStatus.Generated or EInvoiceStatus.Sent or EInvoiceStatus.Rejected); + + /// Whether the state needs the user (a rejection, a refusal). + /// The state. + /// when something must be done. + public static bool NeedsAction(EInvoiceStatus status) => status is EInvoiceStatus.Rejected or EInvoiceStatus.Refused; +} + +/// +/// An e-invoice file of a document (SPEC §11.9, e_invoices): 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. +/// +public sealed class EInvoice : Entity, IDemoMarkable +{ + /// The family of the document. + public DocumentFamily Family { get; set; } + + /// The document. + public long DocumentId { get; set; } + + /// The kind of the document. + public DocumentKind Kind { get; set; } + + /// The number of the document, for the lists. + public string? DocumentNumber { get; set; } + + /// The date of the document. + public DateOnly DocumentDate { get; set; } + + /// The customer, or the supplier of a self-invoice. + public long? PartyId { get; set; } + + /// The type of the format (Italy: TD01 …). + public string DocumentType { get; set; } = string.Empty; + + /// The name of the file (Italy: IT01234567890_00001.xml). + public string FileName { get; set; } = string.Empty; + + /// The progressive number of the file in the company. + public long Progressive { get; set; } + + /// The format (Italy: FPR12, FPA12). + public string Format { get; set; } = string.Empty; + + /// The recipient code. + public string? RecipientCode { get; set; } + + /// The certified mailbox of the recipient. + public string? RecipientPec { get; set; } + + /// The total of the document. + public decimal TotalAmount { get; set; } + + /// The state. + public EInvoiceStatus Status { get; set; } + + /// The channel it was sent through (MANUAL when sent from the portal of the AdE). + public string? ChannelCode { get; set; } + + /// The identifier of the SDI. + public string? ExchangeId { get; set; } + + /// The identifier at the channel. + public string? MessageId { get; set; } + + /// When the file was written (UTC). + public DateTime GeneratedAt { get; set; } + + /// When it was sent (UTC). + public DateTime? SentAt { get; set; } + + /// When the last notification arrived (UTC). + public DateTime? LastNotificationAt { get; set; } + + /// The last message: the error of the channel, or the description of the last notification. + public string? LastMessage { get; set; } + + /// How many times sending failed. + public int SendAttempts { get; set; } + + /// The file. + public byte[] Content { get; set; } = []; + + /// Whether a newer file of the same document replaced it. + public bool Superseded { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// A notification of the SDI (e_invoice_notifications), kept as received. +public sealed class EInvoiceNotification : Entity, IDemoMarkable +{ + /// The e-invoice it is about, when found. + public long? EInvoiceId { get; set; } + + /// The code (RC, NS, MC, NE, DT, AT, SE). + public string Code { get; set; } = string.Empty; + + /// The name of the notification file. + public string FileName { get; set; } = string.Empty; + + /// The name of the invoice file it is about. + public string? InvoiceFileName { get; set; } + + /// The identifier of the SDI. + public string? ExchangeId { get; set; } + + /// When it was received (UTC). + public DateTime ReceivedAt { get; set; } + + /// The outcome of an NE (EC01, EC02). + public string? Outcome { get; set; } + + /// The description. + public string? Description { get; set; } + + /// The errors of a rejection, one per line: code - description. + public string? Errors { get; set; } + + /// The channel it came from (MANUAL when uploaded). + public string? ChannelCode { get; set; } + + /// The file. + public byte[] Content { get; set; } = []; + + /// + public bool IsDemo { get; set; } +} + +/// Where a received invoice is. +public enum InboxFileStatus +{ + /// Received, to register. + New = 0, + + /// Registered as a supplier invoice or credit note. + Registered = 1, + + /// Set aside by the user (a duplicate, an invoice not for the company). + Discarded = 2, + + /// The file could not be read. + Unreadable = 3, +} + +/// +/// A supplier invoice received through a channel or uploaded (e_invoice_inbox, issue #79): the file with its +/// metadata, what it says, and the purchase document that registers it. The same file never enters twice (hash). +/// +public sealed class EInvoiceInboxFile : Entity, IDemoMarkable +{ + /// The name of the file. + public string FileName { get; set; } = string.Empty; + + /// The SHA-256 of the file, in hexadecimal. + public string Hash { get; set; } = string.Empty; + + /// The file. + public byte[] Content { get; set; } = []; + + /// The name of the metadata file (MT). + public string? MetadataFileName { get; set; } + + /// The metadata file. + public byte[]? Metadata { get; set; } + + /// The identifier of the SDI. + public string? ExchangeId { get; set; } + + /// When it was received (UTC). + public DateTime ReceivedAt { get; set; } + + /// The channel (MANUAL when uploaded). + public string? ChannelCode { get; set; } + + /// The VAT number of the supplier. + public string? SupplierVat { get; set; } + + /// The name of the supplier. + public string? SupplierName { get; set; } + + /// The type of the document (TD01 …). + public string? DocumentType { get; set; } + + /// The number of the invoice. + public string? Number { get; set; } + + /// The date of the invoice. + public DateOnly? DocumentDate { get; set; } + + /// The total of the invoice. + public decimal? TotalAmount { get; set; } + + /// The supplier in the archive, when found. + public long? PartyId { get; set; } + + /// The state. + public InboxFileStatus Status { get; set; } + + /// The purchase document that registers it. + public long? PurchaseDocumentId { get; set; } + + /// Why it could not be read or registered. + public string? Error { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// +/// The settings of a channel in a company (e_invoice_channels, mockup 059). Passwords, keys and certificates are +/// stored protected (ISecretProtector, purpose einvoice.channel) and never shown again. +/// +public sealed class EInvoiceChannelSetting : Entity, IDemoMarkable +{ + /// The code of the channel. + public string Code { get; set; } = string.Empty; + + /// Whether it is used. + public bool Enabled { get; set; } + + /// Whether it is paused: no sending and no polling until resumed. + public bool Paused { get; set; } + + /// The certified mailbox (PEC). + public string? Mailbox { get; set; } + + /// The SMTP server. + public string? SmtpHost { get; set; } + + /// The SMTP port. + public int SmtpPort { get; set; } = 465; + + /// The IMAP server. + public string? ImapHost { get; set; } + + /// The IMAP port. + public int ImapPort { get; set; } = 993; + + /// Whether the connections use TLS. + public bool Tls { get; set; } = true; + + /// The user. + public string? UserName { get; set; } + + /// The password, protected. + public string? ProtectedPassword { get; set; } + + /// The address of the SDI to write to (PEC), learned from its messages. + public string? ExchangeAddress { get; set; } + + /// The folder of the mailbox for processed messages. + public string? ArchiveFolder { get; set; } + + /// The address of the web service or API. + public string? Endpoint { get; set; } + + /// The client certificate (PKCS#12, base64), protected. + public string? ProtectedCertificate { get; set; } + + /// The password of the certificate, protected. + public string? ProtectedCertificatePassword { get; set; } + + /// The API key, protected. + public string? ProtectedApiKey { get; set; } + + /// Whether the test environment is used. + public bool TestEnvironment { get; set; } + + /// When the connection was last tested (UTC). + public DateTime? LastCheckAt { get; set; } + + /// Whether the last test worked. + public bool? LastCheckOk { get; set; } + + /// What the last test said. + public string? LastCheckMessage { get; set; } + + /// When the channel was last read (UTC). + public DateTime? LastPollAt { get; set; } + + /// What the last reading found, or its error. + public string? LastPollMessage { get; set; } + + /// Whether the last reading failed. + public bool LastPollFailed { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// When a routing rule applies. +public enum SdiRoutingCondition +{ + /// Always (the last rule, usually). + Default = 0, + + /// The customer is a public administration. + PublicAdministration = 1, + + /// The customer has the code in . + Party = 2, + + /// The type of the format is the one in (TD01, TD17 …). + DocumentType = 3, + + /// The files sent today are at least the number in . + DailyVolume = 4, +} + +/// A rule of the router (e_invoice_routing, issue #77): the first enabled rule that applies chooses the channel. +public sealed class SdiRoutingRule : Entity, IDemoMarkable +{ + /// The order (lower first). + public int Position { get; set; } + + /// When it applies. + public SdiRoutingCondition Condition { get; set; } + + /// The value of the condition. + public string? Value { get; set; } + + /// The channel. + public string ChannelCode { get; set; } = string.Empty; + + /// The channel used when the first is paused, disabled or fails. + public string? FallbackChannelCode { get; set; } + + /// Whether the rule is ignored. + public bool Disabled { get; set; } + + /// + public bool IsDemo { get; set; } +} + +/// What the router knows of a file to send. +/// The type of the format. +/// The code of the customer. +/// Whether the customer is a public administration. +/// How many files were sent today. +public sealed record SdiRoutingInput(string DocumentType, string? PartyCode, bool PublicAdministration, int SentToday); + +/// The channels chosen for a file. +/// The channel to use. +/// The channel to try when the first fails. +/// The rule that chose them. +public sealed record SdiRoute(string Channel, string? Fallback, long? RuleId); + +/// +/// 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. +/// +public static class SdiRouter +{ + /// Chooses. + /// The file. + /// The rules. + /// The codes of the channels enabled and not paused, in the order of the pack. + /// The route, or when no channel can take the file. + public static SdiRoute? Choose(SdiRoutingInput input, IEnumerable rules, IReadOnlyList 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, + }; +} + +/// A conservation package exported (e_invoice_conservation, issue #79): what went out, and its fingerprint. +public sealed class ConservationExport : Entity +{ + /// The first day. + public DateOnly FromDate { get; set; } + + /// The last day. + public DateOnly ToDate { get; set; } + + /// The files in the package. + public int FileCount { get; set; } + + /// The name of the package. + public string FileName { get; set; } = string.Empty; + + /// The SHA-256 of the package. + public string Hash { get; set; } = string.Empty; + + /// The size in bytes. + public long Size { get; set; } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/EInvoicingMaps.cs b/src/Khaemhat.Data/CompanyDatabase/EInvoicingMaps.cs new file mode 100644 index 0000000..8a2a45f --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/EInvoicingMaps.cs @@ -0,0 +1,106 @@ +using Khaemhat.Core.EInvoicing; +using Khaemhat.Data.Mapping; + +namespace Khaemhat.Data.CompanyDatabase; + +/// Map of to e_invoices. +public sealed class EInvoiceMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to e_invoice_notifications. +public sealed class EInvoiceNotificationMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to e_invoice_inbox. +public sealed class EInvoiceInboxFileMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to e_invoice_channels. +public sealed class EInvoiceChannelSettingMap : EntityMap +{ + /// Creates the map. + 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); + } +} + +/// Map of to e_invoice_routing. +public sealed class SdiRoutingRuleMap : EntityMap +{ + /// Creates the map. + public SdiRoutingRuleMap() + { + ToTable("e_invoice_routing"); + Map(x => x.Value).MaxLength(40); + Map(x => x.ChannelCode).MaxLength(20); + Map(x => x.FallbackChannelCode).MaxLength(20); + } +} + +/// Map of to e_invoice_conservation. +public sealed class ConservationExportMap : EntityMap +{ + /// Creates the map. + public ConservationExportMap() + { + ToTable("e_invoice_conservation"); + Map(x => x.FileName).MaxLength(100); + Map(x => x.Hash).MaxLength(64); + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_004_CreateEInvoicing.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_004_CreateEInvoicing.cs new file mode 100644 index 0000000..ff16dab --- /dev/null +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_004_CreateEInvoicing.cs @@ -0,0 +1,159 @@ +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Data.CompanyDatabase.Migrations; + +/// +/// 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. +/// +[Migration(20261113_004, "create_einvoicing")] +public sealed class M20261113_004_CreateEInvoicing : IMigration +{ + /// + 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(); + }); + } +} diff --git a/src/Khaemhat.Infrastructure/Files/PdfWriter.cs b/src/Khaemhat.Infrastructure/Files/PdfWriter.cs index f310170..3ec5255 100644 --- a/src/Khaemhat.Infrastructure/Files/PdfWriter.cs +++ b/src/Khaemhat.Infrastructure/Files/PdfWriter.cs @@ -418,6 +418,7 @@ public sealed class PdfWriter : IAsyncDisposable private readonly List _offsets = [0, -1, -1, -1]; private readonly List _pageObjects = []; private readonly Dictionary _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); } + /// + /// 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 (/AFRelationship), listed in the names of the catalogue + /// and in its associated files (/AF). Readers show it among the attachments. + /// + /// 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. + /// The name of the file. + /// The media type, such as application/xml. + /// The file. + /// What it is. + /// The relationship: Source, Data, Alternative, Supplement or Unspecified. + public void AddAttachment(string fileName, string mediaType, ReadOnlySpan 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)); + } + /// Writes what is buffered to the output. /// Cancellation. /// A task. @@ -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"); diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 0f30e22..ff833ea 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -174,6 +174,14 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); + // Electronic invoice (SPEC §11.9, M9): files, channels to the SDI, inbox, conservation. + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + // The document engine (ADR 0032): one engine, the copies, a typed service per family. services.AddSingleton(); services.AddSingleton(); @@ -247,6 +255,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -265,7 +274,8 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); // 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( diff --git a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json index 0f7cc77..69c29d1 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Dashboard.json +++ b/src/Khaemhat.Web/Resources/it-IT/Dashboard.json @@ -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": { diff --git a/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs index 9d14106..0eb9169 100644 --- a/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs +++ b/tests/Khaemhat.Core.Tests/Documents/DocumentRulesTests.cs @@ -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)); diff --git a/tests/Khaemhat.Data.Tests/MappingTests.cs b/tests/Khaemhat.Data.Tests/MappingTests.cs index bc19b8c..ca438a5 100644 --- a/tests/Khaemhat.Data.Tests/MappingTests.cs +++ b/tests/Khaemhat.Data.Tests/MappingTests.cs @@ -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()); }