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 accepted (RC, NE EC01, DT). /// Rejected by the SDI or refused by a public administration. /// Issued but not delivered: in the reserved area of the customer (MC, AT). /// Invoices received to register. public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int NotDelivered, 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, }; }