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;
///
/// 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 KHAEMHAT_TEST_PG names a server.
///
[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();
var statements = app.Services.GetRequiredService();
var queries = app.Services.GetRequiredService();
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(() => 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(() => 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();
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(() => 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(() => 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();
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();
var refused = await InvoiceAsync(app.Services, company, idrotermica.Declaration.PartyId, 1_000_000m);
var error = await Assert.ThrowsExactlyAsync(() => 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().CreateAsync(DatabaseScope.Company(company)))
{
rossi = (await uow.Repository().FindAsync(Query.For().Where(p => p.Name == "Rossi Impianti S.r.l.")))!.Id;
}
var none = await InvoiceAsync(app.Services, company, rossi, 1m);
error = await Assert.ThrowsExactlyAsync(() => 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();
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(() => 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 InvoiceAsync(IServiceProvider services, string company, long partyId, decimal quantity)
{
var engine = services.GetRequiredService();
var editor = services.GetRequiredService();
long item;
long ni8c;
await using (var uow = await services.GetRequiredService().CreateAsync(DatabaseScope.Company(company)))
{
item = (await uow.Repository- ().FindAsync(Query.For
- ().Where(i => i.IsDemo && i.Kind == ItemKind.Goods).OrderBy(i => i.Id)))!.Id;
ni8c = (await uow.Repository().FindAsync(Query.For().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().ActivateAsync(Root, "KH-TEST-ALL-0000-9999");
Assert.IsTrue(activation.Succeeded, activation.Outcome);
await services.GetRequiredService().RunAsync(company, SeedKind.Demo);
var context = new CompanySeedContext(IsNew: false, Base: false, Demo: true);
await services.GetRequiredService().SeedAsync(company, context);
await services.GetRequiredService().SeedAsync(company, context);
await services.GetRequiredService().SeedAsync(company, context);
await services.GetRequiredService().SeedAsync(company, context);
await services.GetRequiredService().SeedAsync(company, context);
await services.GetRequiredService().SeedAsync(company, context);
}
}