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; /// /// 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. /// [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(); 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().PackOfAsync(company); var validator = pack.GetFeature()!; var engine = app.Services.GetRequiredService(); 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().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(); var engine = app.Services.GetRequiredService(); 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(() => service.MarkSentAsync(Root, company, first.Id, null)); var rejection = DemoEInvoiceSeeder.Notification("NotificaScarto", $"777000111{first.FileName}2026-11-12T10:00:00" + "00311CodiceDestinatario non valido1"); 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(""))]); 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(); 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().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(""))]))[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().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(() => app.Services.GetRequiredService().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(); var remover = app.Services.GetRequiredService(); // 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().ListAsync(Query.For().Where(p => p.IsDemo && p.Kind == PartyKind.Customer).Take(1))).Items[0]; blockerId = await uow.Repository().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().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().CountAsync(Query.For().Where(p => p.IsDemo))); Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For()), "The entries of the demo go with it."); Assert.AreEqual(0, await uow.Repository().CountAsync(Query.For())); } 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().ActivateAsync(Root, "KH-TEST-ALL-0000-9999"); Assert.IsTrue(activation.Succeeded, activation.Outcome); await services.GetRequiredService().RunAsync(company, SeedKind.Demo); var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true); await services.GetRequiredService().SeedAsync(company, context); await services.GetRequiredService().SeedAsync(company, context); await services.GetRequiredService().SeedAsync(company, context); await services.GetRequiredService().SeedAsync(company, context); await services.GetRequiredService().SeedAsync(company, context); } }