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;
///
/// 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.
///
/// Posts the documents.
/// Writes the model entry of the rental.
/// Computes and confirms the settlements.
/// Withholdings, stamp duty and F24.
/// The recurring rental.
/// Reads the ledger.
/// Today.
public sealed class DemoLedgerSeeder(
LedgerService ledger, JournalEntryService journal, VatService vat, TaxService taxes, RecurringEntryService recurring, IUnitOfWorkFactory factory, TimeProvider clock)
: ICompanySeeder
{
/// The account of the rental, from the Italian chart of accounts (Noleggi).
public const string RentAccount = "22.01.003";
/// The bank account that pays it.
public const string BankAccount = "07.01.001";
/// The monthly rental of the demo office printer.
public const decimal Rent = 45m;
private static readonly Actor Seed = Actor.System;
///
public int Order => 40;
///
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();
if (await accounts.CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0)
{
return; // No chart of accounts: the company has no accounting module.
}
if (await uow.Repository().CountAsync(
Query.For().Where(e => e.Source == GlEntrySource.Manual || e.Source == GlEntrySource.VatSettlement), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0)
{
return;
}
rentId = (await accounts.FindAsync(Query.For().Where(a => a.Code == RentAccount), cancellationToken).ConfigureAwait(false))?.Id;
bankId = (await accounts.FindAsync(Query.For().Where(a => a.Code == BankAccount), cancellationToken).ConfigureAwait(false))?.Id;
periodicity = (await uow.Repository().FindAsync(Query.For(), 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);
}
}
}