using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Inventory;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Application.YearEnd;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Inventory;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Seeding;
///
/// The demo data of the year end (SPEC ยง14, issue #87): the opening balances of the year (share capital, retained
/// earnings, bank, the opening stock and the fixed assets bought in the years before with their funds), the standard categories and four assets, one of them
/// bought this year; the declaration of intent of Idrotermica Piemonte taken into the register and an invoice under it
/// (NI8C); an intra-EU sale of goods to Bergwerk Bau (Austria) with nomenclature and mass for the Intrastat list; the
/// insurance premium paid in October with its prepaid share. With these the guided closing of the demo year runs from
/// the first step to the last. Runs after the demo e-invoices and only once: when the company has fixed assets or
/// accruals it adds nothing.
///
/// The document engine.
/// The document editor.
/// Posts the new invoices.
/// The fiscal pack of the company.
/// Reads and writes the company.
/// Which modules are licensed.
/// The clock.
public sealed class DemoYearEndSeeder(
DocumentEngine engine, DocumentEditor editor, LedgerService ledger, CompanyFiscalContext packs, IUnitOfWorkFactory factory, ILicenseGate licenses, TimeProvider clock)
: ICompanySeeder
{
/// The share capital of the demo company.
public const decimal ShareCapital = 50_000m;
/// The bank balance on the first of January.
public const decimal OpeningBank = 25_000m;
/// The yearly insurance premium paid on the first of October.
public const decimal InsurancePremium = 1_800m;
private const string InsuranceAccount = "21.03.005";
private const string RetainedEarnings = "10.02.001";
private static readonly Actor Seed = Actor.System;
///
public int Order => 70;
///
public Task SeedAsync(string companyCode, CompanySeedContext context, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(context);
return context.Demo
? DemoMarker.RunAsync(factory, companyCode, () => SeedCoreAsync(companyCode, cancellationToken), cancellationToken)
: Task.CompletedTask;
}
private async Task SeedCoreAsync(string companyCode, CancellationToken cancellationToken)
{
if (!licenses.IsModuleActive(ModuleCodes.Accounting))
{
return;
}
var pack = await packs.PackOfAsync(companyCode, cancellationToken).ConfigureAwait(false);
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(clock.GetUtcNow(), TimeZoneInfo.Local).DateTime);
var start = new DateOnly(today.Year, 1, 1);
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().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository().CountAsync(Query.For().Where(e => e.EntryDate == start && e.Source == GlEntrySource.Manual), cancellationToken)
.ConfigureAwait(false) > 0)
{
return;
}
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
await OpeningAsync(uow, pack, today, cancellationToken).ConfigureAwait(false);
await InsuranceAsync(uow, today, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature() is { } intent)
{
await IntentDeclarationService.AdoptAsync(uow, intent, null, cancellationToken).ConfigureAwait(false);
}
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
await InvoicesAsync(companyCode, today, cancellationToken).ConfigureAwait(false);
await ledger.PostPendingAsync(Seed, companyCode, start, today, cancellationToken: cancellationToken).ConfigureAwait(false);
}
// The opening entry of the year and the fixed assets: three bought in the years before (cost and funds in the
// opening entry) and the computers bought in March and paid by bank transfer.
private async Task OpeningAsync(IUnitOfWork uow, IFiscalPack pack, DateOnly today, CancellationToken cancellationToken)
{
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
if (pack.GetFeature() is not { } closing
|| !accounts.TryGetValue(closing.Accounts.Capital, out var capital) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank))
{
return;
}
var year = today.Year;
var start = new DateOnly(year, 1, 1);
var lines = new List();
var assets = new List();
if (licenses.IsModuleActive(ModuleCodes.Assets) && pack.GetFeature() is { } rules)
{
await FixedAssetService.CreateStandardCategoriesAsync(uow, rules.Coefficients, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
var categories = (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).ToDictionary(c => c.Code, StringComparer.Ordinal);
void Add(string category, string description, int yearsBack, decimal cost, decimal fund, string? serial = null, string? location = null)
{
if (!categories.TryGetValue(category, out var c) || c.AssetAccountId is not { } asset || c.FundAccountId is not { } fundAccount)
{
return;
}
var bought = new DateOnly(year - yearsBack, 3, 15);
assets.Add(new AssetInput(null, null, description, c.Id, bought, bought, cost)
{
OpeningCivilFund = fund,
OpeningFiscalFund = fund,
LastDepreciationYear = yearsBack > 0 ? year - 1 : null,
SerialNumber = serial,
Location = location,
});
if (yearsBack > 0)
{
lines.Add(new EntryLineDraft(asset, null, description, cost, 0m));
lines.Add(new EntryLineDraft(fundAccount, null, description, 0m, fund));
}
}
// Funds: the civil quotas of the years before, half in the first year.
Add("AUC", "Furgone Fiat Ducato 2.3 Multijet", 3, 32_000m, 16_000m, "ZFA25000002K12345", "Sede");
Add("ATT", "Scaffalature metalliche magazzino", 2, 18_400m, 4_140m, null, "Magazzino");
Add("MOB", "Arredi ufficio commerciale", 4, 9_600m, 4_032m, null, "Uffici");
Add("EDP", "Server e personal computer", 0, 6_500m, 0m, "SRV-2026-001", "Sala server");
}
// The opening stock of the demo warehouse (the inventory entry of the first of January) at its cost.
var stock = (await InventoryService.ValuationAsync(uow, start, null, StockValuationMethod.WeightedAverage, cancellationToken).ConfigureAwait(false)).Sum(r => r.Value);
if (stock > 0m && accounts.TryGetValue(closing.Accounts.Inventory, out var inventory))
{
lines.Add(new EntryLineDraft(inventory.Id, null, "Rimanenze iniziali", Math.Round(stock, 2, MidpointRounding.AwayFromZero), 0m));
}
lines.Add(new EntryLineDraft(bank.Id, null, null, OpeningBank, 0m));
lines.Add(new EntryLineDraft(capital.Id, null, null, 0m, ShareCapital));
if (accounts.TryGetValue(RetainedEarnings, out var retained))
{
var balance = lines.Sum(l => l.Debit - l.Credit);
lines.Add(new EntryLineDraft(retained.Id, null, null, balance < 0m ? -balance : 0m, balance > 0m ? balance : 0m));
}
await YearEndLedger.PostAsync(uow, start, "Apertura conti (dati dimostrativi)", GlEntrySource.Manual, null, lines, true, cancellationToken).ConfigureAwait(false);
foreach (var input in assets)
{
await FixedAssetService.SaveAsync(uow, pack.Require(), input, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
if (input.LastDepreciationYear is null
&& (await FixedAssetService.CategoriesAsync(uow, cancellationToken).ConfigureAwait(false)).FirstOrDefault(c => c.Id == input.CategoryId) is { AssetAccountId: { } account })
{
// Bought this year: the purchase, paid by bank transfer (the invoice of the supplier is not part of the demo).
var bought = input.PurchaseDate;
await YearEndLedger.PostAsync(uow, bought <= today ? bought : today, "Acquisto " + input.Description.ToLowerInvariant(), GlEntrySource.Manual, null,
[new EntryLineDraft(account, null, null, input.Cost, 0m), new EntryLineDraft(bank.Id, null, null, 0m, input.Cost)], true, cancellationToken)
.ConfigureAwait(false);
}
}
}
// The insurance premium of the van, paid on the first of October for a year: three months fall in this year, nine
// in the next (prepaid expense).
private static async Task InsuranceAsync(IUnitOfWork uow, DateOnly today, CancellationToken cancellationToken)
{
var accounts = await YearEndLedger.AccountsByCodeAsync(uow, cancellationToken).ConfigureAwait(false);
var paid = new DateOnly(today.Year, 10, 1);
if (paid > today || !accounts.TryGetValue(InsuranceAccount, out var insurance) || !accounts.TryGetValue(DemoLedgerSeeder.BankAccount, out var bank))
{
return;
}
const string description = "Premio assicurazione furgone 01/10 - 30/09";
await YearEndLedger.PostAsync(uow, paid, description, GlEntrySource.Manual, null,
[new EntryLineDraft(insurance.Id, null, null, InsurancePremium, 0m), new EntryLineDraft(bank.Id, null, null, 0m, InsurancePremium)], true, cancellationToken)
.ConfigureAwait(false);
await AccrualService.SaveAsync(uow, new AccrualDeferral
{
Year = today.Year,
Kind = AccrualKind.PrepaidExpense,
Description = description,
AccountId = insurance.Id,
Amount = InsurancePremium,
PeriodStart = paid,
PeriodEnd = paid.AddYears(1).AddDays(-1),
DocumentNumber = "POL-4471",
}, Seed.UserName, true, cancellationToken).ConfigureAwait(false);
}
// An invoice under the declaration of intent of Idrotermica Piemonte (NI8C) and an intra-EU sale of goods to
// Bergwerk Bau (NI41), both of today so that the numbering stays in date order.
private async Task InvoicesAsync(string company, DateOnly today, CancellationToken cancellationToken)
{
Dictionary parties;
List- goods;
Dictionary taxCodes;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
parties = (await uow.Repository().ListAsync(Query.For().Where(p => p.IsDemo), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(p => p.Name, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
goods = [.. (await uow.Repository
- ().ListAsync(Query.For
- ().Where(i => i.IsDemo && i.Kind == ItemKind.Goods), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(i => i.Id)];
taxCodes = (await uow.Repository().ListAsync(Query.For(), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(t => t.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
if (await uow.Repository().CountAsync(Query.For(), cancellationToken).ConfigureAwait(false) == 0)
{
return; // No demo sales: the documents would open the numbering.
}
}
var intrastat = goods.Where(i => !string.IsNullOrEmpty(i.CustomsCode) && i.NetWeight is > 0m).Take(2).ToList();
if (parties.TryGetValue("Idrotermica Piemonte S.r.l.", out var idrotermica) && taxCodes.TryGetValue("NI8C", out var ni8c) && goods.Count > 3)
{
await InvoiceAsync(company, idrotermica, today, [(goods[1], 40m), (goods[3], 25m)], ni8c, "Fornitura in sospensione d'imposta", cancellationToken).ConfigureAwait(false);
}
if (licenses.IsModuleActive(ModuleCodes.Intrastat) && parties.TryGetValue("Bergwerk Bau GmbH", out var bergwerk) && taxCodes.TryGetValue("NI41", out var ni41)
&& intrastat.Count > 0)
{
await InvoiceAsync(company, bergwerk, today, [.. intrastat.Select(i => (i, 30m))], ni41, "Consegna franco destino Innsbruck", cancellationToken).ConfigureAwait(false);
}
}
private async Task InvoiceAsync(
string company, long partyId, DateOnly date, IReadOnlyList<(Item Item, decimal Quantity)> lines, long taxCodeId, string notes, CancellationToken cancellationToken)
{
var record = await engine.NewAsync(Seed, company, "FI", cancellationToken).ConfigureAwait(false);
record.Header.IsDemo = true;
record.Header.DocumentDate = date;
record.Header.Notes = notes;
await editor.ApplyPartyAsync(Seed, company, record, partyId, cancellationToken).ConfigureAwait(false);
foreach (var (item, quantity) in lines)
{
var line = DocumentStores.Of(record.Family).NewLine();
line.Quantity = quantity;
await editor.FillLineAsync(Seed, company, record, line, item.Id, cancellationToken).ConfigureAwait(false);
line.TaxCodeId = taxCodeId;
record.Lines.Add(line);
}
record = await engine.SaveAsync(Seed, company, record, cancellationToken).ConfigureAwait(false);
await engine.ConfirmAsync(Seed, company, record.Family, record.Header.Id, cancellationToken).ConfigureAwait(false);
}
}