The demo company now has its electronic invoices: a paused PEC channel and an intermediary, routing rules, the files of the demo invoices with the notifications the SDI would send (delivered, one rejected, one not delivered, some waiting) read by the fiscal pack as real ones, and three supplier invoices in the inbox with their metadata. Every demo seeder now marks as demo also the rows the services write for it (entries, open items, payments, mandates, statements), so the new DemoDataRemover, driven by the schema of the migrations, removes the demo data and only them; it stops and names the tables when rows entered by users still refer to demo rows. `scripts/seed.sh --remove-demo` exposes it and the seed prints its time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
195 lines
10 KiB
C#
195 lines
10 KiB
C#
using System.Globalization;
|
|
using System.IO.Compression;
|
|
using System.Text;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Application.Tables;
|
|
using Khaemhat.Core.EInvoicing;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Querying;
|
|
|
|
namespace Khaemhat.Application.EInvoicing;
|
|
|
|
/// <summary>A conservation package made.</summary>
|
|
/// <param name="Export">The row that records it.</param>
|
|
/// <param name="Content">The ZIP.</param>
|
|
public sealed record ConservationPackage(ConservationExport Export, byte[] Content);
|
|
|
|
/// <summary>
|
|
/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent
|
|
/// (<c>emesse/</c>), their notifications (<c>notifiche/</c>) and the files received (<c>ricevute/</c>), each as it
|
|
/// travelled, an index <c>indice.csv</c> with the SHA-256 of every file and a <c>LEGGIMI.txt</c>. It is what a
|
|
/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself.
|
|
/// </summary>
|
|
/// <remarks>Permission: <c>einvoice.document.read</c>. Every package made is recorded with its hash.</remarks>
|
|
public sealed class ConservationExportService
|
|
{
|
|
private static readonly DateTimeOffset Stamp = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
|
|
|
private readonly IUnitOfWorkFactory _factory;
|
|
private readonly PermissionService _permissions;
|
|
private readonly TimeProvider _clock;
|
|
|
|
/// <summary>Creates the service.</summary>
|
|
/// <param name="factory">The units of work.</param>
|
|
/// <param name="permissions">The permissions.</param>
|
|
/// <param name="clock">The clock.</param>
|
|
public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(factory);
|
|
ArgumentNullException.ThrowIfNull(permissions);
|
|
ArgumentNullException.ThrowIfNull(clock);
|
|
_factory = factory;
|
|
_permissions = permissions;
|
|
_clock = clock;
|
|
}
|
|
|
|
/// <summary>The packages made, newest first.</summary>
|
|
/// <param name="actor">Who looks: needs <c>einvoice.document.read</c>.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rows.</returns>
|
|
public async Task<IReadOnlyList<ConservationExport>> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
|
|
{
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
return (await uow.Repository<ConservationExport, long>().ListAsync(Query.For<ConservationExport>().OrderByDescending(e => e.Id).Take(50), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
}
|
|
|
|
/// <summary>Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival.</summary>
|
|
/// <param name="actor">Who makes it: needs <c>einvoice.document.read</c>.</param>
|
|
/// <param name="companyCode">The company.</param>
|
|
/// <param name="from">First day.</param>
|
|
/// <param name="to">Last day.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The package.</returns>
|
|
public async Task<ConservationPackage> ExportAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(actor);
|
|
if (to < from || to.DayNumber - from.DayNumber > 731)
|
|
{
|
|
throw new ValidationFailedException(["To:" + EInvoiceErrors.PeriodInvalid]);
|
|
}
|
|
|
|
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
|
|
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
|
|
var sent = (await uow.Repository<EInvoice, long>()
|
|
.ListAsync(Query.For<EInvoice>().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
var notifications = new List<EInvoiceNotification>();
|
|
foreach (var chunk in sent.Select(e => e.Id).Chunk(500))
|
|
{
|
|
var ids = chunk.Select(id => (long?)id).ToList();
|
|
notifications.AddRange((await uow.Repository<EInvoiceNotification, long>()
|
|
.ListAsync(Query.For<EInvoiceNotification>().Where(n => ids.Contains(n.EInvoiceId)).OrderBy(n => n.ReceivedAt), cancellationToken)
|
|
.ConfigureAwait(false)).Items);
|
|
}
|
|
|
|
var start = from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
|
|
var end = to.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc);
|
|
var received = (await uow.Repository<EInvoiceInboxFile, long>()
|
|
.ListAsync(Query.For<EInvoiceInboxFile>().Where(f => f.ReceivedAt >= start && f.ReceivedAt < end && f.Status != InboxFileStatus.Discarded).OrderBy(f => f.ReceivedAt), cancellationToken)
|
|
.ConfigureAwait(false)).Items;
|
|
|
|
var index = new StringBuilder("cartella;file;tipo;documento;data;controparte;identificativo_sdi;stato;sha256\r\n");
|
|
var count = 0;
|
|
using var buffer = new MemoryStream();
|
|
using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
|
|
{
|
|
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
void Add(string folder, string name, byte[] content, string kind, string? number, string? date, string? party, string? exchange, string state)
|
|
{
|
|
var path = Unique(names, folder + "/" + Path.GetFileName(name));
|
|
var entry = zip.CreateEntry(path, CompressionLevel.Optimal);
|
|
entry.LastWriteTime = Stamp;
|
|
using (var stream = entry.Open())
|
|
{
|
|
stream.Write(content);
|
|
}
|
|
|
|
index.Append(string.Join(';', folder, Csv(Path.GetFileName(path)), kind, Csv(number), date, Csv(party), Csv(exchange), state, EInvoiceStore.Hash(content))).Append("\r\n");
|
|
count++;
|
|
}
|
|
|
|
foreach (var e in sent)
|
|
{
|
|
Add("emesse", e.FileName, e.Content, e.DocumentType, e.DocumentNumber, Date(e.DocumentDate), e.RecipientCode, e.ExchangeId, e.Status.ToString());
|
|
}
|
|
|
|
foreach (var n in notifications)
|
|
{
|
|
Add("notifiche", n.FileName, n.Content, n.Code, n.InvoiceFileName, Date(DateOnly.FromDateTime(n.ReceivedAt)), null, n.ExchangeId, n.Outcome ?? string.Empty);
|
|
}
|
|
|
|
foreach (var f in received)
|
|
{
|
|
Add("ricevute", f.FileName, f.Content, f.DocumentType ?? string.Empty, f.Number, f.DocumentDate is { } d ? Date(d) : null, f.SupplierName, f.ExchangeId, f.Status.ToString());
|
|
if (f.Metadata is { Length: > 0 } metadata && f.MetadataFileName is { } metadataName)
|
|
{
|
|
Add("ricevute", metadataName, metadata, "MT", f.Number, null, f.SupplierName, f.ExchangeId, string.Empty);
|
|
}
|
|
}
|
|
|
|
Write(zip, "indice.csv", Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(index.ToString())).ToArray());
|
|
Write(zip, "LEGGIMI.txt", Encoding.UTF8.GetBytes(Readme(company, from, to, sent.Count, notifications.Count, received.Count)));
|
|
}
|
|
|
|
var content = buffer.ToArray();
|
|
var fileName = string.Create(CultureInfo.InvariantCulture, $"conservazione-{company}-{from:yyyyMMdd}-{to:yyyyMMdd}.zip");
|
|
var export = new ConservationExport
|
|
{
|
|
FromDate = from,
|
|
ToDate = to,
|
|
FileCount = count,
|
|
FileName = fileName,
|
|
Hash = EInvoiceStore.Hash(content),
|
|
Size = content.LongLength,
|
|
};
|
|
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
|
|
export.Id = await uow.Repository<ConservationExport, long>().InsertAsync(export, cancellationToken).ConfigureAwait(false);
|
|
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
|
return new ConservationPackage(export, content);
|
|
}
|
|
|
|
private static void Write(ZipArchive zip, string name, byte[] content)
|
|
{
|
|
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
|
|
entry.LastWriteTime = Stamp;
|
|
using var stream = entry.Open();
|
|
stream.Write(content);
|
|
}
|
|
|
|
private static string Unique(HashSet<string> names, string path)
|
|
{
|
|
var candidate = path;
|
|
for (var i = 2; !names.Add(candidate); i++)
|
|
{
|
|
candidate = Path.ChangeExtension(path, null) + "-" + i.ToString(CultureInfo.InvariantCulture) + Path.GetExtension(path);
|
|
}
|
|
|
|
return candidate;
|
|
}
|
|
|
|
private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
|
|
|
|
private static string Csv(string? value) =>
|
|
string.IsNullOrEmpty(value) ? string.Empty : value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
|
|
|
|
private string Readme(string company, DateOnly from, DateOnly to, int sent, int notifications, int received) =>
|
|
string.Create(CultureInfo.InvariantCulture, $"""
|
|
Khaemhat - pacchetto per la conservazione delle fatture elettroniche
|
|
Azienda: {company}
|
|
Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy}
|
|
Creato il: {_clock.GetUtcNow():yyyy-MM-dd HH:mm} UTC
|
|
|
|
emesse/ {sent} fatture inviate al SDI, nel formato in cui sono state trasmesse
|
|
notifiche/ {notifications} ricevute e notifiche del SDI relative alle fatture emesse
|
|
ricevute/ {received} fatture ricevute dai fornitori, con i file metadati (MT)
|
|
indice.csv l'elenco dei file con l'impronta SHA-256 di ciascuno
|
|
|
|
I file sono quelli originali: nessuno è stato modificato. Il pacchetto va consegnato al servizio di
|
|
conservazione (ad esempio il servizio gratuito dell'Agenzia delle Entrate o un conservatore accreditato);
|
|
Khaemhat non sostituisce la conservazione a norma.
|
|
""");
|
|
}
|