M7 adds the double-entry ledger so that the documents of M5 and M6 reach the accounts without retyping, and the Italian VAT obligations can be prepared from the same data. - Chart of accounts on three levels with the Italian "PMI standard" model in the fiscal pack, journal templates with proposed lines, VAT registers; the chart import now writes the accounts and exports them (#62, ADR 0036). - Journal entries: draft, posted, final with the libro giornale number, reversal; recurring entries with the nightly ledger.recurring job (#63). - Documents post their entry inside the document transaction (PostingEngine, LedgerPoster) with VAT lines, open items and withholdings; a change rewrites the same entry, a cancellation removes or reverses it (#64, ADR 0037). - VAT registers with final print, monthly or quarterly settlement with pro rata, interest, minimum and advance, confirmation with the LIQ entry, period lock and F24 line, LIPE file and F24 data (#65). - Operated and suffered withholdings, CU data, stamp duty by quarter with the 5,000 euro threshold, F24 summary with its payment entry (#66). - Party ledgers, account ledgers, trial balance and libro giornale (#67). - Demo accounting with the settlements of the past months confirmed and checked by hand in a test; wiki Contabilita, IVA, Fiscalita italiana completed with screenshots; CHANGELOG 0.7.0, STATUS, ADR 0036-0037 (#68). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
11 KiB
C#
179 lines
11 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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<LedgerQueryService>();
|
|
var vat = app.Services.GetRequiredService<VatService>();
|
|
var journal = app.Services.GetRequiredService<JournalEntryService>();
|
|
|
|
// 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<LedgerService>().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<TaxService>().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<DemoLedgerSeeder>();
|
|
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<SeedRunner>().RunAsync(company, SeedKind.Base);
|
|
var ledger = app.Services.GetRequiredService<LedgerService>();
|
|
var journal = app.Services.GetRequiredService<JournalEntryService>();
|
|
var queries = app.Services.GetRequiredService<LedgerQueryService>();
|
|
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<ValidationFailedException>(
|
|
() => 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<ValidationFailedException>(() => 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<ValidationFailedException>(() => 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<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);
|
|
}
|
|
|
|
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}"));
|
|
}
|