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>
202 lines
10 KiB
C#
202 lines
10 KiB
C#
using Khaemhat.Core.Documents;
|
|
using Khaemhat.Core.Parties;
|
|
using Khaemhat.Core.Tables;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Querying;
|
|
using Khaemhat.Fiscal.Abstractions;
|
|
|
|
namespace Khaemhat.Application.Documents;
|
|
|
|
/// <summary>The totals of a stored document: its tax summary and installments, as written by the last save.</summary>
|
|
/// <param name="Summary">The tax summary.</param>
|
|
/// <param name="Installments">The installments.</param>
|
|
public sealed record DocumentFigures(IReadOnlyList<DocumentTaxSummary> Summary, IReadOnlyList<DocumentInstallment> Installments)
|
|
{
|
|
/// <summary>No figures.</summary>
|
|
public static DocumentFigures Empty { get; } = new([], []);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Applies <see cref="DocumentTotalsCalculator"/> and <see cref="InstallmentGenerator"/> to a document being saved:
|
|
/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48).
|
|
/// </summary>
|
|
internal static class DocumentCalculation
|
|
{
|
|
/// <summary>Computes the totals of a document in place.</summary>
|
|
/// <param name="uow">The unit of work.</param>
|
|
/// <param name="engine">The country's tax engine.</param>
|
|
/// <param name="behavior">The behaviour of the document.</param>
|
|
/// <param name="record">The document.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The tax summary and installments to write once the document has its id.</returns>
|
|
public static async Task<DocumentFigures> ApplyAsync(IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, CancellationToken cancellationToken)
|
|
{
|
|
var header = record.Header;
|
|
var taxCodes = await TaxCodesAsync(uow, record, cancellationToken).ConfigureAwait(false);
|
|
var options = new TotalsOptions
|
|
{
|
|
PricesIncludeTax = header.PricesIncludeTax,
|
|
FooterDiscount = header.FooterDiscount,
|
|
Exigibility = header.Exigibility,
|
|
SplitPayment = header.SplitPayment,
|
|
StampDutyApplies = behavior.Direction == DocumentDirection.Sale && behavior.Has(DocumentEffects.EInvoice),
|
|
StampDutyCharged = header.StampDutyCharged,
|
|
WithholdingRate = header.WithholdingRate,
|
|
WithholdingBasePercent = header.WithholdingBasePercent <= 0m ? 100m : header.WithholdingBasePercent,
|
|
SocialSecurityRate = header.SocialSecurityRate,
|
|
SocialSecurityTax = header.SocialSecurityTaxCodeId is { } id && taxCodes.TryGetValue(id, out var own) ? own : null,
|
|
SocialSecurityWithheld = header.SocialSecurityWithheld,
|
|
EnasarcoRate = header.EnasarcoRate,
|
|
};
|
|
var lines = record.Lines
|
|
.Select(l => new TotalsLine(l.Kind, l.Quantity, l.Price, l.DiscountFormula,
|
|
l.TaxCodeId is { } t && taxCodes.TryGetValue(t, out var tax) ? tax : null, l.WithholdingExcluded))
|
|
.ToList();
|
|
var totals = DocumentTotalsCalculator.Compute(lines, options, engine);
|
|
for (var i = 0; i < record.Lines.Count; i++)
|
|
{
|
|
record.Lines[i].TaxableAmount = totals.LineAmounts[i];
|
|
}
|
|
|
|
header.TaxableAmount = totals.Taxable;
|
|
header.TaxAmount = totals.Tax;
|
|
header.TotalAmount = totals.Total;
|
|
header.ExpensesAmount = totals.Expenses;
|
|
header.FooterDiscountAmount = totals.FooterDiscountAmount;
|
|
header.StampDuty = totals.StampDuty;
|
|
header.WithholdingAmount = totals.Withholding;
|
|
header.SocialSecurityAmount = totals.SocialSecurity;
|
|
header.EnasarcoAmount = totals.Enasarco;
|
|
header.NetAmount = totals.Net;
|
|
|
|
var summary = totals.Summary.Select(s => new DocumentTaxSummary
|
|
{
|
|
Family = record.Family,
|
|
TaxCodeId = s.Tax.TaxCodeId,
|
|
Rate = s.Tax.Rate,
|
|
Nature = s.Tax.Nature,
|
|
Exigibility = s.Tax.Exigibility,
|
|
NonDeductiblePercent = s.Tax.NonDeductiblePercent,
|
|
LegalReference = s.Tax.LegalReference,
|
|
Taxable = s.Taxable,
|
|
Tax = s.TaxAmount,
|
|
NonDeductibleTax = s.NonDeductibleTax,
|
|
}).ToList();
|
|
|
|
var installments = new List<DocumentInstallment>();
|
|
if (behavior.Has(DocumentEffects.Installments) || behavior.Kind is DocumentKind.ProForma or DocumentKind.SalesOrder or DocumentKind.Quotation)
|
|
{
|
|
installments = await InstallmentsAsync(uow, engine, behavior, record, totals, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
return new DocumentFigures(summary, installments);
|
|
}
|
|
|
|
/// <summary>Replaces the tax summary and installments of a document.</summary>
|
|
/// <param name="uow">The unit of work.</param>
|
|
/// <param name="family">The family.</param>
|
|
/// <param name="documentId">The document.</param>
|
|
/// <param name="figures">The new rows.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>A task.</returns>
|
|
public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken)
|
|
{
|
|
var summaries = uow.Repository<DocumentTaxSummary, long>();
|
|
var installments = uow.Repository<DocumentInstallment, long>();
|
|
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
|
|
foreach (var old in (await summaries.ListAsync(Query.For<DocumentTaxSummary>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
|
|
{
|
|
await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
foreach (var old in (await installments.ListAsync(Query.For<DocumentInstallment>().Where(where), cancellationToken).ConfigureAwait(false)).Items)
|
|
{
|
|
await installments.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
foreach (var row in figures.Summary)
|
|
{
|
|
row.Id = 0;
|
|
row.Family = family;
|
|
row.DocumentId = documentId;
|
|
await summaries.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
foreach (var row in figures.Installments)
|
|
{
|
|
row.Id = 0;
|
|
row.Family = family;
|
|
row.DocumentId = documentId;
|
|
await installments.InsertAsync(row, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
/// <summary>Reads the tax summary and installments of a document.</summary>
|
|
/// <param name="uow">The unit of work.</param>
|
|
/// <param name="family">The family.</param>
|
|
/// <param name="documentId">The document.</param>
|
|
/// <param name="cancellationToken">Cancellation.</param>
|
|
/// <returns>The rows.</returns>
|
|
public static async Task<DocumentFigures> ReadAsync(IUnitOfWork uow, DocumentFamily family, long documentId, CancellationToken cancellationToken)
|
|
{
|
|
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
|
|
var summary = await uow.Repository<DocumentTaxSummary, long>()
|
|
.ListAsync(Query.For<DocumentTaxSummary>().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false);
|
|
var installments = await uow.Repository<DocumentInstallment, long>()
|
|
.ListAsync(Query.For<DocumentInstallment>().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false);
|
|
return new DocumentFigures(summary.Items, installments.Items);
|
|
}
|
|
|
|
private static async Task<Dictionary<long, TotalsTax>> TaxCodesAsync(IUnitOfWork uow, DocumentRecord record, CancellationToken cancellationToken)
|
|
{
|
|
var ids = record.Lines.Where(l => l.TaxCodeId is not null).Select(l => l.TaxCodeId!.Value).ToHashSet();
|
|
if (record.Header.SocialSecurityTaxCodeId is { } own)
|
|
{
|
|
ids.Add(own);
|
|
}
|
|
|
|
if (ids.Count == 0)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var list = ids.ToList();
|
|
var codes = await uow.Repository<TaxCode, long>().ListAsync(Query.For<TaxCode>().Where(c => list.Contains(c.Id)), cancellationToken).ConfigureAwait(false);
|
|
return codes.Items.ToDictionary(c => c.Id, c => new TotalsTax(c.Id, c.Rate, string.IsNullOrWhiteSpace(c.Nature) ? null : c.Nature,
|
|
c.Exigibility, c.NonDeductiblePercent, c.LegalReference));
|
|
}
|
|
|
|
private static async Task<List<DocumentInstallment>> InstallmentsAsync(
|
|
IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken)
|
|
{
|
|
var header = record.Header;
|
|
PaymentTerm? term = null;
|
|
IReadOnlyList<PaymentTermLine> termLines = [];
|
|
if (header.PaymentTermId is { } termId)
|
|
{
|
|
term = await uow.Repository<PaymentTerm, long>().GetAsync(termId, cancellationToken).ConfigureAwait(false);
|
|
termLines = (await uow.Repository<PaymentTermLine, long>()
|
|
.ListAsync(Query.For<PaymentTermLine>().Where(l => l.PaymentTermId == termId).OrderBy(l => l.Number), cancellationToken).ConfigureAwait(false)).Items;
|
|
}
|
|
|
|
ExcludedMonths? excluded = null;
|
|
if (behavior.Direction == DocumentDirection.Sale && header.PartyId is { } partyId)
|
|
{
|
|
var terms = await uow.Repository<PartySalesTerms, long>()
|
|
.FindAsync(Query.For<PartySalesTerms>().Where(t => t.PartyId == partyId), cancellationToken).ConfigureAwait(false);
|
|
if (terms is { } t && (t.ExcludedMonth1 is not null || t.ExcludedMonth2 is not null))
|
|
{
|
|
excluded = new ExcludedMonths(t.ExcludedMonth1, t.ExcludedMonth2, t.ExcludedMonthsDay ?? 10);
|
|
}
|
|
}
|
|
|
|
var paidTax = totals.Tax - totals.SplitPaymentTax;
|
|
var dues = InstallmentGenerator.Generate(
|
|
header.DocumentDate, totals.Net, paidTax,
|
|
[.. termLines.Select(l => new InstallmentRule(l.Days, l.EndOfMonth, l.FixedDay, l.Percent))],
|
|
term?.VatOnFirstInstallment ?? false, excluded, engine.Round);
|
|
var method = header.PaymentMethodId ?? term?.PaymentMethodId;
|
|
return [.. dues.Select(d => new DocumentInstallment { Number = d.Number, DueDate = d.DueDate, Amount = d.Amount, PaymentMethodId = method })];
|
|
}
|
|
}
|