feat: schedule and payments services; posting keeps settled open items (#69)

The schedule lists the open items with aging, disputes and statement of
account; a collection or payment settles items with allowances, exchange
differences and fees, writes its INC/PAG entry and makes the withholding of a
fully paid invoice due. Reposting a document now updates its items by
installment and refuses to drop what was already collected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-13 08:53:21 +01:00
1 parent 5fbbe4d3a4
commit 562bf98092
17 files changed
+1243 -89

No files matched your search

@@ -502,7 +502,10 @@ public sealed class JournalEntryService
cancellationToken).ConfigureAwait(false);
entry.ReversedById = reversal.Id;
await uow.Repository<GlEntry, long>().UpdateAsync(entry, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0"), cancellationToken).ConfigureAwait(false);
// Items the treasury touched stay: a new posting of the document takes them over (ADR 0038).
await uow.ExecuteAsync(
SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entry.Id} AND paid_amount = 0 AND remittance_id IS NULL AND unpaid_count = 0 AND NOT EXISTS (SELECT 1 FROM remittance_lines r WHERE r.open_item_id = gl_open_items.id) AND NOT EXISTS (SELECT 1 FROM payment_lines p WHERE p.open_item_id = gl_open_items.id)"),
cancellationToken).ConfigureAwait(false);
return reversal;
}
+62 -17
View File
@@ -108,7 +108,6 @@ public sealed class LedgerPoster
{
Copy(entry, existing);
await LedgerStore.UpdateAsync(uow, existing, lines, vat, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {existing.Id}"), cancellationToken).ConfigureAwait(false);
result = existing;
}
else if (await SameAsync(uow, existing, lines, cancellationToken).ConfigureAwait(false))
@@ -150,6 +149,7 @@ public sealed class LedgerPoster
return;
}
await LedgerStore.EnsureUnpaidAsync(uow, existing.Id, cancellationToken).ConfigureAwait(false);
if (existing.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, existing, existing.EntryDate, null, cancellationToken).ConfigureAwait(false);
@@ -385,25 +385,70 @@ public sealed class LedgerPoster
var rows = installments.Count > 0
? installments.Select(i => (i.Number, i.DueDate, i.Amount, i.PaymentMethodId)).ToList()
: [(1, header.DocumentDate, header.NetAmount != 0m ? header.NetAmount : header.TotalAmount, header.PaymentMethodId)];
// The items keep their identity by installment (ADR 0038): collections, payments and remittances point at them,
// so a new posting of the document changes them in place and never takes away what was already collected.
var repository = uow.Repository<OpenItem, long>();
foreach (var (number, due, amount, method) in rows)
var current = (await repository.ListAsync(
Query.For<OpenItem>().Where(o => o.SourceFamily == family && o.SourceDocumentId == header.Id), cancellationToken).ConfigureAwait(false)).Items
.Where(o => o.ParentId is null).ToList();
var direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable;
foreach (var (number, due, value, method) in rows)
{
await repository.InsertAsync(new OpenItem
var amount = sign * value;
var item = current.FirstOrDefault(o => o.Installment == number);
if (item is null)
{
Direction = posting.Kind == PostingKind.Sale ? OpenItemDirection.Receivable : OpenItemDirection.Payable,
PartyId = partyId,
AccountId = accountId,
EntryId = entry.Id,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
Installment = number,
DueDate = due,
Amount = sign * amount,
PaymentMethodId = method,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
await repository.InsertAsync(new OpenItem
{
Direction = direction,
PartyId = partyId,
AccountId = accountId,
EntryId = entry.Id,
SourceFamily = family,
SourceDocumentId = header.Id,
DocumentNumber = entry.DocumentNumber,
DocumentDate = entry.DocumentDate ?? header.DocumentDate,
Installment = number,
DueDate = due,
Amount = amount,
PaymentMethodId = method,
IsDemo = header.IsDemo,
}, cancellationToken).ConfigureAwait(false);
continue;
}
current.Remove(item);
if (item.PaidAmount != 0m && (Math.Sign(amount) != Math.Sign(item.PaidAmount) || Math.Abs(amount) < Math.Abs(item.PaidAmount)))
{
throw new ValidationFailedException(["Amount:" + LedgerErrors.OpenItemPaid]);
}
item.Direction = direction;
item.PartyId = partyId;
item.AccountId = accountId;
item.EntryId = entry.Id;
item.DocumentNumber = entry.DocumentNumber;
item.DocumentDate = entry.DocumentDate ?? header.DocumentDate;
item.Amount = amount;
if (item.RemittanceId is null)
{
item.DueDate = due;
item.PaymentMethodId = method;
}
item.Status = Core.Treasury.OpenItemStates.Of(item);
item.Closed = item.Status == Core.Treasury.OpenItemStatus.Closed;
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
}
foreach (var left in current)
{
if (left.PaidAmount != 0m || left.RemittanceId is not null || left.UnpaidCount > 0)
{
throw new ValidationFailedException(["Installments:" + LedgerErrors.OpenItemPaid]);
}
await repository.DeleteAsync(left.Id, cancellationToken).ConfigureAwait(false);
}
}
@@ -115,12 +115,25 @@ internal static class LedgerStore
/// <summary>Removes an entry with its lines, VAT lines and open items.</summary>
public static async Task DeleteAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
await EnsureUnpaidAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
await RemoveLinesAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"DELETE FROM gl_open_items WHERE entry_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.ExecuteAsync(SqlFragment.Of($"UPDATE gl_entries SET reversed_by_id = NULL WHERE reversed_by_id = {entryId}"), cancellationToken).ConfigureAwait(false);
await uow.Repository<GlEntry, long>().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false);
}
/// <summary>Refuses when an open item of the entry was collected, paid or put in a remittance (ADR 0038).</summary>
public static async Task EnsureUnpaidAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken)
{
var touched = await uow.QuerySingleAsync<long?>(
SqlFragment.Of($"SELECT COUNT(*) FROM gl_open_items o WHERE o.entry_id = {entryId} AND (o.paid_amount <> 0 OR o.remittance_id IS NOT NULL OR o.unpaid_count > 0 OR EXISTS (SELECT 1 FROM payment_lines p WHERE p.open_item_id = o.id) OR EXISTS (SELECT 1 FROM remittance_lines r WHERE r.open_item_id = o.id))"),
cancellationToken).ConfigureAwait(false) ?? 0L;
if (touched > 0)
{
throw new Security.ValidationFailedException(["Status:" + LedgerErrors.OpenItemPaid]);
}
}
/// <summary>The lines of an entry, in order.</summary>
public static async Task<IReadOnlyList<GlEntryLine>> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) =>
(await uow.Repository<GlEntryLine, long>().ListAsync(Query.For<GlEntryLine>().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken)
+86 -70
View File
@@ -425,47 +425,7 @@ public sealed class TaxService
}
var before = Copy(withholding);
var operated = withholding.Direction == WithholdingDirection.Operated;
var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false);
withholding.InvoicePaidOn = paidOn;
withholding.GlEntryId = entry?.Id;
if (operated)
{
withholding.Status = WithholdingStatus.Due;
withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules);
var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month);
var code = withholding.PaymentCode;
var payments = uow.Repository<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
await ApplyInvoicePaidAsync(uow, withholding, paidOn, settlementRules, withholdingRules, cancellationToken).ConfigureAwait(false);
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -491,35 +451,7 @@ public sealed class TaxService
}
var before = Copy(withholding);
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
withholding.InvoicePaidOn = null;
withholding.GlEntryId = null;
withholding.TaxPaymentId = null;
withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered;
await UndoInvoicePaidAsync(uow, withholding, Today(), actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, withholding.Id, before, withholding, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
@@ -751,6 +683,90 @@ public sealed class TaxService
// The entry of a withholding when its invoice is paid: operated, supplier debit / withholdings payable credit;
// suffered, withholdings credit debit / customer credit. The party keeps its own account when it has one.
/// <summary>Takes back the payment of the invoice of a withholding: its F24 share and its entry. The caller writes the withholding.</summary>
internal static async Task UndoInvoicePaidAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (withholding.TaxPaymentId is { } paymentId && await uow.Repository<TaxPayment, long>().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment)
{
payment.Amount -= withholding.Amount;
if (payment.Amount == 0m)
{
await uow.Repository<TaxPayment, long>().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false);
}
else
{
await uow.Repository<TaxPayment, long>().UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
}
if (withholding.GlEntryId is { } entryId && await uow.Repository<GlEntry, long>().GetAsync(entryId, cancellationToken).ConfigureAwait(false) is { } entry)
{
if (entry.Status == GlEntryStatus.Final)
{
await JournalEntryService.ReverseAsync(uow, entry, date, userName, cancellationToken).ConfigureAwait(false);
}
else
{
await LedgerStore.DeleteAsync(uow, entryId, cancellationToken).ConfigureAwait(false);
}
}
withholding.InvoicePaidOn = null;
withholding.GlEntryId = null;
withholding.TaxPaymentId = null;
withholding.Status = withholding.Direction == WithholdingDirection.Operated ? WithholdingStatus.Waiting : WithholdingStatus.Suffered;
}
/// <summary>
/// Makes a withholding due because its invoice was paid: the entry of the withholding and the F24 line of the month
/// (used also by the payments of the schedule, ADR 0038). The caller writes the withholding and the history.
/// </summary>
internal static async Task ApplyInvoicePaidAsync(
IUnitOfWork uow, Withholding withholding, DateOnly paidOn, IVatSettlementRules settlementRules, IWithholdingRules? withholdingRules, CancellationToken cancellationToken)
{
var operated = withholding.Direction == WithholdingDirection.Operated;
var entry = await PostWithholdingAsync(uow, withholding, paidOn, operated ? "RIT" : "RITS", cancellationToken).ConfigureAwait(false);
withholding.InvoicePaidOn = paidOn;
withholding.GlEntryId = entry?.Id;
if (operated)
{
withholding.Status = WithholdingStatus.Due;
withholding.PaymentCode ??= PaymentCodeOf(withholding, withholdingRules);
var due = settlementRules.WithholdingDue(paidOn.Year, paidOn.Month);
var code = withholding.PaymentCode;
var payments = uow.Repository<TaxPayment, long>();
var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture);
var year = paidOn.Year;
var payment = await payments.FindAsync(
Query.For<TaxPayment>().Where(t => t.Source == TaxPaymentSource.Withholding && t.PaymentCode == code && t.ReferenceYear == year
&& t.ReferencePeriod == period && t.PaidOn == null),
cancellationToken).ConfigureAwait(false);
if (payment is null)
{
payment = new TaxPayment
{
DueDate = due,
PaymentCode = code,
ReferenceYear = year,
ReferencePeriod = period,
Description = LedgerStore.Trim("Ritenute d'acconto " + paidOn.ToString("MMMM yyyy", CultureInfo.GetCultureInfo("it-IT")), 200)!,
Amount = withholding.Amount,
Source = TaxPaymentSource.Withholding,
IsDemo = withholding.IsDemo,
};
payment.Id = await payments.InsertAsync(payment, cancellationToken).ConfigureAwait(false);
}
else
{
payment.Amount += withholding.Amount;
await payments.UpdateAsync(payment, cancellationToken).ConfigureAwait(false);
}
withholding.TaxPaymentId = payment.Id;
}
}
private static async Task<GlEntry?> PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken)
{
if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found)
@@ -0,0 +1,424 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Treasury;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Treasury;
/// <summary>A line of a collection or payment being recorded.</summary>
/// <param name="OpenItemId">The item.</param>
/// <param name="Amount">The money for the item.</param>
/// <param name="Allowance">The allowance (abbuono) that closes it.</param>
/// <param name="ExchangeDifference">The exchange difference.</param>
public sealed record PaymentLineInput(long OpenItemId, decimal Amount, decimal Allowance = 0m, decimal ExchangeDifference = 0m);
/// <summary>A collection or payment being recorded (mockup 054).</summary>
/// <param name="Direction">Collection or payment.</param>
/// <param name="PartyId">The customer or supplier.</param>
/// <param name="Date">The day of the money.</param>
/// <param name="PaymentMethodId">The method.</param>
/// <param name="BankAccountId">The bank of the company; none with a cash method means the cash.</param>
/// <param name="Fees">The bank fees.</param>
/// <param name="Reference">The reference (CRO, cheque number).</param>
/// <param name="Notes">Notes.</param>
/// <param name="Lines">The items settled.</param>
public sealed record PaymentInput(
PaymentDirection Direction, long PartyId, DateOnly Date, long? PaymentMethodId, long? BankAccountId, decimal Fees, string? Reference, string? Notes,
IReadOnlyList<PaymentLineInput> Lines);
/// <summary>A collection or payment with what the grid shows.</summary>
/// <param name="Payment">The payment.</param>
/// <param name="PartyName">The party.</param>
/// <param name="Bank">The bank (code).</param>
/// <param name="EntryNumber">The number of its entry.</param>
/// <param name="Documents">The documents it settled.</param>
public sealed record PaymentRow(Payment Payment, string PartyName, string? Bank, string? EntryNumber, string Documents);
/// <summary>
/// Collections and payments (SPEC §11.8, mockup 054, ADR 0038): one payment settles one or more items of a party with
/// money, allowances and exchange differences; the entry is written at once (INC or PAG); the withholding of an
/// invoice becomes due when the invoice is fully paid; cancelling takes everything back.
/// </summary>
public sealed class PaymentService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public PaymentService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_audit = audit;
_clock = clock;
}
/// <summary>The collections or payments of a period.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="direction">Collections or payments.</param>
/// <param name="from">From this day.</param>
/// <param name="to">Up to this day.</param>
/// <param name="partyId">One party.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, latest first.</returns>
public async Task<IReadOnlyList<PaymentRow>> ListAsync(
Actor actor, string companyCode, PaymentDirection direction, DateOnly from, DateOnly to, long? partyId = null, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var query = Query.For<Payment>().Where(p => p.Direction == direction && p.PaymentDate >= from && p.PaymentDate <= to);
if (partyId is { } party)
{
query = query.Where(p => p.PartyId == party);
}
var payments = (await uow.Repository<Payment, long>().ListAsync(query.OrderByDescending(p => p.PaymentDate).OrderByDescending(p => p.Id), cancellationToken).ConfigureAwait(false)).Items;
return await RowsAsync(uow, payments, cancellationToken).ConfigureAwait(false);
}
/// <summary>A payment with its lines and their items.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment, its lines and the items, or <see langword="null"/>.</returns>
public async Task<(PaymentRow Row, IReadOnlyList<(PaymentLine Line, OpenItem? Item)> Lines)?> GetAsync(
Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<Payment, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } payment)
{
return null;
}
var lines = await LinesAsync(uow, id, cancellationToken).ConfigureAwait(false);
var itemIds = lines.Select(l => l.OpenItemId).ToList();
var items = (await uow.Repository<OpenItem, long>().ListAsync(Query.For<OpenItem>().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id);
var row = (await RowsAsync(uow, [payment], cancellationToken).ConfigureAwait(false))[0];
return (row, [.. lines.Select(l => (l, items.GetValueOrDefault(l.OpenItemId)))]);
}
/// <summary>Records a collection or payment and its entry.</summary>
/// <param name="actor">Who records it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="input">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The payment.</returns>
public async Task<Payment> RegisterAsync(Actor actor, string companyCode, PaymentInput input, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(input);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false);
var pack = await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payment = await RegisterAsync(uow, pack, input, PaymentOrigin.Manual, null, null, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<Payment>(uow, AuditAction.Insert, payment.Id, null, payment, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>Cancels a collection or payment: its entry is deleted (or reversed when final) and its items reopen.</summary>
/// <param name="actor">Who cancels it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The payment.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public async Task CancelAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.PaymentWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var payment = await uow.Repository<Payment, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
if (payment.Origin == PaymentOrigin.Remittance)
{
throw new ValidationFailedException(["Id:" + TreasuryErrors.FromRemittance]);
}
await CancelAsync(uow, payment, TreasuryStore.Today(_clock), actor.UserName, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync<Payment>(uow, AuditAction.Delete, payment.Id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>Records a payment inside a transaction (manual, remittances, bank statements).</summary>
internal static async Task<Payment> RegisterAsync(
IUnitOfWork uow, IFiscalPack pack, PaymentInput input, PaymentOrigin origin, long? remittanceId, long? statementLineId, CancellationToken cancellationToken)
{
var errors = new List<string>();
if (input.PartyId <= 0)
{
errors.Add("PartyId:" + TreasuryErrors.PartyRequired);
}
var lines = input.Lines.Where(l => l.Amount != 0m || l.Allowance != 0m || l.ExchangeDifference != 0m).ToList();
if (lines.Count == 0)
{
errors.Add("Lines:" + TreasuryErrors.ItemsRequired);
}
if (input.Fees < 0m)
{
errors.Add("Fees:" + TreasuryErrors.AmountRequired);
}
if (errors.Count > 0)
{
throw new ValidationFailedException(errors);
}
var itemRepository = uow.Repository<OpenItem, long>();
var direction = input.Direction == PaymentDirection.Receipt ? OpenItemDirection.Receivable : OpenItemDirection.Payable;
var items = new List<(PaymentLineInput Line, OpenItem Item)>();
foreach (var line in lines)
{
var item = await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) ?? throw new ValidationFailedException(["Lines:" + TreasuryErrors.NotFound]);
if (item.PartyId != input.PartyId || item.Direction != direction)
{
throw new ValidationFailedException(["Lines:" + TreasuryErrors.ItemParty]);
}
if (item.Status == OpenItemStatus.InRemittance && origin != PaymentOrigin.Remittance)
{
throw new ValidationFailedException(["Lines:" + TreasuryErrors.InRemittance]);
}
var settled = line.Amount + line.Allowance + line.ExchangeDifference;
var residual = item.Residual;
if (settled == 0m || Math.Sign(settled) != Math.Sign(residual) || Math.Abs(settled) > Math.Abs(residual))
{
throw new ValidationFailedException(["Lines:" + TreasuryErrors.OverSettled]);
}
items.Add((line, item));
}
var bank = await TreasuryStore.BankAsync(uow, input.BankAccountId, cancellationToken).ConfigureAwait(false);
var method = input.PaymentMethodId is { } methodId ? await uow.Repository<PaymentMethod, long>().GetAsync(methodId, cancellationToken).ConfigureAwait(false) : null;
var cash = input.BankAccountId is null && method is { NeedsBank: false };
var templateCode = input.Direction == PaymentDirection.Receipt ? "INC" : "PAG";
var template = await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false);
var ledger = pack.GetFeature<ILedgerTemplate>();
var templateLines = template?.Lines;
var money = await TreasuryStore.MoneyAccountAsync(uow, cash ? null : bank, cash, templateLines, ledger, cancellationToken).ConfigureAwait(false);
var accounts = new PaymentPostingAccounts(
money,
await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.Rounding, ledger, cancellationToken).ConfigureAwait(false),
await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.AllowanceIncome, ledger, cancellationToken).ConfigureAwait(false),
await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.ExchangeLoss, ledger, cancellationToken).ConfigureAwait(false),
await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.ExchangeGain, ledger, cancellationToken).ConfigureAwait(false),
await TreasuryStore.RoleAccountAsync(uow, templateLines, PostingRole.BankCharges, ledger, cancellationToken).ConfigureAwait(false));
var party = (await TreasuryStore.PartiesAsync(uow, [input.PartyId], cancellationToken).ConfigureAwait(false)).GetValueOrDefault(input.PartyId);
var receipt = input.Direction == PaymentDirection.Receipt;
var description = (receipt ? "Incasso " : "Pagamento ") + (party?.Name ?? string.Empty)
+ (items.Count == 1 && items[0].Item.DocumentNumber is { } number ? " doc. " + number : string.Empty);
IReadOnlyList<PaymentPostedLine> posted;
try
{
posted = PaymentPosting.Build(
input.Direction,
accounts,
[.. items.Select(i => new PaymentPostingLine(i.Item.AccountId, i.Item.PartyId, i.Item.Id, TreasuryStore.ItemText(i.Item), i.Line.Amount, i.Line.Allowance, i.Line.ExchangeDifference))],
input.Fees,
description);
}
catch (PaymentAccountMissingException)
{
throw new ValidationFailedException(["Lines:" + TreasuryErrors.AccountMissing]);
}
var demo = items.All(i => i.Item.IsDemo);
var entry = await TreasuryStore.PostAsync(uow, templateCode, input.Date, description, input.PartyId, posted, demo, cancellationToken).ConfigureAwait(false);
var payment = new Payment
{
Direction = input.Direction,
PartyId = input.PartyId,
PaymentDate = input.Date,
PaymentMethodId = input.PaymentMethodId,
BankAccountId = cash ? null : bank?.Id,
AccountId = money,
Amount = items.Sum(i => i.Line.Amount),
AllowanceAmount = items.Sum(i => i.Line.Allowance),
ExchangeDifference = items.Sum(i => i.Line.ExchangeDifference),
Fees = input.Fees,
Reference = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Reference) ? null : input.Reference.Trim(), 60),
TemplateCode = templateCode,
Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(input.Notes) ? null : input.Notes.Trim(), 500),
Origin = origin,
RemittanceId = remittanceId,
StatementLineId = statementLineId,
GlEntryId = entry.Id,
IsDemo = demo,
};
payment.Id = await uow.Repository<Payment, long>().InsertAsync(payment, cancellationToken).ConfigureAwait(false);
var lineRepository = uow.Repository<PaymentLine, long>();
foreach (var (line, item) in items)
{
await lineRepository.InsertAsync(new PaymentLine
{
PaymentId = payment.Id,
OpenItemId = item.Id,
Amount = line.Amount,
Allowance = line.Allowance,
ExchangeDifference = line.ExchangeDifference,
}, cancellationToken).ConfigureAwait(false);
TreasuryStore.Settle(item, line.Amount + line.Allowance + line.ExchangeDifference);
await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
}
await WithholdingsAsync(uow, pack, items.Select(i => i.Item), input.Date, cancellationToken).ConfigureAwait(false);
return payment;
}
/// <summary>Cancels a payment inside a transaction.</summary>
internal static async Task CancelAsync(IUnitOfWork uow, Payment payment, DateOnly today, string? userName, CancellationToken cancellationToken)
{
var lines = await LinesAsync(uow, payment.Id, cancellationToken).ConfigureAwait(false);
var itemRepository = uow.Repository<OpenItem, long>();
var reopened = new List<OpenItem>();
foreach (var line in lines)
{
if (await itemRepository.GetAsync(line.OpenItemId, cancellationToken).ConfigureAwait(false) is not { } item)
{
continue;
}
TreasuryStore.Settle(item, -line.Settled);
await itemRepository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
reopened.Add(item);
}
// The withholdings of invoices no longer paid go back to waiting, unless already paid with the F24.
foreach (var document in reopened.Where(i => i.SourceDocumentId is not null).Select(i => (i.SourceFamily, Id: i.SourceDocumentId!.Value)).Distinct())
{
var family = document.SourceFamily;
var documentId = document.Id;
var withholdings = (await uow.Repository<Withholding, long>().ListAsync(
Query.For<Withholding>().Where(w => w.SourceFamily == family && w.SourceDocumentId == documentId && w.InvoicePaidOn != null), cancellationToken).ConfigureAwait(false)).Items;
foreach (var withholding in withholdings)
{
if (withholding.Status == WithholdingStatus.Paid)
{
throw new ValidationFailedException(["Id:" + LedgerErrors.PaymentPaid]);
}
await TaxService.UndoInvoicePaidAsync(uow, withholding, today, userName, cancellationToken).ConfigureAwait(false);
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
}
}
await uow.Repository<Payment, long>().DeleteAsync(payment.Id, cancellationToken).ConfigureAwait(false);
await TreasuryStore.UndoEntryAsync(uow, payment.GlEntryId, today, userName, cancellationToken).ConfigureAwait(false);
if (payment.StatementLineId is { } lineId && await uow.Repository<BankStatementLine, long>().GetAsync(lineId, cancellationToken).ConfigureAwait(false) is { } statementLine)
{
statementLine.Status = StatementLineStatus.ToMatch;
statementLine.MatchKind = StatementMatchKind.None;
statementLine.PaymentId = null;
statementLine.MatchedAt = null;
statementLine.MatchedBy = null;
await uow.Repository<BankStatementLine, long>().UpdateAsync(statementLine, cancellationToken).ConfigureAwait(false);
}
}
internal static async Task<IReadOnlyList<PaymentLine>> LinesAsync(IUnitOfWork uow, long paymentId, CancellationToken cancellationToken) =>
(await uow.Repository<PaymentLine, long>().ListAsync(Query.For<PaymentLine>().Where(l => l.PaymentId == paymentId).OrderBy(l => l.Id), cancellationToken).ConfigureAwait(false)).Items;
// An invoice with a withholding fully paid makes the withholding due (operated) or posted (suffered), as
// TaxService.InvoicePaidAsync does by hand.
private static async Task WithholdingsAsync(IUnitOfWork uow, IFiscalPack pack, IEnumerable<OpenItem> items, DateOnly date, CancellationToken cancellationToken)
{
var settlementRules = pack.GetFeature<IVatSettlementRules>();
if (settlementRules is null)
{
return;
}
var withholdingRules = pack.GetFeature<IWithholdingRules>();
foreach (var document in items.Where(i => i.Closed && i.SourceDocumentId is not null).Select(i => (i.SourceFamily, Id: i.SourceDocumentId!.Value)).Distinct())
{
var family = document.SourceFamily;
var documentId = document.Id;
var open = await uow.Repository<OpenItem, long>().CountAsync(
Query.For<OpenItem>().Where(o => o.SourceFamily == family && o.SourceDocumentId == documentId && !o.Closed), cancellationToken).ConfigureAwait(false);
if (open > 0)
{
continue;
}
var withholdings = (await uow.Repository<Withholding, long>().ListAsync(
Query.For<Withholding>().Where(w => w.SourceFamily == family && w.SourceDocumentId == documentId && w.InvoicePaidOn == null), cancellationToken).ConfigureAwait(false)).Items;
foreach (var withholding in withholdings)
{
await TaxService.ApplyInvoicePaidAsync(uow, withholding, date, settlementRules, withholdingRules, cancellationToken).ConfigureAwait(false);
await uow.Repository<Withholding, long>().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false);
}
}
}
private static async Task<IReadOnlyList<PaymentRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<Payment> payments, CancellationToken cancellationToken)
{
if (payments.Count == 0)
{
return [];
}
var parties = await TreasuryStore.PartiesAsync(uow, payments.Select(p => p.PartyId), cancellationToken).ConfigureAwait(false);
var banks = (await uow.Repository<BankAccount, long>().ListAsync(Query.For<BankAccount>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(b => b.Id);
var entryIds = payments.Where(p => p.GlEntryId is not null).Select(p => p.GlEntryId!.Value).ToList();
var entries = new Dictionary<long, string?>();
foreach (var chunk in entryIds.Chunk(500))
{
var list = chunk.ToList();
foreach (var entry in (await uow.Repository<GlEntry, long>().ListAsync(Query.For<GlEntry>().Where(e => list.Contains(e.Id)), cancellationToken).ConfigureAwait(false)).Items)
{
entries[entry.Id] = entry.EntryNumber;
}
}
var ids = payments.Select(p => p.Id).ToList();
var documents = new Dictionary<long, List<string>>();
foreach (var chunk in ids.Chunk(500))
{
var list = chunk.ToList();
var lines = (await uow.Repository<PaymentLine, long>().ListAsync(Query.For<PaymentLine>().Where(l => list.Contains(l.PaymentId)), cancellationToken).ConfigureAwait(false)).Items;
var itemIds = lines.Select(l => l.OpenItemId).Distinct().ToList();
var items = (await uow.Repository<OpenItem, long>().ListAsync(Query.For<OpenItem>().Where(o => itemIds.Contains(o.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(o => o.Id);
foreach (var line in lines)
{
if (items.TryGetValue(line.OpenItemId, out var item) && item.DocumentNumber is { } number)
{
(documents.TryGetValue(line.PaymentId, out var found) ? found : documents[line.PaymentId] = []).Add(number);
}
}
}
return [.. payments.Select(p => new PaymentRow(
p,
parties.GetValueOrDefault(p.PartyId)?.Name ?? string.Empty,
p.BankAccountId is { } b ? banks.GetValueOrDefault(b)?.Code : null,
p.GlEntryId is { } e ? entries.GetValueOrDefault(e) : null,
string.Join(", ", documents.GetValueOrDefault(p.Id)?.Distinct(StringComparer.Ordinal) ?? [])))];
}
}
@@ -0,0 +1,344 @@
using System.Globalization;
using Khaemhat.Application.Audit;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Application.Tables;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Treasury;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Infrastructure.Files;
namespace Khaemhat.Application.Treasury;
/// <summary>Which items the schedule shows.</summary>
public enum ScheduleView
{
/// <summary>Not closed: open, partial, unpaid, in remittance.</summary>
Open = 0,
/// <summary>Not closed and past due.</summary>
Overdue = 1,
/// <summary>Returned effects not collected again.</summary>
Unpaid = 2,
/// <summary>In a remittance not credited yet.</summary>
InRemittance = 3,
/// <summary>Disputed by the customer or the company.</summary>
Disputed = 4,
/// <summary>Closed.</summary>
Closed = 5,
/// <summary>Everything.</summary>
All = 6,
}
/// <summary>The filter of the schedule.</summary>
/// <param name="Direction">Receivables or payables.</param>
/// <param name="View">Which items.</param>
/// <param name="PartyId">One customer or supplier.</param>
/// <param name="From">Due from this day.</param>
/// <param name="To">Due up to this day.</param>
/// <param name="PaymentMethodId">One payment method.</param>
/// <param name="Search">Part of the party name or of the document number.</param>
public sealed record ScheduleFilter(
OpenItemDirection Direction, ScheduleView View = ScheduleView.Open, long? PartyId = null, DateOnly? From = null, DateOnly? To = null,
long? PaymentMethodId = null, string? Search = null);
/// <summary>An item of the schedule with what the grid shows.</summary>
/// <param name="Item">The item.</param>
/// <param name="PartyCode">The code of the party.</param>
/// <param name="PartyName">The name of the party.</param>
/// <param name="Method">The payment method (code).</param>
/// <param name="MethodDescription">The payment method (description).</param>
/// <param name="DaysOverdue">Days past due (negative when not due).</param>
/// <param name="Remittance">The number of the remittance that holds it.</param>
public sealed record ScheduleRow(OpenItem Item, string? PartyCode, string PartyName, string? Method, string? MethodDescription, int DaysOverdue, string? Remittance);
/// <summary>The schedule: the rows of the filter and the aging of what is open.</summary>
/// <param name="Rows">The rows, by due date.</param>
/// <param name="Aging">The residual by age of the open items of the filter.</param>
/// <param name="Residual">The residual of the rows.</param>
/// <param name="Overdue">The overdue residual of the rows.</param>
/// <param name="DueIn30Days">The residual due in the next 30 days.</param>
public sealed record ScheduleResult(IReadOnlyList<ScheduleRow> Rows, AgingBuckets Aging, decimal Residual, decimal Overdue, decimal DueIn30Days);
/// <summary>A change of an item by hand.</summary>
/// <param name="DueDate">The due date.</param>
/// <param name="PaymentMethodId">The payment method.</param>
/// <param name="BankAccountId">The bank of the company it is collected on.</param>
/// <param name="Disputed">Disputed: left out of reminders and remittances.</param>
/// <param name="Notes">Notes.</param>
public sealed record OpenItemChange(DateOnly DueDate, long? PaymentMethodId, long? BankAccountId, bool Disputed, string? Notes);
/// <summary>The statement of account of a party.</summary>
/// <param name="Party">The party.</param>
/// <param name="Direction">Receivables or payables.</param>
/// <param name="Day">The day of the statement.</param>
/// <param name="Items">The items not closed, by due date.</param>
/// <param name="Payments">The collections or payments of the last twelve months.</param>
/// <param name="Residual">What is left.</param>
/// <param name="Overdue">What is past due.</param>
/// <param name="Interest">The late payment interest to the day, when the pack has the rules.</param>
public sealed record PartyStatement(Party Party, OpenItemDirection Direction, DateOnly Day, IReadOnlyList<ScheduleRow> Items, IReadOnlyList<Payment> Payments, decimal Residual, decimal Overdue, decimal Interest);
/// <summary>
/// The schedule (scadenzario, SPEC §11.8, mockup 053, ADR 0038): the open items of the ledger with their state, the
/// aging by bucket, the change of due date, method, bank and dispute, the statement of account and the export.
/// </summary>
public sealed class ScheduleService
{
private readonly IUnitOfWorkFactory _factory;
private readonly PermissionService _permissions;
private readonly CompanyFiscalContext _packs;
private readonly AuditTrail _audit;
private readonly TimeProvider _clock;
/// <summary>Creates the service.</summary>
/// <param name="factory">The units of work.</param>
/// <param name="permissions">The permissions.</param>
/// <param name="packs">The fiscal pack of each company.</param>
/// <param name="audit">The history.</param>
/// <param name="clock">The clock.</param>
public ScheduleService(IUnitOfWorkFactory factory, PermissionService permissions, CompanyFiscalContext packs, AuditTrail audit, TimeProvider clock)
{
ArgumentNullException.ThrowIfNull(factory);
ArgumentNullException.ThrowIfNull(permissions);
ArgumentNullException.ThrowIfNull(packs);
ArgumentNullException.ThrowIfNull(audit);
ArgumentNullException.ThrowIfNull(clock);
_factory = factory;
_permissions = permissions;
_packs = packs;
_audit = audit;
_clock = clock;
}
/// <summary>The items of a filter with the aging.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The schedule.</returns>
public async Task<ScheduleResult> ItemsAsync(Actor actor, string companyCode, ScheduleFilter filter, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(filter);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
return await LoadAsync(uow, filter, TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false);
}
/// <summary>An item with its row.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The row, or <see langword="null"/>.</returns>
public async Task<ScheduleRow?> ItemAsync(Actor actor, string companyCode, long id, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
if (await uow.Repository<OpenItem, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item)
{
return null;
}
return (await RowsAsync(uow, [item], TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false))[0];
}
/// <summary>Changes due date, method, bank, dispute and notes of an item.</summary>
/// <param name="actor">Who changes it.</param>
/// <param name="companyCode">The company.</param>
/// <param name="id">The item.</param>
/// <param name="change">The change.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The item.</returns>
public async Task<OpenItem> UpdateAsync(Actor actor, string companyCode, long id, OpenItemChange change, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(actor);
ArgumentNullException.ThrowIfNull(change);
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleWrite, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
await uow.BeginAsync(cancellationToken).ConfigureAwait(false);
var repository = uow.Repository<OpenItem, long>();
var item = await repository.GetAsync(id, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
var before = Copy(item);
if (item.Status == OpenItemStatus.InRemittance && (change.DueDate != item.DueDate || change.PaymentMethodId != item.PaymentMethodId))
{
throw new ValidationFailedException(["DueDate:" + TreasuryErrors.InRemittance]);
}
item.DueDate = change.DueDate;
item.PaymentMethodId = change.PaymentMethodId;
item.BankAccountId = change.BankAccountId;
item.Disputed = change.Disputed;
item.Notes = LedgerStore.Trim(string.IsNullOrWhiteSpace(change.Notes) ? null : change.Notes.Trim(), 200);
await repository.UpdateAsync(item, cancellationToken).ConfigureAwait(false);
await _audit.RecordAsync(uow, AuditAction.Update, item.Id, before, item, actor.UserName, cancellationToken).ConfigureAwait(false);
await uow.CommitAsync(cancellationToken).ConfigureAwait(false);
return item;
}
/// <summary>The statement of account of a party (estratto conto).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="partyId">The party.</param>
/// <param name="direction">Receivables or payables.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The statement.</returns>
public async Task<PartyStatement> StatementAsync(Actor actor, string companyCode, long partyId, OpenItemDirection direction, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false);
var rules = (await _packs.PackOfAsync(company, cancellationToken).ConfigureAwait(false)).GetFeature<Fiscal.Abstractions.ILatePaymentRules>();
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var party = await uow.Repository<Party, long>().GetAsync(partyId, cancellationToken).ConfigureAwait(false) ?? throw new KeyNotFoundException(TreasuryErrors.NotFound);
var today = TreasuryStore.Today(_clock);
var result = await LoadAsync(uow, new ScheduleFilter(direction, ScheduleView.Open, partyId), today, cancellationToken).ConfigureAwait(false);
var since = today.AddYears(-1);
var paymentDirection = direction == OpenItemDirection.Receivable ? PaymentDirection.Receipt : PaymentDirection.Disbursement;
var payments = (await uow.Repository<Payment, long>().ListAsync(
Query.For<Payment>().Where(p => p.PartyId == partyId && p.Direction == paymentDirection && p.PaymentDate >= since).OrderByDescending(p => p.PaymentDate),
cancellationToken).ConfigureAwait(false)).Items;
var interest = rules is null || direction != OpenItemDirection.Receivable
? 0m
: result.Rows.Where(r => r.Item.Residual > 0m && r.Item.DueDate < today).Sum(r => LateInterestCalculator.Interest(r.Item.Residual, r.Item.DueDate, today, rules.RateOn));
return new PartyStatement(party, direction, today, result.Rows, payments, result.Residual, result.Overdue, interest);
}
/// <summary>The rows of a filter as a CSV file.</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="filter">The filter.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The file.</returns>
public async Task<LedgerFile> ExportAsync(Actor actor, string companyCode, ScheduleFilter filter, CancellationToken cancellationToken = default)
{
var result = await ItemsAsync(actor, companyCode, filter, cancellationToken).ConfigureAwait(false);
using var output = new MemoryStream();
await using (var csv = new CsvWriter(output, CsvOptions.Italian, leaveOpen: true))
{
await csv.WriteRowAsync(["Codice", "Soggetto", "Documento", "Data documento", "Rata", "Scadenza", "Importo", "Pagato", "Residuo", "Stato", "Modalità", "Giorni scaduto", "Distinta", "Contestata", "Note"], cancellationToken).ConfigureAwait(false);
foreach (var row in result.Rows)
{
var item = row.Item;
await csv.WriteRowAsync(
[row.PartyCode, row.PartyName, item.DocumentNumber, item.DocumentDate, item.Installment, item.DueDate, item.Amount, item.PaidAmount, item.Residual,
item.Status.ToString(), row.Method, Math.Max(0, row.DaysOverdue), row.Remittance, item.Disputed ? "Sì" : "No", item.Notes],
cancellationToken).ConfigureAwait(false);
}
await csv.FlushAsync(cancellationToken).ConfigureAwait(false);
}
var name = (filter.Direction == OpenItemDirection.Receivable ? "scadenzario-clienti-" : "scadenzario-fornitori-")
+ TreasuryStore.Today(_clock).ToString("yyyyMMdd", CultureInfo.InvariantCulture) + ".csv";
return new LedgerFile(name, "text/csv", output.ToArray());
}
/// <summary>The items due in the next days, for the dashboard (receivables and payables).</summary>
/// <param name="actor">Who reads.</param>
/// <param name="companyCode">The company.</param>
/// <param name="days">How many days ahead.</param>
/// <param name="take">How many rows at most.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, by due date, overdue first.</returns>
public async Task<IReadOnlyList<ScheduleRow>> DueSoonAsync(Actor actor, string companyCode, int days = 30, int take = 8, CancellationToken cancellationToken = default)
{
var company = await CompanyGuard.DemandAsync(_permissions, actor, companyCode, TreasuryPermissions.ScheduleRead, cancellationToken).ConfigureAwait(false);
await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false);
var today = TreasuryStore.Today(_clock);
var until = today.AddDays(days);
var items = (await uow.Repository<OpenItem, long>().ListAsync(
Query.For<OpenItem>().Where(o => !o.Closed && o.DueDate <= until).OrderBy(o => o.DueDate).OrderBy(o => o.Id).Take(take), cancellationToken).ConfigureAwait(false)).Items;
return await RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false);
}
internal static async Task<ScheduleResult> LoadAsync(IUnitOfWork uow, ScheduleFilter filter, DateOnly today, CancellationToken cancellationToken)
{
var direction = filter.Direction;
var query = Query.For<OpenItem>().Where(o => o.Direction == direction);
if (filter.PartyId is { } party)
{
query = query.Where(o => o.PartyId == party);
}
if (filter.From is { } from)
{
query = query.Where(o => o.DueDate >= from);
}
if (filter.To is { } to)
{
query = query.Where(o => o.DueDate <= to);
}
if (filter.PaymentMethodId is { } method)
{
query = query.Where(o => o.PaymentMethodId == method);
}
query = filter.View switch
{
ScheduleView.Open => query.Where(o => !o.Closed),
ScheduleView.Overdue => query.Where(o => !o.Closed && o.DueDate < today && o.Status != OpenItemStatus.InRemittance),
ScheduleView.Unpaid => query.Where(o => o.Status == OpenItemStatus.Unpaid),
ScheduleView.InRemittance => query.Where(o => o.Status == OpenItemStatus.InRemittance),
ScheduleView.Disputed => query.Where(o => o.Disputed && !o.Closed),
ScheduleView.Closed => query.Where(o => o.Closed),
_ => query,
};
var items = (await uow.Repository<OpenItem, long>().ListAsync(query.OrderBy(o => o.DueDate).OrderBy(o => o.Id), cancellationToken).ConfigureAwait(false)).Items;
var rows = await RowsAsync(uow, items, today, cancellationToken).ConfigureAwait(false);
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var search = filter.Search.Trim();
rows = [.. rows.Where(r => r.PartyName.Contains(search, StringComparison.OrdinalIgnoreCase)
|| (r.PartyCode?.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false)
|| (r.Item.DocumentNumber?.Contains(search, StringComparison.OrdinalIgnoreCase) ?? false))];
}
var open = rows.Where(r => !r.Item.Closed && r.Item.Status != OpenItemStatus.InRemittance).ToList();
var aging = AgingCalculator.Of(open.Select(r => (r.Item.DueDate, r.Item.Residual)), today);
var limit = today.AddDays(30);
return new ScheduleResult(
rows,
aging,
rows.Where(r => !r.Item.Closed).Sum(r => r.Item.Residual),
open.Where(r => r.Item.DueDate < today).Sum(r => r.Item.Residual),
open.Where(r => r.Item.DueDate >= today && r.Item.DueDate <= limit).Sum(r => r.Item.Residual));
}
internal static async Task<IReadOnlyList<ScheduleRow>> RowsAsync(IUnitOfWork uow, IReadOnlyList<OpenItem> items, DateOnly today, CancellationToken cancellationToken)
{
var parties = await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false);
var methods = (await uow.Repository<PaymentMethod, long>().ListAsync(Query.For<PaymentMethod>(), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(m => m.Id);
var remittanceIds = items.Where(i => i.RemittanceId is not null).Select(i => i.RemittanceId!.Value).Distinct().ToList();
var remittances = remittanceIds.Count == 0
? []
: (await uow.Repository<Remittance, long>().ListAsync(Query.For<Remittance>().Where(r => remittanceIds.Contains(r.Id)), cancellationToken).ConfigureAwait(false)).Items.ToDictionary(r => r.Id);
return [.. items.Select(i =>
{
var party = parties.GetValueOrDefault(i.PartyId);
var method = i.PaymentMethodId is { } m ? methods.GetValueOrDefault(m) : null;
var remittance = i.RemittanceId is { } r ? remittances.GetValueOrDefault(r) : null;
return new ScheduleRow(i, party?.Code, party?.Name ?? string.Empty, method?.Code, method?.Description, AgingCalculator.DaysOverdue(i.DueDate, today), remittance?.DisplayNumber);
})];
}
private static OpenItem Copy(OpenItem o) => new()
{
Id = o.Id,
DueDate = o.DueDate,
PaymentMethodId = o.PaymentMethodId,
BankAccountId = o.BankAccountId,
Disputed = o.Disputed,
Notes = o.Notes,
Status = o.Status,
PaidAmount = o.PaidAmount,
};
}
@@ -0,0 +1,169 @@
using System.Globalization;
using Khaemhat.Application.Ledger;
using Khaemhat.Application.Security;
using Khaemhat.Core.Accounting;
using Khaemhat.Core.Parties;
using Khaemhat.Core.Tables;
using Khaemhat.Core.Treasury;
using Khaemhat.Data;
using Khaemhat.Data.Querying;
using Khaemhat.Fiscal.Abstractions;
namespace Khaemhat.Application.Treasury;
/// <summary>The permissions of the schedule and the treasury (module FIN, <see cref="Modules.BuiltInModules"/>).</summary>
public static class TreasuryPermissions
{
/// <summary>See the schedule, the remittances, the reminders and the cash flow.</summary>
public const string ScheduleRead = "finance.schedule.read";
/// <summary>Change due dates, disputes, remittances, mandates and reminders.</summary>
public const string ScheduleWrite = "finance.schedule.write";
/// <summary>See collections and payments.</summary>
public const string PaymentRead = "finance.payment.read";
/// <summary>Record collections and payments.</summary>
public const string PaymentWrite = "finance.payment.write";
/// <summary>Import bank statements and reconcile them.</summary>
public const string BankReconcile = "finance.bank.reconcile";
}
/// <summary>
/// What the services of the treasury share (ADR 0038): the bank and money accounts, the accounts of the roles with the
/// fallback on the chart of the fiscal pack, the entries written by the treasury and the settlement of the items.
/// </summary>
internal static class TreasuryStore
{
/// <summary>The day of the company clock.</summary>
public static DateOnly Today(TimeProvider clock) => DateOnly.FromDateTime(clock.GetLocalNow().DateTime);
/// <summary>A bank account of the company, or the preferred one.</summary>
public static async Task<BankAccount?> BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken)
{
var banks = uow.Repository<BankAccount, long>();
if (id is { } bankId)
{
return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false)
?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]);
}
var profile = await uow.Repository<CompanyProfile, long>().FindAsync(Query.For<CompanyProfile>(), cancellationToken).ConfigureAwait(false);
if (profile?.DefaultBankAccountId is { } defaultId && await banks.GetAsync(defaultId, cancellationToken).ConfigureAwait(false) is { } preferred)
{
return preferred;
}
return await banks.FindAsync(Query.For<BankAccount>().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false)
?? await banks.FindAsync(Query.For<BankAccount>().OrderBy(b => b.Id), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The account of a role: the line of the template when it has one, otherwise the account the fiscal pack gives
/// the role (companies created before a template got the line).
/// </summary>
public static async Task<long?> RoleAccountAsync(
IUnitOfWork uow, IReadOnlyList<JournalTemplateLine>? lines, PostingRole role, ILedgerTemplate? pack, CancellationToken cancellationToken)
{
if (lines?.FirstOrDefault(l => l.Role == role && l.AccountId is not null)?.AccountId is { } fromTemplate)
{
return fromTemplate;
}
return (await LedgerStore.AccountAsync(uow, pack?.AccountOf(role), cancellationToken).ConfigureAwait(false))?.Id;
}
/// <summary>The account the money moves on: the ledger account of the bank, or cash for a method without bank.</summary>
public static async Task<long> MoneyAccountAsync(
IUnitOfWork uow, BankAccount? bank, bool cash, IReadOnlyList<JournalTemplateLine>? lines, ILedgerTemplate? pack, CancellationToken cancellationToken)
{
long? account = null;
if (cash)
{
account = await RoleAccountAsync(uow, lines, PostingRole.Cash, pack, cancellationToken).ConfigureAwait(false);
}
account ??= (await LedgerStore.AccountAsync(uow, bank?.AccountCode, cancellationToken).ConfigureAwait(false))?.Id;
account ??= await RoleAccountAsync(uow, lines, PostingRole.Bank, pack, cancellationToken).ConfigureAwait(false);
return account ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.MoneyAccountMissing]);
}
/// <summary>Writes a posted entry of the treasury from its lines.</summary>
public static async Task<GlEntry> PostAsync(
IUnitOfWork uow, string templateCode, DateOnly date, string description, long? partyId, IReadOnlyList<PaymentPostedLine> lines, bool demo,
CancellationToken cancellationToken)
{
var template = await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false);
var entry = new GlEntry
{
EntryDate = date,
JournalTemplateId = template?.Template.Id,
TemplateCode = template?.Template.Code ?? templateCode,
Description = LedgerStore.Trim(description, 200)!,
Status = GlEntryStatus.Posted,
Source = GlEntrySource.Treasury,
PartyId = partyId,
IsDemo = demo,
};
return await LedgerStore.InsertAsync(
uow, entry, [.. lines.Select(l => new EntryLineDraft(l.AccountId, l.PartyId, l.Description, l.Debit, l.Credit))], [], cancellationToken).ConfigureAwait(false);
}
/// <summary>Takes back an entry of the treasury: deleted while posted, reversed when final.</summary>
public static async Task UndoEntryAsync(IUnitOfWork uow, long? entryId, DateOnly date, string? userName, CancellationToken cancellationToken)
{
if (entryId is not { } id || await uow.Repository<GlEntry, long>().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } entry)
{
return;
}
if (entry.Status == GlEntryStatus.Final)
{
if (entry.ReversedById is null)
{
await JournalEntryService.ReverseAsync(uow, entry, date < entry.EntryDate ? entry.EntryDate : date, userName, cancellationToken).ConfigureAwait(false);
}
}
else
{
await LedgerStore.DeleteAsync(uow, id, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>Moves what an item has settled and gives it its state.</summary>
public static void Settle(OpenItem item, decimal delta)
{
item.PaidAmount += delta;
item.Status = OpenItemStates.Of(item);
item.Closed = item.Status == OpenItemStatus.Closed;
}
/// <summary>The names and codes of parties.</summary>
public static async Task<Dictionary<long, Party>> PartiesAsync(IUnitOfWork uow, IEnumerable<long> ids, CancellationToken cancellationToken)
{
var set = ids.Distinct().ToList();
if (set.Count == 0)
{
return [];
}
var result = new Dictionary<long, Party>();
foreach (var chunk in set.Chunk(500))
{
var list = chunk.ToList();
foreach (var party in (await uow.Repository<Party, long>().ListAsync(Query.For<Party>().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items)
{
result[party.Id] = party;
}
}
return result;
}
/// <summary>The description of an item in entries and files.</summary>
public static string ItemText(OpenItem item) =>
LedgerStore.Trim(
(item.DocumentNumber is null ? "Scadenza" : "Doc. " + item.DocumentNumber) + " del " + item.DocumentDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
+ (item.Installment > 1 ? " rata " + item.Installment.ToString(CultureInfo.InvariantCulture) : string.Empty), 200)!;
}
@@ -122,6 +122,9 @@ public static class LedgerErrors
/// <summary>The account of the bank is missing.</summary>
public const string BankAccountMissing = "ledger.bank.account-missing";
/// <summary>An open item already collected, paid or in a remittance cannot go below what was settled or go away.</summary>
public const string OpenItemPaid = "ledger.open-item.paid";
/// <summary>The final print of a VAT register must follow the last one.</summary>
public const string PrintOrder = "vat.register.print-order";
}
+3
View File
@@ -261,6 +261,9 @@ public enum GlEntrySource
/// <summary>The payment of an invoice with a withholding.</summary>
Withholding = 6,
/// <summary>A collection, a payment or a remittance of the schedule (M8).</summary>
Treasury = 7,
}
/// <summary>
+3
View File
@@ -207,6 +207,9 @@ public sealed class BankAccount : CodedEntity
/// <summary>The ledger account (M7).</summary>
public string? AccountCode { get; set; }
/// <summary>The SEPA creditor identifier for direct debits (M8).</summary>
public string? CreditorId { get; set; }
/// <summary>The account proposed on documents.</summary>
public bool IsDefault { get; set; }
}
@@ -0,0 +1,95 @@
namespace Khaemhat.Core.Treasury;
/// <summary>The error codes of the schedule and the treasury; the interface translates them (<c>Treasury.json</c>).</summary>
public static class TreasuryErrors
{
/// <summary>The record does not exist.</summary>
public const string NotFound = "treasury.not-found";
/// <summary>A collection or payment without customer or supplier.</summary>
public const string PartyRequired = "treasury.payment.party-required";
/// <summary>A collection or payment without items.</summary>
public const string ItemsRequired = "treasury.payment.items-required";
/// <summary>A collection or payment without amount.</summary>
public const string AmountRequired = "treasury.payment.amount-required";
/// <summary>The items belong to another party or the other direction.</summary>
public const string ItemParty = "treasury.payment.item-party";
/// <summary>An item would be settled for more than what is left.</summary>
public const string OverSettled = "treasury.payment.over-settled";
/// <summary>An item is in a remittance: it is settled by the remittance.</summary>
public const string InRemittance = "treasury.item.in-remittance";
/// <summary>The lines do not add up to the amount.</summary>
public const string Unbalanced = "treasury.payment.unbalanced";
/// <summary>An allowance, exchange difference or fee has no account.</summary>
public const string AccountMissing = "treasury.account-missing";
/// <summary>No bank or cash account to move the money.</summary>
public const string MoneyAccountMissing = "treasury.money-account-missing";
/// <summary>A collection made by a remittance or a bank statement is cancelled there.</summary>
public const string FromRemittance = "treasury.payment.from-remittance";
/// <summary>The remittance has no items.</summary>
public const string RemittanceEmpty = "treasury.remittance.empty";
/// <summary>The remittance is not in the state the operation needs.</summary>
public const string RemittanceStatus = "treasury.remittance.status";
/// <summary>The bank of the remittance has no IBAN, SIA or creditor identifier for the file.</summary>
public const string RemittanceBank = "treasury.remittance.bank";
/// <summary>An item has no bank coordinates (IBAN, or ABI and CAB for RiBa).</summary>
public const string RemittanceIban = "treasury.remittance.iban";
/// <summary>A direct debit item has no valid mandate.</summary>
public const string RemittanceMandate = "treasury.remittance.mandate";
/// <summary>The item cannot go in this kind of remittance.</summary>
public const string RemittanceItem = "treasury.remittance.item";
/// <summary>The file format is not available.</summary>
public const string RemittanceFormat = "treasury.remittance.format";
/// <summary>Another mandate has the reference.</summary>
public const string MandateDuplicate = "treasury.mandate.duplicate";
/// <summary>The mandate has no reference.</summary>
public const string MandateReference = "treasury.mandate.reference";
/// <summary>The IBAN is not valid.</summary>
public const string IbanInvalid = "treasury.iban-invalid";
/// <summary>The mandate is used by remittances.</summary>
public const string MandateUsed = "treasury.mandate.used";
/// <summary>The bank file is not recognized.</summary>
public const string StatementFormat = "treasury.statement.format";
/// <summary>The bank file has no movements.</summary>
public const string StatementEmpty = "treasury.statement.empty";
/// <summary>The bank file belongs to another bank account.</summary>
public const string StatementAccount = "treasury.statement.account";
/// <summary>The movement is already matched or ignored.</summary>
public const string MatchDone = "treasury.match.done";
/// <summary>The chosen items or payments do not add up to the movement.</summary>
public const string MatchAmount = "treasury.match.amount";
/// <summary>A rule without pattern or account.</summary>
public const string RulePattern = "treasury.rule.pattern";
/// <summary>The customer has no address for the reminder on the chosen channel.</summary>
public const string DunningRecipient = "treasury.dunning.recipient";
/// <summary>A level of reminders without name, subject or days.</summary>
public const string DunningLevel = "treasury.dunning.level";
}
@@ -686,3 +686,31 @@ public static class CashFlowForecaster
return result;
}
}
/// <summary>The state of an open item in the schedule from its amounts (ADR 0038).</summary>
public static class OpenItemStates
{
/// <summary>The state an item has after a change of its amounts.</summary>
/// <param name="item">The item.</param>
/// <returns>In remittance while a remittance holds it; closed when nothing is left; partial when something was settled; unpaid after a returned effect; open otherwise.</returns>
public static OpenItemStatus Of(Accounting.OpenItem item)
{
ArgumentNullException.ThrowIfNull(item);
if (item.Status == OpenItemStatus.InRemittance && item.RemittanceId is not null)
{
return OpenItemStatus.InRemittance;
}
if (item.Residual == 0m)
{
return OpenItemStatus.Closed;
}
if (item.PaidAmount != 0m)
{
return OpenItemStatus.Partial;
}
return item.UnpaidCount > 0 ? OpenItemStatus.Unpaid : OpenItemStatus.Open;
}
}
@@ -29,6 +29,7 @@ public sealed class M20261113_003_CreateTreasury : IMigration
t.String("notes", 200);
});
schema.CreateIndex("gl_open_items", "ix_gl_open_items_schedule", false, "direction", "status", "due_date");
schema.AlterTable("bank_accounts", t => t.String("creditor_id", 35));
schema.CreateTable("remittances", t =>
{
@@ -208,6 +208,7 @@ public sealed class BankAccountMap : EntityMap<BankAccount>
Map(x => x.Bic).MaxLength(11);
Map(x => x.SiaCode).MaxLength(5);
Map(x => x.CucCode).MaxLength(8);
Map(x => x.CreditorId).MaxLength(35);
Map(x => x.AccountCode).MaxLength(20);
}
}
+5 -1
View File
@@ -364,7 +364,8 @@
"TaxPayment": "Versamento F24",
"Recurring": "Ricorrente",
"Reversal": "Storno",
"Withholding": "Ritenuta"
"Withholding": "Ritenuta",
"Treasury": "Tesoreria"
},
"RecurrenceFrequency": {
"Monthly": "Mensile",
@@ -497,6 +498,9 @@
},
"bank": {
"account-missing": "Il conto bancario non ha un conto contabile e manca il conto banca predefinito."
},
"open-item": {
"paid": "Il documento ha scadenze già incassate, pagate o in distinta: annulla prima l'incasso o togli la scadenza dalla distinta."
}
},
"vat": {
@@ -252,6 +252,7 @@
"SiaCode": "Codice SIA",
"CucCode": "Codice CUC",
"AccountCode": "Conto contabile",
"CreditorId": "Identificativo creditore SEPA",
"IsDefault": "Predefinito",
"Symbol": "Simbolo",
"Decimals": "Decimali",
+1
View File
@@ -178,6 +178,7 @@ public static class TableScreens
new(nameof(BankAccount.SiaCode), TableFieldKind.Code) { Span = 4, MaxLength = 5 },
new(nameof(BankAccount.CucCode), TableFieldKind.Code) { Span = 4, MaxLength = 8 },
new(nameof(BankAccount.AccountCode), TableFieldKind.Code) { Span = 4 },
new(nameof(BankAccount.CreditorId), TableFieldKind.Code) { Span = 8, MaxLength = 35 },
new(nameof(BankAccount.IsDefault), TableFieldKind.Bool) { Span = 12, InGrid = true, Width = "90px" },
],
},