feat: general ledger, automatic posting, VAT settlement, withholdings and F24 (#62 #63 #64 #65 #66 #67 #68)
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>
This commit is contained in:
1 parent
838362bfe1
commit
9e3ba92993
83 files changed
+13838
-497
No files matched your search
@@ -0,0 +1,299 @@
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tax;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Accounting;
|
||||
|
||||
/// <summary>
|
||||
/// The pure rules of the ledger (issues #62-#65): the checks of an entry, the account codes, the posting of each kind of
|
||||
/// document, the VAT settlement with pro rata, carried amounts, interest and minimum, and the December advance.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class LedgerRulesTests
|
||||
{
|
||||
private const long Customer = 1;
|
||||
private const long Supplier = 2;
|
||||
private const long Revenue = 3;
|
||||
private const long OtherRevenue = 4;
|
||||
private const long Cost = 5;
|
||||
private const long SalesVat = 6;
|
||||
private const long PurchaseVat = 7;
|
||||
private const long Stamp = 8;
|
||||
private const long Fund = 9;
|
||||
|
||||
private static readonly PostingAccounts SaleAccounts = new(Customer, Revenue, SalesVat, PurchaseVat, Stamp, Fund);
|
||||
private static readonly PostingAccounts PurchaseAccounts = new(Supplier, Cost, SalesVat, PurchaseVat, Stamp);
|
||||
|
||||
private static readonly Dictionary<long, AccountRule> Accounts = new()
|
||||
{
|
||||
[Customer] = new(Customer, Postable: true, Disabled: false, SubLedger: true),
|
||||
[Revenue] = new(Revenue, Postable: true, Disabled: false, SubLedger: false),
|
||||
[Cost] = new(Cost, Postable: false, Disabled: false, SubLedger: false),
|
||||
[SalesVat] = new(SalesVat, Postable: true, Disabled: true, SubLedger: false),
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
public void Validator_AcceptsABalancedEntry_AndAcceptsUnbalancedDrafts()
|
||||
{
|
||||
EntryLineCheck[] lines = [new(Customer, 10, 122m, 0m), new(Revenue, null, 0m, 122m)];
|
||||
Assert.IsEmpty(JournalEntryValidator.Check("Fattura", lines, 0, false, Accounts, posting: true));
|
||||
|
||||
EntryLineCheck[] half = [new(Revenue, null, 0m, 100m)];
|
||||
Assert.IsEmpty(JournalEntryValidator.Check("Bozza", half, 0, false, Accounts, posting: false));
|
||||
CollectionAssert.Contains(JournalEntryValidator.Check("Bozza", half, 0, false, Accounts, posting: true).ToList(), "Lines:" + LedgerErrors.Unbalanced);
|
||||
Assert.AreEqual(-100m, JournalEntryValidator.Difference(half));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Validator_ReportsEveryProblemOfTheLines()
|
||||
{
|
||||
EntryLineCheck[] lines =
|
||||
[
|
||||
new(null, null, 10m, 0m),
|
||||
new(99, null, 10m, 0m),
|
||||
new(Cost, null, 10m, 0m),
|
||||
new(SalesVat, null, 0m, 10m),
|
||||
new(Customer, null, 0m, 10m),
|
||||
new(Revenue, null, -5m, 0m),
|
||||
new(Revenue, null, 5m, 5m),
|
||||
new(Revenue, null, 0m, 0m),
|
||||
];
|
||||
|
||||
var errors = JournalEntryValidator.Check(" ", lines, 1, false, Accounts, posting: true);
|
||||
|
||||
CollectionAssert.IsSubsetOf(
|
||||
new[]
|
||||
{
|
||||
"Description:" + LedgerErrors.DescriptionRequired,
|
||||
"Lines.0.AccountId:" + LedgerErrors.AccountRequired,
|
||||
"Lines.1.AccountId:" + LedgerErrors.AccountMissing,
|
||||
"Lines.2.AccountId:" + LedgerErrors.AccountNotPostable,
|
||||
"Lines.3.AccountId:" + LedgerErrors.AccountDisabled,
|
||||
"Lines.4.PartyId:" + LedgerErrors.PartyRequired,
|
||||
"Lines.5.Debit:" + LedgerErrors.Negative,
|
||||
"Lines.6.Credit:" + LedgerErrors.BothSides,
|
||||
"Lines.7.Debit:" + LedgerErrors.AmountRequired,
|
||||
"VatRegisterId:" + LedgerErrors.VatRegisterRequired,
|
||||
},
|
||||
errors.ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("05", 1)]
|
||||
[DataRow("05.01", 2)]
|
||||
[DataRow("05.01.001", 3)]
|
||||
[DataRow("05.01.001.1", 0)]
|
||||
[DataRow("05..001", 0)]
|
||||
[DataRow("", 0)]
|
||||
[DataRow("05.0-1", 0)]
|
||||
public void AccountCodes_HaveUpToThreeLevels(string code, int level) => Assert.AreEqual(level, AccountCodes.LevelOf(code));
|
||||
|
||||
[TestMethod]
|
||||
public void AccountCodes_KnowTheirParent()
|
||||
{
|
||||
Assert.AreEqual("05.01", AccountCodes.ParentOf("05.01.001"));
|
||||
Assert.AreEqual("05", AccountCodes.ParentOf("05.01"));
|
||||
Assert.IsNull(AccountCodes.ParentOf("05"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Sale_DebitsTheCustomer_CreditsRevenuesStampAndVat()
|
||||
{
|
||||
var input = new PostingInput(
|
||||
PostingKind.Sale, false, 10,
|
||||
[new PostingLineInput(Revenue, 600m), new PostingLineInput(OtherRevenue, 400m), new PostingLineInput(Revenue, 0m)],
|
||||
[Tax(1000m, 22m, 220m)],
|
||||
Total: 1222m, StampDuty: 2m);
|
||||
|
||||
var result = PostingEngine.Post(input, SaleAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
Assert.AreEqual(1222m, Line(result, PostingRole.Customer).Debit);
|
||||
Assert.AreEqual(10L, Line(result, PostingRole.Customer).PartyId);
|
||||
Assert.AreEqual(600m, result.Lines.Single(l => l.AccountId == Revenue).Credit);
|
||||
Assert.AreEqual(400m, result.Lines.Single(l => l.AccountId == OtherRevenue).Credit);
|
||||
Assert.AreEqual(2m, Line(result, PostingRole.StampDuty).Credit);
|
||||
Assert.AreEqual(220m, Line(result, PostingRole.SalesVat).Credit);
|
||||
Assert.AreEqual(VatRegisterKind.Sales, result.Vat.Single().RegisterKind);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Sale_GivesTheFooterDiscountToTheLargestLine()
|
||||
{
|
||||
// Lines for 1000, a footer discount of 10: the summary says 990.
|
||||
var input = new PostingInput(PostingKind.Sale, false, 10,
|
||||
[new PostingLineInput(Revenue, 700m), new PostingLineInput(OtherRevenue, 300m)], [Tax(990m, 22m, 217.8m)], Total: 1207.8m);
|
||||
|
||||
var result = PostingEngine.Post(input, SaleAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
Assert.AreEqual(690m, result.Lines.Single(l => l.AccountId == Revenue).Credit);
|
||||
Assert.AreEqual(300m, result.Lines.Single(l => l.AccountId == OtherRevenue).Credit);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Sale_WithSplitPayment_TakesTheVatBackFromTheCustomer()
|
||||
{
|
||||
var input = new PostingInput(PostingKind.Sale, false, 10, [new PostingLineInput(Revenue, 1000m)],
|
||||
[Tax(1000m, 22m, 220m) with { Exigibility = TaxExigibility.SplitPayment }], Total: 1220m);
|
||||
|
||||
var result = PostingEngine.Post(input, SaleAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
var customer = result.Lines.Where(l => l.Role == PostingRole.Customer).Sum(l => l.Debit - l.Credit);
|
||||
Assert.AreEqual(1000m, customer, "The public body pays the taxable amount only.");
|
||||
Assert.AreEqual(220m, Line(result, PostingRole.SplitPaymentVat).Debit);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Fee_CreditsTheSocialSecurityCharged()
|
||||
{
|
||||
var input = new PostingInput(PostingKind.Sale, false, 10, [new PostingLineInput(Revenue, 1000m)], [Tax(1040m, 22m, 228.8m)],
|
||||
Total: 1268.8m, SocialSecurity: 40m);
|
||||
|
||||
var result = PostingEngine.Post(input, SaleAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
Assert.AreEqual(40m, Line(result, PostingRole.SocialSecurity).Credit);
|
||||
Assert.AreEqual(1000m, Line(result, PostingRole.Revenue).Credit);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Purchase_PutsTheNonDeductibleVatOnTheCost()
|
||||
{
|
||||
var input = new PostingInput(PostingKind.Purchase, false, 20, [new PostingLineInput(Cost, 500m, TaxCodeId: 77)],
|
||||
[new PostingTaxInput(77, 22m, null, TaxExigibility.Immediate, 500m, 110m, 66m)], Total: 610m);
|
||||
|
||||
var result = PostingEngine.Post(input, PurchaseAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
Assert.AreEqual(610m, Line(result, PostingRole.Supplier).Credit);
|
||||
Assert.AreEqual(566m, Line(result, PostingRole.Cost).Debit);
|
||||
Assert.AreEqual(44m, Line(result, PostingRole.PurchaseVat).Debit);
|
||||
Assert.AreEqual(VatRegisterKind.Purchases, result.Vat.Single().RegisterKind);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void CreditNote_ReversesEverySide_AndTheVat()
|
||||
{
|
||||
var input = new PostingInput(PostingKind.Sale, true, 10, [new PostingLineInput(Revenue, 100m)], [Tax(100m, 22m, 22m)], Total: 122m);
|
||||
|
||||
var result = PostingEngine.Post(input, SaleAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
Assert.AreEqual(122m, Line(result, PostingRole.Customer).Credit);
|
||||
Assert.AreEqual(100m, Line(result, PostingRole.Revenue).Debit);
|
||||
Assert.AreEqual(22m, Line(result, PostingRole.SalesVat).Debit);
|
||||
Assert.AreEqual(-22m, result.Vat.Single().Tax.Tax);
|
||||
Assert.AreEqual(-100m, result.Vat.Single().Tax.Taxable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SelfInvoice_WritesTheVatInBothRegisters()
|
||||
{
|
||||
var input = new PostingInput(PostingKind.SelfInvoice, false, null, [], [Tax(1000m, 22m, 220m)], Total: 220m);
|
||||
|
||||
var result = PostingEngine.Post(input, PurchaseAccounts);
|
||||
|
||||
Assert.AreEqual(result.Debit, result.Credit);
|
||||
Assert.AreEqual(220m, Line(result, PostingRole.PurchaseVat).Debit);
|
||||
Assert.AreEqual(220m, Line(result, PostingRole.SalesVat).Credit);
|
||||
CollectionAssert.AreEquivalent(new[] { VatRegisterKind.Sales, VatRegisterKind.Purchases }, result.Vat.Select(v => v.RegisterKind).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Posting_WithoutAnAccount_SaysWhichOne()
|
||||
{
|
||||
var input = new PostingInput(PostingKind.Sale, false, 10, [new PostingLineInput(Revenue, 100m)], [Tax(100m, 22m, 22m)], Total: 122m);
|
||||
|
||||
var missing = Assert.ThrowsExactly<PostingAccountMissingException>(() => PostingEngine.Post(input, SaleAccounts with { SalesVat = null }));
|
||||
|
||||
Assert.AreEqual(PostingRole.SalesVat, missing.Role);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Settlement_PaysTheDifference_WithQuarterlyInterest()
|
||||
{
|
||||
VatRegisterTotals[] registers =
|
||||
[
|
||||
new(1, VatRegisterKind.Sales, 10, 20000m, 4400m, 0m, 0m),
|
||||
new(2, VatRegisterKind.Receipts, 3, 1000m, 220m, 0m, 0m),
|
||||
new(3, VatRegisterKind.Purchases, 8, 10000m, 2200m, 200m, 0m),
|
||||
];
|
||||
|
||||
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(PreviousCredit: 300m, InterestPercent: 1m, MinimumPayment: 25.82m));
|
||||
|
||||
Assert.AreEqual(4620m, result.SalesTax);
|
||||
Assert.AreEqual(2000m, result.PurchaseTax);
|
||||
Assert.AreEqual(200m, result.NonDeductibleTax);
|
||||
Assert.AreEqual(2320m, result.Balance); // 4620 - 2000 - 300
|
||||
Assert.AreEqual(23.2m, result.Interest);
|
||||
Assert.AreEqual(2343.2m, result.AmountDue);
|
||||
Assert.AreEqual(0m, result.CreditCarried);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Settlement_InCredit_CarriesTheCredit()
|
||||
{
|
||||
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 1, 1000m, 220m, 0m, 0m), new(3, VatRegisterKind.Purchases, 1, 5000m, 1100m, 0m, 0m)];
|
||||
|
||||
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(InterestPercent: 1m, MinimumPayment: 25.82m));
|
||||
|
||||
Assert.AreEqual(0m, result.AmountDue);
|
||||
Assert.AreEqual(880m, result.CreditCarried);
|
||||
Assert.AreEqual(0m, result.Interest);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Settlement_BelowTheMinimum_CarriesTheDebit()
|
||||
{
|
||||
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 1, 100m, 22m, 0m, 0m)];
|
||||
|
||||
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(MinimumPayment: 25.82m));
|
||||
|
||||
Assert.AreEqual(0m, result.AmountDue);
|
||||
Assert.AreEqual(22m, result.DebitCarried);
|
||||
|
||||
var next = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(PreviousDebit: result.DebitCarried, MinimumPayment: 25.82m));
|
||||
Assert.AreEqual(44m, next.AmountDue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Settlement_LeavesTheDeferredVatForLater_AndDeductsTheAdvance()
|
||||
{
|
||||
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 2, 2000m, 440m, 0m, 220m)];
|
||||
|
||||
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(AdvancePaid: 100m));
|
||||
|
||||
Assert.AreEqual(220m, result.SalesTax);
|
||||
Assert.AreEqual(220m, result.DeferredTax);
|
||||
Assert.AreEqual(120m, result.AmountDue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ProRata_RoundsUp_AndLimitsTheDeduction()
|
||||
{
|
||||
Assert.AreEqual(100m, ProRataCalculator.Percent(1000m, 0m));
|
||||
Assert.AreEqual(67m, ProRataCalculator.Percent(2000m, 1000m)); // 66.67 rounded up
|
||||
Assert.AreEqual(670m, ProRataCalculator.Deductible(1000m, 67m));
|
||||
|
||||
VatRegisterTotals[] registers = [new(1, VatRegisterKind.Sales, 1, 10000m, 2200m, 0m, 0m), new(3, VatRegisterKind.Purchases, 1, 5000m, 1000m, 0m, 0m)];
|
||||
var result = VatSettlementCalculator.Compute(registers, new VatSettlementTerms(ProRataPercent: 67m));
|
||||
Assert.AreEqual(670m, result.PurchaseTax);
|
||||
Assert.AreEqual(330m, result.NonDeductibleTax);
|
||||
Assert.AreEqual(1530m, result.AmountDue);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Advance_IsEightyEightPercent_AndNothingBelowTheMinimum()
|
||||
{
|
||||
Assert.AreEqual(880m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Historical, 1000m, 88m, 103.29m));
|
||||
Assert.AreEqual(440m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Forecast, 500m, 88m, 103.29m));
|
||||
Assert.AreEqual(500m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Actual, 500m, 88m, 103.29m));
|
||||
Assert.AreEqual(0m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Historical, 100m, 88m, 103.29m));
|
||||
Assert.AreEqual(0m, VatAdvanceCalculator.Compute(VatAdvanceMethod.Actual, -10m, 88m, 103.29m));
|
||||
}
|
||||
|
||||
private static PostingTaxInput Tax(decimal taxable, decimal rate, decimal tax) => new(1, rate, null, TaxExigibility.Immediate, taxable, tax, 0m);
|
||||
|
||||
private static PostedLine Line(PostingResult result, PostingRole role) => result.Lines.Single(l => l.Role == role);
|
||||
}
|
||||
@@ -82,6 +82,8 @@ public sealed class MappingTests
|
||||
"purchase_orders", "purchase_order_lines", "purchase_documents", "purchase_document_lines", "inventory_documents", "inventory_document_lines",
|
||||
"document_links", "document_tax_summaries", "document_installments",
|
||||
"inventory_entries", "inventory_entry_lines", "item_balances", "stock_takes", "stock_take_lines",
|
||||
"gl_accounts", "vat_registers", "gl_journal_templates", "gl_journal_template_lines", "gl_entries", "gl_entry_lines", "gl_entry_vat",
|
||||
"gl_open_items", "gl_recurring_entries", "vat_settlements", "vat_settlement_lines", "tax_payments", "withholdings", "vat_register_prints",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
using System.Text;
|
||||
using System.Xml.Linq;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The Italian ledger (issues #62, #65, #66): the model chart of accounts and its templates, the F24 codes and due dates
|
||||
/// of VAT, withholdings and stamp duty, the LIPE file and the F24 data file.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ItalianLedgerTests
|
||||
{
|
||||
private static readonly ItalyFiscalPack Pack = new();
|
||||
private static readonly ILedgerTemplate Template = Pack.Require<ILedgerTemplate>();
|
||||
private static readonly IVatSettlementRules Rules = Pack.Require<IVatSettlementRules>();
|
||||
|
||||
[TestMethod]
|
||||
public void Chart_HasValidCodes_WithTheirParentsFirst()
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
Assert.IsGreaterThan(100, Template.Accounts.Count);
|
||||
foreach (var account in Template.Accounts)
|
||||
{
|
||||
Assert.AreNotEqual(0, account.Level, account.Code);
|
||||
Assert.IsTrue(seen.Add(account.Code), "Duplicate " + account.Code);
|
||||
if (account.ParentCode is { } parent)
|
||||
{
|
||||
Assert.Contains(parent, seen, account.Code + " comes before its parent " + parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Templates_UseAccountsOfTheChart_AndTheRolesHaveSubAccounts()
|
||||
{
|
||||
var accounts = Template.Accounts.ToDictionary(a => a.Code, StringComparer.Ordinal);
|
||||
var registers = Template.VatRegisters.Select(r => r.Code).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var template in Template.JournalTemplates)
|
||||
{
|
||||
Assert.IsTrue(template.Reverses || template.Lines.Count > 0, template.Code + " proposes its lines (only the reversal copies them)");
|
||||
if (template.VatRegisterCode is { } register)
|
||||
{
|
||||
Assert.Contains(register, registers, template.Code);
|
||||
}
|
||||
|
||||
foreach (var line in template.Lines.Where(l => l.AccountCode is not null))
|
||||
{
|
||||
Assert.IsTrue(accounts.TryGetValue(line.AccountCode!, out var account), template.Code + " " + line.AccountCode);
|
||||
Assert.AreEqual(3, account.Level, template.Code + " posts on a sub-account");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var role in Enum.GetValues<PostingRole>().Where(r => r != PostingRole.Account))
|
||||
{
|
||||
if (Template.AccountOf(role) is { } code)
|
||||
{
|
||||
Assert.AreEqual(3, accounts[code].Level, role.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsTrue(accounts[ItalianLedgerTemplate.Customers].SubLedger);
|
||||
Assert.IsTrue(accounts[ItalianLedgerTemplate.Suppliers].SubLedger);
|
||||
var templates = Template.JournalTemplates.Select(t => t.Code).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var posting in Template.DocumentPostings)
|
||||
{
|
||||
Assert.Contains(posting.JournalTemplateCode, templates, posting.DocumentTypeCode);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Templates_ForTheSettlementAndThePayments_Exist()
|
||||
{
|
||||
var codes = Template.JournalTemplates.Select(t => t.Code).ToList();
|
||||
CollectionAssert.IsSubsetOf(new[] { "FV", "NCV", "FA", "NCA", "LIQ", "F24", "RIT", "RITS" }, codes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(VatPeriodicity.Monthly, 1, "6001", null)]
|
||||
[DataRow(VatPeriodicity.Monthly, 12, "6012", null)]
|
||||
[DataRow(VatPeriodicity.Quarterly, 1, "6031", null)]
|
||||
[DataRow(VatPeriodicity.Quarterly, 3, "6033", null)]
|
||||
[DataRow(VatPeriodicity.Quarterly, 4, "6099", "0101")]
|
||||
public void VatPaymentCodes(VatPeriodicity periodicity, int number, string code, string? period)
|
||||
{
|
||||
var tax = TaxPeriod.Of(2026, number, periodicity);
|
||||
Assert.AreEqual(code, Rules.PaymentCode(tax));
|
||||
Assert.AreEqual(period, Rules.PaymentPeriod(tax));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheRules_HaveTheItalianAmounts()
|
||||
{
|
||||
Assert.AreEqual(25.82m, Rules.MinimumPayment);
|
||||
Assert.AreEqual(88m, Rules.AdvancePercent);
|
||||
Assert.AreEqual(103.29m, Rules.AdvanceMinimum);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DueDates_MoveToTheNextWorkingDay_AndAugustToThe20th()
|
||||
{
|
||||
// The withholdings of March 2026 by 16 April (a Thursday); of July by 20 August.
|
||||
Assert.AreEqual(new DateOnly(2026, 4, 16), Rules.WithholdingDue(2026, 3));
|
||||
Assert.AreEqual(new DateOnly(2026, 8, 20), Rules.WithholdingDue(2026, 7));
|
||||
// 16 May 2026 is a Saturday: Monday 18.
|
||||
Assert.AreEqual(new DateOnly(2026, 5, 18), Rules.WithholdingDue(2026, 4));
|
||||
// The stamp duty of the second quarter by 30 September, of the first by 31 May (a Sunday: 1 June).
|
||||
Assert.AreEqual(new DateOnly(2026, 9, 30), Rules.StampDutyDue(2026, 2));
|
||||
Assert.AreEqual(new DateOnly(2026, 6, 1), Rules.StampDutyDue(2026, 1));
|
||||
// The advance by 27 December (a Sunday in 2026: Monday 28).
|
||||
Assert.AreEqual(new DateOnly(2026, 12, 28), Rules.AdvanceDue(2026));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Lipe_WritesOneModulePerPeriod_WithCommaAmounts()
|
||||
{
|
||||
var data = new PeriodicVatReturn(2026, 3, "01234567890", "01234567890", null, null, new DateOnly(2026, 11, 13),
|
||||
[
|
||||
new PeriodicVatReturnModule(TaxPeriod.Of(2026, 3, VatPeriodicity.Quarterly), 20000m, 10000m, 4400m, 2200m, 0m, 300m, 19m, 0m, 1919m),
|
||||
]);
|
||||
var writer = Pack.Require<IPeriodicVatReturnWriter>();
|
||||
|
||||
var xml = XDocument.Parse(Encoding.UTF8.GetString(writer.Write(data)));
|
||||
XNamespace iv = LipeWriter.Namespace;
|
||||
var module = xml.Descendants(iv + "Modulo").Single();
|
||||
|
||||
Assert.AreEqual("IT01234567890_LI_2026_T3.xml", writer.FileName(data));
|
||||
Assert.AreEqual("IVP18", xml.Descendants(iv + "CodiceFornitura").Single().Value);
|
||||
Assert.AreEqual("3", module.Element(iv + "Trimestre")!.Value);
|
||||
Assert.AreEqual("4400,00", module.Element(iv + "IvaEsigibile")!.Value);
|
||||
Assert.AreEqual("2200,00", module.Element(iv + "IvaDovuta")!.Value);
|
||||
Assert.AreEqual("300,00", module.Element(iv + "CreditoPeriodoPrecedente")!.Value);
|
||||
Assert.AreEqual("1919,00", module.Element(iv + "ImportoDaVersare")!.Value);
|
||||
Assert.IsNull(module.Element(iv + "Acconto"), "Zero amounts are left out.");
|
||||
Assert.AreEqual("1234,50", LipeWriter.FormatAmount(1234.5m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void F24_ExportsTheErarioLines_AndTheBalance()
|
||||
{
|
||||
var form = new TaxPaymentForm(new DateOnly(2026, 11, 16), "01234567890", "Demo; S.r.l.",
|
||||
[
|
||||
new TaxPaymentFormLine("6033", null, 2026, 1919m, 0m, "IVA terzo trimestre"),
|
||||
new TaxPaymentFormLine("1040", "10", 2026, 400m, 0m, "Ritenute lavoro autonomo"),
|
||||
]);
|
||||
var exporter = Pack.Require<ITaxPaymentFormExporter>();
|
||||
|
||||
var lines = Encoding.UTF8.GetString(exporter.Export(form)).Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
Assert.AreEqual("F24;16/11/2026;01234567890;Demo, S.r.l.", lines[0]);
|
||||
Assert.AreEqual("ER;6033;;2026;1919,00;;IVA terzo trimestre", lines[2]);
|
||||
Assert.AreEqual("ER;1040;10;2026;400,00;;Ritenute lavoro autonomo", lines[3]);
|
||||
Assert.AreEqual("Saldo;;;;2319,00;;", lines[4]);
|
||||
Assert.AreEqual(2319m, form.Balance);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
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}"));
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Application.Preferences;
|
||||
using Khaemhat.Core.Accounting;
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Web.Ledger;
|
||||
using Khaemhat.Web.Shell;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Shell;
|
||||
@@ -94,6 +98,26 @@ public sealed partial class LocalizationRulesTests
|
||||
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LedgerEnumsAndErrors_HaveTexts()
|
||||
{
|
||||
var keys = new List<string>();
|
||||
foreach (var type in new[]
|
||||
{
|
||||
typeof(GlEntryStatus), typeof(GlEntrySource), typeof(RecurrenceFrequency), typeof(AccountNature), typeof(AccountType),
|
||||
typeof(JournalArea), typeof(PostingRole), typeof(AccountSide), typeof(VatRegisterKind), typeof(VatSettlementStatus),
|
||||
typeof(WithholdingStatus), typeof(VatAdvanceMethod), typeof(VatPeriodicity), typeof(TaxExigibility),
|
||||
})
|
||||
{
|
||||
keys.AddRange(Enum.GetValues(type).Cast<Enum>().Select(LedgerScreens.EnumKey));
|
||||
}
|
||||
|
||||
keys.AddRange(typeof(LedgerErrors).GetFields(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral).Select(f => (string)f.GetRawConstantValue()!));
|
||||
|
||||
Assert.IsEmpty(keys.Where(k => !ShellTests.Texts.Contains(k)).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TextFiles_AvoidCharactersGiteaFlagsAsAmbiguous()
|
||||
{
|
||||
@@ -271,6 +295,6 @@ 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)\\.[A-Za-z0-9_.]+)\"")]
|
||||
[GeneratedRegex("\"((?:Shell|Pages|Auth|Common|Ui|Dashboard|Parties|Items|ImportExport|Ledger)\\.[A-Za-z0-9_.]+)\"")]
|
||||
private static partial Regex KeyPattern();
|
||||
}
|
||||
Reference in new issue
Block a user