diff --git a/scripts/seed.sh b/scripts/seed.sh index bb82fdc..272a1c4 100755 --- a/scripts/seed.sh +++ b/scripts/seed.sh @@ -3,6 +3,7 @@ # tables still empty (--scale N repeats the demo catalogues N times). Rows already there are never changed. # scripts/seed.sh --base [--company CODE] # scripts/seed.sh --demo [--scale N] [--company CODE] +# scripts/seed.sh --remove-demo [--company CODE] removes only the rows marked demo (and what belongs to them) # In the container (shipped as /app/scripts/seed.sh, same KHAEMHAT_* variables as the service): # docker compose run --rm --entrypoint /app/scripts/seed.sh khaemhat --base # On a development machine it runs the project with the variables already set in the shell (see scripts/run-dev.sh). diff --git a/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs b/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs index e8a7f3c..785f1b7 100644 --- a/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs +++ b/src/Khaemhat.Application/EInvoicing/ConservationExportService.cs @@ -66,7 +66,7 @@ public sealed class ConservationExportService 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 > 400) + if (to < from || to.DayNumber - from.DayNumber > 731) { throw new ValidationFailedException(["To:" + EInvoiceErrors.PeriodInvalid]); } @@ -79,9 +79,9 @@ public sealed class ConservationExportService var notifications = new List(); foreach (var chunk in sent.Select(e => e.Id).Chunk(500)) { - var ids = chunk.ToList(); + var ids = chunk.Select(id => (long?)id).ToList(); notifications.AddRange((await uow.Repository() - .ListAsync(Query.For().Where(n => n.EInvoiceId != null && ids.Contains(n.EInvoiceId.Value)).OrderBy(n => n.ReceivedAt), cancellationToken) + .ListAsync(Query.For().Where(n => ids.Contains(n.EInvoiceId)).OrderBy(n => n.ReceivedAt), cancellationToken) .ConfigureAwait(false)).Items); } diff --git a/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs b/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs index 539ef4d..9ad1eaf 100644 --- a/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs +++ b/src/Khaemhat.Application/EInvoicing/EInvoiceBuilder.cs @@ -151,7 +151,7 @@ internal static class EInvoiceBuilder } // The customer, or the supplier of a self-invoice. - private static EInvoiceParty PartyOf(Party party, PartyFiscal? fiscal, bool supplier) + internal static EInvoiceParty PartyOf(Party party, PartyFiscal? fiscal, bool supplier) { var country = (party.CountryCode ?? "IT").Trim().ToUpperInvariant(); var italian = country == "IT"; diff --git a/src/Khaemhat.Application/Seeding/DemoDataRemover.cs b/src/Khaemhat.Application/Seeding/DemoDataRemover.cs new file mode 100644 index 0000000..e436051 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoDataRemover.cs @@ -0,0 +1,181 @@ +using Khaemhat.Data; +using Khaemhat.Data.Migrations; +using Khaemhat.Data.Schema; + +namespace Khaemhat.Application.Seeding; + +/// What the removal of the demo data did. +/// Rows removed, by table. +/// Tables whose own rows (not demo) still refer to demo rows: nothing was removed. +public sealed record DemoRemoval(IReadOnlyDictionary Removed, IReadOnlyList Blockers) +{ + /// Whether the demo data were removed. + public bool Done => Blockers.Count == 0; + + /// All the rows removed. + public int Total => Removed.Values.Sum(); +} + +/// +/// Removes the demo data of a company, and only them (SPEC §14, issue #80): the rows marked is_demo and the rows +/// of the tables without the mark that belong to them through a foreign key (the lines of a demo document, the balances +/// of a demo item). The tables and their keys come from the migrations, so a new module is covered without changes. +/// When a row the user entered refers to a demo row (an invoice to a demo customer) nothing is removed and the tables +/// are reported: the user decides what to do. Everything happens in one transaction. +/// +/// The units of work. +public sealed class DemoDataRemover(IUnitOfWorkFactory factory) +{ + private const string DemoColumn = "is_demo"; + + /// Removes the demo data of a company. + /// The company. + /// Cancellation. + /// What was removed, or what stopped it. + public async Task RemoveAsync(string companyCode, CancellationToken cancellationToken = default) + { + var model = MigrationCatalog.ForCompany().BuildModel(); + var tables = model.Tables.ToDictionary(t => t.Name, StringComparer.Ordinal); + var doomed = new Dictionary(StringComparer.Ordinal); + foreach (var table in tables.Values) + { + Predicate(table, tables, doomed, []); + } + + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + + // Rows of the user that point to demo rows through a key that does not follow them. + var blockers = new List(); + foreach (var table in tables.Values.Where(t => t.Column(DemoColumn) is not null)) + { + foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1)) + { + if (doomed.GetValueOrDefault(key.ReferencedTable) is not { } parent) + { + continue; + } + + var count = await uow.QuerySingleAsync( + SqlFragment.Literal("SELECT COUNT(*) FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ") + + SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(false) + SqlFragment.Literal(" AND ") + + SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable) + + SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")"), + cancellationToken).ConfigureAwait(false); + if (count > 0 && !blockers.Contains(table.Name)) + { + blockers.Add(table.Name); + } + } + } + + if (blockers.Count > 0) + { + await uow.RollbackAsync(cancellationToken).ConfigureAwait(false); + return new DemoRemoval(new Dictionary(), blockers); + } + + var removed = new Dictionary(StringComparer.Ordinal); + foreach (var table in DeleteOrder(tables.Values.Where(t => doomed.GetValueOrDefault(t.Name) is not null).ToList())) + { + var where = doomed[table.Name]!; + + // A key to the same table (an item and its parent) is cleared first, so the rows can go in one statement. + foreach (var key in table.ForeignKeys.Where(k => k.ReferencedTable == table.Name && k.Columns.Count == 1)) + { + if (table.Column(key.Columns[0]) is { IsNullable: true }) + { + await uow.ExecuteAsync( + SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(key.Columns[0]) + + SqlFragment.Literal(" = NULL WHERE ") + where, + cancellationToken).ConfigureAwait(false); + } + } + + var rows = await uow.ExecuteAsync(SqlFragment.Literal("DELETE FROM ") + SqlFragment.Identifier(table.Name) + SqlFragment.Literal(" WHERE ") + where, cancellationToken) + .ConfigureAwait(false); + if (rows > 0) + { + removed[table.Name] = rows; + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return new DemoRemoval(removed, []); + } + + // The rows of a table that go: marked demo, or (for a table without the mark) belonging to a row that goes. + private static SqlFragment? Predicate(TableDefinition table, Dictionary tables, Dictionary doomed, HashSet visiting) + { + if (doomed.TryGetValue(table.Name, out var known)) + { + return known; + } + + if (table.Column(DemoColumn) is not null) + { + var own = SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + SqlFragment.Parameter(true); + doomed[table.Name] = own; + return own; + } + + if (table.ForeignKeys.Count == 0) + { + doomed[table.Name] = null; + return null; + } + + if (!visiting.Add(table.Name)) + { + return null; + } + + var parts = new List(); + foreach (var key in table.ForeignKeys.Where(k => k.OnDelete != ReferentialAction.SetNull && k.ReferencedTable != table.Name && k.Columns.Count == 1)) + { + if (tables.TryGetValue(key.ReferencedTable, out var parentTable) && Predicate(parentTable, tables, doomed, visiting) is { } parent) + { + parts.Add(SqlFragment.Identifier(key.Columns[0]) + SqlFragment.Literal(" IN (SELECT ") + SqlFragment.Identifier(key.ReferencedColumns[0]) + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(key.ReferencedTable) + + SqlFragment.Literal(" WHERE ") + parent + SqlFragment.Literal(")")); + } + } + + visiting.Remove(table.Name); + var result = parts.Count == 0 ? null : SqlFragment.Join(" OR ", parts.Select(p => p.Parenthesize())).Parenthesize(); + doomed[table.Name] = result; + return result; + } + + // Children before their parents. + private static List DeleteOrder(List tables) + { + var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal); + var result = new List(); + var placed = new HashSet(StringComparer.Ordinal); + while (result.Count < tables.Count) + { + var progress = false; + foreach (var table in tables.Where(t => !placed.Contains(t.Name))) + { + // A table goes once no table still to place refers to it. + var referenced = tables.Any(other => !placed.Contains(other.Name) && other.Name != table.Name + && other.ForeignKeys.Any(k => k.ReferencedTable == table.Name && names.Contains(other.Name))); + if (!referenced) + { + result.Add(table); + placed.Add(table.Name); + progress = true; + } + } + + if (!progress) + { + // A cycle between tables: the rest in any order (keys that set null resolve it). + result.AddRange(tables.Where(t => !placed.Contains(t.Name))); + break; + } + } + + return result; + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoEInvoiceSeeder.cs b/src/Khaemhat.Application/Seeding/DemoEInvoiceSeeder.cs new file mode 100644 index 0000000..6dce634 --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoEInvoiceSeeder.cs @@ -0,0 +1,283 @@ +using System.Globalization; +using System.Text; +using Khaemhat.Application.Documents; +using Khaemhat.Application.EInvoicing; +using Khaemhat.Application.Instance; +using Khaemhat.Application.Licensing; +using Khaemhat.Application.Modules; +using Khaemhat.Application.Security; +using Khaemhat.Application.Tables; +using Khaemhat.Core.Documents; +using Khaemhat.Core.EInvoicing; +using Khaemhat.Core.Parties; +using Khaemhat.Core.Security; +using Khaemhat.Core.Tables; +using Khaemhat.Data; +using Khaemhat.Data.Querying; +using Khaemhat.Fiscal.Abstractions; + +namespace Khaemhat.Application.Seeding; + +/// +/// The demo electronic invoice (SPEC §14, issue #80): the PEC channel (paused, so the demo never writes to a real +/// mailbox) and the intermediary, the routing rules, the files of the demo invoices with the notifications the SDI +/// would have sent (delivered, one rejected to correct, one not delivered, the last ones still waiting), and three +/// supplier invoices received with their metadata. The notifications are written in the layout of the SDI and read by +/// the fiscal pack, as real ones. It runs after the demo treasury, only when the electronic invoice (EINV) is licensed +/// and only once: when the company has e-invoices it adds nothing. +/// +/// The e-invoices. +/// The fiscal pack of the company. +/// Protects the demo password. +/// Reads and writes the company. +/// Whether the electronic invoice is licensed. +public sealed class DemoEInvoiceSeeder( + EInvoiceService invoices, CompanyFiscalContext packs, ISecretProtector secrets, IUnitOfWorkFactory factory, ILicenseGate licenses) + : ICompanySeeder +{ + /// The demo certified mailbox. + public const string Mailbox = "fatture@pec.khaemhat-demo.it"; + + /// How many of the last invoices stay without a file (to generate). + public const int LeftToGenerate = 1; + + /// How many files stay generated and not sent. + public const int LeftToSend = 1; + + /// How many files sent stay waiting for the receipt. + public const int LeftWaiting = 2; + + private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0"; + + /// + public int Order => 60; + + /// + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.EInvoicing)) + { + return; + } + + var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false); + if (pack.GetFeature() is not { } writer || pack.GetFeature() is not { } validator + || pack.GetFeature() is not { } receipts) + { + return; + } + + List documents; + await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false)) + { + if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0 + || await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false) is null) + { + return; + } + + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + await ChannelsAsync(uow, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + documents = [.. (await uow.Repository() + .ListAsync(Query.For().Where(d => d.IsDemo && d.Status == DocumentStatus.Issued).OrderBy(d => d.DocumentDate).OrderBy(d => d.Id), cancellationToken) + .ConfigureAwait(false)).Items.Where(d => EInvoiceBuilder.IsElectronic(d.Kind))]; + } + + var generated = new List(); + foreach (var document in documents.Take(Math.Max(0, documents.Count - LeftToGenerate))) + { + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var result = await invoices.GenerateCoreAsync(uow, writer, validator, DocumentFamily.SaleDocument, document.Id, Actor.System.UserName, cancellationToken) + .ConfigureAwait(false); + if (result.Invoice is { } invoice) + { + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + generated.Add(invoice); + } + else + { + await uow.RollbackAsync(cancellationToken).ConfigureAwait(false); + } + } + + var sent = generated.Take(Math.Max(0, generated.Count - LeftToSend)).ToList(); + var answered = sent.Count - LeftWaiting; + for (var i = 0; i < sent.Count; i++) + { + var invoice = sent[i]; + var exchangeId = (4_000_000_000L + invoice.Progressive).ToString(CultureInfo.InvariantCulture); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var current = await uow.Repository().GetAsync(invoice.Id, cancellationToken).ConfigureAwait(false); + if (current is null) + { + continue; + } + + await invoices.MarkSentCoreAsync(uow, current, "PEC", null, "", Actor.System.UserName, cancellationToken) + .ConfigureAwait(false); + if (i < answered) + { + var at = new DateTimeOffset(current.DocumentDate.AddDays(1).ToDateTime(new TimeOnly(10, 15)), TimeSpan.FromHours(1)); + var stem = EInvoiceStore.Stem(current.FileName); + var (code, root, body) = (i % 9) switch + { + 2 when answered > 3 => ("NS", "NotificaScarto", Rejection(current.FileName, exchangeId, at)), + 5 when answered > 6 => ("MC", "NotificaMancataConsegna", Basic(current.FileName, exchangeId, at, "Casella del destinatario piena: fattura messa a disposizione nell'area riservata.")), + _ => ("RC", "RicevutaConsegna", Delivery(current.FileName, exchangeId, at)), + }; + var name = stem + "_" + code + "_001.xml"; + var receipt = receipts.Read(name, Notification(root, body)); + await invoices.ApplyReceiptCoreAsync(uow, receipt, "PEC", Actor.System.UserName, true, cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + await InboxAsync(companyCode, pack, writer, documents.FirstOrDefault(), cancellationToken).ConfigureAwait(false); + } + + /// A notification as the SDI writes it (MessaggiTypes v1.0). + /// The root element. + /// The children. + /// The file. + public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes( + $"""{body}"""); + + private static string Stamp(DateTimeOffset at) => at.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", CultureInfo.InvariantCulture); + + private static string Delivery(string file, string exchangeId, DateTimeOffset at) => + $"{exchangeId}{file}demo{Stamp(at.AddMinutes(-20))}" + + $"{Stamp(at)}{exchangeId}1"; + + private static string Basic(string file, string exchangeId, DateTimeOffset at, string note) => + $"{exchangeId}{file}demo{Stamp(at.AddMinutes(-20))}" + + $"{note}{exchangeId}2{note}"; + + private static string Rejection(string file, string exchangeId, DateTimeOffset at) => + $"{exchangeId}{file}demo{Stamp(at.AddMinutes(-20))}" + + "003051.4.1.1.2 IdCodice del cessionario/committente non valido" + + "Verificare la partita IVA del cliente in anagrafica" + + $"{exchangeId}3"; + + private async Task ChannelsAsync(IUnitOfWork uow, CancellationToken cancellationToken) + { + var channels = uow.Repository(); + await channels.InsertAsync( + new EInvoiceChannelSetting + { + Code = "PEC", + Enabled = true, + Paused = true, + Mailbox = Mailbox, + SmtpHost = "smtps.pec.khaemhat-demo.it", + SmtpPort = 465, + ImapHost = "imaps.pec.khaemhat-demo.it", + ImapPort = 993, + Tls = true, + UserName = Mailbox, + ProtectedPassword = secrets.Protect("demo-non-valida", EInvoiceStore.SecretPurpose), + ExchangeAddress = "sdi27@pec.fatturapa.it", + ArchiveFolder = "SDI/Archiviati", + LastCheckMessage = "Canale dimostrativo in pausa: nessun messaggio viene inviato o letto.", + IsDemo = true, + }, + cancellationToken).ConfigureAwait(false); + await channels.InsertAsync( + new EInvoiceChannelSetting + { + Code = "INTA", + Enabled = false, + Endpoint = "https://api.intermediario.khaemhat-demo.it/v1", + TestEnvironment = true, + IsDemo = true, + }, + cancellationToken).ConfigureAwait(false); + var rules = uow.Repository(); + await rules.InsertAsync(new SdiRoutingRule { Position = 10, Condition = SdiRoutingCondition.PublicAdministration, ChannelCode = "PEC", IsDemo = true }, cancellationToken) + .ConfigureAwait(false); + await rules.InsertAsync(new SdiRoutingRule { Position = 20, Condition = SdiRoutingCondition.DailyVolume, Value = "200", ChannelCode = "INTA", FallbackChannelCode = "PEC", IsDemo = true }, + cancellationToken).ConfigureAwait(false); + await rules.InsertAsync(new SdiRoutingRule { Position = 90, Condition = SdiRoutingCondition.Default, ChannelCode = "PEC", FallbackChannelCode = "INTA", IsDemo = true }, + cancellationToken).ConfigureAwait(false); + } + + // Three supplier invoices received through the SDI, with their metadata: made from a demo invoice, turned around. + private async Task InboxAsync(string companyCode, IFiscalPack pack, IEInvoiceWriter writer, SaleDocument? model, CancellationToken cancellationToken) + { + if (model is null || pack.GetFeature() is not { } reader) + { + return; + } + + await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false); + var profile = await uow.Repository().FindAsync(Query.For(), cancellationToken).ConfigureAwait(false); + var record = await DocumentEngine.LoadAsync(uow, DocumentFamily.SaleDocument, model.Id, cancellationToken).ConfigureAwait(false); + if (profile is null || record is null) + { + return; + } + + var suppliers = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo && p.Kind == PartyKind.Supplier).OrderBy(p => p.Id).Take(3), cancellationToken) + .ConfigureAwait(false)).Items; + var (file, _, _) = await EInvoiceBuilder.BuildAsync(uow, record, cancellationToken).ConfigureAwait(false); + var customer = EInvoiceBuilder.CompanyParty(profile); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + var n = 0; + foreach (var supplier in suppliers) + { + n++; + var supplierId = supplier.Id; + var fiscal = await uow.Repository().FindAsync(Query.For().Where(f => f.PartyId == supplierId), cancellationToken).ConfigureAwait(false); + var party = EInvoiceBuilder.PartyOf(supplier, fiscal, supplier: true); + var country = party.CountryCode ?? "IT"; + var id = party.VatNumber ?? party.TaxCode ?? "00000000000"; + var date = model.DocumentDate.AddDays(-3 * n); + var name = writer.FileName(country, id, 100 + n); + var number = string.Create(CultureInfo.InvariantCulture, $"{date.Year}/{(40 * n) + 7}"); + var incoming = file with + { + FileName = name, + ProgressiveNumber = writer.Progressive(100 + n), + TransmitterCountry = country, + TransmitterId = id, + RecipientCode = profile.RecipientCode is { Length: 7 } code ? code : "0000000", + RecipientPec = profile.RecipientCode is { Length: 7 } ? null : Mailbox, + Supplier = party, + Customer = customer, + Invoices = [file.Invoices[0] with { Number = number, Date = date, DocumentType = "TD01" }], + IssuedBy = null, + }; + var content = writer.Write(incoming); + var receivedAt = date.AddDays(1).ToDateTime(new TimeOnly(9, 30 + n), DateTimeKind.Utc); + var exchangeId = (5_000_000_000L + n).ToString(CultureInfo.InvariantCulture); + var stored = await SdiInboxService.StoreCoreAsync(uow, reader, name, content, receivedAt, "PEC", exchangeId, true, cancellationToken).ConfigureAwait(false); + if (stored.Id is { } rowId) + { + var row = await uow.Repository().GetAsync(rowId, cancellationToken).ConfigureAwait(false); + if (row is not null) + { + row.MetadataFileName = EInvoiceStore.Stem(name) + "_MT_001.xml"; + row.Metadata = Notification("FileMetadati", + $"{exchangeId}{name}demo{incoming.RecipientCode}" + + $"FPR121{exchangeId}9"); + await uow.Repository().UpdateAsync(row, cancellationToken).ConfigureAwait(false); + } + } + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs b/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs index 22994c0..d917f82 100644 --- a/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs @@ -41,7 +41,15 @@ public sealed class DemoLedgerSeeder( public int Order => 40; /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo) diff --git a/src/Khaemhat.Application/Seeding/DemoMarker.cs b/src/Khaemhat.Application/Seeding/DemoMarker.cs new file mode 100644 index 0000000..ccf9ebe --- /dev/null +++ b/src/Khaemhat.Application/Seeding/DemoMarker.cs @@ -0,0 +1,71 @@ +using Khaemhat.Data; +using Khaemhat.Data.Migrations; + +namespace Khaemhat.Application.Seeding; + +/// +/// Marks as demo every row a demo seeder created, also those the services wrote for it (the entries of an issued +/// invoice, the open items, the payments): the last identifier of every table with is_demo is taken before the +/// seeder runs, and the rows after it are marked when it ends. So finds them all. A demo +/// seed is an administrative operation: rows the users would write meanwhile in the same company would be marked too. +/// +internal sealed class DemoMarker +{ + private const string DemoColumn = "is_demo"; + + private static readonly Lazy> Tables = new(() => + [.. MigrationCatalog.ForCompany().BuildModel().Tables.Where(t => t.Column(DemoColumn) is not null && t.PrimaryKey is ["id"]).Select(t => t.Name).Order(StringComparer.Ordinal)]); + + private readonly IUnitOfWorkFactory _factory; + private readonly string _company; + private readonly Dictionary _last; + + private DemoMarker(IUnitOfWorkFactory factory, string company, Dictionary last) + { + _factory = factory; + _company = company; + _last = last; + } + + /// Runs a demo seeder and marks what it created. + /// The units of work. + /// The company. + /// The seeder. + /// Cancellation. + /// A task. + public static async Task RunAsync(IUnitOfWorkFactory factory, string company, Func seed, CancellationToken cancellationToken) + { + var marker = await TakeAsync(factory, company, cancellationToken).ConfigureAwait(false); + await seed().ConfigureAwait(false); + await marker.MarkAsync(cancellationToken).ConfigureAwait(false); + } + + private static async Task TakeAsync(IUnitOfWorkFactory factory, string company, CancellationToken cancellationToken) + { + var last = new Dictionary(StringComparer.Ordinal); + await using var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + foreach (var table in Tables.Value) + { + last[table] = await uow.QuerySingleAsync( + SqlFragment.Literal("SELECT MAX(id) FROM ") + SqlFragment.Identifier(table), cancellationToken).ConfigureAwait(false) ?? 0L; + } + + return new DemoMarker(factory, company, last); + } + + private async Task MarkAsync(CancellationToken cancellationToken) + { + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(_company), cancellationToken).ConfigureAwait(false); + await uow.BeginAsync(cancellationToken).ConfigureAwait(false); + foreach (var (table, last) in _last) + { + await uow.ExecuteAsync( + SqlFragment.Literal("UPDATE ") + SqlFragment.Identifier(table) + SqlFragment.Literal(" SET ") + SqlFragment.Identifier(DemoColumn) + SqlFragment.Literal(" = ") + + SqlFragment.Parameter(true) + SqlFragment.Literal(" WHERE id > ") + SqlFragment.Parameter(last) + SqlFragment.Literal(" AND ") + SqlFragment.Identifier(DemoColumn) + + SqlFragment.Literal(" = ") + SqlFragment.Parameter(false), + cancellationToken).ConfigureAwait(false); + } + + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs index 8f4edbd..bcb596a 100644 --- a/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoPurchasesSeeder.cs @@ -43,7 +43,15 @@ public sealed class DemoPurchasesSeeder( public int Order => 30; /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo) diff --git a/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs index 1fa80f7..5834b1f 100644 --- a/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoSalesSeeder.cs @@ -43,7 +43,15 @@ public sealed class DemoSalesSeeder( public int Order => 20; /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo) diff --git a/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs index bc950ab..f42ac01 100644 --- a/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs +++ b/src/Khaemhat.Application/Seeding/DemoTreasurySeeder.cs @@ -78,7 +78,15 @@ public sealed class DemoTreasurySeeder( } /// - public async Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(context); + return context.Demo + ? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, context, cancellationToken), cancellationToken) + : Task.CompletedTask; + } + + private async Task SeedCoreAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(context); if (!context.Demo || !licenses.IsModuleActive(ModuleCodes.Finance)) diff --git a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs index ff833ea..8ee3810 100644 --- a/src/Khaemhat.Web/Hosting/KhaemhatServices.cs +++ b/src/Khaemhat.Web/Hosting/KhaemhatServices.cs @@ -219,6 +219,9 @@ internal static class KhaemhatServices services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddScoped(); diff --git a/src/Khaemhat.Web/Hosting/SeedCommand.cs b/src/Khaemhat.Web/Hosting/SeedCommand.cs index a9c1922..6d5ff25 100644 --- a/src/Khaemhat.Web/Hosting/SeedCommand.cs +++ b/src/Khaemhat.Web/Hosting/SeedCommand.cs @@ -12,13 +12,15 @@ namespace Khaemhat.Web.Hosting; /// Add the demo data too, after the base data, to the tables still empty. /// How many times the demo catalogues are repeated. /// The company, or for every active one. -public sealed record SeedOptions(bool Demo, int Scale, string? Company); +/// Remove the demo data instead (only the rows marked demo and what belongs to them). +public sealed record SeedOptions(bool Demo, int Scale, string? Company, bool RemoveDemo = false); /// /// The command line of scripts/seed.sh (SPEC §4, §14): seed --base|--demo [--scale N] [--company CODE] /// runs the start sequence without serving anything (migrations, first company), then adds the missing base data, and /// with --demo the demo data, to one company or to every active one, and prints what it added. Rows already there -/// are never changed (ADR 0026); each demo seeder fills only its tables still empty. +/// are never changed (ADR 0026); each demo seeder fills only its tables still empty. seed --remove-demo removes +/// the demo data with . /// public static class SeedCommand { @@ -48,6 +50,7 @@ public static class SeedCommand error = null; var wantsBase = false; var wantsDemo = false; + var removeDemo = false; int? scale = null; string? company = null; for (var i = 1; i < args.Length; i++) @@ -60,6 +63,9 @@ public static class SeedCommand case "--demo": wantsDemo = true; break; + case "--remove-demo": + removeDemo = true; + break; case "--scale" when i + 1 < args.Length && int.TryParse(args[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n is >= 1 and <= MaxScale: scale = n; i++; @@ -73,9 +79,15 @@ public static class SeedCommand } } - if (!wantsBase && !wantsDemo) + if (removeDemo && (wantsBase || wantsDemo || scale is not null)) { - error = "Uso: seed --base | --demo [--scale N] [--company CODICE]"; + error = "--remove-demo non si combina con --base, --demo o --scale."; + return false; + } + + if (!wantsBase && !wantsDemo && !removeDemo) + { + error = "Uso: seed --base | --demo [--scale N] | --remove-demo [--company CODICE]"; return false; } @@ -85,7 +97,7 @@ public static class SeedCommand return false; } - options = new SeedOptions(wantsDemo, scale ?? 1, company); + options = new SeedOptions(wantsDemo, scale ?? 1, company, removeDemo); return true; } @@ -119,7 +131,32 @@ public static class SeedCommand return 1; } + if (options.RemoveDemo) + { + var failed = false; + foreach (var code in codes) + { + var removal = await services.GetRequiredService().RemoveAsync(code).ConfigureAwait(false); + if (!removal.Done) + { + failed = true; + await Console.Error.WriteLineAsync(code + ": dati dimostrativi non rimossi, righe inserite dagli utenti li usano in: " + string.Join(", ", removal.Blockers)) + .ConfigureAwait(false); + continue; + } + + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: dati dimostrativi rimossi, {removal.Total} righe.")); + foreach (var (table, count) in removal.Removed.OrderBy(r => r.Key, StringComparer.Ordinal)) + { + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $" {table}: {count}")); + } + } + + return failed ? 1 : 0; + } + var runner = services.GetRequiredService(); + var watch = System.Diagnostics.Stopwatch.StartNew(); foreach (var code in codes) { // The demo data need the base tables: --demo runs the base seeders first. @@ -135,7 +172,11 @@ public static class SeedCommand await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); + await services.GetRequiredService().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false); } + + Console.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{code}: completato in {watch.Elapsed.TotalSeconds:0.0} s.")); + watch.Restart(); } return 0; diff --git a/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs b/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs new file mode 100644 index 0000000..a41c9d9 --- /dev/null +++ b/tests/Khaemhat.Web.Tests/EInvoicing/EInvoiceTests.cs @@ -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; + +/// +/// 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); + } +}