M9 · Fatturazione elettronica (v0.9.0) #128
No files matched your search
@@ -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).
|
||||
|
||||
@@ -66,7 +66,7 @@ public sealed class ConservationExportService
|
||||
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 > 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<EInvoiceNotification>();
|
||||
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<EInvoiceNotification, long>()
|
||||
.ListAsync(Query.For<EInvoiceNotification>().Where(n => n.EInvoiceId != null && ids.Contains(n.EInvoiceId.Value)).OrderBy(n => n.ReceivedAt), cancellationToken)
|
||||
.ListAsync(Query.For<EInvoiceNotification>().Where(n => ids.Contains(n.EInvoiceId)).OrderBy(n => n.ReceivedAt), cancellationToken)
|
||||
.ConfigureAwait(false)).Items);
|
||||
}
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>What the removal of the demo data did.</summary>
|
||||
/// <param name="Removed">Rows removed, by table.</param>
|
||||
/// <param name="Blockers">Tables whose own rows (not demo) still refer to demo rows: nothing was removed.</param>
|
||||
public sealed record DemoRemoval(IReadOnlyDictionary<string, int> Removed, IReadOnlyList<string> Blockers)
|
||||
{
|
||||
/// <summary>Whether the demo data were removed.</summary>
|
||||
public bool Done => Blockers.Count == 0;
|
||||
|
||||
/// <summary>All the rows removed.</summary>
|
||||
public int Total => Removed.Values.Sum();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the demo data of a company, and only them (SPEC §14, issue #80): the rows marked <c>is_demo</c> 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.
|
||||
/// </summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
public sealed class DemoDataRemover(IUnitOfWorkFactory factory)
|
||||
{
|
||||
private const string DemoColumn = "is_demo";
|
||||
|
||||
/// <summary>Removes the demo data of a company.</summary>
|
||||
/// <param name="companyCode">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was removed, or what stopped it.</returns>
|
||||
public async Task<DemoRemoval> 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<string, SqlFragment?>(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<string>();
|
||||
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<long>(
|
||||
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<string, int>(), blockers);
|
||||
}
|
||||
|
||||
var removed = new Dictionary<string, int>(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<string, TableDefinition> tables, Dictionary<string, SqlFragment?> doomed, HashSet<string> 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<SqlFragment>();
|
||||
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<TableDefinition> DeleteOrder(List<TableDefinition> tables)
|
||||
{
|
||||
var names = tables.Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
|
||||
var result = new List<TableDefinition>();
|
||||
var placed = new HashSet<string>(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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="invoices">The e-invoices.</param>
|
||||
/// <param name="packs">The fiscal pack of the company.</param>
|
||||
/// <param name="secrets">Protects the demo password.</param>
|
||||
/// <param name="factory">Reads and writes the company.</param>
|
||||
/// <param name="licenses">Whether the electronic invoice is licensed.</param>
|
||||
public sealed class DemoEInvoiceSeeder(
|
||||
EInvoiceService invoices, CompanyFiscalContext packs, ISecretProtector secrets, IUnitOfWorkFactory factory, ILicenseGate licenses)
|
||||
: ICompanySeeder
|
||||
{
|
||||
/// <summary>The demo certified mailbox.</summary>
|
||||
public const string Mailbox = "fatture@pec.khaemhat-demo.it";
|
||||
|
||||
/// <summary>How many of the last invoices stay without a file (to generate).</summary>
|
||||
public const int LeftToGenerate = 1;
|
||||
|
||||
/// <summary>How many files stay generated and not sent.</summary>
|
||||
public const int LeftToSend = 1;
|
||||
|
||||
/// <summary>How many files sent stay waiting for the receipt.</summary>
|
||||
public const int LeftWaiting = 2;
|
||||
|
||||
private const string Ns = "http://www.fatturapa.gov.it/sdi/messaggi/v1.0";
|
||||
|
||||
/// <inheritdoc />
|
||||
public int Order => 60;
|
||||
|
||||
/// <inheritdoc />
|
||||
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<IEInvoiceWriter>() is not { } writer || pack.GetFeature<IEInvoiceValidator>() is not { } validator
|
||||
|| pack.GetFeature<IEInvoiceReceiptReader>() is not { } receipts)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
List<SaleDocument> documents;
|
||||
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
if (await uow.Repository<EInvoice, long>().CountAsync(Query.For<EInvoice>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<EInvoiceInboxFile, long>().CountAsync(Query.For<EInvoiceInboxFile>(), cancellationToken).ConfigureAwait(false) > 0
|
||||
|| await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), 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<SaleDocument, long>()
|
||||
.ListAsync(Query.For<SaleDocument>().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<EInvoice>();
|
||||
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<EInvoice, long>().GetAsync(invoice.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (current is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await invoices.MarkSentCoreAsync(uow, current, "PEC", null, "<demo-" + exchangeId + "@pec.khaemhat-demo.it>", 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);
|
||||
}
|
||||
|
||||
/// <summary>A notification as the SDI writes it (<c>MessaggiTypes</c> v1.0).</summary>
|
||||
/// <param name="root">The root element.</param>
|
||||
/// <param name="body">The children.</param>
|
||||
/// <returns>The file.</returns>
|
||||
public static byte[] Notification(string root, string body) => Encoding.UTF8.GetBytes(
|
||||
$"""<?xml version="1.0" encoding="UTF-8"?><types:{root} xmlns:types="{Ns}" versione="1.0">{body}</types:{root}>""");
|
||||
|
||||
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) =>
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
|
||||
+ $"<DataOraConsegna>{Stamp(at)}</DataOraConsegna><MessageId>{exchangeId}1</MessageId>";
|
||||
|
||||
private static string Basic(string file, string exchangeId, DateTimeOffset at, string note) =>
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
|
||||
+ $"<Descrizione>{note}</Descrizione><MessageId>{exchangeId}2</MessageId><Note>{note}</Note>";
|
||||
|
||||
private static string Rejection(string file, string exchangeId, DateTimeOffset at) =>
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{file}</NomeFile><Hash>demo</Hash><DataOraRicezione>{Stamp(at.AddMinutes(-20))}</DataOraRicezione>"
|
||||
+ "<ListaErrori><Errore><Codice>00305</Codice><Descrizione>1.4.1.1.2 IdCodice del cessionario/committente non valido</Descrizione>"
|
||||
+ "<Suggerimento>Verificare la partita IVA del cliente in anagrafica</Suggerimento></Errore></ListaErrori>"
|
||||
+ $"<MessageId>{exchangeId}3</MessageId>";
|
||||
|
||||
private async Task ChannelsAsync(IUnitOfWork uow, CancellationToken cancellationToken)
|
||||
{
|
||||
var channels = uow.Repository<EInvoiceChannelSetting, long>();
|
||||
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<SdiRoutingRule, long>();
|
||||
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<IIncomingInvoiceReader>() is not { } reader)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false);
|
||||
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), 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<Party, long>().ListAsync(Query.For<Party>().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<PartyFiscal, long>().FindAsync(Query.For<PartyFiscal>().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<EInvoiceInboxFile, long>().GetAsync(rowId, cancellationToken).ConfigureAwait(false);
|
||||
if (row is not null)
|
||||
{
|
||||
row.MetadataFileName = EInvoiceStore.Stem(name) + "_MT_001.xml";
|
||||
row.Metadata = Notification("FileMetadati",
|
||||
$"<IdentificativoSdI>{exchangeId}</IdentificativoSdI><NomeFile>{name}</NomeFile><Hash>demo</Hash><CodiceDestinatario>{incoming.RecipientCode}</CodiceDestinatario>"
|
||||
+ $"<Formato>FPR12</Formato><TentativiInvio>1</TentativiInvio><MessageId>{exchangeId}9</MessageId>");
|
||||
await uow.Repository<EInvoiceInboxFile, long>().UpdateAsync(row, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,15 @@ public sealed class DemoLedgerSeeder(
|
||||
public int Order => 40;
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Migrations;
|
||||
|
||||
namespace Khaemhat.Application.Seeding;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>is_demo</c> is taken before the
|
||||
/// seeder runs, and the rows after it are marked when it ends. So <see cref="DemoDataRemover"/> finds them all. A demo
|
||||
/// seed is an administrative operation: rows the users would write meanwhile in the same company would be marked too.
|
||||
/// </summary>
|
||||
internal sealed class DemoMarker
|
||||
{
|
||||
private const string DemoColumn = "is_demo";
|
||||
|
||||
private static readonly Lazy<IReadOnlyList<string>> 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<string, long> _last;
|
||||
|
||||
private DemoMarker(IUnitOfWorkFactory factory, string company, Dictionary<string, long> last)
|
||||
{
|
||||
_factory = factory;
|
||||
_company = company;
|
||||
_last = last;
|
||||
}
|
||||
|
||||
/// <summary>Runs a demo seeder and marks what it created.</summary>
|
||||
/// <param name="factory">The units of work.</param>
|
||||
/// <param name="company">The company.</param>
|
||||
/// <param name="seed">The seeder.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task RunAsync(IUnitOfWorkFactory factory, string company, Func<Task> 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<DemoMarker> TakeAsync(IUnitOfWorkFactory factory, string company, CancellationToken cancellationToken)
|
||||
{
|
||||
var last = new Dictionary<string, long>(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<long?>(
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,15 @@ public sealed class DemoPurchasesSeeder(
|
||||
public int Order => 30;
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
|
||||
@@ -43,7 +43,15 @@ public sealed class DemoSalesSeeder(
|
||||
public int Order => 20;
|
||||
|
||||
/// <inheritdoc />
|
||||
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)
|
||||
|
||||
@@ -78,7 +78,15 @@ public sealed class DemoTreasurySeeder(
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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))
|
||||
|
||||
@@ -219,6 +219,9 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoLedgerSeeder>());
|
||||
services.AddSingleton<DemoTreasurySeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoTreasurySeeder>());
|
||||
services.AddSingleton<DemoEInvoiceSeeder>();
|
||||
services.AddSingleton<ICompanySeeder>(sp => sp.GetRequiredService<DemoEInvoiceSeeder>());
|
||||
services.AddSingleton<DemoDataRemover>();
|
||||
services.AddSingleton<CompanyService>();
|
||||
services.AddSingleton<CompanyContextResolver>();
|
||||
services.AddScoped<ICompanyContext, WebCompanyContext>();
|
||||
|
||||
@@ -12,13 +12,15 @@ namespace Khaemhat.Web.Hosting;
|
||||
/// <param name="Demo">Add the demo data too, after the base data, to the tables still empty.</param>
|
||||
/// <param name="Scale">How many times the demo catalogues are repeated.</param>
|
||||
/// <param name="Company">The company, or <see langword="null"/> for every active one.</param>
|
||||
public sealed record SeedOptions(bool Demo, int Scale, string? Company);
|
||||
/// <param name="RemoveDemo">Remove the demo data instead (only the rows marked demo and what belongs to them).</param>
|
||||
public sealed record SeedOptions(bool Demo, int Scale, string? Company, bool RemoveDemo = false);
|
||||
|
||||
/// <summary>
|
||||
/// The command line of <c>scripts/seed.sh</c> (SPEC §4, §14): <c>seed --base|--demo [--scale N] [--company CODE]</c>
|
||||
/// runs the start sequence without serving anything (migrations, first company), then adds the missing base data, and
|
||||
/// with <c>--demo</c> 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. <c>seed --remove-demo</c> removes
|
||||
/// the demo data with <see cref="DemoDataRemover"/>.
|
||||
/// </summary>
|
||||
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<DemoDataRemover>().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<SeedRunner>();
|
||||
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<DemoPurchasesSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
await services.GetRequiredService<DemoLedgerSeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
await services.GetRequiredService<DemoTreasurySeeder>().SeedAsync(code, new CompanySeedContext(IsNew: false, Base: false, Demo: true)).ConfigureAwait(false);
|
||||
await services.GetRequiredService<DemoEInvoiceSeeder>().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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user