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

@@ -87,6 +87,8 @@ public sealed class MappingTests
"payments", "payment_lines", "remittances", "remittance_lines", "sdd_mandates", "bank_statements", "bank_statement_lines",
"bank_match_rules", "dunning_levels", "dunning_letters",
"e_invoices", "e_invoice_notifications", "e_invoice_inbox", "e_invoice_channels", "e_invoice_routing", "e_invoice_conservation",
"fixed_asset_categories", "fixed_assets", "fixed_asset_movements", "accruals", "closing_runs", "closing_steps", "closing_prints",
"intrastat_lists", "intrastat_list_lines", "intent_declarations",
];
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
}
@@ -22,6 +22,8 @@ public sealed class ItalyFiscalPackTests
Assert.IsTrue(Pack.Supports<IWithholdingRules>());
Assert.IsTrue(Pack.Supports<IFixedAssetRules>());
Assert.IsTrue(Pack.Supports<ITaxPaymentFormExporter>());
Assert.IsTrue(Pack.Supports<IFinancialStatementsSchema>());
Assert.IsTrue(Pack.Supports<IIntrastatExporter>());
Assert.AreSame(Pack.TaxCodes, Pack.GetFeature<ITaxCodeCatalog>());
Assert.AreSame(Pack.Calendar, Pack.Require<IFiscalCalendar>());
}
@@ -29,10 +31,10 @@ public sealed class ItalyFiscalPackTests
[TestMethod]
public void Require_OfAFeatureNotYetDelivered_SaysWhichOne()
{
var ex = Assert.ThrowsExactly<FiscalFeatureNotAvailableException>(() => Pack.Require<IIntrastatExporter>());
var ex = Assert.ThrowsExactly<FiscalFeatureNotAvailableException>(() => Pack.Require<IFutureFeature>());
Assert.AreEqual("IT", ex.CountryCode);
Assert.AreEqual(nameof(IIntrastatExporter), ex.Feature);
Assert.AreEqual(nameof(IFutureFeature), ex.Feature);
}
[TestMethod]
@@ -49,6 +51,9 @@ public sealed class ItalyFiscalPackTests
[TestMethod]
public void Catalog_RefusesTwoPacksForOneCountry() =>
Assert.ThrowsExactly<ArgumentException>(() => new FiscalPackCatalog([Pack, new ItalyFiscalPack()]));
/// <summary>A feature no pack delivers.</summary>
public interface IFutureFeature;
}
[TestClass]
@@ -0,0 +1,195 @@
using System.Text;
using Khaemhat.Core.Accounting;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy.Tests;
[TestClass]
public sealed class CeeSchemaItTests
{
private static readonly CeeSchemaIt Schema = new();
[TestMethod]
public void Ordinary_HasTheLinesOfTheCivilCode()
{
var assets = Schema.Lines(FinancialStatementKind.Assets, FinancialStatementForm.Ordinary);
var liabilities = Schema.Lines(FinancialStatementKind.Liabilities, FinancialStatementForm.Ordinary);
var income = Schema.Lines(FinancialStatementKind.IncomeStatement, FinancialStatementForm.Ordinary);
Assert.IsTrue(assets.Any(l => l.Code == "C.II.5-quater"));
Assert.IsTrue(liabilities.Single(l => l.Code == "A.IX").CreditNormal);
Assert.AreEqual("21", income[^1].Code);
CollectionAssert.AreEqual(new[] { "A", "B", "C", "D", "20" }, income[^1].Totals!.ToArray());
Assert.IsFalse(income.Single(l => l.Code == "C.17").CreditNormal);
Assert.IsTrue(income.Single(l => l.Code == "C.17-bis").CreditNormal);
}
[TestMethod]
public void Lines_HaveUniqueCodesAndKnownParents()
{
foreach (var kind in Enum.GetValues<FinancialStatementKind>())
{
foreach (var form in Enum.GetValues<FinancialStatementForm>())
{
var lines = Schema.Lines(kind, form);
var codes = lines.Select(l => l.Code).ToHashSet(StringComparer.Ordinal);
Assert.HasCount(lines.Count, codes, $"{kind} {form}");
Assert.IsTrue(lines.All(l => l.ParentCode is null || codes.Contains(l.ParentCode)), $"{kind} {form}");
}
}
}
[TestMethod]
[DataRow("B.II.4", FinancialStatementKind.Assets, "B.II")]
[DataRow("C.II.5-bis", FinancialStatementKind.Assets, "C.II")]
[DataRow("D.7", FinancialStatementKind.Liabilities, "D")]
[DataRow("A.IX", FinancialStatementKind.Liabilities, "A.IX")]
[DataRow("B.9.a", FinancialStatementKind.IncomeStatement, "B.9")]
[DataRow("B.10.d", FinancialStatementKind.IncomeStatement, "B.10")]
[DataRow("C.17-bis", FinancialStatementKind.IncomeStatement, "C.17-bis")]
public void Abbreviated_CollapsesToTheRomanNumerals(string code, FinancialStatementKind kind, string expected)
{
Assert.AreEqual(expected, Schema.Collapse(code, kind, FinancialStatementForm.Abbreviated));
Assert.AreEqual(expected, Schema.Collapse(code, kind, FinancialStatementForm.Micro));
Assert.AreEqual(code, Schema.Collapse(code, kind, FinancialStatementForm.Ordinary));
}
[TestMethod]
public void Collapse_OfAnUnknownCodeIsNull() =>
Assert.IsNull(Schema.Collapse("Z.9", FinancialStatementKind.Assets, FinancialStatementForm.Ordinary));
[TestMethod]
public void EveryLineOfTheChart_IsInTheSchema()
{
var template = new ItalianLedgerTemplate();
var missing = template.Accounts
.Where(a => !string.IsNullOrEmpty(a.StatementLine))
.Where(a => Schema.Collapse(a.StatementLine!, KindOf(a.Nature), FinancialStatementForm.Ordinary) is null)
.Select(a => a.Code + " " + a.StatementLine)
.ToList();
Assert.IsEmpty(missing, string.Join(", ", missing));
}
[TestMethod]
public void Reclassifications_ReferToKnownLines()
{
foreach (var kind in Enum.GetValues<ReclassificationKind>())
{
var lines = Schema.Reclassification(kind);
var codes = new HashSet<string>(StringComparer.Ordinal);
foreach (var line in lines)
{
var schema = Schema.Lines(line.Source, FinancialStatementForm.Ordinary).Select(l => l.Code).ToHashSet();
Assert.IsTrue(line.Lines.All(schema.Contains), line.Code);
Assert.IsTrue((line.Totals ?? []).All(t => codes.Contains(t.TrimStart('-'))), line.Code);
codes.Add(line.Code);
}
}
}
private static FinancialStatementKind KindOf(AccountNature nature) => nature switch
{
AccountNature.Asset => FinancialStatementKind.Assets,
AccountNature.Liability => FinancialStatementKind.Liabilities,
_ => FinancialStatementKind.IncomeStatement,
};
}
[TestClass]
public sealed class IntrastatExporterItTests
{
private static readonly IntrastatExporterIt Exporter = new();
[TestMethod]
[DataRow(49_999.99, 0, IntrastatPeriodicity.Quarterly, IntrastatPeriodicity.Quarterly)]
[DataRow(50_000, 0, IntrastatPeriodicity.Monthly, IntrastatPeriodicity.Quarterly)]
[DataRow(0, 60_000, IntrastatPeriodicity.Quarterly, IntrastatPeriodicity.Monthly)]
public void Sales_AreMonthlyFrom50000PerQuarter(double goods, double services, IntrastatPeriodicity g, IntrastatPeriodicity s)
{
var due = Exporter.Due(IntrastatFlow.Sales, (decimal)goods, (decimal)services);
Assert.AreEqual(g, due.Goods);
Assert.AreEqual(s, due.Services);
}
[TestMethod]
public void Purchases_AreDueOnlyAboveTheThresholds()
{
var below = Exporter.Due(IntrastatFlow.Purchases, 349_999m, 99_999m);
var goods = Exporter.Due(IntrastatFlow.Purchases, 350_000m, 0m);
var services = Exporter.Due(IntrastatFlow.Purchases, 0m, 100_000m);
Assert.AreEqual(IntrastatPeriodicity.NotDue, below.List);
Assert.AreEqual(IntrastatPeriodicity.Monthly, goods.Goods);
Assert.AreEqual(IntrastatPeriodicity.NotDue, goods.Services);
Assert.AreEqual(IntrastatPeriodicity.Monthly, services.List);
}
[TestMethod]
[DataRow("73043100", true)]
[DataRow("7304310", false)]
[DataRow("7304310A", false)]
[DataRow(null, false)]
public void Nomenclature_IsEightDigits(string? code, bool valid) => Assert.AreEqual(valid, Exporter.ValidNomenclature(code));
[TestMethod]
public void MemberStates_AreTheTwentySevenWithGreeceAsGR()
{
Assert.HasCount(27, Exporter.MemberStates);
Assert.Contains("GR", Exporter.MemberStates);
Assert.DoesNotContain("NO", Exporter.MemberStates);
}
[TestMethod]
public void File_HasAFrontispieceAndOneFixedRecordPerIncludedLine()
{
var list = new IntrastatList { Flow = IntrastatFlow.Sales, Year = 2026, Period = 10, Periodicity = IntrastatPeriodicity.Monthly, Progressive = 3 };
IntrastatListLine[] lines =
[
new() { Id = 1, Section = IntrastatSection.Goods, CountryCode = "AT", VatNumber = "U12345678", Amount = 12_400.40m, NomenclatureCode = "73043100", TransactionNature = "11", NetMass = 820m, DeliveryTerms = "DAP", TransportMode = "3", Province = "TO" },
new() { Id = 2, Section = IntrastatSection.Services, CountryCode = "DE", VatNumber = "123456789", Amount = 900m, NomenclatureCode = "711210", SupplyMode = "I", PaymentMode = "B", DocumentNumber = "FV 2026/0101", DocumentDate = new DateOnly(2026, 10, 12) },
new() { Id = 3, Section = IntrastatSection.Goods, CountryCode = "NO", Amount = 5_000m, Check = IntrastatCheck.OutsideEu },
];
var text = Encoding.ASCII.GetString(Exporter.Write(new IntrastatReturn(list, lines, "01234567890")));
var records = text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
Assert.HasCount(3, records);
Assert.IsTrue(records.All(r => r.Length == IntrastatExporterIt.RecordLength));
Assert.StartsWith("EUROX01234567890000003000000C26M10", records[0]);
Assert.Contains("000010000000012400", records[0]);
Assert.StartsWith("EUROX01234567890000003100001AT", records[1]);
Assert.StartsWith("EUROX01234567890000003300002DE", records[2]);
Assert.AreEqual("SCAMBI.CEE", Exporter.FileName(new IntrastatReturn(list, lines, "01234567890")));
}
}
[TestClass]
public sealed class MinisterialCoefficientsTests
{
[TestMethod]
public void Coefficients_UseAccountsOfTheChart()
{
var accounts = new ItalianLedgerTemplate().Accounts.Select(a => a.Code).ToHashSet(StringComparer.Ordinal);
var missing = MinisterialCoefficients.All
.SelectMany(c => new[] { c.AssetAccount, c.FundAccount, c.DepreciationAccount })
.Where(code => !accounts.Contains(code))
.ToList();
Assert.IsEmpty(missing, string.Join(", ", missing));
Assert.HasCount(MinisterialCoefficients.All.Count, MinisterialCoefficients.All.Select(c => c.Code).Distinct().ToList());
}
[TestMethod]
public void Cars_HaveTheTaxLimits()
{
var car = MinisterialCoefficients.All.Single(c => c.Code == "AUV");
Assert.AreEqual(25m, car.Rate);
Assert.AreEqual(18_075.99m, car.CostLimit);
Assert.AreEqual(20m, car.DeductiblePercent);
Assert.AreSame(MinisterialCoefficients.All, new FixedAssetRulesIt().Coefficients);
}
}
@@ -50,11 +50,12 @@ internal static partial class TestInstance
/// <summary>Builds and starts an instance with changes to its services (fake external services).</summary>
/// <param name="configureServices">The changes.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <param name="extra">More arguments, which win over the defaults (another system database).</param>
/// <returns>The running instance, its address and the company code.</returns>
public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync(
Action<Microsoft.Extensions.DependencyInjection.IServiceCollection>? configureServices, CancellationToken cancellationToken)
Action<Microsoft.Extensions.DependencyInjection.IServiceCollection>? configureServices, CancellationToken cancellationToken, params string[] extra)
{
var app = KhaemhatApp.Build(Arguments(out var company), configureServices);
var app = KhaemhatApp.Build(Arguments(out var company, extra), configureServices);
await app.StartAsync(cancellationToken);
var address = new Uri(app.Urls.First());
using var client = new HttpClient { BaseAddress = address };
@@ -6,6 +6,7 @@ using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tax;
using Khaemhat.Web.Ledger;
using Khaemhat.Web.Shell;
using Khaemhat.Web.YearEnd;
namespace Khaemhat.Web.Tests.Shell;
@@ -118,6 +119,36 @@ public sealed partial class LocalizationRulesTests
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k))));
}
[TestMethod]
public void YearEndEnumsErrorsAndMessages_HaveTexts()
{
var keys = new List<string>();
foreach (var type in new[]
{
typeof(AssetStatus), typeof(AssetClass), typeof(AssetMovementKind), typeof(IntrastatFlow), typeof(IntrastatPeriodicity),
typeof(IntrastatSection), typeof(IntrastatCheck), typeof(IntrastatStatus), typeof(Khaemhat.Core.Parties.IntentStatus),
typeof(Khaemhat.Core.Parties.IntentDirection), typeof(ClosingStepStatus), typeof(AccrualKind),
typeof(Khaemhat.Fiscal.Abstractions.FinancialStatementForm), typeof(Khaemhat.Fiscal.Abstractions.ReclassificationKind),
typeof(Khaemhat.Core.Tables.FiscalYearStatus),
})
{
keys.AddRange(Enum.GetValues(type).Cast<Enum>().Select(YearEndScreens.EnumKey));
}
keys.AddRange(typeof(Khaemhat.Application.YearEnd.YearEndErrors).GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!));
keys.AddRange(Enumerable.Range(1, Khaemhat.Application.YearEnd.ClosingService.StepCount)
.SelectMany(n => new[] { "YearEnd.Closing.Steps." + n + ".Title", "YearEnd.Closing.Steps." + n + ".Detail" }));
keys.AddRange(Khaemhat.Core.Accounting.FinancialRatios.Compute(new RatioInputs(0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 365))
.SelectMany(r => new[] { "YearEnd.Statements.RatioNames." + r.Code, "YearEnd.Statements.RatioFormulas." + r.Code }));
// The messages of the closing steps, as the service writes them: "code|value", "!code" a warning, "-code" an error.
var service = File.ReadAllText(Path.Combine(Repository.Root, "src", "Khaemhat.Application", "YearEnd", "ClosingService.cs"));
keys.AddRange(MessagePattern().Matches(service).Select(m => m.Groups[1].Value).Distinct());
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList(), string.Join(", ", keys.Where(k => !ShellTests.Texts.Contains(k))));
}
[TestMethod]
public void TextFiles_AvoidCharactersGiteaFlagsAsAmbiguous()
{
@@ -295,6 +326,9 @@ public sealed partial class LocalizationRulesTests
[GeneratedRegex(@"&[a-zA-Z]+;|&#\d+;")]
private static partial Regex EntityPattern();
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport|Ledger)\\.[A-Za-z0-9_.]+)\"")]
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport|Ledger|YearEnd)\\.[A-Za-z0-9_.]+)\"")]
private static partial Regex KeyPattern();
[GeneratedRegex(@"""[!-]?(closing\.[a-z-]+)[|""]")]
private static partial Regex MessagePattern();
}
@@ -0,0 +1,311 @@
using System.IO.Compression;
using System.Text;
using Khaemhat.Application.Documents;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Application.YearEnd;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Items;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tables;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.YearEnd;
/// <summary>
/// The year end on a real instance (issues #82-#87): the guided closing of the demo year from the checks to the lock,
/// with the statements that balance before and the accounts that are zero after; the life of a fixed asset; the
/// ceiling of a declaration of intent that stops an invoice; the Intrastat list of the intra-EU sale and its file; the
/// export for the accountant. On SQLite, and on PostgreSQL when <c>KHAEMHAT_TEST_PG</c> names a server.
/// </summary>
[TestClass]
public sealed class YearEndTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
public TestContext TestContext { get; set; } = null!;
private static DateOnly Today => DateOnly.FromDateTime(DateTime.Now);
[TestMethod]
[DataRow("sqlite")]
[DataRow("postgres")]
public async Task DemoYear_ClosesFromTheChecksToTheLock(string engine)
{
var (app, company) = await StartAsync(engine);
await using (app)
{
await SeedAsync(app.Services, company);
var closing = app.Services.GetRequiredService<ClosingService>();
var statements = app.Services.GetRequiredService<FinancialStatementsService>();
var queries = app.Services.GetRequiredService<LedgerQueryService>();
var year = Today.Year;
// Before the closing the statements balance, the result included, and every account has its line.
var before = await statements.StatementsAsync(Root, company, year, FinancialStatementForm.Ordinary);
TestContext.WriteLine($"Assets {before.TotalAssets.Current} liabilities {before.TotalLiabilities.Current} result {before.Result.Current}");
Assert.IsEmpty(before.Unmapped, string.Join(", ", before.Unmapped.Select(u => u.Code + " " + u.Balance)));
Assert.IsTrue(before.Balanced, $"Assets {before.TotalAssets.Current} liabilities {before.TotalLiabilities.Current}");
Assert.IsGreaterThan(0m, before.TotalAssets.Current);
var abbreviated = await statements.StatementsAsync(Root, company, year, FinancialStatementForm.Abbreviated);
Assert.AreEqual(before.TotalAssets.Current, abbreviated.TotalAssets.Current, "The forms differ in detail, not in totals.");
Assert.AreEqual(before.Result.Current, abbreviated.Result.Current);
Assert.HasCount(11, await statements.RatiosAsync(Root, company, year));
Assert.IsNotEmpty(await statements.ReclassifiedAsync(Root, company, year, ReclassificationKind.Financial));
Assert.IsNotEmpty(await statements.ReclassifiedAsync(Root, company, year, ReclassificationKind.ValueAdded));
// The nine steps in order; the third undone and run again on the way.
var view = await closing.GetAsync(Root, company);
Assert.AreEqual(year.ToString(System.Globalization.CultureInfo.InvariantCulture), view.Year.Code);
var yearId = view.Year.Id;
FinancialStatements? adjusted = null;
for (var number = 1; number <= ClosingService.StepCount; number++)
{
view = await closing.RunStepAsync(Root, company, yearId, number);
if (number == 3)
{
view = await closing.UndoStepAsync(Root, company, yearId, 3);
Assert.AreEqual(ClosingStepStatus.Pending, view.Steps[2].Status);
view = await closing.RunStepAsync(Root, company, yearId, 3);
}
var step = view.Steps[number - 1];
TestContext.WriteLine($"{number}: {step.Status} {step.Entries} {step.Amount} {step.Messages?.Replace('\n', ' ')}");
Assert.AreNotEqual(ClosingStepStatus.Failed, step.Status, step.Messages);
Assert.AreNotEqual(ClosingStepStatus.Pending, step.Status);
if (number == 5)
{
adjusted = await statements.StatementsAsync(Root, company, year, FinancialStatementForm.Ordinary);
Assert.IsTrue(adjusted.Balanced, "The adjustments keep the statements balanced.");
}
if (number == 7)
{
// Every account is zero once the income statement and the balance sheet are closed.
var closed = await queries.TrialBalanceAsync(Root, company, new DateOnly(year, 1, 1), new DateOnly(year, 12, 31));
var open = closed.Lines.Where(l => l.Level == 3 && l.Closing != 0m).Select(l => l.Code + " " + l.Closing).ToList();
Assert.IsEmpty(open, string.Join(", ", open));
}
}
Assert.IsNull(view.NextStep);
Assert.AreEqual(adjusted!.Result.Current, view.Run!.Result, "The result of step 6 is the result of the adjusted statements.");
// The next year opens with the same balances, the accruals reversed.
var next = view.Years.Single(y => y.StartDate == new DateOnly(year + 1, 1, 1));
var opening = await queries.TrialBalanceAsync(Root, company, next.StartDate, next.StartDate);
Assert.IsTrue(opening.Balanced);
Assert.IsGreaterThan(0m, opening.TotalDebit);
var reopened = await statements.StatementsAsync(Root, company, year + 1, FinancialStatementForm.Ordinary);
Assert.AreEqual(adjusted.TotalAssets.Current, reopened.TotalAssets.Previous, "The year before of the next year is this year.");
Assert.IsTrue(reopened.Balanced, "The next year opens with the balances of the year closed.");
// The final prints are kept, the last step cannot be undone, then the lock.
Assert.IsGreaterThanOrEqualTo(3, view.Prints.Count);
foreach (var print in view.Prints)
{
var file = await closing.PrintAsync(Root, company, print.Id);
Assert.IsTrue(Encoding.ASCII.GetString(file.Content, 0, 5).StartsWith("%PDF", StringComparison.Ordinal), print.FileName);
}
var irreversible = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => closing.UndoStepAsync(Root, company, yearId, ClosingService.StepCount));
StringAssert.Contains(string.Join(" ", irreversible.Errors), YearEndErrors.StepIrreversible);
view = await closing.LockAsync(Root, company, yearId);
Assert.AreEqual(FiscalYearStatus.Closed, view.Year.Status);
Assert.AreEqual(ClosingStatus.Locked, view.Run!.Status);
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => closing.LockAsync(Root, company, yearId));
// The export for the accountant: chart, trial balance, journal and statements.
var export = await statements.AccountantExportAsync(Root, company, year);
using var zip = new ZipArchive(new MemoryStream(export.Content));
CollectionAssert.IsSubsetOf(
new[] { "piano-dei-conti.csv", "bilancio-di-verifica.csv", "movimenti.csv", "stato-patrimoniale.csv", "conto-economico.csv" },
zip.Entries.Select(e => e.Name).ToList());
await app.StopAsync();
}
}
[TestMethod]
[DataRow("sqlite")]
[DataRow("postgres")]
public async Task FixedAsset_IsDepreciated_UndoneAndDisposed(string engine)
{
var (app, company) = await StartAsync(engine);
await using (app)
{
await SeedAsync(app.Services, company);
var assets = app.Services.GetRequiredService<FixedAssetService>();
var year = Today.Year;
var rows = await assets.ListAsync(Root, company);
Assert.HasCount(4, rows, "The demo assets.");
var categories = await assets.CategoriesAsync(Root, company);
var edp = categories.Single(c => c.Code == "EDP");
// A computer bought this year: half the rate in the first year, civil and fiscal alike.
var view = await assets.SaveAsync(Root, company, new AssetInput(null, null, "Notebook di prova", edp.Id, new DateOnly(year, 1, 10), new DateOnly(year, 1, 10), 1_200m));
Assert.AreEqual(AssetStatus.Active, view.Asset.Status);
var line = (await assets.DepreciationAsync(Root, company, year)).Single(l => l.AssetId == view.Asset.Id);
Assert.AreEqual(Math.Round(1_200m * edp.CivilRate / 100m / 2m, 2), line.Civil);
Assert.AreEqual(line.Civil, line.Fiscal);
var posted = await assets.PostDepreciationAsync(Root, company, year);
Assert.IsGreaterThan(0m, posted);
Assert.IsTrue((await assets.DepreciationAsync(Root, company, year)).All(l => l.Posted || l.Civil == 0m));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => assets.DeleteAsync(Root, company, view.Asset.Id));
await assets.UndoDepreciationAsync(Root, company, year);
Assert.IsTrue((await assets.DepreciationAsync(Root, company, year)).All(l => !l.Posted));
// The van sold: the share of the year to the date, then the gain or the loss.
var van = rows.Single(r => r.Category.Code == "AUC").Asset;
var sold = await assets.DisposeAsync(Root, company, van.Id, new DisposalInput(Today, 15_000m));
Assert.AreEqual(AssetStatus.Disposed, sold.Asset.Status);
Assert.IsTrue(sold.Movements.Any(m => m.Kind == AssetMovementKind.Disposal));
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => assets.DisposeAsync(Root, company, van.Id, new DisposalInput(Today, 1m)));
var register = await assets.PrintRegisterAsync(Root, company, year);
Assert.IsGreaterThan(1000, register.Content.Length);
await app.StopAsync();
}
}
[TestMethod]
[DataRow("sqlite")]
[DataRow("postgres")]
public async Task DeclarationOfIntent_StopsTheInvoiceAboveTheCeiling(string engine)
{
var (app, company) = await StartAsync(engine);
await using (app)
{
await SeedAsync(app.Services, company);
var intents = app.Services.GetRequiredService<IntentDeclarationService>();
var received = await intents.ListAsync(Root, company, IntentDirection.Received, Today.Year);
var idrotermica = received.Single(r => r.PartyName == "Idrotermica Piemonte S.r.l.");
Assert.IsGreaterThan(0m, idrotermica.Declaration.Used, "The demo invoice under the declaration uses the ceiling.");
var coverage = await intents.CoverageAsync(Root, company, idrotermica.Declaration.PartyId, Today);
Assert.AreEqual(idrotermica.Declaration.Id, coverage.Declaration?.Id);
// An invoice above what is left is refused when it is issued; a customer without declaration too.
var documents = app.Services.GetRequiredService<DocumentEngine>();
var refused = await InvoiceAsync(app.Services, company, idrotermica.Declaration.PartyId, 1_000_000m);
var error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => documents.ConfirmAsync(Root, company, refused.Family, refused.Header.Id));
StringAssert.Contains(string.Join(" ", error.Errors), YearEndErrors.CeilingExceeded);
long rossi;
await using (var uow = await app.Services.GetRequiredService<IUnitOfWorkFactory>().CreateAsync(DatabaseScope.Company(company)))
{
rossi = (await uow.Repository<Party, long>().FindAsync(Query.For<Party>().Where(p => p.Name == "Rossi Impianti S.r.l.")))!.Id;
}
var none = await InvoiceAsync(app.Services, company, rossi, 1m);
error = await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => documents.ConfirmAsync(Root, company, none.Family, none.Header.Id));
StringAssert.Contains(string.Join(" ", error.Errors), YearEndErrors.NoDeclaration);
// Within the ceiling the invoice goes, and the ceiling used grows by its amount.
var small = await InvoiceAsync(app.Services, company, idrotermica.Declaration.PartyId, 1m);
await documents.ConfirmAsync(Root, company, small.Family, small.Header.Id);
var after = (await intents.ListAsync(Root, company, IntentDirection.Received, Today.Year)).Single(r => r.Declaration.Id == idrotermica.Declaration.Id);
Assert.AreEqual(idrotermica.Declaration.Used + small.Lines.Sum(l => l.TaxableAmount), after.Declaration.Used);
var register = await intents.PrintRegisterAsync(Root, company, IntentDirection.Received, Today.Year);
Assert.IsGreaterThan(500, register.Content.Length);
await app.StopAsync();
}
}
[TestMethod]
[DataRow("sqlite")]
[DataRow("postgres")]
public async Task Intrastat_ListOfTheIntraEuSale_IsGeneratedExportedAndSent(string engine)
{
var (app, company) = await StartAsync(engine);
await using (app)
{
await SeedAsync(app.Services, company);
var intrastat = app.Services.GetRequiredService<IntrastatService>();
var view = await intrastat.GenerateAsync(Root, company, IntrastatFlow.Sales, Today.Year, IntrastatPeriodicity.Monthly, Today.Month);
foreach (var l in view.Lines)
{
TestContext.WriteLine($"{l.Section} {l.CountryCode} {l.VatNumber} {l.NomenclatureCode} {l.Amount} {l.NetMass} {l.Check}");
}
var austria = view.Lines.Where(l => l.CountryCode == "AT").ToList();
Assert.IsNotEmpty(austria, "The sale to Bergwerk Bau.");
Assert.IsTrue(austria.All(l => l.Section == IntrastatSection.Goods && l.NetMass > 0m && l.Check == IntrastatCheck.Ok));
Assert.AreEqual(view.Lines.Where(l => l.Section == IntrastatSection.Goods).Sum(l => l.Amount), view.List.GoodsAmount);
var file = await intrastat.ExportAsync(Root, company, view.List.Id);
var text = Encoding.ASCII.GetString(file.Content);
StringAssert.StartsWith(text, "EUROX");
StringAssert.Contains(text, "AT");
await intrastat.MarkSentAsync(Root, company, view.List.Id, "26111312345");
var sent = await intrastat.GetAsync(Root, company, view.List.Id);
Assert.AreEqual(IntrastatStatus.Sent, sent!.List.Status);
await Assert.ThrowsExactlyAsync<ValidationFailedException>(() => intrastat.DeleteLineAsync(Root, company, austria[0].Id));
await app.StopAsync();
}
}
private async Task<(Microsoft.AspNetCore.Builder.WebApplication App, string Company)> StartAsync(string engine)
{
if (engine == "sqlite")
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
return (app, company);
}
var server = Environment.GetEnvironmentVariable("KHAEMHAT_TEST_PG");
if (string.IsNullOrEmpty(server))
{
Assert.Inconclusive("KHAEMHAT_TEST_PG is not set: PostgreSQL test skipped.");
}
var root = server[..(server.LastIndexOf('/') + 1)];
var id = Guid.NewGuid().ToString("N")[..8];
var (pgApp, _, pgCompany) = await TestInstance.StartAsync(null, CancellationToken.None, "--KHAEMHAT_SYSTEM_DB=" + root + "khs_" + id);
TestContext.WriteLine("PostgreSQL system database khs_" + id);
return (pgApp, pgCompany);
}
private static async Task<DocumentRecord> InvoiceAsync(IServiceProvider services, string company, long partyId, decimal quantity)
{
var engine = services.GetRequiredService<DocumentEngine>();
var editor = services.GetRequiredService<DocumentEditor>();
long item;
long ni8c;
await using (var uow = await services.GetRequiredService<IUnitOfWorkFactory>().CreateAsync(DatabaseScope.Company(company)))
{
item = (await uow.Repository<Item, long>().FindAsync(Query.For<Item>().Where(i => i.IsDemo && i.Kind == ItemKind.Goods).OrderBy(i => i.Id)))!.Id;
ni8c = (await uow.Repository<TaxCode, long>().FindAsync(Query.For<TaxCode>().Where(t => t.Code == "NI8C")))!.Id;
}
var record = await engine.NewAsync(Root, company, "FI");
record.Header.DocumentDate = Today;
await editor.ApplyPartyAsync(Root, company, record, partyId);
var line = new SaleDocumentLine { Quantity = quantity };
await editor.FillLineAsync(Root, company, record, line, item);
line.TaxCodeId = ni8c;
record.Lines.Add(line);
return await engine.SaveAsync(Root, company, record);
}
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);
await services.GetRequiredService<DemoYearEndSeeder>().SeedAsync(company, context);
}
}