diff --git a/src/Khaemhat.Application/Ledger/JournalEntryService.cs b/src/Khaemhat.Application/Ledger/JournalEntryService.cs index bf0fe2f..54048f5 100644 --- a/src/Khaemhat.Application/Ledger/JournalEntryService.cs +++ b/src/Khaemhat.Application/Ledger/JournalEntryService.cs @@ -502,7 +502,10 @@ public sealed class JournalEntryService cancellationToken).ConfigureAwait(false); entry.ReversedById = reversal.Id; await uow.Repository().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; } diff --git a/src/Khaemhat.Application/Ledger/LedgerPoster.cs b/src/Khaemhat.Application/Ledger/LedgerPoster.cs index 6292366..9567b38 100644 --- a/src/Khaemhat.Application/Ledger/LedgerPoster.cs +++ b/src/Khaemhat.Application/Ledger/LedgerPoster.cs @@ -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(); - foreach (var (number, due, amount, method) in rows) + var current = (await repository.ListAsync( + Query.For().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); } } diff --git a/src/Khaemhat.Application/Ledger/LedgerStore.cs b/src/Khaemhat.Application/Ledger/LedgerStore.cs index 280b07b..41b553d 100644 --- a/src/Khaemhat.Application/Ledger/LedgerStore.cs +++ b/src/Khaemhat.Application/Ledger/LedgerStore.cs @@ -115,12 +115,25 @@ internal static class LedgerStore /// Removes an entry with its lines, VAT lines and open items. 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().DeleteAsync(entryId, cancellationToken).ConfigureAwait(false); } + /// Refuses when an open item of the entry was collected, paid or put in a remittance (ADR 0038). + public static async Task EnsureUnpaidAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) + { + var touched = await uow.QuerySingleAsync( + 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]); + } + } + /// The lines of an entry, in order. public static async Task> LinesAsync(IUnitOfWork uow, long entryId, CancellationToken cancellationToken) => (await uow.Repository().ListAsync(Query.For().Where(l => l.EntryId == entryId).OrderBy(l => l.LineNumber), cancellationToken) diff --git a/src/Khaemhat.Application/Ledger/TaxService.cs b/src/Khaemhat.Application/Ledger/TaxService.cs index 6cbca92..a68e7e6 100644 --- a/src/Khaemhat.Application/Ledger/TaxService.cs +++ b/src/Khaemhat.Application/Ledger/TaxService.cs @@ -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(); - var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture); - var year = paidOn.Year; - var payment = await payments.FindAsync( - Query.For().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().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().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) - { - payment.Amount -= withholding.Amount; - if (payment.Amount == 0m) - { - await uow.Repository().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false); - } - else - { - await uow.Repository().UpdateAsync(payment, cancellationToken).ConfigureAwait(false); - } - } - - if (withholding.GlEntryId is { } entryId && await uow.Repository().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().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. + /// Takes back the payment of the invoice of a withholding: its F24 share and its entry. The caller writes the withholding. + internal static async Task UndoInvoicePaidAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string? userName, CancellationToken cancellationToken) + { + if (withholding.TaxPaymentId is { } paymentId && await uow.Repository().GetAsync(paymentId, cancellationToken).ConfigureAwait(false) is { } payment) + { + payment.Amount -= withholding.Amount; + if (payment.Amount == 0m) + { + await uow.Repository().DeleteAsync(paymentId, cancellationToken).ConfigureAwait(false); + } + else + { + await uow.Repository().UpdateAsync(payment, cancellationToken).ConfigureAwait(false); + } + } + + if (withholding.GlEntryId is { } entryId && await uow.Repository().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; + } + + /// + /// 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. + /// + 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(); + var period = paidOn.Month.ToString("00", CultureInfo.InvariantCulture); + var year = paidOn.Year; + var payment = await payments.FindAsync( + Query.For().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 PostWithholdingAsync(IUnitOfWork uow, Withholding withholding, DateOnly date, string templateCode, CancellationToken cancellationToken) { if (await LedgerStore.TemplateAsync(uow, templateCode, cancellationToken).ConfigureAwait(false) is not { } found) diff --git a/src/Khaemhat.Application/Treasury/PaymentService.cs b/src/Khaemhat.Application/Treasury/PaymentService.cs new file mode 100644 index 0000000..2484112 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/PaymentService.cs @@ -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; + +/// A line of a collection or payment being recorded. +/// The item. +/// The money for the item. +/// The allowance (abbuono) that closes it. +/// The exchange difference. +public sealed record PaymentLineInput(long OpenItemId, decimal Amount, decimal Allowance = 0m, decimal ExchangeDifference = 0m); + +/// A collection or payment being recorded (mockup 054). +/// Collection or payment. +/// The customer or supplier. +/// The day of the money. +/// The method. +/// The bank of the company; none with a cash method means the cash. +/// The bank fees. +/// The reference (CRO, cheque number). +/// Notes. +/// The items settled. +public sealed record PaymentInput( + PaymentDirection Direction, long PartyId, DateOnly Date, long? PaymentMethodId, long? BankAccountId, decimal Fees, string? Reference, string? Notes, + IReadOnlyList Lines); + +/// A collection or payment with what the grid shows. +/// The payment. +/// The party. +/// The bank (code). +/// The number of its entry. +/// The documents it settled. +public sealed record PaymentRow(Payment Payment, string PartyName, string? Bank, string? EntryNumber, string Documents); + +/// +/// 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. +/// +public sealed class PaymentService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + 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; + } + + /// The collections or payments of a period. + /// Who reads. + /// The company. + /// Collections or payments. + /// From this day. + /// Up to this day. + /// One party. + /// Cancellation. + /// The rows, latest first. + public async Task> 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().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().ListAsync(query.OrderByDescending(p => p.PaymentDate).OrderByDescending(p => p.Id), cancellationToken).ConfigureAwait(false)).Items; + return await RowsAsync(uow, payments, cancellationToken).ConfigureAwait(false); + } + + /// A payment with its lines and their items. + /// Who reads. + /// The company. + /// The payment. + /// Cancellation. + /// The payment, its lines and the items, or . + 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().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().ListAsync(Query.For().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)))]); + } + + /// Records a collection or payment and its entry. + /// Who records it. + /// The company. + /// The payment. + /// Cancellation. + /// The payment. + public async Task 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(uow, AuditAction.Insert, payment.Id, null, payment, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + return payment; + } + + /// Cancels a collection or payment: its entry is deleted (or reversed when final) and its items reopen. + /// Who cancels it. + /// The company. + /// The payment. + /// Cancellation. + /// A task. + 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().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(uow, AuditAction.Delete, payment.Id, payment, null, actor.UserName, cancellationToken).ConfigureAwait(false); + await uow.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + /// Records a payment inside a transaction (manual, remittances, bank statements). + internal static async Task RegisterAsync( + IUnitOfWork uow, IFiscalPack pack, PaymentInput input, PaymentOrigin origin, long? remittanceId, long? statementLineId, CancellationToken cancellationToken) + { + var errors = new List(); + 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(); + 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().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(); + 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 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().InsertAsync(payment, cancellationToken).ConfigureAwait(false); + var lineRepository = uow.Repository(); + 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; + } + + /// Cancels a payment inside a transaction. + 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(); + var reopened = new List(); + 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().ListAsync( + Query.For().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().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false); + } + } + + await uow.Repository().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().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().UpdateAsync(statementLine, cancellationToken).ConfigureAwait(false); + } + } + + internal static async Task> LinesAsync(IUnitOfWork uow, long paymentId, CancellationToken cancellationToken) => + (await uow.Repository().ListAsync(Query.For().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 items, DateOnly date, CancellationToken cancellationToken) + { + var settlementRules = pack.GetFeature(); + if (settlementRules is null) + { + return; + } + + var withholdingRules = pack.GetFeature(); + 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().CountAsync( + Query.For().Where(o => o.SourceFamily == family && o.SourceDocumentId == documentId && !o.Closed), cancellationToken).ConfigureAwait(false); + if (open > 0) + { + continue; + } + + var withholdings = (await uow.Repository().ListAsync( + Query.For().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().UpdateAsync(withholding, cancellationToken).ConfigureAwait(false); + } + } + } + + private static async Task> RowsAsync(IUnitOfWork uow, IReadOnlyList 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().ListAsync(Query.For(), 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(); + foreach (var chunk in entryIds.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var entry in (await uow.Repository().ListAsync(Query.For().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>(); + foreach (var chunk in ids.Chunk(500)) + { + var list = chunk.ToList(); + var lines = (await uow.Repository().ListAsync(Query.For().Where(l => list.Contains(l.PaymentId)), cancellationToken).ConfigureAwait(false)).Items; + var itemIds = lines.Select(l => l.OpenItemId).Distinct().ToList(); + var items = (await uow.Repository().ListAsync(Query.For().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) ?? [])))]; + } +} diff --git a/src/Khaemhat.Application/Treasury/ScheduleService.cs b/src/Khaemhat.Application/Treasury/ScheduleService.cs new file mode 100644 index 0000000..713798f --- /dev/null +++ b/src/Khaemhat.Application/Treasury/ScheduleService.cs @@ -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; + +/// Which items the schedule shows. +public enum ScheduleView +{ + /// Not closed: open, partial, unpaid, in remittance. + Open = 0, + + /// Not closed and past due. + Overdue = 1, + + /// Returned effects not collected again. + Unpaid = 2, + + /// In a remittance not credited yet. + InRemittance = 3, + + /// Disputed by the customer or the company. + Disputed = 4, + + /// Closed. + Closed = 5, + + /// Everything. + All = 6, +} + +/// The filter of the schedule. +/// Receivables or payables. +/// Which items. +/// One customer or supplier. +/// Due from this day. +/// Due up to this day. +/// One payment method. +/// Part of the party name or of the document number. +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); + +/// An item of the schedule with what the grid shows. +/// The item. +/// The code of the party. +/// The name of the party. +/// The payment method (code). +/// The payment method (description). +/// Days past due (negative when not due). +/// The number of the remittance that holds it. +public sealed record ScheduleRow(OpenItem Item, string? PartyCode, string PartyName, string? Method, string? MethodDescription, int DaysOverdue, string? Remittance); + +/// The schedule: the rows of the filter and the aging of what is open. +/// The rows, by due date. +/// The residual by age of the open items of the filter. +/// The residual of the rows. +/// The overdue residual of the rows. +/// The residual due in the next 30 days. +public sealed record ScheduleResult(IReadOnlyList Rows, AgingBuckets Aging, decimal Residual, decimal Overdue, decimal DueIn30Days); + +/// A change of an item by hand. +/// The due date. +/// The payment method. +/// The bank of the company it is collected on. +/// Disputed: left out of reminders and remittances. +/// Notes. +public sealed record OpenItemChange(DateOnly DueDate, long? PaymentMethodId, long? BankAccountId, bool Disputed, string? Notes); + +/// The statement of account of a party. +/// The party. +/// Receivables or payables. +/// The day of the statement. +/// The items not closed, by due date. +/// The collections or payments of the last twelve months. +/// What is left. +/// What is past due. +/// The late payment interest to the day, when the pack has the rules. +public sealed record PartyStatement(Party Party, OpenItemDirection Direction, DateOnly Day, IReadOnlyList Items, IReadOnlyList Payments, decimal Residual, decimal Overdue, decimal Interest); + +/// +/// 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. +/// +public sealed class ScheduleService +{ + private readonly IUnitOfWorkFactory _factory; + private readonly PermissionService _permissions; + private readonly CompanyFiscalContext _packs; + private readonly AuditTrail _audit; + private readonly TimeProvider _clock; + + /// Creates the service. + /// The units of work. + /// The permissions. + /// The fiscal pack of each company. + /// The history. + /// The clock. + 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; + } + + /// The items of a filter with the aging. + /// Who reads. + /// The company. + /// The filter. + /// Cancellation. + /// The schedule. + public async Task 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); + } + + /// An item with its row. + /// Who reads. + /// The company. + /// The item. + /// Cancellation. + /// The row, or . + public async Task 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().GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } item) + { + return null; + } + + return (await RowsAsync(uow, [item], TreasuryStore.Today(_clock), cancellationToken).ConfigureAwait(false))[0]; + } + + /// Changes due date, method, bank, dispute and notes of an item. + /// Who changes it. + /// The company. + /// The item. + /// The change. + /// Cancellation. + /// The item. + public async Task 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(); + 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; + } + + /// The statement of account of a party (estratto conto). + /// Who reads. + /// The company. + /// The party. + /// Receivables or payables. + /// Cancellation. + /// The statement. + public async Task 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(); + await using var uow = await _factory.CreateAsync(DatabaseScope.Company(company), cancellationToken).ConfigureAwait(false); + var party = await uow.Repository().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().ListAsync( + Query.For().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); + } + + /// The rows of a filter as a CSV file. + /// Who reads. + /// The company. + /// The filter. + /// Cancellation. + /// The file. + public async Task 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()); + } + + /// The items due in the next days, for the dashboard (receivables and payables). + /// Who reads. + /// The company. + /// How many days ahead. + /// How many rows at most. + /// Cancellation. + /// The rows, by due date, overdue first. + public async Task> 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().ListAsync( + Query.For().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 LoadAsync(IUnitOfWork uow, ScheduleFilter filter, DateOnly today, CancellationToken cancellationToken) + { + var direction = filter.Direction; + var query = Query.For().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().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> RowsAsync(IUnitOfWork uow, IReadOnlyList items, DateOnly today, CancellationToken cancellationToken) + { + var parties = await TreasuryStore.PartiesAsync(uow, items.Select(i => i.PartyId), cancellationToken).ConfigureAwait(false); + var methods = (await uow.Repository().ListAsync(Query.For(), 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().ListAsync(Query.For().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, + }; +} diff --git a/src/Khaemhat.Application/Treasury/TreasuryStore.cs b/src/Khaemhat.Application/Treasury/TreasuryStore.cs new file mode 100644 index 0000000..a0f3a48 --- /dev/null +++ b/src/Khaemhat.Application/Treasury/TreasuryStore.cs @@ -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; + +/// The permissions of the schedule and the treasury (module FIN, ). +public static class TreasuryPermissions +{ + /// See the schedule, the remittances, the reminders and the cash flow. + public const string ScheduleRead = "finance.schedule.read"; + + /// Change due dates, disputes, remittances, mandates and reminders. + public const string ScheduleWrite = "finance.schedule.write"; + + /// See collections and payments. + public const string PaymentRead = "finance.payment.read"; + + /// Record collections and payments. + public const string PaymentWrite = "finance.payment.write"; + + /// Import bank statements and reconcile them. + public const string BankReconcile = "finance.bank.reconcile"; +} + +/// +/// 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. +/// +internal static class TreasuryStore +{ + /// The day of the company clock. + public static DateOnly Today(TimeProvider clock) => DateOnly.FromDateTime(clock.GetLocalNow().DateTime); + + /// A bank account of the company, or the preferred one. + public static async Task BankAsync(IUnitOfWork uow, long? id, CancellationToken cancellationToken) + { + var banks = uow.Repository(); + if (id is { } bankId) + { + return await banks.GetAsync(bankId, cancellationToken).ConfigureAwait(false) + ?? throw new ValidationFailedException(["BankAccountId:" + TreasuryErrors.NotFound]); + } + + var profile = await uow.Repository().FindAsync(Query.For(), 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().Where(b => b.IsDefault), cancellationToken).ConfigureAwait(false) + ?? await banks.FindAsync(Query.For().OrderBy(b => b.Id), cancellationToken).ConfigureAwait(false); + } + + /// + /// 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). + /// + public static async Task RoleAccountAsync( + IUnitOfWork uow, IReadOnlyList? 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; + } + + /// The account the money moves on: the ledger account of the bank, or cash for a method without bank. + public static async Task MoneyAccountAsync( + IUnitOfWork uow, BankAccount? bank, bool cash, IReadOnlyList? 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]); + } + + /// Writes a posted entry of the treasury from its lines. + public static async Task PostAsync( + IUnitOfWork uow, string templateCode, DateOnly date, string description, long? partyId, IReadOnlyList 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); + } + + /// Takes back an entry of the treasury: deleted while posted, reversed when final. + public static async Task UndoEntryAsync(IUnitOfWork uow, long? entryId, DateOnly date, string? userName, CancellationToken cancellationToken) + { + if (entryId is not { } id || await uow.Repository().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); + } + } + + /// Moves what an item has settled and gives it its state. + public static void Settle(OpenItem item, decimal delta) + { + item.PaidAmount += delta; + item.Status = OpenItemStates.Of(item); + item.Closed = item.Status == OpenItemStatus.Closed; + } + + /// The names and codes of parties. + public static async Task> PartiesAsync(IUnitOfWork uow, IEnumerable ids, CancellationToken cancellationToken) + { + var set = ids.Distinct().ToList(); + if (set.Count == 0) + { + return []; + } + + var result = new Dictionary(); + foreach (var chunk in set.Chunk(500)) + { + var list = chunk.ToList(); + foreach (var party in (await uow.Repository().ListAsync(Query.For().Where(p => list.Contains(p.Id)), cancellationToken).ConfigureAwait(false)).Items) + { + result[party.Id] = party; + } + } + + return result; + } + + /// The description of an item in entries and files. + 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)!; +} diff --git a/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs b/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs index 418334d..6e0daf5 100644 --- a/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs +++ b/src/Khaemhat.Core/Accounting/JournalEntryValidator.cs @@ -122,6 +122,9 @@ public static class LedgerErrors /// The account of the bank is missing. public const string BankAccountMissing = "ledger.bank.account-missing"; + /// An open item already collected, paid or in a remittance cannot go below what was settled or go away. + public const string OpenItemPaid = "ledger.open-item.paid"; + /// The final print of a VAT register must follow the last one. public const string PrintOrder = "vat.register.print-order"; } diff --git a/src/Khaemhat.Core/Accounting/Ledger.cs b/src/Khaemhat.Core/Accounting/Ledger.cs index d991b79..15c77c0 100644 --- a/src/Khaemhat.Core/Accounting/Ledger.cs +++ b/src/Khaemhat.Core/Accounting/Ledger.cs @@ -261,6 +261,9 @@ public enum GlEntrySource /// The payment of an invoice with a withholding. Withholding = 6, + + /// A collection, a payment or a remittance of the schedule (M8). + Treasury = 7, } /// diff --git a/src/Khaemhat.Core/Tables/BaseTables.cs b/src/Khaemhat.Core/Tables/BaseTables.cs index e5ca6fa..ed0441a 100644 --- a/src/Khaemhat.Core/Tables/BaseTables.cs +++ b/src/Khaemhat.Core/Tables/BaseTables.cs @@ -207,6 +207,9 @@ public sealed class BankAccount : CodedEntity /// The ledger account (M7). public string? AccountCode { get; set; } + /// The SEPA creditor identifier for direct debits (M8). + public string? CreditorId { get; set; } + /// The account proposed on documents. public bool IsDefault { get; set; } } diff --git a/src/Khaemhat.Core/Treasury/TreasuryErrors.cs b/src/Khaemhat.Core/Treasury/TreasuryErrors.cs new file mode 100644 index 0000000..0d581d9 --- /dev/null +++ b/src/Khaemhat.Core/Treasury/TreasuryErrors.cs @@ -0,0 +1,95 @@ +namespace Khaemhat.Core.Treasury; + +/// The error codes of the schedule and the treasury; the interface translates them (Treasury.json). +public static class TreasuryErrors +{ + /// The record does not exist. + public const string NotFound = "treasury.not-found"; + + /// A collection or payment without customer or supplier. + public const string PartyRequired = "treasury.payment.party-required"; + + /// A collection or payment without items. + public const string ItemsRequired = "treasury.payment.items-required"; + + /// A collection or payment without amount. + public const string AmountRequired = "treasury.payment.amount-required"; + + /// The items belong to another party or the other direction. + public const string ItemParty = "treasury.payment.item-party"; + + /// An item would be settled for more than what is left. + public const string OverSettled = "treasury.payment.over-settled"; + + /// An item is in a remittance: it is settled by the remittance. + public const string InRemittance = "treasury.item.in-remittance"; + + /// The lines do not add up to the amount. + public const string Unbalanced = "treasury.payment.unbalanced"; + + /// An allowance, exchange difference or fee has no account. + public const string AccountMissing = "treasury.account-missing"; + + /// No bank or cash account to move the money. + public const string MoneyAccountMissing = "treasury.money-account-missing"; + + /// A collection made by a remittance or a bank statement is cancelled there. + public const string FromRemittance = "treasury.payment.from-remittance"; + + /// The remittance has no items. + public const string RemittanceEmpty = "treasury.remittance.empty"; + + /// The remittance is not in the state the operation needs. + public const string RemittanceStatus = "treasury.remittance.status"; + + /// The bank of the remittance has no IBAN, SIA or creditor identifier for the file. + public const string RemittanceBank = "treasury.remittance.bank"; + + /// An item has no bank coordinates (IBAN, or ABI and CAB for RiBa). + public const string RemittanceIban = "treasury.remittance.iban"; + + /// A direct debit item has no valid mandate. + public const string RemittanceMandate = "treasury.remittance.mandate"; + + /// The item cannot go in this kind of remittance. + public const string RemittanceItem = "treasury.remittance.item"; + + /// The file format is not available. + public const string RemittanceFormat = "treasury.remittance.format"; + + /// Another mandate has the reference. + public const string MandateDuplicate = "treasury.mandate.duplicate"; + + /// The mandate has no reference. + public const string MandateReference = "treasury.mandate.reference"; + + /// The IBAN is not valid. + public const string IbanInvalid = "treasury.iban-invalid"; + + /// The mandate is used by remittances. + public const string MandateUsed = "treasury.mandate.used"; + + /// The bank file is not recognized. + public const string StatementFormat = "treasury.statement.format"; + + /// The bank file has no movements. + public const string StatementEmpty = "treasury.statement.empty"; + + /// The bank file belongs to another bank account. + public const string StatementAccount = "treasury.statement.account"; + + /// The movement is already matched or ignored. + public const string MatchDone = "treasury.match.done"; + + /// The chosen items or payments do not add up to the movement. + public const string MatchAmount = "treasury.match.amount"; + + /// A rule without pattern or account. + public const string RulePattern = "treasury.rule.pattern"; + + /// The customer has no address for the reminder on the chosen channel. + public const string DunningRecipient = "treasury.dunning.recipient"; + + /// A level of reminders without name, subject or days. + public const string DunningLevel = "treasury.dunning.level"; +} diff --git a/src/Khaemhat.Core/Treasury/TreasuryRules.cs b/src/Khaemhat.Core/Treasury/TreasuryRules.cs index 130713f..8dc18ab 100644 --- a/src/Khaemhat.Core/Treasury/TreasuryRules.cs +++ b/src/Khaemhat.Core/Treasury/TreasuryRules.cs @@ -686,3 +686,31 @@ public static class CashFlowForecaster return result; } } + +/// The state of an open item in the schedule from its amounts (ADR 0038). +public static class OpenItemStates +{ + /// The state an item has after a change of its amounts. + /// The item. + /// In remittance while a remittance holds it; closed when nothing is left; partial when something was settled; unpaid after a returned effect; open otherwise. + 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; + } +} diff --git a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs index d8d3b30..2f2fdd7 100644 --- a/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs +++ b/src/Khaemhat.Data/CompanyDatabase/Migrations/M20261113_003_CreateTreasury.cs @@ -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 => { diff --git a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs index 32419c1..019f698 100644 --- a/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs +++ b/src/Khaemhat.Data/CompanyDatabase/TableMaps.cs @@ -208,6 +208,7 @@ public sealed class BankAccountMap : EntityMap 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); } } diff --git a/src/Khaemhat.Web/Resources/it-IT/Ledger.json b/src/Khaemhat.Web/Resources/it-IT/Ledger.json index 4e9ffbd..7522976 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Ledger.json +++ b/src/Khaemhat.Web/Resources/it-IT/Ledger.json @@ -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": { diff --git a/src/Khaemhat.Web/Resources/it-IT/Tables.json b/src/Khaemhat.Web/Resources/it-IT/Tables.json index 127f764..efe423f 100644 --- a/src/Khaemhat.Web/Resources/it-IT/Tables.json +++ b/src/Khaemhat.Web/Resources/it-IT/Tables.json @@ -252,6 +252,7 @@ "SiaCode": "Codice SIA", "CucCode": "Codice CUC", "AccountCode": "Conto contabile", + "CreditorId": "Identificativo creditore SEPA", "IsDefault": "Predefinito", "Symbol": "Simbolo", "Decimals": "Decimali", diff --git a/src/Khaemhat.Web/Tables/TableScreens.cs b/src/Khaemhat.Web/Tables/TableScreens.cs index 8db0429..9bda8e7 100644 --- a/src/Khaemhat.Web/Tables/TableScreens.cs +++ b/src/Khaemhat.Web/Tables/TableScreens.cs @@ -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" }, ], },