feat: demo e-invoices, demo data removal and e-invoice integration tests (#79 #80)

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 12:33:07 +01:00
1 parent fb12411404
commit 9d7cb9e71f
13 files changed
+877 -13

No files matched your search

@@ -0,0 +1,252 @@
using System.IO.Compression;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.EInvoicing;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.EInvoicing;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Treasury;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.EInvoicing;
/// <summary>
/// The electronic invoice on a real instance (issues #74-#80): the demo files checked against the schema with their
/// notifications, a rejected invoice corrected and generated again, notifications imported by hand, the invoices
/// received registered as supplier documents, the conservation package, the courtesy copy and the removal of the demo
/// data.
/// </summary>
[TestClass]
public sealed class EInvoiceTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task DemoEInvoices_AreValid_AndFollowTheirNotifications()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await SeedAsync(app.Services, company);
var service = app.Services.GetRequiredService<EInvoiceService>();
var dashboard = await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.Issued));
var counters = dashboard.Counters;
TestContext.WriteLine($"Rows {dashboard.Rows.Count}, pending {dashboard.Pending.Count}, {counters}");
Assert.IsGreaterThanOrEqualTo(5, dashboard.Rows.Count, "The demo invoices have their files.");
Assert.IsGreaterThan(0, counters.Delivered);
Assert.AreEqual(DemoEInvoiceSeeder.LeftToSend, counters.ToSend);
Assert.IsGreaterThanOrEqualTo(DemoEInvoiceSeeder.LeftToGenerate, counters.ToGenerate);
Assert.AreEqual(DemoEInvoiceSeeder.LeftWaiting, counters.Waiting);
Assert.AreEqual(3, counters.Received);
// Every file is valid for the schema, and the document follows its e-invoice.
var pack = await app.Services.GetRequiredService<CompanyFiscalContext>().PackOfAsync(company);
var validator = pack.GetFeature<IEInvoiceValidator>()!;
var engine = app.Services.GetRequiredService<DocumentEngine>();
foreach (var row in dashboard.Rows)
{
var (name, xml) = await service.FileAsync(Root, company, row.Invoice.Id);
var problems = validator.ValidateXml(xml).Where(p => p.Severity == EInvoiceProblemSeverity.Error).ToList();
Assert.IsEmpty(problems, name + ": " + string.Join("; ", problems.Select(p => p.Path + " " + p.Message)));
var document = await engine.GetAsync(Root, company, row.Invoice.Family, row.Invoice.DocumentId);
Assert.AreEqual(EInvoiceStates.DocumentStatusOf(row.Invoice.Status), document!.Header.Status, row.Invoice.FileName);
}
// The history of a delivered invoice has its receipt.
var delivered = dashboard.Rows.First(r => r.Invoice.Status == EInvoiceStatus.Delivered).Invoice;
var history = await service.HistoryAsync(Root, company, delivered.Family, delivered.DocumentId);
Assert.AreEqual("RC", history[0].Notifications[0].Code);
Assert.IsNotNull(history[0].Invoice.ExchangeId);
// No channel to send through: the demo PEC is paused.
var toSend = dashboard.Rows.First(r => r.Invoice.Status == EInvoiceStatus.Generated).Invoice;
var outcome = (await service.SendAsync(Root, company, [toSend.Id]))[0];
Assert.IsFalse(outcome.Sent);
Assert.AreEqual(EInvoiceErrors.NoChannel, outcome.Error);
// Seeding again adds nothing.
await app.Services.GetRequiredService<DemoEInvoiceSeeder>().SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true));
Assert.HasCount(dashboard.Rows.Count, (await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.Issued))).Rows);
await app.StopAsync();
}
}
[TestMethod]
public async Task ARejectedInvoice_IsCorrected_AndSentAgainWithANewFile()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await SeedAsync(app.Services, company);
var service = app.Services.GetRequiredService<EInvoiceService>();
var engine = app.Services.GetRequiredService<DocumentEngine>();
var pending = (await service.DashboardAsync(Root, company, new EInvoiceFilter(EInvoiceView.ToDo))).Pending.First(p => p.Status == DocumentStatus.Issued);
// Generate, mark as sent from the portal, then the SDI rejects it.
var generation = await service.GenerateAsync(Root, company, pending.Family, pending.DocumentId);
Assert.IsTrue(generation.Success, string.Join("; ", generation.Problems.Select(p => p.Code + " " + p.Message)));
var first = generation.Invoice!;
Assert.AreEqual(DocumentStatus.SdiGenerated, (await engine.GetAsync(Root, company, pending.Family, pending.DocumentId))!.Header.Status);
await service.MarkSentAsync(Root, company, first.Id, "777000111");
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => service.MarkSentAsync(Root, company, first.Id, null));
var rejection = DemoEInvoiceSeeder.Notification("NotificaScarto",
$"<IdentificativoSdI>777000111</IdentificativoSdI><NomeFile>{first.FileName}</NomeFile><DataOraRicezione>2026-11-12T10:00:00</DataOraRicezione>"
+ "<ListaErrori><Errore><Codice>00311</Codice><Descrizione>CodiceDestinatario non valido</Descrizione></Errore></ListaErrori><MessageId>1</MessageId>");
var name = first.FileName[..first.FileName.IndexOf(".xml", StringComparison.Ordinal)] + "_NS_001.xml";
var imported = await service.ImportReceiptsAsync(Root, company, [(name, rejection), ("altro.xml", Encoding.UTF8.GetBytes("<a/>"))]);
Assert.AreEqual(EInvoiceStatus.Rejected, imported[0].Status);
Assert.AreEqual(EInvoiceErrors.NotAReceipt, imported[1].Error);
Assert.AreEqual(EInvoiceErrors.ReceiptDuplicate, (await service.ImportReceiptsAsync(Root, company, [(name, rejection)]))[0].Error);
var document = (await engine.GetAsync(Root, company, pending.Family, pending.DocumentId))!;
Assert.AreEqual(DocumentStatus.SdiRejected, document.Header.Status);
// The invoice can be changed now; generated again it gets a new progressive, the old file is kept.
document.Header.Notes = "Corretta dopo lo scarto";
await engine.SaveAsync(Root, company, document);
var second = (await service.GenerateAsync(Root, company, pending.Family, pending.DocumentId)).Invoice!;
Assert.AreNotEqual(first.FileName, second.FileName);
Assert.IsGreaterThan(first.Progressive, second.Progressive);
var history = await service.HistoryAsync(Root, company, pending.Family, pending.DocumentId);
Assert.HasCount(2, history);
Assert.IsTrue(history[1].Invoice.Superseded);
Assert.AreEqual("NS", history[1].Notifications[0].Code);
// Generated twice before sending, the same file name is kept.
Assert.AreEqual(second.FileName, (await service.GenerateAsync(Root, company, pending.Family, pending.DocumentId)).Invoice!.FileName);
// The courtesy copy carries the XML.
var (pdfName, pdf) = await service.CourtesyCopyAsync(Root, company, second.Id);
StringAssert.EndsWith(pdfName, ".pdf");
var text = Encoding.Latin1.GetString(pdf);
StringAssert.Contains(text, "/EmbeddedFiles");
StringAssert.Contains(text, "/AFRelationship /Source");
await app.StopAsync();
}
}
[TestMethod]
public async Task ReceivedInvoices_AreRegistered_Discarded_AndPackedForConservation()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await SeedAsync(app.Services, company);
var inbox = app.Services.GetRequiredService<SdiInboxService>();
var rows = await inbox.ListAsync(Root, company, new InboxFilter(InboxFileStatus.New));
Assert.HasCount(3, rows);
Assert.IsTrue(rows.All(r => r.MetadataFileName is not null && r.SupplierName is not null && r.PartyId is not null));
// Registered: a draft supplier invoice with the file attached.
var registered = (await inbox.RegisterAsync(Root, company, [rows[0].Id]))[0];
Assert.IsNull(registered.Error, registered.Error);
var purchase = await app.Services.GetRequiredService<DocumentEngine>().GetAsync(Root, company, DocumentFamily.PurchaseDocument, registered.PurchaseDocumentId!.Value);
Assert.AreEqual(DocumentStatus.Draft, purchase!.Header.Status);
Assert.AreEqual(EInvoiceErrors.InboxState, (await inbox.RegisterAsync(Root, company, [rows[0].Id]))[0].Error);
// Discarded and taken back; the same file uploaded again is not kept twice.
await inbox.DiscardAsync(Root, company, rows[1].Id, discard: true);
Assert.HasCount(1, await inbox.ListAsync(Root, company, new InboxFilter(InboxFileStatus.Discarded)));
await inbox.DiscardAsync(Root, company, rows[1].Id, discard: false);
var (fileName, content) = await inbox.FileAsync(Root, company, rows[1].Id);
Assert.AreEqual(EInvoiceErrors.InboxDuplicate, (await inbox.UploadAsync(Root, company, [(fileName, content)]))[0].Error);
var unreadable = (await inbox.UploadAsync(Root, company, [("note.xml", Encoding.UTF8.GetBytes("<note/>"))]))[0];
Assert.AreEqual(InboxFileStatus.Unreadable, unreadable.Status);
// The package of the year: the files as they travelled, with their hashes in the index.
var year = DateTime.Now.Year;
var package = await app.Services.GetRequiredService<ConservationExportService>().ExportAsync(Root, company, new DateOnly(year - 1, 1, 1), new DateOnly(year, 12, 31));
using var zip = new ZipArchive(new MemoryStream(package.Content));
var names = zip.Entries.Select(e => e.FullName).ToList();
Assert.IsTrue(names.Any(n => n.StartsWith("emesse/", StringComparison.Ordinal)));
Assert.IsTrue(names.Any(n => n.StartsWith("notifiche/", StringComparison.Ordinal)));
Assert.IsTrue(names.Any(n => n.StartsWith("ricevute/", StringComparison.Ordinal)));
using var reader = new StreamReader(zip.GetEntry("indice.csv")!.Open());
var index = await reader.ReadToEndAsync();
Assert.HasCount(package.Export.FileCount, index.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Skip(1));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() =>
app.Services.GetRequiredService<ConservationExportService>().ExportAsync(Root, company, new DateOnly(year, 2, 1), new DateOnly(year, 1, 1)));
await app.StopAsync();
}
}
[TestMethod]
public async Task DemoData_AreRemoved_OnlyWhenNothingOfTheUsersNeedsThem()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await SeedAsync(app.Services, company);
var factory = app.Services.GetRequiredService<IUnitOfWorkFactory>();
var remover = app.Services.GetRequiredService<DemoDataRemover>();
// A mandate the user entered for a demo customer: nothing is removed, and the table is named.
long blockerId;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company)))
{
await uow.BeginAsync();
var customer = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => p.IsDemo && p.Kind == PartyKind.Customer).Take(1))).Items[0];
blockerId = await uow.Repository<SddMandate, long>().InsertAsync(new SddMandate
{
PartyId = customer.Id,
Reference = "UTENTE-1",
SignatureDate = new DateOnly(2026, 1, 10),
Iban = DemoTreasurySeeder.Iban('X', "05428", "11101", "000000123456"),
});
await uow.CommitAsync();
}
var blocked = await remover.RemoveAsync(company);
Assert.IsFalse(blocked.Done);
CollectionAssert.AreEqual(new[] { "sdd_mandates" }, blocked.Blockers.ToArray());
Assert.AreEqual(0, blocked.Total);
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company)))
{
await uow.BeginAsync();
await uow.Repository<SddMandate, long>().DeleteAsync(blockerId);
await uow.CommitAsync();
}
var removal = await remover.RemoveAsync(company);
Assert.IsTrue(removal.Done, string.Join(", ", removal.Blockers));
TestContext.WriteLine($"Removed {removal.Total}: " + string.Join(", ", removal.Removed.Select(r => r.Key + "=" + r.Value)));
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company)))
{
Assert.AreEqual(0, await uow.Repository<Party, long>().CountAsync(Query.For<Party>().Where(p => p.IsDemo)));
Assert.AreEqual(0, await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>()));
Assert.AreEqual(0, await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>()));
Assert.AreEqual(0, await uow.Repository<SaleDocumentLine, long>().CountAsync(Query.For<SaleDocumentLine>()));
Assert.AreEqual(0, await uow.Repository<Khaemhat.Core.Accounting.GlEntry, long>().CountAsync(Query.For<Khaemhat.Core.Accounting.GlEntry>()), "The entries of the demo go with it.");
Assert.AreEqual(0, await uow.Repository<Payment, long>().CountAsync(Query.For<Payment>()));
}
Assert.IsTrue((await remover.RemoveAsync(company)).Done, "Running it again removes nothing and fails nothing.");
await app.StopAsync();
}
}
private static async Task SeedAsync(IServiceProvider services, string company)
{
var activation = await services.GetRequiredService<ILicenseActivationService>().ActivateAsync(Root, "KH-TEST-ALL-0000-9999");
Assert.IsTrue(activation.Succeeded, activation.Outcome);
await services.GetRequiredService<SeedRunner>().RunAsync(company, SeedKind.Demo);
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
await services.GetRequiredService<DemoSalesSeeder>().SeedAsync(company, context);
await services.GetRequiredService<DemoPurchasesSeeder>().SeedAsync(company, context);
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(company, context);
await services.GetRequiredService<DemoTreasurySeeder>().SeedAsync(company, context);
await services.GetRequiredService<DemoEInvoiceSeeder>().SeedAsync(company, context);
}
}