using System.Globalization;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Application.Seeding;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Security;
using Khaemhat.Core.Tax;
using Khaemhat.Web.Tests.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Khaemhat.Web.Tests.Ledger;
///
/// The demo accounting and the ledger flows on a real instance (issues #63-#68): the demo documents posted and balanced,
/// the settlements of the periods ended confirmed and checked by hand against the VAT registers, the withholding of the
/// professional due, the recurring rent, an entry typed, posted, reversed and made final.
///
[TestClass]
public sealed class DemoLedgerTests
{
private static readonly Actor Root = new(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task DemoSeed_PostsTheYear_AndSettlesThePeriodsEnded()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await SeedAsync(app.Services, company);
var today = DateOnly.FromDateTime(DateTime.Now);
var queries = app.Services.GetRequiredService();
var vat = app.Services.GetRequiredService();
var journal = app.Services.GetRequiredService();
// Every document of the year is in the journal, and the trial balance balances.
var (entries, total) = await journal.ListAsync(Root, company, new EntryFilter(Limit: 500));
Assert.IsGreaterThan(10, total);
Assert.IsTrue(entries.Any(e => e.Entry.Source == GlEntrySource.Document));
var rents = Enumerable.Range(2, today.Month - 1).Count(m => new DateOnly(today.Year, m, 5) <= today);
Assert.AreEqual(rents, entries.Count(e => e.Entry.Source == GlEntrySource.Recurring), "The rent of every month after January.");
var balance = await queries.TrialBalanceAsync(Root, company, new DateOnly(today.Year, 1, 1), today);
Assert.IsTrue(balance.Balanced, $"Debit {balance.TotalDebit} credit {balance.TotalCredit}");
// The settlements of the periods ended are confirmed, in order.
var settlements = await vat.SettlementsAsync(Root, company, today.Year);
Assert.IsNotEmpty(settlements);
Assert.IsTrue(settlements.All(s => s.Status == VatSettlementStatus.Confirmed));
foreach (var s in settlements.OrderBy(s => s.Number))
{
TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"{s.Number}/{s.Year}: sales {s.SalesTax:0.00} purchases {s.PurchaseTax:0.00} credit in {s.PreviousCredit:0.00} due {s.AmountDue:0.00} credit out {s.CreditCarried:0.00}"));
}
var first = settlements.Where(s => s.SalesTax != 0m || s.PurchaseTax != 0m).OrderBy(s => s.Number).First();
// The first settlement with VAT checked by hand against the registers.
var registers = await app.Services.GetRequiredService().RegistersAsync(Root, company);
decimal sales = 0m, deductible = 0m;
foreach (var register in registers)
{
var view = await vat.RegisterAsync(Root, company, register.Id, first.StartDate, first.EndDate);
var due = view.Rows.Where(r => r.Exigibility == TaxExigibility.Immediate).Sum(r => r.Tax);
if (register.Kind == VatRegisterKind.Purchases)
{
deductible += due - view.Rows.Sum(r => r.NonDeductibleTax);
}
else
{
sales += due;
}
}
deductible = ProRataCalculator.Deductible(deductible, first.ProRataPercent);
var difference = sales - deductible - first.PreviousCredit + first.PreviousDebit;
var interest = difference > 0m ? Math.Round(difference * first.InterestPercent / 100m, 2, MidpointRounding.AwayFromZero) : 0m;
var expected = difference + interest >= 25.82m ? difference + interest : 0m;
Report(first, sales, deductible, interest, expected);
Assert.AreEqual(sales, first.SalesTax);
Assert.AreEqual(deductible, first.PurchaseTax);
Assert.AreEqual(expected, first.AmountDue);
Assert.AreEqual(difference < 0m ? -difference : 0m, first.CreditCarried);
if (first.AmountDue > 0m)
{
Assert.IsNotNull(first.GlEntryId);
Assert.IsNotNull(first.TaxPaymentId);
}
// The professional's invoice is paid: its withholding is due (or already paid with an F24).
var withholdings = await app.Services.GetRequiredService().WithholdingsAsync(Root, company, today.Year, WithholdingDirection.Operated);
Assert.IsNotEmpty(withholdings);
Assert.IsTrue(withholdings.All(w => w.Withholding.Status is WithholdingStatus.Due or WithholdingStatus.Paid));
// Run again, nothing changes.
var seeder = app.Services.GetRequiredService();
await seeder.SeedAsync(company, new CompanySeedContext(IsNew: false, Base: false, Demo: true));
Assert.AreEqual(total, (await journal.ListAsync(Root, company, new EntryFilter(Limit: 1))).Total);
await app.StopAsync();
}
}
[TestMethod]
public async Task AnEntry_IsTypedPostedReversedAndMadeFinal()
{
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
await using (app)
{
await app.Services.GetRequiredService().RunAsync(company, SeedKind.Base);
var ledger = app.Services.GetRequiredService();
var journal = app.Services.GetRequiredService();
var queries = app.Services.GetRequiredService();
var accounts = (await ledger.AccountsAsync(Root, company)).ToDictionary(a => a.Code, StringComparer.Ordinal);
var rent = accounts[DemoLedgerSeeder.RentAccount].Id;
var bank = accounts[DemoLedgerSeeder.BankAccount].Id;
var day = new DateOnly(DateTime.Now.Year, 1, 10);
// An unbalanced entry is kept as a draft, not posted.
EntryLineDraft[] half = [new(rent, null, null, 500m, 0m), new(bank, null, null, 0m, 400m)];
var draft = await journal.SaveAsync(Root, company, new EntryInput(null, day, "Affitto", half));
Assert.AreEqual(GlEntryStatus.Draft, draft.Entry.Status);
var refused = await Assert.ThrowsExactlyAsync(
() => journal.SaveAsync(Root, company, new EntryInput(draft.Entry.Id, day, "Affitto", half) { Post = true }));
Assert.Contains("Lines:" + LedgerErrors.Unbalanced, refused.Errors);
// Balanced, it is posted with its number; the rent account moves.
EntryLineDraft[] lines = [new(rent, null, null, 500m, 0m), new(bank, null, null, 0m, 500m)];
var posted = await journal.SaveAsync(Root, company, new EntryInput(draft.Entry.Id, day, "Affitto", lines) { Post = true });
Assert.AreEqual(GlEntryStatus.Posted, posted.Entry.Status);
Assert.IsNotNull(posted.Entry.EntryNumber);
var page = await queries.MovementsAsync(Root, company, new LedgerFilter(rent, null, day.AddDays(-9), day.AddDays(20)));
Assert.AreEqual(500m, page.Closing);
// The reversal cancels it, and a second reversal is refused.
var reversal = await journal.ReverseAsync(Root, company, posted.Entry.Id, day.AddDays(1));
Assert.AreEqual(GlEntrySource.Reversal, reversal.Entry.Source);
page = await queries.MovementsAsync(Root, company, new LedgerFilter(rent, null, day.AddDays(-9), day.AddDays(20)));
Assert.AreEqual(0m, page.Closing);
Assert.AreEqual(2, page.TotalCount);
var again = await Assert.ThrowsExactlyAsync(() => journal.ReverseAsync(Root, company, posted.Entry.Id, day.AddDays(2)));
Assert.IsTrue(again.Errors.Any(e => e.EndsWith(LedgerErrors.AlreadyReversed, StringComparison.Ordinal)));
// Made final, the entries get their journal number and cannot be deleted.
Assert.AreEqual(2, await journal.FinalizeAsync(Root, company, day.AddDays(1)));
var final = await journal.GetAsync(Root, company, posted.Entry.Id);
Assert.AreEqual(GlEntryStatus.Final, final!.Entry.Status);
var locked = await Assert.ThrowsExactlyAsync(() => journal.DeleteAsync(Root, company, posted.Entry.Id));
Assert.IsTrue(locked.Errors.Any(e => e.EndsWith(LedgerErrors.Final, StringComparison.Ordinal)));
await app.StopAsync();
}
}
[TestMethod]
[DataRow("2026-01-31", RecurrenceFrequency.Monthly, "2026-02-28")]
[DataRow("2026-02-28", RecurrenceFrequency.Monthly, "2026-03-31")]
[DataRow("2026-01-05", RecurrenceFrequency.Monthly, "2026-02-05")]
[DataRow("2026-01-15", RecurrenceFrequency.Quarterly, "2026-04-15")]
[DataRow("2026-03-31", RecurrenceFrequency.HalfYearly, "2026-09-30")]
[DataRow("2026-06-10", RecurrenceFrequency.Yearly, "2027-06-10")]
public void Recurring_NextDate_KeepsTheEndOfTheMonth(string date, RecurrenceFrequency frequency, string next) =>
Assert.AreEqual(DateOnly.Parse(next, CultureInfo.InvariantCulture), RecurringEntryService.Next(DateOnly.Parse(date, CultureInfo.InvariantCulture), frequency));
private static async Task SeedAsync(IServiceProvider services, string company)
{
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);
}
private void Report(VatSettlement settlement, decimal sales, decimal deductible, decimal interest, decimal expected) =>
TestContext.WriteLine(string.Create(CultureInfo.InvariantCulture,
$"Settlement {settlement.Number}/{settlement.Year} ({settlement.Periodicity}, {settlement.StartDate:dd/MM}-{settlement.EndDate:dd/MM}): " +
$"sales VAT {sales:0.00}, deductible {deductible:0.00}, previous credit {settlement.PreviousCredit:0.00}, interest {interest:0.00}, " +
$"due {expected:0.00}; code {settlement.PaymentCode} by {settlement.DueDate:dd/MM/yyyy}"));
}