using System.Globalization;
using System.IO.Compression;
using System.Text;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.EInvoicing;
/// A conservation package made.
/// The row that records it.
/// The ZIP.
public sealed record ConservationPackage(ConservationExport Export, byte[] Content);
///
/// The package for the conservation of the e-invoices of a period (issue #79): a ZIP with the files sent
/// (emesse/), their notifications (notifiche/) and the files received (ricevute/), each as it
/// travelled, an index indice.csv with the SHA-256 of every file and a LEGGIMI.txt. It is what a
/// conservation service (or the free service of the AdE) takes in; Khaemhat does not replace the conservation itself.
///
/// Permission: einvoice.document.read. Every package made is recorded with its hash.
public sealed class ConservationExportService
{
private static readonly DateTimeOffset Stamp = new(2000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly TimeProvider _clock;
/// Creates the service.
/// The units of work.
/// The permissions.
/// The clock.
public ConservationExportService(IUnitOfWorkFactory factory, PermissionService permissions, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_clock = clock;
}
/// The packages made, newest first.
/// Who looks: needs einvoice.document.read.
/// The company.
/// Cancellation.
/// The rows.
public async Task> ListAsync(Actor actor, string companyCode, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, EInvoicePermissions.Read, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return (await uow.Repository().ListAsync(Query.For().OrderByDescending(e => e.Id).Take(50), cancellationToken)
.ConfigureAwait(false)).Items;
}
/// Makes the package of a period: e-invoices sent by date of the document, files received by date of arrival.
/// Who makes it: needs einvoice.document.read.
/// The company.
/// First day.
/// Last day.
/// Cancellation.
/// The package.
public async Task ExportAsync(Actor actor, string companyCode, DateOnly from, DateOnly to, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
if (to < from || to.DayNumber - from.DayNumber > 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()
.ListAsync(Query.For().Where(e => e.DocumentDate >= from && e.DocumentDate <= to && e.Status != EInvoiceStatus.Generated).OrderBy(e => e.Progressive), cancellationToken)
.ConfigureAwait(false)).Items;
var notifications = new List();
foreach (var chunk in sent.Select(e => e.Id).Chunk(500))
{
var ids = chunk.Select(id => (long?)id).ToList();
notifications.AddRange((await uow.Repository()
.ListAsync(Query.For().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()
.ListAsync(Query.For().Where(f => f.ReceivedAt >= start && f.ReceivedAt < end && f.Status != InboxFileStatus.Discarded).OrderBy(f => f.ReceivedAt), cancellationToken)
.ConfigureAwait(false)).Items;
var index = new StringBuilder("cartella;file;tipo;documento;data;controparte;identificativo_sdi;stato;sha256\r\n");
var count = 0;
using var buffer = new MemoryStream();
using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, leaveOpen: true))
{
var names = new HashSet(StringComparer.OrdinalIgnoreCase);
void Add(string folder, string name, byte[] content, string kind, string? number, string? date, string? party, string? exchange, string state)
{
var path = Unique(names, folder + "/" + Path.GetFileName(name));
var entry = zip.CreateEntry(path, CompressionLevel.Optimal);
entry.LastWriteTime = Stamp;
using (var stream = entry.Open())
{
stream.Write(content);
}
index.Append(string.Join(';', folder, Csv(Path.GetFileName(path)), kind, Csv(number), date, Csv(party), Csv(exchange), state, EInvoiceStore.Hash(content))).Append("\r\n");
count++;
}
foreach (var e in sent)
{
Add("emesse", e.FileName, e.Content, e.DocumentType, e.DocumentNumber, Date(e.DocumentDate), e.RecipientCode, e.ExchangeId, e.Status.ToString());
}
foreach (var n in notifications)
{
Add("notifiche", n.FileName, n.Content, n.Code, n.InvoiceFileName, Date(DateOnly.FromDateTime(n.ReceivedAt)), null, n.ExchangeId, n.Outcome ?? string.Empty);
}
foreach (var f in received)
{
Add("ricevute", f.FileName, f.Content, f.DocumentType ?? string.Empty, f.Number, f.DocumentDate is { } d ? Date(d) : null, f.SupplierName, f.ExchangeId, f.Status.ToString());
if (f.Metadata is { Length: > 0 } metadata && f.MetadataFileName is { } metadataName)
{
Add("ricevute", metadataName, metadata, "MT", f.Number, null, f.SupplierName, f.ExchangeId, string.Empty);
}
}
Write(zip, "indice.csv", Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(index.ToString())).ToArray());
Write(zip, "LEGGIMI.txt", Encoding.UTF8.GetBytes(Readme(company, from, to, sent.Count, notifications.Count, received.Count)));
}
var content = buffer.ToArray();
var fileName = string.Create(CultureInfo.InvariantCulture, $"conservazione-{company}-{from:yyyyMMdd}-{to:yyyyMMdd}.zip");
var export = new ConservationExport
{
FromDate = from,
ToDate = to,
FileCount = count,
FileName = fileName,
Hash = EInvoiceStore.Hash(content),
Size = content.LongLength,
};
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
export.Id = await uow.Repository().InsertAsync(export, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return new ConservationPackage(export, content);
}
private static void Write(ZipArchive zip, string name, byte[] content)
{
var entry = zip.CreateEntry(name, CompressionLevel.Optimal);
entry.LastWriteTime = Stamp;
using var stream = entry.Open();
stream.Write(content);
}
private static string Unique(HashSet names, string path)
{
var candidate = path;
for (var i = 2; !names.Add(candidate); i++)
{
candidate = Path.ChangeExtension(path, null) + "-" + i.ToString(CultureInfo.InvariantCulture) + Path.GetExtension(path);
}
return candidate;
}
private static string Date(DateOnly date) => date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
private static string Csv(string? value) =>
string.IsNullOrEmpty(value) ? string.Empty : value.IndexOfAny([';', '"', '\r', '\n']) >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value;
private string Readme(string company, DateOnly from, DateOnly to, int sent, int notifications, int received) =>
string.Create(CultureInfo.InvariantCulture, $"""
Khaemhat - pacchetto per la conservazione delle fatture elettroniche
Azienda: {company}
Periodo: dal {from:dd/MM/yyyy} al {to:dd/MM/yyyy}
Creato il: {_clock.GetUtcNow():yyyy-MM-dd HH:mm} UTC
emesse/ {sent} fatture inviate al SDI, nel formato in cui sono state trasmesse
notifiche/ {notifications} ricevute e notifiche del SDI relative alle fatture emesse
ricevute/ {received} fatture ricevute dai fornitori, con i file metadati (MT)
indice.csv l'elenco dei file con l'impronta SHA-256 di ciascuno
I file sono quelli originali: nessuno รจ stato modificato. Il pacchetto va consegnato al servizio di
conservazione (ad esempio il servizio gratuito dell'Agenzia delle Entrate o un conservatore accreditato);
Khaemhat non sostituisce la conservazione a norma.
""");
}