using Khaemhat.Application.Tables; using Khaemhat.Core.Documents; using Khaemhat.Core.Tax; using Khaemhat.Fiscal.Abstractions; namespace Khaemhat.Application.Documents; /// The VAT of a line, from its tax code. /// The tax code. /// The rate in percent. /// The nature of operations without VAT. /// When the VAT becomes due. /// The non-deductible share (purchases). /// The law printed for operations without VAT. public sealed record TotalsTax( long? TaxCodeId, decimal Rate, string? Nature = null, TaxExigibility Exigibility = TaxExigibility.Immediate, decimal NonDeductiblePercent = 0m, string? LegalReference = null); /// A line as the calculator sees it. /// The kind of line. /// The quantity (expenses and discounts without quantity count as one). /// The unit price, with VAT when the document's prices include it. /// The discounts, such as 10+5. /// The VAT; lines without it are left out of the summary. /// The line is out of the withholding and of the social security contribution. public sealed record TotalsLine( DocumentLineKind Kind, decimal Quantity, decimal Price, string? DiscountFormula, TotalsTax? Tax, bool WithholdingExcluded = false); /// The settings of the document that change its totals. public sealed record TotalsOptions { /// The prices include VAT: the taxable amount is computed back from each VAT group. public bool PricesIncludeTax { get; init; } /// The discount on the goods (not on expenses), such as 5 or 10+5. public string? FooterDiscount { get; init; } /// The exigibility of the whole document (cash basis, deferred), when not the one of the tax codes. public TaxExigibility? Exigibility { get; init; } /// Split payment: the VAT is paid by the customer to the State. public bool SplitPayment { get; init; } /// The document can carry the stamp duty (invoices and notes). public bool StampDutyApplies { get; init; } /// The stamp duty is added to the total. public bool StampDutyCharged { get; init; } /// The withholding rate, percent. public decimal? WithholdingRate { get; init; } /// The share of the amount the withholding applies to, percent. public decimal WithholdingBasePercent { get; init; } = 100m; /// The social security contribution rate, percent. public decimal? SocialSecurityRate { get; init; } /// The VAT of the contribution; the one of the first taxed line when empty. public TotalsTax? SocialSecurityTax { get; init; } /// The contribution is part of the withholding base. public bool SocialSecurityWithheld { get; init; } /// The ENASARCO rate withheld, percent. public decimal? EnasarcoRate { get; init; } } /// A line of the computed tax summary. /// The VAT of the group, with the exigibility of the document. /// The taxable amount. /// The VAT. /// The non-deductible part of the VAT. public sealed record TotalsSummaryLine(TotalsTax Tax, decimal Taxable, decimal TaxAmount, decimal NonDeductibleTax); /// The totals of a document. /// The amount of each line (quantity × price less its discounts), in the order given. /// The tax summary, by rate (highest first). /// The total of the expense lines. /// What the footer discount took off. /// The social security contribution. /// The taxable amount. /// The VAT. /// The stamp duty due (charged or not). /// The total of the document. /// The withholding tax. /// The ENASARCO contribution withheld. /// The VAT the customer pays to the State. /// The amount to pay. public sealed record DocumentTotals( IReadOnlyList LineAmounts, IReadOnlyList Summary, decimal Expenses, decimal FooterDiscountAmount, decimal SocialSecurity, decimal Taxable, decimal Tax, decimal StampDuty, decimal Total, decimal Withholding, decimal Enasarco, decimal SplitPaymentTax, decimal Net); /// /// 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 DatiRiepilogo); social security contribution with its own VAT; stamp duty; withholding, ENASARCO /// and split payment taken off the amount to pay. /// public static class DocumentTotalsCalculator { /// Computes the totals. /// The lines. /// The settings of the document. /// The country's rounding and stamp duty rules. /// The totals. public static DocumentTotals Compute(IReadOnlyList 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(); 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); } /// The factor of a discount formula: 10+5 is 0.855; an empty or invalid formula is 1. /// The formula. /// The factor. 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 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; } } }