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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 12:54:09 +01:00
1 parent 9d7cb9e71f
commit b78260beb0
21 files changed
+2414 -6

No files matched your search

@@ -100,8 +100,9 @@ public sealed partial class EInvoiceService
pending.Count(p => p.Status == DocumentStatus.Issued), pending.Count(p => p.Status == DocumentStatus.Issued),
all.Count(e => e.Status == EInvoiceStatus.Generated), all.Count(e => e.Status == EInvoiceStatus.Generated),
all.Count(e => e.Status == EInvoiceStatus.Sent), 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 => EInvoiceStates.NeedsAction(e.Status)),
all.Count(e => e.Status is EInvoiceStatus.NotDelivered or EInvoiceStatus.Undeliverable),
received); received);
IEnumerable<EInvoice> rows = filter.View switch IEnumerable<EInvoice> rows = filter.View switch
@@ -160,6 +161,30 @@ public sealed partial class EInvoiceService
return result; return result;
} }
/// <summary>The notifications received in a period, newest first (files not loaded).</summary>
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The notifications.</returns>
public async Task<IReadOnlyList<EInvoiceNotification>> 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<EInvoiceNotification, long>()
.ListAsync(Query.For<EInvoiceNotification>().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;
}
/// <summary>Checks the file a document would have, without writing it.</summary> /// <summary>Checks the file a document would have, without writing it.</summary>
/// <param name="actor">Who checks: needs <c>einvoice.document.read</c>.</param> /// <param name="actor">Who checks: needs <c>einvoice.document.read</c>.</param>
/// <param name="companyCode">The company.</param> /// <param name="companyCode">The company.</param>
@@ -125,10 +125,11 @@ public sealed record EInvoiceFilter(EInvoiceView View = EInvoiceView.Issued, EIn
/// <param name="ToGenerate">Issued documents without a file.</param> /// <param name="ToGenerate">Issued documents without a file.</param>
/// <param name="ToSend">Files generated and not sent.</param> /// <param name="ToSend">Files generated and not sent.</param>
/// <param name="Waiting">Sent, waiting for the receipt.</param> /// <param name="Waiting">Sent, waiting for the receipt.</param>
/// <param name="Delivered">Delivered or issued (RC, MC, NE EC01, DT, AT).</param> /// <param name="Delivered">Delivered or accepted (RC, NE EC01, DT).</param>
/// <param name="Rejected">Rejected by the SDI or refused by a public administration.</param> /// <param name="Rejected">Rejected by the SDI or refused by a public administration.</param>
/// <param name="NotDelivered">Issued but not delivered: in the reserved area of the customer (MC, AT).</param>
/// <param name="Received">Invoices received to register.</param> /// <param name="Received">Invoices received to register.</param>
public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int Received); public sealed record EInvoiceCounters(int ToGenerate, int ToSend, int Waiting, int Delivered, int Rejected, int NotDelivered, int Received);
/// <summary>The dashboard.</summary> /// <summary>The dashboard.</summary>
/// <param name="Rows">The e-invoices of the view.</param> /// <param name="Rows">The e-invoices of the view.</param>
@@ -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;
/// <summary>The answer to a push of the exchange system.</summary>
/// <param name="StatusCode">The HTTP status.</param>
/// <param name="ContentType">The content type.</param>
/// <param name="Body">The body.</param>
public sealed record SdiPushAnswer(int StatusCode, string ContentType, string Body);
/// <summary>
/// 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 <c>X-Khaemhat-SdiCoop-Key</c>); 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.
/// </summary>
public sealed partial class SdiPushService
{
/// <summary>The header with the key of the channel.</summary>
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<SdiPushService> _logger;
/// <summary>Creates the service.</summary>
/// <param name="companies">The companies.</param>
/// <param name="license">The licence.</param>
/// <param name="factory">The units of work.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="secrets">Opens the key of the channel.</param>
/// <param name="polling">Sorts the files received.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The log (section SDI).</param>
public SdiPushService(
ICompanyRegistry companies, ILicenseGate license, IUnitOfWorkFactory factory, CompanyFiscalContext packs, ISecretProtector secrets,
EInvoicePollingService polling, TimeProvider clock, ILogger<SdiPushService> 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;
}
/// <summary>Takes a push.</summary>
/// <param name="companyCode">The company in the address.</param>
/// <param name="key">The key in the header.</param>
/// <param name="contentType">The content type.</param>
/// <param name="body">The body.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The answer.</returns>
public async Task<SdiPushAnswer> 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<IEInvoicePushReader>() 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<EInvoiceChannelSetting, long>().ListAsync(Query.For<EInvoiceChannelSetting>().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);
}
@@ -278,3 +278,30 @@ public interface IEInvoiceChannels
/// <returns>The channel, or <see langword="null"/>.</returns> /// <returns>The channel, or <see langword="null"/>.</returns>
EInvoiceChannel? Find(string code); EInvoiceChannel? Find(string code);
} }
/// <summary>What the exchange system pushed to the company over HTTP: the files and how to answer.</summary>
/// <param name="ExchangeId">The identifier of the exchange system.</param>
/// <param name="Files">The files: a notification, or an invoice with its metadata.</param>
/// <param name="AnswerContentType">The content type of the answer.</param>
/// <param name="Answer">The body of the answer.</param>
public sealed record EInvoicePush(string? ExchangeId, IReadOnlyList<(string FileName, byte[] Content)> Files, string AnswerContentType, string Answer);
/// <summary>
/// Reads what the exchange system sends to the web services of the company (Italy: the SdICoop operations
/// <c>RiceviFatture</c>, <c>RicevutaConsegna</c>, <c>NotificaScarto</c> …), for the channel that receives them.
/// </summary>
public interface IEInvoicePushReader
{
/// <summary>The code of the channel the pushes belong to (Italy: <c>SDICOOP</c>).</summary>
string Channel { get; }
/// <summary>Reads a request.</summary>
/// <param name="contentType">The content type of the HTTP request.</param>
/// <param name="body">The body.</param>
/// <returns>The files with the answer, or <see langword="null"/> when the request is not one of the exchange system.</returns>
EInvoicePush? Read(string? contentType, byte[] body);
/// <summary>The answer to a request that could not be read.</summary>
/// <returns>The content type and the body.</returns>
(string ContentType, string Body) Refusal();
}
@@ -22,6 +22,7 @@ public sealed class ItalyFiscalPack : FiscalPackBase
AddFeature<IEInvoiceValidator>(new FatturaPaValidator()); AddFeature<IEInvoiceValidator>(new FatturaPaValidator());
AddFeature<IEInvoiceReceiptReader>(new SdiReceiptReader()); AddFeature<IEInvoiceReceiptReader>(new SdiReceiptReader());
AddFeature<IEInvoiceChannels>(new Sdi.SdiChannels()); AddFeature<IEInvoiceChannels>(new Sdi.SdiChannels());
AddFeature<IEInvoicePushReader>(new Sdi.SdiCoopPushReader());
AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt()); AddFeature<IIncomingInvoiceRules>(new IncomingInvoiceRulesIt());
AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt()); AddFeature<ISelfInvoiceRules>(new SelfInvoiceRulesIt());
AddFeature<IWithholdingRules>(new WithholdingRulesIt()); AddFeature<IWithholdingRules>(new WithholdingRulesIt());
@@ -0,0 +1,24 @@
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Sdi;
/// <summary>The SdICoop messages the SDI sends to the company, as pushes of the channel <c>SDICOOP</c> (issue #76).</summary>
public sealed class SdiCoopPushReader : IEInvoicePushReader
{
private const string Soap = "text/xml; charset=utf-8";
/// <inheritdoc />
public string Channel => SdiCoopTransport.ChannelCode;
/// <inheritdoc />
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;
}
/// <inheritdoc />
public (string ContentType, string Body) Refusal() => (Soap, SdiCoopMessages.Answer(null));
}
@@ -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. *@
<KhPageTitle Text="@T["EInvoicing.Conservation.Title"]" Icon="folder" />
<EInvoiceGuard Permission="@EInvoicePermissions.Read">
<div class="phead">
<div>
<div class="crumbs"><a href="@EInvoicingScreens.BasePath">@T["Shell.Menu.EInvoicing"]</a> / @T["EInvoicing.Conservation.Title"]</div>
<h1>@T["EInvoicing.Conservation.Heading"]</h1>
<div class="sub">@T["EInvoicing.Conservation.Hint"]</div>
</div>
</div>
<div class="kh-remit">
<KhPanel Title="@T["EInvoicing.Conservation.New"]" Icon="folder">
<div class="form plain">
<KhDateBox Label="@T["EInvoicing.Fields.From"]" Name="cfrom" @bind-Value="_from" Required="true" Span="6" />
<KhDateBox Label="@T["EInvoicing.Fields.To"]" Name="cto" @bind-Value="_to" Required="true" Span="6" />
</div>
<p class="muted sm">@T["EInvoicing.Conservation.Contents"]</p>
<button type="button" class="btn primary" disabled="@(_busy || _from is null || _to is null)" @onclick="ExportAsync"><KhIcon Name="download" /> @T["EInvoicing.Conservation.Export"]</button>
</KhPanel>
<KhPanel Title="@T["EInvoicing.Conservation.History"]" Icon="history" Tight="true">
@if (_exports.Count == 0)
{
<p class="kh-wempty">@T["EInvoicing.Conservation.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["EInvoicing.Conservation.History"]">
<thead>
<tr>
<th scope="col">@T["EInvoicing.Conservation.Period"]</th>
<th scope="col">@T["EInvoicing.Conservation.File"]</th>
<th scope="col" class="num">@T["EInvoicing.Conservation.Files"]</th>
<th scope="col" class="num">@T["EInvoicing.Conservation.Size"]</th>
<th scope="col">@T["EInvoicing.Conservation.Hash"]</th>
</tr>
</thead>
<tbody>
@foreach (var x in _exports)
{
<tr>
<td class="kh-nowrap">@T.Date(x.FromDate) – @T.Date(x.ToDate)</td>
<td class="code">@x.FileName</td>
<td class="num">@x.FileCount</td>
<td class="num">@Size(x.Size)</td>
<td class="code kh-w260" title="@x.Hash">@x.Hash[..16]…</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["EInvoicing.Conservation.Footer"]</span></div>
</KhPanel>
</div>
</EInvoiceGuard>
@code {
private IReadOnlyList<ConservationExport> _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));
/// <inheritdoc />
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;
}
}
}
@@ -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. *@
<KhPageTitle Text="@T["EInvoicing.Channels.Title"]" Icon="server" />
<EInvoiceGuard Permission="@EInvoicePermissions.ChannelManage">
<div class="phead">
<div>
<div class="crumbs"><a href="@EInvoicingScreens.BasePath">@T["Shell.Menu.EInvoicing"]</a> / @T["EInvoicing.Channels.Title"]</div>
<h1>@T["EInvoicing.Channels.Heading"]</h1>
<div class="sub">@T["EInvoicing.Channels.Hint"]</div>
</div>
<button type="button" class="btn" disabled="@_busy" @onclick="PollAsync"><KhIcon Name="refresh" /> @T["EInvoicing.Dashboard.PollNow"]</button>
</div>
<div class="kh-sdi-channels">
@foreach (var ch in _channels)
{
var s = ch.Setting;
<button type="button" class="modcard kh-sdi-card @(s.Enabled && !s.Paused ? "on" : null) @(_code == ch.Code ? "sel" : null)" @onclick="() => Select(ch)">
<span class="mh">
<span class="ico-box"><KhIcon Name="@IconOf(ch.Code)" /></span>
<span>@ch.Name</span>
</span>
<span class="md">@T["EInvoicing.Channels.About." + ch.Code]</span>
<span class="mf">
<KhBadge Tone="@ToneOf(s)">@T[StateOf(s)]</KhBadge>
@if (s.LastPollAt is { } polled)
{
<span>@T.Format("EInvoicing.Channels.LastPoll", T.DateTime(polled, TimeZoneInfo.Local))</span>
}
</span>
@if (s.LastPollFailed && !string.IsNullOrEmpty(s.LastPollMessage))
{
<span class="neg sm">@s.LastPollMessage</span>
}
</button>
}
</div>
@if (_selected is { } sel && _form is { } f)
{
<KhPanel Title="@T.Format("EInvoicing.Channels.Settings", sel.Name)" Icon="settings">
<Actions>
<KhBadge Tone="@ToneOf(sel.Setting)">@T[StateOf(sel.Setting)]</KhBadge>
</Actions>
<ChildContent>
<div class="form">
<KhSwitch Label="@T["EInvoicing.Channels.Enabled"]" Name="enabled" @bind-Value="f.Enabled" Span="6" />
@if (Kind == "PEC")
{
<KhTextBox Label="@T["EInvoicing.Channels.Mailbox"]" Name="mailbox" @bind-Value="f.Mailbox" MaxLength="200" Span="6" />
<KhTextBox Label="@T["EInvoicing.Channels.SmtpHost"]" Name="smtp" @bind-Value="f.SmtpHost" MaxLength="200" Span="4" />
<KhNumberBox Label="@T["EInvoicing.Channels.SmtpPort"]" Name="smtpport" @bind-Value="f.SmtpPort" Decimals="0" Min="1" Max="65535" Span="2" />
<KhTextBox Label="@T["EInvoicing.Channels.ImapHost"]" Name="imap" @bind-Value="f.ImapHost" MaxLength="200" Span="4" />
<KhNumberBox Label="@T["EInvoicing.Channels.ImapPort"]" Name="imapport" @bind-Value="f.ImapPort" Decimals="0" Min="1" Max="65535" Span="2" />
<KhTextBox Label="@T["EInvoicing.Channels.UserName"]" Name="user" @bind-Value="f.UserName" MaxLength="200" Span="6" />
<KhTextBox Label="@Secret("EInvoicing.Channels.Password", sel.HasPassword)" Name="password" Type="password" @bind-Value="f.Password" MaxLength="200" Span="6" />
<KhTextBox Label="@T["EInvoicing.Channels.ExchangeAddress"]" Name="sdiaddress" @bind-Value="f.ExchangeAddress" MaxLength="200" Span="6" />
<KhTextBox Label="@T["EInvoicing.Channels.ArchiveFolder"]" Name="archive" @bind-Value="f.ArchiveFolder" MaxLength="100" Span="6" />
<KhSwitch Label="@T["EInvoicing.Channels.Tls"]" Name="tls" @bind-Value="f.Tls" Span="6" />
}
else
{
<KhTextBox Label="@T["EInvoicing.Channels.Endpoint"]" Name="endpoint" @bind-Value="f.Endpoint" MaxLength="300" Span="12" />
@if (Kind == "SDICOOP")
{
<KhField Label="@Secret("EInvoicing.Channels.Certificate", sel.HasCertificate)" Span="6">
<label class="btn kh-filebtn">
<KhIcon Name="upload" /> @(f.CertificateName ?? T["EInvoicing.Channels.CertificatePick"])
<InputFile OnChange="ReadCertificateAsync" accept=".p12,.pfx" disabled="@_busy" />
</label>
</KhField>
<KhTextBox Label="@Secret("EInvoicing.Channels.CertificatePassword", sel.HasCertificate)" Name="certpassword" Type="password" @bind-Value="f.CertificatePassword" MaxLength="200" Span="6" />
<KhTextBox Label="@Secret("EInvoicing.Channels.PushKey", sel.HasApiKey)" Name="pushkey" Type="password" @bind-Value="f.ApiKey" MaxLength="200" Span="6" />
}
else if (Kind == "INTA")
{
<KhTextBox Label="@Secret("EInvoicing.Channels.ApiKey", sel.HasApiKey)" Name="apikey" Type="password" @bind-Value="f.ApiKey" MaxLength="400" Span="12" />
}
else
{
<KhTextBox Label="@T["EInvoicing.Channels.UserName"]" Name="user" @bind-Value="f.UserName" MaxLength="200" Span="6" />
<KhTextBox Label="@Secret("EInvoicing.Channels.Password", sel.HasPassword)" Name="password" Type="password" @bind-Value="f.Password" MaxLength="200" Span="6" />
}
<KhSwitch Label="@T["EInvoicing.Channels.TestEnvironment"]" Name="testenv" @bind-Value="f.TestEnvironment" Span="6" />
}
</div>
@if (sel.Setting.LastCheckAt is { } checkedAt)
{
<p class="kh-sdi-check @(sel.Setting.LastCheckOk == true ? "ok" : "no")">
<KhIcon Name="@(sel.Setting.LastCheckOk == true ? "check-circle" : "x-circle")" />
@T.Format("EInvoicing.Channels.LastCheck", T.DateTime(checkedAt, TimeZoneInfo.Local)) · @sel.Setting.LastCheckMessage
</p>
}
<div class="kh-sdi-actions">
<button type="button" class="btn" disabled="@(_busy || !sel.Setting.Enabled)" @onclick="CheckAsync"><KhIcon Name="link" /> @T["EInvoicing.Channels.Test"]</button>
@if (sel.Setting.Enabled)
{
<button type="button" class="btn" disabled="@_busy" @onclick="PauseAsync">
<KhIcon Name="@(sel.Setting.Paused ? "zap" : "clock")" /> @T[sel.Setting.Paused ? "EInvoicing.Channels.Resume" : "EInvoicing.Channels.Pause"]
</button>
}
<span class="grow"></span>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveAsync"><KhIcon Name="save" /> @T["Common.Save"]</button>
</div>
</ChildContent>
</KhPanel>
}
<KhPanel Title="@T["EInvoicing.Routing.Title"]" Icon="filter" Tight="true">
<Actions>
<KhIconButton Icon="plus" Text="@T["EInvoicing.Routing.Add"]" Disabled="_busy" OnClick="NewRule" />
</Actions>
<ChildContent>
@if (_rules.Count == 0)
{
<p class="kh-wempty">@T["EInvoicing.Routing.None"]</p>
}
else
{
<table class="grid" aria-label="@T["EInvoicing.Routing.Title"]">
<thead>
<tr>
<th scope="col" class="num">#</th>
<th scope="col">@T["EInvoicing.Routing.Condition"]</th>
<th scope="col">@T["EInvoicing.Fields.Channel"]</th>
<th scope="col">@T["EInvoicing.Routing.Fallback"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var r in _rules)
{
<tr class="@(r.Disabled ? "kh-off" : null)">
<td class="num">@r.Position</td>
<td>@RuleText(r) @(r.Disabled ? " · " + T["EInvoicing.Routing.Disabled"] : null)</td>
<td><b>@ChannelName(r.ChannelCode)</b></td>
<td>@(r.FallbackChannelCode is { } fb ? ChannelName(fb) : "—")</td>
<td class="kh-acts">
<KhIconButton Icon="edit" Text="@T["Common.Edit"]" Disabled="_busy" OnClick="() => EditRule(r)" />
<KhIconButton Icon="trash" Text="@T["Common.Delete"]" Disabled="_busy" OnClick="() => DeleteRuleAsync(r)" />
</td>
</tr>
}
</tbody>
</table>
}
<p class="kh-note"><KhIcon Name="info" /> @T["EInvoicing.Routing.Note"]</p>
</ChildContent>
</KhPanel>
<KhDialog Open="_rule is not null" Title="@T[_rule?.Id > 0 ? "EInvoicing.Routing.Edit" : "EInvoicing.Routing.Add"]" Icon="filter" OnClose="() => _rule = null">
<ChildContent>
@if (_rule is { } rule)
{
<div class="form plain">
<KhNumberBox Label="@T["EInvoicing.Routing.Position"]" Name="position" @bind-Value="_rulePosition" Decimals="0" Min="0" Max="9999" Span="4" />
<KhSelect TValue="SdiRoutingCondition" Label="@T["EInvoicing.Routing.Condition"]" Name="condition" Options="Conditions" @bind-Value="rule.Condition" Span="8" />
@if (rule.Condition is SdiRoutingCondition.Party or SdiRoutingCondition.DocumentType or SdiRoutingCondition.DailyVolume)
{
<KhTextBox Label="@T["EInvoicing.Routing.Value." + rule.Condition]" Name="value" @bind-Value="rule.Value" MaxLength="40" Span="12" />
}
<KhSelect TValue="string" Label="@T["EInvoicing.Fields.Channel"]" Name="channel" Options="ChannelOptions" @bind-Value="rule.ChannelCode" Span="6" />
<KhSelect TValue="string" Label="@T["EInvoicing.Routing.Fallback"]" Name="fallback" Options="ChannelOptions" Empty="—" @bind-Value="rule.FallbackChannelCode" Span="6" />
<KhCheck Label="@T["EInvoicing.Routing.Disabled"]" Name="disabled" @bind-Value="rule.Disabled" Span="12" />
</div>
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _rule = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="SaveRuleAsync"><KhIcon Name="save" /> @T["Common.Save"]</button>
</Footer>
</KhDialog>
</EInvoiceGuard>
@code {
private IReadOnlyList<EInvoiceChannelView> _channels = [];
private IReadOnlyList<SdiRoutingRule> _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<KhOption<SdiRoutingCondition>> Conditions => EInvoicingScreens.Choices<SdiRoutingCondition>(T);
private IReadOnlyList<KhOption<string>> ChannelOptions => [.. _channels.Select(c => new KhOption<string>(c.Code, c.Name))];
/// <inheritdoc />
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<Actor, string, Task> 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;
}
}
/// <summary>What the form edits; secrets start empty and are sent only when typed.</summary>
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,
};
}
}
@@ -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. *@
<KhPageTitle Text="@T["EInvoicing.Dashboard.Title"]" Icon="file-check" />
<EInvoiceGuard Permission="@EInvoicePermissions.Read">
<div class="phead">
<div>
<div class="crumbs"><a href="@EInvoicingScreens.BasePath">@T["Shell.Menu.EInvoicing"]</a> / @T["EInvoicing.Dashboard.Crumb"]</div>
<h1>@T["EInvoicing.Dashboard.Heading"]</h1>
<div class="sub">@T["EInvoicing.Dashboard.Hint"]</div>
</div>
@if (_dashboard?.Counters.Received is > 0 and var received)
{
<a class="btn" href="@EInvoicingScreens.InboxPath"><KhIcon Name="mail" /> @T.Format("EInvoicing.Dashboard.ReceivedLink", received)</a>
}
</div>
@if (_dashboard is { } d)
{
var c = d.Counters;
<div class="kh-aging kh-sdi-tiles">
<KhTile Title="@T["EInvoicing.Tiles.ToGenerate"]" Value="@Count(c.ToGenerate)" Tone="KhTone.Neutral"><Detail>@T["EInvoicing.Tiles.ToGenerateHint"]</Detail></KhTile>
<KhTile Title="@T["EInvoicing.Tiles.ToSend"]" Value="@Count(c.ToSend)" Tone="KhTone.Accent"><Detail>@T["EInvoicing.Tiles.ToSendHint"]</Detail></KhTile>
<KhTile Title="@T["EInvoicing.Tiles.Waiting"]" Value="@Count(c.Waiting)" Tone="KhTone.Info"><Detail>@T["EInvoicing.Tiles.WaitingHint"]</Detail></KhTile>
<KhTile Title="@T["EInvoicing.Tiles.Delivered"]" Value="@Count(c.Delivered)" Tone="KhTone.Ok"><Detail>@T["EInvoicing.Tiles.DeliveredHint"]</Detail></KhTile>
<KhTile Title="@T["EInvoicing.Tiles.Rejected"]" Value="@Count(c.Rejected)" Tone="KhTone.Error"><Detail>@T["EInvoicing.Tiles.RejectedHint"]</Detail></KhTile>
<KhTile Title="@T["EInvoicing.Tiles.NotDelivered"]" Value="@Count(c.NotDelivered)" Tone="KhTone.Warning"><Detail>@T["EInvoicing.Tiles.NotDeliveredHint"]</Detail></KhTile>
</div>
}
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<div class="kh-seg" role="group" aria-label="@T["EInvoicing.Dashboard.View"]">
<button type="button" class="@(_view == EInvoiceView.Issued ? "on" : null)" @onclick="() => SetViewAsync(EInvoiceView.Issued)">@T["EInvoicing.Dashboard.Issued"]</button>
<button type="button" class="@(_view == EInvoiceView.SelfInvoices ? "on" : null)" @onclick="() => SetViewAsync(EInvoiceView.SelfInvoices)">@T["EInvoicing.Dashboard.SelfInvoices"]</button>
<button type="button" class="@(_view == EInvoiceView.ToDo ? "on" : null)" @onclick="() => SetViewAsync(EInvoiceView.ToDo)">@T["EInvoicing.Dashboard.ToDo"]</button>
</div>
<input type="search" class="in kh-searchbox" placeholder="@T["EInvoicing.Dashboard.Search"]" aria-label="@T["EInvoicing.Dashboard.Search"]" value="@_search" @onchange="SearchAsync" />
<KhSelect TValue="EInvoiceStatus?" Label="@T["EInvoicing.Fields.Status"]" Name="status" Options="Statuses" Empty="@T["EInvoicing.All"]" Value="_status" ValueChanged="SetStatusAsync" />
<KhDateBox Label="@T["EInvoicing.Fields.From"]" Name="from" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["EInvoicing.Fields.To"]" Name="to" Value="_to" ValueChanged="SetToAsync" />
<span class="grow"></span>
@if (CanSend)
{
<label class="btn kh-filebtn">
<KhIcon Name="upload" /> @T["EInvoicing.Dashboard.ImportReceipts"]
<InputFile OnChange="ImportReceiptsAsync" multiple accept=".xml,.p7m,.zip" disabled="@_busy" />
</label>
@if (Session.Permissions.Allows(EInvoicePermissions.ChannelManage))
{
<button type="button" class="btn" disabled="@_busy" @onclick="PollAsync"><KhIcon Name="refresh" /> @T["EInvoicing.Dashboard.PollNow"]</button>
}
<button type="button" class="btn" disabled="@(_busy || _files.Count == 0)" @onclick="SendAsync"><KhIcon Name="send" /> @T.Format("EInvoicing.Dashboard.Send", _files.Count)</button>
<button type="button" class="btn primary" disabled="@(_busy || _docs.Count == 0)" @onclick="GenerateAndSendAsync"><KhIcon Name="zap" /> @T.Format("EInvoicing.Dashboard.GenerateAndSend", _docs.Count)</button>
}
</div>
@if (_dashboard is { } dash)
{
@if (dash.Pending.Count > 0)
{
<h3 class="kh-subhead kh-pad-x">@T.Format("EInvoicing.Dashboard.PendingTitle", dash.Pending.Count)</h3>
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["EInvoicing.Dashboard.PendingTitle"]">
<thead>
<tr>
<th scope="col" class="chkcol"><input type="checkbox" aria-label="@T["EInvoicing.SelectAll"]" checked="@(_docs.Count == dash.Pending.Count)" @onchange="e => ToggleAllDocs(e.Value is true)" /></th>
<th scope="col">@T["EInvoicing.Fields.Document"]</th>
<th scope="col">@T["EInvoicing.Fields.Date"]</th>
<th scope="col">@T["EInvoicing.Fields.Party"]</th>
<th scope="col" class="num">@T["EInvoicing.Fields.Total"]</th>
<th scope="col">@T["EInvoicing.Fields.DocumentStatus"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var p in dash.Pending)
{
var key = (p.Family, p.DocumentId);
<tr class="@(p.Status == DocumentStatus.SdiRejected ? "err" : _docs.Contains(key) ? "sel" : null)">
<td class="chkcol"><input type="checkbox" aria-label="@(T["EInvoicing.Select"] + " " + p.Number)" checked="@_docs.Contains(key)" @onchange="e => ToggleDoc(key, e.Value is true)" /></td>
<td class="code">
@if (SalesScreens.RecordUrl(p.Kind, p.DocumentId) is { } url)
{
<a href="@url">@SalesScreens.KindName(T, p.Kind) @p.Number</a>
}
else
{
@(SalesScreens.KindName(T, p.Kind) + " " + p.Number)
}
</td>
<td>@T.Date(p.Date)</td>
<td>@p.PartyName</td>
<td class="num">@T.Money(p.Total)</td>
<td><KhBadge Tone="@(p.Status == DocumentStatus.SdiRejected ? KhTone.Error : KhTone.Neutral)">@T["Sales.States." + p.Status]</KhBadge></td>
<td class="kh-acts">
<KhIconButton Icon="shield-check" Text="@T["EInvoicing.Dashboard.Check"]" Disabled="_busy" OnClick="() => CheckAsync(p)" />
<KhIconButton Icon="history" Text="@T["EInvoicing.Dashboard.History"]" Disabled="_busy" OnClick="() => HistoryAsync(p.Family, p.DocumentId, p.Number)" />
</td>
</tr>
}
</tbody>
</table>
</div>
@if (dash.Rows.Count > 0)
{
<h3 class="kh-subhead kh-pad-x">@T["EInvoicing.Dashboard.FilesTitle"]</h3>
}
}
@if (dash.Rows.Count == 0 && dash.Pending.Count == 0)
{
<p class="kh-wempty">@T[_view == EInvoiceView.ToDo ? "EInvoicing.Dashboard.NothingToDo" : "EInvoicing.Dashboard.None"]</p>
}
else if (dash.Rows.Count > 0)
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["EInvoicing.Dashboard.FilesTitle"]">
<thead>
<tr>
<th scope="col" class="chkcol"><span class="sr-only">@T["EInvoicing.Select"]</span></th>
<th scope="col">@T["EInvoicing.Fields.Document"]</th>
<th scope="col">@T["EInvoicing.Fields.Date"]</th>
<th scope="col">@T[_view == EInvoiceView.SelfInvoices ? "EInvoicing.Fields.Supplier" : "EInvoicing.Fields.Customer"]</th>
<th scope="col" class="num">@T["EInvoicing.Fields.Total"]</th>
<th scope="col">@T["EInvoicing.Fields.Type"]</th>
<th scope="col">@T["EInvoicing.Fields.Channel"]</th>
<th scope="col">@T["EInvoicing.Fields.SdiStatus"]</th>
<th scope="col">@T["EInvoicing.Fields.LastMessage"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var row in dash.Rows)
{
var e = row.Invoice;
var sendable = e.Status == EInvoiceStatus.Generated;
<tr class="@(e.Status is EInvoiceStatus.Rejected or EInvoiceStatus.Refused ? "err" : _files.Contains(e.Id) ? "sel" : null)">
<td class="chkcol">
@if (sendable && CanSend)
{
<input type="checkbox" aria-label="@(T["EInvoicing.Select"] + " " + e.FileName)" checked="@_files.Contains(e.Id)" @onchange="ev => ToggleFile(e.Id, ev.Value is true)" />
}
</td>
<td class="code">
@if (SalesScreens.RecordUrl(e.Kind, e.DocumentId) is { } url)
{
<a href="@url">@e.DocumentNumber</a>
}
else
{
@e.DocumentNumber
}
<div class="muted sm kh-mono">@e.FileName</div>
</td>
<td>@T.Date(e.DocumentDate)</td>
<td>@row.PartyName</td>
<td class="num">@T.Money(e.TotalAmount)</td>
<td class="code">@e.DocumentType</td>
<td>@ChannelName(e.ChannelCode)</td>
<td><KhBadge Tone="EInvoicingScreens.ToneOf(e.Status)">@T[EInvoicingScreens.EnumKey(e.Status)]</KhBadge></td>
<td class="kh-w260">
<span class="@(e.Status is EInvoiceStatus.Rejected or EInvoiceStatus.Refused ? "neg" : "muted") sm" title="@e.LastMessage">@EInvoicingScreens.ErrorText(T, e.LastMessage)</span>
@if (e.LastNotificationAt is { } at)
{
<div class="muted sm">@T.DateTime(at, TimeZoneInfo.Local)</div>
}
</td>
<td class="kh-acts">
@if (CanSend && e.Status is EInvoiceStatus.Rejected && SalesScreens.RecordUrl(e.Kind, e.DocumentId) is { } fix)
{
<a class="btn sm" href="@fix"><KhIcon Name="edit" /> @T["EInvoicing.Dashboard.Correct"]</a>
}
@if (CanSend && sendable)
{
<KhIconButton Icon="check" Text="@T["EInvoicing.Dashboard.MarkSent"]" Disabled="_busy" OnClick="() => OpenMarkSent(e)" />
}
<KhIconButton Icon="download" Text="@T["EInvoicing.Dashboard.Xml"]" Disabled="_busy" OnClick="() => DownloadAsync(e.Id)" />
<KhIconButton Icon="printer" Text="@T["EInvoicing.Dashboard.Courtesy"]" Disabled="_busy" OnClick="() => CourtesyAsync(e.Id)" />
<KhIconButton Icon="history" Text="@T["EInvoicing.Dashboard.History"]" Disabled="_busy" OnClick="() => HistoryAsync(e.Family, e.DocumentId, e.DocumentNumber)" />
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["EInvoicing.Dashboard.Footer"]</span></div>
}
else
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
</KhPanel>
<KhDialog Open="_history is not null" Title="@T.Format("EInvoicing.History.Title", _historyNumber)" Icon="history" Size="lg" OnClose="() => _history = null">
<ChildContent>
@if (_history is { Count: 0 })
{
<p class="kh-wempty">@T["EInvoicing.History.None"]</p>
}
else if (_history is { } history)
{
@foreach (var (file, notes) in history)
{
<div class="kh-sdi-file">
<div class="kh-sdi-filehead">
<KhIcon Name="file" />
<b class="kh-mono">@file.FileName</b>
<KhBadge Tone="EInvoicingScreens.ToneOf(file.Status)">@T[EInvoicingScreens.EnumKey(file.Status)]</KhBadge>
@if (file.Superseded)
{
<KhBadge Tone="KhTone.Neutral">@T["EInvoicing.History.Superseded"]</KhBadge>
}
<span class="grow"></span>
<button type="button" class="btn sm" disabled="@_busy" @onclick="() => DownloadAsync(file.Id)"><KhIcon Name="download" /> @T["EInvoicing.Dashboard.XmlShort"]</button>
</div>
<div class="muted sm">
@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)
</div>
@if (notes.Count > 0)
{
<table class="grid kh-sdi-notes" aria-label="@T["EInvoicing.History.Notifications"]">
<tbody>
@foreach (var n in notes)
{
<tr>
<td class="code">@n.Code</td>
<td>@T.DateTime(n.ReceivedAt, TimeZoneInfo.Local)</td>
<td class="kh-sdi-desc">@T["EInvoicing.Codes." + n.Code] @(n.Description is { Length: > 0 } desc ? "· " + desc : null)</td>
<td class="kh-acts"><KhIconButton Icon="download" Text="@n.FileName" Disabled="_busy" OnClick="() => NotificationAsync(n.Id)" /></td>
</tr>
}
</tbody>
</table>
}
</div>
}
}
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _history = null">@T["Common.Close"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_markSent is not null" Title="@T["EInvoicing.Dashboard.MarkSent"]" Icon="check" OnClose="() => _markSent = null">
<ChildContent>
<p>@T.Format("EInvoicing.MarkSent.Text", _markSent?.FileName)</p>
<div class="form plain">
<KhTextBox Label="@T["EInvoicing.MarkSent.ExchangeId"]" Name="sdiid" @bind-Value="_exchangeId" MaxLength="20" Span="12" />
</div>
</ChildContent>
<Footer>
<button type="button" class="btn" @onclick="() => _markSent = null">@T["Common.Cancel"]</button>
<button type="button" class="btn primary" disabled="@_busy" @onclick="MarkSentAsync"><KhIcon Name="check" /> @T["EInvoicing.Dashboard.MarkSent"]</button>
</Footer>
</KhDialog>
<KhDialog Open="_report.Count > 0" Title="@_reportTitle" Icon="info" Size="lg" OnClose="() => _report.Clear()">
<ChildContent>
<ul class="kh-sdi-report">
@foreach (var (ok, title, text) in _report)
{
<li class="@(ok ? "ok" : "no")">
<KhIcon Name="@(ok ? "check-circle" : "x-circle")" />
<div><b>@title</b> <span class="muted">@text</span></div>
</li>
}
</ul>
</ChildContent>
<Footer>
<button type="button" class="btn primary" @onclick="() => _report.Clear()">@T["Common.Close"]</button>
</Footer>
</KhDialog>
</EInvoiceGuard>
@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<long> _files = [];
private bool _busy;
private IReadOnlyList<(EInvoice Invoice, IReadOnlyList<EInvoiceNotification> 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;
/// <summary>The view asked by the address (<c>?vista=da-fare</c>, from the feed of the dashboard).</summary>
[SupplyParameterFromQuery(Name = "vista")]
public string? ViewQuery { get; set; }
private bool CanSend => Session.Permissions.Allows(EInvoicePermissions.Send);
private IReadOnlyList<KhOption<EInvoiceStatus?>> Statuses =>
[.. Enum.GetValues<EInvoiceStatus>().Select(s => new KhOption<EInvoiceStatus?>(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;
/// <inheritdoc />
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<Actor, string, Task> 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;
}
}
}
@@ -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)
{
<p class="muted kh-pad">@T["Common.Loading"]</p>
}
else if (Session.Company is null)
{
<div class="kh-message">
<KhIcon Name="building" Class="lg" />
<h1>@T["EInvoicing.NoCompany"]</h1>
</div>
}
else if (!Session.Licenses.IsModuleActive(ModuleCodes.EInvoicing))
{
<div class="kh-message">
<KhIcon Name="key" Class="lg" />
<h1>@T["EInvoicing.NoModule.Title"]</h1>
<p class="lead">@T["EInvoicing.NoModule.Lead"]</p>
</div>
}
else if (!Session.Permissions.Allows(Permission))
{
<div class="kh-message">
<KhIcon Name="lock" Class="lg" />
<h1>@T["Pages.AccessDenied.Title"]</h1>
<p class="lead">@T["Pages.AccessDenied.Lead"]</p>
<a class="btn" href="./">@T["Common.BackHome"]</a>
</div>
}
else
{
@ChildContent
}
@code {
private bool _loaded;
/// <summary>The permission the page needs.</summary>
[Parameter, EditorRequired]
public string Permission { get; set; } = string.Empty;
/// <summary>The page.</summary>
[Parameter]
public RenderFragment? ChildContent { get; set; }
/// <summary>Whether the page may load its data: company, licence and permission.</summary>
/// <param name="session">The session.</param>
/// <param name="permission">The permission.</param>
/// <returns>True when it may.</returns>
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);
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await Session.EnsureLoadedAsync();
_loaded = true;
}
}
@@ -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. *@
<KhPageTitle Text="@T["EInvoicing.Inbox.Title"]" Icon="mail" />
<EInvoiceGuard Permission="@EInvoicePermissions.InboxRead">
<div class="phead">
<div>
<div class="crumbs"><a href="@EInvoicingScreens.BasePath">@T["Shell.Menu.EInvoicing"]</a> / @T["EInvoicing.Inbox.Title"]</div>
<h1>@T["EInvoicing.Inbox.Heading"]</h1>
<div class="sub">@T["EInvoicing.Inbox.Hint"]</div>
</div>
</div>
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<input type="search" class="in kh-searchbox" placeholder="@T["EInvoicing.Inbox.Search"]" aria-label="@T["EInvoicing.Inbox.Search"]" value="@_search" @onchange="SearchAsync" />
<KhSelect TValue="InboxFileStatus?" Label="@T["EInvoicing.Fields.Status"]" Name="istatus" Options="Statuses" Empty="@T["EInvoicing.All"]" Value="_status" ValueChanged="SetStatusAsync" />
<span class="grow"></span>
@if (CanImport)
{
<label class="btn kh-filebtn">
<KhIcon Name="upload" /> @T["EInvoicing.Inbox.Upload"]
<InputFile OnChange="UploadAsync" multiple accept=".xml,.p7m,.zip" disabled="@_busy" />
</label>
<button type="button" class="btn primary" disabled="@(_busy || _chosen.Count == 0)" @onclick="() => RegisterAsync(_chosen.ToList())">
<KhIcon Name="check" /> @T.Format("EInvoicing.Inbox.Register", _chosen.Count)
</button>
}
</div>
@if (_files.Count == 0)
{
<p class="kh-wempty">@T["EInvoicing.Inbox.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["EInvoicing.Inbox.Title"]">
<thead>
<tr>
<th scope="col" class="chkcol"><span class="sr-only">@T["EInvoicing.Select"]</span></th>
<th scope="col">@T["EInvoicing.Fields.Supplier"]</th>
<th scope="col">@T["EInvoicing.Fields.Document"]</th>
<th scope="col">@T["EInvoicing.Fields.Date"]</th>
<th scope="col" class="num">@T["EInvoicing.Fields.Total"]</th>
<th scope="col">@T["EInvoicing.Fields.Type"]</th>
<th scope="col">@T["EInvoicing.Inbox.ReceivedAt"]</th>
<th scope="col">@T["EInvoicing.Fields.Status"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var f in _files)
{
<tr class="@(f.Status == InboxFileStatus.Unreadable ? "err" : _chosen.Contains(f.Id) ? "sel" : f.Status == InboxFileStatus.Discarded ? "kh-off" : null)">
<td class="chkcol">
@if (CanImport && f.Status == InboxFileStatus.New)
{
<input type="checkbox" aria-label="@(T["EInvoicing.Select"] + " " + f.FileName)" checked="@_chosen.Contains(f.Id)" @onchange="e => Toggle(f.Id, e.Value is true)" />
}
</td>
<td>
<b>@(f.SupplierName ?? "—")</b>
<div class="muted sm">@f.SupplierVat</div>
</td>
<td class="code">
@f.Number
<div class="muted sm kh-mono">@f.FileName</div>
</td>
<td>@(f.DocumentDate is { } date ? T.Date(date) : null)</td>
<td class="num">@(f.TotalAmount is { } total ? T.Money(total) : null)</td>
<td class="code">@f.DocumentType</td>
<td>
@T.DateTime(f.ReceivedAt, TimeZoneInfo.Local)
<div class="muted sm">@(f.ChannelCode == "MANUAL" ? T["EInvoicing.Inbox.Manual"] : f.ChannelCode) @(f.ExchangeId is { } sdi ? "· " + sdi : null)</div>
</td>
<td>
<KhBadge Tone="EInvoicingScreens.ToneOf(f.Status)">@T[EInvoicingScreens.EnumKey(f.Status)]</KhBadge>
@if (!string.IsNullOrEmpty(f.Error))
{
<div class="neg sm">@EInvoicingScreens.ErrorText(T, f.Error)</div>
}
</td>
<td class="kh-acts">
@if (f.PurchaseDocumentId is { } purchase && SalesScreens.RecordUrl(f.DocumentType == "TD04" ? DocumentKind.PurchaseCreditNote : DocumentKind.PurchaseInvoice, purchase) is { } url)
{
<a class="btn sm" href="@url"><KhIcon Name="external" /> @T["EInvoicing.Inbox.Open"]</a>
}
@if (CanImport && f.Status == InboxFileStatus.New)
{
<KhIconButton Icon="check" Text="@T["EInvoicing.Inbox.RegisterOne"]" Disabled="_busy" OnClick="() => RegisterAsync([f.Id])" />
}
@if (CanImport && f.Status is InboxFileStatus.New or InboxFileStatus.Unreadable)
{
<KhIconButton Icon="x" Text="@T["EInvoicing.Inbox.Discard"]" Disabled="_busy" OnClick="() => DiscardAsync(f.Id, true)" />
}
@if (CanImport && f.Status == InboxFileStatus.Discarded)
{
<KhIconButton Icon="undo" Text="@T["EInvoicing.Inbox.Restore"]" Disabled="_busy" OnClick="() => DiscardAsync(f.Id, false)" />
}
<KhIconButton Icon="download" Text="@T["EInvoicing.Dashboard.Xml"]" Disabled="_busy" OnClick="() => DownloadAsync(f.Id, false)" />
@if (f.MetadataFileName is not null)
{
<KhIconButton Icon="paperclip" Text="@T["EInvoicing.Inbox.Metadata"]" Disabled="_busy" OnClick="() => DownloadAsync(f.Id, true)" />
}
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T["EInvoicing.Inbox.Footer"]</span></div>
</KhPanel>
</EInvoiceGuard>
@code {
private IReadOnlyList<EInvoiceInboxFile> _files = [];
private readonly HashSet<long> _chosen = [];
private InboxFileStatus? _status = InboxFileStatus.New;
private string? _search;
private bool _busy;
private bool CanImport => Session.Permissions.Allows(EInvoicePermissions.InboxImport);
private IReadOnlyList<KhOption<InboxFileStatus?>> Statuses =>
[.. Enum.GetValues<InboxFileStatus>().Select(s => new KhOption<InboxFileStatus?>(s, T[EInvoicingScreens.EnumKey(s)]))];
/// <inheritdoc />
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<long> 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<Actor, string, Task> 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;
}
}
}
@@ -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. *@
<KhPageTitle Text="@T["EInvoicing.Notifications.Title"]" Icon="bell" />
<EInvoiceGuard Permission="@EInvoicePermissions.Read">
<div class="phead">
<div>
<div class="crumbs"><a href="@EInvoicingScreens.BasePath">@T["Shell.Menu.EInvoicing"]</a> / @T["EInvoicing.Notifications.Title"]</div>
<h1>@T["EInvoicing.Notifications.Heading"]</h1>
<div class="sub">@T["EInvoicing.Notifications.Hint"]</div>
</div>
</div>
<KhPanel Tight="true">
<div class="filters kh-ledger-filters">
<KhDateBox Label="@T["EInvoicing.Fields.From"]" Name="nfrom" Value="_from" ValueChanged="SetFromAsync" />
<KhDateBox Label="@T["EInvoicing.Fields.To"]" Name="nto" Value="_to" ValueChanged="SetToAsync" />
<KhSelect TValue="string" Label="@T["EInvoicing.Notifications.Code"]" Name="ncode" Options="Codes" Empty="@T["EInvoicing.All"]" @bind-Value="_code" />
</div>
@if (Shown.Count == 0)
{
<p class="kh-wempty">@T["EInvoicing.Notifications.None"]</p>
}
else
{
<div class="gridwrap kh-scrollx">
<table class="grid" aria-label="@T["EInvoicing.Notifications.Title"]">
<thead>
<tr>
<th scope="col">@T["EInvoicing.Notifications.ReceivedAt"]</th>
<th scope="col">@T["EInvoicing.Notifications.Code"]</th>
<th scope="col">@T["EInvoicing.Notifications.InvoiceFile"]</th>
<th scope="col">@T["EInvoicing.Notifications.ExchangeId"]</th>
<th scope="col">@T["EInvoicing.Notifications.Description"]</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
@foreach (var n in Shown)
{
<tr class="@(n.EInvoiceId is null ? "warn" : null)">
<td class="kh-nowrap">@T.DateTime(n.ReceivedAt, TimeZoneInfo.Local)</td>
<td><KhBadge Tone="@ToneOf(n)">@n.Code</KhBadge> <span class="sm">@T["EInvoicing.Codes." + n.Code]</span></td>
<td class="code">@n.InvoiceFileName</td>
<td class="code">@n.ExchangeId</td>
<td class="kh-w260"><span class="muted sm" title="@n.Description">@n.Description</span></td>
<td class="kh-acts"><KhIconButton Icon="download" Text="@n.FileName" Disabled="_busy" OnClick="() => DownloadAsync(n.Id)" /></td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="filters"><span class="muted sm">@T.Format("EInvoicing.Notifications.Footer", Shown.Count)</span></div>
</KhPanel>
</EInvoiceGuard>
@code {
private IReadOnlyList<EInvoiceNotification> _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<EInvoiceNotification> Shown => _code is null ? _rows : [.. _rows.Where(n => n.Code == _code)];
private IReadOnlyList<KhOption<string>> Codes => [.. AllCodes.Select(c => new KhOption<string>(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,
};
/// <inheritdoc />
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;
}
}
}
@@ -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;
/// <summary>What the screens of the electronic invoice share (SPEC §11.9, mockups 058-059): addresses, texts, tones, downloads.</summary>
public static class EInvoicingScreens
{
/// <summary>The address of the area.</summary>
public const string BasePath = "/fatturazione-elettronica";
/// <summary>The address of the invoices received.</summary>
public const string InboxPath = BasePath + "/ricevute";
/// <summary>The address of the channels.</summary>
public const string ChannelsPath = BasePath + "/canali";
/// <summary>The key of the text of an enum value.</summary>
/// <param name="value">The value.</param>
/// <returns>The key.</returns>
public static string EnumKey(Enum value)
{
ArgumentNullException.ThrowIfNull(value);
return "EInvoicing.Enums." + value.GetType().Name + "." + value;
}
/// <summary>The choices of an enum.</summary>
/// <typeparam name="TEnum">The enum.</typeparam>
/// <param name="texts">The texts.</param>
/// <returns>The choices in declaration order.</returns>
public static IReadOnlyList<KhOption<TEnum>> Choices<TEnum>(ITexts texts)
where TEnum : struct, Enum
{
ArgumentNullException.ThrowIfNull(texts);
return [.. Enum.GetValues<TEnum>().Select(v => new KhOption<TEnum>(v, texts[EnumKey(v)]))];
}
/// <summary>The tone of the state of an e-invoice.</summary>
/// <param name="status">The state.</param>
/// <returns>The tone.</returns>
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,
};
/// <summary>The tone of the state of a received file.</summary>
/// <param name="status">The state.</param>
/// <returns>The tone.</returns>
public static KhTone ToneOf(InboxFileStatus status) => status switch
{
InboxFileStatus.New => KhTone.Info,
InboxFileStatus.Registered => KhTone.Ok,
InboxFileStatus.Unreadable => KhTone.Error,
_ => KhTone.Neutral,
};
/// <summary>The text of an error code, or the code itself.</summary>
/// <param name="texts">The texts.</param>
/// <param name="code">The code (or a message of a channel).</param>
/// <returns>The text.</returns>
public static string ErrorText(ITexts texts, string? code)
{
ArgumentNullException.ThrowIfNull(texts);
return string.IsNullOrEmpty(code) ? string.Empty : texts.Contains(code) ? texts[code] : code;
}
/// <summary>The text of the errors of a refused operation.</summary>
/// <param name="texts">The texts.</param>
/// <param name="exception">The refusal.</param>
/// <returns>The messages.</returns>
public static string Errors(ITexts texts, ValidationFailedException exception) => LedgerScreens.Errors(texts, exception);
/// <summary>The problems of a file as one line each: where, and what.</summary>
/// <param name="texts">The texts.</param>
/// <param name="problems">The problems.</param>
/// <returns>The text.</returns>
public static string Problems(ITexts texts, IEnumerable<EInvoiceProblem> 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)));
}
/// <summary>Gives the browser a file to save.</summary>
/// <param name="js">The interop.</param>
/// <param name="fileName">The name.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="content">The content.</param>
/// <returns>A task.</returns>
public static Task DownloadAsync(IJSRuntime js, string fileName, string mediaType, byte[] content) =>
LedgerScreens.DownloadAsync(js, new Khaemhat.Application.Ledger.LedgerFile(fileName, mediaType, content));
/// <summary>The media type of a file by its extension.</summary>
/// <param name="fileName">The name.</param>
/// <returns>The media type.</returns>
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";
}
+1
View File
@@ -120,6 +120,7 @@ public static class KhaemhatApp
app.MapCompanySwitch(); app.MapCompanySwitch();
app.MapHelp(); app.MapHelp();
app.MapFiles(); app.MapFiles();
app.MapSdiPush();
app.MapRazorComponents<App>() app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode(); .AddInteractiveServerRenderMode();
@@ -180,6 +180,7 @@ internal static class KhaemhatServices
services.AddSingleton<Khaemhat.Application.EInvoicing.SdiInboxService>(); services.AddSingleton<Khaemhat.Application.EInvoicing.SdiInboxService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.EInvoicePollingService>(); services.AddSingleton<Khaemhat.Application.EInvoicing.EInvoicePollingService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.ConservationExportService>(); services.AddSingleton<Khaemhat.Application.EInvoicing.ConservationExportService>();
services.AddSingleton<Khaemhat.Application.EInvoicing.SdiPushService>();
services.AddSingleton<IScheduledJob, Khaemhat.Application.EInvoicing.EInvoicePollingJob>(); services.AddSingleton<IScheduledJob, Khaemhat.Application.EInvoicing.EInvoicePollingJob>();
// The document engine (ADR 0032): one engine, the copies, a typed service per family. // The document engine (ADR 0032): one engine, the copies, a typed service per family.
+53
View File
@@ -0,0 +1,53 @@
using Khaemhat.Application.EInvoicing;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// The web service the SDI calls (SdICoop, issue #76): <c>POST /sdicoop/{company}</c> takes the invoices of suppliers
/// and the notifications. No session: the request carries the key of the channel in <c>X-Khaemhat-SdiCoop-Key</c>, and
/// the reverse proxy in front of Khaemhat does the mutual TLS with the SDI and adds the header.
/// </summary>
public static class SdiEndpoints
{
/// <summary>The address, followed by the code of the company.</summary>
public const string BasePath = "/sdicoop";
/// <summary>The largest message accepted: an invoice of 5 MB in base64 with its metadata.</summary>
public const int MaxBody = 16 * 1024 * 1024;
/// <summary>Maps the endpoint.</summary>
/// <param name="endpoints">The routes.</param>
/// <returns>The routes.</returns>
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;
}
}
@@ -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)."
}
}
@@ -111,6 +111,9 @@
"EInvoicing": { "EInvoicing": {
"_": "Fatt. elettronica", "_": "Fatt. elettronica",
"Dashboard": "Cruscotto SDI", "Dashboard": "Cruscotto SDI",
"Inbox": "Fatture ricevute",
"Notifications": "Notifiche SDI",
"Conservation": "Conservazione",
"Channels": "Canali di trasmissione", "Channels": "Canali di trasmissione",
"IntentDeclarations": "Dichiarazioni d'intento" "IntentDeclarations": "Dichiarazioni d'intento"
}, },
+22 -3
View File
@@ -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.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.Dunning", "solleciti"), ("Shell.Menu.Finance.Remittances", "distinte"), ("Shell.Menu.Finance.Mandates", "mandati"),
("Shell.Menu.Finance.Reconciliation", "riconciliazione"), ("Shell.Menu.Finance.CashFlow", "flusso-di-cassa")), ("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", EInvoicing(),
("Shell.Menu.EInvoicing.Dashboard", "cruscotto"), ("Shell.Menu.EInvoicing.Channels", "canali"),
("Shell.Menu.EInvoicing.IntentDeclarations", "dichiarazioni-intento")),
Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10", Area("Shell.Menu.Assets", "building", "/cespiti", ModuleCodes.Assets, "assets.asset.read", "M10",
("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")), ("Shell.Menu.Assets.Register", "registro"), ("Shell.Menu.Assets.Depreciation", "ammortamenti")),
Area("Shell.Menu.Services", "wrench", "/servizi", ModuleCodes.Services, null, "M12", 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). // 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] }; private static MenuItem WithChild(MenuItem area, MenuItem child) => area with { Children = [.. area.Children, child] };
/// <summary>The electronic invoice (M9): each page has its own permission; the intent declarations come with M10.</summary>
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, private static MenuItem Area(string key, string icon, string href, string module, string? permission, string? milestone,
params (string Key, string Slug)[] children) => params (string Key, string Slug)[] children) =>
Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children); Area(key, icon, href, module, permission, milestone, MenuAudience.Everyone, children);
+25
View File
@@ -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 { display: block; height: 8px; border-radius: 4px; background: var(--kh-accent); min-width: 2px; }
.kh-cfbar.neg { background: var(--kh-err); } .kh-cfbar.neg { background: var(--kh-err); }
@media (max-width: 1100px) { .kh-remit { grid-template-columns: minmax(0, 1fr); } } @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); }
@@ -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<EInvoiceService>();
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",
$"<IdentificativoSdI>{waiting.ExchangeId ?? "555000111"}</IdentificativoSdI><NomeFile>{waiting.FileName}</NomeFile><Hash>x</Hash>"
+ "<DataOraRicezione>2026-11-12T10:00:00</DataOraRicezione><DataOraConsegna>2026-11-12T10:05:00</DataOraConsegna><MessageId>9</MessageId>");
var stem = waiting.FileName[..waiting.FileName.IndexOf(".xml", StringComparison.Ordinal)];
var soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Body>"
+ "<typ:fileSdI xmlns:typ=\"http://www.fatturapa.gov.it/sdi/ws/trasmissione/v1.0/types\">"
+ $"<IdentificativoSdI>{waiting.ExchangeId ?? "555000111"}</IdentificativoSdI><NomeFile>{stem}_RC_009.xml</NomeFile><File>{Convert.ToBase64String(receipt)}</File>"
+ "</typ:fileSdI></soapenv:Body></soapenv:Envelope>";
using var client = new HttpClient { BaseAddress = address };
async Task<HttpResponseMessage> 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<EInvoiceChannelService>();
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", "<niente/>")).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) private static async Task SeedAsync(IServiceProvider services, string company)
{ {
var activation = await services.GetRequiredService<ILicenseActivationService>().ActivateAsync(Root, "KH-TEST-ALL-0000-9999"); var activation = await services.GetRequiredService<ILicenseActivationService>().ActivateAsync(Root, "KH-TEST-ALL-0000-9999");