From b78260beb0f286c921bbfa8738d69a5e187eecb2 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 13 Nov 2026 12:54:09 +0100 Subject: [PATCH] feat: e-invoice screens and SdICoop push endpoint (#74 #75 #76 #77 #79) The SDI dashboard (mockup 058) with its six counters, the documents to generate, generate+send, manual receipts import, history, courtesy copy and mark-as-sent; the channels page (mockup 059) with settings, test, pause and routing rules; the received invoices, the notifications and the conservation packages. The SdICoop web service receives pushes at /sdicoop/{company}, authenticated by the key of the channel, through a new IEInvoicePushReader feature so the web layer stays country-neutral. The menu gives each e-invoice page its own permission and keeps the intent declarations under M10. Co-Authored-By: Claude Opus 5.5 --- .../EInvoicing/EInvoiceService.cs | 27 +- .../EInvoicing/EInvoiceStore.cs | 5 +- .../EInvoicing/SdiPushService.cs | 138 ++++ .../EInvoicing.cs | 27 + src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs | 1 + .../Sdi/SdiCoopPushReader.cs | 24 + .../Pages/EInvoicing/ConservationPage.razor | 130 ++++ .../EInvoicing/EInvoiceChannelsPage.razor | 469 ++++++++++++++ .../EInvoicing/EInvoiceDashboardPage.razor | 589 ++++++++++++++++++ .../Pages/EInvoicing/EInvoiceGuard.razor | 62 ++ .../Pages/EInvoicing/EInvoiceInboxPage.razor | 253 ++++++++ .../EInvoiceNotificationsPage.razor | 149 +++++ .../EInvoicing/EInvoicingScreens.cs | 111 ++++ src/Khaemhat.Web/Hosting/KhaemhatApp.cs | 1 + src/Khaemhat.Web/Hosting/KhaemhatServices.cs | 1 + src/Khaemhat.Web/Hosting/SdiEndpoints.cs | 53 ++ .../Resources/it-IT/EInvoicing.json | 278 +++++++++ src/Khaemhat.Web/Resources/it-IT/Shell.json | 3 + src/Khaemhat.Web/Shell/MenuCatalog.cs | 25 +- src/Khaemhat.Web/wwwroot/app.css | 25 + .../EInvoicing/EInvoiceTests.cs | 49 ++ 21 files changed, 2414 insertions(+), 6 deletions(-) create mode 100644 src/Khaemhat.Application/EInvoicing/SdiPushService.cs create mode 100644 src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs create mode 100644 src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor create mode 100644 src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor create mode 100644 src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor create mode 100644 src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs create mode 100644 src/Khaemhat.Web/Hosting/SdiEndpoints.cs create mode 100644 src/Khaemhat.Web/Resources/it-IT/EInvoicing.json diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs index bed773c..da52fef 100644 --- a/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceService.cs @@ -100,8 +100,9 @@ public sealed partial class EInvoiceService 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.IsIssued(e.Status) && e.Status is not (EInvoiceStatus.Refused or EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable)), all.Count(e => EInvoiceStates.NeedsAction(e.Status)), + all.Count(e => e.Status is EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable), received); IEnumerable rows = filter.View switch @@ -160,6 +161,30 @@ public sealed partial class EInvoiceService return result; } + /// The notifications received in a period, newest first (files not loaded). + /// Who looks: needs einvoice.document.read. + /// The company. + /// From this day. + /// Up to this day. + /// Cancellation. + /// The notifications. + public async Task> NotificationsAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, 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 start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var rows = (await uow.Repository() + .ListAsync(Query.For().Where(n => n.ReceivedAt >= start && n.ReceivedAt < end).OrderByDescending(n => n.ReceivedAt).Take(2000), cancellationToken) + .ConfigureAwait(false)).Items; + foreach (var row in rows) + { + row.Content = []; + } + + return rows; + } + /// Checks the file a document would have, without writing it. /// Who checks: needs einvoice.document.read. /// The company. diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs index d01021f..7c3646a 100644 --- a/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceStore.cs @@ -125,10 +125,11 @@ public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EIn /// Issued documents without a file. /// Files generated and not sent. /// Sent, waiting for the receipt. -/// Delivered or issued (RC, MC, NE EC01, DT, AT). +/// 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 Received); +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. diff --git a/src/Khaemhat.Application/EInvoicing/SdiPushService.cs b/src/Khaemhat.Application/EInvoicing/SdiPushService.cs new file mode 100644 index 0000000..ada4d25 --- /dev/null +++ b/src/Khaemhat.Application/EInvoicing/SdiPushService.cs @@ -0,0 +1,138 @@ +using System.Security.Cryptography; +using System.Text; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Tables; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Instance; +using Khaemhat.Core.Logging; +using Khaemhat.Core.Security; +using Khaemhat.Data; +using Khaemhat.Data.Companies; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; +using Microsoft.Extensions.Logging; + +namespace Khaemhat.Application.EInvoicing; + +/// The answer to a push of the exchange system. +/// The HTTP status. +/// The content type. +/// The body. +public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body); + +/// +/// Takes what the SDI pushes to the web service of a company (SdICoop, issue #76): invoices of suppliers and +/// notifications. The request carries the key stored in the channel (header X-Khaemhat-SdiCoop-Key); the mutual +/// TLS with the SDI is the job of the reverse proxy in front of Khaemhat. A disabled company, a channel that is not +/// enabled or a wrong key get nothing. +/// +public sealed partial class SdiPushService +{ + /// The header with the key of the channel. + public const string KeyHeader = "X-Khaemhat-SdiCoop-Key"; + + private readonly ICompanyRegistry _companies; + private readonly ILicenseGate _license; + private readonly IUnitOfWorkFactory _factory; + private readonly CompanyFiscalContext _packs; + private readonly ISecretProtector _secrets; + private readonly EInvoicePollingService _polling; + private readonly TimeProvider _clock; + private readonly ILogger _logger; + + /// Creates the service. + /// The companies. + /// The licence. + /// The units of work. + /// The fiscal pack of each company. + /// Opens the key of the channel. + /// Sorts the files received. + /// The clock. + /// The log (section SDI). + public SdiPushService( + ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets, + EInvoicePollingService polling, TimeProvider clock, ILogger logger) + { + ArgumentNullException.ThrowIfNull(companies); + ArgumentNullException.ThrowIfNull(license); + ArgumentNullException.ThrowIfNull(factory); + ArgumentNullException.ThrowIfNull(packs); + ArgumentNullException.ThrowIfNull(secrets); + ArgumentNullException.ThrowIfNull(polling); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(logger); + _companies = companies; + _license = license; + _factory = factory; + _packs = packs; + _secrets = secrets; + _polling = polling; + _clock = clock; + _logger = logger; + } + + /// Takes a push. + /// The company in the address. + /// The key in the header. + /// The content type. + /// The body. + /// Cancellation. + /// The answer. + public async Task ReceiveAsync(string companyCode, string? key, string? contentType, byte[] body, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(body); + using var scope = _logger.BeginScope(LogSections.Scope(LogSection.EInvoicing)); + var notFound = new SdiPushAnswer(404, "text/plain", "Not found."); + if (!_license.IsModuleActive(ModuleCodes.EInvoicing) + || await _companies.FindAsync(companyCode, cancellationToken).ConfigureAwait(false) is not { } company + || company.Status is CompanyStatus.Disabled) + { + return notFound; + } + + var pack = await _packs.PackOfAsync(company.Code, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } reader) + { + return notFound; + } + + var channel = reader.Channel; + EInvoiceChannelSetting? row; + await using (var uow = await _factory.CreateAsync(DatabaseScope.Company(company.Code), cancellationToken).ConfigureAwait(false)) + { + var rows = (await uow.Repository().ListAsync(Query.For().Where(c => c.Code == channel).Take(1), cancellationToken) + .ConfigureAwait(false)).Items; + row = rows.Count > 0 ? rows[0] : null; + } + + var expected = row is { Enabled: true, ProtectedApiKey: { Length: > 0 } stored } ? _secrets.Unprotect(stored, EInvoiceStore.SecretPurpose) : null; + if (expected is null || key is null || !SameKey(expected, key)) + { + LogRefused(_logger, company.Code, channel); + return new SdiPushAnswer(401, "text/plain", "Unauthorized."); + } + + if (reader.Read(contentType, body) is not { } push) + { + var (type, refusal) = reader.Refusal(); + return new SdiPushAnswer(400, type, refusal); + } + + var now = _clock.GetUtcNow(); + var messageKey = push.ExchangeId ?? EInvoiceStore.Hash(body); + var files = push.Files.Select(f => new EInvoiceIncoming(f.FileName, f.Content, now, messageKey, null)).ToList(); + var outcome = await _polling.ReceivePushedAsync(company.Code, channel, files, cancellationToken).ConfigureAwait(false); + LogReceived(_logger, company.Code, channel, outcome.Invoices, outcome.Receipts); + return new SdiPushAnswer(200, push.AnswerContentType, push.Answer); + } + + private static bool SameKey(string expected, string given) => + CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(expected)), SHA256.HashData(Encoding.UTF8.GetBytes(given))); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Push of channel {Channel} for company {Company} refused: wrong key or channel not enabled.")] + private static partial void LogRefused(ILogger logger, string company, string channel); + + [LoggerMessage(Level = LogLevel.Information, Message = "Push of channel {Channel} for company {Company}: {Invoices} invoices, {Receipts} notifications.")] + private static partial void LogReceived(ILogger logger, string company, string channel, int invoices, int receipts); +} diff --git a/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs b/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs index f787af3..99ccce1 100644 --- a/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs +++ b/src/Khaemhat.Fiscal.Abstractions/EInvoicing.cs @@ -278,3 +278,30 @@ public interface IEInvoiceChannels /// The channel, or . EInvoiceChannel? Find(string code); } + +/// What the exchange system pushed to the company over HTTP: the files and how to answer. +/// The identifier of the exchange system. +/// The files: a notification, or an invoice with its metadata. +/// The content type of the answer. +/// The body of the answer. +public sealed record EInvoicePush(string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files, string AnswerContentType, string Answer); + +/// +/// Reads what the exchange system sends to the web services of the company (Italy: the SdICoop operations +/// RiceviFatture, RicevutaConsegna, NotificaScarto …), for the channel that receives them. +/// +public interface IEInvoicePushReader +{ + /// The code of the channel the pushes belong to (Italy: SDICOOP). + string Channel { get; } + + /// Reads a request. + /// The content type of the HTTP request. + /// The body. + /// The files with the answer, or when the request is not one of the exchange system. + EInvoicePush? Read(string? contentType, byte[] body); + + /// The answer to a request that could not be read. + /// The content type and the body. + (string ContentType, string Body) Refusal(); +} diff --git a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs index b8eb7ca..1d823b9 100644 --- a/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs +++ b/src/Khaemhat.Fiscal.Italy/ItalyFiscalPack.cs @@ -22,6 +22,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase AddFeature(new FatturaPaValidator()); AddFeature(new SdiReceiptReader()); AddFeature(new Sdi.SdiChannels()); + AddFeature(new Sdi.SdiCoopPushReader()); AddFeature(new IncomingInvoiceRulesIt()); AddFeature(new SelfInvoiceRulesIt()); AddFeature(new WithholdingRulesIt()); diff --git a/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs new file mode 100644 index 0000000..9454536 --- /dev/null +++ b/src/Khaemhat.Fiscal.Italy/Sdi/SdiCoopPushReader.cs @@ -0,0 +1,24 @@ +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Fiscal.Italy.Sdi; + +/// The SdICoop messages the SDI sends to the company, as pushes of the channel SDICOOP (issue #76). +public sealed class SdiCoopPushReader : IEInvoicePushReader +{ + private const string Soap = "text/xml; charset=utf-8"; + + /// + public string Channel => SdiCoopTransport.ChannelCode; + + /// + public EInvoicePush? Read(string? contentType, byte[] body) + { + ArgumentNullException.ThrowIfNull(body); + return SdiCoopMessages.Read(contentType, body) is { } inbound + ? new EInvoicePush(inbound.ExchangeId, inbound.Files, Soap, SdiCoopMessages.Answer(inbound)) + : null; + } + + /// + public (string ContentType, string Body) Refusal() => (Soap, SdiCoopMessages.Answer(null)); +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor new file mode 100644 index 0000000..d758e07 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/ConservationPage.razor @@ -0,0 +1,130 @@ +@page "/fatturazione-elettronica/conservazione" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject ConservationExportService Conservation +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The packages for substitute conservation (SPEC §11.9, issue #79): the files issued and received in a period, their + notifications, an index with the fingerprint of each file, to hand to the conservation provider. Khaemhat is not a + conservation system: it prepares what goes to one, and remembers what went out. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Conservation.Title"]
+

@T["EInvoicing.Conservation.Heading"]

+
@T["EInvoicing.Conservation.Hint"]
+
+
+ +
+ +
+ + +
+

@T["EInvoicing.Conservation.Contents"]

+ +
+ + @if (_exports.Count == 0) + { +

@T["EInvoicing.Conservation.None"]

+ } + else + { +
+ + + + + + + + + + + + @foreach (var x in _exports) + { + + + + + + + + } + +
@T["EInvoicing.Conservation.Period"]@T["EInvoicing.Conservation.File"]@T["EInvoicing.Conservation.Files"]@T["EInvoicing.Conservation.Size"]@T["EInvoicing.Conservation.Hash"]
@T.Date(x.FromDate) – @T.Date(x.ToDate)@x.FileName@x.FileCount@Size(x.Size)@x.Hash[..16]…
+
+ } +
@T["EInvoicing.Conservation.Footer"]
+
+
+
+ +@code { + private IReadOnlyList _exports = []; + private DateOnly? _from; + private DateOnly? _to; + private bool _busy; + + private string Size(long bytes) => bytes >= 1024 * 1024 + ? T.Format("EInvoicing.Conservation.MegaBytes", bytes / 1048576m) + : T.Format("EInvoicing.Conservation.KiloBytes", Math.Max(1, bytes / 1024)); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + var previous = new DateOnly(today.Year, today.Month, 1).AddMonths(-1); + _from = previous; + _to = previous.AddMonths(1).AddDays(-1); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.Read)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is { } actor && Session.Company?.Code is { } company) + { + _exports = await Conservation.ListAsync(actor, company); + } + } + + private async Task ExportAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to) + { + return; + } + + _busy = true; + try + { + var package = await Conservation.ExportAsync(actor, company, from, to); + await EInvoicingScreens.DownloadAsync(JS, package.Export.FileName, "application/zip", package.Content); + Toasts.Show(ToastKind.Success, T["EInvoicing.Conservation.Done"], T.Format("EInvoicing.Conservation.DoneText", package.Export.FileCount)); + await LoadAsync(); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor new file mode 100644 index 0000000..6fd4ddd --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceChannelsPage.razor @@ -0,0 +1,469 @@ +@page "/fatturazione-elettronica/canali" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject EInvoiceChannelService Channels +@inject EInvoicePollingService Polling +@inject ToastService Toasts +@inject DialogService Dialogs + +@* The channels to the SDI (SPEC §11.9, mockup 059): the PEC mailbox, the SdICoop web service and the intermediaries, + each with its settings, a connection test, pause and resume; below, the rules that choose the channel of each file, + with a fallback when the first is paused or fails. Secrets are kept protected and never shown again. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Channels.Title"]
+

@T["EInvoicing.Channels.Heading"]

+
@T["EInvoicing.Channels.Hint"]
+
+ +
+ +
+ @foreach (var ch in _channels) + { + var s = ch.Setting; + + } +
+ + @if (_selected is { } sel && _form is { } f) + { + + + @T[StateOf(sel.Setting)] + + +
+ + @if (Kind == "PEC") + { + + + + + + + + + + + } + else + { + + @if (Kind == "SDICOOP") + { + + + + + + } + else if (Kind == "INTA") + { + + } + else + { + + + } + + } +
+ @if (sel.Setting.LastCheckAt is { } checkedAt) + { +

+ + @T.Format("EInvoicing.Channels.LastCheck", T.DateTime(checkedAt, TimeZoneInfo.Local)) · @sel.Setting.LastCheckMessage +

+ } +
+ + @if (sel.Setting.Enabled) + { + + } + + +
+
+
+ } + + + + + + + @if (_rules.Count == 0) + { +

@T["EInvoicing.Routing.None"]

+ } + else + { + + + + + + + + + + + + @foreach (var r in _rules) + { + + + + + + + + } + +
#@T["EInvoicing.Routing.Condition"]@T["EInvoicing.Fields.Channel"]@T["EInvoicing.Routing.Fallback"]
@r.Position@RuleText(r) @(r.Disabled ? " · " + T["EInvoicing.Routing.Disabled"] : null)@ChannelName(r.ChannelCode)@(r.FallbackChannelCode is { } fb ? ChannelName(fb) : "—") + + +
+ } +

@T["EInvoicing.Routing.Note"]

+
+
+ + + + @if (_rule is { } rule) + { +
+ + + @if (rule.Condition is SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType or SdiRoutingCondition.DailyVolume) + { + + } + + + +
+ } +
+
+ + +
+
+
+ +@code { + private IReadOnlyList _channels = []; + private IReadOnlyList _rules = []; + private string? _code; + private ChannelForm? _form; + private SdiRoutingRule? _rule; + private decimal? _rulePosition; + private bool _busy; + + private EInvoiceChannelView? _selected => _channels.FirstOrDefault(c => c.Code == _code); + + private string Kind => _code?.ToUpperInvariant() ?? string.Empty; + + private IReadOnlyList> Conditions => EInvoicingScreens.Choices(T); + + private IReadOnlyList> ChannelOptions => [.. _channels.Select(c => new KhOption(c.Code, c.Name))]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.ChannelManage)) + { + await LoadAsync(); + if ((_channels.FirstOrDefault(c => c.Setting.Enabled) ?? _channels.FirstOrDefault()) is { } first) + { + Select(first); + } + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _channels = await Channels.ListAsync(actor, company); + _rules = await Channels.RulesAsync(actor, company); + } + + private void Select(EInvoiceChannelView channel) + { + _code = channel.Code; + _form = ChannelForm.From(channel.Setting); + } + + private static string IconOf(string code) => code.ToUpperInvariant() switch + { + "PEC" => "mail", + "SDICOOP" => "server", + _ => "globe", + }; + + private static string StateOf(EInvoiceChannelSetting s) => + !s.Enabled ? "EInvoicing.Channels.State.Off" : s.Paused ? "EInvoicing.Channels.State.Paused" : "EInvoicing.Channels.State.On"; + + private static KhTone ToneOf(EInvoiceChannelSetting s) => !s.Enabled ? KhTone.Neutral : s.Paused ? KhTone.Warning : KhTone.Ok; + + private string Secret(string key, bool stored) => stored ? T[key] + " · " + T["EInvoicing.Channels.Stored"] : T[key]; + + private string ChannelName(string code) => _channels.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase))?.Name ?? code; + + private string RuleText(SdiRoutingRule r) => r.Condition switch + { + SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType or SdiRoutingCondition.DailyVolume => T.Format("EInvoicing.Routing.Text." + r.Condition, r.Value), + _ => T["EInvoicing.Routing.Text." + r.Condition], + }; + + private async Task ReadCertificateAsync(InputFileChangeEventArgs e) + { + if (_form is not { } f) + { + return; + } + + using var buffer = new MemoryStream(); + await using (var stream = e.File.OpenReadStream(512 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + f.Certificate = buffer.ToArray(); + f.CertificateName = e.File.Name; + } + + private async Task SaveAsync() => await RunAsync(async (actor, company) => + { + if (_form is { } f && _code is { } code) + { + await Channels.SaveAsync(actor, company, f.ToInput(code)); + Toasts.Show(ToastKind.Success, T["EInvoicing.Channels.Saved"], ChannelName(code)); + await LoadAsync(); + if (_selected is { } sel) + { + Select(sel); + } + } + }); + + private async Task CheckAsync() => await RunAsync(async (actor, company) => + { + if (_code is { } code) + { + var check = await Channels.CheckAsync(actor, company, code); + Toasts.Show(check.Success ? ToastKind.Success : ToastKind.Error, T[check.Success ? "EInvoicing.Channels.TestOk" : "EInvoicing.Channels.TestFailed"], check.Message); + await LoadAsync(); + } + }); + + private async Task PauseAsync() => await RunAsync(async (actor, company) => + { + if (_selected is { } sel) + { + await Channels.PauseAsync(actor, company, sel.Code, !sel.Setting.Paused); + await LoadAsync(); + } + }); + + private async Task PollAsync() => await RunAsync(async (actor, company) => + { + var outcomes = await Polling.PollNowAsync(actor, company); + if (outcomes.Count == 0) + { + Toasts.Show(ToastKind.Warning, T["EInvoicing.Dashboard.PollNow"], T["EInvoicing.Report.NoChannel"]); + } + + foreach (var o in outcomes) + { + Toasts.Show(o.Error is null ? ToastKind.Success : ToastKind.Error, ChannelName(o.Channel), + o.Error is null ? T.Format("EInvoicing.Report.Polled", o.Messages, o.Invoices, o.Receipts) : EInvoicingScreens.ErrorText(T, o.Error)); + } + + await LoadAsync(); + }); + + private void NewRule() + { + _rule = new SdiRoutingRule { Condition = SdiRoutingCondition.Default, ChannelCode = _channels.FirstOrDefault(c => c.Setting.Enabled)?.Code ?? _channels.FirstOrDefault()?.Code ?? string.Empty }; + _rulePosition = null; + } + + private void EditRule(SdiRoutingRule rule) + { + _rule = new SdiRoutingRule + { + Id = rule.Id, + Position = rule.Position, + Condition = rule.Condition, + Value = rule.Value, + ChannelCode = rule.ChannelCode, + FallbackChannelCode = rule.FallbackChannelCode, + Disabled = rule.Disabled, + IsDemo = rule.IsDemo, + }; + _rulePosition = rule.Position; + } + + private async Task SaveRuleAsync() => await RunAsync(async (actor, company) => + { + if (_rule is { } rule) + { + rule.Position = _rulePosition is { } p ? (int)p : 0; + await Channels.SaveRuleAsync(actor, company, rule); + _rule = null; + await LoadAsync(); + } + }); + + private async Task DeleteRuleAsync(SdiRoutingRule rule) + { + if (!await Dialogs.ConfirmAsync(new ConfirmRequest(T["EInvoicing.Routing.Delete"], RuleText(rule), T["Common.Delete"], T["Common.Cancel"], Danger: true))) + { + return; + } + + await RunAsync(async (actor, company) => + { + await Channels.DeleteRuleAsync(actor, company, rule.Id); + await LoadAsync(); + }); + } + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } + + /// What the form edits; secrets start empty and are sent only when typed. + private sealed class ChannelForm + { + public bool Enabled { get; set; } + + public string? Mailbox { get; set; } + + public string? SmtpHost { get; set; } + + public decimal? SmtpPort { get; set; } + + public string? ImapHost { get; set; } + + public decimal? ImapPort { get; set; } + + public bool Tls { get; set; } + + public string? UserName { get; set; } + + public string? Password { get; set; } + + public string? ExchangeAddress { get; set; } + + public string? ArchiveFolder { get; set; } + + public string? Endpoint { get; set; } + + public byte[]? Certificate { get; set; } + + public string? CertificateName { get; set; } + + public string? CertificatePassword { get; set; } + + public string? ApiKey { get; set; } + + public bool TestEnvironment { get; set; } + + public static ChannelForm From(EInvoiceChannelSetting s) => new() + { + Enabled = s.Enabled, + Mailbox = s.Mailbox, + SmtpHost = s.SmtpHost, + SmtpPort = s.SmtpPort, + ImapHost = s.ImapHost, + ImapPort = s.ImapPort, + Tls = s.Tls, + UserName = s.UserName, + ExchangeAddress = s.ExchangeAddress, + ArchiveFolder = s.ArchiveFolder, + Endpoint = s.Endpoint, + TestEnvironment = s.TestEnvironment, + }; + + public EInvoiceChannelInput ToInput(string code) => new() + { + Code = code, + Enabled = Enabled, + Mailbox = Mailbox, + SmtpHost = SmtpHost, + SmtpPort = SmtpPort is { } sp ? (int)sp : 465, + ImapHost = ImapHost, + ImapPort = ImapPort is { } ip ? (int)ip : 993, + Tls = Tls, + UserName = UserName, + Password = string.IsNullOrEmpty(Password) ? null : Password, + ExchangeAddress = ExchangeAddress, + ArchiveFolder = ArchiveFolder, + Endpoint = Endpoint, + Certificate = Certificate, + CertificatePassword = string.IsNullOrEmpty(CertificatePassword) ? null : CertificatePassword, + ApiKey = string.IsNullOrEmpty(ApiKey) ? null : ApiKey, + TestEnvironment = TestEnvironment, + }; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor new file mode 100644 index 0000000..270a088 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceDashboardPage.razor @@ -0,0 +1,589 @@ +@page "/fatturazione-elettronica" +@page "/fatturazione-elettronica/cruscotto" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.Documents +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.Documents +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject EInvoiceService EInvoices +@inject EInvoicePollingService Polling +@inject ToastService Toasts +@inject IJSRuntime JS + +@* The SDI dashboard (SPEC §11.9, mockup 058): the counters of the exchange, the files issued with their state and the + last notification, the documents still to generate. From here a document is generated and sent, a rejected one is + corrected, the notifications downloaded from the portal are imported, and each file shows its history. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Dashboard.Crumb"]
+

@T["EInvoicing.Dashboard.Heading"]

+
@T["EInvoicing.Dashboard.Hint"]
+
+ @if (_dashboard?.Counters.Received is > 0 and var received) + { + @T.Format("EInvoicing.Dashboard.ReceivedLink", received) + } +
+ + @if (_dashboard is { } d) + { + var c = d.Counters; +
+ @T["EInvoicing.Tiles.ToGenerateHint"] + @T["EInvoicing.Tiles.ToSendHint"] + @T["EInvoicing.Tiles.WaitingHint"] + @T["EInvoicing.Tiles.DeliveredHint"] + @T["EInvoicing.Tiles.RejectedHint"] + @T["EInvoicing.Tiles.NotDeliveredHint"] +
+ } + + +
+
+ + + +
+ + + + + + @if (CanSend) + { + + @if (Session.Permissions.Allows(EInvoicePermissions.ChannelManage)) + { + + } + + + } +
+ + @if (_dashboard is { } dash) + { + @if (dash.Pending.Count > 0) + { +

@T.Format("EInvoicing.Dashboard.PendingTitle", dash.Pending.Count)

+
+ + + + + + + + + + + + + + @foreach (var p in dash.Pending) + { + var key = (p.Family, p.DocumentId); + + + + + + + + + + } + +
@T["EInvoicing.Fields.Document"]@T["EInvoicing.Fields.Date"]@T["EInvoicing.Fields.Party"]@T["EInvoicing.Fields.Total"]@T["EInvoicing.Fields.DocumentStatus"]
+ @if (SalesScreens.RecordUrl(p.Kind, p.DocumentId) is { } url) + { + @SalesScreens.KindName(T, p.Kind) @p.Number + } + else + { + @(SalesScreens.KindName(T, p.Kind) + " " + p.Number) + } + @T.Date(p.Date)@p.PartyName@T.Money(p.Total)@T["Sales.States." + p.Status] + + +
+
+ @if (dash.Rows.Count > 0) + { +

@T["EInvoicing.Dashboard.FilesTitle"]

+ } + } + + @if (dash.Rows.Count == 0 && dash.Pending.Count == 0) + { +

@T[_view == EInvoiceView.ToDo ? "EInvoicing.Dashboard.NothingToDo" : "EInvoicing.Dashboard.None"]

+ } + else if (dash.Rows.Count > 0) + { +
+ + + + + + + + + + + + + + + + + @foreach (var row in dash.Rows) + { + var e = row.Invoice; + var sendable = e.Status == EInvoiceStatus.Generated; + + + + + + + + + + + + + } + +
@T["EInvoicing.Select"]@T["EInvoicing.Fields.Document"]@T["EInvoicing.Fields.Date"]@T[_view == EInvoiceView.SelfInvoices ? "EInvoicing.Fields.Supplier" : "EInvoicing.Fields.Customer"]@T["EInvoicing.Fields.Total"]@T["EInvoicing.Fields.Type"]@T["EInvoicing.Fields.Channel"]@T["EInvoicing.Fields.SdiStatus"]@T["EInvoicing.Fields.LastMessage"]
+ @if (sendable && CanSend) + { + + } + + @if (SalesScreens.RecordUrl(e.Kind, e.DocumentId) is { } url) + { + @e.DocumentNumber + } + else + { + @e.DocumentNumber + } +
@e.FileName
+
@T.Date(e.DocumentDate)@row.PartyName@T.Money(e.TotalAmount)@e.DocumentType@ChannelName(e.ChannelCode)@T[EInvoicingScreens.EnumKey(e.Status)] + @EInvoicingScreens.ErrorText(T, e.LastMessage) + @if (e.LastNotificationAt is { } at) + { +
@T.DateTime(at, TimeZoneInfo.Local)
+ } +
+ @if (CanSend && e.Status is EInvoiceStatus.Rejected && SalesScreens.RecordUrl(e.Kind, e.DocumentId) is { } fix) + { + @T["EInvoicing.Dashboard.Correct"] + } + @if (CanSend && sendable) + { + + } + + + +
+
+ } +
@T["EInvoicing.Dashboard.Footer"]
+ } + else + { +

@T["Common.Loading"]

+ } +
+ + + + @if (_history is { Count: 0 }) + { +

@T["EInvoicing.History.None"]

+ } + else if (_history is { } history) + { + @foreach (var (file, notes) in history) + { +
+
+ + @file.FileName + @T[EInvoicingScreens.EnumKey(file.Status)] + @if (file.Superseded) + { + @T["EInvoicing.History.Superseded"] + } + + +
+
+ @T.Format("EInvoicing.History.Generated", T.DateTime(file.GeneratedAt, TimeZoneInfo.Local), file.Format) + @(file.SentAt is { } sent ? " · " + T.Format("EInvoicing.History.Sent", T.DateTime(sent, TimeZoneInfo.Local), ChannelName(file.ChannelCode)) : null) + @(file.ExchangeId is { } sdi ? " · " + T.Format("EInvoicing.History.ExchangeId", sdi) : null) +
+ @if (notes.Count > 0) + { + + + @foreach (var n in notes) + { + + + + + + + } + +
@n.Code@T.DateTime(n.ReceivedAt, TimeZoneInfo.Local)@T["EInvoicing.Codes." + n.Code] @(n.Description is { Length: > 0 } desc ? "· " + desc : null)
+ } +
+ } + } +
+
+ +
+
+ + + +

@T.Format("EInvoicing.MarkSent.Text", _markSent?.FileName)

+
+ +
+
+
+ + +
+
+ + + +
    + @foreach (var (ok, title, text) in _report) + { +
  • + +
    @title @text
    +
  • + } +
+
+
+ +
+
+
+ +@code { + private EInvoiceDashboard? _dashboard; + private EInvoiceView _view = EInvoiceView.Issued; + private EInvoiceStatus? _status; + private DateOnly? _from; + private DateOnly? _to; + private string? _search; + private readonly HashSet<(DocumentFamily, long)> _docs = []; + private readonly HashSet _files = []; + private bool _busy; + private IReadOnlyList<(EInvoice Invoice, IReadOnlyList Notifications)>? _history; + private string? _historyNumber; + private EInvoice? _markSent; + private string? _exchangeId; + private readonly List<(bool Ok, string Title, string Text)> _report = []; + private string _reportTitle = string.Empty; + + /// The view asked by the address (?vista=da-fare, from the feed of the dashboard). + [SupplyParameterFromQuery(Name = "vista")] + public string? ViewQuery { get; set; } + + private bool CanSend => Session.Permissions.Allows(EInvoicePermissions.Send); + + private IReadOnlyList> Statuses => + [.. Enum.GetValues().Select(s => new KhOption(s, T[EInvoicingScreens.EnumKey(s)]))]; + + private string Count(int value) => value.ToString(T.Culture); + + private string ChannelName(string? code) => + string.IsNullOrEmpty(code) ? "—" : T.Contains("EInvoicing.Channels.Names." + code) ? T["EInvoicing.Channels.Names." + code] : code; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _view = ViewQuery switch + { + "da-fare" => EInvoiceView.ToDo, + "autofatture" => EInvoiceView.SelfInvoices, + _ => EInvoiceView.Issued, + }; + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.Read)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _dashboard = await EInvoices.DashboardAsync(actor, company, new EInvoiceFilter(_view, _status, _from, _to, _search)); + _docs.Clear(); + _files.Clear(); + if (_view == EInvoiceView.ToDo) + { + _docs.UnionWith(_dashboard.Pending.Where(p => p.Status != DocumentStatus.SdiRejected).Select(p => (p.Family, p.DocumentId))); + _files.UnionWith(_dashboard.Rows.Where(r => r.Invoice.Status == EInvoiceStatus.Generated).Select(r => r.Invoice.Id)); + } + } + + private async Task SetViewAsync(EInvoiceView view) + { + _view = view; + await LoadAsync(); + } + + private async Task SetStatusAsync(EInvoiceStatus? status) + { + _status = status; + await LoadAsync(); + } + + private async Task SetFromAsync(DateOnly? date) + { + _from = date; + await LoadAsync(); + } + + private async Task SetToAsync(DateOnly? date) + { + _to = date; + await LoadAsync(); + } + + private async Task SearchAsync(ChangeEventArgs e) + { + _search = e.Value?.ToString(); + await LoadAsync(); + } + + private void ToggleDoc((DocumentFamily, long) key, bool on) + { + if (on) + { + _docs.Add(key); + } + else + { + _docs.Remove(key); + } + } + + private void ToggleAllDocs(bool on) + { + _docs.Clear(); + if (on && _dashboard is { } d) + { + _docs.UnionWith(d.Pending.Select(p => (p.Family, p.DocumentId))); + } + } + + private void ToggleFile(long id, bool on) + { + if (on) + { + _files.Add(id); + } + else + { + _files.Remove(id); + } + } + + private async Task GenerateAndSendAsync() => await RunAsync(async (actor, company) => + { + var results = await EInvoices.GenerateAndSendAsync(actor, company, [.. _docs.Select(k => (k.Item1, k.Item2))]); + _report.Clear(); + foreach (var (doc, generation, sending) in results) + { + var title = doc is null ? string.Empty : SalesScreens.KindName(T, doc.Kind) + " " + doc.Number; + if (!generation.Success) + { + _report.Add((false, title, EInvoicingScreens.Problems(T, generation.Problems))); + } + else if (sending is { Sent: false } failed) + { + _report.Add((false, title, T.Format("EInvoicing.Report.NotSent", generation.Invoice!.FileName, EInvoicingScreens.ErrorText(T, failed.Error)))); + } + else + { + _report.Add((true, title, T.Format("EInvoicing.Report.Sent", generation.Invoice!.FileName, ChannelName(sending?.ChannelCode)))); + } + } + + _reportTitle = T["EInvoicing.Report.Title"]; + await LoadAsync(); + }); + + private async Task SendAsync() => await RunAsync(async (actor, company) => + { + var results = await EInvoices.SendAsync(actor, company, [.. _files]); + _report.Clear(); + foreach (var r in results) + { + _report.Add((r.Sent, r.DocumentNumber ?? r.FileName, r.Sent + ? T.Format("EInvoicing.Report.Sent", r.FileName, ChannelName(r.ChannelCode)) + : T.Format("EInvoicing.Report.NotSent", r.FileName, EInvoicingScreens.ErrorText(T, r.Error)))); + } + + _reportTitle = T["EInvoicing.Report.Title"]; + await LoadAsync(); + }); + + private async Task CheckAsync(PendingEInvoice document) => await RunAsync(async (actor, company) => + { + var problems = await EInvoices.CheckAsync(actor, company, document.Family, document.DocumentId); + var title = SalesScreens.KindName(T, document.Kind) + " " + document.Number; + _report.Clear(); + if (problems.Count == 0) + { + _report.Add((true, title, T["EInvoicing.Report.Valid"])); + } + + foreach (var p in problems) + { + _report.Add((p.Severity != Khaemhat.Fiscal.Abstractions.EInvoiceProblemSeverity.Error, p.Code, (string.IsNullOrEmpty(p.Path) ? string.Empty : p.Path + ": ") + EInvoicingScreens.ErrorText(T, p.Message))); + } + + _reportTitle = T["EInvoicing.Report.CheckTitle"]; + }); + + private async Task ImportReceiptsAsync(InputFileChangeEventArgs e) => await RunAsync(async (actor, company) => + { + var files = new List<(string, byte[])>(); + foreach (var file in e.GetMultipleFiles(200)) + { + using var buffer = new MemoryStream(); + await using (var stream = file.OpenReadStream(20 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + files.Add((file.Name, buffer.ToArray())); + } + + var outcomes = await EInvoices.ImportReceiptsAsync(actor, company, files); + _report.Clear(); + foreach (var o in outcomes) + { + _report.Add((o.Error is null, o.FileName, o.Error is null + ? T.Format("EInvoicing.Report.Applied", o.Code, o.InvoiceFileName, o.Status is { } s ? T[EInvoicingScreens.EnumKey(s)] : string.Empty) + : EInvoicingScreens.ErrorText(T, o.Error))); + } + + _reportTitle = T["EInvoicing.Report.ReceiptsTitle"]; + await LoadAsync(); + }); + + private async Task PollAsync() => await RunAsync(async (actor, company) => + { + var outcomes = await Polling.PollNowAsync(actor, company); + _report.Clear(); + foreach (var o in outcomes) + { + _report.Add((o.Error is null, ChannelName(o.Channel), o.Error is null + ? T.Format("EInvoicing.Report.Polled", o.Messages, o.Invoices, o.Receipts) + : EInvoicingScreens.ErrorText(T, o.Error))); + } + + if (_report.Count == 0) + { + _report.Add((false, T["EInvoicing.Dashboard.PollNow"], T["EInvoicing.Report.NoChannel"])); + } + + _reportTitle = T["EInvoicing.Dashboard.PollNow"]; + await LoadAsync(); + }); + + private async Task HistoryAsync(DocumentFamily family, long documentId, string? number) => await RunAsync(async (actor, company) => + { + _historyNumber = number; + _history = await EInvoices.HistoryAsync(actor, company, family, documentId); + }); + + private void OpenMarkSent(EInvoice invoice) + { + _markSent = invoice; + _exchangeId = null; + } + + private async Task MarkSentAsync() => await RunAsync(async (actor, company) => + { + if (_markSent is { } invoice) + { + await EInvoices.MarkSentAsync(actor, company, invoice.Id, string.IsNullOrWhiteSpace(_exchangeId) ? null : _exchangeId.Trim()); + _markSent = null; + Toasts.Show(ToastKind.Success, T["EInvoicing.MarkSent.Done"], invoice.FileName); + await LoadAsync(); + } + }); + + private async Task DownloadAsync(long id) => await RunAsync(async (actor, company) => + { + var (name, content) = await EInvoices.FileAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + }); + + private async Task NotificationAsync(long id) => await RunAsync(async (actor, company) => + { + var (name, content) = await EInvoices.NotificationFileAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + }); + + private async Task CourtesyAsync(long id) => await RunAsync(async (actor, company) => + { + var (name, content) = await EInvoices.CourtesyCopyAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, "application/pdf", content); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor new file mode 100644 index 0000000..42bf980 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceGuard.razor @@ -0,0 +1,62 @@ +@using Khaemhat.Application.Modules +@inject ShellSession Session + +@* What every page of the electronic invoice checks first: an open company, the module EINV in the licence and the permission. *@ +@if (!_loaded) +{ +

@T["Common.Loading"]

+} +else if (Session.Company is null) +{ +
+ +

@T["EInvoicing.NoCompany"]

+
+} +else if (!Session.Licenses.IsModuleActive(ModuleCodes.EInvoicing)) +{ +
+ +

@T["EInvoicing.NoModule.Title"]

+

@T["EInvoicing.NoModule.Lead"]

+
+} +else if (!Session.Permissions.Allows(Permission)) +{ +
+ +

@T["Pages.AccessDenied.Title"]

+

@T["Pages.AccessDenied.Lead"]

+ @T["Common.BackHome"] +
+} +else +{ + @ChildContent +} + +@code { + private bool _loaded; + + /// The permission the page needs. + [Parameter, EditorRequired] + public string Permission { get; set; } = string.Empty; + + /// The page. + [Parameter] + public RenderFragment? ChildContent { get; set; } + + /// Whether the page may load its data: company, licence and permission. + /// The session. + /// The permission. + /// True when it may. + public static bool Allowed(ShellSession session, string permission) => + session is { Actor: not null, Company: not null } && session.Licenses.IsModuleActive(ModuleCodes.EInvoicing) && session.Permissions.Allows(permission); + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + _loaded = true; + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor new file mode 100644 index 0000000..7072566 --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceInboxPage.razor @@ -0,0 +1,253 @@ +@page "/fatturazione-elettronica/ricevute" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.Documents +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.Documents +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject SdiInboxService Inbox +@inject ToastService Toasts +@inject IJSRuntime JS + +@* The invoices received from the SDI (SPEC §11.9, issue #79): what the channels downloaded and what the user uploads + (XML, P7M, the metadata file, a ZIP of the portal). Each one is registered as a supplier invoice through the import + of the purchases, or set aside; the same file never enters twice. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Inbox.Title"]
+

@T["EInvoicing.Inbox.Heading"]

+
@T["EInvoicing.Inbox.Hint"]
+
+
+ + +
+ + + + @if (CanImport) + { + + + } +
+ @if (_files.Count == 0) + { +

@T["EInvoicing.Inbox.None"]

+ } + else + { +
+ + + + + + + + + + + + + + + + @foreach (var f in _files) + { + + + + + + + + + + + + } + +
@T["EInvoicing.Select"]@T["EInvoicing.Fields.Supplier"]@T["EInvoicing.Fields.Document"]@T["EInvoicing.Fields.Date"]@T["EInvoicing.Fields.Total"]@T["EInvoicing.Fields.Type"]@T["EInvoicing.Inbox.ReceivedAt"]@T["EInvoicing.Fields.Status"]
+ @if (CanImport && f.Status == InboxFileStatus.New) + { + + } + + @(f.SupplierName ?? "—") +
@f.SupplierVat
+
+ @f.Number +
@f.FileName
+
@(f.DocumentDate is { } date ? T.Date(date) : null)@(f.TotalAmount is { } total ? T.Money(total) : null)@f.DocumentType + @T.DateTime(f.ReceivedAt, TimeZoneInfo.Local) +
@(f.ChannelCode == "MANUAL" ? T["EInvoicing.Inbox.Manual"] : f.ChannelCode) @(f.ExchangeId is { } sdi ? "· " + sdi : null)
+
+ @T[EInvoicingScreens.EnumKey(f.Status)] + @if (!string.IsNullOrEmpty(f.Error)) + { +
@EInvoicingScreens.ErrorText(T, f.Error)
+ } +
+ @if (f.PurchaseDocumentId is { } purchase && SalesScreens.RecordUrl(f.DocumentType == "TD04" ? DocumentKind.PurchaseCreditNote : DocumentKind.PurchaseInvoice, purchase) is { } url) + { + @T["EInvoicing.Inbox.Open"] + } + @if (CanImport && f.Status == InboxFileStatus.New) + { + + } + @if (CanImport && f.Status is InboxFileStatus.New or InboxFileStatus.Unreadable) + { + + } + @if (CanImport && f.Status == InboxFileStatus.Discarded) + { + + } + + @if (f.MetadataFileName is not null) + { + + } +
+
+ } +
@T["EInvoicing.Inbox.Footer"]
+
+
+ +@code { + private IReadOnlyList _files = []; + private readonly HashSet _chosen = []; + private InboxFileStatus? _status = InboxFileStatus.New; + private string? _search; + private bool _busy; + + private bool CanImport => Session.Permissions.Allows(EInvoicePermissions.InboxImport); + + private IReadOnlyList> Statuses => + [.. Enum.GetValues().Select(s => new KhOption(s, T[EInvoicingScreens.EnumKey(s)]))]; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.InboxRead)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _files = await Inbox.ListAsync(actor, company, new InboxFilter(_status, _search)); + _chosen.IntersectWith(_files.Where(f => f.Status == InboxFileStatus.New).Select(f => f.Id)); + } + + private async Task SetStatusAsync(InboxFileStatus? status) + { + _status = status; + await LoadAsync(); + } + + private async Task SearchAsync(ChangeEventArgs e) + { + _search = e.Value?.ToString(); + await LoadAsync(); + } + + private void Toggle(long id, bool on) + { + if (on) + { + _chosen.Add(id); + } + else + { + _chosen.Remove(id); + } + } + + private async Task UploadAsync(InputFileChangeEventArgs e) => await RunAsync(async (actor, company) => + { + var files = new List<(string, byte[])>(); + foreach (var file in e.GetMultipleFiles(200)) + { + using var buffer = new MemoryStream(); + await using (var stream = file.OpenReadStream(50 * 1024 * 1024)) + { + await stream.CopyToAsync(buffer); + } + + files.Add((file.Name, buffer.ToArray())); + } + + var stored = await Inbox.UploadAsync(actor, company, files); + var added = stored.Count(s => s.Error is null); + Toasts.Show(added > 0 ? ToastKind.Success : ToastKind.Warning, T.Format("EInvoicing.Inbox.Uploaded", added, stored.Count), + string.Join(" · ", stored.Where(s => s.Error is not null).Select(s => s.FileName + ": " + EInvoicingScreens.ErrorText(T, s.Error)))); + _status = InboxFileStatus.New; + await LoadAsync(); + }); + + private async Task RegisterAsync(IReadOnlyList ids) => await RunAsync(async (actor, company) => + { + var results = await Inbox.RegisterAsync(actor, company, ids); + var done = results.Count(r => r.Error is null); + var problems = results.Where(r => r.Error is not null).Select(r => r.FileName + ": " + EInvoicingScreens.ErrorText(T, r.Error)) + .Concat(results.SelectMany(r => r.Warnings.Select(w => r.FileName + ": " + EInvoicingScreens.ErrorText(T, w)))); + Toasts.Show(done == results.Count ? ToastKind.Success : ToastKind.Warning, T.Format("EInvoicing.Inbox.Registered", done, results.Count), string.Join(" · ", problems)); + _chosen.ExceptWith(ids); + await LoadAsync(); + }); + + private async Task DiscardAsync(long id, bool discard) => await RunAsync(async (actor, company) => + { + await Inbox.DiscardAsync(actor, company, id, discard); + await LoadAsync(); + }); + + private async Task DownloadAsync(long id, bool metadata) => await RunAsync(async (actor, company) => + { + var (name, content) = await Inbox.FileAsync(actor, company, id, metadata); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + }); + + private async Task RunAsync(Func action) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + await action(actor, company); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor new file mode 100644 index 0000000..8a4490d --- /dev/null +++ b/src/Khaemhat.Web/Components/Pages/EInvoicing/EInvoiceNotificationsPage.razor @@ -0,0 +1,149 @@ +@page "/fatturazione-elettronica/notifiche" +@attribute [Authorize] +@using Khaemhat.Application.EInvoicing +@using Khaemhat.Application.Security +@using Khaemhat.Core.EInvoicing +@using Khaemhat.Web.EInvoicing +@inject ShellSession Session +@inject EInvoiceService EInvoices +@inject ToastService Toasts +@inject IJSRuntime JS +@inject TimeProvider Clock + +@* The notifications of the SDI (SPEC §11.9, issue #75): every receipt kept as it arrived (RC, NS, MC, NE, DT, AT), + with the file it is about; each one can be downloaded again. *@ + + + +
+
+
@T["Shell.Menu.EInvoicing"] / @T["EInvoicing.Notifications.Title"]
+

@T["EInvoicing.Notifications.Heading"]

+
@T["EInvoicing.Notifications.Hint"]
+
+
+ + +
+ + + +
+ @if (Shown.Count == 0) + { +

@T["EInvoicing.Notifications.None"]

+ } + else + { +
+ + + + + + + + + + + + + @foreach (var n in Shown) + { + + + + + + + + + } + +
@T["EInvoicing.Notifications.ReceivedAt"]@T["EInvoicing.Notifications.Code"]@T["EInvoicing.Notifications.InvoiceFile"]@T["EInvoicing.Notifications.ExchangeId"]@T["EInvoicing.Notifications.Description"]
@T.DateTime(n.ReceivedAt, TimeZoneInfo.Local)@n.Code @T["EInvoicing.Codes." + n.Code]@n.InvoiceFileName@n.ExchangeId@n.Description
+
+ } +
@T.Format("EInvoicing.Notifications.Footer", Shown.Count)
+
+
+ +@code { + private IReadOnlyList _rows = []; + private DateOnly? _from; + private DateOnly? _to; + private string? _code; + private bool _busy; + + private static readonly string[] AllCodes = ["RC", "NS", "MC", "NE", "DT", "AT", "SE"]; + + private IReadOnlyList Shown => _code is null ? _rows : [.. _rows.Where(n => n.Code == _code)]; + + private IReadOnlyList> Codes => [.. AllCodes.Select(c => new KhOption(c, c + " · " + T["EInvoicing.Codes." + c]))]; + + private static KhTone ToneOf(EInvoiceNotification n) => n.Code switch + { + "RC" or "DT" => KhTone.Ok, + "NS" or "SE" => KhTone.Error, + "NE" => n.Outcome == "EC02" ? KhTone.Error : KhTone.Ok, + "MC" or "AT" => KhTone.Warning, + _ => KhTone.Neutral, + }; + + /// + protected override async Task OnInitializedAsync() + { + await Session.EnsureLoadedAsync(); + var today = DateOnly.FromDateTime(Clock.GetLocalNow().DateTime); + _to = today; + _from = today.AddDays(-90); + if (EInvoiceGuard.Allowed(Session, EInvoicePermissions.Read)) + { + await LoadAsync(); + } + } + + private async Task LoadAsync() + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company || _from is not { } from || _to is not { } to) + { + return; + } + + _rows = await EInvoices.NotificationsAsync(actor, company, from, to); + } + + private async Task SetFromAsync(DateOnly? date) + { + _from = date; + await LoadAsync(); + } + + private async Task SetToAsync(DateOnly? date) + { + _to = date; + await LoadAsync(); + } + + private async Task DownloadAsync(long id) + { + if (Session.Actor is not { } actor || Session.Company?.Code is not { } company) + { + return; + } + + _busy = true; + try + { + var (name, content) = await EInvoices.NotificationFileAsync(actor, company, id); + await EInvoicingScreens.DownloadAsync(JS, name, EInvoicingScreens.MediaTypeOf(name), content); + } + catch (ValidationFailedException ex) + { + Toasts.Show(ToastKind.Error, T["EInvoicing.NotDone"], EInvoicingScreens.Errors(T, ex)); + } + finally + { + _busy = false; + } + } +} diff --git a/src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs b/src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs new file mode 100644 index 0000000..1603117 --- /dev/null +++ b/src/Khaemhat.Web/EInvoicing/EInvoicingScreens.cs @@ -0,0 +1,111 @@ +using Khaemhat.Application.Localization; +using Khaemhat.Application.Security; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Fiscal.Abstractions; +using Khaemhat.Web.Ledger; +using Khaemhat.Web.Ui; +using Microsoft.JSInterop; + +namespace Khaemhat.Web.EInvoicing; + +/// What the screens of the electronic invoice share (SPEC §11.9, mockups 058-059): addresses, texts, tones, downloads. +public static class EInvoicingScreens +{ + /// The address of the area. + public const string BasePath = "/fatturazione-elettronica"; + + /// The address of the invoices received. + public const string InboxPath = BasePath + "/ricevute"; + + /// The address of the channels. + public const string ChannelsPath = BasePath + "/canali"; + + /// The key of the text of an enum value. + /// The value. + /// The key. + public static string EnumKey(Enum value) + { + ArgumentNullException.ThrowIfNull(value); + return "EInvoicing.Enums." + value.GetType().Name + "." + value; + } + + /// The choices of an enum. + /// The enum. + /// The texts. + /// The choices in declaration order. + public static IReadOnlyList> Choices(ITexts texts) + where TEnum : struct, Enum + { + ArgumentNullException.ThrowIfNull(texts); + return [.. Enum.GetValues().Select(v => new KhOption(v, texts[EnumKey(v)]))]; + } + + /// The tone of the state of an e-invoice. + /// The state. + /// The tone. + public static KhTone ToneOf(EInvoiceStatus status) => status switch + { + EInvoiceStatus.Generated => KhTone.Neutral, + EInvoiceStatus.Sent => KhTone.Info, + EInvoiceStatus.Delivered or EInvoiceStatus.Accepted or EInvoiceStatus.TermsElapsed => KhTone.Ok, + EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable => KhTone.Warning, + _ => KhTone.Error, + }; + + /// The tone of the state of a received file. + /// The state. + /// The tone. + public static KhTone ToneOf(InboxFileStatus status) => status switch + { + InboxFileStatus.New => KhTone.Info, + InboxFileStatus.Registered => KhTone.Ok, + InboxFileStatus.Unreadable => KhTone.Error, + _ => KhTone.Neutral, + }; + + /// The text of an error code, or the code itself. + /// The texts. + /// The code (or a message of a channel). + /// The text. + public static string ErrorText(ITexts texts, string? code) + { + ArgumentNullException.ThrowIfNull(texts); + return string.IsNullOrEmpty(code) ? string.Empty : texts.Contains(code) ? texts[code] : code; + } + + /// The text of the errors of a refused operation. + /// The texts. + /// The refusal. + /// The messages. + public static string Errors(ITexts texts, ValidationFailedException exception) => LedgerScreens.Errors(texts, exception); + + /// The problems of a file as one line each: where, and what. + /// The texts. + /// The problems. + /// The text. + public static string Problems(ITexts texts, IEnumerable problems) + { + ArgumentNullException.ThrowIfNull(texts); + ArgumentNullException.ThrowIfNull(problems); + return string.Join(" · ", problems.Where(p => p.Severity == EInvoiceProblemSeverity.Error) + .Select(p => (string.IsNullOrEmpty(p.Path) ? string.Empty : p.Path + ": ") + ErrorText(texts, p.Message))); + } + + /// Gives the browser a file to save. + /// The interop. + /// The name. + /// The media type. + /// The content. + /// A task. + public static Task DownloadAsync(IJSRuntime js, string fileName, string mediaType, byte[] content) => + LedgerScreens.DownloadAsync(js, new Khaemhat.Application.Ledger.LedgerFile(fileName, mediaType, content)); + + /// The media type of a file by its extension. + /// The name. + /// The media type. + public static string MediaTypeOf(string fileName) => + fileName.EndsWith(".p7m", StringComparison.OrdinalIgnoreCase) ? "application/pkcs7-mime" + : fileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase) ? "application/pdf" + : fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) ? "application/zip" + : "application/xml"; +} diff --git a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs index 80068a6..0d7cb59 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatApp.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatApp.cs @@ -120,6 +120,7 @@ public static class KhaemhatApp app.MapCompanySwitch(); app.MapHelp(); app.MapFiles(); + app.MapSdiPush(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index 8ee3810..b6b9631 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -180,6 +180,7 @@ internal static class KhaemhatServices services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); // The document engine (ADR 0032): one engine, the copies, a typed service per family. diff --git a/src/Khaemhat.Web/Hosting/SdiEndpoints.cs b/src/Khaemhat.Web/Hosting/SdiEndpoints.cs new file mode 100644 index 0000000..65f75f3 --- /dev/null +++ b/src/Khaemhat.Web/Hosting/SdiEndpoints.cs @@ -0,0 +1,53 @@ +using Khaemhat.Application.EInvoicing; + +namespace Khaemhat.Web.Hosting; + +/// +/// The web service the SDI calls (SdICoop, issue #76): POST /sdicoop/{company} takes the invoices of suppliers +/// and the notifications. No session: the request carries the key of the channel in X-Khaemhat-SdiCoop-Key, and +/// the reverse proxy in front of Khaemhat does the mutual TLS with the SDI and adds the header. +/// +public static class SdiEndpoints +{ + /// The address, followed by the code of the company. + public const string BasePath = "/sdicoop"; + + /// The largest message accepted: an invoice of 5 MB in base64 with its metadata. + public const int MaxBody = 16 * 1024 * 1024; + + /// Maps the endpoint. + /// The routes. + /// The routes. + public static IEndpointRouteBuilder MapSdiPush(this IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + endpoints.MapPost(BasePath + "/{company}", async (HttpContext context, string company, SdiPushService service) => + { + if (context.Request.ContentLength is > MaxBody) + { + return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + + using var buffer = new MemoryStream(); + var read = new byte[81920]; + int n; + while ((n = await context.Request.Body.ReadAsync(read, context.RequestAborted)) > 0) + { + if (buffer.Length + n > MaxBody) + { + return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + + buffer.Write(read, 0, n); + } + + var key = context.Request.Headers[SdiPushService.KeyHeader].ToString(); + var answer = await service.ReceiveAsync(company, key.Length == 0 ? null : key, context.Request.ContentType, buffer.ToArray(), context.RequestAborted); + return Results.Content(answer.Body, answer.ContentType, System.Text.Encoding.UTF8, answer.StatusCode); + }) + .AllowAnonymous() + .DisableAntiforgery() + .ExcludeFromDescription(); + return endpoints; + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/EInvoicing.json b/src/Khaemhat.Web/Resources/it-IT/EInvoicing.json new file mode 100644 index 0000000..249bb5f --- /dev/null +++ b/src/Khaemhat.Web/Resources/it-IT/EInvoicing.json @@ -0,0 +1,278 @@ +{ + "EInvoicing": { + "NoCompany": "Scegli un'azienda per vedere la fatturazione elettronica.", + "NoModule": { + "Title": "Il modulo Fatturazione elettronica non è attivo", + "Lead": "La generazione dei file FatturaPA, l'invio allo SDI e le fatture ricevute richiedono il modulo EINV nella licenza." + }, + "NotDone": "Operazione non eseguita", + "All": "Tutti", + "Select": "Seleziona", + "SelectAll": "Seleziona tutti", + "Fields": { + "Document": "Documento", + "Date": "Data", + "Party": "Controparte", + "Customer": "Cliente", + "Supplier": "Fornitore", + "Total": "Totale", + "Type": "TD", + "Channel": "Canale", + "Status": "Stato", + "SdiStatus": "Stato SDI", + "DocumentStatus": "Stato documento", + "LastMessage": "Ultima notifica / errore", + "From": "Dal", + "To": "Al" + }, + "Tiles": { + "ToGenerate": "Da generare", + "ToGenerateHint": "documenti emessi senza XML", + "ToSend": "Da inviare", + "ToSendHint": "XML generati e controllati", + "Waiting": "Inviate in attesa", + "WaitingHint": "attendono la ricevuta SDI", + "Delivered": "Consegnate", + "DeliveredHint": "RC, esito EC01, decorrenza termini", + "Rejected": "Scartate", + "RejectedHint": "da correggere e reinviare", + "NotDelivered": "Mancata consegna", + "NotDeliveredHint": "nel cassetto fiscale del cliente" + }, + "Dashboard": { + "Title": "Cruscotto SDI", + "Crumb": "Cruscotto SDI", + "Heading": "Fatturazione elettronica · SDI", + "Hint": "I file FatturaPA emessi, il loro stato presso il Sistema di Interscambio e i documenti ancora da trasmettere.", + "ReceivedLink": "{0} fatture ricevute da registrare", + "View": "Vista", + "Issued": "Emesse", + "SelfInvoices": "Autofatture", + "ToDo": "Da fare", + "Search": "Numero, file, identificativo SDI, controparte", + "ImportReceipts": "Importa notifiche", + "PollNow": "Leggi i canali ora", + "Send": "Invia ({0})", + "GenerateAndSend": "Genera + invia ({0})", + "PendingTitle": "Documenti da generare ({0})", + "FilesTitle": "File trasmessi", + "None": "Nessun file in questo periodo.", + "NothingToDo": "Niente da fare: tutti i documenti sono stati trasmessi e nessuno è stato scartato.", + "Check": "Controlla senza generare", + "History": "Storico del file", + "Correct": "Correggi", + "MarkSent": "Segna come inviata", + "Xml": "Scarica l'XML", + "XmlShort": "XML", + "Courtesy": "Copia di cortesia (PDF)", + "Footer": "Una fattura scartata (NS) non è emessa: correggi il documento e genera un nuovo file. Una fattura rifiutata da una pubblica amministrazione (NE EC02) richiede una nota di credito." + }, + "History": { + "Title": "Storico SDI · {0}", + "None": "Il documento non ha ancora un file.", + "Superseded": "sostituito", + "Generated": "Generato il {0} · formato {1}", + "Sent": "inviato il {0} via {1}", + "ExchangeId": "identificativo SDI {0}", + "Notifications": "Notifiche" + }, + "MarkSent": { + "Text": "Segna {0} come inviata fuori da Khaemhat (dal portale Fatture e Corrispettivi). Le notifiche si importano poi con «Importa notifiche».", + "ExchangeId": "Identificativo SDI (facoltativo)", + "Done": "File segnato come inviato" + }, + "Report": { + "Title": "Esito della trasmissione", + "CheckTitle": "Controllo del file", + "ReceiptsTitle": "Notifiche importate", + "Sent": "{0} preso in carico da {1}", + "NotSent": "{0} non inviato: {1}", + "Valid": "Il file supera i controlli dello SDI.", + "Applied": "{0} su {1}: ora {2}", + "Polled": "{0} messaggi letti · {1} fatture ricevute · {2} notifiche", + "NoChannel": "Nessun canale attivo da leggere." + }, + "Inbox": { + "Title": "Fatture ricevute", + "Heading": "Fatture ricevute dallo SDI", + "Hint": "Le fatture dei fornitori scaricate dai canali o caricate a mano (XML, P7M, file metadati, ZIP del portale): si registrano come fatture di acquisto.", + "Search": "Fornitore, partita IVA, numero, file", + "Upload": "Carica file", + "Register": "Registra ({0})", + "RegisterOne": "Registra come fattura di acquisto", + "Discard": "Scarta", + "Restore": "Ripristina", + "Metadata": "Scarica il file metadati", + "Open": "Apri", + "Manual": "caricata a mano", + "ReceivedAt": "Ricevuta", + "None": "Nessuna fattura ricevuta con questi criteri.", + "Uploaded": "{0} file su {1} acquisiti", + "Registered": "{0} fatture registrate su {1}", + "Footer": "Lo stesso file non entra due volte (impronta SHA-256). Il fornitore si riconosce dalla partita IVA; se manca viene creato dall'importazione." + }, + "Notifications": { + "Title": "Notifiche SDI", + "Heading": "Notifiche dello SDI", + "Hint": "Ogni ricevuta conservata così come è arrivata, con il file a cui si riferisce.", + "Code": "Tipo", + "ReceivedAt": "Ricevuta il", + "InvoiceFile": "File fattura", + "ExchangeId": "Identificativo SDI", + "Description": "Descrizione", + "None": "Nessuna notifica in questo periodo.", + "Footer": "{0} notifiche. Le righe evidenziate non sono state abbinate a un file emesso." + }, + "Conservation": { + "Title": "Conservazione", + "Heading": "Pacchetti per la conservazione", + "Hint": "I file emessi e ricevuti in un periodo, con notifiche e indice delle impronte, da consegnare al conservatore.", + "New": "Nuovo pacchetto", + "Contents": "Lo ZIP contiene le cartelle emesse/, ricevute/ e notifiche/, l'indice indice.csv con l'impronta SHA-256 di ogni file e un LEGGIMI. Al massimo due anni per pacchetto.", + "Export": "Prepara e scarica", + "History": "Pacchetti preparati", + "Period": "Periodo", + "File": "File", + "Files": "File inclusi", + "Size": "Dimensione", + "Hash": "Impronta SHA-256", + "None": "Nessun pacchetto preparato.", + "KiloBytes": "{0:N0} kB", + "MegaBytes": "{0:N1} MB", + "Done": "Pacchetto pronto", + "DoneText": "{0} file inclusi", + "Footer": "Khaemhat non è un sistema di conservazione sostitutiva: prepara il pacchetto e ricorda cosa è uscito e con quale impronta." + }, + "Channels": { + "Title": "Canali di trasmissione", + "Heading": "Canali verso lo SDI", + "Hint": "Come i file arrivano al Sistema di Interscambio e come tornano le notifiche e le fatture dei fornitori.", + "Settings": "{0} · impostazioni", + "Enabled": "Canale attivo", + "Mailbox": "Casella PEC", + "SmtpHost": "Server SMTP", + "SmtpPort": "Porta SMTP", + "ImapHost": "Server IMAP", + "ImapPort": "Porta IMAP", + "Tls": "Connessione cifrata (TLS)", + "UserName": "Utente", + "Password": "Password", + "ExchangeAddress": "Indirizzo PEC dello SDI", + "ArchiveFolder": "Cartella di archivio", + "Endpoint": "Indirizzo del servizio", + "Certificate": "Certificato client (PKCS#12)", + "CertificatePick": "Scegli il file .p12", + "CertificatePassword": "Password del certificato", + "PushKey": "Chiave di ricezione (header X-Khaemhat-SdiCoop-Key)", + "ApiKey": "Chiave API", + "TestEnvironment": "Ambiente di prova", + "Stored": "memorizzata, lascia vuoto per non cambiarla", + "LastCheck": "Ultima prova {0}", + "LastPoll": "letto {0}", + "Test": "Prova connessione", + "TestOk": "Connessione riuscita", + "TestFailed": "Connessione non riuscita", + "Pause": "Metti in pausa", + "Resume": "Riprendi", + "Saved": "Canale salvato", + "State": { + "On": "Attivo", + "Paused": "Configurato · in pausa", + "Off": "Non configurato" + }, + "About": { + "PEC": "Invio dalla casella PEC dell'azienda all'indirizzo dello SDI; ricevute e fatture lette via IMAP.", + "SDICOOP": "Web service SdICoop con certificato client; lo SDI consegna notifiche e fatture al servizio di ricezione.", + "INTA": "Intermediario accreditato con API REST e chiave API.", + "INTB": "Intermediario accreditato con API REST, utente e password." + }, + "Names": { + "PEC": "PEC", + "SDICOOP": "SdICoop", + "INTA": "Intermediario A", + "INTB": "Intermediario B", + "MANUAL": "Portale AdE" + } + }, + "Routing": { + "Title": "Instradamento", + "Add": "Nuova regola", + "Edit": "Modifica regola", + "Delete": "Elimina la regola", + "Condition": "Condizione", + "Fallback": "Canale di riserva", + "Position": "Ordine", + "Disabled": "disattivata", + "None": "Nessuna regola: i file usano il primo canale attivo.", + "Note": "Vale la prima regola attiva che si applica. Il canale di riserva si usa quando il primo è in pausa, disattivato o non risponde.", + "Value": { + "Party": "Codice del cliente", + "DocumentType": "Tipo documento (TD01, TD17…)", + "DailyVolume": "File inviati oggi (almeno)" + }, + "Text": { + "Default": "Sempre", + "PublicAdministration": "Cliente pubblica amministrazione", + "Party": "Cliente {0}", + "DocumentType": "Tipo documento {0}", + "DailyVolume": "Oltre {0} file al giorno" + } + }, + "Codes": { + "RC": "Ricevuta di consegna", + "NS": "Notifica di scarto", + "MC": "Mancata consegna", + "NE": "Esito committente", + "DT": "Decorrenza termini", + "AT": "Attestazione di trasmissione", + "SE": "Scarto esito committente", + "MT": "File metadati" + }, + "Enums": { + "EInvoiceStatus": { + "Generated": "Generata", + "Sent": "Inviata", + "Delivered": "Consegnata", + "NotDelivered": "Mancata consegna", + "Rejected": "Scartata", + "Accepted": "Accettata", + "Refused": "Rifiutata", + "TermsElapsed": "Decorrenza termini", + "Undeliverable": "Impossibile recapitare" + }, + "InboxFileStatus": { + "New": "Da registrare", + "Registered": "Registrata", + "Discarded": "Scartata", + "Unreadable": "Illeggibile" + }, + "SdiRoutingCondition": { + "Default": "Sempre", + "PublicAdministration": "Cliente pubblica amministrazione", + "Party": "Cliente specifico", + "DocumentType": "Tipo documento", + "DailyVolume": "Volume giornaliero" + } + } + }, + "einvoice": { + "not-found": "Il file non esiste più.", + "not-electronic": "Il documento non si trasmette allo SDI (per esempio un DDT o una pro forma).", + "not-issued": "Il documento non è ancora emesso: confermalo prima di generare l'XML.", + "already-sent": "Il file è già stato inviato.", + "profile-missing": "Mancano i dati dell'azienda per la fattura elettronica: completa il profilo azienda (partita IVA, sede, regime fiscale).", + "not-supported": "Il pacchetto fiscale dell'azienda non gestisce la fattura elettronica.", + "no-channel": "Nessun canale attivo per inviare il file: configura un canale o segna il file come inviato dal portale.", + "not-a-receipt": "Il file non è una notifica dello SDI.", + "receipt-unmatched": "La notifica non corrisponde a nessun file emesso.", + "receipt-duplicate": "La notifica era già stata importata.", + "channel-unknown": "Canale sconosciuto.", + "port-invalid": "La porta deve essere tra 1 e 65535.", + "mailbox-invalid": "L'indirizzo PEC non è valido.", + "endpoint-invalid": "L'indirizzo del servizio deve essere https (http solo verso questo computer).", + "rule-value": "La condizione richiede un valore valido.", + "inbox-duplicate": "Il file era già stato ricevuto.", + "inbox-state": "La fattura è già registrata o scartata.", + "period-invalid": "Il periodo non è valido (al massimo due anni)." + } +} diff --git a/src/Khaemhat.Web/Resources/it-IT/Shell.json b/src/Khaemhat.Web/Resources/it-IT/Shell.json index 11b5622..b019147 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Shell.json +++ b/src/Khaemhat.Web/Resources/it-IT/Shell.json @@ -111,6 +111,9 @@ "EInvoicing": { "_": "Fatt. elettronica", "Dashboard": "Cruscotto SDI", + "Inbox": "Fatture ricevute", + "Notifications": "Notifiche SDI", + "Conservation": "Conservazione", "Channels": "Canali di trasmissione", "IntentDeclarations": "Dichiarazioni d'intento" }, diff --git a/src/Khaemhat.Web/Shell/MenuCatalog.cs b/src/Khaemhat.Web/Shell/MenuCatalog.cs index 28153da..4af9a07 100644 --- a/src/Khaemhat.Web/Shell/MenuCatalog.cs +++ b/src/Khaemhat.Web/Shell/MenuCatalog.cs @@ -78,9 +78,7 @@ public static class MenuCatalog ("Shell.Menu.Finance.OpenItems", "scadenze"), ("Shell.Menu.Finance.Receipts", "incassi"), ("Shell.Menu.Finance.Payments", "pagamenti"), ("Shell.Menu.Finance.Dunning", "solleciti"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Mandates", "mandati"), ("Shell.Menu.Finance.Reconciliation", "riconciliazione"), ("Shell.Menu.Finance.CashFlow", "flusso-di-cassa")), - Area("Shell.Menu.EInvoicing", "file-check", "/fatturazione-elettronica", ModuleCodes.EInvoicing, "einvoice.document.read", "M9", - ("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"), - ("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")), + EInvoicing(), Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10", ("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")), Area("Shell.Menu.Services", "wrench", "/servizi", ModuleCodes.Services, null, "M12", @@ -127,6 +125,27 @@ public static class MenuCatalog // An entry delivered before the rest of its area (the guided import of M4 under the administration of M13). private static MenuItem WithChild(MenuItem area, MenuItem child) => area with { Children = [.. area.Children, child] }; + /// The electronic invoice (M9): each page has its own permission; the intent declarations come with M10. + private static MenuItem EInvoicing() + { + const string href = "/fatturazione-elettronica"; + const string icon = "file-check"; + MenuItem Child(string key, string slug, string permission, string? milestone = null) => + new(key, icon, href + "/" + slug, ModuleCodes.EInvoicing, permission, milestone); + return new MenuItem("Shell.Menu.EInvoicing", icon, href, ModuleCodes.EInvoicing, "einvoice.document.read", null) + { + Children = + [ + Child("Shell.Menu.EInvoicing.Dashboard", "cruscotto", "einvoice.document.read"), + Child("Shell.Menu.EInvoicing.Inbox", "ricevute", "einvoice.inbox.read"), + Child("Shell.Menu.EInvoicing.Notifications", "notifiche", "einvoice.document.read"), + Child("Shell.Menu.EInvoicing.Conservation", "conservazione", "einvoice.document.read"), + Child("Shell.Menu.EInvoicing.Channels", "canali", "einvoice.channel.manage"), + Child("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento", "einvoice.document.read", "M10"), + ], + }; + } + private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone, params (string Key, string Slug)[] children) => Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children); diff --git a/src/Khaemhat.Web/wwwroot/app.css b/src/Khaemhat.Web/wwwroot/app.css index 5c1d41d..4d4ad63 100644 --- a/src/Khaemhat.Web/wwwroot/app.css +++ b/src/Khaemhat.Web/wwwroot/app.css @@ -457,3 +457,28 @@ h1[tabindex="-1"]:focus { outline: none; box-shadow: none; } .kh-cfbar { display: block; height: 8px; border-radius: 4px; background: var(--kh-accent); min-width: 2px; } .kh-cfbar.neg { background: var(--kh-err); } @media (max-width: 1100px) { .kh-remit { grid-template-columns: minmax(0, 1fr); } } + +/* Electronic invoice (M9, mockups 058-059): six counters, channel cards, the history of a file, the reports. */ +.kh-sdi-tiles { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); } +.kh-mono { font-family: var(--kh-mono); font-size: 11.5px; } +.kh-pad-x { padding: 0 14px; } +.sm { font-size: 11.5px; } +.grid tr.kh-off td { color: var(--kh-text-3); } +.kh-sdi-channels { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; margin: 10px 0 12px; } +.kh-sdi-card { text-align: left; font: inherit; color: inherit; cursor: pointer; } +.kh-sdi-card:hover { border-color: var(--kh-accent); } +.kh-sdi-card.sel { border-color: var(--kh-accent); box-shadow: 0 0 0 2px var(--kh-accent-soft); } +.kh-sdi-card .mf { flex-wrap: wrap; } +.kh-sdi-actions { display: flex; gap: 8px; align-items: center; margin-top: 12px; flex-wrap: wrap; } +.kh-sdi-actions .grow { flex: 1; } +.kh-sdi-check { display: flex; gap: 6px; align-items: center; margin: 10px 0 0; font-size: 12px; } +.kh-sdi-check.ok { color: var(--kh-ok); } .kh-sdi-check.no { color: var(--kh-err); } +.kh-note { display: flex; gap: 6px; align-items: flex-start; margin: 0; padding: 10px 14px; font-size: 12px; color: var(--kh-text-2); border-top: 1px solid var(--kh-border); } +.kh-sdi-file { border: 1px solid var(--kh-border); border-radius: var(--kh-radius, 8px); padding: 10px 12px; margin-bottom: 10px; } +.kh-sdi-filehead { display: flex; gap: 8px; align-items: center; margin-bottom: 4px; flex-wrap: wrap; } +.kh-sdi-filehead .grow { flex: 1; } +.kh-sdi-notes { margin-top: 8px; } +.kh-sdi-notes .kh-sdi-desc { white-space: normal; } +.kh-sdi-report { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 60vh; overflow: auto; } +.kh-sdi-report li { display: flex; gap: 8px; align-items: flex-start; } +.kh-sdi-report li.ok > svg { color: var(--kh-ok); } .kh-sdi-report li.no > svg { color: var(--kh-err); } diff --git a/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs b/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs index a41c9d9..e7efe40 100644 --- a/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs +++ b/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs @@ -237,6 +237,55 @@ public sealed class EInvoiceTests } } + [TestMethod] + public async Task TheSdi_PushesANotification_WithTheKeyOfTheChannel() + { + var (app, address, company) = await TestInstance.StartAsync(CancellationToken.None); + await using (app) + { + await SeedAsync(app.Services, company); + var service = app.Services.GetRequiredService(); + var waiting = (await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.Issued))).Rows.First(r => r.Invoice.Status == EInvoiceStatus.Sent).Invoice; + var receipt = DemoEInvoiceSeeder.Notification("RicevutaConsegna", + $"{waiting.ExchangeId ?? "555000111"}{waiting.FileName}x" + + "2026-11-12T10:00:002026-11-12T10:05:009"); + var stem = waiting.FileName[..waiting.FileName.IndexOf(".xml", StringComparison.Ordinal)]; + var soap = "" + + "" + + $"{waiting.ExchangeId ?? "555000111"}{stem}_RC_009.xml{Convert.ToBase64String(receipt)}" + + ""; + using var client = new HttpClient { BaseAddress = address }; + async Task PostAsync(string? key, string body) + { + using var request = new HttpRequestMessage(HttpMethod.Post, "sdicoop/" + company) { Content = new StringContent(body, Encoding.UTF8, "text/xml") }; + if (key is not null) + { + request.Headers.Add(SdiPushService.KeyHeader, key); + } + + return await client.SendAsync(request); + } + + // The channel has no key yet: nobody gets in. + Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, (await PostAsync("chiave", soap)).StatusCode); + + var channels = app.Services.GetRequiredService(); + await channels.SaveAsync(Root, company, new EInvoiceChannelInput { Code = "SDICOOP", Enabled = true, Endpoint = "https://sdi.example.test/trasmissione", ApiKey = "chiave-di-prova" }); + Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, (await PostAsync("chiave-sbagliata", soap)).StatusCode); + Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, (await PostAsync(null, soap)).StatusCode); + Assert.AreEqual(System.Net.HttpStatusCode.BadRequest, (await PostAsync("chiave-di-prova", "")).StatusCode); + Assert.AreEqual(System.Net.HttpStatusCode.NotFound, (await client.PostAsync("sdicoop/NESSUNA", new StringContent(soap))).StatusCode); + + var accepted = await PostAsync("chiave-di-prova", soap); + Assert.AreEqual(System.Net.HttpStatusCode.OK, accepted.StatusCode, await accepted.Content.ReadAsStringAsync()); + StringAssert.Contains(await accepted.Content.ReadAsStringAsync(), "Envelope"); + var history = await service.HistoryAsync(Root, company, waiting.Family, waiting.DocumentId); + Assert.AreEqual(EInvoiceStatus.Delivered, history[0].Invoice.Status); + Assert.AreEqual("RC", history[0].Notifications[^1].Code); + await app.StopAsync(); + } + } + private static async Task SeedAsync(IServiceProvider services, string company) { var activation = await services.GetRequiredService().ActivateAsync(Root, "KH-TEST-ALL-0000-9999");