Files
Khaemhat/src/Khaemhat.Fiscal.Italy/VatSettlementRulesIt.cs
T
Alby96andClaude Opus 5.5 9e3ba92993 feat: general ledger, automatic posting, VAT settlement, withholdings and F24 (#62 #63 #64 #65 #66 #67 #68)
M7 adds the double-entry ledger so that the documents of M5 and M6 reach the
accounts without retyping, and the Italian VAT obligations can be prepared from
the same data.

- Chart of accounts on three levels with the Italian "PMI standard" model in the
  fiscal pack, journal templates with proposed lines, VAT registers; the chart
  import now writes the accounts and exports them (#62, ADR 0036).
- Journal entries: draft, posted, final with the libro giornale number,
  reversal; recurring entries with the nightly ledger.recurring job (#63).
- Documents post their entry inside the document transaction (PostingEngine,
  LedgerPoster) with VAT lines, open items and withholdings; a change rewrites
  the same entry, a cancellation removes or reverses it (#64, ADR 0037).
- VAT registers with final print, monthly or quarterly settlement with pro rata,
  interest, minimum and advance, confirmation with the LIQ entry, period lock
  and F24 line, LIPE file and F24 data (#65).
- Operated and suffered withholdings, CU data, stamp duty by quarter with the
  5,000 euro threshold, F24 summary with its payment entry (#66).
- Party ledgers, account ledgers, trial balance and libro giornale (#67).
- Demo accounting with the settlements of the past months confirmed and checked
  by hand in a test; wiki Contabilita, IVA, Fiscalita italiana completed with
  screenshots; CHANGELOG 0.7.0, STATUS, ADR 0036-0037 (#68).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 01:41:58 +01:00

190 lines
8.3 KiB
C#

using System.Globalization;
using System.Text;
using System.Xml;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Fiscal.Italy;
/// <summary>
/// The Italian rules of the periodic VAT settlement and of the other payments of the ledger (issue #65, ADR 0037):
/// <list type="bullet">
/// <item>payments below 25.82 euro are not made and move to the next period (art. 1 c. 4 DPR 100/1998);</item>
/// <item>the December advance is 88% of the base, not due below 103.29 euro, paid by 27 December (L. 405/1990);</item>
/// <item>the last quarter of quarterly payers is paid with the annual return, code 6099 installment <c>0101</c>;</item>
/// <item>withholdings are paid by the 16th of the month after the payment of the fee;</item>
/// <item>the stamp duty of e-invoices of a quarter by 31 May, 30 September, 30 November and 28 February (DM 17/06/2014);</item>
/// <item>the communication of the settlements (LIPE) by 31 May, 16 September, 30 November and the end of February.</item>
/// </list>
/// Deadlines on Saturdays, Sundays and holidays move to the next working day; payments due from 1 to 20 August to the 20th.
/// </summary>
public sealed class VatSettlementRulesIt : IVatSettlementRules
{
private readonly ItalianFiscalCalendar _calendar = new();
/// <inheritdoc />
public decimal MinimumPayment => 25.82m;
/// <inheritdoc />
public decimal AdvancePercent => 88m;
/// <inheritdoc />
public decimal AdvanceMinimum => 103.29m;
/// <inheritdoc />
public string PaymentCode(TaxPeriod period)
{
ArgumentNullException.ThrowIfNull(period);
return period.Periodicity == VatPeriodicity.Monthly
? (6000 + period.Number).ToString(CultureInfo.InvariantCulture)
: period.Number == 4 ? "6099" : (6030 + period.Number).ToString(CultureInfo.InvariantCulture);
}
/// <inheritdoc />
public string? PaymentPeriod(TaxPeriod period)
{
ArgumentNullException.ThrowIfNull(period);
return period.Periodicity == VatPeriodicity.Quarterly && period.Number == 4 ? "0101" : null;
}
/// <inheritdoc />
public DateOnly AdvanceDue(int year) => _calendar.NextWorkingDay(new DateOnly(year, 12, 27));
/// <inheritdoc />
public DateOnly WithholdingDue(int year, int month) => Payment(new DateOnly(year, month, 16).AddMonths(1));
/// <inheritdoc />
public DateOnly StampDutyDue(int year, int quarter) => Payment(quarter switch
{
1 => new DateOnly(year, 5, 31),
2 => new DateOnly(year, 9, 30),
3 => new DateOnly(year, 11, 30),
4 => new DateOnly(year + 1, 2, 28),
_ => throw new ArgumentOutOfRangeException(nameof(quarter)),
});
/// <inheritdoc />
public DateOnly PeriodicReturnDue(int year, int quarter) => _calendar.NextWorkingDay(quarter switch
{
1 => new DateOnly(year, 5, 31),
2 => new DateOnly(year, 9, 16),
3 => new DateOnly(year, 11, 30),
4 => new DateOnly(year + 1, 3, 1).AddDays(-1),
_ => throw new ArgumentOutOfRangeException(nameof(quarter)),
});
private DateOnly Payment(DateOnly due) =>
_calendar.NextWorkingDay(due.Month == 8 && due.Day <= 20 ? new DateOnly(due.Year, 8, 20) : due);
}
/// <summary>
/// The communication of the periodic VAT settlements (LIPE, art. 21-bis DL 78/2010) in the XML of the technical
/// specifications <c>IVP18</c> of the Agenzia delle Entrate: one <c>Modulo</c> per month or quarter, amounts with a comma
/// and two decimals. The file is meant for the intermediary or for the web services of the Agenzia, which sign and send it.
/// </summary>
public sealed class LipeWriter : IPeriodicVatReturnWriter
{
/// <summary>The namespace of the schema.</summary>
public const string Namespace = "urn:www.agenziaentrate.gov.it:specificheTecniche:sco:ivp";
/// <inheritdoc />
public string Name => "LIPE";
/// <inheritdoc />
public string FileName(PeriodicVatReturn data)
{
ArgumentNullException.ThrowIfNull(data);
return string.Create(CultureInfo.InvariantCulture, $"IT{data.TaxCode}_LI_{data.Year}_T{data.Quarter}.xml");
}
/// <inheritdoc />
public byte[] Write(PeriodicVatReturn data)
{
ArgumentNullException.ThrowIfNull(data);
var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true };
using var buffer = new MemoryStream();
using (var xml = XmlWriter.Create(buffer, settings))
{
xml.WriteStartDocument();
xml.WriteStartElement("iv", "Fornitura", Namespace);
xml.WriteStartElement("iv", "Intestazione", Namespace);
Element(xml, "CodiceFornitura", "IVP18");
if (data.DeclarantTaxCode is { Length: > 0 } declarant)
{
Element(xml, "CodiceFiscaleDichiarante", declarant);
Element(xml, "CodiceCarica", "1");
}
xml.WriteEndElement();
xml.WriteStartElement("iv", "Comunicazione", Namespace);
xml.WriteAttributeString("identificativo", "00001");
xml.WriteStartElement("iv", "Frontespizio", Namespace);
Element(xml, "CodiceFiscale", data.TaxCode);
Element(xml, "AnnoImposta", data.Year.ToString(CultureInfo.InvariantCulture));
Element(xml, "PartitaIVA", data.VatNumber);
if (data.DeclarantTaxCode is { Length: > 0 } signer)
{
Element(xml, "CFDichiarante", signer);
Element(xml, "CodiceCaricaDichiarante", "1");
}
Element(xml, "FirmaDichiarazione", "1");
if (data.IntermediaryTaxCode is { Length: > 0 } intermediary)
{
Element(xml, "CFIntermediario", intermediary);
Element(xml, "ImpegnoPresentazione", "1");
Element(xml, "DataImpegno", data.CommitmentDate.ToString("ddMMyyyy", CultureInfo.InvariantCulture));
Element(xml, "FirmaIntermediario", "1");
}
xml.WriteEndElement();
xml.WriteStartElement("iv", "DatiContabili", Namespace);
var number = 0;
foreach (var module in data.Modules)
{
xml.WriteStartElement("iv", "Modulo", Namespace);
Element(xml, "NumeroModulo", (++number).ToString(CultureInfo.InvariantCulture));
Element(
xml,
module.Period.Periodicity == VatPeriodicity.Monthly ? "Mese" : "Trimestre",
module.Period.Number.ToString(CultureInfo.InvariantCulture));
Amount(xml, "TotaleOperazioniAttive", module.ActiveTotal);
Amount(xml, "TotaleOperazioniPassive", module.PassiveTotal);
Amount(xml, "IvaEsigibile", module.TaxDue);
Amount(xml, "IvaDetratta", module.TaxDeducted);
var difference = module.TaxDue - module.TaxDeducted;
Amount(xml, difference >= 0m ? "IvaDovuta" : "IvaCredito", Math.Abs(difference));
Amount(xml, "DebitoPrecedente", module.PreviousDebit);
Amount(xml, "CreditoPeriodoPrecedente", module.PreviousCredit);
Amount(xml, "InteressiDovuti", module.Interest);
Amount(xml, "Acconto", module.Advance);
Amount(xml, module.Balance >= 0m ? "ImportoDaVersare" : "ImportoACredito", Math.Abs(module.Balance), always: true);
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndDocument();
}
return buffer.ToArray();
}
/// <summary>An amount as the schema wants it: comma and two decimals, no thousands separator.</summary>
/// <param name="amount">The amount.</param>
/// <returns>The text, such as <c>1234,50</c>.</returns>
public static string FormatAmount(decimal amount) =>
Math.Round(amount, 2, MidpointRounding.AwayFromZero).ToString("0.00", CultureInfo.InvariantCulture).Replace('.', ',');
private static void Element(XmlWriter xml, string name, string value) => xml.WriteElementString("iv", name, Namespace, value);
private static void Amount(XmlWriter xml, string name, decimal value, bool always = false)
{
if (value != 0m || always)
{
Element(xml, name, FormatAmount(value));
}
}
}