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:
1 parent
8079d3da69
commit
49d2bb166b
22 files changed
+1987
-17
No files matched your search
@@ -7,6 +7,14 @@ un'immagine `gitea.encke-hake.ts.net/balbosoft/khaemhat:X.Y.Z`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Pacchetto fiscale (ADR 0025): `IFiscalPack` con codici IVA, motore delle imposte e calendario fiscale, più funzioni
|
||||
facoltative per paese; `FiscalPackCatalog` sceglie il pacchetto dal paese dell'azienda. Il pacchetto italiano
|
||||
(`IT 2026.2`) porta nature IVA N1-N7, codici IVA di base, code list FatturaPA (specifiche **1.9.1**: TD, MP, TP,
|
||||
RF, ritenute, casse previdenziali), castelletto IVA con arrotondamento sul totale per aliquota, regola del bollo,
|
||||
scadenze IVA mensili e trimestrali con slittamenti di agosto e dei festivi, ritenute, regole di base dei cespiti e
|
||||
codici tributo F24.
|
||||
|
||||
## [0.3.0] - 2026-11-11
|
||||
|
||||
M3 — Framework UI. La shell dell'applicazione, la libreria di componenti `Kh*` con griglie, radar e pagine record, la
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# ADR 0025 - Pacchetto fiscale con parti obbligatorie e funzioni facoltative
|
||||
|
||||
- **Stato:** accettata
|
||||
- **Data:** 2026-11-11
|
||||
- **Modifica:** SPEC §1.10, §3, §21 (Fiscal); ADR 0007; milestone M4, issue #37
|
||||
|
||||
## Contesto
|
||||
|
||||
ADR 0007 isola la fiscalità in `Khaemhat.Fiscal.Abstractions` (interfacce) e `Khaemhat.Fiscal.Italy`
|
||||
(implementazione). SPEC §21 elenca una dozzina di interfacce (`ITaxEngine`, `IEInvoiceFormat`, `IWithholdingRules`,
|
||||
`IIntrastatExporter`…), ma non dice come il pacchetto le espone né cosa succede a quelle che arrivano con milestone
|
||||
successive (FatturaPA in M9, bilancio CEE e Intrastat in M10). Inoltre non tutti i paesi hanno tutte le funzioni:
|
||||
un paese fuori dall'UE non ha Intrastat, non ovunque esistono le ritenute d'acconto.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Tre parti obbligatorie** come proprietà di `IFiscalPack`: `TaxCodes` (`ITaxCodeCatalog`: nature, codici IVA di
|
||||
base, regole del codice IVA), `TaxEngine` (`ITaxEngine`: arrotondamenti, castelletto, bollo) e `Calendar`
|
||||
(`IFiscalCalendar`: periodi, scadenze, festivi). Ogni paese ha imposte e scadenze.
|
||||
2. **Funzioni facoltative** chieste per tipo: `GetFeature<T>()` restituisce `null` se il paese (o la versione) non
|
||||
la offre; `Require<T>()` lancia `FiscalFeatureNotAvailableException` con paese e funzione. In 0.4.0 il pacchetto
|
||||
italiano offre `IEInvoiceFormat` (versione delle specifiche e code list FatturaPA), `IWithholdingRules`,
|
||||
`IFixedAssetRules` e `ITaxPaymentFormExporter` (codici tributo F24); `IFinancialStatementsSchema`,
|
||||
`IChartOfAccountsTemplate` e `IIntrastatExporter` sono definite ma arrivano con la milestone che le usa.
|
||||
3. **Le interfacce crescono con le milestone.** Ognuna contiene oggi solo ciò che serve e si può verificare
|
||||
(code list, regole, costanti); scrittori e lettori di file si aggiungono quando arriva la loro maschera.
|
||||
4. **Problemi come codici.** Le regole restituiscono `FiscalProblem` (campo, codice stabile come
|
||||
`fiscal.tax.nature-required`, errore o avviso); l'interfaccia traduce il codice con le risorse.
|
||||
5. **Risoluzione per paese.** `FiscalPackCatalog` raccoglie i pacchetti registrati e li trova per
|
||||
`company_profile.country` (senza distinzione di maiuscole). La composizione in `Hosting/KhaemhatServices.cs` è
|
||||
l'unico file fuori dal pacchetto che nomina `Khaemhat.Fiscal.Italy`: lo verifica `FiscalPackIsolationTests`, che
|
||||
controlla anche che le astrazioni non contengano nomi italiani.
|
||||
6. **Versione delle specifiche.** `FatturaPaCodeLists.SpecVersion` è **1.9.1** (pubblicata il 31 marzo 2026, in
|
||||
vigore dal 15 maggio 2026; non cambia le code list della 1.9, che aveva introdotto TD29 e ridefinito TD20). Va
|
||||
ricontrollata sul sito dell'Agenzia delle Entrate a ogni rilascio.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Un modulo che usa una funzione facoltativa decide cosa mostrare quando manca (per esempio nascondere Intrastat),
|
||||
invece di fallire alla prima chiamata.
|
||||
- Codici IVA di base, nature e code list del seed (#45) vengono dal pacchetto: c'è un'unica fonte.
|
||||
- La regola del bollo considera le nature N1, N2.x, N3.5, N3.6, N4 e N5; esportazioni, cessioni intracomunitarie,
|
||||
San Marino, operazioni assimilate, inversione contabile e N7 non contano. È da rivedere con i documenti di
|
||||
vendita (M5) se la normativa cambia.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Fiscalità italiana
|
||||
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-10 · **Versione software:** non ancora rilasciata (milestone M4-M10)
|
||||
> **Stato:** bozza · **Ultima revisione:** 2026-11-11 · **Versione software:** 0.4.0 (codici e regole di base; il resto con M5-M10)
|
||||
> **Modulo di licenza:** CORE, ACCT, EINV, INTRA · **Specifica:** SPEC §11.1, §11.3-§11.9, §14
|
||||
|
||||
Questa pagina raccoglie in un solo posto i **codici e le regole fiscali italiane** che Khaemhat usa: tipi documento
|
||||
@@ -58,6 +58,9 @@ caso di dubbio fa fede il testo mostrato dal programma, non questa pagina.
|
||||
| TD28 | Acquisti da San Marino con IVA (fattura cartacea) | acquisti |
|
||||
| TD29 | Comunicazione per omessa o irregolare fatturazione | regolarizzazione (introdotto con le specifiche v1.9) |
|
||||
|
||||
Versione delle specifiche tecniche seguita: **1.9.1** (pubblicata dall'Agenzia il 31 marzo 2026, in vigore dal
|
||||
15 maggio 2026; non cambia le code list della 1.9, che ha introdotto TD29 e ridefinito TD20).
|
||||
|
||||
Formati di trasmissione: **FPR12** (verso privati), **FPA12** (verso pubbliche amministrazioni), **FSM10** (fattura
|
||||
semplificata). Nome del file: `IT<partita IVA>_<progressivo>.xml`.
|
||||
|
||||
@@ -70,7 +73,7 @@ codice IVA sulla riga del documento la natura viene compilata da sola.
|
||||
|---|---|---|
|
||||
| N1 | Escluse ex art. 15 DPR 633/72 | `ESC15` |
|
||||
| N2.1 | Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72 | `FC7` |
|
||||
| N2.2 | Non soggette - altri casi | fuori campo altre (anche fatture da forfettari) |
|
||||
| N2.2 | Non soggette - altri casi | `NS`, `FORF` (operazioni in regime forfettario) |
|
||||
| N3.1 | Non imponibili - esportazioni | `NI8` |
|
||||
| N3.2 | Non imponibili - cessioni intracomunitarie | `NI41` |
|
||||
| N3.3 | Non imponibili - cessioni verso San Marino | `NI71` |
|
||||
@@ -79,11 +82,25 @@ codice IVA sulla riga del documento la natura viene compilata da sola.
|
||||
| N3.6 | Non imponibili - altre operazioni che non concorrono alla formazione del plafond | — |
|
||||
| N4 | Esenti | `ESE10` |
|
||||
| N5 | Regime del margine / IVA non esposta in fattura | — (regime del margine previsto in fase 2) |
|
||||
| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC17` (varianti per sotto-codice) |
|
||||
| N6.1 … N6.9 | Inversione contabile (reverse charge): rottami (N6.1), oro e argento (N6.2), subappalto edile (N6.3), cessione di fabbricati (N6.4), telefoni cellulari (N6.5), prodotti elettronici (N6.6), prestazioni comparto edile e connessi (N6.7), settore energetico (N6.8), altri casi (N6.9) | `RC74` (N6.1), `RC17O` (N6.2), `RC17A` (N6.3), `RC17F` (N6.4), `RC17B` (N6.5), `RC17C` (N6.6), `RC17E` (N6.7), `RC17N` (N6.8), `RC17` (N6.9) |
|
||||
| N7 | IVA assolta in altro stato UE | — |
|
||||
|
||||
Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **SPLIT** (scissione dei pagamenti), **NS**,
|
||||
**indetraibili 50% e 100%**, codici per **forfettari**.
|
||||
Altri codici IVA di base: aliquote **22**, **10**, **5**, **4**; **22SP** e **10SP** (scissione dei pagamenti,
|
||||
esigibilità S); **22I50** e **22I100** (IVA 22% indetraibile al 50% e al 100%).
|
||||
|
||||
I codici N2, N3 e N6 senza sotto-codice non sono più accettati dallo SDI: Khaemhat li riconosce nei documenti vecchi
|
||||
ma non li lascia scegliere su un codice IVA nuovo.
|
||||
|
||||
**Controlli sul codice IVA.** Salvando un codice IVA Khaemhat verifica che:
|
||||
|
||||
- un'aliquota maggiore di zero non abbia natura e un'aliquota zero ce l'abbia;
|
||||
- la natura esista e sia ancora valida;
|
||||
- la scissione dei pagamenti abbia un'aliquota;
|
||||
- l'inversione contabile (N6.x) abbia esigibilità immediata;
|
||||
- la percentuale di indetraibilità sia fra 0 e 100.
|
||||
|
||||
Sono solo **avvisi** (il codice si salva) un'aliquota diversa da 4, 5, 10 e 22 (per esempio le percentuali di
|
||||
compensazione agricole) e la mancanza del riferimento normativo, che va stampato in fattura quando c'è la natura.
|
||||
|
||||
**Esigibilità** (campo del codice IVA): **I** immediata, **D** differita, **S** scissione dei pagamenti (split
|
||||
payment).
|
||||
@@ -181,12 +198,13 @@ Khaemhat propone il codice tributo e prepara i **dati F24** da passare a interme
|
||||
| Adempimento | Regola | Note in Khaemhat |
|
||||
|---|---|---|
|
||||
| Liquidazione IVA mensile | versamento entro il **16 del mese successivo** | la conferma della liquidazione **blocca il periodo** |
|
||||
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale | interessi calcolati in automatico |
|
||||
| Liquidazione IVA trimestrale | versamento entro il 16 del secondo mese successivo al trimestre (per il secondo trimestre vale la proroga estiva di agosto), con **interessi dell'1%**; il quarto trimestre si versa con il saldo annuale entro il 16 marzo | interessi calcolati in automatico |
|
||||
| Scadenze in agosto e nei festivi | i versamenti fra il 1° e il 20 agosto slittano al **20 agosto**; una scadenza di sabato, domenica o festivo slitta al primo giorno lavorativo | festivi nazionali, Pasquetta e, dal 2026, il 4 ottobre |
|
||||
| Versamento minimo | importo fino a **€ 25,82** non versato e riportato al periodo successivo | valore della specifica; da verificare in sviluppo rispetto alla norma vigente |
|
||||
| Acconto IVA | entro il **27 dicembre**; metodo **storico**, **previsionale** o **analitico** | scelta del metodo nella liquidazione di dicembre |
|
||||
| LIPE | 1° trimestre entro 31 maggio, 2° entro 16 settembre, 3° entro 30 novembre, 4° entro fine febbraio (o nella dichiarazione annuale) | XML LIPE generato dalla liquidazione |
|
||||
| Ritenute d'acconto operate | versamento entro il **16 del mese successivo** al pagamento della parcella (1040/1038) | la ritenuta nasce al pagamento della fattura |
|
||||
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | applicato in automatico; addebito al cliente o a carico azienda |
|
||||
| Imposta di bollo | **€ 2,00** se le operazioni esenti, non imponibili o fuori campo superano **€ 77,47** | contano le nature N1, N2.1, N2.2, N3.5, N3.6, N4, N5; non contano esportazioni (N3.1), cessioni intracomunitarie (N3.2), San Marino (N3.3), operazioni assimilate (N3.4), inversione contabile (N6.x) e N7 |
|
||||
| Bollo virtuale | versamento trimestrale: 1° trimestre entro 31 maggio, 2° entro 30 settembre, 3° entro 30 novembre, 4° entro fine febbraio; con importi bassi i primi trimestri possono slittare (soglia di € 5.000) | elenco da confrontare con quello proposto dall'Agenzia |
|
||||
| Autofatture e integrazioni (TD16-TD19) | XML da trasmettere **entro il 15 del mese successivo** | promemoria nella dashboard |
|
||||
| Fattura differita (TD24) | emissione entro il 15 del mese successivo a quello delle consegne documentate da DDT | procedura **Fatturazione differita** |
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace Khaemhat.Core.Accounting;
|
||||
|
||||
/// <summary>The nature of a ledger account: which statement it ends up in.</summary>
|
||||
public enum AccountNature
|
||||
{
|
||||
/// <summary>Balance sheet, assets.</summary>
|
||||
Asset = 0,
|
||||
|
||||
/// <summary>Balance sheet, liabilities and equity.</summary>
|
||||
Liability = 1,
|
||||
|
||||
/// <summary>Income statement, costs.</summary>
|
||||
Cost = 2,
|
||||
|
||||
/// <summary>Income statement, revenues.</summary>
|
||||
Revenue = 3,
|
||||
|
||||
/// <summary>Memorandum accounts (conti d'ordine), outside both statements.</summary>
|
||||
Memorandum = 4,
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace Khaemhat.Core.Tax;
|
||||
|
||||
/// <summary>When the VAT of an operation becomes due (FatturaPA <c>EsigibilitaIVA</c>: I, D, S).</summary>
|
||||
public enum TaxExigibility
|
||||
{
|
||||
/// <summary>Due when the invoice is issued (I).</summary>
|
||||
Immediate = 0,
|
||||
|
||||
/// <summary>Due when the invoice is paid, as with cash VAT or deferred VAT for public bodies (D).</summary>
|
||||
Deferred = 1,
|
||||
|
||||
/// <summary>Paid by the public body that buys (split payment, S).</summary>
|
||||
SplitPayment = 2,
|
||||
}
|
||||
|
||||
/// <summary>What a tax code means for the VAT return, independent of the country's code for it.</summary>
|
||||
public enum TaxCodeKind
|
||||
{
|
||||
/// <summary>Taxable with a rate above zero.</summary>
|
||||
Taxable = 0,
|
||||
|
||||
/// <summary>Not taxable (exports, intra-EU supplies, letters of intent).</summary>
|
||||
NonTaxable = 1,
|
||||
|
||||
/// <summary>Exempt.</summary>
|
||||
Exempt = 2,
|
||||
|
||||
/// <summary>Excluded from the taxable amount.</summary>
|
||||
Excluded = 3,
|
||||
|
||||
/// <summary>Outside the scope of VAT.</summary>
|
||||
NotSubject = 4,
|
||||
|
||||
/// <summary>VAT paid by the buyer (reverse charge).</summary>
|
||||
ReverseCharge = 5,
|
||||
|
||||
/// <summary>Margin scheme: VAT not shown on the invoice.</summary>
|
||||
Margin = 6,
|
||||
|
||||
/// <summary>VAT paid in another EU country.</summary>
|
||||
OtherEuVat = 7,
|
||||
}
|
||||
|
||||
/// <summary>How often the company settles VAT.</summary>
|
||||
public enum VatPeriodicity
|
||||
{
|
||||
/// <summary>Every month.</summary>
|
||||
Monthly = 0,
|
||||
|
||||
/// <summary>Every quarter, with interest where the country requires it.</summary>
|
||||
Quarterly = 1,
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The code lists of the FatturaPA technical specifications of the Agenzia delle Entrate (SPEC §11.9). Descriptions
|
||||
/// follow the official tables, shortened where the official text runs to several lines.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <see cref="SpecVersion"/> is the version checked at each release (ADR 0025): 1.9 (in force from 1 April 2025)
|
||||
/// added TD29 and redefined TD20; 1.9.1 (published 31 March 2026, in force from 15 May 2026) changed no code list.
|
||||
/// </remarks>
|
||||
public static class FatturaPaCodeLists
|
||||
{
|
||||
/// <summary>The version of the technical specifications that this pack follows.</summary>
|
||||
public const string SpecVersion = "1.9.1";
|
||||
|
||||
/// <summary>The date from which <see cref="SpecVersion"/> is in force.</summary>
|
||||
public static readonly DateOnly SpecInForceFrom = new(2026, 5, 15);
|
||||
|
||||
/// <summary>Transmission formats (<c>FormatoTrasmissione</c>).</summary>
|
||||
public static CodeList TransmissionFormats { get; } = new("TransmissionFormats",
|
||||
[
|
||||
new("FPA12", "Fattura verso pubbliche amministrazioni"),
|
||||
new("FPR12", "Fattura verso privati"),
|
||||
new("FSM10", "Fattura semplificata"),
|
||||
]);
|
||||
|
||||
/// <summary>Document types (<c>TipoDocumento</c>).</summary>
|
||||
public static CodeList DocumentTypes { get; } = new("DocumentTypes",
|
||||
[
|
||||
new("TD01", "Fattura"),
|
||||
new("TD02", "Acconto/anticipo su fattura"),
|
||||
new("TD03", "Acconto/anticipo su parcella"),
|
||||
new("TD04", "Nota di credito"),
|
||||
new("TD05", "Nota di debito"),
|
||||
new("TD06", "Parcella"),
|
||||
new("TD07", "Fattura semplificata"),
|
||||
new("TD08", "Nota di credito semplificata"),
|
||||
new("TD09", "Nota di debito semplificata"),
|
||||
new("TD16", "Integrazione fattura reverse charge interno"),
|
||||
new("TD17", "Integrazione/autofattura per acquisto servizi dall'estero"),
|
||||
new("TD18", "Integrazione per acquisto di beni intracomunitari"),
|
||||
new("TD19", "Integrazione/autofattura per acquisto di beni ex art. 17 c. 2 DPR 633/72"),
|
||||
new("TD20", "Autofattura per regolarizzazione e integrazione delle fatture (art. 6 c. 8 e 9-bis D.Lgs. 471/97 o art. 46 c. 5 DL 331/93)"),
|
||||
new("TD21", "Autofattura per splafonamento"),
|
||||
new("TD22", "Estrazione beni da deposito IVA"),
|
||||
new("TD23", "Estrazione beni da deposito IVA con versamento dell'IVA"),
|
||||
new("TD24", "Fattura differita di cui all'art. 21 c. 4 lett. a) DPR 633/72"),
|
||||
new("TD25", "Fattura differita di cui all'art. 21 c. 4 terzo periodo lett. b) DPR 633/72"),
|
||||
new("TD26", "Cessione di beni ammortizzabili e per passaggi interni (art. 36 DPR 633/72)"),
|
||||
new("TD27", "Fattura per autoconsumo o per cessioni gratuite senza rivalsa"),
|
||||
new("TD28", "Acquisti da San Marino con IVA (fattura cartacea)"),
|
||||
new("TD29", "Comunicazione per omessa o irregolare fatturazione (art. 6 c. 8 D.Lgs. 471/97)"),
|
||||
]);
|
||||
|
||||
/// <summary>Document types accepted only in the simplified format <c>FSM10</c>.</summary>
|
||||
public static IReadOnlySet<string> SimplifiedDocumentTypes { get; } = new HashSet<string>(StringComparer.Ordinal) { "TD07", "TD08", "TD09" };
|
||||
|
||||
/// <summary>Payment methods (<c>ModalitaPagamento</c>).</summary>
|
||||
public static CodeList PaymentMethods { get; } = new("PaymentMethods",
|
||||
[
|
||||
new("MP01", "Contanti"),
|
||||
new("MP02", "Assegno"),
|
||||
new("MP03", "Assegno circolare"),
|
||||
new("MP04", "Contanti presso Tesoreria"),
|
||||
new("MP05", "Bonifico"),
|
||||
new("MP06", "Vaglia cambiario"),
|
||||
new("MP07", "Bollettino bancario"),
|
||||
new("MP08", "Carta di pagamento"),
|
||||
new("MP09", "RID"),
|
||||
new("MP10", "RID utenze"),
|
||||
new("MP11", "RID veloce"),
|
||||
new("MP12", "RIBA"),
|
||||
new("MP13", "MAV"),
|
||||
new("MP14", "Quietanza erario"),
|
||||
new("MP15", "Giroconto su conti di contabilità speciale"),
|
||||
new("MP16", "Domiciliazione bancaria"),
|
||||
new("MP17", "Domiciliazione postale"),
|
||||
new("MP18", "Bollettino di c/c postale"),
|
||||
new("MP19", "SEPA Direct Debit"),
|
||||
new("MP20", "SEPA Direct Debit CORE"),
|
||||
new("MP21", "SEPA Direct Debit B2B"),
|
||||
new("MP22", "Trattenuta su somme già riscosse"),
|
||||
new("MP23", "PagoPA"),
|
||||
]);
|
||||
|
||||
/// <summary>Payment conditions (<c>CondizioniPagamento</c>).</summary>
|
||||
public static CodeList PaymentConditions { get; } = new("PaymentConditions",
|
||||
[
|
||||
new("TP01", "Pagamento a rate"),
|
||||
new("TP02", "Pagamento completo"),
|
||||
new("TP03", "Anticipo"),
|
||||
]);
|
||||
|
||||
/// <summary>Tax regimes of the seller (<c>RegimeFiscale</c>); RF03 no longer exists.</summary>
|
||||
public static CodeList TaxRegimes { get; } = new("TaxRegimes",
|
||||
[
|
||||
new("RF01", "Ordinario"),
|
||||
new("RF02", "Contribuenti minimi (art. 1 c. 96-117 L. 244/2007)"),
|
||||
new("RF03", "Nuove iniziative produttive (abrogato)", Obsolete: true),
|
||||
new("RF04", "Agricoltura e attività connesse e pesca (artt. 34 e 34-bis DPR 633/72)"),
|
||||
new("RF05", "Vendita sali e tabacchi (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF06", "Commercio dei fiammiferi (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF07", "Editoria (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF08", "Gestione di servizi di telefonia pubblica (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF09", "Rivendita di documenti di trasporto pubblico e di sosta (art. 74 c. 1 DPR 633/72)"),
|
||||
new("RF10", "Intrattenimenti, giochi e altre attività di cui alla tariffa allegata al DPR 640/72 (art. 74 c. 6 DPR 633/72)"),
|
||||
new("RF11", "Agenzie di viaggi e turismo (art. 74-ter DPR 633/72)"),
|
||||
new("RF12", "Agriturismo (art. 5 c. 2 L. 413/91)"),
|
||||
new("RF13", "Vendite a domicilio (art. 25-bis c. 6 DPR 600/73)"),
|
||||
new("RF14", "Rivendita di beni usati, oggetti d'arte, d'antiquariato o da collezione (art. 36 DL 41/95)"),
|
||||
new("RF15", "Agenzie di vendite all'asta di oggetti d'arte, antiquariato o da collezione (art. 40-bis DL 41/95)"),
|
||||
new("RF16", "IVA per cassa P.A. (art. 6 c. 5 DPR 633/72)"),
|
||||
new("RF17", "IVA per cassa (art. 32-bis DL 83/2012)"),
|
||||
new("RF18", "Altro"),
|
||||
new("RF19", "Regime forfettario (art. 1 c. 54-89 L. 190/2014)"),
|
||||
]);
|
||||
|
||||
/// <summary>Withholding types (<c>TipoRitenuta</c>).</summary>
|
||||
public static CodeList WithholdingTypes { get; } = new("WithholdingTypes",
|
||||
[
|
||||
new("RT01", "Ritenuta persone fisiche"),
|
||||
new("RT02", "Ritenuta persone giuridiche"),
|
||||
new("RT03", "Contributo INPS"),
|
||||
new("RT04", "Contributo ENASARCO"),
|
||||
new("RT05", "Contributo ENPAM"),
|
||||
new("RT06", "Altro contributo previdenziale"),
|
||||
]);
|
||||
|
||||
/// <summary>Payment reasons of the withholding (<c>CausalePagamento</c>, as in the CU form).</summary>
|
||||
public static CodeList WithholdingReasons { get; } = new("WithholdingReasons",
|
||||
[
|
||||
new("A", "Prestazioni di lavoro autonomo rientranti nell'esercizio di arte o professione abituale"),
|
||||
new("B", "Utilizzazione economica, da parte dell'autore o dell'inventore, di opere dell'ingegno"),
|
||||
new("C", "Utili derivanti da contratti di associazione in partecipazione e cointeressenza (solo apporto di lavoro)"),
|
||||
new("D", "Utili spettanti ai soci promotori e ai soci fondatori delle società di capitali"),
|
||||
new("E", "Levata di protesti cambiari da parte dei segretari comunali"),
|
||||
new("G", "Indennità corrisposte per la cessazione di attività sportiva professionale"),
|
||||
new("H", "Indennità corrisposte per la cessazione dei rapporti di agenzia"),
|
||||
new("I", "Indennità corrisposte per la cessazione da funzioni notarili"),
|
||||
new("L", "Utilizzazione economica di opere dell'ingegno da parte di soggetto diverso dall'autore"),
|
||||
new("L1", "Redditi da utilizzazione economica di opere dell'ingegno acquisiti a titolo oneroso"),
|
||||
new("M", "Prestazioni di lavoro autonomo non esercitate abitualmente"),
|
||||
new("M1", "Redditi derivanti dall'assunzione di obblighi di fare, non fare o permettere"),
|
||||
new("M2", "Prestazioni di lavoro autonomo non esercitate abitualmente con obbligo di iscrizione alla Gestione Separata ENPAPI"),
|
||||
new("N", "Indennità di trasferta, rimborsi forfetari, premi e compensi nell'esercizio diretto di attività sportive dilettantistiche"),
|
||||
new("O", "Prestazioni di lavoro autonomo non esercitate abitualmente, senza obbligo di iscrizione alla gestione separata"),
|
||||
new("O1", "Redditi da obblighi di fare, non fare o permettere, senza obbligo di iscrizione alla gestione separata"),
|
||||
new("P", "Compensi a soggetti non residenti privi di stabile organizzazione per l'uso di attrezzature"),
|
||||
new("Q", "Provvigioni ad agente o rappresentante di commercio monomandatario"),
|
||||
new("R", "Provvigioni ad agente o rappresentante di commercio plurimandatario"),
|
||||
new("S", "Provvigioni a commissionario"),
|
||||
new("T", "Provvigioni a mediatore"),
|
||||
new("U", "Provvigioni a procacciatore di affari"),
|
||||
new("V", "Provvigioni a incaricato per le vendite a domicilio o porta a porta"),
|
||||
new("V1", "Redditi derivanti da attività commerciali non esercitate abitualmente"),
|
||||
new("V2", "Prestazioni non esercitate abitualmente rese dagli incaricati alla vendita diretta a domicilio"),
|
||||
new("W", "Corrispettivi per prestazioni relative a contratti d'appalto (art. 25-ter DPR 600/73)"),
|
||||
new("X", "Canoni corrisposti nel 2004 da società o enti residenti (art. 26-quater DPR 600/73)"),
|
||||
new("Y", "Canoni corrisposti dal 2005 da società o enti residenti (art. 26-quater DPR 600/73)"),
|
||||
new("Z", "Titolo diverso dai precedenti (sostituito da ZO)", Obsolete: true),
|
||||
new("ZO", "Titolo diverso dai precedenti"),
|
||||
]);
|
||||
|
||||
/// <summary>Social security funds (<c>TipoCassa</c>).</summary>
|
||||
public static CodeList SocialSecurityFunds { get; } = new("SocialSecurityFunds",
|
||||
[
|
||||
new("TC01", "Cassa nazionale previdenza e assistenza avvocati e procuratori legali"),
|
||||
new("TC02", "Cassa previdenza dottori commercialisti"),
|
||||
new("TC03", "Cassa previdenza e assistenza geometri"),
|
||||
new("TC04", "Cassa nazionale previdenza e assistenza ingegneri e architetti liberi professionisti"),
|
||||
new("TC05", "Cassa nazionale del notariato"),
|
||||
new("TC06", "Cassa nazionale previdenza e assistenza ragionieri e periti commerciali"),
|
||||
new("TC07", "Ente nazionale assistenza agenti e rappresentanti di commercio (ENASARCO)"),
|
||||
new("TC08", "Ente nazionale previdenza e assistenza consulenti del lavoro (ENPACL)"),
|
||||
new("TC09", "Ente nazionale previdenza e assistenza medici (ENPAM)"),
|
||||
new("TC10", "Ente nazionale previdenza e assistenza farmacisti (ENPAF)"),
|
||||
new("TC11", "Ente nazionale previdenza e assistenza veterinari (ENPAV)"),
|
||||
new("TC12", "Ente nazionale previdenza e assistenza impiegati dell'agricoltura (ENPAIA)"),
|
||||
new("TC13", "Fondo previdenza impiegati imprese di spedizione e agenzie marittime"),
|
||||
new("TC14", "Istituto nazionale previdenza giornalisti italiani (INPGI)"),
|
||||
new("TC15", "Opera nazionale assistenza orfani sanitari italiani (ONAOSI)"),
|
||||
new("TC16", "Cassa autonoma assistenza integrativa giornalisti italiani (CASAGIT)"),
|
||||
new("TC17", "Ente previdenza periti industriali e periti industriali laureati (EPPI)"),
|
||||
new("TC18", "Ente previdenza e assistenza pluricategoriale (EPAP)"),
|
||||
new("TC19", "Ente nazionale previdenza e assistenza biologi (ENPAB)"),
|
||||
new("TC20", "Ente nazionale previdenza e assistenza professione infermieristica (ENPAPI)"),
|
||||
new("TC21", "Ente nazionale previdenza e assistenza psicologi (ENPAP)"),
|
||||
new("TC22", "INPS"),
|
||||
]);
|
||||
|
||||
/// <summary>Recipient code for consumers and companies without a channel.</summary>
|
||||
public const string RecipientCodeNone = "0000000";
|
||||
|
||||
/// <summary>Recipient code for foreign customers.</summary>
|
||||
public const string RecipientCodeForeign = "XXXXXXX";
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Italian VAT deadlines (wiki <i>Fiscalità italiana</i>, "Scadenze e regole principali"):
|
||||
/// <list type="bullet">
|
||||
/// <item>monthly VAT by the 16th of the next month;</item>
|
||||
/// <item>quarterly VAT by the 16th of the second month after the quarter, with 1% interest; the fourth quarter is paid
|
||||
/// with the annual balance by 16 March;</item>
|
||||
/// <item>payments due from 1 to 20 August move to 20 August (art. 3-quater DL 16/2012);</item>
|
||||
/// <item>a deadline on a Saturday, Sunday or public holiday moves to the next working day (art. 7 DL 70/2011).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class ItalianFiscalCalendar : IFiscalCalendar
|
||||
{
|
||||
/// <summary>Interest on quarterly VAT, in percent.</summary>
|
||||
public const decimal QuarterlyInterestRate = 1m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateOnly VatPaymentDue(TaxPeriod period)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(period);
|
||||
DateOnly due;
|
||||
if (period.Periodicity == VatPeriodicity.Monthly)
|
||||
{
|
||||
due = new DateOnly(period.Year, period.Number, 16).AddMonths(1);
|
||||
}
|
||||
else if (period.Number == 4)
|
||||
{
|
||||
due = new DateOnly(period.Year + 1, 3, 16);
|
||||
}
|
||||
else
|
||||
{
|
||||
due = new DateOnly(period.End.Year, period.End.Month, 16).AddMonths(2);
|
||||
}
|
||||
|
||||
if (due.Month == 8 && due.Day <= 20)
|
||||
{
|
||||
due = new DateOnly(due.Year, 8, 20);
|
||||
}
|
||||
|
||||
return NextWorkingDay(due);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal VatInterestRate(VatPeriodicity periodicity) =>
|
||||
periodicity == VatPeriodicity.Quarterly ? QuarterlyInterestRate : 0m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNonWorkingDay(DateOnly day) =>
|
||||
day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday || IsPublicHoliday(day);
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateOnly NextWorkingDay(DateOnly day)
|
||||
{
|
||||
while (IsNonWorkingDay(day))
|
||||
{
|
||||
day = day.AddDays(1);
|
||||
}
|
||||
|
||||
return day;
|
||||
}
|
||||
|
||||
/// <summary>Whether a day is an Italian national public holiday.</summary>
|
||||
/// <param name="date">The day.</param>
|
||||
/// <returns><see langword="true"/> for a holiday.</returns>
|
||||
public static bool IsPublicHoliday(DateOnly date)
|
||||
{
|
||||
switch ((date.Month, date.Day))
|
||||
{
|
||||
case (1, 1): // Capodanno
|
||||
case (1, 6): // Epifania
|
||||
case (4, 25): // Liberazione
|
||||
case (5, 1): // Festa del lavoro
|
||||
case (6, 2): // Festa della Repubblica
|
||||
case (8, 15): // Ferragosto
|
||||
case (11, 1): // Ognissanti
|
||||
case (12, 8): // Immacolata
|
||||
case (12, 25): // Natale
|
||||
case (12, 26): // Santo Stefano
|
||||
return true;
|
||||
case (10, 4) when date.Year >= 2026: // San Francesco, national holiday again from 2026
|
||||
return true;
|
||||
default:
|
||||
return date == EasterSunday(date.Year).AddDays(1); // Lunedì dell'Angelo
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Easter Sunday of a year (Gregorian calendar, anonymous algorithm).</summary>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <returns>The date.</returns>
|
||||
public static DateOnly EasterSunday(int year)
|
||||
{
|
||||
var a = year % 19;
|
||||
var b = year / 100;
|
||||
var c = year % 100;
|
||||
var d = b / 4;
|
||||
var e = b % 4;
|
||||
var f = (b + 8) / 25;
|
||||
var g = (b - f + 1) / 3;
|
||||
var h = ((19 * a) + b - d - g + 15) % 30;
|
||||
var i = c / 4;
|
||||
var k = c % 4;
|
||||
var l = (32 + (2 * e) + (2 * i) - h - k) % 7;
|
||||
var m = (a + (11 * h) + (22 * l)) / 451;
|
||||
var month = (h + l - (7 * m) + 114) / 31;
|
||||
var day = ((h + l - (7 * m) + 114) % 31) + 1;
|
||||
return new DateOnly(year, month, day);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>The FatturaPA format: version of the specifications and code lists (writer and reader arrive in M9).</summary>
|
||||
public sealed class FatturaPaFormat : IEInvoiceFormat
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string Name => "FatturaPA";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string SpecVersion => FatturaPaCodeLists.SpecVersion;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList TransmissionFormats => FatturaPaCodeLists.TransmissionFormats;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList DocumentTypes => FatturaPaCodeLists.DocumentTypes;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList PaymentMethods => FatturaPaCodeLists.PaymentMethods;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList PaymentConditions => FatturaPaCodeLists.PaymentConditions;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList TaxRegimes => FatturaPaCodeLists.TaxRegimes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Italian withholding taxes: fees of professionals (20% on the whole fee, F24 1040), commissions of agents (23% on 50%,
|
||||
/// or on 20% for agents with employees, F24 1038) and the 4% of condominiums (F24 1019).
|
||||
/// </summary>
|
||||
public sealed class WithholdingRulesIt : IWithholdingRules
|
||||
{
|
||||
private readonly ItalianTaxEngine _engine = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<WithholdingKind> Kinds { get; } =
|
||||
[
|
||||
new("PROF", "Lavoro autonomo professionale", 20m, 100m, "1040", "RT01", "A"),
|
||||
new("OCC", "Lavoro autonomo occasionale", 20m, 100m, "1040", "RT01", "M"),
|
||||
new("AGEN", "Provvigioni ad agenti e rappresentanti", 23m, 50m, "1038", "RT01", "R"),
|
||||
new("AGEND", "Provvigioni ad agenti con dipendenti o terzi", 23m, 20m, "1038", "RT01", "R"),
|
||||
new("COND", "Ritenuta del condominio sugli appalti", 4m, 100m, "1019", "RT01", "W"),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList InvoiceTypes => FatturaPaCodeLists.WithholdingTypes;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList PaymentReasons => FatturaPaCodeLists.WithholdingReasons;
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList SocialSecurityFunds => FatturaPaCodeLists.SocialSecurityFunds;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal Compute(decimal amount, WithholdingKind kind)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(kind);
|
||||
return _engine.Round(amount * kind.TaxableBasePercent / 100m * kind.Rate / 100m);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Italian depreciation rules (DM 31/12/1988 coefficients arrive with the asset register, M10).</summary>
|
||||
public sealed class FixedAssetRulesIt : IFixedAssetRules
|
||||
{
|
||||
private readonly ItalianTaxEngine _engine = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal FirstYearFactor => 0.5m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal LowValueThreshold => 516.46m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal PassengerCarCostLimit => 18_075.99m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal YearlyDepreciation(decimal cost, decimal ratePercent, bool firstYear, decimal alreadyDepreciated)
|
||||
{
|
||||
var remaining = Math.Max(0m, cost - alreadyDepreciated);
|
||||
var amount = _engine.Round(cost * ratePercent / 100m * (firstYear ? FirstYearFactor : 1m));
|
||||
return Math.Min(amount, remaining);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The F24 payment codes Khaemhat proposes (the file export arrives with the VAT settlement, M7).</summary>
|
||||
public sealed class F24Exporter : ITaxPaymentFormExporter
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string FormName => "F24";
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<TaxPaymentCode> Codes { get; } = BuildCodes();
|
||||
|
||||
/// <inheritdoc />
|
||||
public string VatCode(TaxPeriod period)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(period);
|
||||
return period.Periodicity == VatPeriodicity.Monthly
|
||||
? (6000 + period.Number).ToString(System.Globalization.CultureInfo.InvariantCulture)
|
||||
: (6030 + period.Number).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string VatAdvanceCode(VatPeriodicity periodicity) => periodicity == VatPeriodicity.Monthly ? "6013" : "6035";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string StampDutyCode(int quarter)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(quarter, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(quarter, 4);
|
||||
return (2520 + quarter).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static List<TaxPaymentCode> BuildCodes()
|
||||
{
|
||||
string[] months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
|
||||
var codes = new List<TaxPaymentCode>();
|
||||
for (var m = 1; m <= 12; m++)
|
||||
{
|
||||
codes.Add(new((6000 + m).ToString(System.Globalization.CultureInfo.InvariantCulture), "Versamento IVA mensile " + months[m - 1]));
|
||||
}
|
||||
|
||||
codes.Add(new("6013", "Versamento acconto IVA mensile"));
|
||||
for (var q = 1; q <= 4; q++)
|
||||
{
|
||||
codes.Add(new((6030 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Versamento IVA trimestrale {q}° trimestre"));
|
||||
}
|
||||
|
||||
codes.Add(new("6035", "Versamento IVA acconto trimestrali"));
|
||||
codes.Add(new("6099", "Versamento IVA sulla base della dichiarazione annuale"));
|
||||
codes.Add(new("1040", "Ritenute su redditi di lavoro autonomo"));
|
||||
codes.Add(new("1038", "Ritenute su provvigioni"));
|
||||
codes.Add(new("1019", "Ritenute del 4% operate dal condominio a titolo di acconto IRPEF"));
|
||||
for (var q = 1; q <= 4; q++)
|
||||
{
|
||||
codes.Add(new((2520 + q).ToString(System.Globalization.CultureInfo.InvariantCulture), $"Imposta di bollo sulle fatture elettroniche, {q}° trimestre"));
|
||||
}
|
||||
|
||||
return codes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>The Italian VAT natures, the base tax codes of SPEC §14 and the rules of a tax code (mockup 076).</summary>
|
||||
public sealed class ItalianTaxCodeCatalog : ITaxCodeCatalog
|
||||
{
|
||||
/// <summary>The rates of Italian VAT in percent (ordinary and reduced).</summary>
|
||||
public static IReadOnlySet<decimal> StandardRates { get; } = new HashSet<decimal> { 0m, 4m, 5m, 10m, 22m };
|
||||
|
||||
/// <inheritdoc />
|
||||
public CodeList Natures => VatNatures.All;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<TaxCodeDefinition> BaseCodes { get; } =
|
||||
[
|
||||
new("22", "IVA 22%", 22m),
|
||||
new("10", "IVA 10%", 10m),
|
||||
new("5", "IVA 5%", 5m),
|
||||
new("4", "IVA 4%", 4m),
|
||||
new("22SP", "IVA 22% scissione dei pagamenti", 22m, Exigibility: TaxExigibility.SplitPayment, LegalReference: "Art. 17-ter DPR 633/72"),
|
||||
new("10SP", "IVA 10% scissione dei pagamenti", 10m, Exigibility: TaxExigibility.SplitPayment, LegalReference: "Art. 17-ter DPR 633/72"),
|
||||
new("22I50", "IVA 22% indetraibile al 50%", 22m, NonDeductiblePercent: 50m),
|
||||
new("22I100", "IVA 22% indetraibile", 22m, NonDeductiblePercent: 100m),
|
||||
new("ESC15", "Escluso art. 15", 0m, "N1", LegalReference: "Art. 15 DPR 633/72"),
|
||||
new("FC7", "Non soggetto artt. 7-7 septies", 0m, "N2.1", LegalReference: "Artt. 7-7-septies DPR 633/72"),
|
||||
new("NS", "Non soggetto, altri casi", 0m, "N2.2", LegalReference: "Art. 2 DPR 633/72"),
|
||||
new("FORF", "Operazione in regime forfettario", 0m, "N2.2", LegalReference: "Art. 1 c. 54-89 L. 190/2014"),
|
||||
new("NI8", "Non imponibile art. 8 (esportazioni)", 0m, "N3.1", LegalReference: "Art. 8 c. 1 lett. a) DPR 633/72"),
|
||||
new("NI41", "Non imponibile art. 41 (cessioni intracomunitarie)", 0m, "N3.2", LegalReference: "Art. 41 DL 331/93"),
|
||||
new("NI71", "Non imponibile art. 71 (San Marino)", 0m, "N3.3", LegalReference: "Art. 71 DPR 633/72"),
|
||||
new("NI8C", "Non imponibile art. 8 c. 1 lett. c) (dichiarazione d'intento)", 0m, "N3.5", LegalReference: "Art. 8 c. 1 lett. c) DPR 633/72"),
|
||||
new("ESE10", "Esente art. 10", 0m, "N4", LegalReference: "Art. 10 DPR 633/72"),
|
||||
new("RC74", "Inversione contabile, rottami", 0m, "N6.1", LegalReference: "Art. 74 c. 7 e 8 DPR 633/72"),
|
||||
new("RC17O", "Inversione contabile, oro e argento", 0m, "N6.2", LegalReference: "Art. 17 c. 5 DPR 633/72"),
|
||||
new("RC17A", "Inversione contabile, subappalto edile", 0m, "N6.3", LegalReference: "Art. 17 c. 6 lett. a) DPR 633/72"),
|
||||
new("RC17F", "Inversione contabile, cessione di fabbricati", 0m, "N6.4", LegalReference: "Art. 17 c. 6 lett. a-bis) DPR 633/72"),
|
||||
new("RC17B", "Inversione contabile, telefoni cellulari", 0m, "N6.5", LegalReference: "Art. 17 c. 6 lett. b) DPR 633/72"),
|
||||
new("RC17C", "Inversione contabile, prodotti elettronici", 0m, "N6.6", LegalReference: "Art. 17 c. 6 lett. c) DPR 633/72"),
|
||||
new("RC17E", "Inversione contabile, comparto edile e settori connessi", 0m, "N6.7", LegalReference: "Art. 17 c. 6 lett. a-ter) DPR 633/72"),
|
||||
new("RC17N", "Inversione contabile, settore energetico", 0m, "N6.8", LegalReference: "Art. 17 c. 6 lett. d-bis), d-ter), d-quater) DPR 633/72"),
|
||||
new("RC17", "Inversione contabile, altri casi", 0m, "N6.9", LegalReference: "Art. 17 DPR 633/72"),
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public TaxCodeKind KindOf(decimal rate, string? nature) =>
|
||||
string.IsNullOrWhiteSpace(nature) ? TaxCodeKind.Taxable : VatNatures.KindOf(nature);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<FiscalProblem> Validate(TaxCodeDefinition code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var problems = new List<FiscalProblem>();
|
||||
var nature = string.IsNullOrWhiteSpace(code.Nature) ? null : code.Nature.Trim();
|
||||
|
||||
if (code.Rate is < 0m or > 100m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Rate), "fiscal.tax.rate-range"));
|
||||
}
|
||||
else if (!StandardRates.Contains(code.Rate))
|
||||
{
|
||||
// Compensation rates of the agricultural regime are legal but rare: a warning, not an error.
|
||||
problems.Add(new(nameof(code.Rate), "fiscal.tax.rate-unusual", FiscalProblemSeverity.Warning));
|
||||
}
|
||||
|
||||
if (nature is null)
|
||||
{
|
||||
if (code.Rate == 0m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-required"));
|
||||
}
|
||||
}
|
||||
else if (Natures.Find(nature) is not { } entry)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-unknown"));
|
||||
}
|
||||
else if (entry.Obsolete)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-obsolete"));
|
||||
}
|
||||
else if (code.Rate != 0m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Nature), "fiscal.tax.nature-with-rate"));
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(code.LegalReference))
|
||||
{
|
||||
problems.Add(new(nameof(code.LegalReference), "fiscal.tax.legal-reference-missing", FiscalProblemSeverity.Warning));
|
||||
}
|
||||
|
||||
if (code.Exigibility == TaxExigibility.SplitPayment && code.Rate == 0m)
|
||||
{
|
||||
problems.Add(new(nameof(code.Exigibility), "fiscal.tax.split-needs-rate"));
|
||||
}
|
||||
|
||||
if (code.Exigibility != TaxExigibility.Immediate && VatNatures.IsReverseCharge(nature))
|
||||
{
|
||||
problems.Add(new(nameof(code.Exigibility), "fiscal.tax.reverse-charge-immediate"));
|
||||
}
|
||||
|
||||
if (code.NonDeductiblePercent is < 0m or > 100m)
|
||||
{
|
||||
problems.Add(new(nameof(code.NonDeductiblePercent), "fiscal.tax.non-deductible-range"));
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// Italian VAT arithmetic: amounts to the cent, halves away from zero; the tax of the summary is computed on the total
|
||||
/// taxable of each line, as the FatturaPA <c>DatiRiepilogo</c> requires (tolerance of one cent on rows).
|
||||
/// </summary>
|
||||
public sealed class ItalianTaxEngine : ITaxEngine
|
||||
{
|
||||
/// <summary>The stamp duty on invoices without VAT (art. 13 of the tariff of DPR 642/72).</summary>
|
||||
public const decimal StampDutyAmount = 2.00m;
|
||||
|
||||
/// <summary>The amount without VAT above which the stamp duty is due.</summary>
|
||||
public const decimal StampDutyThreshold = 77.47m;
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal Round(decimal amount) => Math.Round(amount, 2, MidpointRounding.AwayFromZero);
|
||||
|
||||
/// <inheritdoc />
|
||||
public decimal ComputeTax(decimal taxable, decimal rate) => Round(taxable * rate / 100m);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<TaxSummaryLine> Summarize(IEnumerable<TaxableAmount> amounts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(amounts);
|
||||
return
|
||||
[
|
||||
.. amounts
|
||||
.GroupBy(a => (a.Rate, Nature: Normalize(a.Nature), a.Exigibility, a.NonDeductiblePercent))
|
||||
.Select(g =>
|
||||
{
|
||||
var taxable = Round(g.Sum(a => a.Amount));
|
||||
var tax = ComputeTax(taxable, g.Key.Rate);
|
||||
return new TaxSummaryLine(g.Key.Rate, g.Key.Nature, g.Key.Exigibility, g.Key.NonDeductiblePercent,
|
||||
taxable, tax, Round(tax * g.Key.NonDeductiblePercent / 100m));
|
||||
})
|
||||
.OrderByDescending(l => l.Rate)
|
||||
.ThenBy(l => l.Nature, StringComparer.Ordinal)
|
||||
.ThenBy(l => l.Exigibility)
|
||||
.ThenBy(l => l.NonDeductiblePercent),
|
||||
];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public StampDutyAssessment AssessStampDuty(IEnumerable<TaxSummaryLine> summary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(summary);
|
||||
var exempt = Round(summary.Where(l => l.Rate == 0m && VatNatures.CountsForStampDuty(l.Nature)).Sum(l => l.Taxable));
|
||||
var required = exempt > StampDutyThreshold;
|
||||
return new StampDutyAssessment(required, required ? StampDutyAmount : 0m, exempt, StampDutyThreshold);
|
||||
}
|
||||
|
||||
private static string? Normalize(string? nature) =>
|
||||
string.IsNullOrWhiteSpace(nature) ? null : nature.Trim().ToUpperInvariant();
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The Italian fiscal pack (SPEC §1.10, ADR 0007, ADR 0025): chosen for companies whose <c>company_profile.country</c>
|
||||
/// is <c>IT</c>. Registered only by the composition root of <c>Khaemhat.Web</c>.
|
||||
/// </summary>
|
||||
public sealed class ItalyFiscalPack : FiscalPackBase
|
||||
{
|
||||
/// <summary>The version of the Italian base data and code lists.</summary>
|
||||
public const string Version = "IT 2026.2";
|
||||
|
||||
/// <summary>Creates the pack with every feature this version delivers.</summary>
|
||||
public ItalyFiscalPack()
|
||||
{
|
||||
AddFeature<IEInvoiceFormat>(new FatturaPaFormat());
|
||||
AddFeature<IWithholdingRules>(new WithholdingRulesIt());
|
||||
AddFeature<IFixedAssetRules>(new FixedAssetRulesIt());
|
||||
AddFeature<ITaxPaymentFormExporter>(new F24Exporter());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string CountryCode => "IT";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Name => "Italia";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string DataVersion => Version;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override ITaxCodeCatalog TaxCodes { get; } = new ItalianTaxCodeCatalog();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override ITaxEngine TaxEngine { get; } = new ItalianTaxEngine();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override IFiscalCalendar Calendar { get; } = new ItalianFiscalCalendar();
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy;
|
||||
|
||||
/// <summary>
|
||||
/// The VAT natures of the FatturaPA specifications (<c>Natura</c>, N1-N7). Since 2021 the generic codes N2, N3 and N6
|
||||
/// are no longer accepted: only their sub-codes.
|
||||
/// </summary>
|
||||
public static class VatNatures
|
||||
{
|
||||
/// <summary>Every nature, obsolete ones included.</summary>
|
||||
public static CodeList All { get; } = new("VatNatures",
|
||||
[
|
||||
new("N1", "Escluse ex art. 15 DPR 633/72"),
|
||||
new("N2", "Non soggette", Obsolete: true),
|
||||
new("N2.1", "Non soggette ad IVA ai sensi degli artt. da 7 a 7-septies DPR 633/72"),
|
||||
new("N2.2", "Non soggette - altri casi"),
|
||||
new("N3", "Non imponibili", Obsolete: true),
|
||||
new("N3.1", "Non imponibili - esportazioni"),
|
||||
new("N3.2", "Non imponibili - cessioni intracomunitarie"),
|
||||
new("N3.3", "Non imponibili - cessioni verso San Marino"),
|
||||
new("N3.4", "Non imponibili - operazioni assimilate alle cessioni all'esportazione"),
|
||||
new("N3.5", "Non imponibili - a seguito di dichiarazioni d'intento"),
|
||||
new("N3.6", "Non imponibili - altre operazioni che non concorrono alla formazione del plafond"),
|
||||
new("N4", "Esenti"),
|
||||
new("N5", "Regime del margine / IVA non esposta in fattura"),
|
||||
new("N6", "Inversione contabile", Obsolete: true),
|
||||
new("N6.1", "Inversione contabile - cessione di rottami e altri materiali di recupero"),
|
||||
new("N6.2", "Inversione contabile - cessione di oro e argento ai sensi della L. 7/2000 nonché di oreficeria usata ad OPO"),
|
||||
new("N6.3", "Inversione contabile - subappalto nel settore edile"),
|
||||
new("N6.4", "Inversione contabile - cessione di fabbricati"),
|
||||
new("N6.5", "Inversione contabile - cessione di telefoni cellulari"),
|
||||
new("N6.6", "Inversione contabile - cessione di prodotti elettronici"),
|
||||
new("N6.7", "Inversione contabile - prestazioni comparto edile e settori connessi"),
|
||||
new("N6.8", "Inversione contabile - operazioni settore energetico"),
|
||||
new("N6.9", "Inversione contabile - altri casi"),
|
||||
new("N7", "IVA assolta in altro stato UE (art. 7-octies e art. 74-sexies DPR 633/72)"),
|
||||
]);
|
||||
|
||||
// Natures whose amounts count toward the stamp duty threshold: exports (N3.1), intra-EU supplies (N3.2), San Marino
|
||||
// (N3.3), operations assimilated to exports (N3.4), reverse charge (N6.x) and VAT paid in another EU state (N7) are
|
||||
// exempt from stamp duty (art. 15 of the table attached to DPR 642/72 and the Agenzia's guidance).
|
||||
private static readonly HashSet<string> StampDutyNatures = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"N1", "N2.1", "N2.2", "N3.5", "N3.6", "N4", "N5",
|
||||
};
|
||||
|
||||
/// <summary>The kind of operation a nature describes; no nature means a taxable operation.</summary>
|
||||
/// <param name="nature">The nature code.</param>
|
||||
/// <returns>The kind.</returns>
|
||||
public static TaxCodeKind KindOf(string? nature)
|
||||
{
|
||||
var code = nature?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||
return code switch
|
||||
{
|
||||
"" => TaxCodeKind.Taxable,
|
||||
"N1" => TaxCodeKind.Excluded,
|
||||
"N4" => TaxCodeKind.Exempt,
|
||||
"N5" => TaxCodeKind.Margin,
|
||||
"N7" => TaxCodeKind.OtherEuVat,
|
||||
_ when code.StartsWith("N2", StringComparison.Ordinal) => TaxCodeKind.NotSubject,
|
||||
_ when code.StartsWith("N3", StringComparison.Ordinal) => TaxCodeKind.NonTaxable,
|
||||
_ when code.StartsWith("N6", StringComparison.Ordinal) => TaxCodeKind.ReverseCharge,
|
||||
_ => throw new ArgumentException($"Unknown VAT nature '{nature}'.", nameof(nature)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Whether an amount with this nature counts toward the stamp duty threshold.</summary>
|
||||
/// <param name="nature">The nature code.</param>
|
||||
/// <returns><see langword="true"/> when the stamp duty rule counts it.</returns>
|
||||
public static bool CountsForStampDuty(string? nature) => nature is not null && StampDutyNatures.Contains(nature.Trim());
|
||||
|
||||
/// <summary>Whether the nature is a reverse charge one (N6.x).</summary>
|
||||
/// <param name="nature">The nature code.</param>
|
||||
/// <returns><see langword="true"/> for reverse charge.</returns>
|
||||
public static bool IsReverseCharge(string? nature) =>
|
||||
nature is not null && nature.Trim().StartsWith("N6", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -23,6 +23,8 @@ using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.PostgreSql;
|
||||
using Khaemhat.Data.Sqlite;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
using Khaemhat.Fiscal.Italy;
|
||||
using Khaemhat.Infrastructure.Caching;
|
||||
using Khaemhat.Infrastructure.Files;
|
||||
using Khaemhat.Infrastructure.Licensing;
|
||||
@@ -125,6 +127,11 @@ internal static class KhaemhatServices
|
||||
services.AddSingleton<SignInService>();
|
||||
services.AddSingleton<ProfileService>();
|
||||
|
||||
// Country fiscal packs (ADR 0007, ADR 0025): the only place that names a concrete pack. The application finds
|
||||
// the pack of a company through FiscalPackCatalog and company_profile.country.
|
||||
services.AddSingleton<IFiscalPack, ItalyFiscalPack>();
|
||||
services.AddSingleton(sp => new FiscalPackCatalog(sp.GetServices<IFiscalPack>()));
|
||||
|
||||
// Companies and start.
|
||||
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
|
||||
services.AddSingleton<CompanyService>();
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
namespace Khaemhat.Core.Tests.Architecture;
|
||||
|
||||
/// <summary>
|
||||
/// ADR 0007 and ADR 0025: the Italian pack is reached only through the interfaces of <c>Khaemhat.Fiscal.Abstractions</c>.
|
||||
/// Project references already keep it out of <c>Application</c>; these tests keep it out of the sources of
|
||||
/// <c>Web</c> too, except for the composition root.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class FiscalPackIsolationTests
|
||||
{
|
||||
private const string ItalianNamespace = "Khaemhat.Fiscal.Italy";
|
||||
|
||||
// The composition root registers the pack; nothing else names it.
|
||||
private static readonly HashSet<string> AllowedOutsideThePack = new(StringComparer.Ordinal)
|
||||
{
|
||||
"src/Khaemhat.Web/Hosting/KhaemhatServices.cs",
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyTheCompositionRoot_NamesTheItalianPack()
|
||||
{
|
||||
var violations = SourceFiles()
|
||||
.Where(f => !f.Relative.StartsWith("src/Khaemhat.Fiscal.Italy/", StringComparison.Ordinal))
|
||||
.Where(f => !AllowedOutsideThePack.Contains(f.Relative))
|
||||
.Where(f => File.ReadAllText(f.Path).Contains(ItalianNamespace, StringComparison.Ordinal))
|
||||
.Select(f => f.Relative)
|
||||
.ToList();
|
||||
|
||||
Assert.IsEmpty(violations, "Use IFiscalPack and FiscalPackCatalog instead of the Italian pack in: " + string.Join(", ", violations));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheAbstractions_SayNothingItalian()
|
||||
{
|
||||
string[] italianTerms = ["Italy", "Italian", "FatturaPa", "Iva"];
|
||||
var violations = SourceFiles()
|
||||
.Where(f => f.Relative.StartsWith("src/Khaemhat.Fiscal.Abstractions/", StringComparison.Ordinal))
|
||||
.SelectMany(f => italianTerms
|
||||
.Where(term => CodeLines(f.Path).Any(line => line.Contains(term, StringComparison.Ordinal)))
|
||||
.Select(term => $"{f.Relative}: {term}"))
|
||||
.ToList();
|
||||
|
||||
Assert.IsEmpty(violations, "Country-specific names belong in the country pack: " + string.Join("; ", violations));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCompositionRoot_RegistersThePackBehindTheCatalog()
|
||||
{
|
||||
var root = File.ReadAllText(Path.Combine(RepositoryLayout.Root, "src", "Khaemhat.Web", "Hosting", "KhaemhatServices.cs"));
|
||||
|
||||
StringAssert.Contains(root, "AddSingleton<IFiscalPack, ItalyFiscalPack>()");
|
||||
StringAssert.Contains(root, "new FiscalPackCatalog(");
|
||||
}
|
||||
|
||||
private static IEnumerable<(string Path, string Relative)> SourceFiles() =>
|
||||
Directory.EnumerateFiles(Path.Combine(RepositoryLayout.Root, "src"), "*.*", SearchOption.AllDirectories)
|
||||
.Where(f => f.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".razor", StringComparison.OrdinalIgnoreCase))
|
||||
.Select(f => (Path: f, Relative: RepositoryLayout.Relative(f)))
|
||||
.Where(f => !f.Relative.Contains("/obj/", StringComparison.Ordinal) && !f.Relative.Contains("/bin/", StringComparison.Ordinal));
|
||||
|
||||
// Comments may cite the country as an example (Italy: N1...N7); code may not.
|
||||
private static IEnumerable<string> CodeLines(string path) =>
|
||||
File.ReadLines(path).Where(line => !line.TrimStart().StartsWith("//", StringComparison.Ordinal));
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
using Khaemhat.Core.Tax;
|
||||
using Khaemhat.Fiscal.Abstractions;
|
||||
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
[TestClass]
|
||||
public sealed class ItalyFiscalPackTests
|
||||
{
|
||||
private static readonly ItalyFiscalPack Pack = new();
|
||||
|
||||
[TestMethod]
|
||||
public void Pack_IsItalianWithItsDataVersion()
|
||||
{
|
||||
Assert.AreEqual("IT", Pack.CountryCode);
|
||||
Assert.AreEqual("IT 2026.2", Pack.DataVersion);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Pack_DeliversTheFeaturesOfThisMilestone()
|
||||
{
|
||||
Assert.IsTrue(Pack.Supports<IEInvoiceFormat>());
|
||||
Assert.IsTrue(Pack.Supports<IWithholdingRules>());
|
||||
Assert.IsTrue(Pack.Supports<IFixedAssetRules>());
|
||||
Assert.IsTrue(Pack.Supports<ITaxPaymentFormExporter>());
|
||||
Assert.AreSame(Pack.TaxCodes, Pack.GetFeature<ITaxCodeCatalog>());
|
||||
Assert.AreSame(Pack.Calendar, Pack.Require<IFiscalCalendar>());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Require_OfAFeatureNotYetDelivered_SaysWhichOne()
|
||||
{
|
||||
var ex = Assert.ThrowsExactly<FiscalFeatureNotAvailableException>(() => Pack.Require<IIntrastatExporter>());
|
||||
|
||||
Assert.AreEqual("IT", ex.CountryCode);
|
||||
Assert.AreEqual(nameof(IIntrastatExporter), ex.Feature);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Catalog_FindsThePackByCountryWithoutCase()
|
||||
{
|
||||
var catalog = new FiscalPackCatalog([Pack]);
|
||||
|
||||
Assert.AreSame(Pack, catalog.ForCountry("it"));
|
||||
Assert.AreSame(Pack, catalog.ForCountry(" IT "));
|
||||
Assert.IsFalse(catalog.TryForCountry("FR", out _));
|
||||
Assert.ThrowsExactly<FiscalPackNotFoundException>(() => catalog.ForCountry(null));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Catalog_RefusesTwoPacksForOneCountry() =>
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new FiscalPackCatalog([Pack, new ItalyFiscalPack()]));
|
||||
}
|
||||
|
||||
[TestClass]
|
||||
public sealed class FatturaPaCodeListsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void SpecVersion_IsTheLatestChecked() => Assert.AreEqual("1.9.1", new FatturaPaFormat().SpecVersion);
|
||||
|
||||
[TestMethod]
|
||||
public void DocumentTypes_RunFromTD01ToTD29WithoutTheRemovedOnes()
|
||||
{
|
||||
var codes = FatturaPaCodeLists.DocumentTypes.Entries.Select(e => e.Code).ToList();
|
||||
|
||||
Assert.HasCount(23, codes);
|
||||
Assert.AreEqual("TD01", codes[0]);
|
||||
Assert.AreEqual("TD29", codes[^1]);
|
||||
Assert.IsNull(FatturaPaCodeLists.DocumentTypes.Find("TD10"));
|
||||
Assert.IsTrue(FatturaPaCodeLists.DocumentTypes.IsActive("td24"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PaymentMethods_AreMP01ToMP23()
|
||||
{
|
||||
var codes = FatturaPaCodeLists.PaymentMethods.Entries.Select(e => e.Code).ToList();
|
||||
|
||||
CollectionAssert.AreEqual(Enumerable.Range(1, 23).Select(n => $"MP{n:00}").ToList(), codes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TaxRegimes_KeepRF03OnlyAsObsolete()
|
||||
{
|
||||
Assert.HasCount(18, FatturaPaCodeLists.TaxRegimes.Active.ToList());
|
||||
Assert.IsFalse(FatturaPaCodeLists.TaxRegimes.IsActive("RF03"));
|
||||
Assert.IsTrue(FatturaPaCodeLists.TaxRegimes.IsActive("RF19"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SocialSecurityFunds_AreTC01ToTC22() =>
|
||||
Assert.HasCount(22, FatturaPaCodeLists.SocialSecurityFunds.Entries);
|
||||
|
||||
[TestMethod]
|
||||
public void CodeList_RefusesDuplicates() =>
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new CodeList("X", [new("A", "a"), new("a", "b")]));
|
||||
}
|
||||
|
||||
[TestClass]
|
||||
public sealed class ItalianTaxCodeCatalogTests
|
||||
{
|
||||
private static readonly ItalianTaxCodeCatalog Catalog = new();
|
||||
|
||||
[TestMethod]
|
||||
public void Natures_AcceptOnlyTheSubCodesOfN2N3N6()
|
||||
{
|
||||
Assert.IsFalse(Catalog.Natures.IsActive("N2"));
|
||||
Assert.IsFalse(Catalog.Natures.IsActive("N3"));
|
||||
Assert.IsFalse(Catalog.Natures.IsActive("N6"));
|
||||
Assert.IsTrue(Catalog.Natures.IsActive("N6.9"));
|
||||
Assert.HasCount(21, Catalog.Natures.Active.ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BaseCodes_HaveNoErrorsAndUniqueCodes()
|
||||
{
|
||||
var errors = Catalog.BaseCodes
|
||||
.SelectMany(c => Catalog.Validate(c).Where(p => p.Severity == FiscalProblemSeverity.Error).Select(p => $"{c.Code}: {p.Code}"))
|
||||
.ToList();
|
||||
|
||||
Assert.IsEmpty(errors, string.Join(", ", errors));
|
||||
Assert.HasCount(Catalog.BaseCodes.Count, Catalog.BaseCodes.Select(c => c.Code).Distinct(StringComparer.OrdinalIgnoreCase).ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BaseCodes_CoverTheCodesOfSpecSection14()
|
||||
{
|
||||
string[] expected = ["22", "10", "5", "4", "ESE10", "NI8", "NI41", "NI71", "NI8C", "FC7", "ESC15", "RC17", "NS", "22I50", "22I100", "FORF"];
|
||||
var codes = Catalog.BaseCodes.Select(c => c.Code).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
Assert.IsEmpty(expected.Where(c => !codes.Contains(c)).ToList());
|
||||
Assert.IsTrue(Catalog.BaseCodes.Any(c => c.Exigibility == TaxExigibility.SplitPayment));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(0, null, "Nature", "fiscal.tax.nature-required")]
|
||||
[DataRow(22, "N4", "Nature", "fiscal.tax.nature-with-rate")]
|
||||
[DataRow(0, "N9", "Nature", "fiscal.tax.nature-unknown")]
|
||||
[DataRow(0, "N2", "Nature", "fiscal.tax.nature-obsolete")]
|
||||
[DataRow(-1, null, "Rate", "fiscal.tax.rate-range")]
|
||||
public void Validate_ReportsTheBrokenRule(int rate, string? nature, string field, string code)
|
||||
{
|
||||
var problems = Catalog.Validate(new TaxCodeDefinition("X", "x", rate, nature, LegalReference: "Art. 1"));
|
||||
|
||||
Assert.IsTrue(problems.Any(p => p.Field == field && p.Code == code && p.Severity == FiscalProblemSeverity.Error),
|
||||
string.Join(", ", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Validate_WarnsWithoutLegalReferenceAndOnUnusualRates()
|
||||
{
|
||||
var noReference = Catalog.Validate(new TaxCodeDefinition("ESE", "Esente", 0m, "N4"));
|
||||
var unusual = Catalog.Validate(new TaxCodeDefinition("AGR", "Compensazione", 7.3m));
|
||||
|
||||
Assert.AreEqual(FiscalProblemSeverity.Warning, noReference.Single().Severity);
|
||||
Assert.AreEqual("fiscal.tax.rate-unusual", unusual.Single().Code);
|
||||
Assert.AreEqual(FiscalProblemSeverity.Warning, unusual.Single().Severity);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Validate_RefusesSplitWithoutTaxAndReverseChargeNotImmediate()
|
||||
{
|
||||
var split = Catalog.Validate(new TaxCodeDefinition("S", "s", 0m, "N4", TaxExigibility.SplitPayment, LegalReference: "x"));
|
||||
var reverse = Catalog.Validate(new TaxCodeDefinition("R", "r", 0m, "N6.3", TaxExigibility.Deferred, LegalReference: "x"));
|
||||
|
||||
Assert.IsTrue(split.Any(p => p.Code == "fiscal.tax.split-needs-rate"));
|
||||
Assert.IsTrue(reverse.Any(p => p.Code == "fiscal.tax.reverse-charge-immediate"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(null, TaxCodeKind.Taxable)]
|
||||
[DataRow("N1", TaxCodeKind.Excluded)]
|
||||
[DataRow("N2.1", TaxCodeKind.NotSubject)]
|
||||
[DataRow("N3.5", TaxCodeKind.NonTaxable)]
|
||||
[DataRow("N4", TaxCodeKind.Exempt)]
|
||||
[DataRow("N5", TaxCodeKind.Margin)]
|
||||
[DataRow("n6.4", TaxCodeKind.ReverseCharge)]
|
||||
[DataRow("N7", TaxCodeKind.OtherEuVat)]
|
||||
public void KindOf_FollowsTheNature(string? nature, TaxCodeKind kind) => Assert.AreEqual(kind, Catalog.KindOf(0m, nature));
|
||||
}
|
||||
|
||||
[TestClass]
|
||||
public sealed class ItalianTaxEngineTests
|
||||
{
|
||||
private static readonly ItalianTaxEngine Engine = new();
|
||||
|
||||
[TestMethod]
|
||||
public void Round_TakesHalvesAwayFromZero()
|
||||
{
|
||||
Assert.AreEqual(0.13m, Engine.Round(0.125m));
|
||||
Assert.AreEqual(-0.13m, Engine.Round(-0.125m));
|
||||
Assert.AreEqual(2.2m, Engine.ComputeTax(10m, 22m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Summarize_ComputesTheTaxOnTheTotalOfEachRate()
|
||||
{
|
||||
// Three rows of 0.07 at 22%: per row the tax would be 0.02 each (0.06); on the total it is 0.21 * 22% = 0.0462 -> 0.05.
|
||||
var summary = Engine.Summarize(
|
||||
[
|
||||
new(0.07m, 22m), new(0.07m, 22m), new(0.07m, 22m),
|
||||
new(100m, 10m),
|
||||
new(50m, 0m, "N4"),
|
||||
]);
|
||||
|
||||
Assert.HasCount(3, summary);
|
||||
Assert.AreEqual(22m, summary[0].Rate);
|
||||
Assert.AreEqual(0.21m, summary[0].Taxable);
|
||||
Assert.AreEqual(0.05m, summary[0].Tax);
|
||||
Assert.AreEqual(10m, summary[1].Tax);
|
||||
Assert.AreEqual("N4", summary[2].Nature);
|
||||
Assert.AreEqual(0m, summary[2].Tax);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Summarize_KeepsSplitPaymentAndNonDeductibleApart()
|
||||
{
|
||||
var summary = Engine.Summarize(
|
||||
[
|
||||
new(100m, 22m),
|
||||
new(100m, 22m, Exigibility: TaxExigibility.SplitPayment),
|
||||
new(100m, 22m, NonDeductiblePercent: 50m),
|
||||
]);
|
||||
|
||||
Assert.HasCount(3, summary);
|
||||
Assert.AreEqual(11m, summary.Single(l => l.NonDeductiblePercent == 50m).NonDeductibleTax);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StampDuty_IsDueAboveTheThresholdOfExemptAmounts()
|
||||
{
|
||||
var exempt = Engine.AssessStampDuty(Engine.Summarize([new(77.48m, 0m, "N4")]));
|
||||
var atThreshold = Engine.AssessStampDuty(Engine.Summarize([new(77.47m, 0m, "N4")]));
|
||||
var mixed = Engine.AssessStampDuty(Engine.Summarize([new(1000m, 22m), new(50m, 0m, "N2.2"), new(30m, 0m, "N3.5")]));
|
||||
|
||||
Assert.IsTrue(exempt.Required);
|
||||
Assert.AreEqual(2.00m, exempt.Amount);
|
||||
Assert.IsFalse(atThreshold.Required);
|
||||
Assert.IsTrue(mixed.Required);
|
||||
Assert.AreEqual(80m, mixed.ExemptTotal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("N3.1")]
|
||||
[DataRow("N3.2")]
|
||||
[DataRow("N6.3")]
|
||||
public void StampDuty_IsNotDueOnExportsIntraEuAndReverseCharge(string nature) =>
|
||||
Assert.IsFalse(Engine.AssessStampDuty(Engine.Summarize([new(1000m, 0m, nature)])).Required);
|
||||
}
|
||||
|
||||
[TestClass]
|
||||
public sealed class ItalianFiscalCalendarTests
|
||||
{
|
||||
private static readonly ItalianFiscalCalendar Calendar = new();
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(2026, 1, 2026, 2, 16)] // Monday 16 February
|
||||
[DataRow(2026, 4, 2026, 5, 18)] // 16 May 2026 is a Saturday
|
||||
[DataRow(2026, 7, 2026, 8, 20)] // August deadlines move to the 20th
|
||||
[DataRow(2026, 12, 2027, 1, 18)] // 16 January 2027 is a Saturday
|
||||
public void MonthlyVat_IsDueOnThe16thOfTheNextMonth(int year, int month, int y, int m, int d) =>
|
||||
Assert.AreEqual(new DateOnly(y, m, d), Calendar.VatPaymentDue(TaxPeriod.Of(year, month, VatPeriodicity.Monthly)));
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(1, 2026, 5, 18)]
|
||||
[DataRow(2, 2026, 8, 20)]
|
||||
[DataRow(3, 2026, 11, 16)]
|
||||
[DataRow(4, 2027, 3, 16)]
|
||||
public void QuarterlyVat_IsDueOnThe16thOfTheSecondMonth(int quarter, int y, int m, int d) =>
|
||||
Assert.AreEqual(new DateOnly(y, m, d), Calendar.VatPaymentDue(TaxPeriod.Of(2026, quarter, VatPeriodicity.Quarterly)));
|
||||
|
||||
[TestMethod]
|
||||
public void QuarterlyVat_CarriesOnePercentInterest()
|
||||
{
|
||||
Assert.AreEqual(1m, Calendar.VatInterestRate(VatPeriodicity.Quarterly));
|
||||
Assert.AreEqual(0m, Calendar.VatInterestRate(VatPeriodicity.Monthly));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Holidays_IncludeEasterMondayAndTheFixedOnes()
|
||||
{
|
||||
Assert.AreEqual(new DateOnly(2026, 4, 5), ItalianFiscalCalendar.EasterSunday(2026));
|
||||
Assert.AreEqual(new DateOnly(2027, 3, 28), ItalianFiscalCalendar.EasterSunday(2027));
|
||||
Assert.IsTrue(ItalianFiscalCalendar.IsPublicHoliday(new DateOnly(2026, 4, 6)));
|
||||
Assert.IsTrue(ItalianFiscalCalendar.IsPublicHoliday(new DateOnly(2026, 6, 2)));
|
||||
Assert.IsTrue(ItalianFiscalCalendar.IsPublicHoliday(new DateOnly(2026, 10, 4)));
|
||||
Assert.IsFalse(ItalianFiscalCalendar.IsPublicHoliday(new DateOnly(2025, 10, 4)));
|
||||
Assert.AreEqual(new DateOnly(2026, 12, 28), Calendar.NextWorkingDay(new DateOnly(2026, 12, 25)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TaxPeriod_CoversTheMonthsOfTheQuarter()
|
||||
{
|
||||
var q2 = TaxPeriod.Containing(new DateOnly(2026, 5, 31), VatPeriodicity.Quarterly);
|
||||
|
||||
Assert.AreEqual(2, q2.Number);
|
||||
Assert.AreEqual(new DateOnly(2026, 4, 1), q2.Start);
|
||||
Assert.AreEqual(new DateOnly(2026, 6, 30), q2.End);
|
||||
Assert.HasCount(12, TaxPeriod.OfYear(2026, VatPeriodicity.Monthly));
|
||||
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => TaxPeriod.Of(2026, 5, VatPeriodicity.Quarterly));
|
||||
}
|
||||
}
|
||||
|
||||
[TestClass]
|
||||
public sealed class ItalianRulesTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Withholding_OfAgents_AppliesTheRateToHalfTheCommission()
|
||||
{
|
||||
var rules = new WithholdingRulesIt();
|
||||
|
||||
Assert.AreEqual(115m, rules.Compute(1000m, rules.Kinds.Single(k => k.Code == "AGEN")));
|
||||
Assert.AreEqual(46m, rules.Compute(1000m, rules.Kinds.Single(k => k.Code == "AGEND")));
|
||||
Assert.AreEqual(200m, rules.Compute(1000m, rules.Kinds.Single(k => k.Code == "PROF")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Withholding_KindsUseActiveCodes()
|
||||
{
|
||||
var rules = new WithholdingRulesIt();
|
||||
|
||||
foreach (var kind in rules.Kinds)
|
||||
{
|
||||
Assert.IsTrue(rules.InvoiceTypes.IsActive(kind.InvoiceType), kind.Code);
|
||||
Assert.IsTrue(rules.PaymentReasons.IsActive(kind.PaymentReason), kind.Code);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FixedAssets_HalveTheFirstYearAndStopAtTheCost()
|
||||
{
|
||||
var rules = new FixedAssetRulesIt();
|
||||
|
||||
Assert.AreEqual(1000m, rules.YearlyDepreciation(10_000m, 20m, firstYear: true, 0m));
|
||||
Assert.AreEqual(2000m, rules.YearlyDepreciation(10_000m, 20m, firstYear: false, 1000m));
|
||||
Assert.AreEqual(1000m, rules.YearlyDepreciation(10_000m, 20m, firstYear: false, 9000m));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void F24_CodesFollowThePeriod()
|
||||
{
|
||||
var f24 = new F24Exporter();
|
||||
|
||||
Assert.AreEqual("6001", f24.VatCode(TaxPeriod.Of(2026, 1, VatPeriodicity.Monthly)));
|
||||
Assert.AreEqual("6012", f24.VatCode(TaxPeriod.Of(2026, 12, VatPeriodicity.Monthly)));
|
||||
Assert.AreEqual("6033", f24.VatCode(TaxPeriod.Of(2026, 3, VatPeriodicity.Quarterly)));
|
||||
Assert.AreEqual("6035", f24.VatAdvanceCode(VatPeriodicity.Quarterly));
|
||||
Assert.AreEqual("2524", f24.StampDutyCode(4));
|
||||
Assert.IsTrue(f24.Codes.Any(c => c.Code == "6099"));
|
||||
Assert.HasCount(f24.Codes.Count, f24.Codes.Select(c => c.Code).Distinct().ToList());
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace Khaemhat.Fiscal.Italy.Tests;
|
||||
|
||||
/// <summary>Keeps the test project runnable until the milestone that fills it (see docs/STATUS.md).</summary>
|
||||
[TestClass]
|
||||
public sealed class ProjectSmokeTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TestedAssembly_IsKhaemhat() =>
|
||||
StringAssert.StartsWith(typeof(ProjectSmokeTests).Assembly.GetName().Name, "Khaemhat.");
|
||||
}
|
||||
Reference in new issue
Block a user