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;
/// The totals of a stored document: its tax summary and installments, as written by the last save.
/// The tax summary.
/// The installments.
public sealed record DocumentFigures(IReadOnlyList Summary, IReadOnlyList Installments)
{
/// No figures.
public static DocumentFigures Empty { get; } = new([], []);
}
///
/// Applies and to a document being saved:
/// writes the line amounts and header totals, then replaces its tax summary and installments (issue #48).
///
internal static class DocumentCalculation
{
/// Computes the totals of a document in place.
/// The unit of work.
/// The country's tax engine.
/// The behaviour of the document.
/// The document.
/// Cancellation.
/// The tax summary and installments to write once the document has its id.
public static async Task 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();
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);
}
/// Replaces the tax summary and installments of a document.
/// The unit of work.
/// The family.
/// The document.
/// The new rows.
/// Cancellation.
/// A task.
public static async Task WriteAsync(IUnitOfWork uow, DocumentFamily family, long documentId, DocumentFigures figures, CancellationToken cancellationToken)
{
var summaries = uow.Repository();
var installments = uow.Repository();
var where = SqlFragment.Of($"family = {family.ToString()} AND document_id = {documentId}");
foreach (var old in (await summaries.ListAsync(Query.For().Where(where), cancellationToken).ConfigureAwait(false)).Items)
{
await summaries.DeleteAsync(old.Id, cancellationToken).ConfigureAwait(false);
}
foreach (var old in (await installments.ListAsync(Query.For().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);
}
}
/// Reads the tax summary and installments of a document.
/// The unit of work.
/// The family.
/// The document.
/// Cancellation.
/// The rows.
public static async Task 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()
.ListAsync(Query.For().Where(where).OrderByDescending(s => s.Rate), cancellationToken).ConfigureAwait(false);
var installments = await uow.Repository()
.ListAsync(Query.For().Where(where).OrderBy(s => s.Number), cancellationToken).ConfigureAwait(false);
return new DocumentFigures(summary.Items, installments.Items);
}
private static async Task> 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().ListAsync(Query.For().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> InstallmentsAsync(
IUnitOfWork uow, ITaxEngine engine, DocumentBehavior behavior, DocumentRecord record, DocumentTotals totals, CancellationToken cancellationToken)
{
var header = record.Header;
PaymentTerm? term = null;
IReadOnlyList termLines = [];
if (header.PaymentTermId is { } termId)
{
term = await uow.Repository().GetAsync(termId, cancellationToken).ConfigureAwait(false);
termLines = (await uow.Repository()
.ListAsync(Query.For().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()
.FindAsync(Query.For().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 })];
}
}