Files
Khaemhat/src/Khaemhat.Application/Documents/DocumentTotalsCalculator.cs
T
Alby96andClaude Opus 5.5 f12848865d feat: document totals, VAT summary, stamp duty, withholding and installments (#48)
The engine now computes the totals of every document it saves: line amounts with
cascaded discounts, footer discount on goods, VAT summary per tax code with the tax
on the group total, prices with VAT split back once per group, split payment and
cash-basis exigibility, stamp duty above the threshold of the fiscal pack, social
security contribution, withholding (also on part of the amount) and ENASARCO taken
off the amount to pay. Installments come from the payment terms with end of month,
fixed day, the customer's excluded months and VAT on the first installment.

The figures live in two shared tables keyed by family (ADR 0033) and are rewritten
in the same transaction as the document. DocumentEditor serves the screens: radars,
values proposed by party and item, totals preview without saving, linked documents
and open documents to fulfil. The copy service can merge several documents of one
party, the base of deferred invoicing.

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

258 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Khaemhat.Application.Tables;
using Khaemhat.Core.Documents;
using Khaemhat.Core.Tax;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Documents;
/// <summary>The VAT of a line, from its tax code.</summary>
/// <param name="TaxCodeId">The tax code.</param>
/// <param name="Rate">The rate in percent.</param>
/// <param name="Nature">The nature of operations without VAT.</param>
/// <param name="Exigibility">When the VAT becomes due.</param>
/// <param name="NonDeductiblePercent">The non-deductible share (purchases).</param>
/// <param name="LegalReference">The law printed for operations without VAT.</param>
public sealed record TotalsTax(
long? TaxCodeId,
decimal Rate,
string? Nature = null,
TaxExigibility Exigibility = TaxExigibility.Immediate,
decimal NonDeductiblePercent = 0m,
string? LegalReference = null);
/// <summary>A line as the calculator sees it.</summary>
/// <param name="Kind">The kind of line.</param>
/// <param name="Quantity">The quantity (expenses and discounts without quantity count as one).</param>
/// <param name="Price">The unit price, with VAT when the document's prices include it.</param>
/// <param name="DiscountFormula">The discounts, such as <c>10+5</c>.</param>
/// <param name="Tax">The VAT; lines without it are left out of the summary.</param>
/// <param name="WithholdingExcluded">The line is out of the withholding and of the social security contribution.</param>
public sealed record TotalsLine(
DocumentLineKind Kind,
decimal Quantity,
decimal Price,
string? DiscountFormula,
TotalsTax? Tax,
bool WithholdingExcluded = false);
/// <summary>The settings of the document that change its totals.</summary>
public sealed record TotalsOptions
{
/// <summary>The prices include VAT: the taxable amount is computed back from each VAT group.</summary>
public bool PricesIncludeTax { get; init; }
/// <summary>The discount on the goods (not on expenses), such as <c>5</c> or <c>10+5</c>.</summary>
public string? FooterDiscount { get; init; }
/// <summary>The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes.</summary>
public TaxExigibility? Exigibility { get; init; }
/// <summary>Split payment: the VAT is paid by the customer to the State.</summary>
public bool SplitPayment { get; init; }
/// <summary>The document can carry the stamp duty (invoices and notes).</summary>
public bool StampDutyApplies { get; init; }
/// <summary>The stamp duty is added to the total.</summary>
public bool StampDutyCharged { get; init; }
/// <summary>The withholding rate, percent.</summary>
public decimal? WithholdingRate { get; init; }
/// <summary>The share of the amount the withholding applies to, percent.</summary>
public decimal WithholdingBasePercent { get; init; } = 100m;
/// <summary>The social security contribution rate, percent.</summary>
public decimal? SocialSecurityRate { get; init; }
/// <summary>The VAT of the contribution; the one of the first taxed line when empty.</summary>
public TotalsTax? SocialSecurityTax { get; init; }
/// <summary>The contribution is part of the withholding base.</summary>
public bool SocialSecurityWithheld { get; init; }
/// <summary>The ENASARCO rate withheld, percent.</summary>
public decimal? EnasarcoRate { get; init; }
}
/// <summary>A line of the computed tax summary.</summary>
/// <param name="Tax">The VAT of the group, with the exigibility of the document.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="TaxAmount">The VAT.</param>
/// <param name="NonDeductibleTax">The non-deductible part of the VAT.</param>
public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax);
/// <summary>The totals of a document.</summary>
/// <param name="LineAmounts">The amount of each line (quantity × price less its discounts), in the order given.</param>
/// <param name="Summary">The tax summary, by rate (highest first).</param>
/// <param name="Expenses">The total of the expense lines.</param>
/// <param name="FooterDiscountAmount">What the footer discount took off.</param>
/// <param name="SocialSecurity">The social security contribution.</param>
/// <param name="Taxable">The taxable amount.</param>
/// <param name="Tax">The VAT.</param>
/// <param name="StampDuty">The stamp duty due (charged or not).</param>
/// <param name="Total">The total of the document.</param>
/// <param name="Withholding">The withholding tax.</param>
/// <param name="Enasarco">The ENASARCO contribution withheld.</param>
/// <param name="SplitPaymentTax">The VAT the customer pays to the State.</param>
/// <param name="Net">The amount to pay.</param>
public sealed record DocumentTotals(
IReadOnlyList<decimal> LineAmounts,
IReadOnlyList<TotalsSummaryLine> Summary,
decimal Expenses,
decimal FooterDiscountAmount,
decimal SocialSecurity,
decimal Taxable,
decimal Tax,
decimal StampDuty,
decimal Total,
decimal Withholding,
decimal Enasarco,
decimal SplitPaymentTax,
decimal Net);
/// <summary>
/// The totals of a document (SPEC §11.3, issue #48): line amount = quantity × price × (1 − d1)(1 − d2)… rounded to the
/// cent; footer discount on the goods; tax summary per VAT code with the tax computed on the total of each group
/// (FatturaPA <c>DatiRiepilogo</c>); social security contribution with its own VAT; stamp duty; withholding, ENASARCO
/// and split payment taken off the amount to pay.
/// </summary>
public static class DocumentTotalsCalculator
{
/// <summary>Computes the totals.</summary>
/// <param name="lines">The lines.</param>
/// <param name="options">The settings of the document.</param>
/// <param name="engine">The country's rounding and stamp duty rules.</param>
/// <returns>The totals.</returns>
public static DocumentTotals Compute(IReadOnlyList<TotalsLine> lines, TotalsOptions options, ITaxEngine engine)
{
ArgumentNullException.ThrowIfNull(lines);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(engine);
var footer = Factor(options.FooterDiscount);
var amounts = new decimal[lines.Count];
var groups = new List<Group>();
decimal beforeFooter = 0m, afterFooter = 0m, expenses = 0m, withholdingBase = 0m;
TotalsTax? firstTax = null;
for (var i = 0; i < lines.Count; i++)
{
var line = lines[i];
if (line.Kind == DocumentLineKind.Description)
{
continue;
}
var quantity = line.Kind is DocumentLineKind.Expense or DocumentLineKind.Discount && line.Quantity == 0m ? 1m : line.Quantity;
var raw = quantity * line.Price * Factor(line.DiscountFormula);
if (line.Kind == DocumentLineKind.Discount)
{
raw = -Math.Abs(raw);
}
amounts[i] = engine.Round(raw);
var net = amounts[i];
if (line.Kind == DocumentLineKind.Expense)
{
expenses += net;
}
else if (footer != 1m)
{
net = engine.Round(raw * footer);
beforeFooter += amounts[i];
afterFooter += net;
}
if (!line.WithholdingExcluded)
{
withholdingBase += net;
}
if (line.Tax is { } tax)
{
firstTax ??= tax.Rate > 0m ? tax : null;
var group = GroupOf(groups, tax);
if (options.PricesIncludeTax)
{
group.Gross += net;
}
else
{
group.Net += net;
}
}
}
var socialSecurity = 0m;
if (options.SocialSecurityRate is > 0m and var rate)
{
socialSecurity = engine.Round(withholdingBase * rate / 100m);
if ((options.SocialSecurityTax ?? firstTax ?? groups.FirstOrDefault()?.Tax) is { } tax)
{
GroupOf(groups, tax).Net += socialSecurity;
}
}
var summary = groups
.Select(g => Summarize(g, options, engine))
.OrderByDescending(s => s.Tax.Rate)
.ThenBy(s => s.Tax.Nature, StringComparer.Ordinal)
.ToList();
var taxable = summary.Sum(s => s.Taxable);
var taxAmount = summary.Sum(s => s.TaxAmount);
var stamp = 0m;
if (options.StampDutyApplies)
{
stamp = engine.AssessStampDuty(summary.Select(s => new TaxSummaryLine(s.Tax.Rate, s.Tax.Nature, s.Tax.Exigibility,
s.Tax.NonDeductiblePercent, s.Taxable, s.TaxAmount, s.NonDeductibleTax))).Amount;
}
var total = taxable + taxAmount + (options.StampDutyCharged ? stamp : 0m);
var withholding = options.WithholdingRate is > 0m and var withholdingRate
? engine.Round((withholdingBase + (options.SocialSecurityWithheld ? socialSecurity : 0m)) * options.WithholdingBasePercent / 100m * withholdingRate / 100m)
: 0m;
var enasarco = options.EnasarcoRate is > 0m and var enasarcoRate ? engine.Round(withholdingBase * enasarcoRate / 100m) : 0m;
var split = summary.Where(s => s.Tax.Exigibility == TaxExigibility.SplitPayment).Sum(s => s.TaxAmount);
return new DocumentTotals(amounts, summary, expenses, beforeFooter - afterFooter, socialSecurity, taxable, taxAmount, stamp, total,
withholding, enasarco, split, total - withholding - enasarco - split);
}
/// <summary>The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1.</summary>
/// <param name="formula">The formula.</param>
/// <returns>The factor.</returns>
public static decimal Factor(string? formula) =>
DiscountFormula.TryParse(formula, out var steps) ? steps.Aggregate(1m, (left, step) => left * (1m - (step / 100m))) : 1m;
private static Group GroupOf(List<Group> groups, TotalsTax tax)
{
var group = groups.Find(g => g.Tax.TaxCodeId == tax.TaxCodeId && g.Tax.Rate == tax.Rate && g.Tax.Nature == tax.Nature);
if (group is null)
{
group = new Group(tax);
groups.Add(group);
}
return group;
}
private static TotalsSummaryLine Summarize(Group group, TotalsOptions options, ITaxEngine engine)
{
var tax = group.Tax;
var exigibility = tax.Rate == 0m ? tax.Exigibility
: options.SplitPayment ? TaxExigibility.SplitPayment
: options.Exigibility ?? tax.Exigibility;
var grossTaxable = group.Gross == 0m ? 0m : engine.Round(group.Gross * 100m / (100m + tax.Rate));
var taxable = grossTaxable + group.Net;
var amount = group.Gross - grossTaxable + engine.ComputeTax(group.Net, tax.Rate);
return new TotalsSummaryLine(tax with { Exigibility = exigibility }, taxable, amount, engine.Round(amount * tax.NonDeductiblePercent / 100m));
}
private sealed class Group(TotalsTax tax)
{
public TotalsTax Tax { get; } = tax;
public decimal Net { get; set; }
public decimal Gross { get; set; }
}
}