feat: fixed assets, Intrastat, intent declarations, year-end closing and statements (#82 #83 #84 #85 #86 #87)
CI / Build and test (SQLite) (pull_request) Successful in 4m35s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Successful in 1m24s

M10 gives the ledger its year end. Fixed assets get categories with the
ministerial coefficients, a civil and a fiscal plan, depreciation posted
per category and undoable, disposals with gain or loss and the register
print (ADR 0041). Intrastat lists are generated from confirmed invoices
with the due periodicity and the SCAMBI.CEE file; declarations of intent
get their own register and the N3.5 ceiling is checked when an invoice is
confirmed (ADR 0042). Accruals, deferrals and exchange differences feed a
nine-step guided closing that can repeat or undo its last step until the
final prints, reopens the next year and locks the closed one; the CEE
statements (ordinary, abbreviated, micro), the reclassified statements,
the ratios and the accountant export read the year's balances (ADR 0043).

The demo seed now opens the year with assets, stock, bank and capital, so
the integration test closes the demo year from the checks to the lock on
SQLite and PostgreSQL. Docs: wiki pages with screenshots, ADR 0041-0043,
MODULES, STATUS, DATA-MODEL and the 0.10.0 changelog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 19:31:26 +01:00
1 parent 836a316b05
commit 51007d68ca
84 files changed
+11701 -298

No files matched your search

@@ -0,0 +1,267 @@
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;
/// <summary>
/// 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.
/// </summary>
/// <param name="engine">The document engine.</param>
/// <param name="editor">The document editor.</param>
/// <param name="ledger">Posts the new invoices.</param>
/// <param name="packs">The fiscal pack of the company.</param>
/// <param name="factory">Reads and writes the company.</param>
/// <param name="licenses">Which modules are licensed.</param>
/// <param name="clock">The clock.</param>
public sealed class DemoYearEndSeeder(
DocumentEngine engine, DocumentEditor editor, LedgerService ledger, CompanyFiscalContext packs, IUnitOfWorkFactory factory, ILicenseGate licenses, TimeProvider clock)
: ICompanySeeder
{
/// <summary>The share capital of the demo company.</summary>
public const decimal ShareCapital = 50_000m;
/// <summary>The bank balance on the first of January.</summary>
public const decimal OpeningBank = 25_000m;
/// <summary>The yearly insurance premium paid on the first of October.</summary>
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;
/// <inheritdoc />
public int Order => 70;
/// <inheritdoc />
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<GlAccount, long>().CountAsync(Query.For<GlAccount>(), cancellationToken).ConfigureAwait(false) == 0
|| await uow.Repository<FixedAsset, long>().CountAsync(Query.For<FixedAsset>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<AccrualDeferral, long>().CountAsync(Query.For<AccrualDeferral>(), cancellationToken).ConfigureAwait(false) > 0
|| await uow.Repository<GlEntry, long>().CountAsync(Query.For<GlEntry>().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<IIntentRules>() 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<IClosingRules>() 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<EntryLineDraft>();
var assets = new List<AssetInput>();
if (licenses.IsModuleActive(ModuleCodes.Assets) && pack.GetFeature<IFixedAssetRules>() 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<IFixedAssetRules>(), 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<string, long> parties;
List<Item> goods;
Dictionary<string, long> taxCodes;
await using (var uow = await factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false))
{
parties = (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().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<Item, long>().ListAsync(Query.For<Item>().Where(i => i.IsDemo && i.Kind == ItemKind.Goods), cancellationToken).ConfigureAwait(false)).Items
.OrderBy(i => i.Id)];
taxCodes = (await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>(), cancellationToken).ConfigureAwait(false)).Items
.GroupBy(t => t.Code, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().Id, StringComparer.Ordinal);
if (await uow.Repository<SaleDocument, long>().CountAsync(Query.For<SaleDocument>(), 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);
}
}