feat: fiscal pack abstractions and the Italian pack (#37)

The rest of the product needs tax codes, natures, code lists and VAT rules
without knowing the country. IFiscalPack exposes the parts every country has
(tax code catalog, tax engine, calendar) and optional features by type, so a
module can tell a missing feature from a broken one. FiscalPackCatalog finds
the pack by country; only the composition root names the Italian pack, as an
architecture test now checks.

The Italian pack carries the FatturaPA 1.9.1 code lists, VAT natures and base
tax codes with their rules, summary rounding on the total per rate, the stamp
duty rule, VAT deadlines with the August and holiday shifts, withholding kinds,
basic depreciation rules and F24 codes. ADR 0025 records the design.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 21:48:09 +01:00
1 parent 8079d3da69
commit 49d2bb166b
22 files changed
+1987 -17

No files matched your search

@@ -0,0 +1,71 @@
using Khaemhat.Core.Tax;
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>A tax period: a month or a quarter of a year.</summary>
/// <param name="Year">The year.</param>
/// <param name="Number">The month (1-12) or the quarter (1-4).</param>
/// <param name="Periodicity">Monthly or quarterly.</param>
/// <param name="Start">The first day.</param>
/// <param name="End">The last day.</param>
public sealed record TaxPeriod(int Year, int Number, VatPeriodicity Periodicity, DateOnly Start, DateOnly End)
{
/// <summary>The period of a periodicity that contains a date.</summary>
/// <param name="date">The date.</param>
/// <param name="periodicity">Monthly or quarterly.</param>
/// <returns>The period.</returns>
public static TaxPeriod Containing(DateOnly date, VatPeriodicity periodicity) =>
periodicity == VatPeriodicity.Monthly
? Of(date.Year, date.Month, periodicity)
: Of(date.Year, ((date.Month - 1) / 3) + 1, periodicity);
/// <summary>A period by number.</summary>
/// <param name="year">The year.</param>
/// <param name="number">The month (1-12) or the quarter (1-4).</param>
/// <param name="periodicity">Monthly or quarterly.</param>
/// <returns>The period.</returns>
public static TaxPeriod Of(int year, int number, VatPeriodicity periodicity)
{
var months = periodicity == VatPeriodicity.Monthly ? 1 : 3;
ArgumentOutOfRangeException.ThrowIfLessThan(number, 1);
ArgumentOutOfRangeException.ThrowIfGreaterThan(number, 12 / months);
var start = new DateOnly(year, ((number - 1) * months) + 1, 1);
return new TaxPeriod(year, number, periodicity, start, start.AddMonths(months).AddDays(-1));
}
/// <summary>Every period of a year.</summary>
/// <param name="year">The year.</param>
/// <param name="periodicity">Monthly or quarterly.</param>
/// <returns>12 months or 4 quarters.</returns>
public static IReadOnlyList<TaxPeriod> OfYear(int year, VatPeriodicity periodicity) =>
[.. Enumerable.Range(1, periodicity == VatPeriodicity.Monthly ? 12 : 4).Select(n => Of(year, n, periodicity))];
/// <summary>Whether a date falls in the period.</summary>
/// <param name="date">The date.</param>
/// <returns><see langword="true"/> inside the period.</returns>
public bool Contains(DateOnly date) => date >= Start && date <= End;
}
/// <summary>Tax deadlines and the days on which they move.</summary>
public interface IFiscalCalendar
{
/// <summary>The day by which the VAT of a period must be paid, already moved past holidays.</summary>
/// <param name="period">The period.</param>
/// <returns>The due date.</returns>
DateOnly VatPaymentDue(TaxPeriod period);
/// <summary>The interest added to the VAT of a period, in percent (Italy: 1% for quarterly payers).</summary>
/// <param name="periodicity">Monthly or quarterly.</param>
/// <returns>The rate in percent.</returns>
decimal VatInterestRate(VatPeriodicity periodicity);
/// <summary>Whether no tax payment can fall on a day (weekend or public holiday).</summary>
/// <param name="day">The day.</param>
/// <returns><see langword="true"/> for a non-working day.</returns>
bool IsNonWorkingDay(DateOnly day);
/// <summary>The day itself, or the next working day if it is not one.</summary>
/// <param name="day">The day.</param>
/// <returns>A working day.</returns>
DateOnly NextWorkingDay(DateOnly day);
}
@@ -0,0 +1,71 @@
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>One code of an official code list, such as <c>TD01</c> or <c>MP05</c>.</summary>
/// <param name="Code">The code as written in files and messages.</param>
/// <param name="Description">The official description, in the country's language.</param>
/// <param name="Obsolete">Kept to read old documents; not accepted on new ones.</param>
public sealed record CodeListEntry(string Code, string Description, bool Obsolete = false);
/// <summary>An official code list of a country (document types, payment methods, tax natures...).</summary>
public sealed class CodeList
{
private readonly Dictionary<string, CodeListEntry> _byCode;
/// <summary>Creates the list.</summary>
/// <param name="name">A stable name, such as <c>DocumentTypes</c>.</param>
/// <param name="entries">The entries in their official order; codes are unique, compared without case.</param>
public CodeList(string name, IEnumerable<CodeListEntry> entries)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentNullException.ThrowIfNull(entries);
Name = name;
Entries = [.. entries];
_byCode = new Dictionary<string, CodeListEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in Entries)
{
if (!_byCode.TryAdd(entry.Code, entry))
{
throw new ArgumentException($"Code '{entry.Code}' appears twice in {name}.", nameof(entries));
}
}
}
/// <summary>The name of the list.</summary>
public string Name { get; }
/// <summary>Every entry, obsolete ones included, in the official order.</summary>
public IReadOnlyList<CodeListEntry> Entries { get; }
/// <summary>The entries accepted on new documents.</summary>
public IEnumerable<CodeListEntry> Active => Entries.Where(e => !e.Obsolete);
/// <summary>An entry by code, obsolete ones included.</summary>
/// <param name="code">The code, compared without case.</param>
/// <returns>The entry, or <see langword="null"/>.</returns>
public CodeListEntry? Find(string? code) =>
code is not null && _byCode.TryGetValue(code.Trim(), out var entry) ? entry : null;
/// <summary>Whether a code exists and is accepted on new documents.</summary>
/// <param name="code">The code.</param>
/// <returns><see langword="true"/> for an active code.</returns>
public bool IsActive(string? code) => Find(code) is { Obsolete: false };
}
/// <summary>How serious a <see cref="FiscalProblem"/> is.</summary>
public enum FiscalProblemSeverity
{
/// <summary>The record cannot be saved.</summary>
Error = 0,
/// <summary>The record can be saved, but the user should check it.</summary>
Warning = 1,
}
/// <summary>
/// A rule of the country that a record breaks. <see cref="Code"/> is a stable key (such as
/// <c>fiscal.tax.nature-required</c>) that the interface translates; <see cref="Field"/> names the property at fault.
/// </summary>
/// <param name="Field">The property name, such as <c>Nature</c>.</param>
/// <param name="Code">The problem code.</param>
/// <param name="Severity">Error or warning.</param>
public sealed record FiscalProblem(string Field, string Code, FiscalProblemSeverity Severity = FiscalProblemSeverity.Error);
@@ -0,0 +1,194 @@
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tax;
namespace Khaemhat.Fiscal.Abstractions;
// The optional features of a country pack. Each interface starts with what the current milestone needs and grows with
// the milestone that uses it (writer and reader of e-invoices in M9, statements in M10...), see ADR 0025.
/// <summary>The country's electronic invoice format: version and code lists (Italy: FatturaPA).</summary>
public interface IEInvoiceFormat
{
/// <summary>The name of the format, such as <c>FatturaPA</c>.</summary>
string Name { get; }
/// <summary>The version of the official technical specifications that this pack follows.</summary>
string SpecVersion { get; }
/// <summary>The transmission formats (Italy: <c>FPR12</c>, <c>FPA12</c>, <c>FSM10</c>).</summary>
CodeList TransmissionFormats { get; }
/// <summary>The document types (Italy: <c>TD01</c>...).</summary>
CodeList DocumentTypes { get; }
/// <summary>The payment methods (Italy: <c>MP01</c>...).</summary>
CodeList PaymentMethods { get; }
/// <summary>The payment conditions (Italy: <c>TP01</c>...).</summary>
CodeList PaymentConditions { get; }
/// <summary>The tax regimes of the seller (Italy: <c>RF01</c>...).</summary>
CodeList TaxRegimes { get; }
}
/// <summary>A kind of withholding tax the company applies or suffers.</summary>
/// <param name="Code">A stable code, such as <c>PROF</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="Rate">The rate in percent.</param>
/// <param name="TaxableBasePercent">The share of the amount the rate applies to, in percent.</param>
/// <param name="PaymentCode">The tax payment code (Italy: F24 <c>1040</c>).</param>
/// <param name="InvoiceType">The type written in the e-invoice (Italy: <c>RT01</c>).</param>
/// <param name="PaymentReason">The default reason written in the e-invoice (Italy: <c>A</c>).</param>
public sealed record WithholdingKind(
string Code,
string Description,
decimal Rate,
decimal TaxableBasePercent,
string PaymentCode,
string InvoiceType,
string PaymentReason);
/// <summary>Withholding taxes and social security funds.</summary>
public interface IWithholdingRules
{
/// <summary>The usual kinds of withholding.</summary>
IReadOnlyList<WithholdingKind> Kinds { get; }
/// <summary>The withholding types of the e-invoice (Italy: <c>RT01</c>...).</summary>
CodeList InvoiceTypes { get; }
/// <summary>The payment reasons of the e-invoice (Italy: <c>A</c>, <c>B</c>... <c>ZO</c>).</summary>
CodeList PaymentReasons { get; }
/// <summary>The social security funds (Italy: <c>TC01</c>...).</summary>
CodeList SocialSecurityFunds { get; }
/// <summary>The tax withheld on an amount.</summary>
/// <param name="amount">The amount the withholding is computed on (fee, commission).</param>
/// <param name="kind">The kind of withholding.</param>
/// <returns>The withheld tax, rounded to the cent.</returns>
decimal Compute(decimal amount, WithholdingKind kind);
}
/// <summary>Depreciation rules for fixed assets.</summary>
public interface IFixedAssetRules
{
/// <summary>The share of the yearly rate allowed in the first year (Italy: 0.5).</summary>
decimal FirstYearFactor { get; }
/// <summary>The cost up to which an asset may be expensed in one year (Italy: 516.46).</summary>
decimal LowValueThreshold { get; }
/// <summary>The tax limit on the cost of a passenger car (Italy: 18,075.99).</summary>
decimal PassengerCarCostLimit { get; }
/// <summary>The depreciation of one year, never more than what is left to depreciate.</summary>
/// <param name="cost">The depreciable cost.</param>
/// <param name="ratePercent">The yearly rate in percent.</param>
/// <param name="firstYear">Whether this is the first year of use.</param>
/// <param name="alreadyDepreciated">The depreciation of the previous years.</param>
/// <returns>The depreciation, rounded to the cent.</returns>
decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated);
}
/// <summary>A tax payment code of the country's payment form (Italy: codice tributo F24).</summary>
/// <param name="Code">The code, such as <c>6001</c>.</param>
/// <param name="Description">What it pays.</param>
public sealed record TaxPaymentCode(string Code, string Description);
/// <summary>The country's tax payment form (Italy: F24); the file export arrives with the VAT settlement (M7).</summary>
public interface ITaxPaymentFormExporter
{
/// <summary>The name of the form, such as <c>F24</c>.</summary>
string FormName { get; }
/// <summary>The payment codes the product uses.</summary>
IReadOnlyList<TaxPaymentCode> Codes { get; }
/// <summary>The code for the VAT of a period.</summary>
/// <param name="period">The period.</param>
/// <returns>The payment code.</returns>
string VatCode(TaxPeriod period);
/// <summary>The code for the VAT advance of December.</summary>
/// <param name="periodicity">Monthly or quarterly.</param>
/// <returns>The payment code.</returns>
string VatAdvanceCode(VatPeriodicity periodicity);
/// <summary>The code for the stamp duty on e-invoices of a quarter.</summary>
/// <param name="quarter">The quarter, 1-4.</param>
/// <returns>The payment code.</returns>
string StampDutyCode(int quarter);
}
/// <summary>Which statement a schema line belongs to.</summary>
public enum FinancialStatementKind
{
/// <summary>Balance sheet (Italy: art. 2424 c.c.).</summary>
BalanceSheet = 0,
/// <summary>Income statement (Italy: art. 2425 c.c.).</summary>
IncomeStatement = 1,
}
/// <summary>A line of the legal financial statements.</summary>
/// <param name="Code">The code of the line, such as <c>B.II.1</c>.</param>
/// <param name="Description">The legal description.</param>
/// <param name="ParentCode">The line it adds up into, if any.</param>
/// <param name="Postable">Whether accounts can be mapped to it.</param>
public sealed record FinancialStatementLine(string Code, string Description, string? ParentCode, bool Postable);
/// <summary>The legal schema of the financial statements (arrives with the statements, M10).</summary>
public interface IFinancialStatementsSchema
{
/// <summary>The lines of a statement, in legal order.</summary>
/// <param name="kind">The statement.</param>
/// <returns>The lines.</returns>
IReadOnlyList<FinancialStatementLine> Lines(FinancialStatementKind kind);
}
/// <summary>An account of the country's model chart of accounts.</summary>
/// <param name="Code">The hierarchical code, such as <c>01.01.001</c>.</param>
/// <param name="Description">The description.</param>
/// <param name="ParentCode">The parent account, if any.</param>
/// <param name="Nature">The statement it ends up in.</param>
/// <param name="StatementLine">The financial statement line it maps to, if any.</param>
public sealed record AccountTemplate(string Code, string Description, string? ParentCode, AccountNature Nature, string? StatementLine);
/// <summary>The model chart of accounts loaded into a new company (arrives with the ledger, M7).</summary>
public interface IChartOfAccountsTemplate
{
/// <summary>The name of the model, such as <c>PMI standard</c>.</summary>
string Name { get; }
/// <summary>The accounts, parents before children.</summary>
IReadOnlyList<AccountTemplate> Accounts { get; }
}
/// <summary>A line of an Intrastat return.</summary>
/// <param name="CountryCode">The country of the counterparty.</param>
/// <param name="VatNumber">The VAT number of the counterparty, without country prefix.</param>
/// <param name="Amount">The amount in euro.</param>
/// <param name="NomenclatureCode">The combined nomenclature code (goods) or CPA code (services).</param>
/// <param name="TransactionNature">The nature of the transaction.</param>
public sealed record IntrastatLine(string CountryCode, string VatNumber, decimal Amount, string? NomenclatureCode, string? TransactionNature);
/// <summary>An Intrastat return of a period.</summary>
/// <param name="Form">The form, such as <c>INTRA-1 bis</c>.</param>
/// <param name="Period">The period.</param>
/// <param name="Lines">The lines.</param>
public sealed record IntrastatReturn(string Form, TaxPeriod Period, IReadOnlyList<IntrastatLine> Lines);
/// <summary>Writes Intrastat returns in the customs format (arrives with Intrastat, M10).</summary>
public interface IIntrastatExporter
{
/// <summary>The forms the exporter writes.</summary>
IReadOnlyList<string> Forms { get; }
/// <summary>Writes a return.</summary>
/// <param name="intrastatReturn">The return.</param>
/// <param name="output">The stream to write to.</param>
/// <param name="cancellationToken">Cancels the write.</param>
/// <returns>A task that completes when the file is written.</returns>
Task WriteAsync(IntrastatReturn intrastatReturn, Stream output, CancellationToken cancellationToken);
}
@@ -0,0 +1,77 @@
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>
/// The country packs registered at start-up, found by country code. The composition root registers the concrete packs;
/// application code receives this catalog and never names a country's implementation.
/// </summary>
public sealed class FiscalPackCatalog
{
private readonly Dictionary<string, IFiscalPack> _byCountry;
/// <summary>Creates the catalog.</summary>
/// <param name="packs">The packs; two packs for the same country are a configuration error.</param>
public FiscalPackCatalog(IEnumerable<IFiscalPack> packs)
{
ArgumentNullException.ThrowIfNull(packs);
_byCountry = new Dictionary<string, IFiscalPack>(StringComparer.OrdinalIgnoreCase);
foreach (var pack in packs)
{
if (!_byCountry.TryAdd(pack.CountryCode, pack))
{
throw new ArgumentException($"Two fiscal packs for country '{pack.CountryCode}'.", nameof(packs));
}
}
Packs = [.. _byCountry.Values.OrderBy(p => p.CountryCode, StringComparer.Ordinal)];
}
/// <summary>Every registered pack, by country code.</summary>
public IReadOnlyList<IFiscalPack> Packs { get; }
/// <summary>The pack of a country.</summary>
/// <param name="countryCode">ISO 3166-1 alpha-2 code, case-insensitive.</param>
/// <returns>The pack.</returns>
/// <exception cref="FiscalPackNotFoundException">No pack for that country.</exception>
public IFiscalPack ForCountry(string? countryCode) =>
TryForCountry(countryCode, out var pack) ? pack : throw new FiscalPackNotFoundException(countryCode ?? string.Empty);
/// <summary>The pack of a country, if registered.</summary>
/// <param name="countryCode">ISO 3166-1 alpha-2 code, case-insensitive.</param>
/// <param name="pack">The pack, when found.</param>
/// <returns>Whether a pack was found.</returns>
public bool TryForCountry(string? countryCode, out IFiscalPack pack)
{
if (!string.IsNullOrWhiteSpace(countryCode) && _byCountry.TryGetValue(countryCode.Trim(), out var found))
{
pack = found;
return true;
}
pack = null!;
return false;
}
}
/// <summary>No fiscal pack is registered for the country of the company.</summary>
public sealed class FiscalPackNotFoundException : Exception
{
/// <summary>Creates the exception.</summary>
public FiscalPackNotFoundException()
: this(string.Empty)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="countryCode">The country without a pack.</param>
public FiscalPackNotFoundException(string countryCode)
: base($"No fiscal pack for country '{countryCode}'.") => CountryCode = countryCode;
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public FiscalPackNotFoundException(string message, Exception innerException)
: base(message, innerException) => CountryCode = string.Empty;
/// <summary>The country without a pack.</summary>
public string CountryCode { get; }
}
@@ -0,0 +1,157 @@
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>
/// Everything a country's tax rules contribute (SPEC §1.10, §3, ADR 0007). The rest of the product talks to these
/// interfaces only; the country's pack is chosen by <c>company_profile.country</c> through <see cref="FiscalPackCatalog"/>.
/// </summary>
/// <remarks>
/// Taxes and a calendar exist everywhere, so they are properties. The other features (e-invoicing, withholding taxes,
/// Intrastat...) depend on the country and on the milestone that delivers them: ask for them with
/// <see cref="GetFeature{T}"/> or <see cref="FiscalPackExtensions.Require{T}(IFiscalPack)"/>.
/// </remarks>
public interface IFiscalPack
{
/// <summary>ISO 3166-1 alpha-2 code of the country, such as <c>IT</c>.</summary>
string CountryCode { get; }
/// <summary>The name of the country in the interface language.</summary>
string Name { get; }
/// <summary>The version of the pack's data (code lists, base tables), such as <c>IT 2026.2</c>.</summary>
string DataVersion { get; }
/// <summary>Tax natures, base tax codes and their rules.</summary>
ITaxCodeCatalog TaxCodes { get; }
/// <summary>Tax computation and rounding.</summary>
ITaxEngine TaxEngine { get; }
/// <summary>Tax periods, deadlines and holidays.</summary>
IFiscalCalendar Calendar { get; }
/// <summary>A feature of the pack, or <see langword="null"/> if the country (or this version) has none.</summary>
/// <typeparam name="T">The feature interface, such as <see cref="IEInvoiceFormat"/>.</typeparam>
/// <returns>The feature, or <see langword="null"/>.</returns>
T? GetFeature<T>()
where T : class;
}
/// <summary>Helpers over <see cref="IFiscalPack"/>.</summary>
public static class FiscalPackExtensions
{
/// <summary>A feature the caller cannot work without.</summary>
/// <typeparam name="T">The feature interface.</typeparam>
/// <param name="pack">The pack.</param>
/// <returns>The feature.</returns>
/// <exception cref="FiscalFeatureNotAvailableException">The pack has no such feature.</exception>
public static T Require<T>(this IFiscalPack pack)
where T : class
{
ArgumentNullException.ThrowIfNull(pack);
return pack.GetFeature<T>() ?? throw new FiscalFeatureNotAvailableException(pack.CountryCode, typeof(T).Name);
}
/// <summary>Whether the pack has a feature.</summary>
/// <typeparam name="T">The feature interface.</typeparam>
/// <param name="pack">The pack.</param>
/// <returns><see langword="true"/> if <see cref="IFiscalPack.GetFeature{T}"/> returns it.</returns>
public static bool Supports<T>(this IFiscalPack pack)
where T : class
{
ArgumentNullException.ThrowIfNull(pack);
return pack.GetFeature<T>() is not null;
}
}
/// <summary>
/// Base class for country packs: the three mandatory parts plus a table of optional features registered with
/// <see cref="AddFeature{T}"/>.
/// </summary>
public abstract class FiscalPackBase : IFiscalPack
{
private readonly Dictionary<Type, object> _features = [];
/// <inheritdoc />
public abstract string CountryCode { get; }
/// <inheritdoc />
public abstract string Name { get; }
/// <inheritdoc />
public abstract string DataVersion { get; }
/// <inheritdoc />
public abstract ITaxCodeCatalog TaxCodes { get; }
/// <inheritdoc />
public abstract ITaxEngine TaxEngine { get; }
/// <inheritdoc />
public abstract IFiscalCalendar Calendar { get; }
/// <inheritdoc />
public T? GetFeature<T>()
where T : class
{
object? feature = typeof(T) == typeof(ITaxCodeCatalog) ? TaxCodes
: typeof(T) == typeof(ITaxEngine) ? TaxEngine
: typeof(T) == typeof(IFiscalCalendar) ? Calendar
: _features.GetValueOrDefault(typeof(T));
return feature as T;
}
/// <summary>Registers an optional feature; call it from the constructor of the pack.</summary>
/// <typeparam name="T">The feature interface.</typeparam>
/// <param name="feature">The implementation.</param>
protected void AddFeature<T>(T feature)
where T : class
{
ArgumentNullException.ThrowIfNull(feature);
_features[typeof(T)] = feature;
}
}
/// <summary>A feature the country's pack does not provide (yet).</summary>
public sealed class FiscalFeatureNotAvailableException : Exception
{
/// <summary>Creates the exception.</summary>
public FiscalFeatureNotAvailableException()
: this(string.Empty, string.Empty)
{
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
public FiscalFeatureNotAvailableException(string message)
: base(message)
{
CountryCode = string.Empty;
Feature = string.Empty;
}
/// <summary>Creates the exception.</summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The cause.</param>
public FiscalFeatureNotAvailableException(string message, Exception innerException)
: base(message, innerException)
{
CountryCode = string.Empty;
Feature = string.Empty;
}
/// <summary>Creates the exception.</summary>
/// <param name="countryCode">The country of the pack.</param>
/// <param name="feature">The name of the missing feature interface.</param>
public FiscalFeatureNotAvailableException(string countryCode, string feature)
: base($"The fiscal pack for '{countryCode}' has no {feature}.")
{
CountryCode = countryCode;
Feature = feature;
}
/// <summary>The country of the pack.</summary>
public string CountryCode { get; }
/// <summary>The name of the missing feature interface.</summary>
public string Feature { get; }
}
+109
View File
@@ -0,0 +1,109 @@
using Khaemhat.Core.Tax;
namespace Khaemhat.Fiscal.Abstractions;
/// <summary>
/// The fiscal content of a tax code (SPEC §11.1, mockup 076): the parts the country's rules check. The table
/// <c>tax_codes</c> adds validity, accounts and the other company data.
/// </summary>
/// <param name="Code">The company's code, such as <c>22</c> or <c>NI8</c>.</param>
/// <param name="Description">The description shown on documents.</param>
/// <param name="Rate">The rate in percent, such as 22.</param>
/// <param name="Nature">The country's nature code for zero-rate operations (Italy: <c>N1</c>...<c>N7</c>).</param>
/// <param name="Exigibility">When the tax becomes due.</param>
/// <param name="NonDeductiblePercent">Share of the purchase tax that cannot be deducted, 0-100.</param>
/// <param name="LegalReference">The law the operation is based on, printed on the invoice.</param>
public sealed record TaxCodeDefinition(
string Code,
string Description,
decimal Rate,
string? Nature = null,
TaxExigibility Exigibility = TaxExigibility.Immediate,
decimal NonDeductiblePercent = 0m,
string? LegalReference = null);
/// <summary>The country's tax natures and base tax codes, and the rules a tax code must follow.</summary>
public interface ITaxCodeCatalog
{
/// <summary>The nature codes for operations without tax.</summary>
CodeList Natures { get; }
/// <summary>The tax codes loaded by the base data (SPEC §14).</summary>
IReadOnlyList<TaxCodeDefinition> BaseCodes { get; }
/// <summary>The kind of operation a rate and nature describe.</summary>
/// <param name="rate">The rate in percent.</param>
/// <param name="nature">The nature code, if any.</param>
/// <returns>The kind.</returns>
TaxCodeKind KindOf(decimal rate, string? nature);
/// <summary>The rules a tax code breaks; empty when it is valid.</summary>
/// <param name="code">The tax code.</param>
/// <returns>Errors and warnings.</returns>
IReadOnlyList<FiscalProblem> Validate(TaxCodeDefinition code);
}
/// <summary>An amount of a document subject to one tax code.</summary>
/// <param name="Amount">The taxable amount, already net of discounts.</param>
/// <param name="Rate">The rate in percent.</param>
/// <param name="Nature">The nature code for zero-rate operations.</param>
/// <param name="Exigibility">When the tax becomes due.</param>
/// <param name="NonDeductiblePercent">Share of the tax that cannot be deducted (purchases).</param>
public sealed record TaxableAmount(
decimal Amount,
decimal Rate,
string? Nature = null,
TaxExigibility Exigibility = TaxExigibility.Immediate,
decimal NonDeductiblePercent = 0m);
/// <summary>One line of the tax summary of a document (castelletto IVA).</summary>
/// <param name="Rate">The rate in percent.</param>
/// <param name="Nature">The nature code, if any.</param>
/// <param name="Exigibility">When the tax becomes due.</param>
/// <param name="NonDeductiblePercent">Share of the tax that cannot be deducted.</param>
/// <param name="Taxable">The sum of the taxable amounts.</param>
/// <param name="Tax">The tax, rounded to the cent.</param>
/// <param name="NonDeductibleTax">The part of <paramref name="Tax"/> that cannot be deducted.</param>
public sealed record TaxSummaryLine(
decimal Rate,
string? Nature,
TaxExigibility Exigibility,
decimal NonDeductiblePercent,
decimal Taxable,
decimal Tax,
decimal NonDeductibleTax);
/// <summary>Whether a document needs stamp duty, and how much.</summary>
/// <param name="Required">The document must carry the duty.</param>
/// <param name="Amount">The duty, zero when not required.</param>
/// <param name="ExemptTotal">The sum of the amounts without tax that the rule counts.</param>
/// <param name="Threshold">The amount above which the duty is due.</param>
public sealed record StampDutyAssessment(bool Required, decimal Amount, decimal ExemptTotal, decimal Threshold);
/// <summary>Tax computation with the country's rounding rules.</summary>
public interface ITaxEngine
{
/// <summary>Rounds an amount of money as the country's tax rules require.</summary>
/// <param name="amount">The amount.</param>
/// <returns>The amount rounded to the cent.</returns>
decimal Round(decimal amount);
/// <summary>The tax on a taxable amount.</summary>
/// <param name="taxable">The taxable amount.</param>
/// <param name="rate">The rate in percent.</param>
/// <returns>The tax, rounded.</returns>
decimal ComputeTax(decimal taxable, decimal rate);
/// <summary>
/// The tax summary of a document: one line per rate, nature, exigibility and non-deductible share, with the tax
/// computed on the total of the line (not summed from the rows).
/// </summary>
/// <param name="amounts">The taxable amounts of the document rows.</param>
/// <returns>The summary lines, by rate (highest first) and then by nature.</returns>
IReadOnlyList<TaxSummaryLine> Summarize(IEnumerable<TaxableAmount> amounts);
/// <summary>Whether the document needs stamp duty.</summary>
/// <param name="summary">The tax summary of the document.</param>
/// <returns>The assessment.</returns>
StampDutyAssessment AssessStampDuty(IEnumerable<TaxSummaryLine> summary);
}