Files
Khaemhat/src/Khaemhat.Application/Seeding/DemoLedgerSeeder.cs
T
Alby96andClaude Opus 5.5 9d7cb9e71f feat: demo e-invoices, demo data removal and e-invoice integration tests (#79 #80)
The demo company now has its electronic invoices: a paused PEC channel and an
intermediary, routing rules, the files of the demo invoices with the notifications
the SDI would send (delivered, one rejected, one not delivered, some waiting) read
by the fiscal pack as real ones, and three supplier invoices in the inbox with their
metadata. Every demo seeder now marks as demo also the rows the services write for
it (entries, open items, payments, mandates, statements), so the new
DemoDataRemover, driven by the schema of the migrations, removes the demo data and
only them; it stops and names the tables when rows entered by users still refer to
demo rows. `scripts/seed.sh --remove-demo` exposes it and the seed prints its time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:33:07 +01:00

132 lines
7.0 KiB
C#

using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Tax;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
namespace Khaemhat.Application.Seeding;
/// <summary>
/// The demo accounting (SPEC §14, issue #68): the demo documents posted, the professional's invoice paid so that its
/// withholding is due, the monthly rental of the office printer as a recurring entry, the VAT settlements of the periods already
/// ended confirmed, and the F24 already due paid. It runs after the demo sales and purchases and only once: when
/// the company has typed or settled anything in the ledger it adds nothing.
/// </summary>
/// <param name="ledger">Posts the documents.</param>
/// <param name="journal">Writes the model entry of the rental.</param>
/// <param name="vat">Computes and confirms the settlements.</param>
/// <param name="taxes">Withholdings, stamp duty and F24.</param>
/// <param name="recurring">The recurring rental.</param>
/// <param name="factory">Reads the ledger.</param>
/// <param name="clock">Today.</param>
public sealed class DemoLedgerSeeder(
LedgerService ledger, JournalEntryService journal, VatService vat, TaxService taxes, RecurringEntryService recurring, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The account of the rental, from the Italian chart of accounts (Noleggi).</summary>
public const string RentAccount = "22.01.003";
/// <summary>The bank account that pays it.</summary>
public const string BankAccount = "07.01.001";
/// <summary>The monthly rental of the demo office printer.</summary>
public const decimal Rent = 45m;
private static readonly Actor Seed = Actor.System;
/// <inheritdoc />
public int Order => 40;
/// <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)
{
return;
}
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var start = new DateOnly(today.Year, 1, 1);
long? rentId;
long? bankId;
VatPeriodicity periodicity;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(companyCode), cancellationToken).ConfigureAwait(false))
{
var accounts = uow.Repository<GlAccount, long>();
if (await accounts.CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0)
{
return; // No chart of accounts: the company has no accounting module.
}
if (await uow.Repository<GlEntry, long>().CountAsync(
Query.For<GlEntry>().Where(e => e.Source == GlEntrySource.Manual || e.Source == GlEntrySource.VatSettlement), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<VatSettlement, long>().CountAsync(Query.For<VatSettlement>(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
rentId = (await accounts.FindAsync(Query.For<GlAccount>().Where(a => a.Code == RentAccount), cancellationToken).ConfigureAwait(false))?.Id;
bankId = (await accounts.FindAsync(Query.For<GlAccount>().Where(a => a.Code == BankAccount), cancellationToken).ConfigureAwait(false))?.Id;
periodicity = (await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false))?.VatPeriodicity
?? VatPeriodicity.Monthly;
}
// The documents confirmed before the ledger existed.
await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false);
// The professionals' invoices paid ten days after their date: their withholdings become due.
foreach (var row in await taxes.WithholdingsAsync(Seed, companyCode, today.Year, WithholdingDirection.Operated, cancellationToken).ConfigureAwait(false))
{
if (row.Withholding.Status == WithholdingStatus.Waiting)
{
var paid = row.Withholding.DocumentDate.AddDays(10);
await taxes.InvoicePaidAsync(Seed, companyCode, row.Withholding.Id, paid > today ? today : paid, cancellationToken).ConfigureAwait(false);
}
}
// The printer rental of January, and the same entry every month after as a recurring entry.
if (rentId is { } rent && bankId is { } bank)
{
var first = new DateOnly(today.Year, 1, 5);
var model = await journal.SaveAsync(Seed, companyCode, new EntryInput(null, first, "Noleggio stampante multifunzione",
[new EntryLineDraft(rent, null, null, Rent, 0m), new EntryLineDraft(bank, null, null, 0m, Rent)]) { Post = true }, cancellationToken).ConfigureAwait(false);
await recurring.SaveAsync(Seed, companyCode, new RecurringEntryInput(null, "Noleggio mensile stampante", model.Entry.Id, RecurrenceFrequency.Monthly,
RecurringEntryService.Next(first, RecurrenceFrequency.Monthly), null, false), cancellationToken).ConfigureAwait(false);
await recurring.GenerateAsync(Seed, companyCode, today, cancellationToken).ConfigureAwait(false);
}
// The settlements of the periods already ended, in order, and the stamp duty of the quarters ended.
var periods = periodicity == VatPeriodicity.Quarterly ? (today.Month - 1) / 3 : today.Month - 1;
for (var number = 1; number <= periods; number++)
{
var computed = await vat.ComputeAsync(Seed, companyCode, today.Year, number, cancellationToken).ConfigureAwait(false);
await vat.ConfirmAsync(Seed, companyCode, computed.Settlement.Id, cancellationToken).ConfigureAwait(false);
}
for (var quarter = 1; quarter <= (today.Month - 1) / 3; quarter++)
{
await taxes.StampDutyPaymentAsync(Seed, companyCode, today.Year, quarter, cancellationToken).ConfigureAwait(false);
}
// The F24 already due are paid on their day; those still to come stay to pay.
var dues = (await taxes.PaymentsAsync(Seed, companyCode, today.Year, cancellationToken).ConfigureAwait(false))
.Where(p => p.PaidOn is null && p.DueDate < today).Select(p => p.DueDate).Distinct().Order().ToList();
foreach (var due in dues)
{
await taxes.PayAsync(Seed, companyCode, due, due, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}